Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 54 additions & 8 deletions crates/victory-gpu/src/alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ use crate::host::host;
use crate::watch::PAGE;
use windows::Win32::Graphics::Direct3D12::ID3D12Resource;

#[cfg(any(test, feature = "diagnostics"))]
use windows::Win32::Graphics::Direct3D12::*;

#[cfg(target_arch = "x86_64")]
Expand Down Expand Up @@ -360,7 +359,6 @@ fn supported() -> Option<bool> {

/// CPU-visible backing for XMem physical pages. The placed buffer keeps a
/// CPU mapping of the heap from which reserved resources can take tiles.
#[cfg(any(test, feature = "diagnostics"))]
pub struct PhysicalHeap {
backing: ID3D12Resource,
// A placed buffer must keep its heap alive.
Expand All @@ -369,7 +367,6 @@ pub struct PhysicalHeap {
len: usize,
}

#[cfg(any(test, feature = "diagnostics"))]
impl PhysicalHeap {
pub(crate) fn new(device: &ID3D12Device, len: usize) -> windows::core::Result<Self> {
let desc = D3D12_HEAP_DESC {
Expand Down Expand Up @@ -459,19 +456,68 @@ impl PhysicalHeap {
}
}

#[cfg(any(test, feature = "diagnostics"))]
impl Drop for PhysicalHeap {
fn drop(&mut self) {
// SAFETY: unmapped once, while the placed buffer still owns the view.
unsafe { self.backing.Unmap(0, None) };
}
}

/// Allocates CPU-visible physical tiles for the Rosetta diagnostics trial.
#[cfg(feature = "diagnostics")]
pub fn physical_heap(len: usize) -> Option<PhysicalHeap> {
/// Whether the title's physical pages are GPU memory
/// (`VICTORY_PHYSICAL_TILES=1`, off by default; Rosetta and D3DMetal only):
/// each section of them is a CPU-visible heap, its title views remapped
/// onto it ([`PhysicalHeap::alias_view`]), and host copies of title buffers
/// on those pages read them in place (`crate::tiled`).
pub fn physical_tiles() -> bool {
#[cfg(test)]
if let Some(on) = TEST_PHYSICAL_TILES.with(std::cell::Cell::get) {
return on && supported().is_some();
}
static ENABLED: OnceLock<bool> = OnceLock::new();
if !*ENABLED.get_or_init(|| crate::switch::on("VICTORY_PHYSICAL_TILES") && supported().is_some())
*ENABLED.get_or_init(|| {
let on = crate::switch::on("VICTORY_PHYSICAL_TILES") && supported().is_some();
if on {
tracing::info!("the title's physical pages are GPU memory, read in place (VICTORY_PHYSICAL_TILES=1)");
}
on
})
}

#[cfg(test)]
thread_local! {
/// [`physical_tiles`] on this test's thread.
pub(crate) static TEST_PHYSICAL_TILES: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}

/// One 64 KiB tile of a [`PhysicalHeap`]: a host copy's reserved buffer maps
/// it (`crate::tiled`), holding the heap while it does.
#[derive(Clone)]
pub struct Tile {
pub(crate) heap: ID3D12Heap,
pub(crate) index: u32,
}

impl Tile {
/// Its 64 KiB tile in its heap.
pub fn index(&self) -> u32 {
self.index
}
}

impl PhysicalHeap {
/// The tile at byte `offset` of the heap.
pub fn tile(&self, offset: usize) -> Option<Tile> {
(offset.is_multiple_of(PAGE) && offset < self.len).then(|| Tile {
heap: self._heap.clone(),
index: (offset / PAGE) as u32,
})
}
}

/// CPU-visible GPU memory for a section of the title's physical pages, of
/// `len` bytes ([`physical_tiles`]); none when off or not made.
pub fn physical_heap(len: usize) -> Option<PhysicalHeap> {
if !physical_tiles()
|| len == 0
|| !len.is_multiple_of(PAGE)
{
Expand Down
129 changes: 128 additions & 1 deletion crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3379,7 +3379,7 @@ impl Host {
}

/// The queue submissions go to now.
fn queue(&self) -> ID3D12CommandQueue {
pub(crate) fn queue(&self) -> ID3D12CommandQueue {
self.queue.lock().unwrap_or_else(|e| e.into_inner()).clone()
}

Expand Down Expand Up @@ -8994,3 +8994,130 @@ mod waiting_on_tests {
}
}
}

/// `VICTORY_PHYSICAL_TILES=1`: a title buffer on physical pages that are GPU
/// memory is read in place (`crate::tiled`).
#[cfg(test)]
mod tiled_tests {
use crate::alias::{PhysicalHeap, Tile};
use crate::backend::{HostGpu, HostMemory};
use crate::watch::PAGE;
use std::sync::Mutex;

/// What the test's "runtime" maps: page address and its tile.
static SHOWN: Mutex<Vec<(usize, Tile)>> = Mutex::new(Vec::new());

fn lookup(at: usize, len: usize, out: &mut Vec<Option<Tile>>) -> bool {
let shown = SHOWN.lock().unwrap();
out.clear();
out.extend((at / PAGE..(at + len).div_ceil(PAGE)).map(|page| {
shown.iter().find(|(a, _)| *a == page * PAGE).map(|(_, t)| t.clone())
}));
true
}

/// Title memory of four pages showing heap tiles 2, 0, 3, 1 in turn.
#[test]
fn a_buffer_on_gpu_physical_pages_is_read_and_written_in_place() {
let Some(host) = super::host() else {
return; // no host GPU here
};
let _mode = super::flight::ModeGuard::new(false, false);
crate::alias::TEST_PHYSICAL_TILES.with(|c| c.set(Some(true)));
if !crate::alias::physical_tiles() {
crate::alias::TEST_PHYSICAL_TILES.with(|c| c.set(None));
return; // not Rosetta and D3DMetal
}
crate::tiled::on_physical_tiles(lookup);
let heap = PhysicalHeap::new(&host.device, 4 * PAGE).expect("a CPU-visible heap");
// SAFETY: a fresh reservation of four pages, never freed (its
// addresses stay the test's).
let at = unsafe {
windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
4 * PAGE,
windows_sys::Win32::System::Memory::MEM_RESERVE | windows_sys::Win32::System::Memory::MEM_COMMIT,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
)
} as usize;
assert_ne!(at, 0);
let order = [2usize, 0, 3, 1];
for (k, &tile) in order.iter().enumerate() {
// SAFETY: our reservation's page and the heap's tile.
assert!(unsafe { heap.alias_view(at + k * PAGE, tile * PAGE, PAGE) }, "remap page {k}");
SHOWN.lock().unwrap().push((at + k * PAGE, heap.tile(tile * PAGE).unwrap()));
}
// The title writes each page through its own address.
for k in 0..4 {
// SAFETY: mapped read-write.
unsafe { ((at + k * PAGE) as *mut u32).write_volatile(0x1000 + k as u32) };
}
let resource = 0x7e57_0000_usize;
crate::shadow::register(resource, at as u64, (4 * PAGE) as u64);
let copy = crate::shadow::find(at as u64, (4 * PAGE) as u64).expect("a copy");
assert!(copy.is_aliased(), "the copy reads the pages in place");

// The GPU reads what the title wrote, with no refresh.
let (out, out_ptr) = host.mapped_buffer(64, true).expect("readback");
let read = |page: usize| {
// SAFETY: mapped readback memory, no copy into it in flight.
unsafe { out_ptr.cast::<u32>().write_volatile(0xDEAD_DEAD) };
let list = host.new_list().unwrap();
// SAFETY: open list, live buffers.
unsafe { list.list.CopyBufferRegion(&out, 0, &copy.buffer, copy.offset((at + page * PAGE) as u64), 4) };
list.keep(&out);
list.close();
host.execute(&[&list]);
// SAFETY: the copy has run.
unsafe { out_ptr.cast::<u32>().read_volatile() }
};
for k in 0..4 {
assert_eq!(read(k), 0x1000 + k as u32, "page {k} as the GPU reads it");
}
// What the GPU writes the title reads at once.
let (src, src_ptr) = host.upload_buffer(64).expect("upload");
// SAFETY: mapped upload memory.
unsafe { src_ptr.cast::<u32>().write_volatile(0xBEEF) };
let list = host.new_list().unwrap();
// SAFETY: open list, live buffers.
unsafe { list.list.CopyBufferRegion(&copy.buffer, copy.offset((at + 2 * PAGE + 8) as u64), &src, 0, 4) };
list.keep(&src);
list.close();
host.execute(&[&list]);
// SAFETY: mapped read-write.
assert_eq!(unsafe { ((at + 2 * PAGE + 8) as *const u32).read_volatile() }, 0xBEEF);

// The title maps tile 3 at its second page as well: the copy follows.
// SAFETY: as above.
assert!(unsafe { heap.alias_view(at + PAGE, 3 * PAGE, PAGE) });
crate::tiled::physical_retiled(at + PAGE, PAGE, &[heap.tile(3 * PAGE)]);
assert_eq!(read(1), 0x1002, "the second page shows tile 3 now");
// Unmapped, it reads zeros (D3DMetal ignores null tile mappings: a
// tile of zeros stands in), and the other pages are as they were.
crate::tiled::physical_retiled(at + PAGE, PAGE, &[None]);
assert_eq!(read(1), 0, "an unmapped page reads zeros");
assert_eq!([read(0), read(3)], [0x1000, 0x1003]);

crate::shadow::unregister(resource, at as u64);
SHOWN.lock().unwrap().clear();
crate::alias::TEST_PHYSICAL_TILES.with(|c| c.set(None));
}

/// A buffer with a page that is not GPU memory is copied as before.
#[test]
fn a_buffer_off_gpu_pages_is_copied() {
if super::host().is_none() {
return;
}
crate::alias::TEST_PHYSICAL_TILES.with(|c| c.set(Some(true)));
crate::tiled::on_physical_tiles(lookup);
let p = crate::watch::tests::pool(2);
crate::shadow::register(p, p as u64, (2 * PAGE) as u64);
let copy = crate::shadow::find(p as u64, (2 * PAGE) as u64).expect("a copy");
assert!(!copy.is_aliased());
crate::shadow::unregister(p, p as u64);
drop(copy);
crate::watch::tests::free(p);
crate::alias::TEST_PHYSICAL_TILES.with(|c| c.set(None));
}
}
24 changes: 18 additions & 6 deletions crates/victory-gpu/src/host/flight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1966,7 +1966,9 @@ void main(uint3 id : SV_DispatchThreadID) {
TEST_PAUSE_LANDING.store(true, Ordering::Release);
host.execute_flight1(vec![quiet_copy(host, 0x1111_0001, &out1)], vec![]);
assert!(host.attach_signal(f1, 1, false));
assert_eq!(flights_in_air(host), 1);
// Another test's synchronous submission may land it at once: then
// this attempt does not take the path (`until_taken`).
let first_in_air = flights_in_air(host) == 1;

// SAFETY: valid title buffer.
unsafe { title_ptr.cast::<u32>().write_volatile(0x2222_0002) };
Expand All @@ -1981,7 +1983,10 @@ void main(uint3 id : SV_DispatchThreadID) {
assert!(host.attach_signal(f2, 1, false));

let after = ahead_counts();
let taken = after[0] - before[0] == 1 && after[1] - before[1] == 1 && flights_in_air(host) == 2;
let taken = first_in_air
&& after[0] - before[0] == 1
&& after[1] - before[1] == 1
&& flights_in_air(host) == 2;

TEST_PAUSE_LANDING.store(false, Ordering::Release);
let start = Instant::now();
Expand Down Expand Up @@ -2342,11 +2347,18 @@ void main(uint3 id : SV_DispatchThreadID) {
[Probe::Behind, Probe::RangesOnly, Probe::CleanKnown, Probe::Ceiling]
.map(|p| after[slot(p)] - before[slot(p)])
};
let [behind, ranges, clean, ceiling] = round(b, &sb);
assert_eq!((behind, ranges), (1, 1), "compared behind a flight with declared writes only");
// Another test's flight landing between the two (the last landed is
// the process's) leaves a round uncompared: it runs again.
let compared = |refreshed: u64, shadow: &Arc<crate::shadow::Shadow>| {
(0..20)
.map(|_| round(refreshed, shadow))
.find(|counts| counts[0] == 1)
.expect("another test's flight landed between the two every time")
};
let [_, ranges, clean, ceiling] = compared(b, &sb);
assert_eq!(ranges, 1, "compared behind a flight with declared writes only");
assert_eq!((clean, ceiling), (1, 1), "another copy: could go ahead");
let [behind, _, clean, ceiling] = round(a, &sa);
assert_eq!(behind, 1);
let [_, _, clean, ceiling] = compared(a, &sa);
assert_eq!((clean, ceiling), (0, 0), "the range it wrote: could not");
drop((sa, sb));
// SAFETY: the flights have landed.
Expand Down
4 changes: 4 additions & 0 deletions crates/victory-gpu/src/inplace_probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,10 @@ fn inplace_probe_6_remap_cpu_visible_tiles() {
D3D12_TILE_MAPPING_FLAG_NONE,
);
}
// shortcut: under D3DMetal this passes without the null mapping taking
// effect: the tile keeps its heap tile, and the copy out of it reads
// what the fetch's fresh buffer held anyway, zeros (`crate::tiled` maps
// unmapped pages to a tile of zeros instead).
let bytes = rig.fetch(&reserved, 0, K64).unwrap();
assert!(bytes.iter().all(|&byte| byte == 0), "null tile reads as zeros");
// SAFETY: null-mapping the GPU view leaves the CPU heap tile alive.
Expand Down
8 changes: 6 additions & 2 deletions crates/victory-gpu/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ mod sampler;
pub mod shader_cache;
#[cfg(windows)]
mod shadow;
#[cfg(windows)]
mod tiled;
pub mod signature;
mod switch;
#[cfg(windows)]
Expand Down Expand Up @@ -128,8 +130,10 @@ mod footprint_probe;
pub use copystat::CountingAlloc;
#[cfg(windows)]
pub use alias::{Unaliased, alias_region, enabled as alias_buffers, note_unaliased, unalias_region};
#[cfg(all(windows, feature = "diagnostics"))]
pub use alias::{PhysicalHeap, physical_heap};
#[cfg(windows)]
pub use alias::{PhysicalHeap, Tile, physical_heap, physical_tiles};
#[cfg(windows)]
pub use tiled::{on_physical_tiles, physical_retiled};
#[cfg(windows)]
pub use host::{MeshSupport, host_mesh_support, on_failure};
#[cfg(windows)]
Expand Down
24 changes: 20 additions & 4 deletions crates/victory-gpu/src/shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2329,23 +2329,39 @@ fn find_uncached(address: u64, end: u64) -> Option<Arc<Shadow>> {
if let Some(shadow) = find_aliased(address, end) {
return Some(shadow);
}
{
let found = {
let map = buffers_read();
let Some(key) = enclosing(&map, MAX_SPAN.load(Ordering::Relaxed), address, end) else {
drop(map);
return loose(address, end);
};
if let Some(shadow) = map.get(&key).and_then(|entry| entry.shadow.clone()) {
return Some(shadow);
match map.get(&key) {
Some(entry) => match &entry.shadow {
Some(shadow) => return Some(shadow.clone()),
None => Some((key, entry.end - key.0)),
},
None => None,
}
}
};
// `VICTORY_PHYSICAL_TILES=1`: a buffer on the title's physical pages
// reads them in place. Asked without the buffers' lock: the runtime's
// lookup takes its own, which it holds while it tells the trackers of
// a mapping (and they may read the buffers).
let mut tiled = found.and_then(|(key, len)| Some((key, crate::tiled::make(key.0, len)?)));
let mut map = buffers();
let key = enclosing(&map, MAX_SPAN.load(Ordering::Relaxed), address, end);
let Some(key) = key else {
drop(map);
return loose(address, end);
};
let entry = map.get_mut(&key)?;
if entry.shadow.is_none()
&& let Some((_, copy)) = tiled.take().filter(|(k, _)| *k == key)
{
entry.shadow = Some(copy);
released().remade(key.0);
changed();
}
if entry.shadow.is_none() {
let len = entry.end - key.0;
// Rounded up so that views ending in the buffer's last 256 bytes fit.
Expand Down
Loading