diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index f46925c3f..2ab398890 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -204,7 +204,9 @@ not yet in a group (`held_for_room`); the command buffers of the runtime's own i the Managed buffers' copy-ins (`runtime_command_buffers`), and the GPU's time they ran, on timestamps of their own (`runtime_command_buffer_gpu_nanos`); the copies of textures over a buffer that no linear image holds are split by cause -(`over_copies_pitch` and the rest, in Textures below); +(`over_copies_pitch` and the rest, in Textures below); the exported blocks a public call handed +out a device address of, each counted at the first (`exported_blocks_addressed`, the exported +block's rule in Textures below), 0 where none went out; `gauges()` are live counts per kind of resource, every one zero after teardown, and `handles_out`, 1 while a handle of the device is out (Teardown). They are relaxed atomics, always on. What an encoder's commands count arrives when the encoder ends. @@ -656,7 +658,8 @@ handle may outlive the block, unused. Neither `BlockMappings` hook runs for an e its bytes are undefined until written, as a taken block's are. No image is made in its memory, which is dedicated to its buffer (`VUID-vkBindImageMemory-memory-10926`): a texture over a buffer in it is the counted copy, as over host memory's import, and a heap texture in it is -`Gap::HeapTexture`. +`Gap::HeapTexture`. The `Block` handle states the block's `gpu_address`, so the make counts in +`Metrics::exported_blocks_addressed` (Textures over a buffer, the exported block's rule). Once the other API's work that accessed the block has completed (work that wrote it, or that read it after a release; the consumer's own wait on the decoder), the consumer calls @@ -943,7 +946,11 @@ the Direct3D 11 texture's payload until it is freed. pointer member of an argument buffer, an address it wrote into a buffer, a pointer it made from an integer. The stored word must be a buffer's `gpu_address` plus an offset inside that buffer, and a buffer the consumer did not place at the address its guest asked for has a `gpu_address` - other than that one. A stale address, of a released buffer, can still fault the device. + other than that one. A stale address, of a released buffer, can still fault the device. An + address in an exported block is one the consumer read from rt before the commit of the command + buffer that writes through it (`Buffer::gpu_address`, or the block's own from + `Device::new_exported_block`): a write through an address made any other way does not reach + the textures over the block, whose copies in owe nothing for it (Textures over a buffer). - An app buffer too large for the consumer's map budget is copied, on drivers whose dma-buf query offers a non-host-visible type first. - A block freed before a submission used it waits on the block-maker thread for its bind, and a @@ -1423,11 +1430,20 @@ made, with no lock, and never rewritten for layouts. texture's making, the block's acquire (`Block::external_writes_done`, which `Surface::external_writes_done` makes in the copy form) or a zero fill of its range (`Device::zero_block_range`), each ahead of every command buffer committed after it, and a - submitted command's write of the texture's bytes (every such texture for a write through an - address) or another texture's copy back over them. The upload that leads the next submission - that uses the texture makes it; a submission that only reads the texture copies nothing. The - block is Private, so no host write reaches it, and the other API's writes are the consumer's - to announce by the acquire. + submitted command's write of the texture's bytes or another texture's copy back over them. A + write through an address outside the command's bound slots and declared resources changes + the bytes of every such texture whose block's address a public call handed out before that + submission, and of no other: `Buffer::gpu_address` of a buffer whose bytes shaders reach in + the block (a Managed buffer's device copy placed there included), the `Block` that + `Device::new_exported_block` answers, whose `gpu_address` states the block's address, and a + texture buffer's storage element at an index over the block's bytes. An exported surface's + block in the copy form is the surface's own, so only `Surface::buffer`'s `gpu_address` + hands it out; the planes' resource IDs reach their own images. Each such block counts once in + `Metrics::exported_blocks_addressed`. A command recorded while no texture over a buffer in an + image of its own lived is untracked, and changes every such texture's bytes. The upload that + leads the next submission that uses the texture makes the copy; a submission that only reads + the texture copies nothing. The block is Private, so no host write reaches it, and the other + API's writes are the consumer's to announce by the acquire. - Over a Managed buffer's device copy, only at Metal's own Managed events, each texture keeping one flag of each kind: in, after a `did_modify_range` over its range, by the commit that captures the range, after its copies into the device copy; and at its making, or where device diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 5fe3ff9bb..c09b5140a 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -492,8 +492,13 @@ impl crate::kept::Handle for Buffer { impl Buffer { /// `gpuAddress`: the block's device address plus the buffer's offset; of a Managed buffer with - /// a device copy, the copy block's device address plus the copy's offset. + /// a device copy, the copy block's device address plus the copy's offset. The first call that + /// answers an address in an exported block counts in + /// [`Metrics::exported_blocks_addressed`](crate::Metrics::exported_blocks_addressed): from + /// then on a write through an address makes the textures over that block owe their copies in + /// ([`Buffer::new_texture`]). pub fn gpu_address(&self) -> u64 { + BufferObject::address_out(self); BufferObject::gpu_address(self) } @@ -566,6 +571,16 @@ pub(crate) trait BufferObject { } } + /// A public call put the bytes shaders reach (a Managed buffer's device copy, where it has + /// one) where a shader may write them outside every bound slot: their block is marked where it + /// is exported ([`Block::address_out`]). + fn address_out(&self) { + let inner = self.object(); + (inner.copy.as_ref()) + .map_or(&inner.block, |copy| ©.block) + .address_out(); + } + /// [`Buffer::did_modify_range`]. fn did_modify_range(&self, start: u64, length: u64) -> Result<(), Error> { let inner = self.object(); diff --git a/crates/metal2vulkan-runtime/src/command.rs b/crates/metal2vulkan-runtime/src/command.rs index da0cf8d22..11912e463 100644 --- a/crates/metal2vulkan-runtime/src/command.rs +++ b/crates/metal2vulkan-runtime/src/command.rs @@ -1525,7 +1525,7 @@ impl Building { ) { match self.copies_over() { true => self.last().overs.after(reached, unbound), - false => self.last().overs.after([], true), + false => self.last().overs.untracked(), } } diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index c1faab90e..d09084bad 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -260,6 +260,8 @@ pub(crate) enum Metric { SurfacesInPlace, /// [`Metrics::surfaces_copied`]. SurfacesCopied, + /// [`Metrics::exported_blocks_addressed`]. + ExportedBlocksAddressed, /// [`Metrics::texture_clear_barriers`]. TextureClearBarriers, /// [`Metrics::attachment_loop_reads`]. @@ -318,6 +320,7 @@ const METRIC_ORDER: [Metric; METRICS] = [ Metric::ExternalReleases, Metric::SurfacesInPlace, Metric::SurfacesCopied, + Metric::ExportedBlocksAddressed, Metric::TextureClearBarriers, Metric::AttachmentLoopReads, Metric::SparseBinds, @@ -687,6 +690,7 @@ struct Atomics { external_releases: AtomicU64, surfaces_in_place: AtomicU64, surfaces_copied: AtomicU64, + exported_blocks_addressed: AtomicU64, surface_waits: AtomicU64, surface_wait_nanos: AtomicU64, surface_wait_max_nanos: AtomicU64, @@ -844,6 +848,7 @@ impl Counters { Metric::ExternalReleases => &a.external_releases, Metric::SurfacesInPlace => &a.surfaces_in_place, Metric::SurfacesCopied => &a.surfaces_copied, + Metric::ExportedBlocksAddressed => &a.exported_blocks_addressed, Metric::TextureClearBarriers => &a.texture_clear_barriers, Metric::AttachmentLoopReads => &a.attachment_loop_reads, Metric::SparseBinds => &a.sparse_binds, @@ -1707,6 +1712,7 @@ impl Counters { external_releases: a.external_releases.load(Relaxed), surfaces_in_place: a.surfaces_in_place.load(Relaxed), surfaces_copied: a.surfaces_copied.load(Relaxed), + exported_blocks_addressed: a.exported_blocks_addressed.load(Relaxed), surface_waits: a.surface_waits.load(Relaxed), surface_wait_nanos: a.surface_wait_nanos.load(Relaxed), surface_wait_max_nanos: a.surface_wait_max_nanos.load(Relaxed), @@ -2506,6 +2512,14 @@ pub struct Metrics { /// ([`Device::new_exported_surface`](crate::Device::new_exported_surface), /// [`SurfaceForm::Copy`](crate::SurfaceForm::Copy)). pub surfaces_copied: u64, + /// Exported blocks a public call handed out a device address of, each counted at the first: + /// [`Buffer::gpu_address`](crate::Buffer::gpu_address) answering an address in one, + /// [`Device::new_exported_block`](crate::Device::new_exported_block), whose handle states its + /// block's, and a texture buffer's storage element at an index over its bytes. A write + /// through an address makes the textures over an exported block owe their copies in only + /// once its address went out; 0 where none went out, as for a surface's block in the copy + /// form whose buffer's address nothing read. + pub exported_blocks_addressed: u64, /// Waits of surfaces made in place for the submission that moves their planes to the general /// layout ([`Surface::wait_until_ready`](crate::Surface::wait_until_ready)), on the /// consumer's thread: one per call. The make diff --git a/crates/metal2vulkan-runtime/src/export.rs b/crates/metal2vulkan-runtime/src/export.rs index 50f98c6dd..5d38019fb 100644 --- a/crates/metal2vulkan-runtime/src/export.rs +++ b/crates/metal2vulkan-runtime/src/export.rs @@ -202,7 +202,10 @@ impl Device { /// No image is made in its memory, which is dedicated to its buffer /// (`VUID-vkBindImageMemory-memory-10926`): a texture over a buffer in it is copied, as over /// host memory's import ([`Buffer::new_texture`](crate::Buffer::new_texture)), and it is no - /// heap's memory ([`Device::new_heap_texture`]). + /// heap's memory ([`Device::new_heap_texture`]). The block's handle states its device address + /// ([`BlockInfo::gpu_address`](crate::BlockInfo::gpu_address)), so the make counts in + /// [`Metrics::exported_blocks_addressed`](crate::Metrics::exported_blocks_addressed), as + /// [`Buffer::gpu_address`](crate::Buffer::gpu_address) does. /// /// Err: [`Limit::NoExport`] where the device does not export the handle; /// [`Limit::ExportType`] for a dma-buf on a device without the foreign queue family, or where @@ -215,6 +218,18 @@ impl Device { &self, handle: ExportHandle, len: u64, + ) -> Result<(Block, Export), Error> { + let (block, export) = self.exported_block(handle, len)?; + block.held()?.1.address_out(); + Ok((block, export)) + } + + /// An exported block, as [`Device::new_exported_block`] makes it, whose address no call has + /// handed out yet: an exported surface's in the copy form, whose handle the surface keeps. + pub(crate) fn exported_block( + &self, + handle: ExportHandle, + len: u64, ) -> Result<(Block, Export), Error> { let started = crate::host_time(); let core = self.core(); diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 7c9a95531..b82e0e616 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -495,12 +495,17 @@ pub(crate) struct Block { /// this one, so the block-maker thread destroys the sparse buffer before it frees any of /// their memory, the last of them holding the release. _chunks: Vec, + /// Of an exported block: set once a public call hands out a device address of its memory + /// ([`address_out`](Self::address_out)), which the textures over it read at each submission + /// (`crate::over::ExportedOvers`). + pub(crate) addressed: Option>, } impl Block { pub(crate) fn new(memory: Memory, core: Arc) -> Block { note(&core, &memory); Block { + addressed: memory.exported().then(Arc::default), memory, core, release: Mutex::new(None), @@ -509,6 +514,17 @@ impl Block { } } + /// A public call handed out a device address of the block's memory, where a shader may write + /// through it outside every bound slot: an exported block is marked, and counted at the first + /// (`Metrics::exported_blocks_addressed`). + pub(crate) fn address_out(&self) { + let marked = + (self.addressed.as_ref()).is_some_and(|flag| !flag.swap(true, Ordering::Relaxed)); + if marked { + self.core.counters.count(Metric::ExportedBlocksAddressed); + } + } + /// An import's block ([`import`]), whose `release` runs once its memory is freed. pub(crate) fn imported(memory: Memory, core: Arc, release: Option) -> Block { note(&core, &memory); @@ -518,6 +534,7 @@ impl Block { release: Mutex::new(release), _under: None, _chunks: Vec::new(), + addressed: None, } } @@ -530,6 +547,7 @@ impl Block { release: Mutex::new(None), _under: Some(under), _chunks: Vec::new(), + addressed: None, } } } @@ -2336,6 +2354,7 @@ pub(crate) fn sparse_block( release: Mutex::new(None), _under: None, _chunks: chunks, + addressed: None, } } diff --git a/crates/metal2vulkan-runtime/src/over.rs b/crates/metal2vulkan-runtime/src/over.rs index 2996b6191..e3e4d2f65 100644 --- a/crates/metal2vulkan-runtime/src/over.rs +++ b/crates/metal2vulkan-runtime/src/over.rs @@ -5,7 +5,8 @@ //! `vkCmdCopyBufferToImage` or `vkCmdCopyImageToBuffer` region a texture, with no CPU copy. Over a //! Managed buffer's device copy, only Metal's Managed events copy ([`ManagedOvers`]); over any //! other buffer, the Shared rules, but for a buffer in an exported block, whose leading copy waits -//! for an event that changes its bytes ([`ExportedOvers`]): +//! for an event that changes its bytes, a write through an address among them only once an address +//! of the block went out ([`ExportedOvers`]): //! //! - **In, once a submission.** The upload that leads a submission copies the bytes into the //! image of every such texture a segment of the submission uses before any command of the @@ -56,7 +57,7 @@ use crate::texture::{Image, OverCopy, TextureInner, TextureObject}; use ash::vk; use std::collections::{HashMap, HashSet}; use std::hash::BuildHasherDefault; -use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed}; use std::sync::{Arc, Mutex, Weak}; /// Bytes of memory a resource lies in: `start..end` of block `block`, from the block's first @@ -138,6 +139,9 @@ pub(crate) struct Overs { /// A command of the segment wrote through an address outside its resources, or was recorded /// while no such texture lived, its writes untracked. unbound: bool, + /// A command of the segment was recorded while no such texture lived, its writes untracked + /// ([`untracked`](Self::untracked)). + untracked: bool, /// The textures used whose images a command wrote since their bytes last went back /// (`Used::buffer_stale`). ahead: usize, @@ -166,6 +170,7 @@ pub(crate) struct Leans { wrote: Written, backed: Vec<(Span, u32)>, unbound: bool, + untracked: bool, } impl Leans { @@ -185,6 +190,7 @@ impl Leans { self.wrote.extend(&later.wrote); self.backed.extend_from_slice(&later.backed); self.unbound |= later.unbound; + self.untracked |= later.untracked; } } @@ -365,6 +371,13 @@ impl Overs { } } + /// A command recorded while no such texture lived: its writes, untracked, count as a write + /// through an address that reaches every block. + pub(crate) fn untracked(&mut self) { + self.after([], true); + self.untracked = true; + } + /// Whether a texture the segment used has an image ahead of its buffer: a command wrote it /// since its bytes last went back. While none has, a command's reads of buffers owe nothing. pub(crate) fn ahead(&self) -> bool { @@ -597,6 +610,9 @@ struct Exported { id: u32, image: vk::Image, memory: Span, + /// Whether a public call handed out an address of its block's memory + /// (`crate::memory::Block::address_out`): only then does a write through an address reach it. + addressed: Arc, /// An event changed its bytes since its image last took them: the commit number from which /// every command buffer runs behind that event (0 for a submitted write). owed: Option, @@ -609,17 +625,28 @@ struct Exported { /// by the upload that leads the next submission that leans on the leading copy for it, and a /// submission that only reads it copies nothing. The events: the texture's making; an acquire or a /// zero fill of the block, which go ahead of every command buffer committed after them; and a -/// submitted command's write of memory its texels lie in, a write through an address (every -/// texture), or another texture's copy back over those bytes. Within a segment the Shared rules -/// stand. +/// submitted command's write of memory its texels lie in, a write through an address once an +/// address of the block went out (every such texture), or another texture's copy back over those +/// bytes. An address goes out by a public call alone: [`crate::Buffer::gpu_address`] of a buffer +/// whose bytes shaders reach in the block (a Managed buffer's device copy included), the handle +/// [`crate::Device::new_exported_block`] answers, which states the block's address, and a texture +/// buffer's storage element at an index over such bytes. A surface's block in the copy form is +/// the surface's own, so its address goes out only through its buffer +/// ([`crate::Surface::buffer`]). Within a segment the Shared rules stand. #[derive(Default)] pub(crate) struct ExportedOvers { entries: Vec, } impl ExportedOvers { - /// Keeps `texture`, whose copy is `copy`, owing its first copy in. - pub(crate) fn add(&mut self, texture: &Arc, copy: &OverCopy) { + /// Keeps `texture`, whose copy is `copy` and whose block's flag is `addressed`, owing its + /// first copy in. + pub(crate) fn add( + &mut self, + texture: &Arc, + copy: &OverCopy, + addressed: Arc, + ) { self.entries .retain(|entry| entry.texture.strong_count() > 0); self.entries.push(Exported { @@ -627,6 +654,7 @@ impl ExportedOvers { id: texture.id(), image: copy.image, memory: copy.memory, + addressed, owed: Some(0), }); } @@ -665,13 +693,17 @@ impl ExportedOvers { } /// A submission went whose segments wrote `leans`: each texture whose bytes they changed owes - /// its copy in to every later submission. + /// its copy in to every later submission. A write through an address reaches the texture's + /// bytes only where an address of its block went out before this submission; the flag read + /// here covers every call made before the commits it holds, and Metal leaves undefined an + /// address taken after a commit and written for that command buffer to read. pub(crate) fn wrote(&mut self, leans: &Leans) { self.entries .retain(|entry| entry.texture.strong_count() > 0); for entry in &mut self.entries { let memory = entry.memory; - let changed = leans.unbound + let changed = leans.untracked + || (leans.unbound && entry.addressed.load(Relaxed)) || leans.wrote.meets(memory) || (leans.backed.iter()).any(|&(span, by)| span.meets(memory) && by != entry.id); if changed { diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index 4d1e36afa..78622b71f 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -2130,7 +2130,7 @@ impl RenderCommandEncoder { if !buffer.is_of(building.device.core()) { return Err(Error::Refused(Refusal::OtherDevice)); } - if buffer.gpu_address().wrapping_add(offset) % 2 != 0 { + if BufferObject::gpu_address(buffer).wrapping_add(offset) % 2 != 0 { return Err(Error::Refused(Refusal::TessellationFactorOffset { offset })); } // SAFETY: the encoder holds the borrow, and it ends before its command buffer @@ -2499,7 +2499,7 @@ impl RenderCommandEncoder { } = call { let range = range.map_or(self.facts.nil.2, |(buffer, offset)| { - buffer.gpu_address().wrapping_add(offset) + BufferObject::gpu_address(buffer).wrapping_add(offset) }); let draws = &state.inner.compiled.draws; let places = (&mut self.push, &mut self.blocks); @@ -2790,7 +2790,7 @@ impl RenderCommandEncoder { return Err(self.interrupt_refused()); } let part = self.execution_part(buffer)?; - let range = range_buffer.gpu_address().wrapping_add(offset); + let range = BufferObject::gpu_address(range_buffer).wrapping_add(offset); let counts = self.execution_counts(range, buffer.size(), part)?; let call = Call::Commands { buffer, diff --git a/crates/metal2vulkan-runtime/src/submit.rs b/crates/metal2vulkan-runtime/src/submit.rs index ff5596d95..226c415e1 100644 --- a/crates/metal2vulkan-runtime/src/submit.rs +++ b/crates/metal2vulkan-runtime/src/submit.rs @@ -593,9 +593,14 @@ impl Work { } /// Keeps `texture`, over a buffer in an exported block in an image of its own whose copy is - /// `copy` ([`ExportedOvers`]). - pub(crate) fn exported_over(&self, texture: &Arc, copy: &OverCopy) { - self.lock().exported.add(texture, copy); + /// `copy`, the block's flag `addressed` ([`ExportedOvers`]). + pub(crate) fn exported_over( + &self, + texture: &Arc, + copy: &OverCopy, + addressed: Arc, + ) { + self.lock().exported.add(texture, copy, addressed); } /// Work recorded into the upload changed `range` of `block`'s bytes, ahead of every command diff --git a/crates/metal2vulkan-runtime/src/surface.rs b/crates/metal2vulkan-runtime/src/surface.rs index 3a74d85a4..d62634174 100644 --- a/crates/metal2vulkan-runtime/src/surface.rs +++ b/crates/metal2vulkan-runtime/src/surface.rs @@ -945,7 +945,7 @@ impl Device { .checked_next_multiple_of(multiple) .ok_or_else(too_long)?; let (starts, end) = lay(spec, plans, pitch).ok_or_else(too_long)?; - let (block, export) = self.new_exported_block(spec.handle, end)?; + let (block, export) = self.exported_block(spec.handle, end)?; let buffer = self.new_buffer(block.id, 0, block.len, None)?; let planes = (spec.planes.iter().zip(&starts)) .map(|(plane, &start)| { diff --git a/crates/metal2vulkan-runtime/src/tests/exported_overs.rs b/crates/metal2vulkan-runtime/src/tests/exported_overs.rs index 0dcefc47b..6025613fe 100644 --- a/crates/metal2vulkan-runtime/src/tests/exported_overs.rs +++ b/crates/metal2vulkan-runtime/src/tests/exported_overs.rs @@ -3,21 +3,76 @@ //! counted in `Metrics::over_copies` and `Metrics::over_copy_bytes`. After a fill of the buffer and //! the block's acquire, four submissions that read the texture copy it in once; a fill between //! makes one copy more, and a zero fill of the block's range one more; reads with no event between -//! copy nothing. Each read finds the bytes of the last event. +//! copy nothing. Each read finds the bytes of the last event. The block's make states its address, +//! counted in `Metrics::exported_blocks_addressed`. +//! +//! A write through an address owes such a texture its copy in only once an address of its block +//! went out. A plane of an exported surface in the copy form, read by four submissions that each +//! then write through an address into another buffer (`store_through`), is copied in once, and the +//! count of blocks whose address went out reads 0; once its buffer's `gpu_address` is read, it +//! reads 1, and each submission after the next copies the plane in again. #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { use crate::tests::command::on_device::{each_device, finished}; use crate::{ - Buffer, BufferLayout, CommandQueue, Device, ExportHandle, IndexClass, MemoryClass, - PixelFormat, StorageMode, Texture, TextureDescriptor, TexturePlace, TextureType, - TextureUsage, + Buffer, BufferLayout, CommandQueue, ComputePipelineDescriptor, ComputePipelineState, + Device, DispatchType, ExportHandle, FunctionDescriptor, IndexClass, Library, MemoryClass, + PixelFormat, PlaneSpec, Resource, ResourceUsage, StageSource, StorageMode, SurfaceForm, + SurfaceSpec, Texture, TextureDescriptor, TexturePlace, TextureType, TextureUsage, }; + use metal2vulkan_devtools::{llvm_assemble_text, AssembleError}; const WIDTH: u32 = 64; const HEIGHT: u32 = 8; const ROW: u64 = WIDTH as u64 * 4; const LEN: u64 = 1 << 16; + /// The read layout of a texture of `WIDTH` by `HEIGHT` texels. + const LAYOUT: BufferLayout = BufferLayout { + offset: 0, + bytes_per_row: ROW, + bytes_per_image: 0, + }; + + /// The opaque handle of this host. + const OPAQUE: ExportHandle = match cfg!(windows) { + true => ExportHandle::OpaqueWin32, + false => ExportHandle::OpaqueFd, + }; + + /// A kernel that loads a pointer from buffer 0, an argument buffer of one pointer member, and + /// stores each thread's position at word `gid` past it: a write through an address outside + /// its bound slots. + const STORE_THROUGH: &str = r#"; Owned synthetic kernel. +source_filename = "store_through.metal" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +%struct.Held = type { ptr addrspace(1) } + +define void @store_through(ptr addrspace(2) noundef readonly align 8 dereferenceable(8) %held, i32 noundef %gid) { +entry: + %at = getelementptr inbounds %struct.Held, ptr addrspace(2) %held, i64 0, i32 0 + %p = load ptr addrspace(1), ptr addrspace(2) %at, align 8 + %w = zext i32 %gid to i64 + %q = getelementptr inbounds i32, ptr addrspace(1) %p, i64 %w + store i32 %gid, ptr addrspace(1) %q, align 4 + ret void +} + +!air.kernel = !{!0} +!air.version = !{!5} +!air.language_version = !{!6} +!0 = !{ptr @store_through, !1, !2} +!1 = !{} +!2 = !{!3, !4} +!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !7, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Held", !"air.arg_name", !"held"} +!4 = !{i32 1, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} +!5 = !{i32 2, i32 8, i32 0} +!6 = !{!"Metal", i32 4, i32 0, i32 0} +!7 = !{i32 0, i32 8, i32 0, !"uint", !"p", !"air.indirect_argument", !8} +!8 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"p"} +"#; /// Runs `encode` in a command buffer of its own on `queue`, and waits for it. fn run(name: &str, queue: &CommandQueue, encode: impl FnOnce(&mut crate::BlitCommandEncoder)) { @@ -72,8 +127,176 @@ mod on_device { ) } + /// A dispatch of `store_through` whose argument buffer `held` holds `target`'s address. + struct Writer<'a> { + state: &'a ComputePipelineState, + held: &'a Buffer, + target: &'a Buffer, + } + + /// `count` submissions that each copy the texture into `out`, every byte of which then is + /// `byte`, and then write through an address into the writer's target, every word of which + /// then is its thread's position: the copies in each made. + fn written_reads( + name: &str, + (device, queue): (&Device, &CommandQueue), + (texture, out): (&Texture, &Buffer), + writer: &Writer<'_>, + count: usize, + byte: u8, + ) -> Vec { + let contents = out.contents().expect("Shared"); + let words = writer.target.contents().expect("Shared"); + let threads = (writer.target.length() / 4) as u32; + (0..count) + .map(|read| { + let before = device.counters().metrics().over_copies; + // SAFETY: no pending command reaches either buffer's bytes. + unsafe { + contents.as_ptr().write_bytes(0xee, out.length() as usize); + words + .as_ptr() + .write_bytes(0xff, writer.target.length() as usize); + } + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut blit = command_buffer.blit_command_encoder().expect("an encoder"); + (blit.copy_from_texture_to_buffer( + texture, + TexturePlace::default(), + [WIDTH, HEIGHT, 1], + out, + LAYOUT, + )) + .unwrap_or_else(|error| panic!("{name}: the read: {error}")); + blit.end_encoding(); + let mut compute = (command_buffer.compute_command_encoder(DispatchType::Serial)) + .expect("an encoder"); + (compute.set_compute_pipeline_state(writer.state)).expect("a state"); + (compute.set_buffer(Some(writer.held), 0, 0)).expect("the argument buffer"); + (compute.use_resource(Resource::Buffer(writer.target), ResourceUsage::WRITE)) + .expect("the target"); + (compute.dispatch_threadgroups([1, 1, 1], [threads, 1, 1])) + .unwrap_or_else(|error| panic!("{name}: the write: {error}")); + compute.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + // SAFETY: the submission has completed; nothing else reaches the bytes. + let bytes = + unsafe { std::slice::from_raw_parts(contents.as_ptr(), out.length() as usize) }; + let wrong = bytes.iter().position(|&b| b != byte); + assert_eq!(wrong, None, "{name}: read {read}: byte {byte:#x}"); + // SAFETY: as above; the target holds `threads` words, 4-byte aligned. + let written = unsafe { + std::slice::from_raw_parts(words.as_ptr().cast::(), threads as usize) + }; + let wrong = (0..threads).position(|at| written[at as usize] != at); + assert_eq!(wrong, None, "{name}: write {read} through the address"); + device.counters().metrics().over_copies - before + }) + .collect() + } + + /// A plane of an exported surface in the copy form, over a block whose address no call has + /// handed out, read by submissions that each then write through an address into another + /// buffer: the copies in each made before and after its buffer's `gpu_address` is read, and + /// the surface's form; `None` where the device makes no such surface. + fn through_addresses( + name: &str, + at: (&Device, &CommandQueue), + out: &Buffer, + library: &Library, + ) -> Option<(Vec, Vec, SurfaceForm)> { + let device = at.0; + let mut d = + TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, WIDTH, HEIGHT); + d.usage = TextureUsage::SHADER_READ; + d.storage_mode = StorageMode::Private; + let planes = [PlaneSpec { + descriptor: d, + index: None, + rows_below: 0, + }]; + // A pitch multiple no driver's pitch of a 256-byte row meets: the copy form. + let spec = SurfaceSpec { + handle: OPAQUE, + pitch_multiple: 4096, + start_multiple: 1, + planes: &planes, + }; + let addressed = || device.counters().metrics().exported_blocks_addressed; + let made = addressed(); + let (surface, export) = match device.new_exported_surface(&spec) { + Ok(made) => made, + Err(error) => { + println!("exported_overs: {name}: no {OPAQUE:?} surface: {error}"); + return None; + } + }; + if export.form == SurfaceForm::InPlace { + println!("exported_overs: {name}: the {OPAQUE:?} surface is in place"); + return None; + } + let buffer = (surface.buffer()).unwrap_or_else(|error| panic!("{name}: {error}")); + run(name, at.1, |encoder| { + (encoder.fill_buffer(&buffer, 0..buffer.length(), 0x3c)) + .unwrap_or_else(|error| panic!("{name}: the fill: {error}")); + }); + let function = library.function("store_through").expect("the kernel"); + let kernel = ComputePipelineDescriptor::new(StageSource::Function( + FunctionDescriptor::new(function), + )); + let state = (device + .new_compute_pipeline_state(&kernel, crate::tests::no_constexpr_samplers)) + .unwrap_or_else(|error| panic!("{name}: store_through: {error}")); + let interface = &state.inner.compiled.whole.interface; + assert!( + interface.writes_unbound, + "{name}: store_through writes through an address" + ); + let block = (device.take_block(MemoryClass::Shared, 2 * ROW)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let target = (device.new_buffer(block.id, 0, ROW, Some(0))).expect("a buffer"); + let held = (device.new_buffer(block.id, ROW, 8, Some(0))).expect("a buffer"); + let address = target.gpu_address().to_le_bytes(); + let contents = held.contents().expect("Shared"); + // SAFETY: the buffer holds 8 bytes, and no command reaches them. + unsafe { std::ptr::copy_nonoverlapping(address.as_ptr(), contents.as_ptr(), 8) }; + let writer = Writer { + state: &state, + held: &held, + target: &target, + }; + let over = (&surface.planes()[0], out); + let before = written_reads(name, at, over, &writer, 4, 0x3c); + assert_eq!(before, [1, 0, 0, 0], "{name}: no address of the block out"); + assert_eq!(addressed() - made, 0, "{name}: no address of the block out"); + assert_ne!( + buffer.gpu_address(), + 0, + "{name}: the surface buffer's address" + ); + assert_eq!( + addressed() - made, + 1, + "{name}: the surface buffer's address read" + ); + // The submission before the read owes nothing: no address of the block was out then. + let after = written_reads(name, at, over, &writer, 3, 0x3c); + assert_eq!(after, [0, 1, 1], "{name}: the block's address out"); + Some((before, after, export.form)) + } + #[test] fn an_exported_blocks_texture_is_copied_in_once_a_change() { + let library = match llvm_assemble_text(STORE_THROUGH) { + Ok(bitcode) => Some(Library::from_air(&bitcode).expect("the library")), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: the writes through an address: {why}"); + None + } + Err(error) => panic!("store_through: {error:?}"), + }; each_device("exported_overs", |name, _, device| { let Some(handle) = (ExportHandle::ALL.into_iter()) .find(|&handle| device.new_exported_block(handle, LEN).is_ok()) @@ -81,8 +304,15 @@ mod on_device { println!("exported_overs: {name}: exports no handle"); return; }; + let addressed = || device.counters().metrics().exported_blocks_addressed; + let made = addressed(); let (block, _export) = (device.new_exported_block(handle, LEN)) .unwrap_or_else(|error| panic!("{name}: {error}")); + assert_eq!( + addressed() - made, + 1, + "{name}: the block's handle states its address" + ); let buffer = (device.new_buffer(block.id, 0, LEN, None)).expect("a buffer"); let pitch = (device.minimum_linear_texture_alignment(PixelFormat::RGBA8Unorm)) .unwrap_or_else(|error| panic!("{name}: {error}")) @@ -127,6 +357,16 @@ mod on_device { fill and no event: {} {} {} {}", acquired.0, filled.0, zeroed.0, unchanged.0 ); + let Some(library) = &library else { + return; + }; + if let Some((before, after, form)) = through_addresses(name, at, &out, library) { + println!( + "exported_overs: {name}: {OPAQUE:?} surface, {form:?}: copies in a \ + submission that writes through an address, the block's address not out: \ + {before:?}, then out: {after:?}; blocks addressed 0, then 1" + ); + } }); } } diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index ce7811344..b50630cae 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -1619,8 +1619,11 @@ impl Device { } // Over an exported block, the submissions keep what changes its bytes // (`crate::over::ExportedOvers`). - if let Some((_, copy)) = texture.copied_over().filter(|(_, copy)| copy.exported) { - core.work.exported_over(&texture.inner, ©); + if let Some((buffer, copy)) = texture.copied_over().filter(|(_, copy)| copy.exported) { + if let Some(addressed) = &buffer.held().0.addressed { + core.work + .exported_over(&texture.inner, ©, Arc::clone(addressed)); + } } Ok(texture) } @@ -5312,6 +5315,11 @@ impl Device { } None => None, }; + // A storage element at an index reaches the bytes outside every bound slot, as an + // address does (`crate::over::ExportedOvers`). + if index.is_some() && elements[1] { + buffer.address_out(); + } let named = Named { buffer: Arc::clone(buffer.object()), places: vec![BytesPlace { diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 8a20156ff..e3d5af32a 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1624,6 +1624,7 @@ field metal2vulkan-runtime::Metrics.export_allocations pub export_allocations: T field metal2vulkan-runtime::Metrics.export_claims pub export_claims: Timed field metal2vulkan-runtime::Metrics.export_handles pub export_handles: Timed field metal2vulkan-runtime::Metrics.export_makes pub export_makes: Timed +field metal2vulkan-runtime::Metrics.exported_blocks_addressed pub exported_blocks_addressed: u64 field metal2vulkan-runtime::Metrics.external_acquires pub external_acquires: u64 field metal2vulkan-runtime::Metrics.external_releases pub external_releases: u64 field metal2vulkan-runtime::Metrics.first_use_line_wait_max_nanos pub first_use_line_wait_max_nanos: u64