diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 805439844..cf99c52e1 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -513,28 +513,34 @@ in its memory. named as `did_modify_range` names a range. `Buffer::did_modify_range(start, length)` names a range changed (`Refusal::ModifiedRange` past the buffer), merged with the buffer's others where they overlap or touch, and submits and - allocates nothing. The next commit of a command buffer, with commands or none, on any queue, - takes every range named since, once each: GPU copies from the consumer's block into the device - copy, recorded at the commit into a command buffer of their own. It goes in the submission of - the first command buffer committed at or after that commit that the device submits, whichever - queue and whichever waits held the committing one, as a part of its own ahead of that command - buffer's commands and outside its waits, after every earlier command on the device, which the - barrier ending each earlier command buffer orders; the copies record one barrier, after them. - A command buffer with nothing for the GPU (no commands, or only dispatches that record none: a - kernel that writes no memory, or a grid with no thread) that reaches the submit thread while - the copies wait for it takes a submission of them alone, and completes once they have run, its - GPU start and end one time as for any command buffer with nothing for the GPU. A command buffer - committed before it never takes it. The copy runs when that submission - reaches the GPU, so every command buffer committed after a range is named reads the bytes the - consumer wrote before the naming, as Metal's `didModifyRange:` asks; a write made after the - commit may reach it, and so may a command buffer committed before that runs after a later one, - where Metal leaves the range undefined for the GPU. - `Metrics::managed_bytes_captured` counts the bytes the copies take. A command buffer keeps each - device copy it uses, and the consumer's blocks its copies read, until it retires. A range named - and not yet taken keeps neither block: once the buffer's last handle is gone (a command buffer, - an encoder or a texture that could read the copy would hold the buffer), its ranges are - forgotten and its blocks go at once, an imported block's release among them, as Metal runs a - no-copy buffer's deallocator when it deallocates the buffer. + allocates nothing. The first commit, on any queue, of a command buffer whose encoders name the + buffer (a slot of any stage, `use_resource`, a blit, an index, indirect, tessellation factor or + visibility result buffer, a texture over it) takes its ranges named since, once each: GPU copies + from the consumer's block into the device copy, recorded at the commit into a command buffer of + their own, which goes in the submission of the first command buffer committed at or after that + commit that the device submits, whichever queue and whichever waits held the committing one, as + a part of its own ahead of that command buffer's commands and outside its waits, after every + earlier command on the device, which the barrier ending each earlier command buffer orders; the + copies record one barrier, after them. A commit that does not name the buffer takes nothing of + it, so a shader that reaches it through its address alone reads the bytes the device copy last + took, as Metal on an AMD Radeon Pro 5300M does (jobs 81602 and 81644); Metal's contract has such + a resource declared by `useResource:`. A command buffer with nothing for the GPU (no commands, + or only dispatches that record none: a kernel that writes no memory, or a grid with no thread) + that reaches the submit thread while the copies wait for it takes a submission of them alone, + and completes once they have run, its GPU start and end one time as for any command buffer with + nothing for the GPU. A command buffer committed before it never takes it. The copy runs when + that submission reaches the GPU, so every command buffer that names the buffer, committed after + a range is named, reads the bytes the consumer wrote before the naming, as Metal's + `didModifyRange:` asks, and those written after the naming and before its commit, as the 5300M + answers where Metal leaves the range undefined for the GPU; a write made after the commit may + reach it, and so may a command buffer committed before that runs after a later one, where Metal + leaves the range undefined for the GPU. `Metrics::managed_bytes_captured` counts the bytes the + copies take. A command buffer keeps each device copy it uses, and the consumer's blocks its + copies read, until it retires. A range named and not yet taken keeps neither block: once the + buffer's last handle is gone (a command buffer, an encoder or a texture that could read the copy + would hold the buffer), its ranges are forgotten and its blocks go at once, an imported block's + release among them, as Metal runs a no-copy buffer's deallocator when it deallocates the buffer. + A live buffer's ranges never overlap or touch, so they are bounded by the buffer. The consumer's ranges follow Metal's retention: it reuses a range only once the work that named the buffer there before has completed. A command buffer keeps each buffer it uses, and so its diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 28dbd8379..8d031fc11 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -547,19 +547,33 @@ impl Buffer { } /// `didModifyRange:`: the consumer changed `length` bytes from `start` of the buffer's bytes. - /// Of a Managed buffer with a device copy, the range is named, and the next commit of a command - /// buffer, with commands or none, on any queue, takes every range named since, once each, - /// merged where they overlap or touch: GPU copies from the consumer's block into the device - /// copy, and into the images of its textures over the range in images of their own, go ahead - /// of that command buffer's commands in its submission. One with nothing for the GPU (no - /// commands, or only dispatches that record none) submits the copies alone and completes after - /// them. So a command buffer committed after this call reads the bytes the consumer wrote - /// before its commit, as Metal owes. Metal on a discrete Mac GPU (an AMD Radeon Pro 5300M) - /// takes a named range at the first commit whose encoder binds its buffer; this takes it at - /// the next commit of any command buffer, the same commit where that one binds the buffer, and - /// never a later one. The copy reads the consumer's bytes as it runs, so a write made after the - /// commit may reach it, where Metal leaves the range undefined for the GPU. Of any other - /// buffer it does nothing, as the GPU reads the consumer's bytes. It allocates nothing. + /// Of a Managed buffer with a device copy, the range is named, merged with the buffer's others + /// where they overlap or touch, and the first commit, on any queue, of a command buffer whose + /// encoders name the buffer takes them, once each. An encoder names it by binding it in a slot + /// of any stage, by [`use_resource`](crate::ComputeCommandEncoder::use_resource), in a blit, as + /// an index, indirect, tessellation factor or visibility result buffer, or through a texture + /// over it. GPU copies from the consumer's block into the device copy, and into the images of + /// its textures over the range in images of their own, go ahead of that command buffer's + /// commands in its submission. One with nothing for the GPU (no commands, or only dispatches + /// that record none) submits the copies alone and completes after them. A commit of a command + /// buffer that does not name the buffer takes nothing of it, so a shader that reaches the + /// buffer through its address alone reads the bytes the device copy last took: Metal's + /// contract has a resource reached through an address declared by `useResource:`. + /// + /// So a command buffer that names the buffer, committed after this call, reads the bytes the + /// consumer's block holds when the copy runs: those written before this call, as Metal owes, + /// and those written after it and before that commit, where Metal leaves the range undefined + /// for the GPU. That is Metal's answer on a discrete Mac GPU: an AMD Radeon Pro 5300M under + /// macOS 26.7.1, 8 rounds each, takes a named range at the first commit whose encoders bind + /// the buffer in a compute or a vertex slot (with a draw), declare it by `useResource:` or read + /// it in a blit's copy, with its bytes as of that commit; an unrelated commit takes nothing; + /// and a buffer no encoder names, reached through its address, keeps its last synced bytes + /// (jobs 81602 and 81644). The other ways of naming it hold to the same rule unaudited on + /// Metal, as does a named range narrower than a later write, which takes the range's bytes + /// alone. The copy reads the consumer's bytes as it runs, so a write made after the commit may + /// reach it, where Metal leaves the range undefined for the GPU. Of any other buffer it does + /// nothing, as the GPU reads the consumer's bytes, as it does on an Intel UHD Graphics 630, + /// whose Managed buffers are one copy (jobs 81603 and 81645). It allocates nothing. /// /// Err: [`Refusal::ModifiedRange`] for a range that leaves the buffer; for a copy, /// [`Error::Quiesced`]. diff --git a/crates/metal2vulkan-runtime/src/capture.rs b/crates/metal2vulkan-runtime/src/capture.rs index 9cadb849a..3fe25d31e 100644 --- a/crates/metal2vulkan-runtime/src/capture.rs +++ b/crates/metal2vulkan-runtime/src/capture.rs @@ -1,22 +1,22 @@ //! A Managed buffer's changed ranges, copied in at the commit: where a Managed buffer has a device //! copy (a device whose Vulkan device type is neither integrated nor CPU), `didModifyRange:` only -//! names a range ([`Changes::add`]), and the next commit on any queue, of a command buffer with -//! commands or none, takes every range named since the last commit, once each -//! ([`Work::capture`](crate::submit::Work::capture)). Its copy-in ([`copy_in`]) is a command -//! buffer of its own, [`CopyIn`]: GPU copies of each range from the consumer's block into the -//! device copy, then the copies in the textures over the ranges in images of their own take -//! (`crate::over::ManagedOvers`). It waits in [`Captured`] at the capturing commit's number, a -//! point in the commit order, and the first command buffer submitted whose commit number is at or -//! after it takes it ([`taker`]): it goes in that command buffer's submission, as a part of its own -//! ahead of its commands and outside its waits. A command buffer with nothing for the GPU that it -//! waits for ([`Captured::waits_for`]) takes a submission for it alone, and completes once the -//! copies have run. A command buffer committed before the capture leaves it pending, so it never -//! goes ahead of older work of the queue that may write the range. The submission keeps each -//! consumer's block and device copy until it retires. A copy-in records no barrier before its -//! copies: the one that ends every earlier segment, upload, fill and copy-in on the queue puts -//! every earlier command first, as it does for a segment (`record::end`), and the submission that -//! carries it makes the host's writes before it visible to the copies (Vulkan's host write -//! ordering guarantee). +//! names a range ([`Changes::add`]), and the first commit on any queue of a command buffer whose +//! encoders name the buffer ([`Names`]) takes its ranges named and not yet taken, once each +//! ([`Work::capture`](crate::submit::Work::capture)); a commit that does not name it takes nothing +//! of it. Its copy-in ([`copy_in`]) is a command buffer of its own, [`CopyIn`]: GPU copies of each +//! range from the consumer's block into the device copy, then the copies in the textures over the +//! ranges in images of their own take (`crate::over::ManagedOvers`). It waits in [`Captured`] at +//! the capturing commit's number, a point in the commit order, and the first command buffer +//! submitted whose commit number is at or after it takes it ([`taker`]): it goes in that command +//! buffer's submission, as a part of its own ahead of its commands and outside its waits. A command +//! buffer with nothing for the GPU that it waits for ([`Captured::waits_for`]) takes a submission +//! for it alone, and completes once the copies have run. A command buffer committed before the +//! capture leaves it pending, so it never goes ahead of older work of the queue that may write the +//! range. The submission keeps each consumer's block and device copy until it retires. A copy-in +//! records no barrier before its copies: the one that ends every earlier segment, upload, fill and +//! copy-in on the queue puts every earlier command first, as it does for a segment (`record::end`), +//! and the submission that carries it makes the host's writes before it visible to the copies +//! (Vulkan's host write ordering guarantee). //! //! A write of such a texture that runs before the copy-in keeps its texels outside the ranges, as //! Metal's device copy keeps a GPU write outside a `didModifyRange:`'s range: the copies back it @@ -28,32 +28,39 @@ //! write of another queue not yet submitted runs after the copy-in, which copies nothing back for //! it: its copy in follows the copy-in, and its copy back is owed to the readers after it. //! -//! So every command buffer committed after a range is named reads the bytes the consumer wrote -//! there before the commit, on any queue and wherever the capturing command buffer waits, which is -//! what Metal owes (`MTLBuffer.h`, `didModifyRange:`): a write makes the range "undefined for any -//! accesses by the GPU" until a `didModifyRange:` "followed by a commit of the MTLCommandBuffer -//! that will access the buffer", which "does not make the contents coherent for any previously -//! committed command buffers". One committed before that runs after a later one, held at an event -//! wait, may read them too, where the header leaves the contents undefined. The copy reads the -//! consumer's bytes as it runs, so a write after the commit may reach it, where Metal leaves the -//! range undefined. +//! So every command buffer that names the buffer, committed after a range is named, reads the +//! bytes the consumer wrote there before its commit, on any queue and wherever the capturing +//! command buffer waits, which is what Metal owes (`MTLBuffer.h`, `didModifyRange:`): a write makes +//! the range "undefined for any accesses by the GPU" until a `didModifyRange:` "followed by a +//! commit of the MTLCommandBuffer that will access the buffer", which "does not make the contents +//! coherent for any previously committed command buffers". The bytes are those the consumer's +//! block holds when the copy runs, so a write after the `didModifyRange:` and before that commit, +//! which the header leaves undefined, reaches the GPU, as Metal on a discrete Mac GPU answers +//! (`Buffer::did_modify_range`). One committed before that runs after a later one, held at an +//! event wait, may read them too, where the header leaves the contents undefined. The copy reads +//! the consumer's bytes as it runs, so a write after the commit may reach it, where Metal leaves +//! the range undefined. A buffer no command buffer names keeps the bytes its device copy last +//! took, though shaders reach it through its address, as Metal on a discrete Mac GPU answers: its +//! range stays named until a commit names the buffer or the buffer is gone. //! //! A range named and not yet captured holds its buffer weakly, and neither of its blocks: once the //! buffer's last handle is gone, nothing can read its device copy (a command buffer, an encoder's -//! binding or a texture that could holds the buffer), so the capture forgets its ranges, and the -//! buffer's drop lets its blocks go at once, an import's release among them. Metal runs a no-copy +//! binding or a texture that could holds the buffer), so a sweep forgets its ranges ([`Changes`]), +//! and the buffer's drop lets its blocks go at once, an import's release among them. The ranges of +//! a live buffer are bounded by the buffer: they never overlap or touch. Metal runs a no-copy //! buffer's deallocator as it deallocates the buffer, and its `didModifyRange:` is owed only to a //! command buffer that accesses the buffer, which then holds it. -use crate::buffer::{BufferInner, DeviceCopy}; +use crate::buffer::{Buffer, BufferInner, DeviceCopy}; use crate::coherence::Range; use crate::counters::Metric; use crate::device::Core; use crate::error::Error; +use crate::kept::Kept; use crate::memory::Block; use crate::over::{self, Back, ManagedOvers}; use crate::record::{self, Reach, Recorder}; -use crate::texture::{Image, OverCopy, TextureInner, TextureObject}; +use crate::texture::{Image, OverCopy, Texture, TextureInner, TextureObject}; use crate::times; use ash::vk; use std::collections::{HashMap, VecDeque}; @@ -83,46 +90,110 @@ struct Named { ranges: Vec<(u64, u64)>, } -/// The device's ranges named and not yet captured, in the order of each buffer's first. -#[derive(Default)] +/// What a committing command buffer's encoders named, whose ranges its commit takes +/// ([`Changes::take`]): each buffer it keeps, which is each buffer an encoder bound in a slot of +/// any stage, declared by `useResource:`, read or wrote in a blit (a copy's source or destination, +/// a fill, a texture copy's buffer, a synchronize) or took as an index, indirect, tessellation +/// factor or visibility result buffer; and each texture it keeps, which names the buffer it lies +/// over (`TextureObject::over_buffer`). A heap use names none: Metal refuses a Managed heap (an AMD +/// Radeon Pro 5300M and an Intel UHD Graphics 630 under macOS 26.7.1 fail its descriptor's +/// validation, jobs 81602 and 81603). +pub(crate) struct Names<'a> { + pub(crate) buffers: &'a Kept, + pub(crate) textures: &'a Kept, +} + +/// The device's ranges named and not yet captured. An entry stays until a commit whose encoders +/// name its buffer takes it, or its buffer is gone: then the next sweep drops it. pub(crate) struct Changes { named: Vec, /// Each buffer's place in `named`, by its address, which a weak hold keeps from reuse. at: HashMap, + /// The length of `named` at which the next [`add`](Self::add) of a new buffer first drops the + /// entries of buffers gone: twice the entries left by the last sweep, at least + /// [`SWEEP_FLOOR`], so the entries never exceed twice the live buffers with ranges named, or + /// the floor. + sweep_at: usize, /// The copy-ins captured and not yet taken. pub(crate) captured: Captured, } +/// The fewest entries [`Changes`] holds before it first sweeps the entries of buffers gone. +const SWEEP_FLOOR: usize = 64; + +impl Default for Changes { + fn default() -> Changes { + Changes { + named: Vec::new(), + at: HashMap::new(), + sweep_at: SWEEP_FLOOR, + captured: Captured::default(), + } + } +} + impl Changes { /// Names `start..end` of `buffer`, a Managed buffer with a device copy. pub(crate) fn add(&mut self, buffer: &Arc, start: u64, end: u64) { let key = Arc::as_ptr(buffer) as usize; - match self.at.get(&key) { - Some(&index) => merge(&mut self.named[index].ranges, start, end), - None => { - self.at.insert(key, self.named.len()); - self.named.push(Named { - buffer: Arc::downgrade(buffer), - ranges: vec![(start, end)], - }); - } + if let Some(&index) = self.at.get(&key) { + merge(&mut self.named[index].ranges, start, end); + return; } + if self.named.len() >= self.sweep_at { + self.sweep(); + } + self.at.insert(key, self.named.len()); + self.named.push(Named { + buffer: Arc::downgrade(buffer), + ranges: vec![(start, end)], + }); } - /// The ranges named since the last capture, taken: those of the buffers that still live, each - /// holding the buffer's blocks from here; a buffer gone has its ranges forgotten. - pub(crate) fn take(&mut self) -> Vec { + /// Drops the entries of buffers gone, whose ranges nothing can take: no command buffer names a + /// buffer gone. + fn sweep(&mut self) { + self.named.retain(|named| named.buffer.strong_count() > 0); self.at.clear(); - (self.named.drain(..)) - .filter_map(|named| { - let buffer = named.buffer.upgrade()?; - buffer.modified(named.ranges) - }) - .collect() + for (index, named) in self.named.iter().enumerate() { + self.at.insert(Weak::as_ptr(&named.buffer) as usize, index); + } + self.sweep_at = (2 * self.named.len()).max(SWEEP_FLOOR); + } + + /// The ranges named of the buffers `names` holds, taken, each holding its buffer's blocks from + /// here; every other buffer's stay named, for a later commit that names it. It looks up each + /// buffer and texture the command buffer keeps, and allocates only where it takes a range. + pub(crate) fn take(&mut self, names: &Names<'_>) -> Vec { + if self.named.is_empty() { + return Vec::new(); + } + let over = (names.textures.iter()).filter_map(|texture| texture.over_buffer()); + let mut taken: Vec = (names.buffers.iter().chain(over)) + .filter_map(|buffer| self.at.get(&(Arc::as_ptr(buffer) as usize)).copied()) + .collect(); + if taken.is_empty() { + return Vec::new(); + } + taken.sort_unstable(); + taken.dedup(); + // The last first, so each index left to take stays where it was; `at` follows each move. + let mut modified = Vec::with_capacity(taken.len()); + for &index in taken.iter().rev() { + let named = self.named.swap_remove(index); + self.at.remove(&(Weak::as_ptr(&named.buffer) as usize)); + if let Some(moved) = self.named.get(index) { + self.at.insert(Weak::as_ptr(&moved.buffer) as usize, index); + } + if let Some(buffer) = named.buffer.upgrade() { + modified.extend(buffer.modified(named.ranges)); + } + } + modified } /// A capture of `modified` that will not run: its ranges are named again, for the next commit - /// to capture, where the buffer still lives. + /// that names the buffer to capture, where the buffer still lives. pub(crate) fn give_up(&mut self, modified: &[Modified]) { for modified in modified { let Some(buffer) = modified.buffer.upgrade() else { diff --git a/crates/metal2vulkan-runtime/src/command.rs b/crates/metal2vulkan-runtime/src/command.rs index f0c34dcb5..e5679a7bd 100644 --- a/crates/metal2vulkan-runtime/src/command.rs +++ b/crates/metal2vulkan-runtime/src/command.rs @@ -3,6 +3,7 @@ use crate::alias::{Aliased, Marks, Placement}; use crate::buffer::{Buffer, BufferInner, BufferObject}; +use crate::capture; use crate::coherence::{self, Ranges}; use crate::complete::Completion; use crate::counters::{Metric, Stage, Tally}; @@ -772,13 +773,22 @@ impl CommandBuffer { if work.closed() { return Err(Error::Quiesced); } - // With commands or none, it captures the Managed buffers' ranges named since the last - // capture, at its number in the commit order (`crate::capture`). A commit that fails - // after its capture leaves the copy-in at that number. - self.state().open()?; - let mut work = match work.lost() { - true => work, - false => core.work.capture(&core, work)?, + // With commands or none, it captures the ranges named and not yet taken of the Managed + // buffers its encoders name, at its number in the commit order (`crate::capture`). A + // commit that fails after its capture leaves the copy-in at that number. + let mut work = { + let mut state = self.state(); + let kept = &state.open()?.gpu.kept; + match work.lost() { + true => work, + false => { + let names = capture::Names { + buffers: &kept.buffers, + textures: &kept.textures, + }; + core.work.capture(&core, work, &names)? + } + } }; let mut state = self.state(); state.open()?; diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index c348d4e24..ea8d23f24 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -3323,8 +3323,8 @@ pub struct Metrics { /// a class's reserve, which the idle rule does not free, is taken again past 250 ms. pub idle_reuses_by_age: [u64; 7], /// Bytes the commits' copy-ins copy on the GPU from Managed buffers' bytes into their device - /// copies: each range `didModifyRange:` named since the last capture, once, on a device whose - /// Managed buffers have device copies + /// copies: each range `didModifyRange:` named, once, at the first commit that names its buffer, + /// on a device whose Managed buffers have device copies /// ([`Buffer::did_modify_range`](crate::Buffer::did_modify_range)). pub managed_bytes_captured: u64, /// Releases of a texture or a block while an upload not yet submitted held it: a texture diff --git a/crates/metal2vulkan-runtime/src/over.rs b/crates/metal2vulkan-runtime/src/over.rs index 68ba8a71e..868ba6cc1 100644 --- a/crates/metal2vulkan-runtime/src/over.rs +++ b/crates/metal2vulkan-runtime/src/over.rs @@ -581,18 +581,18 @@ impl Entry { /// A Managed buffer's textures over its device copy in an image of their own (`Entry`), each owing /// copies only at Metal's own Managed events, with no tracking of commands: /// -/// - **In** after a didModifyRange over its range: the capture of the range at the next commit -/// (`crate::capture`) makes it, after its copies into the device copy, in the same command -/// buffer. And at its making, or where device work wrote the buffer (a binding whose compiled -/// interface writes it, a blit or fill into it) or another texture over a range that meets its, -/// from the submission after that work's: the upload that leads the first submission that uses -/// the texture makes it, taken as that submission goes, as the device's one `VkQueue` runs -/// submissions in the order they go, so a command buffer of another queue that passes a group -/// held takes it ahead of the group. A capture over its range settles that copy only for the -/// command buffers committed at or after the capture, which run behind its copy in; one -/// committed before it may run first, and takes its own. Both copy from the device copy, never -/// from the consumer's bytes a second time. Apple GPUs may alias Managed memory; the documented -/// contract, not one GPU's answer, is the rule here. +/// - **In** after a didModifyRange over its range: the capture of the range at the first commit +/// that names the buffer (`crate::capture`) makes it, after its copies into the device copy, in +/// the same command buffer. And at its making, or where device work wrote the buffer (a binding +/// whose compiled interface writes it, a blit or fill into it) or another texture over a range +/// that meets its, from the submission after that work's: the upload that leads the first +/// submission that uses the texture makes it, taken as that submission goes, as the device's one +/// `VkQueue` runs submissions in the order they go, so a command buffer of another queue that +/// passes a group held takes it ahead of the group. A capture over its range settles that copy +/// only for the command buffers committed at or after the capture, which run behind its copy in; +/// one committed before it may run first, and takes its own. Both copy from the device copy, +/// never from the consumer's bytes a second time. Apple GPUs may alias Managed memory; the +/// documented contract, not one GPU's answer, is the rule here. /// - **Back** where device work wrote the texture since the last copy back: before the next /// reader of the device copy (a binding whose interface reads the buffer, a blit from it, a copy /// into another texture over a range that meets its, a synchronize, a capture of a range over diff --git a/crates/metal2vulkan-runtime/src/submit.rs b/crates/metal2vulkan-runtime/src/submit.rs index 3aa899039..3b4f93b82 100644 --- a/crates/metal2vulkan-runtime/src/submit.rs +++ b/crates/metal2vulkan-runtime/src/submit.rs @@ -55,10 +55,11 @@ //! staging region ([`crate::staging`]), which the work lock guards with the uploads; they go //! without a wait once their copies' spans take half the region. //! -//! A command buffer's commit takes the Managed buffers' ranges named since the last capture -//! ([`crate::capture`]): its copy-in, GPU copies from the consumers' blocks into the device -//! copies, waits at that commit's number, and the first submission of a command buffer numbered -//! at or after it takes it, ahead of that command buffer's first segment and outside its waits. +//! A command buffer's commit takes the ranges named and not yet taken of the Managed buffers its +//! encoders name ([`crate::capture`]): its copy-in, GPU copies from the consumers' blocks into the +//! device copies, waits at that commit's number, and the first submission of a command buffer +//! numbered at or after it takes it, ahead of that command buffer's first segment and outside its +//! waits. use crate::alias; use crate::buffer::{BufferInner, BufferObject, DeviceCopy}; @@ -1023,9 +1024,9 @@ impl Work { /// `didModifyRange:` of a Managed buffer with a device copy: the consumer's bytes /// `start..end` of `buffer` changed. The range is only named, merged with the buffer's others - /// where they overlap or touch, holding the buffer weakly; the next commit, of a command - /// buffer with commands or none, copies it in ([`capture`](Self::capture)) where the buffer - /// still lives. It allocates nothing. + /// where they overlap or touch, holding the buffer weakly; the first commit whose encoders name + /// the buffer copies it in ([`capture`](Self::capture)) where the buffer still lives. It + /// allocates nothing. /// /// Err: [`Error::Quiesced`]. pub(crate) fn modify( @@ -1043,22 +1044,24 @@ impl Work { } /// At every commit, with commands or none, on the committing thread, under the work lock - /// `state`, which it keeps: takes every Managed buffer's range named since the last - /// capture (`crate::capture`) into one copy-in, GPU copies from the consumers' blocks into the - /// device copies, recorded into a command buffer of its own ([`capture::copy_in`]); none - /// where every buffer named is gone. It waits at the committing command buffer's number, the - /// next in the commit order ([`WorkState::seq`]), for the first command buffer submitted that - /// is numbered at or after it ([`capture::Captured`]). A commit that fails after its capture - /// leaves it there, for the next. + /// `state`, which it keeps: takes the ranges named and not yet taken of each Managed buffer the + /// committing command buffer's encoders name (`names`, `crate::capture`) into one copy-in, GPU + /// copies from the consumers' blocks into the device copies, recorded into a command buffer of + /// its own ([`capture::copy_in`]); none where it names no such buffer. Every other buffer's + /// ranges stay named. It waits at the committing command buffer's number, the next in the + /// commit order ([`WorkState::seq`]), for the first command buffer submitted that is numbered + /// at or after it ([`capture::Captured`]). A commit that fails after its capture leaves it + /// there, for the next. /// /// Err: [`Error::Quiesced`]; what making the copy-in's command buffer returns. The ranges are - /// then named again for the next commit. + /// then named again, for the next commit that names their buffers. pub(crate) fn capture<'a>( &'a self, core: &Core, mut state: MutexGuard<'a, WorkState>, + names: &capture::Names<'_>, ) -> Result, Error> { - let named = state.changes.take(); + let named = state.changes.take(names); if named.is_empty() { return Ok(state); } @@ -1076,9 +1079,9 @@ impl Work { Ok(state) } - /// A capture that cannot finish: its ranges `named` are named again for the next commit (none - /// once the device is closed: its submit thread forgot the ranges at its end), and `error` is - /// the commit's. + /// A capture that cannot finish: its ranges `named` are named again, for the next commit that + /// names their buffers (none once the device is closed: its submit thread forgot the ranges at + /// its end), and `error` is the commit's. fn unwind( &self, mut state: MutexGuard<'_, WorkState>, diff --git a/crates/metal2vulkan-runtime/src/tests/managed.rs b/crates/metal2vulkan-runtime/src/tests/managed.rs index cf2809579..a656a32c2 100644 --- a/crates/metal2vulkan-runtime/src/tests/managed.rs +++ b/crates/metal2vulkan-runtime/src/tests/managed.rs @@ -1,29 +1,36 @@ //! Managed buffers: changed ranges merge where they overlap or touch; and, under a device cfg, on //! every device of the cfg's kind, in the form Vulkan's device type picks and, on a device that //! keeps one copy, in the two-copy form too, through the two-copy view -//! (`command::on_device::each_device_in_both_forms`): with a device copy -//! where the device is neither integrated nor a CPU, the copy holds the consumer's first bytes and -//! zeros after them, a changed range reaches it at the next commit and a range not marked changed +//! (`command::on_device::each_device_in_both_forms`): with a device copy where the device is +//! neither integrated nor a CPU, the copy holds the consumer's first bytes and zeros after them, a +//! changed range reaches it at the next commit that names the buffer and a range not marked changed //! does not, a change submits nothing, and the copy-in at a commit adds one barrier; without one, //! shaders read the consumer's bytes as they are. In both forms a command buffer reads the bytes //! the consumer wrote and named before its commit (Metal's `didModifyRange:` contract), though the //! consumer's buffer and block handles go before it runs; nothing writes under a pending command //! buffer, where Metal leaves the range undefined for the GPU. A range is taken at the first commit //! whose encoders name its buffer: a reader committed after a commit that does not name it reads -//! the bytes written after the name, with no second name. A commit with nothing for the GPU (no -//! commands, or one dispatch of a kernel without effects) takes the ranges named before it: with a -//! device copy its one submission is the copy-in, it completes after it, and the next commit -//! captures nothing. A range of three 16 MiB units named -//! arrives whole at one commit, which takes no staging and allocates nothing. A Managed buffer over -//! an imported dma-buf, a block the runtime does not map, has no `contents`, and a kernel reads the -//! bytes the consumer wrote through its own mapping and named, in either form. Metal's two-copy -//! rule holds where `Device::has_unified_memory` is false: a kernel's write stays in the device -//! copy, and a range named with no host write puts the consumer's bytes back over it. A range past -//! the buffer and a Managed buffer over a Private block are refused, and every gauge reads zero -//! after teardown. The consumer places the device copy: at an odd offset of its Private block it -//! holds the bytes there and nowhere else, the consumer's slack after it and the bytes before it -//! as the consumer left them; a missing copy, a copy on a unified device, one in a Shared block, -//! one in an exported block and one past its block are refused. +//! the bytes written after the name, with no second name. Each way an encoder names a buffer takes +//! it at its commit (a compute, vertex or fragment slot, `use_resource`, an index buffer, an +//! indirect dispatch's or draw's arguments, the tessellation factor and visibility result buffers, +//! a blit's copy source or destination, a fill, a copy into or out of a texture, a synchronize, and +//! a command that names a texture over the buffer), and a reach by address alone takes nothing; a +//! buffer no encoder names keeps the bytes taken last, and a range named narrower than a later +//! write is taken with its own bytes alone. A commit with nothing for the GPU that names the buffer +//! (a declaration alone, or one dispatch of a kernel without effects) takes the ranges named before +//! it: with a device copy its one submission is the copy-in, it completes after it, and the next +//! commit captures nothing; one with no commands takes nothing, and the next commit that names the +//! buffer takes the ranges. A range of three 16 MiB units named arrives whole at one commit, which +//! takes no staging and allocates nothing. A Managed buffer over an imported dma-buf, a block the +//! runtime does not map, has no `contents`, and a kernel reads the bytes the consumer wrote through +//! its own mapping and named, in either form. Metal's two-copy rule holds where +//! `Device::has_unified_memory` is false: a kernel's write stays in the device copy, and a range +//! named with no host write puts the consumer's bytes back over it. A range past the buffer and a +//! Managed buffer over a Private block are refused, and every gauge reads zero after teardown. The +//! consumer places the device copy: at an odd offset of its Private block it holds the bytes there +//! and nowhere else, the consumer's slack after it and the bytes before it as the consumer left +//! them; a missing copy, a copy on a unified device, one in a Shared block, one in an exported +//! block and one past its block are refused. //! //! Managed textures, on every device: the image takes the named bytes of a region at its upload //! and nothing outside it, `get_bytes` reads the named bytes, `replace_region` writes them and @@ -176,12 +183,16 @@ pub(crate) mod on_device { Arena, }; use crate::tests::compute::on_device::{add, quiet_step, step, WORDS}; + use crate::tests::draw::on_device::{ + descriptor, examples, pass, state as render_state, target, vertices, Buffers, + }; use crate::texture::TextureObject; use crate::{ Block, BlockId, Buffer, BufferLayout, BytesPlace, CommandBuffer, CommandBufferStatus, - ComputePipelineState, Device, DispatchType, Error, ExportHandle, IndexClass, MemoryClass, - PixelFormat, Refusal, Region, StorageMode, Texture, TextureDescriptor, TexturePlace, - TextureType, TextureUsage, + ComputePipelineState, Device, DispatchType, Error, ExportHandle, IndexBuffer, IndexClass, + IndexType, MemoryClass, PixelFormat, PrimitiveType, Refusal, Region, Resource, + ResourceUsage, StorageMode, Texture, TextureDescriptor, TexturePlace, TextureType, + TextureUsage, }; use ash::vk; use std::time::Instant; @@ -206,21 +217,39 @@ pub(crate) mod on_device { } /// The bytes shaders reach at `managed`'s address, `len` of them, copied by the GPU into - /// `into`, a Shared buffer as long. + /// `into`, a Shared buffer as long, by a command buffer whose commands name both. fn device_bytes(device: &Device, managed: &Buffer, into: &Buffer, len: u64) -> Vec { + copied_bytes(device, managed, into, len, &[managed, into]) + } + + /// As [`device_bytes`], by a command buffer whose commands name `into` alone: they reach + /// `managed` at its address, as a shader reaches a buffer whose address it loads, and name it + /// to no encoder. `managed` lives until the copy completes. + fn address_bytes(device: &Device, managed: &Buffer, into: &Buffer, len: u64) -> Vec { + copied_bytes(device, managed, into, len, &[into]) + } + + /// The copy of [`device_bytes`] and [`address_bytes`], its command buffer naming `named`. + fn copied_bytes( + device: &Device, + managed: &Buffer, + into: &Buffer, + len: u64, + named: &[&Buffer], + ) -> Vec { let queue = device.new_command_queue(1).expect("a queue"); let command_buffer = queue.command_buffer().expect("a command buffer"); let (source, from) = managed.device_range(); let (target, to) = into.device_range(); command_buffer - .record_for_test(&[managed, into], |device, command| { + .record_for_test(named, |device, command| { let region = vk::BufferCopy { src_offset: from, dst_offset: to, size: len, }; // SAFETY: the command buffer is recording; both ranges are the buffers', which it - // keeps. + // keeps or which live until it completes. unsafe { device.cmd_copy_buffer(command, source, target, &[region]) }; }) .expect("a copy"); @@ -757,11 +786,496 @@ pub(crate) mod on_device { }); } + /// What the tests below name: words an indirect dispatch takes as one threadgroup, an + /// indirect draw as one vertex from vertex 1 (no triangle), an indexed indirect draw as one + /// index from index 1, and 16-bit indices as indices 1 and 0; zeros after them, 256 bytes. + fn arguments() -> Vec { + let words = [1u32, 1, 1] + .into_iter() + .chain(std::iter::repeat(0)) + .take(64); + words.flat_map(u32::to_le_bytes).collect() + } + + /// A range named is taken at the first commit whose commands name its buffer as `encode` does + /// (`way`), and not before, in either form. A Managed buffer of 256 bytes, its zeros taken; + /// [`arguments`] written and named; a command buffer that reaches the buffer at its address + /// alone ([`address_bytes`]) captures nothing at its commit and reads the zeros where the + /// device keeps a copy, the arguments where it does not; `encode`'s command buffer captures + /// the range at its commit where the device keeps a copy, nothing where it does not, and + /// completes; the bytes shaders reach are then the arguments. Where `encode` writes the buffer + /// it writes the bytes [`arguments`] holds there. + fn takes_at_naming_commit( + name: &str, + device: &Device, + way: &str, + encode: impl FnOnce(&CommandBuffer, &Buffer), + ) { + let copied = !device.has_unified_memory(); + let counters = device.counters(); + let captured = |from: u64| counters.metrics().managed_bytes_captured - from; + let take = || { + (device.take_block(MemoryClass::Shared, 1)) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }; + let (cpu, side) = (take(), take()); + let into = (device.new_buffer(side.id, 0, 256, None)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let managed = (new_managed(device, cpu.id, 0, 256, 0)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let (zeros, words) = (vec![0; 256], arguments()); + write(&managed, 0, &zeros); + (managed.did_modify_range(0, 256)).unwrap_or_else(|error| panic!("{name}: {error}")); + assert!( + device_bytes(device, &managed, &into, 256) == zeros, + "{name}: {way}: the zeros taken" + ); + write(&managed, 0, &words); + (managed.did_modify_range(0, 256)).unwrap_or_else(|error| panic!("{name}: {error}")); + let before = counters.metrics().managed_bytes_captured; + let reached = address_bytes(device, &managed, &into, 256); + assert_eq!( + captured(before), + 0, + "{name}: {way}: a reach by address alone captures nothing" + ); + let last: &[u8] = if copied { &zeros } else { &words }; + assert!( + reached == last, + "{name}: {way}: a reach by address alone reads the bytes taken last (device copy: \ + {copied})" + ); + + let queue = device.new_command_queue(1).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + encode(&command_buffer, &managed); + let before = counters.metrics().managed_bytes_captured; + command_buffer.commit().expect("a commit"); + assert_eq!( + captured(before), + 256 * u64::from(copied), + "{name}: {way}: captured at its commit (device copy: {copied})" + ); + finished(way, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}: {way}"); + let before = counters.metrics().managed_bytes_captured; + assert!( + address_bytes(device, &managed, &into, 256) == words, + "{name}: {way}: the bytes shaders reach after its commit (device copy: {copied})" + ); + assert_eq!(captured(before), 0, "{name}: {way}: taken once"); + println!("managed named: {name}: {way}: device copy {copied}"); + drop((command_buffer, queue, managed, into)); + for block in [cpu, side] { + (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); + } + } + + /// [`takes_at_naming_commit`] for each way a compute encoder names a buffer: a slot a dispatch + /// reads, `use_resource` alone, and an indirect dispatch's arguments. + #[test] + fn every_device_takes_a_named_range_at_a_commit_whose_compute_encoder_names_its_buffer() { + each_device_in_both_forms("managed named by compute", |name, _, device| { + let mut arena = Arena::new(&device); + let (zero, out) = (arena.buffer(), arena.buffer()); + let state = add(&device); + takes_at_naming_commit(name, &device, "a slot a dispatch reads", |cb, managed| { + kernel(cb, &state, [managed, &zero, &out]); + }); + assert!( + read(&out, 256) == arguments(), + "{name}: the dispatch read the bytes taken at its commit" + ); + takes_at_naming_commit(name, &device, "use_resource", |cb, managed| { + let mut encoder = + (cb.compute_command_encoder(DispatchType::Serial)).expect("an encoder"); + let read = ResourceUsage::READ; + (encoder.use_resource(Resource::Buffer(managed), read)).expect("a declaration"); + encoder.end_encoding(); + }); + takes_at_naming_commit(name, &device, "an indirect dispatch", |cb, managed| { + let mut encoder = + (cb.compute_command_encoder(DispatchType::Serial)).expect("an encoder"); + encoder.set_compute_pipeline_state(&state).expect("a state"); + for (slot, buffer) in [&zero, &zero, &out].into_iter().enumerate() { + (encoder.set_buffer(Some(buffer), 0, slot as u32)).expect("a buffer"); + } + (encoder.dispatch_threadgroups_with_indirect_buffer(managed, 0, [16, 1, 1])) + .expect("a dispatch"); + encoder.end_encoding(); + }); + drop((state, zero, out, arena)); + }); + } + + /// The ways a render encoder names a buffer that the test below takes. + #[derive(Clone, Copy, Debug)] + enum RenderWay { + /// A vertex slot a draw reads. + VertexSlot, + /// A fragment slot, with a draw. + FragmentSlot, + /// `use_resource` alone. + UseResource, + /// An indexed draw's index buffer. + IndexBuffer, + /// An indirect draw's arguments. + IndirectDraw, + /// An indexed indirect draw's arguments. + IndexedIndirectDraw, + /// The tessellation factor buffer, set. + TessellationFactors, + /// The pass's visibility result buffer. + VisibilityResults, + } + + /// 16-bit indices from the start of `buffer`. + fn u16_indices(buffer: &Buffer) -> IndexBuffer<'_> { + IndexBuffer { + buffer, + offset: 0, + index_type: IndexType::UInt16, + } + } + + /// [`takes_at_naming_commit`] for each way a render encoder names a buffer ([`RenderWay`]). + #[test] + fn every_device_takes_a_named_range_at_a_commit_whose_render_encoder_names_its_buffer() { + let Some(library) = examples() else { + return; + }; + let d = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm); + each_device_in_both_forms("managed named by a render encoder", |name, _, device| { + let state = render_state(name, &device, &d); + let mut buffers = Buffers::new(&device); + let (positions, colors) = vertices(&device, &mut buffers); + let indices = buffers.of(&device, &[0, 0, 1, 0, 2, 0, 0, 0]); + let color = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + use RenderWay as W; + let ways = [ + W::VertexSlot, + W::FragmentSlot, + W::UseResource, + W::IndexBuffer, + W::IndirectDraw, + W::IndexedIndirectDraw, + W::TessellationFactors, + W::VisibilityResults, + ]; + for way in ways { + let what = format!("{way:?}"); + takes_at_naming_commit(name, &device, &what, |cb, managed| { + let mut d = pass(&color, None); + if let W::VisibilityResults = way { + d.visibility_result_buffer = Some(managed.clone()); + } + let mut encoder = (cb.render_command_encoder(&d)) + .unwrap_or_else(|error| panic!("{name}: {way:?}: {error}")); + let ok = |result: Result<(), Error>| { + result.unwrap_or_else(|error| panic!("{name}: {way:?}: {error}")) + }; + let triangle = PrimitiveType::Triangle; + ok(encoder.set_render_pipeline_state(&state)); + ok(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + ok(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + match way { + W::VertexSlot => { + ok(encoder.set_vertex_buffer(Some(managed), 0, 0)); + ok(encoder.draw_primitives(triangle, 0, 3, 1, 0)); + } + W::FragmentSlot => { + ok(encoder.set_fragment_buffer(Some(managed), 0, 0)); + ok(encoder.draw_primitives(triangle, 0, 3, 1, 0)); + } + W::UseResource => { + let read = ResourceUsage::READ; + ok(encoder.use_resource(Resource::Buffer(managed), read)); + } + W::IndexBuffer => { + let indexed = u16_indices(managed); + ok(encoder.draw_indexed_primitives(triangle, 3, indexed, 1, 0, 0)); + } + W::IndirectDraw => { + ok(encoder.draw_primitives_indirect(triangle, managed, 0)); + } + W::IndexedIndirectDraw => { + let indexed = u16_indices(&indices); + let draw = encoder + .draw_indexed_primitives_indirect(triangle, indexed, managed, 0); + ok(draw); + } + W::TessellationFactors => { + ok(encoder.set_tessellation_factor_buffer(Some(managed), 0, 0)); + } + W::VisibilityResults => {} + } + encoder.end_encoding(); + }); + } + drop((state, positions, colors, indices, color, buffers)); + }); + } + + /// The ways a blit encoder names a buffer that the test below takes. + #[derive(Clone, Copy, Debug)] + enum BlitWay { + /// A copy's source. + CopySource, + /// A copy's destination. + CopyDestination, + /// A fill. + Fill, + /// A copy into a texture's source. + TexelSource, + /// A copy out of a texture's destination. + TexelDestination, + /// `synchronize_resource`. + Synchronize, + } + + /// [`takes_at_naming_commit`] for each way a blit encoder names a buffer ([`BlitWay`]). + #[test] + fn every_device_takes_a_named_range_at_a_commit_whose_blit_encoder_names_its_buffer() { + each_device_in_both_forms("managed named by a blit encoder", |name, _, device| { + let mut arena = Arena::new(&device); + let (source, out) = (arena.buffer(), arena.buffer()); + write(&source, 0, &arguments()); + // 8 by 8 texels of 4 bytes: the 256 bytes. + let texture = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + let rows = BufferLayout { + offset: 0, + bytes_per_row: 32, + bytes_per_image: 0, + }; + let (at, size) = (TexturePlace::default(), [8, 8, 1]); + use BlitWay as W; + let ways = [ + W::CopySource, + W::CopyDestination, + W::Fill, + W::TexelSource, + W::TexelDestination, + W::Synchronize, + ]; + for way in ways { + let what = format!("{way:?}"); + takes_at_naming_commit(name, &device, &what, |cb, managed| { + let mut blit = cb.blit_command_encoder().expect("an encoder"); + let ok = |result: Result<(), Error>| { + result.unwrap_or_else(|error| panic!("{name}: {way:?}: {error}")) + }; + match way { + W::CopySource => { + ok(blit.copy_from_buffer_to_buffer(managed, 0, &out, 0, 256)); + } + W::CopyDestination => { + ok(blit.copy_from_buffer_to_buffer(&source, 0, managed, 0, 256)); + } + W::Fill => ok(blit.fill_buffer(managed, 16..256, 0)), + W::TexelSource => { + ok(blit.copy_from_buffer(managed, rows, size, &texture, at)); + } + W::TexelDestination => { + ok(blit.copy_from_buffer(&source, rows, size, &texture, at)); + ok(blit.copy_from_texture_to_buffer(&texture, at, size, managed, rows)); + } + W::Synchronize => ok(blit.synchronize_resource(Resource::Buffer(managed))), + } + blit.end_encoding(); + }); + } + assert!( + read(&out, 256) == arguments(), + "{name}: the copy read the bytes taken at its commit" + ); + drop((texture, source, out, arena)); + }); + } + + /// A buffer no encoder names keeps the bytes taken last, in either form, as Metal on a + /// discrete Mac GPU (an AMD Radeon Pro 5300M) keeps them (`Buffer::did_modify_range`): zeros + /// taken, a table written and named, three commits whose kernels reach other buffers alone, + /// and a reach by address alone reads the zeros where the device keeps a copy, the table where + /// it does not; none of them captures anything. The range stays with the buffer, which goes + /// with it pending. + #[test] + fn every_device_keeps_the_bytes_taken_last_for_a_buffer_no_encoder_names() { + each_device_in_both_forms("managed never named", |name, _, device| { + let copied = !device.has_unified_memory(); + let counters = device.counters(); + let mut arena = Arena::new(&device); + let (zero, other, out, into) = ( + arena.buffer(), + arena.buffer(), + arena.buffer(), + arena.buffer(), + ); + let cpu = (device.take_block(MemoryClass::Shared, 1)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let managed = (new_managed(&device, cpu.id, 0, 256, 0)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let state = add(&device); + let queue = device.new_command_queue(4).expect("a queue"); + let zeros = vec![0; 256]; + write(&managed, 0, &zeros); + (managed.did_modify_range(0, 256)).unwrap_or_else(|error| panic!("{name}: {error}")); + assert!( + device_bytes(&device, &managed, &into, 256) == zeros, + "{name}: the zeros" + ); + let table: Vec = (0..256u32).map(|i| (i * 7 + 3) as u8).collect(); + write(&managed, 0, &table); + (managed.did_modify_range(0, 256)).unwrap_or_else(|error| panic!("{name}: {error}")); + let before = counters.metrics().managed_bytes_captured; + for _ in 0..3 { + let elsewhere = queue.command_buffer().expect("a command buffer"); + kernel(&elsewhere, &state, [&other, &zero, &out]); + elsewhere.commit().expect("a commit"); + finished("a kernel over other buffers", &elsewhere); + assert_eq!(elsewhere.error(), None, "{name}"); + } + let reached = address_bytes(&device, &managed, &into, 256); + let captured = counters.metrics().managed_bytes_captured - before; + assert_eq!(captured, 0, "{name}: nothing names the buffer"); + let last: &[u8] = if copied { &zeros } else { &table }; + assert!( + reached == last, + "{name}: a reach by address alone reads the bytes taken last (device copy: \ + {copied})" + ); + drop(managed); + let after = queue.command_buffer().expect("a command buffer"); + kernel(&after, &state, [&other, &zero, &out]); + after.commit().expect("a commit"); + finished("a kernel after the buffer went", &after); + assert_eq!(after.error(), None, "{name}"); + println!("managed never named: {name}: device copy {copied}"); + drop((after, queue, state, zero, other, out, into, arena)); + (device.release_block(cpu)).unwrap_or_else(|error| panic!("{name}: {error}")); + }); + } + + /// A range named narrower than a later write is taken with its own bytes as they are at the + /// first commit that names the buffer, and nothing past it (`Buffer::did_modify_range`; no + /// Metal run measures this case): zeros taken, `64..128` named, all 256 bytes then written + /// with no name, and a kernel that reads the buffer reads the new bytes in `64..128` and + /// zeros elsewhere where the device keeps a copy, the new bytes throughout where it does not. + #[test] + fn every_device_takes_a_narrow_named_range_and_nothing_past_it() { + each_device_in_both_forms("managed narrow name", |name, _, device| { + let copied = !device.has_unified_memory(); + let counters = device.counters(); + let mut arena = Arena::new(&device); + let (zero, out, into) = (arena.buffer(), arena.buffer(), arena.buffer()); + let cpu = (device.take_block(MemoryClass::Shared, 1)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let managed = (new_managed(&device, cpu.id, 0, 256, 0)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let state = add(&device); + let queue = device.new_command_queue(4).expect("a queue"); + let zeros = vec![0; 256]; + write(&managed, 0, &zeros); + (managed.did_modify_range(0, 256)).unwrap_or_else(|error| panic!("{name}: {error}")); + assert!( + device_bytes(&device, &managed, &into, 256) == zeros, + "{name}: the zeros" + ); + (managed.did_modify_range(64, 64)).unwrap_or_else(|error| panic!("{name}: {error}")); + let table: Vec = (0..256u32).map(|i| (i * 7 + 3) as u8).collect(); + write(&managed, 0, &table); + let before = counters.metrics().managed_bytes_captured; + let reader = queue.command_buffer().expect("a command buffer"); + kernel(&reader, &state, [&managed, &zero, &out]); + reader.commit().expect("a commit"); + let captured = counters.metrics().managed_bytes_captured - before; + finished("the reader", &reader); + assert_eq!(reader.error(), None, "{name}"); + assert_eq!( + captured, + 64 * u64::from(copied), + "{name}: the named range alone" + ); + let mut expected = table.clone(); + if copied { + expected[..64].fill(0); + expected[128..].fill(0); + } + assert!( + read(&out, 256) == expected, + "{name}: the reader reads the named range's new bytes{} (device copy: {copied})", + if copied { " and zeros past it" } else { "" } + ); + println!("managed narrow name: {name}: device copy {copied}"); + drop((reader, queue, state, managed, zero, out, into, arena)); + (device.release_block(cpu)).unwrap_or_else(|error| panic!("{name}: {error}")); + }); + } + + /// A texture over a Managed buffer names the buffer wherever a command names the texture + /// (`Buffer::did_modify_range`), in either form: a row of the buffer written and named, a + /// command buffer of other buffers captures nothing at its commit, and one whose one command + /// copies the texture's texels captures the row at its commit where the device keeps a copy + /// and reads it. + #[test] + fn every_device_takes_a_named_range_at_a_commit_that_names_a_texture_over_its_buffer() { + each_device_in_both_forms("managed named through a texture", |name, _, device| { + let copied = !device.has_unified_memory(); + let counters = device.counters(); + let cpu = (device.take_block(MemoryClass::Shared, 1)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let (managed, mut bytes, texture, form) = over_texture(name, &device, cpu.id, true); + let mut arena = Arena::new(&device); + let (scratch, out) = (arena.buffer(), arena.buffer()); + let queue = device.new_command_queue(4).expect("a queue"); + let row = OVER_PITCH as usize..(OVER_PITCH + OVER_ROW) as usize; + bytes[row.clone()].fill(0x6D); + write(&managed, OVER_PITCH, &bytes[row]); + (managed.did_modify_range(OVER_PITCH, OVER_ROW)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let before = counters.metrics().managed_bytes_captured; + let elsewhere = queue.command_buffer().expect("a command buffer"); + fill(&elsewhere, &scratch, 1); + elsewhere.commit().expect("a commit"); + finished("a fill of another buffer", &elsewhere); + let captured = counters.metrics().managed_bytes_captured - before; + assert_eq!(captured, 0, "{name}: {form}: another buffer's commit"); + let reader = queue.command_buffer().expect("a command buffer"); + read_over(&reader, &texture, &out); + let before = counters.metrics().managed_bytes_captured; + reader.commit().expect("a commit"); + let captured = counters.metrics().managed_bytes_captured - before; + finished("the texture's reader", &reader); + assert_eq!(reader.error(), None, "{name}: {form}"); + assert_eq!( + captured, + OVER_ROW * u64::from(copied), + "{name}: {form}: the reader's commit (device copy: {copied})" + ); + assert!( + read(&out, 4 * OVER_ROW as usize) == over_rows(&bytes), + "{name}: {form}: the reader reads the row named" + ); + println!("managed named through a texture: {name}: {form}"); + drop(( + elsewhere, reader, queue, texture, managed, scratch, out, arena, + )); + (device.release_block(cpu)).unwrap_or_else(|error| panic!("{name}: {error}")); + }); + } + /// The copy-in waits at its capture's number in the commit order, not on the command buffer - /// whose commit captured it (`crate::capture`): with that one held, waiting on an event of its - /// own or behind a held command buffer of its queue, a kernel committed after it on another - /// queue reads the bytes named before, at once, in either form. The capturing command buffer - /// is still held when the reader completes. + /// whose commit captured it (`crate::capture`): with that one, whose kernel reads the buffer, + /// held, waiting on an event of its own or behind a held command buffer of its queue, a kernel + /// committed after it on another queue reads the bytes named before, at once, in either form. + /// The capturing command buffer is still held when the reader completes. #[test] fn every_device_reads_bytes_named_before_its_commit_while_the_capturing_one_waits() { each_device_in_both_forms("managed capture held", |name, _, device| { @@ -796,7 +1310,7 @@ pub(crate) mod on_device { if !behind { (capturing.encode_wait_for_event(event.as_event(), 1)).expect("a wait"); } - fill(&capturing, &scratch, 2); + kernel(&capturing, &state, [&managed, &zero, &scratch]); capturing.commit().expect("a commit"); let reader = other.command_buffer().expect("a command buffer"); @@ -879,18 +1393,19 @@ pub(crate) mod on_device { }); } - /// A commit takes the ranges named since the last, with commands or none (`crate::capture`): - /// a Managed buffer written and named, then a command buffer that `encode` leaves with nothing - /// for the GPU, committed and waited for. With a device copy, its commit captured the range, - /// its one submission was the copy-in, and it completed after it, its GPU start and end one - /// time as for any command buffer with nothing for the GPU; the next commit captures nothing - /// and reads the bytes in the device copy. With one copy nothing is captured or submitted. - /// A discrete Mac GPU (an AMD Radeon Pro 5300M) takes a named range at the first commit whose - /// encoder binds its buffer: the same commit where the command buffer binds it and records - /// nothing, and a later one than here where it binds nothing. + /// A commit with nothing for the GPU takes the ranges named of the buffers its encoders name, + /// and nothing of any other (`crate::capture`): a Managed buffer written and named, then a + /// command buffer that `encode` leaves with nothing for the GPU, naming the buffer where + /// `names`, committed and waited for. With a device copy, where it names the buffer its commit + /// captured the range, its one submission was the copy-in, and it completed after it, its GPU + /// start and end one time as for any command buffer with nothing for the GPU, and the next + /// commit captures nothing; where it does not, its commit captured nothing and the next commit, + /// which names the buffer, captures the range. Either way that next commit reads the bytes in + /// the device copy. With one copy nothing is captured or submitted. fn empty_commit_takes_named_ranges( name: &str, device: &Device, + names: bool, encode: impl FnOnce(&CommandBuffer, &Buffer), ) { let copied = !device.has_unified_memory(); @@ -918,16 +1433,16 @@ pub(crate) mod on_device { finished("the empty one", &command_buffer); let after = counters.metrics(); let captured = committed.managed_bytes_captured - before.managed_bytes_captured; - let one = u64::from(copied); + let (one, now) = (u64::from(copied), u64::from(copied && names)); assert_eq!( ( captured, after.submissions - before.submissions, after.runtime_command_buffers - before.runtime_command_buffers, ), - (256 * one, one, one), + (256 * now, now, now), "{name}: captured at its commit, its submissions and the runtime's command buffers \ - in them (device copy: {copied})" + in them (device copy: {copied}, names the buffer: {names})" ); assert_eq!( (command_buffer.status(), command_buffer.error()), @@ -944,7 +1459,11 @@ pub(crate) mod on_device { ); let read = device_bytes(device, &managed, &into, 256); let next = counters.metrics().managed_bytes_captured - after.managed_bytes_captured; - assert_eq!(next, 0, "{name}: the next commit captures nothing"); + assert_eq!( + next, + 256 * (one - now), + "{name}: the next commit, which names the buffer, captures what this one did not" + ); assert!( read == bytes, "{name}: the bytes shaders reach (device copy: {copied})" @@ -957,9 +1476,24 @@ pub(crate) mod on_device { } #[test] - fn every_device_takes_named_ranges_at_a_commit_with_no_commands() { + fn every_device_takes_nothing_at_a_commit_with_no_commands() { each_device_in_both_forms("managed empty commit", |name, _, device| { - empty_commit_takes_named_ranges(name, &device, |_, _| {}); + empty_commit_takes_named_ranges(name, &device, false, |_, _| {}); + }); + } + + /// [`empty_commit_takes_named_ranges`] with a command buffer whose one compute encoder + /// declares the Managed buffer by `use_resource` and dispatches nothing. + #[test] + fn every_device_takes_named_ranges_at_a_commit_that_only_declares_the_buffer() { + each_device_in_both_forms("managed declared commit", |name, _, device| { + empty_commit_takes_named_ranges(name, &device, true, |command_buffer, managed| { + let mut encoder = (command_buffer.compute_command_encoder(DispatchType::Serial)) + .expect("an encoder"); + let read = ResourceUsage::READ; + (encoder.use_resource(Resource::Buffer(managed), read)).expect("a declaration"); + encoder.end_encoding(); + }); }); } @@ -970,7 +1504,7 @@ pub(crate) mod on_device { each_device_in_both_forms("managed quiet commit", |name, _, device| { let quiet = quiet_step(&device); let before = device.counters().metrics().dispatches_without_effects; - empty_commit_takes_named_ranges(name, &device, |command_buffer, managed| { + empty_commit_takes_named_ranges(name, &device, true, |command_buffer, managed| { let mut encoder = (command_buffer.compute_command_encoder(DispatchType::Serial)) .expect("an encoder"); encoder.set_compute_pipeline_state(&quiet).expect("a state"); @@ -1420,6 +1954,8 @@ pub(crate) mod on_device { .unwrap_or_else(|error| panic!("{name}: {error}")); let queue = device.new_command_queue(1).expect("a queue"); let capture = queue.command_buffer().expect("a command buffer"); + // Its commands name the buffer, so its commit takes the range. + (capture.record_for_test(&[&buffer], |_, _| {})).expect("a command buffer's commands"); capture.commit().expect("a commit"); finished(name, &capture); } diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index a7eec2a2e..f3f934365 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -6681,6 +6681,12 @@ pub(crate) trait TextureObject { }) } + /// The buffer it lies over, in any form: a texture made over a buffer, a view of one, a + /// texture buffer. An encoder that names it names that buffer (`crate::capture::Names`). + fn over_buffer(&self) -> Option<&Arc> { + self.object().named.as_ref().map(|named| &named.buffer) + } + /// Of a texture over a Managed buffer's device copy in an image of its own, which Metal's /// Managed events owe copies (`crate::over::ManagedOvers`): the buffer. fn managed_over(&self) -> Option<&Arc> {