diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index 95272309d..1fefb213e 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -55,7 +55,7 @@ use std::mem::MaybeUninit; use super::address_map::SamplerMaps; use super::argument_table::{ArgumentTable, InlineBytes}; use super::buffer::{Buffer, KeptSpaces}; -use super::command_buffer::{NotedTable, State}; +use super::command_buffer::{CommandBuffer, NotedTable, State}; use super::degradation::EachWatch; use super::device::lock; use super::error::{internal, Error, RuntimeGap}; @@ -153,6 +153,209 @@ pub(super) struct Tables<'a> { /// A draw's sampled slots that read the levels of their texture's own image apart from the /// attached ones, in place of its copy (`render/attached_levels.rs`). narrowed: Option<&'a NarrowedSlots>, + /// The texture and buffer slots the command reads through read twins, in place of what they + /// bind (`read_twin.rs`, [`TwinSlots`]). + twins: Option<&'a TwinSlots>, +} + +/// The slots a command reads through read twins (`read_twin.rs`), each bound in place of what +/// the slot binds where the command only reads it: at a texture slot, the runtime's texture over a +/// no-copy buffer's pages in place, made for the program's texture over the buffer's copy; at a +/// buffer slot, the buffer's own read twin, at the slot's offset. +pub(super) struct TwinSlots { + textures: Vec<(SlotRef, Texture)>, + buffers: Vec<(SlotRef, (Buffer, u64))>, +} + +impl TwinSlots { + /// The slots of `tables` that the command of `plan` and its own uses `command_uses`, which + /// reaches memory through a root table where `roots`, reads through read twins, in + /// `command_buffer` (`None` where none is): + /// + /// - each texture slot whose every use only reads, as a sampled or storage image (proven + /// from lowering: an unknown access is a write), and whose every descriptor is that image, + /// with no element of the heap, texel buffer or plane of it; not read through a snapshot, + /// narrowed to levels, nor presenting an attachment of the draw's instance; whose texture + /// has a read twin that serves each such binding with no shadow of its usage, and whose + /// bytes no earlier command of the command buffer may have written (`Texture::read_twin`); + /// - each buffer slot of a command that reaches no memory through a root table (so no address + /// of the slot's buffer reaches its functions), whose every use only reads, as a storage or + /// uniform buffer (proven from lowering, writes through the slot's escaped address among + /// them), and whose every descriptor is that buffer's, none a vertex buffer of it; whose + /// buffer has a read twin at its own base, and whose copy no earlier command of the command + /// buffer may have written (`Buffer::slot_twin`). + pub(super) fn of( + command_buffer: &CommandBuffer, + (plan, command_uses, roots): (&BindingPlan, &[ResourceUse], bool), + tables: &Tables<'_>, + ) -> Option { + if !crate::read_twin::twinned(command_buffer) { + return None; + } + let unproven = crate::read_twin::binds_unproven(command_buffer.generation()); + let mut seen: Vec = Vec::new(); + let mut textures = Vec::new(); + let mut buffers = Vec::new(); + for used in plan.uses.iter().chain(command_uses) { + let UseTarget::Slot(slot) = used.resource else { + continue; + }; + if seen.contains(&slot) { + continue; + } + seen.push(slot); + if slot.class == SlotClass::Buffer && !roots { + let Some((buffer, offset)) = stage_buffer(tables.stages, slot) else { + continue; + }; + if !read_only_buffer_slot(slot, (plan, command_uses), unproven) { + continue; + } + if let Some(twin) = buffer.slot_twin(command_buffer) { + buffers.push((slot, (twin, *offset))); + } + continue; + } + if slot.class != SlotClass::Texture { + continue; + } + let Some(texture) = tables + .of(slot.stage) + .and_then(|t| t.textures.get(&slot.index)) + else { + continue; + }; + let Some(kinds) = read_only_slot(slot, (plan, command_uses), unproven) else { + continue; + }; + let apart = tables.snapshot_slot(slot) + || (tables.narrowed).is_some_and(|n| n.levels(slot).is_some()) + || (tables.attached).is_some_and(|instance| texture.attached_in(instance)); + if apart { + continue; + } + if let Some(twin) = texture.read_twin(command_buffer, kinds) { + textures.push((slot, twin)); + } + } + let any = !textures.is_empty() || !buffers.is_empty(); + any.then_some(TwinSlots { textures, buffers }) + } + + /// The read twin bound at texture slot `slot`, where the command reads it so. + fn texture(&self, slot: SlotRef) -> Option<&Texture> { + let found = self.textures.iter().find(|(at, _)| *at == slot); + found.map(|(_, twin)| twin) + } + + /// The read twin bound at buffer slot `slot`, with the slot's offset, where the command + /// reads it so. + fn buffer(&self, slot: SlotRef) -> Option<&(Buffer, u64)> { + let found = self.buffers.iter().find(|(at, _)| *at == slot); + found.map(|(_, twin)| twin) + } +} + +/// Whether every use of buffer slot `slot` by a command of `plan` with its own uses +/// `command_uses` only reads it, as a storage or uniform buffer, and every descriptor of the +/// plan that names the slot is its buffer's, none of it a vertex buffer. +fn read_only_buffer_slot( + slot: SlotRef, + (plan, command_uses): (&BindingPlan, &[ResourceUse]), + unproven: bool, +) -> bool { + let mut read = unproven; + for used in plan.uses.iter().chain(command_uses) { + if used.resource != UseTarget::Slot(slot) { + continue; + } + let buffer = matches!(used.class, AccessClass::Storage | AccessClass::Uniform); + if (used.access.write && !unproven) || !buffer { + return false; + } + read |= used.access.read; + } + let vertex = (plan.vertex_buffers.iter()) + .any(|bind| slot.stage == Stage::Vertex && bind.buffer_index == slot.index); + let named = |write: &&DescriptorWrite| match &write.source { + WriteSource::Buffer { slot: at } | WriteSource::InlineBytes { slot: at } => *at == slot, + _ => false, + }; + let buffers = plan.descriptors.iter().filter(named).all(|write| { + let ty: vk::DescriptorType = write.ty.into(); + matches!(write.source, WriteSource::Buffer { .. }) + && matches!( + ty, + vk::DescriptorType::STORAGE_BUFFER + | vk::DescriptorType::STORAGE_BUFFER_DYNAMIC + | vk::DescriptorType::UNIFORM_BUFFER + | vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC + ) + }); + read && !vertex && buffers +} + +/// Where every use of texture slot `slot` by a command of `plan` with its own uses +/// `command_uses` only reads it, as a sampled or storage image, and every descriptor of the plan +/// that names the slot is that image (a texture's or a combined image sampler's): the kinds of +/// its bindings, a storage image's and a sampled one's ([`TwinKinds`]); else `None`. +fn read_only_slot( + slot: SlotRef, + (plan, command_uses): (&BindingPlan, &[ResourceUse]), + unproven: bool, +) -> Option { + let mut read = unproven; + for used in plan.uses.iter().chain(command_uses) { + let named = match used.resource { + UseTarget::Slot(at) | UseTarget::TileMap(at) => at == slot, + _ => false, + }; + if !named { + continue; + } + let image = matches!(used.class, AccessClass::Sampled | AccessClass::StorageImage); + let writes = used.access.write && !unproven; + if writes || !image || matches!(used.resource, UseTarget::TileMap(_)) { + return None; + } + read |= used.access.read; + } + let mut kinds = TwinKinds::default(); + for write in &plan.descriptors { + // The slot's own descriptors: `Some(true)` an image of it, `Some(false)` any other + // binding of it; another slot's, `None`. + let named = match &write.source { + WriteSource::Texture { slot: at, .. } => (*at == slot).then_some(true), + WriteSource::CombinedImageSampler { + image: ImageSource::Texture { slot: at, .. }, + .. + } => (*at == slot).then_some(true), + WriteSource::YCbCrInPlace { slot: at } + | WriteSource::YCbCrPlanesImage { slot: at } + | WriteSource::TexelBuffer { slot: at, .. } + | WriteSource::HeapEntry { + source: HeapSource::Bound(at), + .. + } => (*at == slot).then_some(false), + _ => None, + }; + let ty: vk::DescriptorType = write.ty.into(); + match named { + Some(true) if ty == vk::DescriptorType::STORAGE_IMAGE => kinds.storage = true, + Some(true) => kinds.sampled = true, + Some(false) => return None, + None => {} + } + } + (read && (kinds.storage || kinds.sampled)).then_some(kinds) +} + +/// The kinds of a texture slot's bindings ([`read_only_slot`]): whether one is a storage image, +/// and whether one is sampled. +#[derive(Clone, Copy, Default)] +pub(super) struct TwinKinds { + pub(super) storage: bool, + pub(super) sampled: bool, } /// The levels a narrowed slot reads of its texture's own image (`NarrowedSlots`), counted from @@ -293,6 +496,16 @@ impl<'a> Tables<'a> { snapshots: None, merged_header: None, narrowed: None, + twins: None, + } + } + + /// The tables, with the texture slots the command reads through their textures' read twins + /// (`read_twin.rs`). + pub(super) fn with_twins(self, twins: &'a TwinSlots) -> Tables<'a> { + Tables { + twins: Some(twins), + ..self } } @@ -845,8 +1058,12 @@ pub(super) struct Bound { pub(super) samplers: Vec>, } -/// The buffer bound at buffer slot `slot`, if any. +/// The buffer bound at buffer slot `slot`, if any: its read twin where the command reads it +/// through that ([`TwinSlots`]). fn slot_buffer<'a>(tables: &Tables<'a>, slot: SlotRef) -> Option<&'a (Buffer, u64)> { + if let Some(twin) = tables.twins.and_then(|twins| twins.buffer(slot)) { + return Some(twin); + } stage_buffer(tables.stages, slot) } @@ -873,11 +1090,16 @@ fn slot_bytes<'a>(tables: &Tables<'a>, slot: SlotRef) -> Option<&'a InlineBytes> .flatten() } -/// The texture bound at texture slot `slot`, if any. +/// The texture bound at texture slot `slot`, if any: its read twin where the command reads it +/// through that ([`TwinSlots`]). fn slot_texture<'a>(tables: &Tables<'a>, slot: SlotRef) -> Option<&'a Texture> { - (slot.class == SlotClass::Texture) - .then(|| tables.of(slot.stage)?.textures.get(&slot.index)) - .flatten() + if slot.class != SlotClass::Texture { + return None; + } + if let Some(twin) = tables.twins.and_then(|twins| twins.texture(slot)) { + return Some(twin); + } + tables.of(slot.stage)?.textures.get(&slot.index) } /// The tile map of the sparse texture bound at texture slot `slot`, which the plan reads where diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index d7fe75583..0fd1eb924 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -222,6 +222,19 @@ pub(super) struct HostCell { /// the same pages in place, which commands that cannot write the buffer read instead of its /// copy. Let go of as the buffer lies elsewhere ([`HostCell::replace`]). read_twin: Mutex>, + /// The read twins of the program's textures over its bytes, while it has a read twin + /// (`read_twin.rs`): each the runtime's texture over the read twin's bytes, in place, which + /// the slots that only read the texture bind instead. Let go of with the read twin. + twin_textures: Mutex>, +} + +/// A texture's read twin, as a no-copy buffer's [`HostCell`] keeps it (`read_twin.rs`): the +/// texture's `ObjectId`, the texture held weakly, and its twin, a `Texture`, each by type erased +/// as [`NotedTexture`] holds a texture. +pub(super) struct TextureTwin { + pub(super) of: ObjectId, + pub(super) texture: Weak, + pub(super) twin: Arc, } /// An image in place over a buffer's host pages ([`HostCell`], `texture/in_place_image.rs`), @@ -622,7 +635,8 @@ impl HostCell { // Its read twin lies over the pages it lay in: let go of, outside the pages' lock, so the // buffer is its copy alone from now on (`read_twin.rs`). let twin = lock(&self.read_twin).take(); - drop(twin); + let textures: Vec = lock(&self.twin_textures).drain(..).collect(); + drop((twin, textures)); lay } @@ -637,6 +651,29 @@ impl HostCell { drop(earlier); } + /// The read twin of the texture of `id` over its bytes (`read_twin.rs`), by type erased, + /// while the buffer lies in the pages it was made over. + pub(super) fn twin_texture(&self, id: ObjectId) -> Option> { + let textures = lock(&self.twin_textures); + let found = textures.iter().find(|kept| kept.of == id); + found.map(|kept| Arc::clone(&kept.twin)) + } + + /// Keep `kept`, a texture's read twin over the read twin's bytes, while the buffer has that + /// read twin (`read_twin.rs`); those of textures that went are let go of. + pub(super) fn keep_twin_texture(&self, kept: TextureTwin) { + if lock(&self.read_twin).is_none() { + return; + } + let mut textures = lock(&self.twin_textures); + let gone: Vec = textures + .extract_if(.., |kept| kept.texture.strong_count() == 0) + .collect(); + textures.push(kept); + drop(textures); + drop(gone); + } + /// A detach let go of `pages`: their deallocator is held back until the buffer's next rebind /// or its release ([`HostCell::release_held_back`]), as Metal never runs it at a detach. pub(super) fn hold_back(&self, pages: &HostPages) { @@ -3736,6 +3773,7 @@ impl Device { drops_writes, held_back: Mutex::new(None), read_twin: Mutex::new(None), + twin_textures: Mutex::new(Vec::new()), }); self.shared().rebinds.register(key, &cell); Lie::Host(cell) diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index fb6fe07b7..04dd6d342 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -929,7 +929,13 @@ impl Buffer { ycbcr: ycbcr_surface, }; let device = texture.generation().clone(); - Ok(device.kept_texture(texture, remake)) + let texture = device.kept_texture(texture, remake); + // Over a no-copy buffer with a read twin, its own read twin, which the slots that only + // read it bind instead (`read_twin.rs`): of a plain texture over its rows. + if form == BufferTextureCall::Texture && ycbcr_surface.is_none() { + self.make_twin_texture(&texture, descriptor, (offset, bytes_per_row)); + } + Ok(texture) } /// The texture over the buffer that `call` made through `form`, of `descriptor` at `over` diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 3023134de..3645c2f12 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -2525,11 +2525,20 @@ fn record( let texture_table = heap_tables.texture_table(core.device())?; let sampler_table = heap_tables.sampler_table(core.device())?; let stages = [(Stage::Kernel, tables.table)]; + let twins; let mut bound_tables = binding::Tables::new(&stages) .with_residency(tables.residency) .with_texture_table(texture_table.as_ref()) .with_sampler_table(sampler_table.as_ref()) .with_sampler_maps(sampler_maps.clone()); + // The texture slots the dispatch only reads through their textures' read twins + // (`read_twin.rs`). + let cb = core.command_buffer(); + let roots = commands.root_table.iter().next().is_some(); + twins = binding::TwinSlots::of(cb, (&**plan, &commands.uses, roots), &bound_tables); + if let Some(twins) = &twins { + bound_tables = bound_tables.with_twins(twins); + } // The flat dispatch's preprocess: its scratch holds the region record the variant reads. let preprocess = match &flat { Some((_, indirect)) => { diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 1dce5ad2e..e562adb0a 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -635,6 +635,15 @@ pub(super) struct DeviceShared { /// shadow then lacks it and is sampled through a usage shadow. #[cfg(test)] pub(crate) sampled_costs_forced: AtomicBool, + /// Its encoders record a command that writes a read twin, which they refuse otherwise: the + /// negative control of the tests of `tests/read_twin_device.rs` (`read_twin::refuses_writes`). + #[cfg(test)] + pub(crate) read_twin_unguarded: AtomicBool, + /// Its commands bind a read twin at a slot they may write, which they never do otherwise: the + /// negative control of the slots' proof in `tests/read_twin_device.rs` + /// (`read_twin::binds_unproven`). + #[cfg(test)] + pub(crate) read_twin_unproven: AtomicBool, /// The route a test takes for images over dma-buf pages, whatever the driver answers of an /// explicit plane's offset (`dma_buf.rs`'s `PlaneRoute`, as its `u8`): for the tests of /// `tests/dma_buf_plane_offset.rs` on a driver that answers the offset asked. @@ -3106,6 +3115,10 @@ impl Device { #[cfg(test)] sampled_costs_forced: Default::default(), #[cfg(test)] + read_twin_unguarded: Default::default(), + #[cfg(test)] + read_twin_unproven: Default::default(), + #[cfg(test)] plane_route_forced: Default::default(), dirty: Default::default(), standings: Default::default(), diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 0e95c88e6..099a90cc8 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1556,17 +1556,7 @@ impl EncoderCore { self.touch_reaching(uses, resident); return None; } - // A command that writes a read twin, which lies over pages whose GPU writes are dropped in - // place (`read_twin.rs`), records nothing, and its command buffer fails from this encoder - // on: no path binds a twin where a command may write it, so only a defect of the - // runtime's meets this, which it keeps from the pages. - let writes_twin = - || (uses.iter()).any(|used| used.key.is_read_twin() && !used.write.is_empty()); - if writes_twin() && crate::read_twin::refuses_writes() { - self.device().shared().counts.read_twin_write_refused(); - self.fail_command_buffer(CommandBufferError::Internal(VkResultCode( - vk::Result::ERROR_UNKNOWN.as_raw(), - ))); + if self.refuses_twin_write(uses) { return None; } // A command reading a new texture's levels that read zero where Metal reads its pattern, @@ -1600,6 +1590,26 @@ impl EncoderCore { Some(barrier) } + /// Whether a command whose own uses are `uses` writes a read twin, which lies over pages whose + /// GPU writes are dropped in place (`read_twin.rs`): refused, it records nothing, and its + /// command buffer fails from this encoder on. No path binds a twin where a command may write + /// it, so only a defect of the runtime's meets this, which it keeps from the pages. + fn refuses_twin_write(&mut self, uses: &[Use]) -> bool { + let shared = self.device().shared(); + if !shared.counts.read_twins_any() { + return false; + } + let writes = (uses.iter()).any(|used| used.key.is_read_twin() && !used.write.is_empty()); + if !writes || !crate::read_twin::refuses_writes(shared) { + return false; + } + shared.counts.read_twin_write_refused(); + self.fail_command_buffer(CommandBufferError::Internal(VkResultCode( + vk::Result::ERROR_UNKNOWN.as_raw(), + ))); + true + } + /// Log for the commit each texture `uses` read in a level and layer, where a new texture's /// unwritten pattern may lie (`FreshUnwritten::observe_reads`). fn observe_fresh(&self, uses: &[Use], reads: &[FreshRead]) { @@ -1841,6 +1851,9 @@ impl EncoderCore { "a command recorded apart in an ordered encoder", )); } + if self.refuses_twin_write(uses) { + return Err(twin_written()); + } self.observe_fresh(uses, &[]); self.hold_resident(); let Some(noted) = noted else { @@ -1877,6 +1890,9 @@ impl EncoderCore { "a command recorded apart in an ordered encoder", )); } + if self.refuses_twin_write(uses) { + return Err(twin_written()); + } let len = prefix.prefix.len; // A chunk's core notes the uses past those its pass's core notes ([`ResidentPart`]). let apart = match &mut self.resident_notes { @@ -1953,6 +1969,9 @@ impl EncoderCore { "a command recorded apart in an ordered encoder", )); } + if self.refuses_twin_write(uses) { + return Err(twin_written()); + } // Read before the host aliases' uses are worked out, so a change made since counts. let into = self.noted_into(); if !noted.moves((uses, resident), into) { @@ -3954,3 +3973,10 @@ pub(super) fn count_shadow_copies(counts: &Counters, copies: &[ShadowCopy]) { counts.shadow_texels_kept(kept); } } + +/// What a command recorded apart (a draw) answers where its uses write a read twin, which its +/// encoder refused, failing its command buffer (`EncoderCore`'s `refuses_twin_write`): it records +/// nothing. +fn twin_written() -> Error { + super::error::internal("a command that writes a read twin") +} diff --git a/crates/metal2vulkan-runtime/src/read_twin.rs b/crates/metal2vulkan-runtime/src/read_twin.rs index 9764b6f4b..255bdf58e 100644 --- a/crates/metal2vulkan-runtime/src/read_twin.rs +++ b/crates/metal2vulkan-runtime/src/read_twin.rs @@ -28,15 +28,34 @@ //! place: //! - a blit's copy out of the buffer, into a buffer or a texture: a copy reads its source alone //! (`vkCmdCopyBuffer`, `vkCmdCopyBufferToImage`). Counted: `WorkCounts::read_twin_blit_reads`. +//! - a texture slot of an encoder's own draw or dispatch, bound to the program's texture over +//! the buffer's rows, where the command only reads the slot (`binding::TwinSlots`): every use +//! of it the plan lists only reads, as a sampled or storage image (proven from lowering, an +//! unknown access being a write), and every descriptor of it is that image, none an element +//! of the heap, a texel buffer or a plane. The slot then binds the texture's read twin: the +//! runtime's texture of the same descriptor over the twin's bytes, made with the texture and +//! kept only where it lies in place over them, the device's check of textures in place +//! passed (`Buffer::make_twin_texture`; else `WorkCounts::read_twin_textures_not_in_place`), +//! and only where it serves the slot's bindings with no shadow of its usage. A slot read +//! through a snapshot, narrowed to levels, or presenting an attachment of the draw's instance +//! binds the texture itself. Counted: `WorkCounts::read_twin_slot_reads`. +//! - a buffer slot of an encoder's own draw or dispatch bound to the buffer, where the command +//! reaches no memory through a root table (so no address of the buffer reaches its +//! functions, and no loaded address reaches the twin) and only reads the slot: every use of +//! it the plan lists only reads, as a storage or uniform buffer (proven from lowering, writes +//! through the slot's escaped address among them), and every descriptor of it is the +//! buffer's, none a vertex buffer. The slot then binds the twin at the slot's offset, where +//! the twin's base is the buffer's (`Buffer::slot_twin`). Counted: +//! `WorkCounts::read_twin_slot_reads`. //! //! Each such site takes the twin only while no earlier command of its command buffer may have //! written the buffer's copy (a write of its key, or a function that may store through an //! address, `State::writes_unnamed`): after one, the command buffer reads the copy, so a later //! command reads the dropped write back as Metal's GPU caches let it (`read_only_view.rs`), //! and the next command buffer reads the pages (`WorkCounts::read_twin_reads_after_writes`). -//! And every encoder refuses a command whose uses write a twin's key: it records nothing, and -//! its command buffer fails (`WorkCounts::read_twin_writes_refused`), which only a defect of -//! the runtime's meets. +//! And every encoder refuses a command whose uses write a twin's key, a texture twin's uses +//! being its buffer twin's bytes: it records nothing, and its command buffer fails +//! (`WorkCounts::read_twin_writes_refused`), which only a defect of the runtime's meets. //! - **What it saves.** A command buffer that reads such a buffer only through its twin uses //! none of its copy, so its commit compares none of it (`copied.rs`, //! `WorkCounts::copied_copy_ins_compared`, `copied_copy_in_bytes_compared`): the twin is placed @@ -44,15 +63,22 @@ //! `Placements`), which a use of the copy takes and a use of the twin takes nothing beside. use super::address::{AddressPlacement, Place}; -use super::buffer::{Buffer, Naming}; +use super::binding::TwinKinds; +use super::buffer::{Buffer, Naming, TextureTwin}; use super::command_buffer::CommandBuffer; -use super::device::Device; +use super::device::{Device, DeviceShared}; use super::encoder::EncoderCore; use super::error::{internal, Error}; use super::host_memory::HostParts; +use super::texture::Texture; +use super::texture_descriptor::TextureDescriptor; +use super::tracker::Access; use super::values::ResourceOptions; use metal2vulkan::device::ContainmentPolicy; -use std::sync::Arc; +use std::any::Any; +#[cfg(test)] +use std::sync::atomic::Ordering; +use std::sync::{Arc, Weak}; /// The refusal a read twin answers where its pages' import would be a copy of them /// (`Device::copied_buffer`): it takes none. @@ -60,24 +86,32 @@ pub(super) fn uncopied() -> Error { internal("a read twin is never a copy of its pages") } +/// Whether a command binds a read twin at a slot it may write (`binding::TwinSlots`): never, +/// but on a test's device that asked it to (`DeviceShared::read_twin_unproven`), to show that the +/// twin is the pages in place and what the slots' proof keeps from them. #[cfg(test)] -thread_local! { - /// The tests' negative control: an encoder on this thread records a command that writes a - /// read twin, which it refuses otherwise ([`refuses_writes`]). - pub(crate) static UNGUARDED: std::cell::Cell = const { std::cell::Cell::new(false) }; +pub(super) fn binds_unproven(device: &DeviceShared) -> bool { + device.read_twin_unproven.load(Ordering::Relaxed) } -/// Whether an encoder refuses a command whose uses write a read twin (`encoder.rs`): always, but -/// on a test's thread that turned the guard off ([`UNGUARDED`]), to show what it keeps from the -/// pages. -#[cfg(test)] -pub(super) fn refuses_writes() -> bool { - !UNGUARDED.with(std::cell::Cell::get) -} - -/// Whether an encoder refuses a command whose uses write a read twin (`encoder.rs`): always. +/// Whether a command binds a read twin at a slot it may write (`binding::TwinSlots`): never. #[cfg(not(test))] -pub(super) fn refuses_writes() -> bool { +pub(super) fn binds_unproven(_device: &DeviceShared) -> bool { + false +} + +/// Whether an encoder refuses a command whose uses write a read twin (`EncoderCore`'s +/// `refuses_twin_write`): always, but on a test's device that turned the guard off +/// (`DeviceShared::read_twin_unguarded`), to show what it keeps from the pages. +#[cfg(test)] +pub(super) fn refuses_writes(device: &DeviceShared) -> bool { + !device.read_twin_unguarded.load(Ordering::Relaxed) +} + +/// Whether an encoder refuses a command whose uses write a read twin (`EncoderCore`'s +/// `refuses_twin_write`): always. +#[cfg(not(test))] +pub(super) fn refuses_writes(_device: &DeviceShared) -> bool { true } @@ -170,3 +204,95 @@ impl EncoderCore { Some(twin) } } + +impl Buffer { + /// Give `texture`, the program's texture of `descriptor` just made over the buffer's bytes + /// at `offset` with rows `bytes_per_row` apart, its read twin, where the buffer has one (the + /// module docs): the runtime's texture of the same descriptor over the read twin's bytes, + /// kept where it lies in place over them; else nothing, counted. + pub(super) fn make_twin_texture( + &self, + texture: &Texture, + descriptor: &TextureDescriptor, + (offset, bytes_per_row): (u64, u64), + ) { + let (Some(twin), Some(cell)) = (self.read_twin(), self.host_cell()) else { + return; + }; + let counts = &self.generation().shared().counts; + let made = (twin + .new_runtime_texture(descriptor, offset, bytes_per_row) + .ok()) + .filter(Texture::aliases_buffer); + let Some(made) = made else { + counts.read_twin_texture(false); + return; + }; + let weak: Weak = texture.downgrade(); + cell.keep_twin_texture(TextureTwin { + of: texture.object_id(), + texture: weak, + twin: Arc::new(made), + }); + counts.read_twin_texture(true); + } +} + +/// Whether a command of `command_buffer` may read a slot through a read twin: a buffer of its +/// device took one. +pub(super) fn twinned(command_buffer: &CommandBuffer) -> bool { + command_buffer.generation().counts.read_twins_any() +} + +impl Buffer { + /// The buffer's read twin, for a command of `command_buffer` that binds it at a buffer slot it + /// only reads (`binding::TwinSlots`): where it has one at its own base (so the ranges the + /// command planned for the buffer are the twin's), and no earlier command of the command + /// buffer may have written its copy (after one, the command reads the copy, so it reads that + /// write back). Else `None`, the buffer itself. + pub(super) fn slot_twin(&self, command_buffer: &CommandBuffer) -> Option { + let twin = self.read_twin()?; + if twin.base() != self.base() { + return None; + } + let counts = &command_buffer.generation().counts; + if command_buffer.may_have_written(self.identity().key) { + counts.read_twin_read_after_write(); + return None; + } + counts.read_twin_slot_read(); + Some(twin) + } +} + +impl Texture { + /// The texture's read twin, for a command of `command_buffer` that binds it at a slot of + /// `kinds` and only reads it there (`binding::TwinSlots`): the runtime's texture over its + /// buffer's read twin's bytes, in place, where it has one that serves each kind of binding + /// with no shadow of its usage, and no earlier command of the command buffer may have written + /// the buffer's copy or the texture (after one, the command reads the copy, so it reads that + /// write back as Metal's GPU caches let it). Else `None`, the texture itself. + pub(super) fn read_twin( + &self, + command_buffer: &CommandBuffer, + kinds: TwinKinds, + ) -> Option { + let buffer = &self.buffer_texels()?.buffer; + let kept = buffer.host_cell()?.twin_texture(self.object_id())?; + let twin = kept.downcast_ref::()?.clone(); + let shadowed = (kinds.storage && twin.needs_usage_shadow(true)) + || (kinds.sampled && twin.needs_usage_shadow(false)); + if shadowed || !twin.aliases_buffer() { + return None; + } + let counts = &command_buffer.generation().counts; + let own = self.bound_use(Access::NONE, Access::NONE).key; + let key = buffer.identity().key; + if command_buffer.may_have_written(key) || command_buffer.may_have_written(own) { + counts.read_twin_read_after_write(); + return None; + } + counts.read_twin_slot_read(); + Some(twin) + } +} diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 63a6be4fa..636287804 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -9711,6 +9711,7 @@ impl RenderLowering { } false => binding::NarrowedSlots::default(), }; + let twins; let mut tables = binding::Tables::new(&stages) .with_pass(layout, views) .with_residency(&self.residency) @@ -9726,6 +9727,14 @@ impl RenderLowering { if let Some(views) = &snapshot_views { tables = tables.with_snapshots(views); } + // The texture slots the draw only reads through their textures' read twins + // (`read_twin.rs`), apart from those it reads through snapshots, narrowed or attached. + let cb = self.core.command_buffer(); + let roots = !commands.root_tables.is_empty(); + twins = binding::TwinSlots::of(cb, (&*plan, &commands.uses, roots), &tables); + if let Some(twins) = &twins { + tables = tables.with_twins(twins); + } if let Some(heap) = &heap { // Taken as the draw settled: its variant has set-1 arrays. let states = argument_samplers diff --git a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs index 9a63e3ac0..277741262 100644 --- a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs +++ b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs @@ -1073,6 +1073,7 @@ impl RenderLowering { // not the kept draw's, its uses where they were not patched), made only for one. let mut rebound = true; if !writes_kept || !patched { + let twins; let mut tables = binding::Tables::new(&stages) .with_pass(&self.layout, plan.views) .with_residency(&self.residency); @@ -1084,6 +1085,14 @@ impl RenderLowering { if let Some(read_again) = &read_again { tables = tables.with_snapshots(&read_again.views); } + // The texture slots it only reads through their textures' read twins, as every step + // binds them (`read_twin.rs`). + let cb = self.core.command_buffer(); + let roots = !command.root_tables.is_empty(); + twins = binding::TwinSlots::of(cb, (&**plan, command.uses, roots), &tables); + if let Some(twins) = &twins { + tables = tables.with_twins(twins); + } // Its runtime samplers' address modes: the kept draw's, as `bring_in` found them. if images { tables = tables.with_sampler_maps(live.read_from.maps().clone()); diff --git a/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs b/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs index a5aa3d6b6..e328cab09 100644 --- a/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs @@ -19,21 +19,45 @@ //! pages keep their bytes and a later command buffer reads them in place. //! - **The guard, and the negative control.** A fill of the twin itself is refused by the //! encoder, its command buffer failed and the pages kept; with the guard off on the test's -//! thread the same fill changes the pages: the twin is the pages in place, and what keeps them +//! device the same fill changes the pages: the twin is the pages in place, and what keeps them //! is that no write reaches it. +//! - **A texture over it, read in place.** A buffer's texture takes a read twin of its own, which +//! a kernel that only reads the texture binds: its texels are the pages', and the commit +//! compares none of the buffer's copy. After a fill of the buffer in the same command buffer +//! the kernel reads the texture itself, the fill read back, and the next command buffer reads +//! the pages in place again. So for the screen-sized buffer's texture at a 3648-texel pitch, +//! where the device's linear image of it lies within the buffer's bytes; where it runs past +//! them (lavapipe's takes two rows more), neither the texture nor a twin lies in place, and the +//! texture is read through its shadow as before. +//! - **A texture over it, sampled in place by a draw.** A small buffer's texture sampled by a +//! draw reads through its twin, the pass's pixels those of a draw sampling a texture of the +//! device's own holding the same texels, and the commit compares nothing; after a fill of the +//! buffer in the same command buffer the draw samples the texture itself, the fill read back. +//! - **A buffer slot, read in place.** A kernel that only reads the buffer at a slot (and +//! reaches no memory through a root table) binds its twin there: it reads the pages, the commit +//! comparing nothing; after a fill of the buffer in the same command buffer it reads the copy, +//! the fill read back. Bound at the slot the kernel writes, the buffer itself takes the writes, +//! dropped; bound there without the proof the twin's write is refused, and with the guard off +//! too it changes the pages. +//! - **The slots' proof, and its negative control.** A kernel that writes the texture binds the +//! texture: its writes are dropped and the pages kept. Bound at that slot without the proof +//! (on the test's device alone), the twin's write is refused by the guard, and with the guard +//! off too it changes the pages. //! //! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). A device //! that imports no host memory, and a system that maps read-only views (macOS, whose buffers take //! no twin), say so and pass. use crate::{ - Buffer, CommandBufferStatus, Device, DeviceKind, DeviceOptions, HostMemory, ImportGate, - ImportRequest, Origin, ResourceOptions, Size, TextureDescriptor, WorkCounts, + Buffer, CommandBufferStatus, ComputePipelineState, Device, DeviceKind, DeviceOptions, + HostMemory, ImportGate, ImportRequest, Origin, Region, ResourceOptions, Size, Texture, + TextureDescriptor, WorkCounts, }; use metal2vulkan::device::{ContainmentPolicy, DevicePolicy, GuestIsolation}; -use metal2vulkan::metal::PixelFormat; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; use std::alloc::Layout; use std::ptr::NonNull; +use std::sync::atomic::Ordering; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -439,13 +463,13 @@ fn a_write_of_the_twin_itself_is_refused_and_would_reach_the_pages() { 1 ); assert!(pages.bytes() == kept, "the guard keeps the pages"); - // The negative control: with the guard off on this thread, the same fill reaches the pages, + // The negative control: with the guard off on this device, the same fill reaches the pages, // which the twin is in place. - crate::read_twin::UNGUARDED.with(|unguarded| unguarded.set(true)); + (device.shared().read_twin_unguarded).store(true, Ordering::Relaxed); let status = blit(&device, |encoder| { encoder.fill_buffer(&twin, 0..4096, 0xe1).unwrap(); }); - crate::read_twin::UNGUARDED.with(|unguarded| unguarded.set(false)); + (device.shared().read_twin_unguarded).store(false, Ordering::Relaxed); assert_eq!(status, CommandBufferStatus::Completed); assert!( pages.bytes()[..4096] == [0xe1; 4096], @@ -543,3 +567,647 @@ fn no_twin_where_the_policy_contains_no_access() { assert_eq!(compared(&before, &after)[0], 1, "its copy compared"); drop(buffer); } + +/// Where the textures made between `before` and `after` lie: their counts in place, as +/// shadows, and why. +fn placed(before: &WorkCounts, after: &WorkCounts) -> String { + let delta = |of: fn(&WorkCounts) -> u64| of(after) - of(before); + format!( + "twins {} (not in place {}), in place over host pages {}, over copies {}, pitched {}, \ + shadowed {}: pending {} failed {} unchecked {} refused rows {} image {} pitch {} \ + placement {} source {}", + delta(|c| c.read_twin_textures_made), + delta(|c| c.read_twin_textures_not_in_place), + delta(|c| c.host_textures_in_place), + delta(|c| c.copied_textures_in_place), + delta(|c| c.pitched_host_images), + delta(|c| c.shadowed_textures), + delta(|c| c.host_texture_shadows_check_pending), + delta(|c| c.host_texture_shadows_check_failed), + delta(|c| c.host_texture_shadows_unchecked), + delta(|c| c.host_texture_shadows_refused_rows), + delta(|c| c.host_texture_shadows_refused_image), + delta(|c| c.host_texture_shadows_refused_pitch), + delta(|c| c.host_texture_shadows_refused_placement), + delta(|c| c.host_texture_shadows_refused_source), + ) +} + +/// The kernel that writes each texel of its texture 0 into its texture 1 inverted, its alpha +/// kept (`examples/runtime_examples.ll`'s `invert_texels`). +fn invert(device: &Device) -> ComputePipelineState { + let function = super::encoder_holds::library(device, "examples/runtime_examples.ll") + .new_function_with_name("invert_texels") + .unwrap(); + device + .new_compute_pipeline_state_with_function(&function, &crate::PipelineOptions::default()) + .unwrap() +} + +/// The side of the square of texels a kernel inverts. +const SIDE: u64 = 64; + +/// Commit one command buffer that runs `state` over the first `SIDE` x `SIDE` texels with +/// `source` at texture 0 and `destination` at texture 1, after a blit fill of `fill`'s buffer and +/// bytes where given, wait for it, and answer its status. +fn invert_texels( + device: &Device, + state: &ComputePipelineState, + (source, destination): (&Texture, &Texture), + fill: Option<(&Buffer, std::ops::Range, u8)>, +) -> CommandBufferStatus { + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + if let Some((buffer, bytes, value)) = fill { + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encoder.fill_buffer(buffer, bytes, value).unwrap(); + encoder.end_encoding().unwrap(); + } + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + encoder.set_texture(Some(source), 0).unwrap(); + encoder.set_texture(Some(destination), 1).unwrap(); + encoder + .dispatch_threads(Size::new(SIDE, SIDE, 1), Size::new(8, 8, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + command_buffer.status() +} + +/// A `Shared` texture of `format` (of 4-byte texels) of the device's own, `SIDE` texels square, +/// that kernels read and write. +fn square(device: &Device, format: PixelFormat) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(format, SIDE, SIDE, false); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + descriptor.resource_options = ResourceOptions::shared(); + device.new_texture(&descriptor).unwrap() +} + +/// The first `SIDE` x `SIDE` texels of `texture` as the CPU reads them, rows tight. +fn square_texels(texture: &Texture) -> Vec { + let mut bytes = vec![0; (SIDE * SIDE * 4) as usize]; + let region = Region::new_2d(0, 0, SIDE, SIDE); + texture + .get_bytes(&mut bytes, SIDE * 4, 0, region, 0, 0) + .unwrap(); + bytes +} + +/// The first `SIDE` x `SIDE` texels of `bytes` (`BGRA8Unorm` or `RGBA8Unorm`), rows `row` bytes +/// apart, as `invert_texels` writes them: each colour channel inverted, its alpha kept. +fn inverted(bytes: &[u8], row: u64) -> Vec { + let mut out = Vec::with_capacity((SIDE * SIDE * 4) as usize); + for y in 0..SIDE { + let start = (y * row) as usize; + for texel in bytes[start..start + (SIDE * 4) as usize].chunks(4) { + out.extend([255 - texel[0], 255 - texel[1], 255 - texel[2], texel[3]]); + } + } + out +} + +/// A texture of `format` (of 4-byte texels), `width` x `height`, of `usage`, over `buffer`'s +/// bytes from its first, rows tight. +fn texture_over( + buffer: &Buffer, + (format, width, height): (PixelFormat, u64, u64), + usage: TextureUsage, +) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(format, width, height, false); + descriptor.usage = usage; + descriptor.resource_options = ResourceOptions::shared(); + buffer.new_texture(&descriptor, 0, width * 4).unwrap() +} + +/// The screen's texture (`WIDTH` x `HEIGHT` `BGRA8Unorm`, rows `ROW` bytes apart, `ShaderRead`) +/// over a buffer of bit 24 over `pages`, and whether it took a read twin: one where the device +/// lays its linear image in the buffer's bytes. Where it does not (lavapipe's image takes two rows +/// more), neither the texture nor its twin lies in place, and the texture is read through its +/// shadow, its texels the pages'. +fn screen_texture(device: &Device, pages: &Pages) -> (Buffer, Texture, bool) { + let buffer = pages.private_bit_buffer(device, None); + assert!(buffer.read_twin().is_some(), "a twin made"); + let before = device.work_counts(); + let shape = (PixelFormat::BGRA8Unorm, WIDTH, HEIGHT); + let texture = texture_over(&buffer, shape, TextureUsage::SHADER_READ); + let after = device.work_counts(); + eprintln!( + "READ-TWIN: the screen's texture: {}", + placed(&before, &after) + ); + let twinned = after.read_twin_textures_made > before.read_twin_textures_made; + if !twinned { + let refused = after.host_texture_shadows_refused_placement + - before.host_texture_shadows_refused_placement; + assert_eq!( + after.read_twin_textures_not_in_place - before.read_twin_textures_not_in_place, + 1 + ); + assert!(refused > 0, "the twin's image would not lie in the bytes"); + } + (buffer, texture, twinned) +} + +#[test] +fn a_screen_sized_private_bit_buffer_s_texture_is_read_in_place_by_a_kernel() { + let pages = Pages::new(SCREEN, 13); + let Some(device) = device(None) else { + return; + }; + let (buffer, texture, twinned) = screen_texture(&device, &pages); + if !twinned { + let state = invert(&device); + let out = square(&device, PixelFormat::BGRA8Unorm); + let before = device.work_counts(); + let status = invert_texels(&device, &state, (&texture, &out), None); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(after.read_twin_slot_reads, before.read_twin_slot_reads); + assert!( + square_texels(&out) == inverted(&pages.bytes(), ROW), + "the pages' texels" + ); + return; + } + read_by_a_kernel(&device, (&pages, &buffer), &texture, ROW); + drop((texture, buffer)); +} + +#[test] +fn a_screen_sized_private_bit_buffer_s_texture_is_sampled_in_place_by_a_draw() { + let pages = Pages::new(SCREEN, 23); + let Some(device) = device(None) else { + return; + }; + let (buffer, texture, twinned) = screen_texture(&device, &pages); + let shape = (WIDTH, HEIGHT, ROW); + if !twinned { + let target = draw_target(&device); + let own = reference(&device, shape, &pages.bytes()); + let expected = sampled(&device, &own, &target); + let before = device.work_counts(); + let drawn = sampled(&device, &texture, &target); + let after = device.work_counts(); + assert_eq!(after.read_twin_slot_reads, before.read_twin_slot_reads); + assert!(drawn == expected, "the pages' texels sampled"); + return; + } + sampled_in_place(&device, (&pages, &buffer), &texture, shape); + drop((texture, buffer)); +} + +#[test] +fn a_private_bit_buffer_s_texture_is_read_in_place_by_a_kernel() { + let pages = Pages::new(SMALL, 37); + let Some(device) = device(None) else { + return; + }; + let buffer = pages.private_bit_buffer(&device, None); + let before = device.work_counts(); + let shape = (PixelFormat::BGRA8Unorm, SIDE, SIDE); + let texture = texture_over(&buffer, shape, TextureUsage::SHADER_READ); + let after = device.work_counts(); + assert_eq!( + after.read_twin_textures_made - before.read_twin_textures_made, + 1, + "the texture's twin made, in place: {}", + placed(&before, &after) + ); + read_by_a_kernel(&device, (&pages, &buffer), &texture, SIDE * 4); + drop((texture, buffer)); +} + +/// A kernel reads `texture`, over `buffer`'s bytes (of `pages`) in rows `row` bytes apart, which +/// took a read twin: through its twin, the commit comparing nothing; a CPU write of the pages +/// read in place; after a fill of the buffer in the same command buffer, through the texture +/// itself, the fill read back; and the next command buffer through its twin again. +fn read_by_a_kernel( + device: &Device, + (pages, buffer): (&Pages, &Buffer), + texture: &Texture, + row: u64, +) { + let state = invert(device); + let out = square(device, PixelFormat::BGRA8Unorm); + let before = device.work_counts(); + let status = invert_texels(device, &state, (texture, &out), None); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(after.read_twin_slot_reads - before.read_twin_slot_reads, 1); + assert_eq!(compared(&before, &after), [0, 0, 0], "nothing compared"); + eprintln!( + "READ-TWIN: a kernel reading a texture over a buffer of bit 24, rows {row} bytes apart: \ + copies in compared {:?} (copies, bytes, threads)", + compared(&before, &after) + ); + assert!( + square_texels(&out) == inverted(&pages.bytes(), row), + "the pages' texels" + ); + // A CPU write of the pages reaches the next command buffer's read in place. + pages.write(0, &[0x42; 64]); + let status = invert_texels(device, &state, (texture, &out), None); + assert_eq!(status, CommandBufferStatus::Completed); + assert!( + square_texels(&out) == inverted(&pages.bytes(), row), + "the CPU's write read" + ); + // A fill of the buffer, then the kernel, in one command buffer: it reads the texture itself, + // the fill read back, and the commit compares the copy. + let kept = pages.bytes(); + let before = device.work_counts(); + let fill = Some((buffer, 0..row * SIDE, 0x5a)); + let status = invert_texels(device, &state, (texture, &out), fill); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(after.read_twin_slot_reads, before.read_twin_slot_reads); + assert_eq!( + after.read_twin_reads_after_writes - before.read_twin_reads_after_writes, + 1 + ); + assert_eq!(compared(&before, &after)[0], 1, "its copy compared"); + assert!( + square_texels(&out) == inverted(&vec![0x5a; (row * SIDE) as usize], row), + "the fill read back" + ); + assert!(pages.bytes() == kept, "the fill never reaches the pages"); + // The next command buffer reads the pages in place again. + let before = device.work_counts(); + let status = invert_texels(device, &state, (texture, &out), None); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(after.read_twin_slot_reads - before.read_twin_slot_reads, 1); + assert_eq!(compared(&before, &after), [0, 0, 0]); + assert!( + square_texels(&out) == inverted(&kept, row), + "the pages read again" + ); + assert_eq!(after.read_twin_writes_refused, 0); +} + +#[test] +fn a_texture_twin_bound_without_the_slots_proof_is_refused_and_would_reach_the_pages() { + let pages = Pages::new(SMALL, 17); + let Some(device) = device(None) else { + return; + }; + let buffer = pages.private_bit_buffer(&device, None); + let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + let before = device.work_counts(); + let texture = texture_over(&buffer, (PixelFormat::RGBA8Unorm, SIDE, SIDE), usage); + let after = device.work_counts(); + assert_eq!( + after.read_twin_textures_made - before.read_twin_textures_made, + 1, + "the texture's twin made, in place" + ); + let state = invert(&device); + let source = square(&device, PixelFormat::RGBA8Unorm); + let texels = pattern((SIDE * SIDE * 4) as usize, 0x70); + let region = Region::new_2d(0, 0, SIDE, SIDE); + source + .replace_region(region, 0, 0, &texels, SIDE * 4, 0) + .unwrap(); + let kept = pages.bytes(); + // The proof: a kernel that writes the texture binds the texture itself, its writes dropped. + let before = device.work_counts(); + let status = invert_texels(&device, &state, (&source, &texture), None); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(after.read_twin_slot_reads, before.read_twin_slot_reads); + assert!(pages.bytes() == kept, "a kernel's writes leave the pages"); + // Bound without the proof, the twin's write is refused by the guard. + (device.shared().read_twin_unproven).store(true, Ordering::Relaxed); + let before = device.work_counts(); + let status = invert_texels(&device, &state, (&source, &texture), None); + let after = device.work_counts(); + let seen = ( + status, + after.read_twin_slot_reads - before.read_twin_slot_reads, + after.read_twin_writes_refused - before.read_twin_writes_refused, + ); + eprintln!("READ-TWIN: a texture twin bound unproven: (status, slot reads, refused) {seen:?}"); + assert_eq!( + seen, + (CommandBufferStatus::Error, 1, 1), + "the command buffer fails: (status, twin slot reads, writes refused)" + ); + assert!(pages.bytes() == kept, "the guard keeps the pages"); + // The negative control: with the guard off too, the kernel's writes reach the pages. + (device.shared().read_twin_unguarded).store(true, Ordering::Relaxed); + let status = invert_texels(&device, &state, (&source, &texture), None); + (device.shared().read_twin_unguarded).store(false, Ordering::Relaxed); + (device.shared().read_twin_unproven).store(false, Ordering::Relaxed); + assert_eq!(status, CommandBufferStatus::Completed); + assert!( + pages.bytes()[..(SIDE * SIDE * 4) as usize] == inverted(&texels, SIDE * 4)[..], + "the pages hold the kernel's texels" + ); + drop((texture, source, state, buffer)); +} + +/// One command buffer that clears `target` and draws a triangle over it sampling `source` +/// (`examples/runtime_examples.ll`'s `sampled_fragment`), after a blit fill of `fill`'s buffer +/// and bytes where given, to completion: its status. +fn draw_sampled( + device: &Device, + (source, target): (&Texture, &Texture), + fill: Option<(&Buffer, std::ops::Range, u8)>, +) -> CommandBufferStatus { + let state = super::encoder_holds::render_state( + device, + "examples/runtime_examples.ll", + "colored_vertex", + "sampled_fragment", + ); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + if let Some((buffer, bytes, value)) = fill { + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encoder.fill_buffer(buffer, bytes, value).unwrap(); + encoder.end_encoding().unwrap(); + } + let pass = super::encoder_holds::pass(target); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&state).unwrap(); + let positions = [-1.0f32, -1.0, 3.0, -1.0, -1.0, 3.0]; + let positions = super::encoder_holds::bytes_of(&positions, f32::to_le_bytes); + let colors = super::encoder_holds::bytes_of(&[1.0f32; 12], f32::to_le_bytes); + encoder.set_vertex_bytes(&positions, 0).unwrap(); + encoder.set_vertex_bytes(&colors, 1).unwrap(); + encoder.set_fragment_texture(Some(source), 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + command_buffer.status() +} + +/// `target`'s `SIDE` x `SIDE` texels after a draw sampling `source` (`draw_sampled`, no fill). +fn sampled(device: &Device, source: &Texture, target: &Texture) -> Vec { + let status = draw_sampled(device, (source, target), None); + assert_eq!(status, CommandBufferStatus::Completed); + square_texels(target) +} + +/// The `SIDE` x `SIDE` target a draw samples a texture into. +fn draw_target(device: &Device) -> Texture { + let mut plain = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + plain.usage = TextureUsage::RENDER_TARGET; + plain.resource_options = ResourceOptions::shared(); + device.new_texture(&plain).unwrap() +} + +/// A `BGRA8Unorm` texture of the device's own, `width` x `height`, holding `bytes`'s texels in +/// rows `row` bytes apart: what a draw samples there is what it must sample through a twin over +/// the same bytes. +fn reference(device: &Device, (width, height, row): (u64, u64, u64), bytes: &[u8]) -> Texture { + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, width, height, false); + descriptor.resource_options = ResourceOptions::shared(); + let texture = device.new_texture(&descriptor).unwrap(); + let region = Region::new_2d(0, 0, width, height); + let texels = &bytes[..(row * height) as usize]; + (texture.replace_region(region, 0, 0, texels, row, 0)).unwrap(); + texture +} + +/// A draw samples `texture` (`BGRA8Unorm`, `width` x `height`, rows `row` bytes apart over +/// `buffer`'s bytes, of `pages`), which took a read twin: through its twin, the commit comparing +/// nothing; after a fill of the buffer in the same command buffer, through the texture itself, +/// the fill read back; and the next command buffer through its twin again. +fn sampled_in_place( + device: &Device, + (pages, buffer): (&Pages, &Buffer), + texture: &Texture, + (width, height, row): (u64, u64, u64), +) { + let target = draw_target(device); + let own = reference(device, (width, height, row), &pages.bytes()); + let expected = sampled(device, &own, &target); + let before = device.work_counts(); + let drawn = sampled(device, texture, &target); + let after = device.work_counts(); + assert_eq!(after.read_twin_slot_reads - before.read_twin_slot_reads, 1); + assert_eq!(compared(&before, &after), [0, 0, 0], "nothing compared"); + eprintln!( + "READ-TWIN: a draw sampling a {width}x{height} texture over a buffer of bit 24: copies \ + in compared {:?} (copies, bytes, threads)", + compared(&before, &after) + ); + assert!(drawn == expected, "the pages' texels sampled"); + // A fill of the buffer, then the draw, in one command buffer: it samples the texture itself, + // the fill read back. + let bytes = row * height; + let filled = vec![0x5a; bytes as usize]; + let own = reference(device, (width, height, row), &filled); + let expected_filled = sampled(device, &own, &target); + let kept = pages.bytes(); + let before = device.work_counts(); + let fill = Some((buffer, 0..bytes, 0x5a)); + let status = draw_sampled(device, (texture, &target), fill); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(after.read_twin_slot_reads, before.read_twin_slot_reads); + assert_eq!( + after.read_twin_reads_after_writes - before.read_twin_reads_after_writes, + 1 + ); + assert!( + square_texels(&target) == expected_filled, + "the fill read back" + ); + assert!(pages.bytes() == kept, "the fill never reaches the pages"); + assert!( + sampled(device, texture, &target) == expected, + "the next command buffer samples the pages" + ); + assert_eq!(device.work_counts().read_twin_writes_refused, 0); +} + +#[test] +fn a_private_bit_buffer_s_texture_is_sampled_in_place_by_a_draw() { + let pages = Pages::new(SMALL, 19); + let Some(device) = device(None) else { + return; + }; + let buffer = pages.private_bit_buffer(&device, None); + let before = device.work_counts(); + let shape = (PixelFormat::BGRA8Unorm, SIDE, SIDE); + let texture = texture_over(&buffer, shape, TextureUsage::SHADER_READ); + let after = device.work_counts(); + assert_eq!( + after.read_twin_textures_made - before.read_twin_textures_made, + 1, + "the texture's twin made, in place" + ); + sampled_in_place(&device, (&pages, &buffer), &texture, (SIDE, SIDE, SIDE * 4)); + drop((texture, buffer)); +} + +/// The words a kernel reads at a slot: `count` floats, each a multiple of a quarter. +fn quarters(count: usize) -> Vec { + (0..count) + .flat_map(|at| (at as f32 * 0.25).to_le_bytes()) + .collect() +} + +/// What `scale_and_offset` writes for `input`'s floats, scaled by 2: `input[i] * 2 + i`. +fn scaled(input: &[u8]) -> Vec { + (input.as_chunks::<4>().0.iter().enumerate()) + .flat_map(|(at, word)| (f32::from_le_bytes(*word) * 2.0 + at as f32).to_le_bytes()) + .collect() +} + +/// How many floats a kernel scales. +const FLOATS: usize = 1024; + +/// Commit one command buffer that runs `examples/runtime_examples.ll`'s `scale_and_offset` over +/// `FLOATS` threads, reading `input` at buffer 0 and writing `output` at buffer 1, scaled by 2, +/// after a blit fill of `fill`'s buffer and bytes where given, wait for it, and answer its status. +fn scale( + device: &Device, + (input, output): (&Buffer, &Buffer), + fill: Option<(&Buffer, std::ops::Range, u8)>, +) -> CommandBufferStatus { + let function = super::encoder_holds::library(device, "examples/runtime_examples.ll") + .new_function_with_name("scale_and_offset") + .unwrap(); + let state = device + .new_compute_pipeline_state_with_function(&function, &crate::PipelineOptions::default()) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + if let Some((buffer, bytes, value)) = fill { + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encoder.fill_buffer(buffer, bytes, value).unwrap(); + encoder.end_encoding().unwrap(); + } + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder.set_buffer(Some(input), 0, 0).unwrap(); + encoder.set_buffer(Some(output), 0, 1).unwrap(); + encoder.set_bytes(&2.0f32.to_le_bytes(), 2).unwrap(); + encoder + .dispatch_threads(Size::new(FLOATS as u64, 1, 1), Size::new(64, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + command_buffer.status() +} + +#[test] +fn a_kernel_reading_a_private_bit_buffer_at_a_slot_reads_its_pages_in_place() { + let pages = Pages::new(SMALL, 23); + pages.write(0, &quarters(FLOATS)); + let Some(device) = device(None) else { + return; + }; + let buffer = pages.private_bit_buffer(&device, None); + assert!(buffer.read_twin().is_some(), "a twin made"); + let output = own(&device, FLOATS * 4); + // Read through its twin: the pages' floats, the copy compared nowhere. + let before = device.work_counts(); + let status = scale(&device, (&buffer, &output), None); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(after.read_twin_slot_reads - before.read_twin_slot_reads, 1); + assert_eq!(compared(&before, &after), [0, 0, 0], "nothing compared"); + eprintln!( + "READ-TWIN: a kernel reading a buffer of bit 24 at a slot: copies in compared {:?} \ + (copies, bytes, threads)", + compared(&before, &after) + ); + let expected = scaled(&pages.bytes()[..FLOATS * 4]); + assert!( + contents(&output, FLOATS * 4) == expected, + "the pages' floats" + ); + // A fill of the buffer, then the kernel, in one command buffer: it reads the copy, the fill + // read back, and the commit compares the copy. + let kept = pages.bytes(); + let before = device.work_counts(); + let fill = Some((&buffer, 0..(FLOATS * 4) as u64, 0x40)); + let status = scale(&device, (&buffer, &output), fill); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(after.read_twin_slot_reads, before.read_twin_slot_reads); + assert_eq!( + after.read_twin_reads_after_writes - before.read_twin_reads_after_writes, + 1 + ); + assert_eq!(compared(&before, &after)[0], 1, "its copy compared"); + let filled = vec![0x40; FLOATS * 4]; + assert!( + contents(&output, FLOATS * 4) == scaled(&filled), + "the fill read back" + ); + assert!(pages.bytes() == kept, "the fill never reaches the pages"); + // The next command buffer reads the pages in place again. + let status = scale(&device, (&buffer, &output), None); + assert_eq!(status, CommandBufferStatus::Completed); + assert!( + contents(&output, FLOATS * 4) == expected, + "the pages read again" + ); + assert_eq!(device.work_counts().read_twin_writes_refused, 0); + drop((output, buffer)); +} + +#[test] +fn a_buffer_twin_bound_without_the_slots_proof_is_refused_and_would_reach_the_pages() { + let pages = Pages::new(SMALL, 29); + let Some(device) = device(None) else { + return; + }; + let buffer = pages.private_bit_buffer(&device, None); + assert!(buffer.read_twin().is_some(), "a twin made"); + let input = own(&device, FLOATS * 4); + let floats = quarters(FLOATS); + // SAFETY: the buffer's bytes, which no command uses now. + unsafe { + let at = input.contents().unwrap().as_ptr(); + std::ptr::copy_nonoverlapping(floats.as_ptr(), at, floats.len()); + } + let kept = pages.bytes(); + // The proof: a kernel that writes the buffer at a slot binds the buffer itself, its writes + // dropped. + let before = device.work_counts(); + let status = scale(&device, (&input, &buffer), None); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(after.read_twin_slot_reads, before.read_twin_slot_reads); + assert!(pages.bytes() == kept, "a kernel's writes leave the pages"); + // Bound without the proof, the twin's write is refused by the guard. + (device.shared().read_twin_unproven).store(true, Ordering::Relaxed); + let before = device.work_counts(); + let status = scale(&device, (&input, &buffer), None); + let after = device.work_counts(); + assert_eq!( + status, + CommandBufferStatus::Error, + "the command buffer fails" + ); + assert_eq!(after.read_twin_slot_reads - before.read_twin_slot_reads, 1); + assert_eq!( + after.read_twin_writes_refused - before.read_twin_writes_refused, + 1 + ); + assert!(pages.bytes() == kept, "the guard keeps the pages"); + // The negative control: with the guard off too, the kernel's writes reach the pages. + (device.shared().read_twin_unguarded).store(true, Ordering::Relaxed); + let status = scale(&device, (&input, &buffer), None); + (device.shared().read_twin_unguarded).store(false, Ordering::Relaxed); + (device.shared().read_twin_unproven).store(false, Ordering::Relaxed); + assert_eq!(status, CommandBufferStatus::Completed); + assert!( + pages.bytes()[..FLOATS * 4] == scaled(&floats)[..], + "bound without the proof and unguarded, a kernel's writes reach the pages" + ); + drop((input, buffer)); +} diff --git a/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs b/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs index fbd1b564c..63d46815e 100644 --- a/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs +++ b/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs @@ -137,7 +137,7 @@ impl Texture { /// takes the shadow: the texture's image lacks the binding's usage, and so does the /// texture's own (Metal's) usage, where `binding_view` refuses the image /// (`UndeclaredTextureUsage`). - pub(in crate::texture) fn needs_usage_shadow(&self, storage: bool) -> bool { + pub(crate) fn needs_usage_shadow(&self, storage: bool) -> bool { let (vk, metal) = match storage { true => (ImageUsageFlags::STORAGE, TextureUsage::SHADER_WRITE), false => (ImageUsageFlags::SAMPLED, TextureUsage::SHADER_READ), diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index b842082d4..dc73f28b9 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -490,6 +490,9 @@ pub(crate) struct Counters { read_twin_blit_reads: AtomicU64, read_twin_reads_after_writes: AtomicU64, read_twin_writes_refused: AtomicU64, + read_twin_textures_made: AtomicU64, + read_twin_textures_not_in_place: AtomicU64, + read_twin_slot_reads: AtomicU64, host_ram_copies: AtomicU64, host_ram_copy_bytes: AtomicU64, host_ram_copy_dispatches: AtomicU64, @@ -4495,6 +4498,29 @@ impl Counters { (self.read_twin_writes_refused).fetch_add(1, Ordering::Relaxed); } + /// A texture over a no-copy buffer with a read twin took a read twin of its own, in place + /// over the twin's bytes (`made`), or took none as the twin's texture would not lie in place + /// (`read_twin.rs`). + pub(crate) fn read_twin_texture(&self, made: bool) { + match made { + true => &self.read_twin_textures_made, + false => &self.read_twin_textures_not_in_place, + } + .fetch_add(1, Ordering::Relaxed); + } + + /// Whether any buffer took a read twin (`read_twin.rs`), a texture's twin among them: else no + /// command's slots look for one. + pub(crate) fn read_twins_any(&self) -> bool { + self.read_twins_made.load(Ordering::Relaxed) > 0 + } + + /// A command's texture or buffer slot read what it binds through a read twin, in place + /// (`read_twin.rs`). + pub(crate) fn read_twin_slot_read(&self) { + (self.read_twin_slot_reads).fetch_add(1, Ordering::Relaxed); + } + /// A batch's completion dropped `bytes` the GPU changed in copies of pages the process /// cannot write, taking them out of the copies (`copied.rs`). pub(crate) fn copied_dropped(&self, bytes: u64) { @@ -9082,6 +9108,18 @@ pub struct WorkCounts { /// The commands an encoder refused because their uses write a read twin: never, but for a /// defect of the runtime's, which the refusal keeps from reaching the pages. pub read_twin_writes_refused: u64, + /// The read twins of textures made (`read_twin.rs`): of a program's texture over the bytes of + /// a no-copy buffer with a read twin, the runtime's texture over the twin's bytes in place, + /// which the slots that only read the texture bind instead. + pub read_twin_textures_made: u64, + /// The textures over a no-copy buffer with a read twin that took no read twin because the + /// twin's texture would not lie in place over its bytes (a shadow, pending or refused by the + /// device's check of textures in place). + pub read_twin_textures_not_in_place: u64, + /// The slot bindings made through a read twin, in place, one per slot and command (a draw or + /// a dispatch): a texture slot's through its texture's twin, a buffer slot's through its + /// buffer's. + pub read_twin_slot_reads: u64, /// The host bytes the live copied host buffers' bases hold (a gauge): their tags, a 64th of /// each copy's length, and the bytes of those kept in host memory. pub copied_base_host_bytes: u64, @@ -11562,6 +11600,10 @@ impl Device { read_twin_reads_after_writes: (counters.read_twin_reads_after_writes) .load(Ordering::Relaxed), read_twin_writes_refused: counters.read_twin_writes_refused.load(Ordering::Relaxed), + read_twin_textures_made: counters.read_twin_textures_made.load(Ordering::Relaxed), + read_twin_textures_not_in_place: (counters.read_twin_textures_not_in_place) + .load(Ordering::Relaxed), + read_twin_slot_reads: counters.read_twin_slot_reads.load(Ordering::Relaxed), copied_base_host_bytes, copied_base_device_bytes, copied_base_host_blocks: self.shared().copied.base_host_blocks(), diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 571ad6b7a..52ae893c4 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2275; +pub const RUNTIME_VERSION: u32 = 2276; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index cefa8bc0c..44025578e 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3362,6 +3362,9 @@ field metal2vulkan-runtime::WorkCounts.rate_map_runs_every_region pub rate_map_r field metal2vulkan-runtime::WorkCounts.rate_map_straddling_triangles pub rate_map_straddling_triangles: u64 field metal2vulkan-runtime::WorkCounts.read_twin_blit_reads pub read_twin_blit_reads: u64 field metal2vulkan-runtime::WorkCounts.read_twin_reads_after_writes pub read_twin_reads_after_writes: u64 +field metal2vulkan-runtime::WorkCounts.read_twin_slot_reads pub read_twin_slot_reads: u64 +field metal2vulkan-runtime::WorkCounts.read_twin_textures_made pub read_twin_textures_made: u64 +field metal2vulkan-runtime::WorkCounts.read_twin_textures_not_in_place pub read_twin_textures_not_in_place: u64 field metal2vulkan-runtime::WorkCounts.read_twin_writes_refused pub read_twin_writes_refused: u64 field metal2vulkan-runtime::WorkCounts.read_twins_made pub read_twins_made: u64 field metal2vulkan-runtime::WorkCounts.read_twins_uncontained pub read_twins_uncontained: u64 diff --git a/docs/API.md b/docs/API.md index 30406ddd2..aaf2be085 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3708,14 +3708,18 @@ bound. them (`read_twins_made`), where they import in place and the device's policy contains every access (no twin otherwise: `read_twins_unimported`, `read_twins_uncontained`), while no earlier command of its command buffer may have written the buffer (`read_twin_blit_reads`; after one, - `read_twin_reads_after_writes`, the copy); no command writes the twin, and one that would fails - its command buffer (`read_twin_writes_refused`). On macOS the pages are imported through a - read-only view of them. A - buffer's or heap's rebind is copied the same way, - its heap's bound textures and its images in place made again over the copy, and a buffer's - rebind to bytes at another offset in their page under a texture planned at the old one is a copy - laid out there (the detail says which). A buffer made over exactly the bytes (the same first - byte and length) a live copied buffer was made over, of either storage mode, lies in its copy, + `read_twin_reads_after_writes`, the copy). So does a texture slot of an encoder's own draw or + dispatch that only reads a texture over the buffer's rows, through the texture's read twin over + the twin's bytes, made with it where it lies in place (`read_twin_textures_made`, + `read_twin_textures_not_in_place`, `read_twin_slot_reads`), and a buffer slot of such a draw or + dispatch that only reads the buffer, of a command that reaches no memory through a root table + (`read_twin_slot_reads`). No command writes a twin, and one that would fails its command buffer + (`read_twin_writes_refused`). On macOS the pages are imported through a read-only view of them. + A buffer's or heap's rebind is copied the same way, its heap's bound textures and its images in + place made again over the copy, and a buffer's rebind to bytes at another offset in their page + under a texture planned at the old one is a copy laid out there (the detail says which). A + buffer made over exactly the bytes (the same first byte and length) a live copied buffer was + made over, of either storage mode, lies in its copy, as one over a live import's bytes lies in that import, and makes no copy of its own (`copied_host_buffers_shared`, the gate not asked; announced, the detail saying it lies in the live copy): one memory, ordered as one resource's diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index de7ed0b14..bca8c580c 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -1015,11 +1015,16 @@ driver's. Each is open work. buffer over the same pages, outside the Metal address space, which no command writes (an encoder refuses a command that would, failing its command buffer: `WorkCounts::read_twin_writes_refused`). A blit's copy out of the buffer, into a buffer or a texture, reads the pages through the twin, - so a command buffer that reads the buffer only so uses none of its copy and its commit compares - none of it (`WorkCounts::read_twin_blit_reads`, `copied_copy_ins_compared`); after a command of - its command buffer that may have written the buffer, its copy is read instead, so the command - buffer reads its own dropped write back (`read_twin_reads_after_writes`). Every other use reads - the copy as above. + and so does a texture slot of an encoder's own draw or dispatch that only reads the program's + texture over the buffer's rows (every use the plan lists reads, every descriptor is that image), + through the texture's own read twin over the twin's bytes, made with it where the device's check + of textures in place passed (`read_twin_textures_made`, `read_twin_slot_reads`), and a buffer + slot of such a draw or dispatch, of a command that reaches no memory through a root table, that + only reads the buffer (`read_twin_slot_reads`); a command buffer that reads the buffer only so + uses none of its copy and its commit compares none of it (`WorkCounts::read_twin_blit_reads`, + `copied_copy_ins_compared`); after a command of its command buffer that may have written the + buffer, its copy is read instead, so the command buffer reads its own dropped write back + (`read_twin_reads_after_writes`). Every other use reads the copy as above. - **A function linked from a module that declares function constants** is refused (`Unsupported{Linking; NotImplemented}` at a surviving call to the stub, `canon::link`), keyed on