diff --git a/crates/metal2vulkan-validation/src/replay/heaps.rs b/crates/metal2vulkan-validation/src/replay/heaps.rs new file mode 100644 index 000000000..58190b1e4 --- /dev/null +++ b/crates/metal2vulkan-validation/src/replay/heaps.rs @@ -0,0 +1,185 @@ +//! The stream's heaps on the runtime (`docs/REPLAY-STREAM.md`, sections 5 and 10): a placement +//! heap laid out again for the runtime's sizes and alignments (`relay`), and, on a backend that +//! makes objects at their recorded addresses, a heap's buffers and textures made apart +//! (`HeapSplit`), with the textures whose recorded range met a live buffer's counted +//! (`Overlaps`). + +use super::stream::Call; +use super::value::Value; +use std::collections::{BTreeMap, HashMap}; + +/// How a backend that makes objects at their recorded addresses (`Backend::places_at_recorded`) +/// makes a heap the stream made with a recorded range (`Backend::split_heap`), read ahead, by +/// what the stream places in it: its buffers in a heap at the recorded address, its textures in +/// one outside the recorded addresses. A heap the stream places only buffers in is the first +/// alone, one it places no buffer in the second alone, one it places both in both. Decided by +/// what the stream places in it, whatever its type. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct HeapSplit { + /// The stream places a buffer in the heap: a heap at its recorded address, of its recorded + /// size, holds its buffers, each at its recorded offset. It never grows. + pub buffers: bool, + /// The size of the heap outside the recorded addresses that holds the heap's textures, laid + /// out for the runtime's sizes (`relay` of its textures alone); none where the stream places + /// a buffer and no texture in it. + pub textures: Option, +} + +/// What a placement heap holds at each recorded offset: the largest size and alignment the +/// runtime answers for the resources placed there. +pub(super) type Placements = BTreeMap; + +/// A placement heap's layout on the runtime: its size, and the offset the player places each +/// resource at by the offset the stream places it at. +pub(super) struct Layout { + pub size: u64, + pub offsets: HashMap, + /// Whether it lays out the heap's textures alone, which a backend that makes objects at their + /// recorded addresses makes in a heap of their own (`HeapSplit::textures`): the heap's buffers + /// keep their recorded offsets, and the heap its recorded size. + pub textures_only: bool, +} + +/// The layout of a placement heap of `size` bytes, as a program asking the runtime's sizes and +/// alignments lays it out, whose resources the stream places at the offsets of `at`, each with the +/// most bytes and the largest alignment the runtime answers for its resources there. Each offset +/// keeps at least its distance from the one below, moves up until the resources below it end, and +/// rounds up to its alignment; the heap keeps at least its distance past the last offset and holds +/// the resources there. Resources at one offset still share it; resources at different offsets no +/// longer meet. Where every resource ends before the next offset and every offset is aligned, the +/// layout is the stream's. +pub(super) fn relay(size: u64, at: &Placements, textures_only: bool) -> Layout { + let mut offsets = HashMap::with_capacity(at.len()); + let mut below: Option<(u64, u64, u64)> = None; + for (&recorded, &(bytes, align)) in at { + let floor = match below { + None => recorded, + Some((was, placed, held)) => (placed + (recorded - was)).max(placed + held), + }; + let placed = floor.next_multiple_of(align.max(1)); + offsets.insert(recorded, placed); + below = Some((recorded, placed, bytes)); + } + let size = match below { + None => size, + Some((was, placed, held)) => (placed + size.saturating_sub(was)).max(placed + held), + }; + Layout { + size, + offsets, + textures_only, + } +} + +/// The recorded size of the heap `call` (`newHeapWithDescriptor:`) makes. +pub(super) fn heap_size(call: &Call) -> Option { + descriptor_field(call, "size") +} + +/// The recorded size of the heap `call` (`newHeapWithDescriptor:`) makes, where it is a placement +/// heap (`MTLHeapTypePlacement`). +pub(super) fn placement_heap(call: &Call) -> Option { + (descriptor_field(call, "heapType")? == 1).then_some(heap_size(call)?) +} + +fn descriptor_field(call: &Call, key: &str) -> Option { + let entries = call.args.first()?.as_map()?; + entries.iter().find(|(k, _)| &**k == key)?.1.as_uint() +} + +/// Whether `selector` places a buffer in its receiver where that is a heap: a placement heap's +/// `newBufferWithLength:options:offset:` or an automatic heap's `newBufferWithLength:options:`. +pub(super) fn places_buffer(selector: &str) -> bool { + matches!( + selector, + "newBufferWithLength:options:offset:" | "newBufferWithLength:options:" + ) +} + +/// Whether `selector` places a texture in its receiver where that is a heap: a placement heap's +/// `newTextureWithDescriptor:offset:` or an automatic heap's `newTextureWithDescriptor:`. +pub(super) fn places_texture(selector: &str) -> bool { + matches!( + selector, + "newTextureWithDescriptor:offset:" | "newTextureWithDescriptor:" + ) +} + +/// The argument of a placement heap's call that is the offset it places at. +pub(super) fn placement_offset(selector: &str) -> Option { + match selector { + "newTextureWithDescriptor:offset:" => Some(1), + "newBufferWithLength:options:offset:" => Some(2), + _ => None, + } +} + +/// The live buffers and textures the stream places in each placement heap with a recorded range, +/// by heap, and the textures whose recorded range met a live buffer's, each counted once (`met`), +/// whichever of the two was placed first: a texture's range starts at the heap's recorded address +/// plus its offset and holds the bytes the runtime answers for its descriptor (the stream holds no +/// texture's size), a buffer's is the range it answered. Such a texture and buffer shared memory +/// in the recording; a backend that makes the heap's buffers and textures apart (`HeapSplit`) no +/// longer shares it. +#[derive(Default)] +pub(super) struct Overlaps { + /// Each heap's live buffers and live textures, by id: each one's range and, for a texture, + /// whether it met a buffer. + heaps: HashMap, + /// The heap of each live resource placed in one. + of: HashMap, + /// The textures that met a live buffer. + pub met: u64, +} + +#[derive(Default)] +struct Live { + buffers: HashMap, + textures: HashMap, +} + +fn meet((start, end): (u64, u64), (other, other_end): (u64, u64)) -> bool { + start < other_end && other < end +} + +impl Overlaps { + /// Buffer `buffer` placed in `heap`, at `range`. + pub fn buffer(&mut self, heap: u64, buffer: u64, range: (u64, u64)) { + let live = self.heaps.entry(heap).or_default(); + for (start, end, met) in live.textures.values_mut() { + if !*met && meet((*start, *end), range) { + *met = true; + self.met += 1; + } + } + live.buffers.insert(buffer, range); + self.of.insert(buffer, heap); + } + + /// Texture `texture` placed in `heap`, at `range`. + pub fn texture(&mut self, heap: u64, texture: u64, range: (u64, u64)) { + let live = self.heaps.entry(heap).or_default(); + let met = live.buffers.values().any(|&buffer| meet(buffer, range)); + self.met += u64::from(met); + live.textures.insert(texture, (range.0, range.1, met)); + self.of.insert(texture, heap); + } + + /// `object` released: no longer live, where it was placed in a heap. + pub fn release(&mut self, object: u64) { + let Some(heap) = self.of.remove(&object) else { + return; + }; + if let Some(live) = self.heaps.get_mut(&heap) { + live.buffers.remove(&object); + live.textures.remove(&object); + } + } +} + +/// A buffer's recorded range, from `call`'s answers. +pub(super) fn recorded_range(call: &Call) -> Option<(u64, u64)> { + let address = call.answer("gpuAddress")?.as_address()?; + let length = call.answer("gpuLength").and_then(Value::as_uint)?; + Some((address, address + length)) +} diff --git a/crates/metal2vulkan-validation/src/replay/mod.rs b/crates/metal2vulkan-validation/src/replay/mod.rs index 911e080f1..14f2d8fd8 100644 --- a/crates/metal2vulkan-validation/src/replay/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/mod.rs @@ -3,6 +3,7 @@ mod addresses; mod args; +mod heaps; mod new_runtime; mod old_runtime; mod player; @@ -12,6 +13,7 @@ mod texwrites; mod translator; mod value; +pub use heaps::HeapSplit; pub use new_runtime::{ManagedCopies, NewRuntime}; pub use old_runtime::OldRuntime; pub use player::WAIT_COMPLETED; diff --git a/crates/metal2vulkan-validation/src/replay/old_runtime/encoders.rs b/crates/metal2vulkan-validation/src/replay/old_runtime/encoders.rs index a1fdc4c11..1891c6e49 100644 --- a/crates/metal2vulkan-validation/src/replay/old_runtime/encoders.rs +++ b/crates/metal2vulkan-validation/src/replay/old_runtime/encoders.rs @@ -253,11 +253,16 @@ impl OldRuntime { self.compute(id).use_resource(resource.as_ref(), usage) } "useHeap:" => { - let heap = self.kind(call, Self::id(call, 0)?, "heap", |object| match object { - Object::Heap(heap) | Object::Block(heap, _) => Some(heap.clone()), + let heaps = self.kind(call, Self::id(call, 0)?, "heap", |object| match object { + Object::Heap(heap, textures) => Some((heap.clone(), textures.clone())), + Object::Block(heap, _) => Some((heap.clone(), None)), _ => None, })?; - self.compute(id).use_heap(&heap) + // A heap the player split is both of the runtime's heaps. + match heaps { + (heap, None) => self.compute(id).use_heap(&heap), + (heap, Some(textures)) => self.compute(id).use_heaps(&[&heap, &textures]), + } } "updateFence:" => { let fence = self.fence(call, 0)?; diff --git a/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs index 28762dfa1..39023e353 100644 --- a/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs @@ -8,6 +8,7 @@ mod args; mod descriptors; mod encoders; +use super::heaps::HeapSplit; use super::player::{Backend, Counters, Made, PlayError}; use super::stream::Call; use super::value::Value; @@ -38,7 +39,10 @@ enum Object { Buffer(Buffer), /// A block: its heap, and the buffer over all of it where the CPU writes it. Block(Heap, Option), - Heap(Heap), + /// A heap: the runtime's heap its buffers go in, and, where the player split it (`HeapSplit`) + /// and the stream places both buffers and textures in it, the heap outside the space its + /// textures go in. Otherwise its textures go in the first. + Heap(Heap, Option), Texture(Texture), TextureDescriptor(Box), Pass(Box), @@ -86,9 +90,8 @@ pub struct OldRuntime { /// arguments is made of. display: Option>, read_backs_left_out: u64, - /// The heap the next call makes, where the stream places no buffer in it - /// (`Backend::holds_no_buffer`): it is made outside the space. - no_buffer: Cell>, + /// The heap the next call makes and how the player split it (`Backend::split_heap`). + split: Cell>, } /// A made object with no address. @@ -185,7 +188,7 @@ impl OldRuntime { marked: false, read_backs_left_out: 0, display: None, - no_buffer: Cell::new(None), + split: Cell::new(None), } } @@ -383,16 +386,35 @@ impl OldRuntime { (Object::Block(heap, whole), made) } "newHeapWithDescriptor:" => { - let at = match self.no_buffer.take() { - Some(heap) if heap == call.result => AddressPlacement::Outside, - _ => address_placement(call)?, + let descriptor = descriptors::heap(call)?; + let split = self.split.take().filter(|&(heap, _)| heap == call.result); + // The heap the buffers go in, at the recorded address and size; the one the + // textures go in, outside the space at the size the player laid them out at. + let pinned = || -> Result { + let at = address_placement(call)?; + let pinned = descriptor.with_placement(at); + device.new_heap(&pinned).map_err(unplaced(call, at)) + }; + let outside = |size: u64| -> Result { + let mut outside = descriptor.with_placement(AddressPlacement::Outside); + outside.size = size; + device.new_heap(&outside).map_err(failed(call)) + }; + let (heap, textures) = match split.map(|(_, split)| split) { + None => (pinned()?, None), + Some(HeapSplit { + buffers: false, + textures, + }) => (outside(textures.unwrap_or(descriptor.size))?, None), + Some(HeapSplit { + buffers: true, + textures, + }) => (pinned()?, textures.map(outside).transpose()?), }; - let descriptor = descriptors::heap(call)?.with_placement(at); - let heap = device.new_heap(&descriptor).map_err(unplaced(call, at))?; let made = Made { address: Some(heap.gpu_address().0), }; - (Object::Heap(heap), made) + (Object::Heap(heap, textures), made) } "newLibraryWithData:error:" => { let library = device.new_library_with_data(data(call, 0)?); @@ -532,8 +554,15 @@ impl OldRuntime { Ok(Some(unaddressed(Object::Texture(texture)))) } - /// A call of a heap or a block, and what it made. - fn heap_call(&self, call: &Call, heap: &Heap) -> Result<(Object, Made), PlayError> { + /// A call of a heap or a block, and what it made: a buffer in `heap`, at its recorded address + /// where it has one (a refusal stops the play naming it, `PlayError::Unpinned`), a texture in + /// `textures`. + fn heap_call( + &self, + call: &Call, + heap: &Heap, + textures: &Heap, + ) -> Result<(Object, Made), PlayError> { match &*call.selector { "m2v.newBufferInBlock:offset:length:options:" => { if Self::id(call, 0)? != call.receiver { @@ -545,12 +574,13 @@ impl OldRuntime { } "newBufferWithLength:options:offset:" => { let options = options(call, uint(call, 1)?)?; + let at = address_placement(call)?; let buffer = heap.new_buffer_at_offset(uint(call, 0)?, options, uint(call, 2)?); - Ok(addressed(buffer.map_err(failed(call))?)) + Ok(addressed(buffer.map_err(unplaced(call, at))?)) } "newTextureWithDescriptor:offset:" => { let descriptor = self.texture_descriptor(call, 0)?; - let texture = heap.new_texture_at_offset(&descriptor, uint(call, 1)?); + let texture = textures.new_texture_at_offset(&descriptor, uint(call, 1)?); Ok(unaddressed(Object::Texture(texture.map_err(failed(call))?))) } _ => Err(refuse(call, "not played on a heap")), @@ -850,7 +880,11 @@ impl Backend for OldRuntime { None } Some(Object::Buffer(buffer)) => self.buffer_call(call, buffer)?, - Some(Object::Block(heap, _) | Object::Heap(heap)) => Some(self.heap_call(call, heap)?), + Some(Object::Block(heap, _)) => Some(self.heap_call(call, heap, heap)?), + Some(Object::Heap(heap, textures)) => { + let textures = textures.as_ref().unwrap_or(heap); + Some(self.heap_call(call, heap, textures)?) + } Some(Object::Texture(texture)) => self.texture_call(call, texture)?, Some(Object::TextureDescriptor(_)) => { self.texture_descriptor_call(call)?; @@ -1094,10 +1128,11 @@ impl Backend for OldRuntime { true } - /// The heap goes outside the space: no address the program holds lies in it, and a heap the - /// player grew for the runtime's sizes would hold pages past its recorded span. - fn holds_no_buffer(&mut self, heap: u64) { - self.no_buffer.set(Some(heap)); + /// The heap's buffers go in a heap at its recorded address and size, its textures in one + /// outside the space: no address the program holds lies in a texture, and a heap the player + /// grew for the runtime's texture sizes would hold pages past its recorded span. + fn split_heap(&mut self, heap: u64, split: HeapSplit) { + self.split.set(Some((heap, split))); } fn managed_texture(&self, texture: u64) -> Option { diff --git a/crates/metal2vulkan-validation/src/replay/player.rs b/crates/metal2vulkan-validation/src/replay/player.rs index 213d8c380..489b7c332 100644 --- a/crates/metal2vulkan-validation/src/replay/player.rs +++ b/crates/metal2vulkan-validation/src/replay/player.rs @@ -6,6 +6,10 @@ //! a dispatch compared. use super::addresses::AddressMap; +use super::heaps::{ + heap_size, placement_heap, placement_offset, places_buffer, places_texture, recorded_range, + relay, HeapSplit, Layout, Overlaps, Placements, +}; use super::stream::{Call, StreamError, StreamReader}; use super::texwrites::TexWrites; use super::value::{Hash, Value}; @@ -159,12 +163,16 @@ pub trait Backend { /// recording's runtime did ignores it. fn recorded_id(&mut self, _object: u64, _id: u64) {} - /// The stream places no buffer in heap `heap`, which the next call makes (read ahead): no - /// address the program holds lies in it, as a texture has none and a heap answers none. A - /// backend that makes objects at their recorded addresses (`places_at_recorded`) makes it - /// outside them, so that a heap the player grew for the runtime's sizes (`relay`) meets no - /// other object's recorded range; another ignores it. - fn holds_no_buffer(&mut self, _heap: u64) {} + /// How to make heap `heap`, which the next call makes with a recorded range, by what the + /// stream places in it (read ahead), told only to a backend that makes objects at their + /// recorded addresses (`places_at_recorded`): its buffers in a heap at the recorded address + /// and size, each at its recorded offset, and its textures in a heap outside the recorded + /// addresses of the size the player laid them out at (`relay`). A texture has no address the + /// program holds, so the textures' heap may grow for the runtime's sizes and meet no other + /// object's recorded range; the buffers' heap never grows. The next call carries the heap's + /// recorded size, and the heap's calls that place a texture the offsets of the textures' + /// layout. + fn split_heap(&mut self, _heap: u64, _split: HeapSplit) {} /// Whether the backend makes every object with a recorded range at its recorded address (the /// `gpuAddress` it answered) and every other object outside the addresses a recording holds. @@ -342,10 +350,16 @@ pub struct Report { /// arguments for. pub pinned: Option, /// On a backend that makes objects at their recorded addresses, the heaps with a recorded - /// range the stream places no buffer in, which it made outside the recorded addresses - /// (`Backend::holds_no_buffer`). Their ranges keep their recorded addresses in the address - /// map. - pub heaps_outside: u64, + /// range whose textures it made in a heap outside the recorded addresses + /// (`Backend::split_heap`): those the stream places a texture in, or no buffer. A heap the + /// stream places no buffer in is that heap alone, and its range keeps its recorded address in + /// the address map. + pub textures_outside: u64, + /// On a backend that makes objects at their recorded addresses, the textures the stream + /// places in a heap with a recorded range whose recorded range met a buffer's live in that + /// heap, read ahead (`Overlaps`): memory they shared in the recording and no longer share. + /// Reported, not a stop. + pub textures_met: u64, /// The placement heaps the player laid out again for the runtime's sizes and alignments /// (`relay`). pub relaid: Relaid, @@ -729,9 +743,9 @@ impl Report { } if let Some(pinned) = self.pinned { lines.push(format!( - "pinned {pinned} of {pinned}; {} heaps without buffers outside: every other object \ - with a recorded range at its recorded address; the address map moves no word", - self.heaps_outside + "pinned {pinned} of {pinned}; {} heaps' textures outside; {} textures whose \ + recorded range (by the runtime's texture sizes) met a live buffer's", + self.textures_outside, self.textures_met )); } let relaid = self.relaid; @@ -832,75 +846,11 @@ struct Snapshot { ranges: Vec<(Around, u64)>, } -/// What a placement heap holds at each recorded offset: the largest size and alignment the -/// runtime answers for the resources placed there. -type Placements = BTreeMap; - -/// A placement heap's layout on the runtime: its size, and the offset the player places each -/// resource at by the offset the stream places it at. -struct Layout { - size: u64, - offsets: HashMap, -} - -/// The layout of a placement heap of `size` bytes, as a program asking the runtime's sizes and -/// alignments lays it out, whose resources the stream places at the offsets of `at`, each with the -/// most bytes and the largest alignment the runtime answers for its resources there. Each offset -/// keeps at least its distance from the one below, moves up until the resources below it end, and -/// rounds up to its alignment; the heap keeps at least its distance past the last offset and holds -/// the resources there. Resources at one offset still share it; resources at different offsets no -/// longer meet. Where every resource ends before the next offset and every offset is aligned, the -/// layout is the stream's. -fn relay(size: u64, at: &Placements) -> Layout { - let mut offsets = HashMap::with_capacity(at.len()); - let mut below: Option<(u64, u64, u64)> = None; - for (&recorded, &(bytes, align)) in at { - let floor = match below { - None => recorded, - Some((was, placed, held)) => (placed + (recorded - was)).max(placed + held), - }; - let placed = floor.next_multiple_of(align.max(1)); - offsets.insert(recorded, placed); - below = Some((recorded, placed, bytes)); - } - let size = match below { - None => size, - Some((was, placed, held)) => (placed + size.saturating_sub(was)).max(placed + held), - }; - Layout { size, offsets } -} - /// Whether `selector` makes a texture descriptor (`docs/REPLAY-STREAM.md`, section 9). fn makes_texture_descriptor(selector: &str) -> bool { selector == "m2v.textureDescriptor" || selector.starts_with("MTLTextureDescriptor.") } -/// The recorded size of the heap `call` (`newHeapWithDescriptor:`) makes, where it is a placement -/// heap (`MTLHeapTypePlacement`). -fn placement_heap(call: &Call) -> Option { - let entries = call.args.first()?.as_map()?; - let field = |key: &str| entries.iter().find(|(k, _)| &**k == key)?.1.as_uint(); - (field("heapType")? == 1).then_some(field("size")?) -} - -/// Whether `selector` places a buffer in its receiver where that is a heap: a placement heap's -/// `newBufferWithLength:options:offset:` or an automatic heap's `newBufferWithLength:options:`. -fn places_buffer(selector: &str) -> bool { - matches!( - selector, - "newBufferWithLength:options:offset:" | "newBufferWithLength:options:" - ) -} - -/// The argument of a placement heap's call that is the offset it places at. -fn placement_offset(selector: &str) -> Option { - match selector { - "newTextureWithDescriptor:offset:" => Some(1), - "newBufferWithLength:options:offset:" => Some(2), - _ => None, - } -} - /// Plays one stream on one backend. pub struct Player<'b, B: Backend> { backend: &'b mut B, @@ -922,10 +872,9 @@ pub struct Player<'b, B: Backend> { /// The live texture descriptors marked `outside` and the textures made of them: objects outside /// the program's IDs, whose `gpuResourceID` the program never saw (section 5). outside: HashSet, - /// On a backend that makes objects at their recorded addresses, the heaps with a recorded - /// range the stream places no buffer in, read ahead: each one's id and the position of the - /// call that makes it. - bufferless: HashSet<(u64, u64)>, + /// On a backend that makes objects at their recorded addresses, how it makes each heap with a + /// recorded range, read ahead, by the heap's id and the position of the call that makes it. + splits: HashMap<(u64, u64), HeapSplit>, /// The `m2v.privateBytes` records, read ahead, by the position of the dispatch each names. ahead: HashMap>, /// The placement heaps' layouts on the runtime, read ahead, by heap. @@ -1154,7 +1103,7 @@ impl<'b, B: Backend> Player<'b, B> { events: HashMap::new(), compared: HashSet::new(), outside: HashSet::new(), - bufferless: HashSet::new(), + splits: HashMap::new(), ahead: HashMap::new(), layouts: HashMap::new(), guest_device: None, @@ -1268,10 +1217,12 @@ impl<'b, B: Backend> Player<'b, B> { /// Index the `m2v.privateBytes` records by the dispatch each names, which comes before it, and /// the ID the program saw of each object by its making (`recorded_ids`), lay out each /// placement heap for the runtime's answers (`relay`), and, on a backend that makes objects - /// at their recorded addresses, find the heaps with a recorded range the stream places no - /// buffer in (`bufferless`). A stream error ends the reading: the play meets it where it lies, - /// as it meets a placement whose size the runtime does not answer. + /// at their recorded addresses, decide how it makes each heap with a recorded range + /// (`splits`) and count the textures whose recorded range met a live buffer's (`Overlaps`). + /// A stream error ends the reading: the play meets it where it lies, as it meets a placement + /// whose size the runtime does not answer. fn read_ahead(&mut self, stream: &StreamReader) -> Result<(), PlayError> { + let pins = self.report.pinned.is_some(); let mut ahead = stream.reopened()?; let mut position = 0; // The position of the call that made each object. @@ -1279,15 +1230,18 @@ impl<'b, B: Backend> Player<'b, B> { // Each live texture descriptor's calls: the one that made it, then its setters. let mut descriptors: HashMap> = HashMap::new(); // Each placement heap's recorded size and, by offset, the most bytes and the largest - // alignment the runtime answers for what the stream places there. - let mut heaps: HashMap = HashMap::new(); + // alignment the runtime answers for what the stream places there: all of it, and its + // textures alone. + let mut heaps: HashMap = HashMap::new(); // The objects made on each recorded device. let mut made_on: BTreeMap = BTreeMap::new(); - // Each heap making with a recorded range (its id and position), the position of each live - // one's by its id, and those the stream places a buffer in. + // Each heap making with a recorded range (its id and position) and its recorded size; the + // position and recorded address of each such heap by its id; and the makings the stream + // places a buffer in and a texture in. let mut heap_makings = Vec::new(); - let mut live_heaps: HashMap = HashMap::new(); - let mut with_buffer = HashSet::new(); + let mut live_heaps: HashMap = HashMap::new(); + let (mut with_buffer, mut with_texture) = (HashSet::new(), HashSet::new()); + let mut overlaps = Overlaps::default(); while let Ok(Some(call)) = ahead.next_call() { if &*call.selector == "MTLCreateSystemDefaultDevice" { made_on.entry(call.result).or_default(); @@ -1305,12 +1259,15 @@ impl<'b, B: Backend> Player<'b, B> { self.recorded_ids.entry((call.receiver, at)).or_insert(id); } } - if &*call.selector == "newHeapWithDescriptor:" && call.answer("gpuAddress").is_some() { - heap_makings.push((call.result, position)); - live_heaps.insert(call.result, position); - } else if places_buffer(&call.selector) { - if let Some(&at) = live_heaps.get(&call.receiver) { + let address = call.answer("gpuAddress").and_then(Value::as_address); + if let ("newHeapWithDescriptor:", Some(address)) = (&*call.selector, address) { + heap_makings.push(((call.result, position), heap_size(&call))); + live_heaps.insert(call.result, (position, address)); + } else if let Some(&(at, _)) = live_heaps.get(&call.receiver) { + if places_buffer(&call.selector) { with_buffer.insert((call.receiver, at)); + } else if places_texture(&call.selector) { + with_texture.insert((call.receiver, at)); } } match &*call.selector { @@ -1323,10 +1280,13 @@ impl<'b, B: Backend> Player<'b, B> { } self.ahead.entry(dispatch).or_default().push(around); } - "release" => drop(descriptors.remove(&call.receiver)), + "release" => { + descriptors.remove(&call.receiver); + overlaps.release(call.receiver); + } "newHeapWithDescriptor:" => { if let Some(size) = placement_heap(&call) { - heaps.insert(call.result, (size, BTreeMap::new())); + heaps.insert(call.result, (size, BTreeMap::new(), BTreeMap::new())); } } selector if call.result != 0 && makes_texture_descriptor(selector) => { @@ -1337,7 +1297,7 @@ impl<'b, B: Backend> Player<'b, B> { None => { let at = placement_offset(selector); let heap = heaps.get_mut(&call.receiver); - let (Some(at), Some((_, placed))) = (at, heap) else { + let (Some(at), Some((_, placed, textures))) = (at, heap) else { position += 1; continue; }; @@ -1346,9 +1306,29 @@ impl<'b, B: Backend> Player<'b, B> { let descriptor = descriptor.and_then(|d| descriptors.get(&d)); let descriptor = descriptor.map_or(&[][..], Vec::as_slice); let answer = self.backend.heap_size_and_align(&call, descriptor); - if let (Some(offset), Ok((bytes, align))) = (offset, answer) { + let answer = answer.ok(); + let texture = places_texture(selector); + if let (Some(offset), Some((bytes, align))) = (offset, answer) { let most = placed.entry(offset).or_default(); *most = (most.0.max(bytes), most.1.max(align)); + if texture { + let most = textures.entry(offset).or_default(); + *most = (most.0.max(bytes), most.1.max(align)); + } + } + let heap = live_heaps.get(&call.receiver).filter(|_| pins); + if let (Some(&(_, address)), Some(offset)) = (heap, offset) { + if texture { + let start = address + offset; + let bytes = answer.map_or(1, |(bytes, _)| bytes.max(1)); + overlaps.texture( + call.receiver, + call.result, + (start, start + bytes), + ); + } else if let Some(range) = recorded_range(&call) { + overlaps.buffer(call.receiver, call.result, range); + } } } }, @@ -1361,8 +1341,14 @@ impl<'b, B: Backend> Player<'b, B> { self.report.other_devices = (made_on.keys().copied()) .filter(|&device| self.guest_device.is_some_and(|guest| guest != device)) .collect(); - for (heap, (size, placed)) in heaps { - let layout = relay(size, &placed); + for (heap, (size, placed, textures)) in heaps { + // On a backend that makes objects at their recorded addresses, a heap with a recorded + // range keeps its buffers at their recorded offsets in its recorded size: only its + // textures are laid out again, in a heap of their own (`HeapSplit`). + let layout = match pins && live_heaps.contains_key(&heap) { + true => relay(size, &textures, true), + false => relay(size, &placed, false), + }; let moved = layout.offsets.iter().filter(|(was, now)| was != now); let moved = moved.count() as u64; if moved > 0 || layout.size != size { @@ -1372,18 +1358,31 @@ impl<'b, B: Backend> Player<'b, B> { self.layouts.insert(heap, layout); } } - if self.report.pinned.is_some() { - let bufferless = heap_makings.into_iter(); - self.bufferless = bufferless.filter(|m| !with_buffer.contains(m)).collect(); + if pins { + for (making, size) in heap_makings { + let Some(size) = size else { + continue; + }; + let buffers = with_buffer.contains(&making); + let laid = self.layouts.get(&making.0); + let outside = laid.map_or(size, |layout| layout.size); + let textures = (with_texture.contains(&making) || !buffers).then_some(outside); + self.splits.insert(making, HeapSplit { buffers, textures }); + } + self.report.textures_met = overlaps.met; } Ok(()) } /// `call` with the size of the placement heap it makes, or the offset it places at in one, as - /// the heap's layout on the runtime has it (`relay`). + /// the heap's layout on the runtime has it (`relay`). A layout of a heap's textures alone + /// (`Layout::textures_only`) moves only the offsets the stream places textures at: the heap + /// keeps its recorded size and its buffers their recorded offsets, and the backend makes the + /// textures' heap of the layout's size (`HeapSplit::textures`). fn placed(&self, mut call: Call) -> Call { if &*call.selector == "newHeapWithDescriptor:" { - let Some(layout) = self.layouts.get(&call.result) else { + let layout = self.layouts.get(&call.result); + let Some(layout) = layout.filter(|layout| !layout.textures_only) else { return call; }; if let Some(Value::Map(entries)) = call.args.first_mut() { @@ -1401,6 +1400,9 @@ impl<'b, B: Backend> Player<'b, B> { ) else { return call; }; + if layout.textures_only && !places_texture(&call.selector) { + return call; + } if let Some(offset) = call.args.get_mut(at) { let placed = offset.as_uint().and_then(|o| layout.offsets.get(&o)); if let Some(&placed) = placed { @@ -1684,9 +1686,10 @@ impl<'b, B: Backend> Player<'b, B> { if let Some(&id) = (self.recorded_ids).get(&(resolved.result, self.position)) { self.backend.recorded_id(resolved.result, id); } - let bufferless = self.bufferless.remove(&(resolved.result, self.position)); - if bufferless { - self.backend.holds_no_buffer(resolved.result); + let split = self.splits.remove(&(resolved.result, self.position)); + if let Some(split) = split { + self.report.textures_outside += u64::from(split.textures.is_some()); + self.backend.split_heap(resolved.result, split); } let made = self.run(&resolved)?; self.track(&resolved); @@ -1717,12 +1720,10 @@ impl<'b, B: Backend> Player<'b, B> { *pinned += 1; address } - // A heap without buffers, made outside the recorded addresses: no address the - // program holds lies in it, so its range keeps its recorded address in the map. - Some(_) if bufferless => { - self.report.heaps_outside += 1; - address - } + // A heap the stream places no buffer in, made outside the recorded addresses: no + // address the program holds lies in it, so its range keeps its recorded address + // in the map. + Some(_) if split.is_some_and(|split| !split.buffers) => address, Some(_) => { return Err(PlayError::Unpinned { object, diff --git a/crates/metal2vulkan-validation/src/replay/tests.rs b/crates/metal2vulkan-validation/src/replay/tests.rs index 0c87b83dc..7289193df 100644 --- a/crates/metal2vulkan-validation/src/replay/tests.rs +++ b/crates/metal2vulkan-validation/src/replay/tests.rs @@ -2,6 +2,7 @@ //! is asked (no device). The runtime backends' tests are device tests (`runtime_lane`). use super::addresses::AddressMap; +use super::heaps::HeapSplit; use super::new_runtime::indices::Indices; use super::new_runtime::places::Waiting; use super::new_runtime::second::merge; @@ -451,8 +452,8 @@ fn a_range_that_meets_a_live_one_in_part_ends_it() { /// A backend that keeps what it is asked: the calls, the waits, the bytes written, the objects /// whose resource IDs it gave. It places blocks and buffers apart from the recorded addresses, and /// a buffer in a block at its offset; where it `pins`, it makes heaps at their recorded addresses -/// (one it is told holds no buffer outside them) and a heap's buffer at the heap's address plus -/// its offset. It holds the bytes of the buffers made by length, which +/// (one it is told to split with no buffer outside them) and a heap's buffer at the heap's address +/// plus its offset. It holds the bytes of the buffers made by length, which /// writes and buffer copies change and a read gives; it runs no dispatch. It counts submissions, /// and buffer copies once there was one. #[derive(Default)] @@ -473,8 +474,9 @@ struct Kept { memory: HashMap>, copies: u64, /// The size and alignment it answers for a heap texture, by the id of its descriptor; a heap - /// buffer it answers its length at 256 bytes. + /// buffer it answers its length at `buffer_align` bytes (256 where that is 0). heap_answers: HashMap, + buffer_align: u64, /// Each heap size it was asked: the placing selector and how many calls made and set the /// texture descriptor. heap_asked: Vec<(String, usize)>, @@ -493,8 +495,8 @@ struct Kept { located: Vec<(u64, u64)>, /// Whether it makes objects at their recorded addresses (`Backend::places_at_recorded`). pins: bool, - /// The heaps it was told hold no buffer, in order. - no_buffer: Vec, + /// The heaps it was told how to split, in order. + splits: Vec<(u64, HeapSplit)>, } impl Backend for Kept { @@ -517,8 +519,8 @@ impl Backend for Kept { made.address = Some(self.bases[&block] + call.args[1].as_uint().unwrap()); } "newHeapWithDescriptor:" if self.pins => { - made.address = match self.no_buffer.last() { - Some(&heap) if heap == call.result => Some(1 << 47), + made.address = match self.splits.last() { + Some(&(heap, split)) if heap == call.result && !split.buffers => Some(1 << 47), _ => call.answer("gpuAddress").and_then(Value::as_address), }; } @@ -593,9 +595,13 @@ impl Backend for Kept { ) -> Result<(u64, u64), PlayError> { self.heap_asked .push((call.selector.to_string(), descriptor.len())); + let align = match self.buffer_align { + 0 => 256, + align => align, + }; Ok(match descriptor.first() { Some(made) => self.heap_answers[&made.result], - None => (call.args[0].as_uint().unwrap(), 256), + None => (call.args[0].as_uint().unwrap(), align), }) } @@ -639,8 +645,8 @@ impl Backend for Kept { self.pins } - fn holds_no_buffer(&mut self, heap: u64) { - self.no_buffer.push(heap); + fn split_heap(&mut self, heap: u64, split: HeapSplit) { + self.splits.push((heap, split)); } } @@ -664,33 +670,48 @@ fn addressed(address: u64, length: u64) -> [(&'static str, Value); 2] { ] } +/// A heap descriptor of `size` bytes and type `kind` (`MTLHeapType`). +fn heap_of(size: u64, kind: u64) -> [Value; 1] { + [map(&[ + ("size", Value::Uint(size)), + ("heapType", Value::Uint(kind)), + ("options", Value::List(Vec::new())), + ])] +} + +/// The `size` of the heap descriptor the backend was given for the call that made `heap`. +fn made_size(kept: &Kept, heap: u64) -> Option { + let descriptor = args_of(kept, heap)[0].as_map()?; + descriptor + .iter() + .find(|(key, _)| &**key == "size")? + .1 + .as_uint() +} + /// On a backend that makes objects at their recorded addresses, a heap the stream places only a -/// texture in is told it holds no buffer before its making, and is made outside them; its range -/// stays at its recorded address in the map, so a word into it is counted as an address and no -/// word moves. A heap the stream places a buffer in, and its buffer, are made at their recorded -/// addresses. The report counts each. +/// texture in is told before its making that it splits with no buffer: it is made outside them, at +/// the size its textures take on the runtime (here twice the heap's), while the call that makes it +/// carries its recorded size. Its range stays at its recorded address in the map, so a word into +/// it is counted as an address and no word moves. A heap the stream places only a buffer in, and +/// its buffer, are made at their recorded addresses. The report counts each. #[test] -fn a_heap_without_buffers_is_made_outside_the_recorded_addresses() { +fn a_heap_of_textures_alone_is_made_outside_the_recorded_addresses() { let mut kept = Kept { pins: true, ..Kept::default() }; - kept.heap_answers.insert(5, (0x4000, 0x4000)); - let heap = [map(&[ - ("size", Value::Uint(0x1_0000)), - ("heapType", Value::Uint(1)), - ("options", Value::List(Vec::new())), - ])]; + kept.heap_answers.insert(5, (0x2_0000, 0x4000)); let (with_buffer, textures_only) = (BLOCK, BLOCK + 0x2_0000); let (report, ended) = played(&mut kept, |w| { w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; let made = addressed(with_buffer, 0x1_0000); - w.call("newHeapWithDescriptor:", 1, 2, &heap, &made)?; + w.call("newHeapWithDescriptor:", 1, 2, &heap_of(0x1_0000, 1), &made)?; let buffer = [Value::Uint(0x100), Value::Uint(0), Value::Uint(0x8000)]; let made = addressed(with_buffer + 0x8000, 0x100); w.call("newBufferWithLength:options:offset:", 2, 3, &buffer, &made)?; let made = addressed(textures_only, 0x1_0000); - w.call("newHeapWithDescriptor:", 1, 4, &heap, &made)?; + w.call("newHeapWithDescriptor:", 1, 4, &heap_of(0x1_0000, 1), &made)?; w.call("m2v.textureDescriptor", 0, 5, &[map(&[])], &[])?; let texture = [Value::Object(5), Value::Uint(0)]; w.call("newTextureWithDescriptor:offset:", 4, 6, &texture, &[])?; @@ -704,16 +725,182 @@ fn a_heap_without_buffers_is_made_outside_the_recorded_addresses() { ) }); ended.unwrap(); - assert_eq!(kept.no_buffer, [4]); - assert_eq!((report.pinned, report.heaps_outside), (Some(2), 1)); + let buffers = HeapSplit { + buffers: true, + textures: None, + }; + let textures = HeapSplit { + buffers: false, + textures: Some(0x2_0000), + }; + assert_eq!(kept.splits, [(2, buffers), (4, textures)]); + assert_eq!(made_size(&kept, 4), Some(0x1_0000), "the recorded size"); + assert_eq!((report.pinned, report.textures_outside), (Some(2), 1)); assert_eq!(report.total.stream["address_looking_words"], 1); assert_eq!(report.total.stream["relocated_words"], 0); - let line = - "pinned 2 of 2; 1 heaps without buffers outside: every other object with a recorded \ - range at its recorded address; the address map moves no word"; + let line = "pinned 2 of 2; 1 heaps' textures outside; 0 textures whose recorded range \ + (by the runtime's texture sizes) met a live buffer's"; assert!(report.lines().contains(&line.to_owned()), "{report:?}"); } +/// On a backend that makes objects at their recorded addresses, a heap the stream places only +/// buffers in is made at its recorded address and of its recorded size, each buffer at its +/// recorded offset, though the runtime's alignment (here 64 KiB) would move the second up and grow +/// the heap where it is laid out again: a pinned span never grows, and no heap goes outside. +#[test] +fn a_heap_of_buffers_alone_keeps_its_recorded_layout() { + let mut kept = Kept { + pins: true, + buffer_align: 0x1_0000, + ..Kept::default() + }; + let (report, ended) = played(&mut kept, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + let made = addressed(BLOCK, 0x2_0000); + w.call("newHeapWithDescriptor:", 1, 2, &heap_of(0x2_0000, 1), &made)?; + for (buffer, offset) in [(3, 0), (4, 0x8000)] { + let args = [Value::Uint(0x100), Value::Uint(0), Value::Uint(offset)]; + let made = addressed(BLOCK + offset, 0x100); + w.call( + "newBufferWithLength:options:offset:", + 2, + buffer, + &args, + &made, + )?; + } + Ok(()) + }); + ended.unwrap(); + let split = HeapSplit { + buffers: true, + textures: None, + }; + assert_eq!(kept.splits, [(2, split)]); + assert_eq!(made_size(&kept, 2), Some(0x2_0000), "the recorded size"); + assert_eq!( + args_of(&kept, 4)[2].as_uint(), + Some(0x8000), + "the recorded offset" + ); + assert_eq!(report.relaid, Relaid::default()); + let line = "pinned 3 of 3; 0 heaps' textures outside; 0 textures whose recorded range \ + (by the runtime's texture sizes) met a live buffer's"; + assert!(report.lines().contains(&line.to_owned()), "{report:?}"); +} + +/// On a backend that makes objects at their recorded addresses, a heap the stream places buffers +/// and textures in is made as two: its buffers in a heap at its recorded address and of its +/// recorded size, each at its recorded offset; its textures in one outside the recorded +/// addresses, laid out alone for the runtime's sizes, where a texture larger than the room the +/// stream left it moves the next texture up past it and no buffer. The texture whose recorded +/// range met a live buffer's is counted; one placed there once that buffer was released is not. +#[test] +fn a_heap_of_buffers_and_textures_is_made_as_two() { + let mut kept = Kept { + pins: true, + ..Kept::default() + }; + kept.heap_answers.insert(3, (0x1_8000, 0x4000)); + kept.heap_answers.insert(6, (0x4000, 0x4000)); + let (report, ended) = played(&mut kept, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + let made = addressed(BLOCK, 0x1_0000); + w.call("newHeapWithDescriptor:", 1, 2, &heap_of(0x1_0000, 1), &made)?; + w.call("m2v.textureDescriptor", 0, 3, &[map(&[])], &[])?; + let texture = [Value::Object(3), Value::Uint(0)]; + w.call("newTextureWithDescriptor:offset:", 2, 4, &texture, &[])?; + let buffer = [Value::Uint(0x100), Value::Uint(0), Value::Uint(0x8000)]; + let made = addressed(BLOCK + 0x8000, 0x100); + w.call("newBufferWithLength:options:offset:", 2, 5, &buffer, &made)?; + w.call("release", 5, 0, &[], &[])?; + w.call("m2v.textureDescriptor", 0, 6, &[map(&[])], &[])?; + let texture = [Value::Object(6), Value::Uint(0x8000)]; + w.call("newTextureWithDescriptor:offset:", 2, 7, &texture, &[]) + }); + ended.unwrap(); + let split = HeapSplit { + buffers: true, + textures: Some(0x2_0000), + }; + assert_eq!(kept.splits, [(2, split)]); + assert_eq!(made_size(&kept, 2), Some(0x1_0000), "the recorded size"); + assert_eq!( + args_of(&kept, 5)[2].as_uint(), + Some(0x8000), + "the recorded offset" + ); + assert_eq!( + args_of(&kept, 7)[1].as_uint(), + Some(0x1_8000), + "past the larger texture" + ); + let relaid = Relaid { + heaps: 1, + moved: 1, + grown: 0x1_0000, + }; + assert_eq!(report.relaid, relaid); + assert_eq!((report.textures_outside, report.textures_met), (1, 1)); + let line = "pinned 2 of 2; 1 heaps' textures outside; 1 textures whose recorded range \ + (by the runtime's texture sizes) met a live buffer's"; + assert!(report.lines().contains(&line.to_owned()), "{report:?}"); +} + +/// The split follows what the stream places in a heap, whatever the heap's type: of three +/// automatic heaps (`MTLHeapTypeAutomatic`, whose resources take no offset and are not laid out +/// again), the one with a buffer and a texture splits in two, its textures' heap of the recorded +/// size; the one with a texture alone is made outside the recorded addresses; the one with a +/// buffer alone at them. +#[test] +fn a_heap_splits_by_what_the_stream_places_whatever_its_type() { + let mut kept = Kept { + pins: true, + ..Kept::default() + }; + let (report, ended) = played(&mut kept, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + w.call("m2v.textureDescriptor", 0, 2, &[map(&[])], &[])?; + let (buffer, texture) = ([Value::Uint(0x100), Value::Uint(0)], [Value::Object(2)]); + let made = |at: u64| addressed(BLOCK + (at << 20), 0x1_0000); + w.call( + "newHeapWithDescriptor:", + 1, + 3, + &heap_of(0x1_0000, 0), + &made(0), + )?; + w.call("newBufferWithLength:options:", 3, 4, &buffer, &[])?; + w.call("newTextureWithDescriptor:", 3, 5, &texture, &[])?; + w.call( + "newHeapWithDescriptor:", + 1, + 6, + &heap_of(0x1_0000, 0), + &made(1), + )?; + w.call("newTextureWithDescriptor:", 6, 7, &texture, &[])?; + w.call( + "newHeapWithDescriptor:", + 1, + 8, + &heap_of(0x1_0000, 0), + &made(2), + )?; + w.call("newBufferWithLength:options:", 8, 9, &buffer, &[]) + }); + ended.unwrap(); + let split = |buffers, textures| HeapSplit { buffers, textures }; + let splits = [ + (3, split(true, Some(0x1_0000))), + (6, split(false, Some(0x1_0000))), + (8, split(true, None)), + ]; + assert_eq!(kept.splits, splits); + assert_eq!((report.pinned, report.textures_outside), (Some(2), 2)); + assert_eq!(report.relaid, Relaid::default()); +} + /// A buffer whose recorded range meets a live buffer's in part, as a guest's allocator reuses /// block memory before the older buffer's release, ends the older range; the report counts it. #[test] @@ -2243,6 +2430,10 @@ fn placement_heaps_take_the_runtimes_sizes_and_alignments() { assert_eq!((offset(4, 1), offset(6, 1)), (Some(0), Some(0))); assert_eq!(offset(5, 2), Some(0xC000), "past the larger texture"); assert_eq!(size(7), Some(0x1_0000), "every answer fits"); + assert!( + kept.splits.is_empty(), + "a split is told only where the backend pins" + ); assert_eq!((offset(10, 1), offset(11, 2)), (Some(0), Some(0x8000))); let asked = |selector: &str, calls| (selector.to_owned(), calls); let texture = "newTextureWithDescriptor:offset:"; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs b/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs index ad89c904a..53801befa 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs @@ -12,7 +12,9 @@ //! the object, with no other placement tried. //! - A heap the stream places no buffer in is made outside the recorded addresses: grown for a //! texture the runtime makes larger than the heap, it leaves the buffer pinned past its recorded -//! span that address. +//! span that address. One it places a buffer in too is made as two: its buffers in a heap at its +//! recorded address and size, its textures in a grown one outside, so both buffers keep their +//! addresses. //! - A command buffer waiting on an event the CPU signals later does not stop another queue's. //! - Textures made from descriptor records read back as written. //! - A render pass its setter records describe clears a drawable the stream never saw made. @@ -313,8 +315,8 @@ fn a_data_word_in_a_live_range_plays_as_written() { assert_eq!(report.total.stream["address_looking_words"], 2); assert_eq!(report.total.stream["relocated_words"], 0); assert_eq!(report.pinned, Some(2)); - let line = "pinned 2 of 2; 0 heaps without buffers outside: every other object with a \ - recorded range at its recorded address; the address map moves no word"; + let line = "pinned 2 of 2; 0 heaps' textures outside; 0 textures whose recorded range \ + (by the runtime's texture sizes) met a live buffer's"; assert!(report.lines().contains(&line.to_string()), "{report:?}"); }); } @@ -344,6 +346,29 @@ fn a_recorded_address_the_runtime_refuses_stops_the_play() { }); } +/// Heap #2: 64 KiB, Private, pinned at `heap`, the stream placing at its start texture #4, 256 by +/// 256 RGBA8Unorm (256 KiB, larger than the heap), of descriptor #3. +fn heap_with_a_texture(w: &mut StreamWriter, heap: u64) -> std::io::Result<()> { + let descriptor = Value::Map(vec![ + ("size".into(), Value::Uint(64 << 10)), + ("heapType".into(), Value::Uint(1)), + ("options".into(), Value::List(Vec::new())), + ("pinnedGpuAddress".into(), Value::Address(heap)), + ]); + let made = addressed(heap, 64 << 10); + w.call("newHeapWithDescriptor:", 1, 2, &[descriptor], &made)?; + // RGBA8Unorm, 256 by 256, not mipmapped, Private as the heap is. + let two_d = [70, 256, 256].map(Value::Uint); + let two_d = [&two_d[..], &[Value::Bool(false)]].concat(); + let selector = "MTLTextureDescriptor.texture2DDescriptorWithPixelFormat:width:height:\ + mipmapped:"; + w.call(selector, 0, 3, &two_d, &[])?; + w.call("setUsage:", 3, 0, &[Value::Uint(1)], &[])?; + w.call("setResourceOptions:", 3, 0, &[Value::Uint(2 << 4)], &[])?; + let texture = [Value::Object(3), Value::Uint(0)]; + w.call("newTextureWithDescriptor:offset:", 2, 4, &texture, &[]) +} + /// A 64-KiB heap pinned at its recorded address, the stream placing only a 256-KiB texture in it, /// and a buffer pinned at the first granule past the heap's recorded span (its four pages and a /// guard page, rounded up to 96 KiB): the player grows the heap for the texture, and since the @@ -355,32 +380,46 @@ fn a_heap_without_buffers_leaves_the_next_pin_its_address() { let (heap, after) = (BLOCK, BLOCK + (96 << 10)); let path = written(&dir, |w| { w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; - let descriptor = Value::Map(vec![ - ("size".into(), Value::Uint(64 << 10)), - ("heapType".into(), Value::Uint(1)), - ("options".into(), Value::List(Vec::new())), - ("pinnedGpuAddress".into(), Value::Address(heap)), - ]); - let made = addressed(heap, 64 << 10); - w.call("newHeapWithDescriptor:", 1, 2, &[descriptor], &made)?; - // RGBA8Unorm, 256 by 256, not mipmapped, Private as the heap is. - let two_d = [70, 256, 256].map(Value::Uint); - let two_d = [&two_d[..], &[Value::Bool(false)]].concat(); - let selector = "MTLTextureDescriptor.texture2DDescriptorWithPixelFormat:width:height:\ - mipmapped:"; - w.call(selector, 0, 3, &two_d, &[])?; - w.call("setUsage:", 3, 0, &[Value::Uint(1)], &[])?; - w.call("setResourceOptions:", 3, 0, &[Value::Uint(2 << 4)], &[])?; - let texture = [Value::Object(3), Value::Uint(0)]; - w.call("newTextureWithDescriptor:offset:", 2, 4, &texture, &[])?; + heap_with_a_texture(w, heap)?; pinned_buffer(w, 5, after, 0x100) }); on_device_with(at_plan, |device| { let report = play("heap-without-buffers", device, &path); assert!(report.relaid.grown >= 192 << 10, "{:?}", report.relaid); - assert_eq!((report.pinned, report.heaps_outside), (Some(1), 1)); - let line = "pinned 1 of 1; 1 heaps without buffers outside: every other object with a \ - recorded range at its recorded address; the address map moves no word"; + assert_eq!((report.pinned, report.textures_outside), (Some(1), 1)); + let line = "pinned 1 of 1; 1 heaps' textures outside; 0 textures whose recorded range \ + (by the runtime's texture sizes) met a live buffer's"; + assert!(report.lines().contains(&line.to_string()), "{report:?}"); + }); +} + +/// The same heap and texture, the stream placing also a buffer 32 KiB into the heap (the texture's +/// range meets it), and the same buffer pinned past the heap's recorded span: the player makes +/// the heap's buffers in a heap at its recorded address and size, so the buffer in it keeps its +/// recorded address, and its textures in one outside the recorded addresses, grown for the +/// texture, so the buffer past the span keeps its own. Laid out as one heap at its recorded +/// address, the heap would move its buffer past the texture, and grown, its span would hold the +/// next buffer's. +#[test] +fn a_heap_of_buffers_and_textures_leaves_every_pin_its_address() { + let dir = ScratchDir::new("replay-heap-split").unwrap(); + let (heap, after) = (BLOCK, BLOCK + (96 << 10)); + let path = written(&dir, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + heap_with_a_texture(w, heap)?; + // 256 bytes, Private as the heap is, 32 KiB in. + let buffer = [0x100, 2 << 4, 32 << 10].map(Value::Uint); + let made = addressed(heap + (32 << 10), 0x100); + w.call("newBufferWithLength:options:offset:", 2, 5, &buffer, &made)?; + pinned_buffer(w, 6, after, 0x100) + }); + on_device_with(at_plan, |device| { + let report = play("heap-split", device, &path); + assert!(report.relaid.grown >= 192 << 10, "{:?}", report.relaid); + let counts = (report.textures_outside, report.textures_met); + assert_eq!((report.pinned, counts), (Some(3), (1, 1))); + let line = "pinned 3 of 3; 1 heaps' textures outside; 1 textures whose recorded range \ + (by the runtime's texture sizes) met a live buffer's"; assert!(report.lines().contains(&line.to_string()), "{report:?}"); }); } diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index be6d87574..341db263e 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -182,19 +182,35 @@ and the (name id, value) answer pairs. - **Recorded addresses on the old runtime.** The old runtime's player makes every object that answered a `gpuAddress` at that address (`AddressPlacement::At`): a buffer, a block or a heap at its own answer, the descriptor's `pinnedGpuAddress` aside; a buffer in a heap lands at the - heap's address plus its offset. A heap the stream places no buffer in (read ahead: no - `newBufferWithLength:options:offset:` or `newBufferWithLength:options:` of it) is the exception: - a texture has no address and a heap answers none, so no address the program holds lies in it. - It goes outside the space whatever size the player lays it out at (section 10), and its range - keeps its recorded address in the address map. Every other object, and the player's own - buffers (its staging, readback and host copies), goes outside the space a pin can take - (`AddressPlacement::Outside`, `[2^47, 2^48)`; a pin's span ends at or below 2^47). A recorded - address the runtime refuses (its span meets a live pin's, its first page starts no 32-KiB - granule, or it leaves the space), or an object the runtime made at another address than it - recorded, stops the play, naming the object and its recorded address (`PlayError::Unpinned`); - no other placement is tried. Each range's address in the play is then its recorded one, so no - address argument moves (below). The report says how many objects it pinned and how many heaps - without buffers it made outside the space (section 10). + heap's address plus its offset. A heap with a recorded range plays as its buffers and its + textures apart, decided by what the stream places in it (read ahead), whatever the heap's type: + - its buffers (`newBufferWithLength:options:offset:` or `newBufferWithLength:options:` of it) + go in a heap at its recorded address and of its recorded size, each at its recorded offset, + never laid out again: a pinned span never grows; + - its textures (`newTextureWithDescriptor:offset:` or `newTextureWithDescriptor:` of it) go in + a heap outside the space, laid out for the runtime's sizes (section 10). A texture has no + address and a heap answers none, so no address the program holds lies in it. It is one heap, + so textures the stream placed at one offset still share memory. + + A heap the stream places only buffers in is the first heap alone; one it places no buffer in is + the second alone, and its range keeps its recorded address in the address map; one it places + both in is both. A texture and a buffer that shared memory in the recording no longer share it. + The report counts such textures: those whose range in the recording (the heap's recorded + address plus the texture's offset, for the bytes the runtime answers for its descriptor, as the + stream holds no texture's size) met the recorded range of a buffer live in the same heap. A + count above 0 is reported, and the play goes on. Every heap the streams recorded so far hold is + a placement heap; the rule for an automatic one is held by the player's unit test alone. A heap + without a recorded range goes outside the space whole, laid out as on any runtime. Every other + object, and the player's own buffers (its staging, readback and host copies), goes outside the + space a pin can take (`AddressPlacement::Outside`, `[2^47, 2^48)`; a pin's span ends at or + below 2^47). A recorded address the runtime refuses (its span meets a live pin's, its first page + starts no 32-KiB granule, or it leaves the space), a buffer the runtime will not place at its + recorded offset in its heap's recorded span, or an object the runtime made at another address + than it recorded, stops the play, naming the object and its recorded address + (`PlayError::Unpinned`); no other placement is tried. Each range's address in the play is then + its recorded one, so no address argument moves (below). The report says how many objects it + pinned, how many heaps' textures it made outside the space and how many textures met a live + buffer (section 10). - **Address arguments move.** On the new runtime the player makes each object where the runtime has room. Every address value (tag 8) whose value lies in a live range becomes the player's address of that range's object plus its offset into the range; the innermost range wins, so an @@ -417,7 +433,8 @@ and the (name id, value) answer pairs. - `newBufferWithDescriptor:`: `{length, options, pinnedGpuAddress, contents, noCopy, deallocator, zeroFrom}`. - `newHeapWithDescriptor:`: `{size, heapType, options, pinnedGpuAddress}`. The old runtime's - player makes the heap at its pin only where the stream places a buffer in it (section 5). + player makes the heap's buffers in a heap at its pin and its textures in a heap outside the + pinned space (section 5). - `newSamplerStateWithDescriptor:`: `{minFilter, magFilter, lodAverage, compareFunction, sAddressMode, tAddressMode, rAddressMode, mipFilter, maxAnisotropy, normalizedCoordinates, supportArgumentBuffers, reductionMode, lodMinClamp, lodMaxClamp, lodBias, borderColor, @@ -591,9 +608,10 @@ counted from 0), completes the work committed so far, reports as at the stream's stream's did, on every runtime. Where every resource ends before the next offset and every offset is aligned, the layout is the stream's. A placement whose size the runtime does not answer keeps its offset, and the play meets the runtime's refusal where it lies. On the old runtime a heap - grown past its recorded span holds pages the recording gave the objects after it: a heap the - stream places no buffer in goes outside the space (section 5); one it places a buffer in keeps - its recorded address, and where its span then meets another pin, the play stops there. + grown past its recorded span would hold pages the recording gave the objects after it, so a heap + with a recorded range is laid out by its textures alone, which go in a heap of their own outside + the space, while its buffers keep their recorded offsets in a heap of its recorded size at its + recorded address (section 5). - It reports, for each group of command buffers it waited for (normally the one just committed), for each frame and in total, two sets of counts: - **Fixed by the stream** (`stream`), the same on every play of the stream on any runtime: the @@ -770,10 +788,13 @@ recording's high word, which is the recording runtime's own; `private ID DISPATC encoders around them (`N` the encoders split, `COUNTS` the executed counts of their groups), `unsnapshotted N` where the backend took none of them (`N` the dispatches played as they are), `parted N` where a recorded range met a live one in part (`N` the older ranges ended), -`pinned N of N; K heaps without buffers outside: every other object with a recorded range at its -recorded address; the address map moves no word` on the old runtime (`N` the objects made at their -recorded addresses, `K` the heaps the stream places no buffer in, made outside the space; section -5), +`pinned N of N; K heaps' textures outside; S textures whose recorded range (by the runtime's +texture sizes) met a live buffer's` on the old runtime (`N` the objects made at their recorded +addresses, every other object with a recorded range there too, so the address map moves no word; +`K` the heaps with a recorded range whose textures it made in a heap outside the space, those the +stream places a texture or no buffer in; `S` the textures whose range in the recording, by the +runtime's size for each, met the recorded range of a buffer live in the same heap, read ahead and +not a stop; section 5), `relaid HEAPS moved OFFSETS grown BYTES` where it laid placement heaps out again (the heaps, the offsets it moved in them and the bytes it added to their sizes), `texture_writes ...` (the CPU's writes into Managed textures, below), `total COUNTS` (its `calls` the