mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:58:37 +00:00
GPU: views off their buffer's elements get their own copy; heap records copied as bytes are mirrored
A structured view that does not start on an element of its host copy was refused and read zeros: the world's culling constants and the colour table bakes among them. The title also fills its heap with plain byte copies; written pages are mirrored at each submission. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@ -138,12 +138,18 @@ fn seen(view: &View) -> Option<Seen> {
|
||||
{
|
||||
return crate::texture::title_written(texture).then_some(Seen::Texture(*resource));
|
||||
}
|
||||
let (address, len) = match *view {
|
||||
View::Constant(address, size) => (address, u64::from(size)),
|
||||
_ => crate::descriptor::host::buffer_range(view)?,
|
||||
// The copy the host view reads.
|
||||
let (shadow, address, len) = match *view {
|
||||
View::Constant(address, size) => {
|
||||
let len = u64::from(size);
|
||||
((len > 0).then(|| crate::shadow::find(address, len)).flatten()?, address, len)
|
||||
}
|
||||
_ => crate::descriptor::host::view_copy(view)?,
|
||||
};
|
||||
let uav = matches!(view, View::Unordered(..) | View::Placed(true, ..));
|
||||
let shadow = (len > 0).then(|| crate::shadow::find(address, len)).flatten()?;
|
||||
if len == 0 {
|
||||
return None;
|
||||
}
|
||||
let len = len.min(shadow.left(address));
|
||||
Some(Seen::Buffer(shadow, address, len, uav))
|
||||
}
|
||||
|
||||
@ -59,6 +59,10 @@ pub(crate) struct Heap {
|
||||
host: std::sync::OnceLock<Option<host::HostHeap>>,
|
||||
#[cfg(windows)]
|
||||
pending: std::sync::Mutex<Vec<u32>>,
|
||||
/// A shader-visible heap in the title's memory, tracked: the title also
|
||||
/// copies descriptors into it itself, as bytes (`sync_heaps`).
|
||||
#[cfg(windows)]
|
||||
written: Option<crate::watch::Tracked>,
|
||||
}
|
||||
|
||||
pub(crate) fn heap<'a>(this: This) -> &'a Heap {
|
||||
@ -148,6 +152,44 @@ fn mirror(handle: u64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirrors what the title wrote into its shader-visible heaps without a
|
||||
/// call: Grand Theft Auto VI copies descriptors (our records) into its heap
|
||||
/// as bytes, so only a change of its memory shows them. Each slot of a page
|
||||
/// written since the last sync is made again if its record changed (in the
|
||||
/// world 1,300-14,400 slots a frame, against a few hundred views made by
|
||||
/// calls). Called before each submission: shaders take descriptors from the
|
||||
/// heap at indices in their data, where a slot never mirrored reads nothing.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn sync_heaps() {
|
||||
// Held throughout: a heap is not dropped while its slots are made.
|
||||
let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for &(start, _, at) in heaps.iter() {
|
||||
// SAFETY: registered heaps are live (removed when dropped).
|
||||
let heap = unsafe { &*(at as *const Heap) };
|
||||
let (Some(Some(host)), Some(written), Some(step)) =
|
||||
(heap.host.get(), &heap.written, increment(heap.desc.kind))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let step = u64::from(step);
|
||||
for (from, to) in written.take(start as usize, usize::MAX) {
|
||||
// By page: one with nothing mapped (the title unmaps heap pages
|
||||
// too) holds no records.
|
||||
let page_size = crate::watch::PAGE;
|
||||
for page in (from & !(page_size - 1)..to).step_by(page_size) {
|
||||
let (page, end) = (page.max(from), (page + page_size).min(to));
|
||||
if !crate::host::read_into(page as *const u8, &mut [0u8; 4]) {
|
||||
continue;
|
||||
}
|
||||
let (first, last) = ((page as u64 - start) / step, (end as u64 - start).div_ceil(step));
|
||||
for index in first..last.min(u64::from(heap.desc.count)) {
|
||||
host.mirror(index as u32, start + index * step, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives back dynamic slots of the host heap behind the title heap at
|
||||
/// `heap`, if that heap still exists.
|
||||
#[cfg(windows)]
|
||||
@ -608,6 +650,10 @@ pub(crate) extern "system" fn create_heap(
|
||||
host: std::sync::OnceLock::new(),
|
||||
#[cfg(windows)]
|
||||
pending: Default::default(),
|
||||
#[cfg(windows)]
|
||||
written: (placed && visible)
|
||||
.then(|| crate::watch::track(start as usize, size as usize, true))
|
||||
.flatten(),
|
||||
});
|
||||
#[cfg(windows)]
|
||||
if visible {
|
||||
@ -744,6 +790,41 @@ mod tests {
|
||||
assert_ne!(old, new, "a new generation");
|
||||
}
|
||||
|
||||
/// A record the title copies into its shader-visible heap as bytes (no
|
||||
/// call) is made on the host at the next sync, and only then.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn records_copied_as_bytes_are_made_at_the_next_sync() {
|
||||
let memory = crate::watch::tests::pool(1);
|
||||
let desc = HeapDesc {
|
||||
kind: SAMPLERS,
|
||||
count: 64,
|
||||
flags: SHADER_VISIBLE,
|
||||
nodes: 1,
|
||||
};
|
||||
let mut h = std::ptr::null();
|
||||
let placement = Placement {
|
||||
address: memory as u64,
|
||||
size: 64 * 16,
|
||||
};
|
||||
assert_eq!(create(desc, placement, &mut h), S_OK);
|
||||
if let Some(host) = heap(h).host() {
|
||||
// Our record, written where no heap sees it, then copied in.
|
||||
let mut elsewhere = [0u64; 2];
|
||||
let at = elsewhere.as_mut_ptr() as u64;
|
||||
create_sampler(std::ptr::null(), &[21, 3, 3, 3, 0, 1, 0, 0, 0, 0, 0, 0x7f7f_ffff, 0], at);
|
||||
let slot = memory as u64 + 5 * 16;
|
||||
// SAFETY: 16 bytes of each, ours; the heap's page is guarded
|
||||
// (our handler opens it).
|
||||
unsafe { std::ptr::copy_nonoverlapping(at as *const u8, slot as *mut u8, 16) };
|
||||
assert!(!host.made(5));
|
||||
sync_heaps();
|
||||
assert!(host.made(5), "made at the sync");
|
||||
}
|
||||
slot::<extern "system" fn(This) -> u32>(h, 0x10)(h);
|
||||
crate::watch::tests::free(memory);
|
||||
}
|
||||
|
||||
/// Grand Theft Auto VI places its shader-visible heap in its own memory
|
||||
/// and checks that the heap starts there.
|
||||
#[test]
|
||||
|
||||
@ -614,6 +614,12 @@ impl HostHeap {
|
||||
}
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// Whether slot `index` was made from a record (tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn made(&self, index: u32) -> bool {
|
||||
self.made.lock().unwrap_or_else(|e| e.into_inner())[index as usize] != 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Logs `what` the first time it happens.
|
||||
@ -743,6 +749,14 @@ pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> {
|
||||
))
|
||||
}
|
||||
|
||||
/// The host copy a buffer view's bytes are in (the one its host view
|
||||
/// reads, [`crate::shadow::for_view`]) and the view's title range.
|
||||
pub(crate) fn view_copy(view: &View) -> Option<(std::sync::Arc<crate::shadow::Shadow>, u64, u64)> {
|
||||
let (address, len) = buffer_range(view)?;
|
||||
let shadow = crate::shadow::for_view(address, len, u64::from(view_stride(view)))?;
|
||||
Some((shadow, address, len))
|
||||
}
|
||||
|
||||
/// [`buffer_range`] of an unordered access view of memory at `base`.
|
||||
fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
|
||||
let desc = uav_desc(words);
|
||||
@ -770,20 +784,17 @@ fn buffer_srv(
|
||||
mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC,
|
||||
at: D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
) -> Option<Kept> {
|
||||
let shadow = crate::shadow::find(address, len)?;
|
||||
let element = element_size(&desc);
|
||||
// SAFETY: a buffer view's union member.
|
||||
let buffer = unsafe { &mut desc.Anonymous.Buffer };
|
||||
let offset = shadow.offset(address);
|
||||
if element == 0 || offset % element != 0 {
|
||||
once!(
|
||||
offset,
|
||||
element,
|
||||
"buffer view not on an element of its host copy"
|
||||
);
|
||||
if element == 0 {
|
||||
once!(len, "buffer view of elements without a size");
|
||||
return None;
|
||||
}
|
||||
buffer.FirstElement += offset / element;
|
||||
// The copy its own bytes are in, its first element counted from there.
|
||||
let start = address + buffer.FirstElement * element;
|
||||
let shadow = crate::shadow::for_view(start, u64::from(buffer.NumElements) * element, element)?;
|
||||
buffer.FirstElement = shadow.offset(start) / element;
|
||||
let (first, count) = (buffer.FirstElement, buffer.NumElements);
|
||||
if !in_buffer(&shadow.buffer, first, count, element) {
|
||||
once!(first, count, element, "buffer view empty or past its host copy");
|
||||
@ -821,13 +832,6 @@ fn buffer_uav(
|
||||
mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC,
|
||||
at: D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
) -> Option<Kept> {
|
||||
let shadow = crate::shadow::find(address, len)?;
|
||||
// SAFETY: a live buffer.
|
||||
let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
|
||||
if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
|
||||
once!("unordered access to a buffer whose host copy shaders cannot write");
|
||||
return None;
|
||||
}
|
||||
// SAFETY: a buffer view's union member.
|
||||
let buffer = unsafe { &mut desc.Anonymous.Buffer };
|
||||
let element = if buffer.StructureByteStride > 0 {
|
||||
@ -837,12 +841,19 @@ fn buffer_uav(
|
||||
} else {
|
||||
crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
|
||||
};
|
||||
let offset = shadow.offset(address);
|
||||
if element == 0 || offset % element != 0 {
|
||||
once!(offset, element, "unordered buffer view not on an element of its host copy");
|
||||
if element == 0 {
|
||||
once!(len, "unordered buffer view of elements without a size");
|
||||
return None;
|
||||
}
|
||||
buffer.FirstElement += offset / element;
|
||||
let start = address + buffer.FirstElement * element;
|
||||
let shadow = crate::shadow::for_view(start, u64::from(buffer.NumElements) * element, element)?;
|
||||
// SAFETY: a live buffer.
|
||||
let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
|
||||
if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
|
||||
once!("unordered access to a buffer whose host copy shaders cannot write");
|
||||
return None;
|
||||
}
|
||||
buffer.FirstElement = shadow.offset(start) / element;
|
||||
buffer.CounterOffsetInBytes = 0;
|
||||
let (first, count) = (buffer.FirstElement, buffer.NumElements);
|
||||
if !in_buffer(&shadow.buffer, first, count, element) {
|
||||
|
||||
@ -1551,15 +1551,17 @@ fn readable(list: &HostList, u: &UsedResource, view: &View) {
|
||||
let view = placed.as_ref().unwrap_or(view);
|
||||
// Buffer views read title memory: their range is copied at submission;
|
||||
// what shaders write through unordered access goes back to it after.
|
||||
// Constant buffers (raw views) to their copy's end at most.
|
||||
// Constant buffers (raw views) to their copy's end at most; others in
|
||||
// the copy their host view reads.
|
||||
let range = match *view {
|
||||
View::Constant(address, size) => crate::shadow::find(address, 1)
|
||||
.map(|s| (address, u64::from(size).min(s.left(address)))),
|
||||
_ => crate::descriptor::host::buffer_range(view),
|
||||
View::Constant(address, size) => crate::shadow::find(address, 1).and_then(|s| {
|
||||
let len = u64::from(size).min(s.left(address));
|
||||
crate::shadow::find(address, len).map(|s| (s, address, len))
|
||||
}),
|
||||
_ => crate::descriptor::host::view_copy(view),
|
||||
};
|
||||
if let Some((address, len)) = range
|
||||
if let Some((shadow, address, len)) = range
|
||||
&& len > 0
|
||||
&& let Some(shadow) = crate::shadow::find(address, len)
|
||||
{
|
||||
shadow.refresh(list, address, len);
|
||||
if u.kind == ResourceType::Uav {
|
||||
@ -2243,4 +2245,45 @@ void main(uint3 id : SV_DispatchThreadID) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A structured view the title places off its buffer's elements (the
|
||||
/// culling constants at a ring position) is made over a copy of its own
|
||||
/// bytes; one on an element views the buffer's copy.
|
||||
#[test]
|
||||
fn structured_views_off_their_buffers_elements_get_their_own_copy() {
|
||||
let Some(host) = crate::host::host() else {
|
||||
return; // no host GPU here
|
||||
};
|
||||
let src = buffer(1 << 16);
|
||||
let (bytes, _) = crate::resource::buffer_bytes(src).unwrap();
|
||||
let start = bytes as u64;
|
||||
// SAFETY: a plain CPU-side heap of one view.
|
||||
let cpu: ID3D12DescriptorHeap = unsafe {
|
||||
host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
|
||||
NumDescriptors: 1,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
.unwrap();
|
||||
// SAFETY: a live heap.
|
||||
let at = unsafe { cpu.GetCPUDescriptorHandleForHeapStart() };
|
||||
// Four 456-byte elements placed at `address` (resource and view
|
||||
// descriptions as the title passes them to device 0x230).
|
||||
let view = |address: u64| {
|
||||
let resource: [u32; 14] = [1, 0, 0, 0, 4 * 456, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
|
||||
let mut desc = [0u32; 16];
|
||||
desc[..10].copy_from_slice(&[0, 1, 5768, 0, 0, 0, 4, 456, 0, 0]);
|
||||
(desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
|
||||
View::Placed(false, resource, desc)
|
||||
};
|
||||
let width = |address: u64| {
|
||||
let made = crate::descriptor::host::make_view(&view(address), at).expect("a view");
|
||||
// SAFETY: a live buffer.
|
||||
unsafe { made.GetDesc() }.Width
|
||||
};
|
||||
assert_eq!(width(start + 456), 1 << 16, "on an element: the buffer's copy");
|
||||
assert_eq!(width(start + 100), (4 * 456u64).next_multiple_of(256), "off: its own bytes");
|
||||
let (copy, address, len) = crate::descriptor::host::view_copy(&view(start + 100)).unwrap();
|
||||
assert_eq!((copy.range(), address, len), ((start + 100, 4 * 456), start + 100, 4 * 456));
|
||||
}
|
||||
}
|
||||
|
||||
@ -587,6 +587,9 @@ impl Host {
|
||||
let faults = crate::copystat::page_faults();
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::Submissions, 1);
|
||||
// Descriptors the title copied into its heaps itself, before the
|
||||
// heaps' views are brought up to date below.
|
||||
crate::descriptor::sync_heaps();
|
||||
// Textures heap-indexing shaders may read, uploaded first by a list
|
||||
// of ours where their title memory changed.
|
||||
let heaps: Vec<std::sync::Arc<crate::bindless::Viewed>> = runs
|
||||
@ -1911,6 +1914,7 @@ impl Meter {
|
||||
let copy_frames = std::mem::take(&mut self.copy_stats_frames) as f64;
|
||||
crate::copystat::log(copy_frames);
|
||||
crate::bindless::log(copy_frames);
|
||||
crate::shadow::log_views(copy_frames);
|
||||
for (why, n) in drops.iter().take(40) {
|
||||
tracing::info!(
|
||||
"dropped {:.1}/frame without a host pipeline: {why}",
|
||||
|
||||
@ -511,6 +511,84 @@ fn loose(address: u64, end: u64) -> Option<Arc<Shadow>> {
|
||||
Some(shadow)
|
||||
}
|
||||
|
||||
/// The copy a buffer view of `len` bytes at `address`, whose elements are
|
||||
/// `element` bytes, reads: the innermost title buffer's ([`find`]), unless
|
||||
/// the view does not start on an element of that copy. A host view counts
|
||||
/// its first element from its buffer's start; a console view starts at any
|
||||
/// address, and the title places structured views at ring positions inside
|
||||
/// its big GPU heap (the meshlet culling's 456-byte constants, the colour
|
||||
/// bakes' parameter blocks: refused, their slots read zeros, every meshlet
|
||||
/// culled). Such a view gets a copy of its own bytes, starting at its
|
||||
/// address.
|
||||
pub(crate) fn for_view(address: u64, len: u64, element: u64) -> Option<Arc<Shadow>> {
|
||||
let shadow = find(address, len)?;
|
||||
if element == 0 || shadow.offset(address).is_multiple_of(element) {
|
||||
return Some(shadow);
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
VIEWS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
exact(address, len)
|
||||
}
|
||||
|
||||
/// Asks for, and copies made of, views off their copy's elements, the
|
||||
/// copies' bytes and the largest (diagnostics).
|
||||
#[cfg(feature = "diagnostics")]
|
||||
static VIEWS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
|
||||
|
||||
/// Logs [`VIEWS`] per frame over `frames`.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn log_views(frames: f64) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let [asks, made, bytes, largest] = [0, 1, 2, 3].map(|i| VIEWS[i].swap(0, Relaxed));
|
||||
let kept = EXACT.lock().unwrap_or_else(|e| e.into_inner()).1.len();
|
||||
if asks > 0 {
|
||||
tracing::info!(
|
||||
"buffer views off their copy's elements: {:.0} asked for/frame, {:.0} copies made/frame ({:.1} KB), largest {largest} bytes, {kept} kept",
|
||||
asks as f64 / frames,
|
||||
made as f64 / frames,
|
||||
bytes as f64 / frames / 1e3
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies of single views' bytes ([`for_view`]), by (start, length), with
|
||||
/// the use that last asked for each.
|
||||
#[allow(clippy::type_complexity)]
|
||||
static EXACT: Mutex<(u64, BTreeMap<(u64, u64), (Arc<Shadow>, u64)>)> = Mutex::new((0, BTreeMap::new()));
|
||||
|
||||
/// Copies [`EXACT`] keeps: ring positions change every frame, so the least
|
||||
/// recently asked for go (lists and heap slots using one keep it alive).
|
||||
const EXACT_KEPT: usize = 1024;
|
||||
|
||||
fn exact(address: u64, len: u64) -> Option<Arc<Shadow>> {
|
||||
let mut guard = EXACT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (tick, map) = &mut *guard;
|
||||
*tick += 1;
|
||||
if let Some((shadow, used)) = map.get_mut(&(address, len)) {
|
||||
*used = *tick;
|
||||
return Some(shadow.clone());
|
||||
}
|
||||
if map.len() >= EXACT_KEPT
|
||||
&& let Some(&oldest) = map.iter().min_by_key(|(_, (_, used))| *used).map(|(k, _)| k)
|
||||
{
|
||||
map.remove(&oldest);
|
||||
}
|
||||
let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?;
|
||||
crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}"));
|
||||
// SAFETY: a live buffer.
|
||||
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
|
||||
let shadow = Arc::new(Shadow::new(buffer, data, gpu, address, len));
|
||||
map.insert((address, len), (shadow.clone(), *tick));
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
VIEWS[1].fetch_add(1, Relaxed);
|
||||
VIEWS[2].fetch_add(len, Relaxed);
|
||||
VIEWS[3].fetch_max(len, Relaxed);
|
||||
}
|
||||
Some(shadow)
|
||||
}
|
||||
|
||||
/// Every host copy of title memory made so far (buffers and windows).
|
||||
pub(crate) fn all() -> Vec<Arc<Shadow>> {
|
||||
let mut all: Vec<Arc<Shadow>> = buffers().values().filter_map(|e| e.shadow.clone()).collect();
|
||||
|
||||
@ -530,7 +530,7 @@ pub(crate) mod tests {
|
||||
|
||||
/// A write-watched allocation of `pages` pages (as the runtime's pools),
|
||||
/// on a 64 KiB boundary (the allocation granularity).
|
||||
fn pool(pages: usize) -> usize {
|
||||
pub(crate) fn pool(pages: usize) -> usize {
|
||||
// SAFETY: a fresh allocation, freed by the test.
|
||||
let p = unsafe {
|
||||
VirtualAlloc(
|
||||
@ -544,7 +544,7 @@ pub(crate) mod tests {
|
||||
p
|
||||
}
|
||||
|
||||
fn free(p: usize) {
|
||||
pub(crate) fn free(p: usize) {
|
||||
// SAFETY: an allocation of ours.
|
||||
unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user