diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/indices.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/indices.rs new file mode 100644 index 000000000..bc3fde404 --- /dev/null +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/indices.rs @@ -0,0 +1,158 @@ +//! The indices the new runtime's backend gives textures and sampler states, which the runtime +//! leaves to its consumer: the index the stream names for the object where the runtime takes it +//! (a descriptor's or a view's resource index, else the ID the program saw of the object), else +//! the lowest index of the object's class that no object holds and the program did not reserve, +//! as Metal's pool hands out a sampler state's ID. + +use metal2vulkan_rt as rt; +use std::collections::{BTreeSet, HashMap}; + +/// The slot of `class`: textures, storage-capable textures, samplers (and any class the runtime +/// adds, which the backend asks for no index of). +fn slot(class: rt::IndexClass) -> usize { + match class { + rt::IndexClass::Texture => 0, + rt::IndexClass::StorageTexture => 1, + _ => 2, + } +} + +#[derive(Default)] +pub(in crate::replay) struct Indices { + /// The indices of each class an object of the play holds, a constexpr sampler's for good. + held: [BTreeSet; 3], + /// The indices of each class the program reserved. + reserved: [BTreeSet; 3], + /// The class slot and index each live object holds. + objects: HashMap, + /// The objects placed at the index the stream named. + named: u64, + /// The objects the stream named an index for that the runtime refused (an object lives + /// there, or it is outside the object's class): placed at the lowest free index instead. + refused: u64, +} + +impl Indices { + /// `index` of `class` reserved by the program (`reserveResourceIndicesForResourceType:...`): + /// no object takes it but where the stream names it. + pub(in crate::replay) fn reserve(&mut self, class: rt::IndexClass, index: u32) { + if class.range().contains(&index) { + self.reserved[slot(class)].insert(index); + } + } + + /// `index` of `class` held by `object` until [`give`](Self::give), or for good where + /// `object` is `None` (a constexpr sampler). + pub(in crate::replay) fn hold( + &mut self, + object: Option, + class: rt::IndexClass, + index: u32, + ) { + self.held[slot(class)].insert(index); + if let Some(object) = object { + self.objects.insert(object, (slot(class), index)); + } + } + + /// The index `object` held, free again. + pub(in crate::replay) fn give(&mut self, object: u64) { + if let Some((slot, index)) = self.objects.remove(&object) { + self.held[slot].remove(&index); + } + } + + /// The lowest index of `class` from `from` that no object holds, the program did not reserve + /// and `skip` does not name. + pub(in crate::replay) fn lowest( + &self, + class: rt::IndexClass, + from: u32, + skip: impl Fn(u32) -> bool, + ) -> Option { + let (held, reserved) = (&self.held[slot(class)], &self.reserved[slot(class)]); + let range = class.range(); + (from.max(range.start)..range.end) + .find(|index| !held.contains(index) && !reserved.contains(index) && !skip(*index)) + } + + /// `make` at `named` where the stream names an index and the runtime takes it, else at the + /// lowest free index of `class`, an index the runtime finds in use passed over (an object the + /// stream released that work in flight still holds); what `object` then holds. None where + /// every index of the class is in use. + pub(in crate::replay) fn place( + &mut self, + object: u64, + class: rt::IndexClass, + named: Option, + make: impl Fn(u32) -> Result, + ) -> Option> { + if let Some(index) = named { + match make(index) { + Err(rt::Error::Refused( + rt::Refusal::IndexInUse { .. } | rt::Refusal::IndicesNotGranted { .. }, + )) => self.refused += 1, + made => { + if made.is_ok() { + self.named += 1; + self.hold(Some(object), class, index); + } + return Some(made); + } + } + } + let mut from = 0; + while let Some(index) = self.lowest(class, from, |_| false) { + match make(index) { + Err(rt::Error::Refused(rt::Refusal::IndexInUse { .. })) => from = index + 1, + made => { + if made.is_ok() { + self.hold(Some(object), class, index); + } + return Some(made); + } + } + } + None + } + + /// `make` at the highest index of `class` that no object holds and the program did not + /// reserve, an index the runtime finds in use passed over: one away from the lowest indices, + /// which the program's own objects take; what `object` then holds. None where every index of + /// the class is in use. + pub(in crate::replay) fn top( + &mut self, + object: u64, + class: rt::IndexClass, + make: impl Fn(u32) -> Result, + ) -> Option> { + let range = class.range(); + let mut below = range.end; + loop { + let (held, reserved) = (&self.held[slot(class)], &self.reserved[slot(class)]); + let index = (range.start..below) + .rev() + .find(|index| !held.contains(index) && !reserved.contains(index))?; + match make(index) { + Err(rt::Error::Refused(rt::Refusal::IndexInUse { .. })) => below = index, + made => { + if made.is_ok() { + self.hold(Some(object), class, index); + } + return Some(made); + } + } + } + } + + /// The report's line: the objects placed at the index the stream named, those whose named + /// index the runtime refused, and the indices the program reserved. + pub(in crate::replay) fn line(&self) -> String { + let reserved: usize = self.reserved.iter().map(BTreeSet::len).sum(); + format!( + "indices named {}: objects placed at the index the stream named; {} whose named index \ + the runtime refused, placed at the lowest free one; {reserved} reserved", + self.named, self.refused + ) + } +} diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index a756acbab..a0f6d6427 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -10,6 +10,7 @@ //! is refused. mod encoders; +pub(super) mod indices; pub(super) mod places; mod render; pub(super) mod second; @@ -198,10 +199,17 @@ pub struct NewRuntime { device: rt::Device, objects: HashMap, places: Places, - /// The last index taken of each class: textures, storage-capable textures, samplers. - last: [u32; 3], + /// The indices textures and sampler states hold and the program reserved. + indices: indices::Indices, + /// The index the call being played names for the object it makes (a resource index). + named: Option, + /// The object the next call makes and the ID the program saw of it, where it saw one + /// (`Backend::recorded_id`). + recorded: Option<(u64, u64)>, + /// Each live texture descriptor's resource index, where its record sets one. + resource_indices: HashMap, /// The texture descriptors the stream marks `outside` (section 5 of docs/REPLAY-STREAM.md): - /// a texture of one takes an index outside the sequence of `last`. + /// a texture of one takes an index outside those the program's objects take. outside: HashSet, /// Each constexpr sampler's index, by its state words. constexprs: HashMap<[u64; 2], u32>, @@ -331,8 +339,8 @@ const TEXTURE_KEYS: [&str; 20] = [ "outside", ]; -/// `f`'s properties set on `d`. The resource index is the guest's, which the player relocates -/// the IDs of; the GPU-optimized contents are a hint. +/// `f`'s properties set on `d`. The resource index places the texture (`named_index`); the +/// GPU-optimized contents are a hint. fn texture_fields(call: &Call, f: &Fields, d: &mut rt::TextureDescriptor) -> Result<(), PlayError> { if let Some(kind) = f.metal("textureType")? { d.texture_type = kind; @@ -408,6 +416,30 @@ fn made_texture_descriptor(call: &Call) -> Result Result, PlayError> { + match &*call.selector { + "m2v.textureDescriptor" => resource_index_of(call, &Fields::arg(call, 0, &TEXTURE_KEYS)?), + _ => Ok(None), + } +} + +/// The index of a texture descriptor's `resourceIndex` (`[index, forced]`): Metal places the +/// texture there whether or not it is forced. +fn resource_index_of(call: &Call, f: &Fields) -> Result, PlayError> { + let Some(list) = f.list("resourceIndex")? else { + return Ok(None); + }; + match list { + [index, Value::Bool(_)] => match index.as_uint().map(u32::try_from) { + Some(Ok(index)) => Ok(Some(index)), + _ => Err(refuse(call, format!("resource index {index}"))), + }, + _ => Err(refuse(call, "a resource index that is no [index, forced]")), + } +} + /// Texture descriptor `d` changed by `call`, one of its setters. fn set_texture_descriptor(call: &Call, d: &mut rt::TextureDescriptor) -> Result<(), PlayError> { let raw = uint(call, 0)?; @@ -457,7 +489,10 @@ impl NewRuntime { places: Places::new(device.clone()), device, objects: HashMap::new(), - last: [0; 3], + indices: indices::Indices::default(), + named: None, + recorded: None, + resource_indices: HashMap::new(), outside: HashSet::new(), constexprs: HashMap::new(), commits: 0, @@ -609,35 +644,34 @@ impl NewRuntime { self.completed } - /// `make` at the next index of `class` that no live object holds. + /// `make` at the index the stream names for the object `call` makes (`indices`): the call's + /// resource index (`named`), else the ID the program saw of the object (`recorded`); else at + /// the lowest free index of `class`. fn place( &mut self, call: &Call, class: rt::IndexClass, make: impl Fn(u32) -> Result, ) -> Result { - let slot = match class { - rt::IndexClass::Texture => 0, - rt::IndexClass::StorageTexture => 1, - _ => 2, - }; - let constexprs = &self.constexprs; - let skip = - |index| class == rt::IndexClass::Sampler && constexprs.values().any(|&i| i == index); - match next_index(&mut self.last[slot], class.range(), skip, make) { + let recorded = (self.recorded).filter(|&(object, _)| object == call.result); + // The ID's low half is its index (docs/RESOURCE-ID.md). + let recorded = recorded.map(|(_, id)| id as u32); + let named = self.named.or(recorded); + match self.indices.place(call.result, class, named, make) { Some(made) => made.map_err(failed(call)), None => Err(refuse(call, format!("every {class:?} index is in use"))), } } - /// `make` at the highest index of `class` that no live object holds ([`top_index`]). + /// `make` at the highest index of `class` that no object holds and the program did not + /// reserve (`Indices::top`): outside the indices the program's own objects take. fn place_outside( &mut self, call: &Call, class: rt::IndexClass, make: impl Fn(u32) -> Result, ) -> Result { - match top_index(class.range(), make) { + match self.indices.top(call.result, class, make) { Some(made) => made.map_err(failed(call)), None => Err(refuse(call, format!("every {class:?} index is in use"))), } @@ -734,6 +768,31 @@ impl NewRuntime { } } + /// The index `call` names for the texture it makes: its descriptor's resource index, or a + /// view's `resourceIndex:`. + fn named_index(&self, call: &Call) -> Result, PlayError> { + let at = match &*call.selector { + "newTextureWithDescriptor:" + | "newTextureWithDescriptor:offset:" + | "newTextureWithDescriptor:offset:bytesPerRow:" => { + return match arg(call, 0)? { + Value::Object(id) => Ok(self.resource_indices.get(id).copied()), + map @ Value::Map(_) => { + resource_index_of(call, &Fields::of(call, map, &TEXTURE_KEYS)?) + } + _ => Ok(None), + }; + } + "newTextureViewWithPixelFormat:resourceIndex:" => 1, + "newTextureViewWithPixelFormat:textureType:levels:slices:resourceIndex:" => 4, + _ => return Ok(None), + }; + let index = u32::try_from(uint(call, at)?); + index + .map(Some) + .map_err(|_| refuse(call, format!("resource index past u32 at {at}"))) + } + /// The function `call`'s library makes. fn library_call(&self, call: &Call, library: &rt::Library) -> Result { let name = arg(call, 0)?.as_str(); @@ -820,52 +879,56 @@ impl NewRuntime { descriptor: &rt::ComputePipelineDescriptor, ) -> Result { self.numbered(|device, ids| { - device.new_compute_pipeline_state(descriptor, |samplers| Ok(ids(samplers))) + device.new_compute_pipeline_state(descriptor, |samplers| ids(samplers)) }) .map_err(failed(call)) } /// The pipeline state `make` makes on the device with `ids`, which gives each numbered - /// constexpr sampler an index of its own, the same words one index. + /// constexpr sampler an index of its own, the lowest free one, the same words one index. fn numbered( &mut self, make: impl FnOnce( &rt::Device, - &mut dyn FnMut(&[rt::NumberedSampler]) -> Vec, + &mut dyn FnMut(&[rt::NumberedSampler]) -> Result, rt::Error>, ) -> Result, ) -> Result { - let mut taken = Vec::new(); + let mut taken: Vec<([u64; 2], u32)> = Vec::new(); let made = { - let (constexprs, last) = (&self.constexprs, self.last[2]); + let (constexprs, indices) = (&self.constexprs, &self.indices); let mut sampler_ids = |samplers: &[rt::NumberedSampler]| { - let mut next = last; - let ids = samplers.iter().map(|sampler| match sampler { - rt::NumberedSampler::Constexpr(words) => match constexprs - .get(words) - .copied() - .or_else(|| taken.iter().find(|(w, _)| w == words).map(|&(_, i)| i)) - { + let mut ids = Vec::with_capacity(samplers.len()); + for sampler in samplers { + let rt::NumberedSampler::Constexpr(words) = sampler else { + ids.push(0); + continue; + }; + let known = (constexprs.get(words).copied()) + .or_else(|| taken.iter().find(|(w, _)| w == words).map(|&(_, i)| i)); + let index = match known { Some(index) => index, + // The lowest free sampler index this call has not taken yet. None => { - let range = rt::IndexClass::Sampler.range(); - next = if range.contains(&(next + 1)) { - next + 1 - } else { - range.start - }; - taken.push((*words, next)); - next + let fresh = |index| taken.iter().any(|&(_, i)| i == index); + let index = indices.lowest(rt::IndexClass::Sampler, 0, fresh); + let index = + index.ok_or(rt::Error::Refused(rt::Refusal::IndexInUse { + class: rt::IndexClass::Sampler, + index: rt::IndexClass::Sampler.range().end - 1, + }))?; + taken.push((*words, index)); + index } - }, - _ => 0, - }); - ids.collect() + }; + ids.push(index); + } + Ok(ids) }; make(&self.device, &mut sampler_ids) }; for (words, index) in taken { self.constexprs.insert(words, index); - self.last[2] = index; + self.indices.hold(None, rt::IndexClass::Sampler, index); } made } @@ -1069,6 +1132,7 @@ impl NewRuntime { if let Some(color) = f.metal("borderColor")? { descriptor.border_color = color; } + self.named = f.uint("resourceIndex")?.map(|index| index as u32); let device = self.device.clone(); let state = self.place(call, rt::IndexClass::Sampler, |index| { device.new_sampler_state(&descriptor, index) @@ -1098,13 +1162,30 @@ impl NewRuntime { self.outside.insert(call.result); } } + if let Some(index) = resource_index(call)? { + self.resource_indices.insert(call.result, index); + } unaddressed(Object::TextureDescriptor(Box::new(descriptor))) } // Every index is the backend's already. - "reserveResourceIndicesForResourceType:indices:indexCount:" => match uint(call, 0)? { - 0 | 1 => Ok(None), - other => Err(refuse(call, format!("resource type {other}"))), - }, + // Metal's one space of texture IDs is two classes here, by usage: an index is + // reserved in the class whose range holds it. + "reserveResourceIndicesForResourceType:indices:indexCount:" => { + let classes: &[rt::IndexClass] = match uint(call, 0)? { + 0 => &[rt::IndexClass::StorageTexture, rt::IndexClass::Texture], + 1 => &[rt::IndexClass::Sampler], + other => return Err(refuse(call, format!("resource type {other}"))), + }; + for index in super::args::list(call, 1)? { + let index = index.as_uint().and_then(|i| u32::try_from(i).ok()); + let index = + index.ok_or_else(|| refuse(call, "argument 1 is no list of indices"))?; + for &class in classes { + self.indices.reserve(class, index); + } + } + Ok(None) + } "newEvent" => { let event = self.device.new_event().map_err(failed(call))?; unaddressed(Object::Event(event)) @@ -1346,7 +1427,7 @@ impl NewRuntime { uint(call, 3)?, 0, ), - // The resource index is the guest's, which the player relocates the IDs of. + // The resource index places the view (`named_index`). "newTextureViewWithPixelFormat:" | "newTextureViewWithPixelFormat:resourceIndex:" => { let d = *texture.descriptor(); let format = metal(call, uint(call, 0)?)?; @@ -1410,50 +1491,9 @@ fn write_into(buffer: &rt::Buffer, offset: u64, bytes: &[u8]) -> Result<(), Play Ok(()) } -/// The index of `range` after `last` that `make` takes, `last` moved to each index tried: the -/// sequence the program's own objects take, wrapping at the range's end. An index `skip` names or -/// `make` finds in use is passed over; none where every index is. -pub(super) fn next_index( - last: &mut u32, - range: Range, - skip: impl Fn(u32) -> bool, - make: impl Fn(u32) -> Result, -) -> Option> { - for _ in range.clone() { - let mut index = *last + 1; - if !range.contains(&index) { - index = range.start; - } - *last = index; - if skip(index) { - continue; - } - match make(index) { - Err(rt::Error::Refused(rt::Refusal::IndexInUse { .. })) => continue, - made => return Some(made), - } - } - None -} - -/// The highest index of `range` that `make` takes, an index in use passed over: one outside the -/// sequence [`next_index`] hands out, which it leaves as it was, so the program's objects take the -/// indices they take without this one. None where every index is in use. -pub(super) fn top_index( - range: Range, - make: impl Fn(u32) -> Result, -) -> Option> { - for index in range.rev() { - match make(index) { - Err(rt::Error::Refused(rt::Refusal::IndexInUse { .. })) => continue, - made => return Some(made), - } - } - None -} - impl Backend for NewRuntime { fn call(&mut self, call: &Call) -> Result { + self.named = self.named_index(call)?; if &*call.selector == "release" { self.owners.remove(&call.receiver); self.fresh.remove(&call.receiver); @@ -1464,6 +1504,8 @@ impl Backend for NewRuntime { if let Some(place) = self.seconds.remove(call.receiver) { self.places.give(place, self.commits, Vec::new()); } + self.indices.give(call.receiver); + self.resource_indices.remove(&call.receiver); match self.objects.remove(&call.receiver) { Some(Object::Buffer(_, Some(place))) => { let users = (self.users.iter()) @@ -1897,6 +1939,7 @@ impl Backend for NewRuntime { lines.push(self.seconds.line()); } lines.push(self.unwritten.line()); + lines.push(self.indices.line()); lines } @@ -1921,6 +1964,10 @@ impl Backend for NewRuntime { false } + fn recorded_id(&mut self, object: u64, id: u64) { + self.recorded = Some((object, id)); + } + fn managed_texture(&self, texture: u64) -> Option { match self.objects.get(&texture) { Some(Object::Texture(texture)) => { diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs index 9e1ae14e9..6b4f6adba 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/render.rs @@ -128,7 +128,7 @@ impl NewRuntime { ))) })?; let made = self.numbered(|device, ids| { - device.new_render_pipeline_state(&descriptor, |samplers| Ok(ids(samplers))) + device.new_render_pipeline_state(&descriptor, |samplers| ids(samplers)) }); match made { Ok(state) => unaddressed(Object::RenderPipeline(state)), diff --git a/crates/metal2vulkan-validation/src/replay/player.rs b/crates/metal2vulkan-validation/src/replay/player.rs index b9c46a085..ce0f19825 100644 --- a/crates/metal2vulkan-validation/src/replay/player.rs +++ b/crates/metal2vulkan-validation/src/replay/player.rs @@ -128,6 +128,12 @@ pub trait Backend { fn managed_texture(&self, _texture: u64) -> Option { None } + + /// The `gpuResourceID` the program saw of `object`, which the next call makes, from the + /// stream's first `gpuResourceID` record of it (read ahead): a backend that places objects + /// at indices of its own choosing places it at that ID's. One that places them as the + /// recording's runtime did ignores it. + fn recorded_id(&mut self, _object: u64, _id: u64) {} } /// Why a play stopped. @@ -786,6 +792,9 @@ pub struct Player<'b, B: Backend> { /// making an object have as their receiver (the lowest id of a tie). Only its identity record /// tells the backend the Managed form; none where no call makes an object on a device. guest_device: Option, + /// The ID the program saw of each object, read ahead: its first `gpuResourceID` record's + /// answer, by the object and the position of the call that made it. + recorded_ids: HashMap<(u64, u64), u64>, /// The next call's position: the calls stepped so far. position: u64, /// The compute encoders open while a record names a later dispatch. @@ -1001,6 +1010,7 @@ impl<'b, B: Backend> Player<'b, B> { ahead: HashMap::new(), layouts: HashMap::new(), guest_device: None, + recorded_ids: HashMap::new(), position: 0, encoders: HashMap::new(), done: VecDeque::new(), @@ -1105,12 +1115,15 @@ impl<'b, B: Backend> Player<'b, B> { } /// Index the `m2v.privateBytes` records by the dispatch each names, which comes before it, and - /// lay out each placement heap for the runtime's answers (`relay`). 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. + /// the ID the program saw of each object by its making (`recorded_ids`), and lay out each + /// placement heap for the runtime's answers (`relay`). 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 mut ahead = stream.reopened()?; let mut position = 0; + // The position of the call that made each object. + let mut made_at: HashMap = HashMap::new(); // 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 @@ -1126,6 +1139,15 @@ impl<'b, B: Backend> Player<'b, B> { *made += 1; } } + if call.result != 0 { + made_at.insert(call.result, position); + } + let answer = call.answer("gpuResourceID").and_then(Value::as_uint); + if let (Some(id), "gpuResourceID") = (answer, &*call.selector) { + if let Some(&at) = made_at.get(&call.receiver) { + self.recorded_ids.entry((call.receiver, at)).or_insert(id); + } + } match &*call.selector { PRIVATE_BYTES => { let (dispatch, around) = Around::of(&call)?; @@ -1478,6 +1500,9 @@ impl<'b, B: Backend> Player<'b, B> { } let resolved = self.placed(Call { args, ..call }); let resolved = self.uploaded(resolved)?; + if let Some(&id) = (self.recorded_ids).get(&(resolved.result, self.position)) { + self.backend.recorded_id(resolved.result, id); + } let made = self.run(&resolved)?; self.track(&resolved); let backend = &*self.backend; diff --git a/crates/metal2vulkan-validation/src/replay/tests.rs b/crates/metal2vulkan-validation/src/replay/tests.rs index dc12a1870..0eceaeb8b 100644 --- a/crates/metal2vulkan-validation/src/replay/tests.rs +++ b/crates/metal2vulkan-validation/src/replay/tests.rs @@ -2,10 +2,10 @@ //! is asked (no device). The runtime backends' tests are device tests (`runtime_lane`). use super::addresses::AddressMap; +use super::new_runtime::indices::Indices; use super::new_runtime::places::Waiting; use super::new_runtime::second::merge; use super::new_runtime::unwritten::Unwritten; -use super::new_runtime::{next_index, top_index}; use super::player::{ Backend, Counters, Counts, IdDiffers, Made, PlayError, Player, PrivateBytes, Relaid, Report, TextureWrites, WAIT_COMPLETED, @@ -1099,26 +1099,75 @@ fn a_texture_marked_outside_whose_id_the_program_saw_stops_the_play() { /// index down. #[test] fn a_texture_marked_outside_takes_no_index_of_the_sequence() { - let range = 8..16; - let in_use = RefCell::new(HashSet::new()); + let class = rt::IndexClass::Texture; + let make = |index: u32| Ok::(index); + let placed = |indices: &mut Indices, object| { + let made = indices.place(object, class, None, make); + made.expect("a free index").expect("made") + }; + let topped = |indices: &mut Indices, object| { + let made = indices.top(object, class, make); + made.expect("a free index").expect("made") + }; + let mut indices = Indices::default(); + let unmarked = [placed(&mut indices, 1), placed(&mut indices, 2)]; + let mut indices = Indices::default(); + let first = placed(&mut indices, 1); + let marked = topped(&mut indices, 2); + let second = placed(&mut indices, 3); + let marked_again = topped(&mut indices, 4); + assert_eq!([first, second], unmarked); + let end = class.range().end; + assert_eq!((marked, marked_again), (end - 1, end - 2)); +} + +/// An object takes the index its record names where the runtime takes it; else, and for an +/// object with none, the lowest index of its class that no live object holds and the program did +/// not reserve, an index the runtime finds in use passed over; a released object's index is free +/// again. +#[test] +fn objects_take_the_named_index_else_the_lowest_free_one() { + let class = rt::IndexClass::Sampler; + let start = class.range().start; + // The runtime's own record: start + 1 held by work in flight of a released object. + let in_use = RefCell::new(HashSet::from([start + 1])); let make = |index: u32| match in_use.borrow_mut().insert(index) { true => Ok(index), - false => Err(rt::Error::Refused(rt::Refusal::IndexInUse { - class: rt::IndexClass::Texture, - index, - })), + false => Err(rt::Error::Refused(rt::Refusal::IndexInUse { class, index })), }; - let plain = |last: &mut u32| next_index(last, range.clone(), |_| false, make).unwrap(); - let mut last = 0; - let unmarked = [plain(&mut last).unwrap(), plain(&mut last).unwrap()]; - in_use.borrow_mut().clear(); - let mut last = 0; - let first = plain(&mut last).unwrap(); - let marked = top_index(range.clone(), make).unwrap().unwrap(); - let second = plain(&mut last).unwrap(); - let marked_again = top_index(range.clone(), make).unwrap().unwrap(); - assert_eq!([first, second], unmarked); - assert_eq!((marked, marked_again), (15, 14)); + let mut indices = Indices::default(); + indices.reserve(class, start + 2); + let take = |indices: &mut Indices, object, named| { + let made = indices.place(object, class, named, make); + made.expect("a free index").expect("made") + }; + assert_eq!( + take(&mut indices, 1, Some(start + 7)), + start + 7, + "the named index" + ); + assert_eq!(take(&mut indices, 2, None), start, "the lowest"); + // start + 1 is in use (work in flight holds it), start + 2 reserved. + assert_eq!(take(&mut indices, 3, None), start + 3); + // A named index an object holds: the lowest free one instead. + assert_eq!(take(&mut indices, 4, Some(start + 7)), start + 4); + assert_eq!( + take(&mut indices, 5, Some(start + 2)), + start + 2, + "the stream names a reserved index" + ); + indices.give(2); + in_use.borrow_mut().remove(&start); + assert_eq!( + take(&mut indices, 6, None), + start, + "free again after the release" + ); + assert!( + indices.line().starts_with("indices named 2:"), + "{}", + indices.line() + ); } /// The first object of the player's own. diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs b/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs index 52d113d02..f9c1eaf5c 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs @@ -11,6 +11,10 @@ //! own second copy where the device has one): a blit's fill reaches the GPU's copy and not the //! CPU's, an announcement with no write puts the CPU's bytes back into the GPU's copy at the next //! commit, and a synchronize brings the GPU's bytes into the CPU's copy. +//! - Sampler states take the lowest index of their class that no live object holds and the +//! program did not reserve: made and released past the class's 3,999 indices, they reuse the +//! released ones. A reserved index is taken only where the stream names it, by a descriptor's +//! resource index or by the ID the program saw of the state. //! //! The new runtime's device is opened behind the hang tripwire, as every device open in this crate //! is (`gpu.rs`), its kernels kept in a cache the test owns ([`ScratchCache`]). @@ -68,6 +72,13 @@ fn written( /// `path` played on the new runtime's device, its report and the backend's lines printed; the /// play's end unwrapped. fn play(test: &str, path: &Path) -> (Report, Vec) { + let (report, lines, _) = played(test, path, &[]); + (report, lines) +} + +/// `path` played as [`play`] plays it, and the index (the low half of the `gpuResourceID`) the +/// runtime then gives each of `objects`. +fn played(test: &str, path: &Path, objects: &[u64]) -> (Report, Vec, Vec) { let cache = ScratchCache::new().unwrap(); let mut backend = NewRuntime::new(rt_device(cache.path())).unwrap(); let mut reader = StreamReader::open(&[path.to_path_buf()], None).unwrap(); @@ -77,7 +88,15 @@ fn play(test: &str, path: &Path) -> (Report, Vec) { eprintln!("REPLAY {test} {line}"); } ended.unwrap(); - (report, lines) + let mut index = |object: &u64| backend.resource_id(*object).unwrap().expect("an ID") as u32; + let indices = objects.iter().map(&mut index).collect(); + (report, lines, indices) +} + +/// A sampler descriptor's map: the default descriptor, its resource index `index` where given. +fn sampler(index: Option) -> Value { + let index = index.map(|index| ("resourceIndex".into(), Value::Uint(index))); + Value::Map(index.into_iter().collect()) } /// A recorder struct's map of unsigned fields. @@ -347,3 +366,56 @@ fn a_two_copy_stream_s_managed_buffer_keeps_both_copies() { assert_eq!(Some(check.sha256), check.recorded, "#{object}: {lines:?}"); } } + +#[test] +fn sampler_states_made_and_released_past_their_class_reuse_the_lowest_free_index() { + let dir = ScratchDir::new("rt-replay-samplers").unwrap(); + let made = "newSamplerStateWithDescriptor:"; + let path = written(&dir, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + w.call(made, 1, 2, &[sampler(None)], &[])?; + // More than the class's 3,999 indices, each released before the next is made. + for object in 10..4110 { + w.call(made, 1, object, &[sampler(None)], &[])?; + w.call("release", object, 0, &[], &[])?; + } + w.call(made, 1, 3, &[sampler(None)], &[]) + }); + let (_, _, indices) = played("samplers", &path, &[2, 3]); + assert_eq!(indices, [1, 2]); +} + +#[test] +fn a_reserved_sampler_index_is_taken_only_where_the_stream_names_it() { + let dir = ScratchDir::new("rt-replay-reserved").unwrap(); + let made = "newSamplerStateWithDescriptor:"; + let path = written(&dir, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + // The sampler type's indices 1 and 2, reserved. + let indices = Value::List(vec![Value::Uint(1), Value::Uint(2)]); + let reserve = [Value::Uint(1), indices, Value::Uint(2)]; + let selector = "reserveResourceIndicesForResourceType:indices:indexCount:"; + w.call(selector, 1, 0, &reserve, &[])?; + w.call(made, 1, 2, &[sampler(None)], &[])?; + w.call(made, 1, 3, &[sampler(Some(2))], &[]) + }); + let (_, _, indices) = played("reserved", &path, &[2, 3]); + assert_eq!(indices, [3, 2]); +} + +#[test] +fn a_sampler_state_takes_the_index_of_the_id_the_program_saw() { + let dir = ScratchDir::new("rt-replay-recorded").unwrap(); + let made = "newSamplerStateWithDescriptor:"; + let path = written(&dir, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + w.call(made, 1, 2, &[sampler(None)], &[])?; + w.call(made, 1, 3, &[sampler(None)], &[])?; + // The program saw #2 at index 7, the default descriptor's word 0 (docs/RESOURCE-ID.md). + let id = [("gpuResourceID", Value::Uint(7))]; + w.call("gpuResourceID", 2, 0, &[], &id) + }); + let (report, _, indices) = played("recorded", &path, &[2, 3]); + assert_eq!(indices, [7, 1]); + assert!(report.ids.is_empty(), "{:?}", report.ids); +} diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index ddffcb5a7..80c43a2ae 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -169,7 +169,14 @@ and the (name id, value) answer pairs. - **Resource IDs.** A descriptor's resource index places its object at that ID, as Metal places it whether or not the index is forced: a texture descriptor's and a render pipeline's `resourceIndex` (`[index, forced]`), a sampler's (an index), and a view's `resourceIndex:` - argument. Every other object takes the ID its runtime gives it. + argument. Every other object takes the ID its runtime gives it; on the new runtime, whose + consumer gives every texture and sampler index, the index of the ID the program saw of the + object (its first `gpuResourceID` record, read ahead), else the lowest index of its class that + no live object holds and the program did not reserve (`reserveResourceIndicesForResourceType: + indices:indexCount:`), as Metal's pool hands out a sampler state's ID. A reserved index is taken + only where the stream names it. Where the runtime refuses a named index (an object of the play + still holds it, or it lies outside the object's class), the object takes the lowest free one, + and the report counts it. - **Textures outside the program's IDs.** A texture the recorder makes for itself, not the program's (the host's cursor), comes from a texture descriptor record whose map holds `outside: true` and a device's `newTextureWithDescriptor:` of that descriptor. Live, it took no @@ -528,7 +535,9 @@ counted from 0), completes the work committed so far, reports as at the stream's runtime's blocks of 16 MiB of either class (a longer one in a block of its own), a range freed for reuse once every command buffer committed before its release completed, gives the runtime back a block or heap of the stream at its release (`release_block`), and gives - textures and sampler states indices from the whole of each index class. Its readback serves + textures and sampler states indices from the whole of each index class (section 5): its + `indices named N: ...` line counts the objects placed at the index the stream named, those + whose named index the runtime refused, and the indices the program reserved. Its readback serves Shared and Managed buffers only; a check of anything else is a refusal. The runtime gives a compute or render pipeline state no `gpuResourceID`, so each one the program saw is reported on an `id` line as `none` and counted (`gap_pipeline_ids`); each skipped object's the program saw