diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index c6b517a5a..11e72ff69 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -331,20 +331,22 @@ the record the pass is making. program; no order of either changes a result. - **Textures over buffers** share the buffer's bytes. Over a no-copy buffer's host pages or such a long buffer's fresh pages, an image bound to them would start `UNDEFINED`, and Vulkan lets its - first move rewrite any byte bound to it: by default (`HostPageTexturePolicy::InPlace`) a texture - there that only samples or reads is an image in place wherever the device's own check showed - that move keeping every byte for that kind of pages (run once per driver and release on a - thread of its own, kept in the shader cache). The runtime keeps a copy and announces it - (`shadowed-texture`, naming why) for every other texture there (under - `HostPageTexturePolicy::Shadow`, one that renders or writes, one made before the check answered - or whose check did not pass), where the device's linear images cannot hold Metal's layout, and - where the rows lie with bytes between them. On a discrete GPU, a texture whose policy and usage - take the image in place, over a no-copy buffer whose memory carries a log of its writes - (`HostMemory::with_dirty_pages`), tracked and laid out as one copy, is instead such a copy in - the device's memory, announced nowhere, whatever the check answered: its copies in take only the - rows the log reports changed, so the GPU reads the surface from its own memory, where in place it - reads the pages across the bus at every sample (`WorkCounts::device_copy_textures`). Exact either - way; integrated GPUs, CPU devices and memory without a log keep the image in place. + first move, and a render pass's load and store, rewrite any byte bound to it: by default + (`HostPageTexturePolicy::InPlace`) a texture there that samples, reads or renders into it and + does not write it through a shader is an image in place wherever the device makes it and its own + check showed those operations keeping every byte for that kind of pages (run once per driver and + release on a thread of its own, kept in the shader cache). The runtime keeps a copy and + announces it (`shadowed-texture`, naming why) for every other texture there (under + `HostPageTexturePolicy::Shadow`, one that writes through a shader, one made before the check + answered or whose check did not pass), where the device's linear images cannot hold Metal's + layout, and where the rows lie with bytes between them. On a discrete GPU, a texture that only + samples or reads whose policy takes the image in place, over a no-copy buffer whose memory + carries a log of its writes (`HostMemory::with_dirty_pages`), tracked and laid out as one copy, + is instead such a copy in the device's memory, announced nowhere, whatever the check answered: + its copies in take only the rows the log reports changed, so the GPU reads the surface from its + own memory, where in place it reads the pages across the bus at every sample + (`WorkCounts::device_copy_textures`). Exact either way; integrated GPUs, CPU devices and memory + without a log keep the image in place. - **Two-plane YCbCr textures** (`YCBCR8_420_2P` and its kin over a surface's planes) hold an image of the texels Metal reads, converted from the planes before a command buffer's first use where they changed. Where `has_unified_memory`, a function that only samples or gathers a diff --git a/crates/metal2vulkan-runtime/src/fresh_pages.rs b/crates/metal2vulkan-runtime/src/fresh_pages.rs index f4948c651..10188d542 100644 --- a/crates/metal2vulkan-runtime/src/fresh_pages.rs +++ b/crates/metal2vulkan-runtime/src/fresh_pages.rs @@ -41,10 +41,10 @@ //! Only a buffer made here reads zero unwritten. //! - **Textures over it.** An image bound to imported memory starts `UNDEFINED` //! (`VUID-VkImageCreateInfo-pNext-01443`), and its first move may write any byte bound to it. A -//! texture over it that only samples or reads is a linear image in place where the device's -//! check passed for fresh pages (`in_place.rs`; counted: `WorkCounts::fresh_page_textures_in_place`), -//! and every other one takes the shadow (`shadow.rs`; counted: -//! `WorkCounts::shadows_over_fresh_pages`). +//! texture over it that samples, reads or renders and does not write through a shader is a +//! linear image in place where the device's check passed for fresh pages and its access +//! (`in_place.rs`; counted: `WorkCounts::fresh_page_textures_in_place`), and every other one +//! takes the shadow (`shadow.rs`; counted: `WorkCounts::shadows_over_fresh_pages`). //! - **Freed.** The pages are unmapped once the memory imported from them is freed, since the //! import requires them mapped for its whole life. That happens with the buffer's block, or //! after it where freed memory waits for the batches in flight (`freed_memory.rs`). diff --git a/crates/metal2vulkan-runtime/src/in_place.rs b/crates/metal2vulkan-runtime/src/in_place.rs index 2bad4ac2e..dc4a8c31c 100644 --- a/crates/metal2vulkan-runtime/src/in_place.rs +++ b/crates/metal2vulkan-runtime/src/in_place.rs @@ -1,7 +1,7 @@ -//! Textures over host pages, in place: a 2D texture (or array) whose declared usage only samples -//! or reads it, over a no-copy buffer's host pages or over a buffer the runtime placed in fresh -//! host pages, is a linear image aliasing those pages, where the device's own check shows that the -//! one operation Vulkan lets touch bytes beside the texels leaves every byte alone. +//! Textures over host pages, in place: a 2D texture (or array) whose declared usage samples, +//! reads or renders into it, over a no-copy buffer's host pages or over a buffer the runtime placed +//! in fresh host pages, is a linear image aliasing those pages, where the device's own check shows +//! that the operations Vulkan lets touch bytes beside the texels leave every byte alone. //! //! - **What Vulkan says.** An image bound to imported memory starts `UNDEFINED` //! (`VUID-VkImageCreateInfo-pNext-01443`: "If the pNext chain includes a @@ -12,30 +12,41 @@ //! Synchronization chapter says "Image layout transitions may perform read and write accesses on //! all memory bound to the image subresource range", and "If the old layout is //! VK_IMAGE_LAYOUT_UNDEFINED, the contents of that range may be discarded". Metal keeps every -//! CPU write to bytes no command writes, at every moment. No later operation of such an image -//! touches a byte beside its texels: a shader's read touches its texels alone (the Memory Model: -//! "A memory operation must not affect memory at a memory location not within its set of memory -//! locations"), every command uses it in `GENERAL` with memory barriers, which move no layout -//! (`tracker.rs`), and nothing renders into it or writes it through a shader (below). +//! CPU write to bytes no command writes, at every moment. A shader's read touches the texels +//! alone (the Memory Model: "A memory operation must not affect memory at a memory location not +//! within its set of memory locations"), and every command uses the image in `GENERAL` with +//! memory barriers, which move no layout (`tracker.rs`), but for two operations of an image that +//! renders ([`Access::Renders`]): a render pass's load and store operations, of which the Render +//! Pass chapter says "any writes performed by a load operation (as defined by its access masks) +//! to a given attachment may read and write back any memory locations within the image +//! subresource bound for that attachment", and a store alike; and, for an image with feedback +//! loop usage, its moves into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` and back around a pass +//! whose draws read it through a snapshot (`render_target::moved_barriers`), layout transitions +//! as the first move is. Nothing writes it through a shader (below). //! - **Relying on the driver, checked.** The owner's ruling of 2026-10-26 ("In place, trusting the //! driver") takes the image where the device's own check shows the move leaving every byte //! alone: a deliberate, scoped exception to never relying on undocumented Vulkan behaviour, -//! recorded in `docs/FAST-PATHS.md`. The check (`in_place_check.rs`) runs once per driver and -//! release, per memory class ([`PagesClass`]), and its verdict is kept in the shader cache's -//! content records ([`record_name`]); a class it did not pass keeps the shadow. +//! recorded in `docs/FAST-PATHS.md`. The owner's rulings of 2026-10-27 and 2026-11-07 widen it to +//! textures that render, where the check shows a pass's load and store and the feedback loop +//! moves leaving every byte alone too, whatever a linear image costs the GPU: a texture over the +//! caller's pages is the GPU's to work on there, as a Mac's GPU works on them. The check +//! (`in_place_check.rs`) runs once per driver and release, per memory class ([`PagesClass`]) and +//! access ([`Access`]), and its verdicts are kept in the shader cache's content records +//! ([`record_name`]); a class and access it did not pass keep the shadow. //! - **Which textures** ([`in_place`]): those whose declared usage (as Metal reports it, an -//! `Unknown` one every usage) has none of `RenderTarget`, `ShaderWrite` and `ShaderAtomic`, under -//! `HostPageTexturePolicy::InPlace`, over a class whose check passed. Plain Metal also writes +//! `Unknown` one every usage) has neither `ShaderWrite` nor `ShaderAtomic`, under +//! `HostPageTexturePolicy::InPlace`, over a class whose check passed for the texture's access +//! (one that renders, `RenderTarget` among its usage, its render check). Plain Metal also writes //! through a texture beyond its declared usage, and renders into one made without //! `RenderTarget`: such a write binds the texture's usage shadow (`texture/usage_shadow.rs`), and //! such a pass renders through an attachment stand-in (`attachment_stand_in.rs`), since the //! image has neither storage nor attachment usage; the copies of both touch texels alone. //! Elsewhere the texture is a shadow (`shadow.rs`), its notice naming why ([`ShadowCause`]) and -//! counted by cause (`WorkCounts::host_texture_shadows_*`). -//! - **Before the verdict.** A texture made before its class's verdict is known waits for nothing: -//! it is a shadow ([`ShadowCause::CheckPending`], counted apart). The first such texture starts -//! the check on a thread of its own; a device whose record holds the verdict knows it as it is -//! made, and starts none. +//! counted by cause (`WorkCounts::host_texture_shadows_*`, and those that render apart). +//! - **Before the verdict.** A texture made before its class's verdict for its access is known +//! waits for nothing: it is a shadow ([`ShadowCause::CheckPending`], counted apart). The first +//! such texture starts the check on a thread of its own; a device whose record holds the +//! verdicts knows them as it is made, and starts none. //! - **Visibility.** A command reads the image's texels in the memory a buffer over the same pages //! reads: the pages' host-visible, host-coherent import (a dma-buf's own import is of the same //! memory type). So a CPU write reaches a command through the image as it reaches the buffer's @@ -97,6 +108,60 @@ impl PagesClass { } } +/// What a texture over host pages does with its image in place, each checked apart: the +/// operations Vulkan lets touch bytes bound to the image beside its texels differ. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Access { + /// Its usage samples or reads it alone: its image takes its first move, and no other + /// operation that may touch those bytes. + Reads, + /// Its usage renders into it (`RenderTarget`, whatever else it holds): its image takes its + /// first move, render passes' load and store operations, and, made with feedback loop usage, + /// the moves into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` and back. + Renders, +} + +impl Access { + /// Every access, in the order the check runs them and the record holds their verdicts. + pub(crate) const ALL: [Access; 2] = [Access::Reads, Access::Renders]; + + /// The access of a texture of Metal `usage` (as Metal reports it). + pub(crate) fn of(usage: TextureUsage) -> Access { + match usage.contains(TextureUsage::RENDER_TARGET) { + true => Access::Renders, + false => Access::Reads, + } + } + + /// Its place in [`ALL`](Self::ALL). + pub(crate) fn index(self) -> usize { + match self { + Access::Reads => 0, + Access::Renders => 1, + } + } + + /// The operations its check covers, in words, for a notice. + pub(crate) fn words(self) -> &'static str { + match self { + Access::Reads => "the first move of an image", + Access::Renders => { + "the first move, a render pass's load and store and the feedback loop moves of an \ + image that renders" + } + } + } +} + +/// The verdicts a device's check gives: one for each class and access, class by class +/// ([`PagesClass::ALL`]), each class's accesses in [`Access::ALL`]'s order. +pub(crate) const VERDICTS: usize = PagesClass::ALL.len() * Access::ALL.len(); + +/// The place of `class`'s verdict for `access` among the [`VERDICTS`]. +pub(crate) fn verdict_index(class: PagesClass, access: Access) -> usize { + class.index() * Access::ALL.len() + access.index() +} + /// What the device's check answered for a class. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Verdict { @@ -136,18 +201,15 @@ impl Verdict { pub(crate) enum ShadowCause { /// The device's policy asks the shadow (`HostPageTexturePolicy::Shadow`). Exact, - /// Its usage renders into it (`RenderTarget`, whatever else it holds; an `Unknown` usage, - /// every usage, among them). - RenderTarget, - /// Its usage writes it through a shader (`ShaderWrite` or `ShaderAtomic`) and does not render - /// into it. + /// Its usage writes it through a shader (`ShaderWrite` or `ShaderAtomic`, whatever else it + /// holds; an `Unknown` usage, every usage, among them). ShaderWrite, - /// Its class's check has not answered yet. - CheckPending(PagesClass), - /// Its class's check found a byte changed. - CheckFailed(PagesClass), - /// Its class's check made no image. - Unchecked(PagesClass), + /// Its class's check for its access has not answered yet. + CheckPending(PagesClass, Access), + /// Its class's check for its access found a byte changed. + CheckFailed(PagesClass, Access), + /// Its class's check for its access made no image. + Unchecked(PagesClass, Access), /// The device makes no image over its texels as Metal lays them out: why, and the words. Refused(Refusal, String), } @@ -214,25 +276,27 @@ impl ShadowCause { ShadowCause::Exact => "the device's policy asks a shadow of every texture over host \ pages (HostPageTexturePolicy::Shadow)" .to_owned(), - ShadowCause::RenderTarget | ShadowCause::ShaderWrite => "its usage renders into it or \ - writes it (RenderTarget, ShaderWrite or ShaderAtomic), and \ - an image bound to host pages starts UNDEFINED \ - (VUID-VkImageCreateInfo-pNext-01443), its layout \ - transitions and a render pass's load and store operations \ - free to read and write every byte bound to it" + ShadowCause::ShaderWrite => "its usage writes it through a shader (ShaderWrite or \ + ShaderAtomic), and an image bound to host pages starts \ + UNDEFINED (VUID-VkImageCreateInfo-pNext-01443), its \ + layout transitions free to read and write every byte \ + bound to it, which no check covers for such an image" .to_owned(), - ShadowCause::CheckPending(class) => format!( - "the device's check of the first move of an image over {} has not answered yet", + ShadowCause::CheckPending(class, access) => format!( + "the device's check of {} over {} has not answered yet", + access.words(), class.words() ), - ShadowCause::CheckFailed(class) => format!( - "the device's check found the first move of an image over {} changing a byte \ - the CPU wrote beside it", + ShadowCause::CheckFailed(class, access) => format!( + "the device's check found {} over {} changing a byte the CPU wrote beside it", + access.words(), class.words() ), - ShadowCause::Unchecked(class) => { - format!("the device's check made no image over {}", class.words()) - } + ShadowCause::Unchecked(class, access) => format!( + "the device's check made no image over {} for {}", + class.words(), + access.words() + ), ShadowCause::Refused(_, why) => why.clone(), } } @@ -240,35 +304,34 @@ impl ShadowCause { /// Whether a texture over host pages of `class`, of Metal `usage` (as Metal reports it), on a /// device of `policy`, is tried as an image in place; else why it is a shadow (the module docs). -/// `verdict` answers the device's check for the class, asked only of a texture the policy and -/// usage let through (a pending one starts the check). +/// `verdict` answers the device's check for the class and the texture's access +/// ([`Access::of`]), asked only of a texture the policy and usage let through (a pending one +/// starts the check). pub(crate) fn in_place( policy: HostPageTexturePolicy, usage: TextureUsage, class: PagesClass, - verdict: impl FnOnce(PagesClass) -> Verdict, + verdict: impl FnOnce(PagesClass, Access) -> Verdict, ) -> Result<(), ShadowCause> { if policy == HostPageTexturePolicy::Shadow { return Err(ShadowCause::Exact); } - if usage.contains(TextureUsage::RENDER_TARGET) { - return Err(ShadowCause::RenderTarget); - } if usage.intersects(TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC) { return Err(ShadowCause::ShaderWrite); } - match verdict(class) { + let access = Access::of(usage); + match verdict(class, access) { Verdict::Passed => Ok(()), - Verdict::Pending => Err(ShadowCause::CheckPending(class)), - Verdict::Failed => Err(ShadowCause::CheckFailed(class)), - Verdict::Unchecked => Err(ShadowCause::Unchecked(class)), + Verdict::Pending => Err(ShadowCause::CheckPending(class, access)), + Verdict::Failed => Err(ShadowCause::CheckFailed(class, access)), + Verdict::Unchecked => Err(ShadowCause::Unchecked(class, access)), } } -/// A device's check verdicts (`DeviceShared::in_place`): one per class, and whether its check -/// started and settled. +/// A device's check verdicts (`DeviceShared::in_place`): one per class and access +/// ([`VERDICTS`]), and whether its check started and settled. pub(crate) struct InPlaceChecks { - verdicts: [AtomicU8; 3], + verdicts: [AtomicU8; VERDICTS], /// The check was started on its thread (at most once per device). started: AtomicBool, /// Every class's verdict is known: from the record, or the check ended. @@ -287,7 +350,7 @@ impl InPlaceChecks { /// No verdict yet; `fail` as [`InPlaceChecks::fail`] says. pub(crate) fn new(fail: bool) -> InPlaceChecks { InPlaceChecks { - verdicts: [0, 0, 0].map(AtomicU8::new), + verdicts: [0; VERDICTS].map(AtomicU8::new), started: AtomicBool::new(false), settled: Mutex::new(false), wake: Condvar::new(), @@ -302,20 +365,23 @@ impl InPlaceChecks { lock(&self.notes).push(line); } - /// `class`'s verdict now. - pub(crate) fn verdict(&self, class: PagesClass) -> Verdict { - let byte = self.verdicts[class.index()].load(Ordering::Acquire); + /// `class`'s verdict for `access` now. + pub(crate) fn verdict(&self, class: PagesClass, access: Access) -> Verdict { + let byte = self.verdicts[verdict_index(class, access)].load(Ordering::Acquire); Verdict::of_byte(byte).unwrap_or(Verdict::Pending) } - /// Every class's verdict now. - pub(crate) fn verdicts(&self) -> [Verdict; 3] { - PagesClass::ALL.map(|class| self.verdict(class)) + /// Every verdict now, in [`VERDICTS`]' order. + pub(crate) fn verdicts(&self) -> [Verdict; VERDICTS] { + std::array::from_fn(|at| { + let byte = self.verdicts[at].load(Ordering::Acquire); + Verdict::of_byte(byte).unwrap_or(Verdict::Pending) + }) } - /// Give `class` its verdict. - pub(crate) fn set(&self, class: PagesClass, verdict: Verdict) { - self.verdicts[class.index()].store(verdict.byte(), Ordering::Release); + /// Give `class` its verdict for `access`. + pub(crate) fn set(&self, class: PagesClass, access: Access, verdict: Verdict) { + self.verdicts[verdict_index(class, access)].store(verdict.byte(), Ordering::Release); } /// Whether the check is to fail whatever the moves did. @@ -367,7 +433,7 @@ impl InPlaceChecks { /// The version of what the check does and of how a record of it is named and framed: a change to /// either bumps it, and a record of another version is never read (its name differs, and so does /// the version it holds). -pub(crate) const CHECK_VERSION: u32 = 1; +pub(crate) const CHECK_VERSION: u32 = 2; /// A record's first bytes. const MAGIC: [u8; 8] = *b"M2VINPL\0"; @@ -375,8 +441,9 @@ const MAGIC: [u8; 8] = *b"M2VINPL\0"; /// The domain tag of a record's name. const NAME_TAG: &[u8] = b"metal2vulkan in-place check record\0"; -/// What the check checks, in a record's name: the first move of an image over host pages. A check -/// of another operation keeps its own record beside this one's, which it leaves valid. +/// What the check checks, in a record's name: the first move of an image over host pages, and of +/// one that renders its render passes' operations and feedback loop moves. A check of another +/// operation keeps its own record beside this one's, which it leaves valid. const CHECK_KIND: &[u8] = b"first move\0"; /// The driver identity a verdict holds for: `VkPhysicalDeviceProperties`' vendor, device and @@ -434,12 +501,12 @@ pub(crate) fn record_name(identity: &DriverIdentity) -> String { /// version u32 CHECK_VERSION /// runtime u32 RUNTIME_VERSION /// identity 32 bytes DriverIdentity::digest -/// verdicts 3 bytes one per class, in PagesClass::ALL's order +/// verdicts 6 bytes one per class and access, VERDICTS' order (verdict_index) /// checksum 32 bytes SHA-256 of every byte before it /// ``` /// /// Integers are little-endian. -pub(crate) fn encode(identity: &DriverIdentity, verdicts: [Verdict; 3]) -> Vec { +pub(crate) fn encode(identity: &DriverIdentity, verdicts: [Verdict; VERDICTS]) -> Vec { let mut bytes = Vec::with_capacity(RECORD_BYTES); bytes.extend_from_slice(&MAGIC); bytes.extend_from_slice(&CHECK_VERSION.to_le_bytes()); @@ -452,12 +519,12 @@ pub(crate) fn encode(identity: &DriverIdentity, verdicts: [Verdict; 3]) -> Vec Option<[Verdict; 3]> { +pub(crate) fn decode(identity: &DriverIdentity, bytes: &[u8]) -> Option<[Verdict; VERDICTS]> { if bytes.len() != RECORD_BYTES { return None; } @@ -478,11 +545,11 @@ pub(crate) fn decode(identity: &DriverIdentity, bytes: &[u8]) -> Option<[Verdict { return None; } - let verdicts = [rest[0], rest[1], rest[2]].map(Verdict::of_byte); - match verdicts { - [Some(a), Some(b), Some(c)] if ![a, b, c].contains(&Verdict::Pending) => Some([a, b, c]), - _ => None, + let mut verdicts = [Verdict::Pending; VERDICTS]; + for (verdict, &byte) in verdicts.iter_mut().zip(rest) { + *verdict = Verdict::of_byte(byte).filter(|&known| known != Verdict::Pending)?; } + Some(verdicts) } impl Device { @@ -542,18 +609,21 @@ impl Device { .content_store() .load_content(&name, |bytes| decode(&identity, &bytes)); if let Lookup::Hit(verdicts) = looked { - for (class, verdict) in PagesClass::ALL.into_iter().zip(verdicts) { - shared.in_place.set(class, verdict); - shared.counts.in_place_check_recalled(); + for class in PagesClass::ALL { + for access in Access::ALL { + let verdict = verdicts[verdict_index(class, access)]; + shared.in_place.set(class, access, verdict); + shared.counts.in_place_check_recalled(); + } } shared.in_place.settle(None); } } - /// `class`'s verdict for a texture asking it now: a pending one starts the check, unless it - /// started already. Never waits. - pub(crate) fn in_place_verdict(&self, class: PagesClass) -> Verdict { - let verdict = self.shared().in_place.verdict(class); + /// `class`'s verdict for `access` for a texture asking it now: a pending one starts the + /// check, unless it started already. Never waits. + pub(crate) fn in_place_verdict(&self, class: PagesClass, access: Access) -> Verdict { + let verdict = self.shared().in_place.verdict(class, access); if verdict == Verdict::Pending { self.start_in_place_checks(); } @@ -584,14 +654,23 @@ impl Device { self.shared().in_place.took() } - /// The device's check's verdicts now, one line per class, and what it found changed where a - /// class failed. A runtime extension for the lanes that report it. + /// The device's check's verdicts now, one line per class for a texture that reads + /// (`Pointer: Passed`), then one per class for one that renders (`Pointer renders: Passed`), + /// and what it found changed where one failed. A runtime extension for the lanes that report + /// it. #[doc(hidden)] pub fn in_place_check_report(&self) -> Vec { let checks = &self.shared().in_place; - let verdicts = PagesClass::ALL + let line = |class: PagesClass, access: Access| { + let verdict = checks.verdict(class, access); + match access { + Access::Reads => format!("{class:?}: {verdict:?}"), + Access::Renders => format!("{class:?} renders: {verdict:?}"), + } + }; + let verdicts = Access::ALL .into_iter() - .map(|class| format!("{class:?}: {:?}", checks.verdict(class))); + .flat_map(|access| PagesClass::ALL.map(|class| line(class, access))); verdicts .chain(lock(&checks.notes).iter().cloned()) .collect() diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index 3a5413ebb..25dadd7bc 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -1,6 +1,7 @@ -//! The device's check of the first move of an image in place over host pages (`in_place.rs`): -//! whether that move leaves every byte alone while the CPU writes beside it, per class of pages -//! ([`PagesClass`]), on a thread of its own. +//! The device's check of an image in place over host pages (`in_place.rs`): whether the +//! operations Vulkan lets touch the bytes bound to it beside its texels leave every byte alone +//! while the CPU writes beside it, per class of pages ([`PagesClass`]) and access ([`Access`]), on +//! a thread of its own. //! //! - **What it does.** For each class it makes a buffer as the product makes one there (a no-copy //! buffer over anonymous pages it maps, imported by their pointer; a buffer of the runtime's own @@ -18,6 +19,18 @@ //! must then read the CPU's write where the CPU wrote it, and the pattern elsewhere. Each class //! runs every shape of [`SHAPES`] (texels of 1, 2, 4, 8 and 16 bytes, rows apart or one after //! another, and 3840x2160 at 4 bytes) [`ROUNDS`] times. +//! - **An image that renders** ([`Access::Renders`]) is checked apart, in rounds of their own: the +//! texture is made with `RenderTarget` usage as well, as the program's render targets are, so +//! its image takes the feedback loop usage where the product's does; the writer writes the bytes +//! between rows and after the image alone, through the image's first move, its moves into +//! `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` and back where it has the usage +//! (`Texture::settle_feedback_moves`, as `render_target::moved_barriers` records them), and a +//! render pass of a command queue of the check's own that clears it to zero at its load and +//! stores it, waited for (each by a submission the round waits for). Every texel must then read +//! zero, and every other byte as above. A draw's color writes reach its fragments' texels alone +//! (the Memory Model); the load, store and resolve operations and the layout transitions are +//! what Vulkan lets touch the rest of the subresource, and the program's resolves into such a +//! texture are not among the rounds. //! - **Its buffers' addresses** lie outside the Metal address space (`AddressPlacement::Outside`, //! `address.rs`), each made as the product makes its class's otherwise: the check runs while //! the program makes its resources, so a range of the space it took would refuse a pin of the @@ -67,21 +80,26 @@ use crate::device::holds::Holder; use crate::exit_guard; use crate::host_memory::HostMemory; -use crate::in_place::{encode, mark_checking, record_name, PagesClass, Verdict}; +use crate::in_place::{encode, mark_checking, record_name, Access, PagesClass, Verdict}; use crate::values::ResourceOptions; use crate::{ - AddressPlacement, Buffer, BufferContents, BufferDescriptor, Device, TextureDescriptor, + AddressPlacement, Buffer, BufferContents, BufferDescriptor, ClearColor, CommandQueue, Device, + LoadAction, RenderPassDescriptor, StoreAction, Texture, TextureDescriptor, }; use metal2vulkan::device::HostPageTexturePolicy; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use std::ptr::NonNull; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Barrier; -use std::time::Instant; +use std::time::{Duration, Instant}; /// How many times each shape is checked in each class. pub(crate) const ROUNDS: usize = 3; +/// The longest a render round waits for its pass's command buffer: a pass that clears a 3840x2160 +/// surface and stores it. +const PASS_WAIT: Duration = Duration::from_secs(20); + /// A shape the check makes a texture of: its format, the bytes of one texel, its width and height, /// and its rows' pitch. #[derive(Clone, Copy, Debug)] @@ -124,6 +142,12 @@ const fn shape(format: PixelFormat, texel: u64, width: u64, height: u64, bpr: u6 } impl Shape { + /// Whether the window's byte at `offset` is one of the texture's texels. + fn is_texel(&self, offset: u64) -> bool { + offset < self.bytes_per_row * self.height + && offset % self.bytes_per_row < self.width * self.texel + } + /// The bytes of the window the check fills and writes: the texture's rows, then the bytes /// after them to two pages past the page their last byte is in. fn window(&self, page: u64) -> u64 { @@ -153,8 +177,10 @@ impl Device { let started = exit_guard::spawn(builder, move || run(weak)); if started.is_err() { for class in PagesClass::ALL { - if checks.verdict(class) == Verdict::Pending { - checks.set(class, Verdict::Unchecked); + for access in Access::ALL { + if checks.verdict(class, access) == Verdict::Pending { + checks.set(class, access, Verdict::Unchecked); + } } } checks.settle(None); @@ -162,30 +188,36 @@ impl Device { } } -/// The check's thread: each class in turn, its verdict given as it is known, then the record. +/// The check's thread: each class in turn, each of its accesses, each verdict given as it is +/// known, then the record. fn run(weak: crate::device::WeakDevice) { mark_checking(); let started = Instant::now(); let mut stopped = false; for class in PagesClass::ALL { - let Some(device) = weak.hold() else { - return; - }; - if device.shared().in_place.verdict(class) != Verdict::Pending { - continue; + for access in Access::ALL { + let Some(device) = weak.hold() else { + return; + }; + if device.shared().in_place.verdict(class, access) != Verdict::Pending { + continue; + } + if stopped || word_overwritten(&device) { + stopped = true; + device + .shared() + .in_place + .set(class, access, Verdict::Unchecked); + continue; + } + let Some(verdict) = check_class(&device, class, access) else { + // The process is exiting, or the program let the device go: nothing is kept. + return; + }; + let checks = &device.shared().in_place; + checks.set(class, access, verdict); + device.shared().counts.in_place_check_ran(verdict); } - if stopped || word_overwritten(&device) { - stopped = true; - device.shared().in_place.set(class, Verdict::Unchecked); - continue; - } - let Some(verdict) = check_class(&device, class) else { - // The process is exiting, or the program let the device go: nothing is kept. - return; - }; - let checks = &device.shared().in_place; - checks.set(class, verdict); - device.shared().counts.in_place_check_ran(verdict); } let Some(device) = weak.hold() else { return; @@ -220,15 +252,26 @@ fn word_overwritten(device: &Device) -> bool { unsafe { device.shared().loader_word.overwritten() } } -/// The verdict of `class` on `device`: every shape's rounds, until one fails, or until the -/// device's loader word is found overwritten (unchecked then where no round ran). `None` where -/// the process is exiting, or the program's last drop stopped the device's holds before a round -/// (`device/holds.rs`). -fn check_class(device: &Device, class: PagesClass) -> Option { +/// The verdict of `class` for `access` on `device`: every shape's rounds, until one fails, or +/// until the device's loader word is found overwritten (unchecked then where no round ran). +/// `None` where the process is exiting, or the program's last drop stopped the device's holds +/// before a round (`device/holds.rs`). +fn check_class(device: &Device, class: PagesClass, access: Access) -> Option { let page = host_page(); let Some(pages) = ClassPages::make(device, class, BUFFER_BYTES) else { return Some(Verdict::Unchecked); }; + // The command queue an image that renders takes its passes on: the check's own. + let queue = match access { + Access::Reads => None, + Access::Renders => { + let made = exit_guard::enter().map(|_busy| device.new_command_queue()); + match made? { + Ok(queue) => Some(queue), + Err(_) => return Some(Verdict::Unchecked), + } + } + }; let mut made = 0; for shape in SHAPES { if shape.window(page) > BUFFER_BYTES { @@ -243,7 +286,7 @@ fn check_class(device: &Device, class: PagesClass) -> Option { } let outcome = { let _busy = exit_guard::enter()?; - check_round(&pages, shape, round, page) + check_round(&pages, shape, round, page, queue.as_ref()) }; match outcome { Round::Kept => made += 1, @@ -255,8 +298,14 @@ fn check_class(device: &Device, class: PagesClass) -> Option { Some(column) if column >= shape.width * shape.texel => "between two rows", _ => "a texel", }; + let operations = match access { + Access::Reads => "the first move", + Access::Renders => { + "the first move, feedback loop moves or a pass's clear and store" + } + }; device.shared().in_place.note(format!( - "{class:?}: the first move of a {:?} image of {}x{} with rows {} bytes \ + "{class:?}: {operations} of a {:?} image of {}x{} with rows {} bytes \ apart changed byte {offset} ({place}) from {due:#04x} to {read:#04x} in \ round {round}", shape.format, shape.width, shape.height, shape.bytes_per_row @@ -285,8 +334,15 @@ enum Round { } /// One round of `shape` over `pages`, inside the caller's section: the pattern, the texture, the -/// writes beside its image's first move, and the bytes compared. -fn check_round(pages: &ClassPages, shape: Shape, round: usize, page: u64) -> Round { +/// writes beside its image's first move (and, for an image that renders, `queue` its queue, beside +/// its feedback loop moves and a pass that clears and stores it), and the bytes compared. +fn check_round( + pages: &ClassPages, + shape: Shape, + round: usize, + page: u64, + queue: Option<&CommandQueue>, +) -> Round { let window = shape.window(page); let bytes = Bytes { start: pages.start, @@ -296,7 +352,12 @@ fn check_round(pages: &ClassPages, shape: Shape, round: usize, page: u64) -> Rou bytes.fill(&pattern); let mut descriptor = TextureDescriptor::texture_2d(shape.format, shape.width, shape.height, false); - descriptor.usage = TextureUsage::SHADER_READ; + descriptor.usage = match queue { + None => TextureUsage::SHADER_READ, + Some(_) => TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + }; + // An image that renders: the writer writes beside its texels alone, which its pass writes. + let texels = queue.map(|_| shape); // The runtime's own texture: it takes no resource ID, so the program's IDs are Metal's // whether or when the check runs. let Ok(texture) = pages @@ -311,13 +372,19 @@ fn check_round(pages: &ClassPages, shape: Shape, round: usize, page: u64) -> Rou let settled = std::thread::scope(|scope| { let builder = std::thread::Builder::new().name("m2v-in-place-writes".to_owned()); let writer = exit_guard::spawn_scoped(scope, builder, || { - bytes.write_until(&pattern, &stop, &started, &written); + bytes.write_until(&pattern, texels, (&stop, &started, &written)); }); if writer.is_err() { return None; } started.wait(); - let settled = texture.settle_in_place(); + let settled = match texture.settle_in_place() { + Some(Ok(())) => match queue { + None => Some(Ok(())), + Some(queue) => Some(render(queue, &texture)), + }, + other => other, + }; stop.store(true, Ordering::Release); settled }); @@ -325,12 +392,41 @@ fn check_round(pages: &ClassPages, shape: Shape, round: usize, page: u64) -> Rou return Round::NotMade; }; drop(texture); - match bytes.compare(&pattern, written.load(Ordering::Acquire)) { + match bytes.compare(&pattern, texels, written.load(Ordering::Acquire)) { None => Round::Kept, Some(changed) => Round::Changed(changed), } } +/// An image that renders, after its first move: its moves into the feedback loop layout and back +/// where it has the usage, then a pass of `queue` that clears it to zero at its load and stores +/// it, each waited for. An error where either was not made, or the pass's command buffer failed or +/// did not complete within [`PASS_WAIT`]. +fn render(queue: &CommandQueue, texture: &Texture) -> Result<(), crate::Error> { + if let Some(moved) = texture.settle_feedback_moves() { + moved?; + } + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(texture.clone()); + color.load_action = LoadAction::Clear; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + color.store_action = StoreAction::Store; + let command_buffer = queue.command_buffer()?; + command_buffer + .render_command_encoder(&pass)? + .end_encoding()?; + command_buffer.commit()?; + let failed = || crate::error::internal("the in-place check's pass did not complete"); + command_buffer + .wait_until_completed_for(PASS_WAIT) + .map_err(|_| failed())?; + match command_buffer.error() { + None => Ok(()), + Some(_) => Err(failed()), + } +} + /// The pages of one class's check: its buffer, and the host address of its byte 0. struct ClassPages { buffer: Buffer, @@ -571,39 +667,55 @@ impl Bytes { } /// Write each byte once, the pattern's complement, at the stride, until `stop` or every byte - /// is written; `started` once the first is. How many were written goes in `written`. + /// is written; `started` once the first is. Where `texels` names the texture's shape, its + /// texels are passed over (its pass writes them), and only the bytes beside them written. How + /// many of the stride's bytes were reached goes in `written`. fn write_until( &self, pattern: &Pattern, - stop: &AtomicBool, - started: &Barrier, - written: &AtomicU64, + texels: Option, + (stop, started, written): (&AtomicBool, &Barrier, &AtomicU64), ) { let stride = self.stride(); let mut n = 0; - while n < self.length && (n == 0 || !stop.load(Ordering::Acquire)) { + let mut first = true; + while n < self.length && (first || !stop.load(Ordering::Acquire)) { let offset = self.nth(n, stride); + n += 1; + if texels.is_some_and(|shape| shape.is_texel(offset)) { + continue; + } // SAFETY: as in `fill`; the round's thread does not touch the bytes meanwhile. unsafe { self.byte(offset).write_volatile(!pattern.at(offset)) }; - n += 1; - if n == 1 { + if first { + first = false; started.wait(); } } - if n == 0 { + if first { started.wait(); } written.store(n, Ordering::Release); } - /// The first byte that reads other than the writer left it, where the first `written` were - /// written: its offset, what was due and what was read; `None` where every byte reads right. - /// Each written byte must read its complement, and is set back to the pattern as it is read; - /// then every byte must read the pattern, compared a period at a time. - fn compare(&self, pattern: &Pattern, written: u64) -> Option<(u64, u8, u8)> { + /// The first byte that reads other than the writer and the round left it, where the first + /// `written` of the stride's bytes were reached: its offset, what was due and what was read; + /// `None` where every byte reads right. Each written byte must read its complement, and is set + /// back to the pattern as it is read; then every byte must read the pattern, compared a + /// period at a time, but, where `texels` names the shape a pass cleared, its texels, which + /// must read zero. + fn compare( + &self, + pattern: &Pattern, + texels: Option, + written: u64, + ) -> Option<(u64, u8, u8)> { let stride = self.stride(); for n in 0..written { let offset = self.nth(n, stride); + if texels.is_some_and(|shape| shape.is_texel(offset)) { + continue; + } let due = !pattern.at(offset); // SAFETY: as in `fill`; the writer was joined. let read = unsafe { self.byte(offset).read_volatile() }; @@ -613,12 +725,36 @@ impl Bytes { // SAFETY: as above. unsafe { self.byte(offset).write_volatile(pattern.at(offset)) }; } - let mut offset = 0; - while offset < self.length { - let count = (self.length - offset).min(PERIOD as u64) as usize; - // SAFETY: as above; nothing writes the bytes while the slice is read. + let Some(shape) = texels else { + return self.matches(pattern, 0, self.length); + }; + // Each row's texels read zero, and the bytes after them to the next row the pattern. + let row_bytes = shape.width * shape.texel; + for row in 0..shape.height { + let start = row * shape.bytes_per_row; + // SAFETY: as above; the row's texels lie in the window. + let read = unsafe { std::slice::from_raw_parts(self.byte(start), row_bytes as usize) }; + if let Some(at) = read.iter().position(|&read| read != 0) { + return Some((start + at as u64, 0, read[at])); + } + let next = start + shape.bytes_per_row; + if let Some(changed) = self.matches(pattern, start + row_bytes, next) { + return Some(changed); + } + } + self.matches(pattern, shape.bytes_per_row * shape.height, self.length) + } + + /// The first byte from `from` to `to` that does not read the pattern: its offset, what was due + /// and what was read; `None` where every one does. Compared a period at a time. + fn matches(&self, pattern: &Pattern, from: u64, to: u64) -> Option<(u64, u8, u8)> { + let mut offset = from; + while offset < to { + let phase = (offset % PERIOD as u64) as usize; + let count = (to - offset).min((PERIOD - phase) as u64) as usize; + // SAFETY: as in `compare`; nothing writes the bytes while the slice is read. let read = unsafe { std::slice::from_raw_parts(self.byte(offset), count) }; - let due = &pattern.bytes[..count]; + let due = &pattern.bytes[phase..phase + count]; if let Some(at) = read.iter().zip(due).position(|(read, due)| read != due) { return Some((offset + at as u64, due[at], read[at])); } diff --git a/crates/metal2vulkan-runtime/src/linear_attachment.rs b/crates/metal2vulkan-runtime/src/linear_attachment.rs index e0be3ff3c..b136f0ebd 100644 --- a/crates/metal2vulkan-runtime/src/linear_attachment.rs +++ b/crates/metal2vulkan-runtime/src/linear_attachment.rs @@ -2,7 +2,8 @@ //! //! A texture over a buffer of the runtime's memory is a linear image over the buffer's bytes where //! the device makes one that lies on Metal's layout there (`Device::alias_image`; one over a -//! no-copy buffer's host pages is a shadow), and a heap's texture may be a linear image +//! no-copy buffer's host pages is an image in place where the device's check passed for an image +//! that renders, `in_place.rs`, else a shadow), and a heap's texture may be a linear image //! (`texture/heap.rs`). On a device that enabled `VK_NV_linear_color_attachment`'s //! `linearColorAttachment` (`enables.rs`), such an image of a format whose linear tiling has //! `LINEAR_COLOR_ATTACHMENT_NV` takes color attachment usage (`ImageFacts::linear`), and a pass diff --git a/crates/metal2vulkan-runtime/src/render_target.rs b/crates/metal2vulkan-runtime/src/render_target.rs index c412152a4..8a33f7770 100644 --- a/crates/metal2vulkan-runtime/src/render_target.rs +++ b/crates/metal2vulkan-runtime/src/render_target.rs @@ -1061,6 +1061,37 @@ pub(super) unsafe fn moved_barriers( } } +/// The moves of a color image's `range` from `GENERAL` into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` +/// and back, one after the other, as [`moved_barriers`] records them around an instance whose +/// draws read the image through a snapshot: the device's check of an image in place over host +/// pages that renders (`in_place_check.rs`), which checks that those moves leave every byte bound +/// to it beside its texels alone. +/// +/// # Safety +/// +/// As [`moved_barriers`]': `command_buffer` is recording outside a render pass, only the caller +/// records it, the image is live until it completes, made with feedback loop usage, and its +/// `range` rests in `GENERAL`. +pub(crate) unsafe fn feedback_moves( + raw: &ash::Device, + command_buffer: vk::CommandBuffer, + image: vk::Image, + range: vk::ImageSubresourceRange, + family: vk::QueueFlags, +) { + let moved = [MovedImage { + image, + range, + layout: vk::ImageLayout::ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT, + }]; + // SAFETY: the caller's contract; the first moves the range out of `GENERAL`, where it rests, + // and the second back from the layout the first left. + unsafe { + moved_barriers(raw, command_buffer, &moved, true, family); + moved_barriers(raw, command_buffer, &moved, false, family); + } +} + /// The pass of `shape` with every operation `LOAD` and `STORE`: compatible with every pass of /// that shape, kept by its device ([`create`]). A shape without attachments takes its device's /// kept pass (`attachmentless.rs`). diff --git a/crates/metal2vulkan-runtime/src/tests/in_place.rs b/crates/metal2vulkan-runtime/src/tests/in_place.rs index df790adca..0acdf4f22 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place.rs @@ -2,20 +2,20 @@ //! and why one is a shadow, and the record that keeps the device's check's verdicts. //! //! - **The decision.** Under `HostPageTexturePolicy::Shadow` every texture is a shadow, the check -//! never asked; under `InPlace` a texture whose usage renders into it (`RenderTarget`, -//! `Unknown`) is one counted as a render target, and one that writes it through a shader and -//! does not render into it (`ShaderWrite`, `ShaderAtomic`) one counted as a shader write, the -//! check never asked; and a texture that only samples or reads is tried in place exactly where -//! its class's check passed, else a shadow naming the check's answer (pending, failed, -//! unchecked). +//! never asked; under `InPlace` a texture whose usage writes it through a shader +//! (`ShaderWrite`, `ShaderAtomic`, `Unknown`, whatever else it holds) is one counted as a shader +//! write, the check never asked; and a texture that samples, reads or renders is tried in place +//! exactly where its class's check passed for its access (one that renders, `RenderTarget`, its +//! render check; else its read check), else a shadow naming the check's answer (pending, +//! failed, unchecked) and the access. //! - **The record.** Its verdicts read back for the identity it was written for, and nothing else //! reads: a record cut short or grown, of another check version or runtime, of another identity, //! with a byte changed (its checksum), or holding a pending or unknown verdict. //! - **Its name** changes with every field of the driver's identity. use crate::in_place::{ - decode, encode, in_place, record_name, DriverIdentity, InPlaceChecks, PagesClass, ShadowCause, - Verdict, CHECK_VERSION, + decode, encode, in_place, record_name, verdict_index, Access, DriverIdentity, InPlaceChecks, + PagesClass, ShadowCause, Verdict, CHECK_VERSION, VERDICTS, }; use metal2vulkan::device::HostPageTexturePolicy; use metal2vulkan::metal::TextureUsage; @@ -40,21 +40,25 @@ fn each_usage() -> Vec { ] } -/// The shadow `usage` takes whatever the check answers: a render target's where it renders -/// into the texture, whatever else it holds, a shader write's where it writes it through a shader -/// alone; `None` where it only samples or reads. +/// The shadow `usage` takes whatever the check answers: a shader write's where it writes the +/// texture through a shader, whatever else it holds; `None` where it samples, reads or renders. fn written(usage: TextureUsage) -> Option { - if usage.contains(TextureUsage::RENDER_TARGET) { - Some(ShadowCause::RenderTarget) - } else if usage.intersects(TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC) { - Some(ShadowCause::ShaderWrite) - } else { - None + match usage.intersects(TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC) { + true => Some(ShadowCause::ShaderWrite), + false => None, + } +} + +/// The access whose check `usage` asks: an image that renders where it holds `RenderTarget`. +fn access_of(usage: TextureUsage) -> Access { + match usage.contains(TextureUsage::RENDER_TARGET) { + true => Access::Renders, + false => Access::Reads, } } #[test] -fn the_decision_takes_only_a_sampled_texture_whose_class_passed() { +fn the_decision_takes_a_texture_that_does_not_write_whose_class_passed_its_access() { let mut usages = each_usage(); usages.push(TextureUsage::SHADER_READ | TextureUsage::PIXEL_FORMAT_VIEW); usages.push(TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET); @@ -76,16 +80,18 @@ fn the_decision_takes_only_a_sampled_texture_whose_class_passed() { for verdict in VERDICTS { // Shadow: always the exact form, the check never asked. let asked = std::cell::Cell::new(false); - let decided = in_place(HostPageTexturePolicy::Shadow, usage, class, |_| { + let decided = in_place(HostPageTexturePolicy::Shadow, usage, class, |_, _| { asked.set(true); verdict }); assert_eq!(decided, Err(ShadowCause::Exact)); assert!(!asked.get(), "the exact form asks no check"); - // In place: written textures never asked; the rest follow the verdict. + // In place: written textures never asked; the rest follow the verdict of their + // access. let asked = std::cell::Cell::new(false); - let decided = in_place(HostPageTexturePolicy::InPlace, usage, class, |of| { - assert_eq!(of, class); + let access = access_of(usage); + let decided = in_place(HostPageTexturePolicy::InPlace, usage, class, |of, by| { + assert_eq!((of, by), (class, access)); asked.set(true); verdict }); @@ -94,9 +100,9 @@ fn the_decision_takes_only_a_sampled_texture_whose_class_passed() { } else { match verdict { Verdict::Passed => Ok(()), - Verdict::Pending => Err(ShadowCause::CheckPending(class)), - Verdict::Failed => Err(ShadowCause::CheckFailed(class)), - Verdict::Unchecked => Err(ShadowCause::Unchecked(class)), + Verdict::Pending => Err(ShadowCause::CheckPending(class, access)), + Verdict::Failed => Err(ShadowCause::CheckFailed(class, access)), + Verdict::Unchecked => Err(ShadowCause::Unchecked(class, access)), } }; assert_eq!(decided, expected, "{class:?} {usage:?} {verdict:?}"); @@ -110,10 +116,13 @@ fn the_decision_takes_only_a_sampled_texture_whose_class_passed() { fn every_shadow_cause_names_itself() { let causes = [ ShadowCause::Exact, - ShadowCause::RenderTarget, - ShadowCause::CheckPending(PagesClass::Pointer), - ShadowCause::CheckFailed(PagesClass::DmaBuf), - ShadowCause::Unchecked(PagesClass::Fresh), + ShadowCause::ShaderWrite, + ShadowCause::CheckPending(PagesClass::Pointer, Access::Reads), + ShadowCause::CheckPending(PagesClass::Pointer, Access::Renders), + ShadowCause::CheckFailed(PagesClass::DmaBuf, Access::Reads), + ShadowCause::CheckFailed(PagesClass::DmaBuf, Access::Renders), + ShadowCause::Unchecked(PagesClass::Fresh, Access::Reads), + ShadowCause::Unchecked(PagesClass::Fresh, Access::Renders), ]; let words: Vec = causes.iter().map(ShadowCause::words).collect(); for (at, word) in words.iter().enumerate() { @@ -124,10 +133,10 @@ fn every_shadow_cause_names_itself() { ); } assert!(words[0].contains("HostPageTexturePolicy::Shadow")); - assert!(words[2].contains("not answered")); - assert!(words[3].contains("dma-bufs")); - // A shader write's shadow announces what a render target's does: the notice is unchanged. - assert_eq!(ShadowCause::ShaderWrite.words(), words[1]); + assert!(words[1].contains("ShaderWrite")); + assert!(words[2].contains("not answered") && words[3].contains("not answered")); + assert!(words[3].contains("render pass")); + assert!(words[4].contains("dma-bufs")); } /// A driver identity, every field set. @@ -154,7 +163,14 @@ fn rechecked(mut bytes: Vec) -> Vec { #[test] fn a_record_reads_back_for_its_identity_alone() { let identity = identity(); - let verdicts = [Verdict::Passed, Verdict::Unchecked, Verdict::Failed]; + let verdicts = [ + Verdict::Passed, + Verdict::Failed, + Verdict::Unchecked, + Verdict::Passed, + Verdict::Failed, + Verdict::Unchecked, + ]; let bytes = encode(&identity, verdicts); assert_eq!(decode(&identity, &bytes), Some(verdicts)); @@ -182,15 +198,17 @@ fn a_record_reads_back_for_its_identity_alone() { runtime[12..16].copy_from_slice(&other.to_le_bytes()); assert_eq!(decode(&identity, &rechecked(runtime)), None); - // A pending or unknown verdict, with a checksum that holds. - for byte in [0u8, 4, 0xff] { - let mut verdict = bytes.clone(); - verdict[48] = byte; - assert_eq!( - decode(&identity, &rechecked(verdict)), - None, - "verdict {byte}" - ); + // A pending or unknown verdict, at any of their places, with a checksum that holds. + for at in 48..48 + VERDICTS { + for byte in [0u8, 4, 0xff] { + let mut verdict = bytes.clone(); + verdict[at] = byte; + assert_eq!( + decode(&identity, &rechecked(verdict)), + None, + "verdict {byte} at {at}" + ); + } } // Another identity. @@ -232,13 +250,30 @@ fn a_record_s_name_follows_every_field_of_the_identity() { fn the_checks_state_settles_once_and_wakes_its_waiters() { let checks = InPlaceChecks::new(false); assert!(!checks.forced_failure()); - assert_eq!(checks.verdicts(), [Verdict::Pending; 3]); + assert_eq!(checks.verdicts(), [Verdict::Pending; VERDICTS]); assert!(!checks.wait(Duration::from_millis(1))); assert!(checks.start()); assert!(!checks.start(), "the check starts once"); - checks.set(PagesClass::Fresh, Verdict::Passed); - assert_eq!(checks.verdict(PagesClass::Fresh), Verdict::Passed); - assert_eq!(checks.verdict(PagesClass::Pointer), Verdict::Pending); + checks.set(PagesClass::Fresh, Access::Renders, Verdict::Passed); + assert_eq!( + checks.verdict(PagesClass::Fresh, Access::Renders), + Verdict::Passed + ); + assert_eq!( + checks.verdict(PagesClass::Fresh, Access::Reads), + Verdict::Pending + ); + assert_eq!( + checks.verdict(PagesClass::Pointer, Access::Renders), + Verdict::Pending + ); + // Each class and access has a place of its own. + let mut places: Vec = PagesClass::ALL + .into_iter() + .flat_map(|class| Access::ALL.map(|access| verdict_index(class, access))) + .collect(); + places.sort_unstable(); + assert_eq!(places, (0..VERDICTS).collect::>()); std::thread::scope(|scope| { let waiter = scope.spawn(|| checks.wait(Duration::from_secs(30))); checks.settle(Some(Duration::from_millis(5))); diff --git a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs index fe3e943fa..6314877f1 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs @@ -83,7 +83,12 @@ fn pins(odd: bool) -> impl Iterator { #[test] fn the_in_place_check_takes_no_range_of_the_metal_space() { let verdicts = |device: &Device| -> Vec { - device.in_place_check_report().into_iter().take(3).collect() + let lines = crate::in_place::VERDICTS; + device + .in_place_check_report() + .into_iter() + .take(lines) + .collect() }; let reference = { let scratch = Scratch::new("in-place-check-reference"); diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index ce6c443c7..6bbbe951a 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -81,7 +81,7 @@ use super::host_bytes::HostBytes; use super::image_plan::{ check_image_limits, plan_image, DepthImageFacts, ImageFacts, ImagePlan, ImageRefusal, }; -use super::in_place::{self, PagesClass, Refusal, ShadowCause, Verdict}; +use super::in_place::{self, Access, PagesClass, Refusal, ShadowCause, Verdict}; use super::key_hash::KeyMap; use super::linear_plan::{ aliases, check_linear_limits, holding, linear_lack, LinearImage, LinearLack, @@ -2221,11 +2221,13 @@ impl Device { .map_err(|refusal| image_error(call, refusal))?; // Over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their // pointer or as dma-bufs; or fresh pages the runtime imported for a long buffer of its - // own, `fresh_pages.rs`), the image in place, with the texture's declared plan alone, + // own, `fresh_pages.rs`), the image in place, with the texture's declared plan (and the + // feedback loop usage, for one that renders, where the device makes the image with it), // where the device's policy, the texture's usage and the device's check of the pages' - // class take it (`in_place.rs`); else the shadow, its notice naming why. The device's - // check's own textures take it whatever the verdict, and are neither counted nor - // announced. + // class for its access take it (`in_place.rs`); else the shadow, its notice naming why. + // A texture that renders whose image took the feedback loop usage is counted so, as an + // aliasing image over a buffer of the runtime's is. The device's check's own textures + // take it whatever the verdict, and are neither counted nor announced. let class = match texels.buffer.caller_memory() { Some(CallerMemory::HostPages) if texels.buffer.over_dma_buf() => { Some(PagesClass::DmaBuf) @@ -2234,18 +2236,20 @@ impl Device { None if texels.buffer.in_fresh_pages() => Some(PagesClass::Fresh), _ => None, }; - // On a discrete GPU, a texture whose policy and usage take the image in place, over pages - // whose memory carries a log, is a device copy instead: a shadow whose copies in take - // only the rows the log reports changed (`dirty_pages.rs`), so the GPU reads the texels - // from its own memory, where in place it reads the pages across the bus at every sample. - // It binds no image to the pages, so the in-place check's verdict is not asked. + // On a discrete GPU, a texture that only samples or reads whose policy takes the image in + // place, over pages whose memory carries a log, is a device copy instead: a shadow whose + // copies in take only the rows the log reports changed (`dirty_pages.rs`), so the GPU + // reads the texels from its own memory, where in place it reads the pages across the bus + // at every sample. It binds no image to the pages, so the in-place check's verdict is not + // asked. One that renders works on the pages in place, as a discrete Mac's GPU does. // Texels past the buffer's length lie in no image over its memory: the shadow's copies go // through the texture's tail (`buffer_texture.rs`). let past = texels.past().is_some(); let device_copy = match class { Some(class) if !past && !in_place::checking() && !texels.buffer.detached() => { let policy = self.compile_device().policy().host_page_textures; - in_place::in_place(policy, usage, class, |_| Verdict::Passed).is_ok() + Access::of(usage) == Access::Reads + && in_place::in_place(policy, usage, class, |_, _| Verdict::Passed).is_ok() && texels.device_copy(self) } _ => false, @@ -2283,16 +2287,23 @@ impl Device { true => HostPageTexturePolicy::InPlace, false => self.compile_device().policy().host_page_textures, }; - let verdict = |class| match checking { + let verdict = |class, access| match checking { true => Verdict::Passed, - false => self.in_place_verdict(class), + false => self.in_place_verdict(class, access), }; match in_place::in_place(policy, usage, class, verdict) { Ok(()) => { match self.in_place_image(&plan, descriptor, &texels, class, &facts)? { Ok((image, pitched)) => { if !checking { - self.shared().counts.host_texture_in_place(class, pitched); + let counts = &self.shared().counts; + counts.host_texture_in_place(class, pitched); + let usage = image.plan().usage; + if usage + .contains(ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT) + { + counts.feedback_loop_alias_image(); + } } return Ok(Storage::Alias { image, texels }); } @@ -2307,7 +2318,8 @@ impl Device { "the in-place check's texture takes no image in place", )); } - self.shared().counts.host_texture_shadowed(&cause); + let renders = Access::of(usage) == Access::Renders; + self.shared().counts.host_texture_shadowed(&cause, renders); if class == PagesClass::Fresh { self.shared().counts.shadow_over_fresh_pages(); } diff --git a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs index 58d6fc92d..4077673bb 100644 --- a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs @@ -21,15 +21,20 @@ //! holds a texel twice. The image's memory may run past the buffer's bytes into the rest of its //! placement (its last page's bytes past the buffer), as Vulkan binds it within the memory: its //! texels never reach them, and the check's bytes after its image are such bytes. -//! - **Its usage** is the texture's declared plan's, nothing wider: a write beyond it binds the -//! texture's usage shadow (`texture/usage_shadow.rs`), and a render pass into it renders through -//! an attachment stand-in (`attachment_stand_in.rs`), since the image has neither storage nor -//! attachment usage. Their copies into it touch its texels alone. +//! - **Its usage** is the texture's declared plan's: a write beyond it binds the texture's usage +//! shadow (`texture/usage_shadow.rs`), and a render pass into one made without `RenderTarget` +//! renders through an attachment stand-in (`attachment_stand_in.rs`), since the image has +//! neither storage nor attachment usage; their copies into it touch its texels alone. One that +//! renders also takes the feedback loop usage a draw takes that reads the texture its own pass +//! renders through a snapshot (`texture::feedback_candidate`, `render/snapshot.rs`) where the +//! device makes the image with it, as an aliasing image over a buffer of the runtime's does: +//! else the declared plan's image. //! - **A rebind** (`rebind.rs`) makes it again over the new pages, its texels as far from their //! first byte as from the old pages', as a no-copy heap's images are //! ([`Device::rebound_in_place_images`]); a detach makes it present a stand-in, as it does every //! image bound to the pages (`detach.rs`). +use super::attached_reads::feedback_candidate; use super::{ first_color_subresource, pages_hold, FirstMove, Image, ImageObjects, ImageSwap, KeptResolves, KeyMap, LinearMade, LinearRefusal, ObjectsToken, Owner, Raw, Remade, Storage, Texture, @@ -39,7 +44,7 @@ use crate::buffer_texture::Texels; use crate::device::lock; use crate::error::{vulkan, Error, RuntimeGap}; use crate::image_plan::{ImageFacts, ImagePlan}; -use crate::in_place::{PagesClass, Refusal}; +use crate::in_place::{Access, PagesClass, Refusal}; use crate::linear_plan::{check_linear_limits, linear_lack, BufferLayout, LinearLack}; use crate::texture_descriptor::TextureDescriptor; use crate::{release, Device}; @@ -65,15 +70,50 @@ impl Texture { _ => None, } } + + /// Move the texture's image in place from `GENERAL` into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` + /// and back, as a render pass instance whose draws read it through a snapshot holds it + /// (`render_target::moved_barriers`), by an internal submission the call waits for, after its + /// first move: the device's check's round of an image that renders (`in_place_check.rs`). + /// `None` where the texture is no image aliasing its bytes, or its image has no feedback loop + /// usage. + pub(crate) fn settle_feedback_moves(&self) -> Option> { + let Storage::Alias { image, .. } = &self.0.storage else { + return None; + }; + let plan = image.plan(); + if !(plan.usage).contains(vk::ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT) { + return None; + } + let range = vk::ImageSubresourceRange { + aspect_mask: vk::ImageAspectFlags::COLOR, + base_mip_level: 0, + level_count: plan.levels, + base_array_layer: 0, + layer_count: plan.layers, + }; + let family = image.device.shared().queue_flags_of(0); + let raw = image.raw.get(); + Some(image.submit_copy(|commands, command_buffer| { + // SAFETY: the internal command buffer of the device's first `VkQueue` is recording, + // outside a render pass; the image is live until the submission, waited for, + // completed, made with feedback loop usage, and rests in `GENERAL` after its first + // move, which the submission makes first. + unsafe { + crate::render_target::feedback_moves(commands, command_buffer, raw, range, family) + }; + })) + } } impl Device { - /// The image in place of a texture of `plan` (its declared usage's, the module docs) made with - /// `descriptor` over `texels`, host pages of `class`, with whether it is a - /// `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch made for host allocations; why not where the - /// device makes none (the module docs). Over a no-copy buffer's pages (or a no-copy heap's) it - /// is noted for a rebind to make again. Its first move is noted, for the device's next - /// submission that takes it (`texture/first_move.rs`). + /// The image in place of a texture of `plan` (its declared usage's, with the feedback loop + /// usage where the device makes it so: the module docs) made with `descriptor` over `texels`, + /// host pages of `class`, with whether it is a `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch + /// made for host allocations; why not where the device makes none, the declared plan's + /// refusal (the module docs). Over a no-copy buffer's pages (or a no-copy heap's) it is noted + /// for a rebind to make again. Its first move is noted, for the device's next submission that + /// takes it (`texture/first_move.rs`). pub(super) fn in_place_image( &self, plan: &ImagePlan, @@ -94,15 +134,22 @@ impl Device { ), ))); } - let made = match class { - PagesClass::DmaBuf => self.dma_buf_in_place(plan, descriptor, texels, facts)?, + let make = |plan: &ImagePlan| match class { + PagesClass::DmaBuf => self.dma_buf_in_place(plan, descriptor, texels, facts), PagesClass::Pointer | PagesClass::Fresh => { - self.host_in_place(plan, descriptor, texels, class, facts)? + self.host_in_place(plan, descriptor, texels, class, facts) } }; - let (image, pitched) = match made { - Ok(made) => made, - Err(refused) => return Ok(Err(refused)), + let with_feedback = match feedback_candidate(plan, self) { + Some(candidate) => make(&candidate)?.ok(), + None => None, + }; + let (image, pitched) = match with_feedback { + Some(made) => made, + None => match make(plan)? { + Ok(made) => made, + Err(refused) => return Ok(Err(refused)), + }, }; // Over a no-copy buffer's pages, noted for a rebind. if class != PagesClass::Fresh { @@ -607,10 +654,18 @@ impl Device { let refused = || Error::NotImplemented(RuntimeGap::RebindTextures); // A copy in fresh pages the runtime imported takes the image an import of the caller's // pages takes, made for host allocations (`in_place_unbound`), where the device's check - // passed for fresh pages; one in memory the device allocates, a linear image of its own. + // passed for fresh pages and the image's access (an image of attachment usage renders); + // one in memory the device allocates, a linear image of its own. let made = match pages.over_own_pages() { true => { - if self.in_place_verdict(PagesClass::Fresh) != crate::in_place::Verdict::Passed { + let access = + match (image.plan().usage).contains(vk::ImageUsageFlags::COLOR_ATTACHMENT) { + true => Access::Renders, + false => Access::Reads, + }; + if self.in_place_verdict(PagesClass::Fresh, access) + != crate::in_place::Verdict::Passed + { return Err(refused()); } let facts = self diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 435303829..e3407634b 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -2944,23 +2944,30 @@ impl Counters { } } - /// A texture over host pages was made a shadow of them for `cause` (`in_place.rs`). - pub(crate) fn host_texture_shadowed(&self, cause: &crate::in_place::ShadowCause) { + /// A texture over host pages was made a shadow of them for `cause` (`in_place.rs`), one whose + /// usage renders into it where `renders`. + pub(crate) fn host_texture_shadowed( + &self, + cause: &crate::in_place::ShadowCause, + renders: bool, + ) { use crate::in_place::ShadowCause as C; let counter = match cause { C::Exact => &self.host_texture_shadows_exact, - C::RenderTarget => &self.host_texture_shadows_render_target, C::ShaderWrite => &self.host_texture_shadows_shader_write, - C::CheckPending(_) => &self.host_texture_shadows_check_pending, - C::CheckFailed(_) => &self.host_texture_shadows_check_failed, - C::Unchecked(_) => &self.host_texture_shadows_unchecked, + C::CheckPending(..) => &self.host_texture_shadows_check_pending, + C::CheckFailed(..) => &self.host_texture_shadows_check_failed, + C::Unchecked(..) => &self.host_texture_shadows_unchecked, C::Refused(refusal, _) => &self.host_texture_shadows_refused[refusal.index()], }; counter.fetch_add(1, Ordering::Relaxed); + if renders { + (self.host_texture_shadows_render_target).fetch_add(1, Ordering::Relaxed); + } } - /// The device's check of the first move over host pages answered `verdict` for a class it - /// ran (`in_place_check.rs`). + /// The device's check over host pages answered `verdict` for a class and access it ran + /// (`in_place_check.rs`). pub(crate) fn in_place_check_ran(&self, verdict: crate::in_place::Verdict) { use crate::in_place::Verdict as V; self.in_place_checks_run.fetch_add(1, Ordering::Relaxed); @@ -5837,9 +5844,10 @@ pub struct WorkCounts { /// first move may write any byte bound to it. pub shadows_over_fresh_pages: u64, /// Textures over host pages (a no-copy buffer's, a no-copy heap's buffer's, or a buffer in - /// fresh pages it imported) that only sample or read, made an image aliasing the pages in - /// place, where the device's check passed for their class (`HostPageTexturePolicy::InPlace`): - /// no shadow, and no copy in or back. + /// fresh pages it imported) that sample, read or render, made an image aliasing the pages in + /// place, where the device's check passed for their class and access + /// (`HostPageTexturePolicy::InPlace`): no shadow, and no copy in or back. One that renders + /// whose image took feedback loop usage is also counted in `feedback_loop_alias_images`. pub host_textures_in_place: u64, /// Textures over host pages that `host_textures_in_place` would count (or a shadow made /// before the check answered or where it failed), made instead a copy in the device's memory @@ -5860,20 +5868,23 @@ pub struct WorkCounts { /// Textures over host pages made shadows because the device's policy asks it /// (`HostPageTexturePolicy::Shadow`). pub host_texture_shadows_exact: u64, - /// Textures over host pages made shadows because their usage renders into them - /// (`RenderTarget`, whatever else it holds; an `Unknown` usage among them). + /// Of the textures over host pages made shadows, counted by why in the counts beside this + /// one, those whose usage renders into them (`RenderTarget`, whatever else it holds; an + /// `Unknown` usage among them): the render targets a pass renders through a shadow, its + /// copies in and merges back. pub host_texture_shadows_render_target: u64, /// Textures over host pages made shadows because their usage writes them through a shader - /// (`ShaderWrite` or `ShaderAtomic`) and does not render into them. + /// (`ShaderWrite` or `ShaderAtomic`, whatever else it holds). pub host_texture_shadows_shader_write: u64, - /// Textures over host pages made shadows because the device's check of their class had not - /// answered yet (a first session's, before the verdict is kept). + /// Textures over host pages made shadows because the device's check of their class and + /// access (one that renders, or one that reads) had not answered yet (a first session's, + /// before the verdicts are kept). pub host_texture_shadows_check_pending: u64, - /// Textures over host pages made shadows because the device's check of their class found a - /// byte changed. + /// Textures over host pages made shadows because the device's check of their class and + /// access found a byte changed. pub host_texture_shadows_check_failed: u64, /// Textures over host pages made shadows because the device's check made no image of their - /// class. + /// class for their access. pub host_texture_shadows_unchecked: u64, /// Textures over host pages made shadows because their rows share bytes (an IOSurface /// plane's GPU rows). @@ -5900,18 +5911,20 @@ pub struct WorkCounts { /// reason than the source or the pitch (counted in `host_texture_shadows_refused_pitch`): the /// modifier's features or limits, the image's memory past the pages, or the driver's import. pub host_texture_shadows_refused_dma_buf: u64, - /// Classes of host pages (pointer, dma-buf, fresh) the device's check of the first move ran - /// for in this process: `in_place_checks_passed`, `in_place_checks_failed` and - /// `in_place_checks_unchecked` together. + /// Classes of host pages (pointer, dma-buf, fresh), each with each access (an image that + /// reads, an image that renders), the device's check ran for in this process: + /// `in_place_checks_passed`, `in_place_checks_failed` and `in_place_checks_unchecked` + /// together. pub in_place_checks_run: u64, - /// Of `in_place_checks_run`, those whose every image's first move left every byte alone. + /// Of `in_place_checks_run`, those whose every image left every byte alone: its first move, + /// and for one that renders its pass's load and store and its feedback loop moves. pub in_place_checks_passed: u64, /// Of `in_place_checks_run`, those that found a byte changed (or were made to fail). pub in_place_checks_failed: u64, - /// Of `in_place_checks_run`, those that made no image of the class. + /// Of `in_place_checks_run`, those that made no image of the class for the access. pub in_place_checks_unchecked: u64, - /// Classes whose verdict was read from the record of an earlier check of the same driver, - /// device and runtime: no check ran for them. + /// Classes and accesses whose verdict was read from the record of an earlier check of the + /// same driver, device and runtime: no check ran for them. pub in_place_checks_recalled: u64, /// Buffers of the runtime's own made in fresh anonymous pages imported by their pointer /// (`VK_EXT_external_memory_host`), which read zero with nothing written: host-visible ones diff --git a/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs index 3ec6f8a29..f9d762201 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs @@ -53,11 +53,14 @@ //! readers, the baseline. Printed per case (`SELF-READ-COST`): the GPU time per frame, and per //! frame the splits, snapshots, render pass instances begun, shadow copies, texels copied in //! (and of them those of a surface's shadow copied in again), keeps and their texels, merges, the -//! shadows made of render targets over host pages, and the images made with feedback loop usage. +//! shadows made of render targets over host pages and the textures in place over them (once the +//! device's in-place check answered, each line printed, `SELF-READ-CHECK`), and the images made +//! with feedback loop usage. //! //! Ignored by default: measurements, not checks. Run them by name with `--run-ignored all`. use super::attachment_reads::{floats, function}; +use super::first_use_writes::CHECK_WAIT; use super::host_memory::{no_copy, Mapping, GUEST_PAGE}; use super::{open_device, WAIT}; use crate::gpu::TEST_DEVICE; @@ -913,6 +916,16 @@ fn self_reads() { /// [`self_reads`] on `device`, of `policy`: its surface, and under `InPlace` the private target. fn self_reads_on(device: &Device, policy: HostPageTexturePolicy) { + // The surface takes the path the device's check answers, not a shadow made before it did. + if policy == HostPageTexturePolicy::InPlace { + let settled = device.settle_in_place_checks(CHECK_WAIT); + for line in device.in_place_check_report() { + println!( + "SELF-READ-CHECK {}: settled {settled}: {line}", + device.name() + ); + } + } let bgra = PixelFormat::BGRA8Unorm; let draws = ( state(device, "tob_solid", "tob_renders.ll", bgra), @@ -978,8 +991,8 @@ fn self_reads_on(device: &Device, policy: HostPageTexturePolicy) { {}x{}: GPU {:.3} ms/frame (median); per frame: splits {:.2}, snapshotted \ {:.2}, instances {:.2}, shadow copies {:.2}, bounded {:.2}, texels copied in \ {:.0}, of a surface again {:.0}, keeps {:.2}, texels kept {:.0}, merges {:.2}; \ - render-target shadows over host pages {}, images made with feedback loop \ - usage: shadows {}, aliases {}", + render-target shadows over host pages {}, textures in place over host pages \ + {}, images made with feedback loop usage: shadows {}, aliases {}", SELF_PAIRS, if baseline { "baseline" } else { "self-read" }, SELF_RECT[0], @@ -1008,6 +1021,7 @@ fn self_reads_on(device: &Device, policy: HostPageTexturePolicy) { per(kept(&before), kept(&after)), per(before.shadow_merges_fetched, after.shadow_merges_fetched), after.host_texture_shadows_render_target, + after.host_textures_in_place, after.feedback_loop_shadow_images, after.feedback_loop_alias_images, ); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs index 38f8cedd9..bcc6fd447 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs @@ -25,11 +25,14 @@ //! value, and the bytes between the rows hold the pattern. //! - [`textures_that_render_or_write_count_their_shadows_apart`], under the validation layer: a //! 64x64 `R32Uint` texture over a no-copy buffer of anonymous pages, of each usage that renders -//! or writes, is a shadow counted by why: one that renders into it (`RenderTarget`, whatever else -//! it holds) as a render target's (`host_texture_shadows_render_target`), one that writes it -//! through a shader alone (`ShaderWrite`, `ShaderAtomic`) as a shader write's -//! (`host_texture_shadows_shader_write`), and under `HostPageTexturePolicy::Shadow` every one as -//! the exact form's (`host_texture_shadows_exact`). +//! or writes, once the device's check answered: one that writes it through a shader +//! (`ShaderWrite`, `ShaderAtomic`, whatever else it holds) is a shadow counted as a shader +//! write's (`host_texture_shadows_shader_write`); one that renders into it and does not write it +//! is in place where the check passed for an image that renders over the class +//! (`Pointer renders: Passed`; `vk_image` answers one, `host_textures_in_place`), else a shadow +//! counted by the check's answer or the device's refusal; under `HostPageTexturePolicy::Shadow` +//! every one is the exact form's (`host_texture_shadows_exact`). Each shadow that renders also +//! counts in `host_texture_shadows_render_target`. //! - [`a_failed_check_keeps_the_shadow_and_no_record`], under the validation layer: a device made //! to fail its check (`DeviceOptions::fail_in_place_check`) answers failed or unchecked for every //! class and makes such a texture a shadow counted as the failed check's, never in place, and @@ -457,7 +460,7 @@ fn writes_and_passes_beyond_the_usage_take_their_shadows() { #[test] fn textures_that_render_or_write_count_their_shadows_apart() { use TextureUsage as U; - // Each usage, and whether it counts as a render target's shadow (else a shader write's). + // Each usage, and whether it renders. let usages = [ (U::SHADER_READ | U::RENDER_TARGET, true), (U::SHADER_READ | U::SHADER_WRITE, false), @@ -477,6 +480,10 @@ fn textures_that_render_or_write_count_their_shadows_apart() { options.policy.host_page_textures = policy; }) .unwrap(); + if policy == HostPageTexturePolicy::InPlace { + settled(&device); + } + let renders_in_place = passed(&device, "Pointer renders"); let (w, h, bpr) = (64u64, 64u64, 256u64); let len = ((bpr * h) as usize).next_multiple_of(GUEST_PAGE); let mapping = Mapping::anonymous(len); @@ -520,19 +527,36 @@ fn textures_that_render_or_write_count_their_shadows_apart() { delta(|c| c.host_texture_shadows_shader_write), delta(|c| c.host_texture_shadows_exact), ); - let due = match (policy, renders) { - (HostPageTexturePolicy::Shadow, _) => (0, 0, 1), - (_, true) => (1, 0, 0), - (_, false) => (0, 1, 0), - }; + let writes = usage.intersects(U::SHADER_WRITE | U::SHADER_ATOMIC); + // SAFETY: the handle is only read, while the texture lives. + let aliased = unsafe { texture.vk_image() }.is_some(); eprintln!( "IN-PLACE-SHADOWS on {}: {policy:?} {usage:?}: (render target, shader write, \ - exact) {counted:?}", + exact) {counted:?}, in place {aliased}", device.name() ); - assert_eq!(counted, due, "{policy:?} {usage:?}"); - // SAFETY: the handle is only read, while the texture lives. - assert!(unsafe { texture.vk_image() }.is_none(), "{usage:?}"); + let shadow = u64::from(renders); + match (policy, writes) { + (HostPageTexturePolicy::Shadow, _) => { + assert_eq!(counted, (shadow, 0, 1), "{policy:?} {usage:?}"); + assert!(!aliased, "{usage:?}"); + } + (_, true) => { + assert_eq!(counted, (shadow, 1, 0), "{policy:?} {usage:?}"); + assert!(!aliased, "{usage:?}"); + } + // A texture that renders and does not write: in place where its check passed, + // else a shadow counted by the check's answer or the device's refusal. + (_, false) => { + let in_place = delta(|c| c.host_textures_in_place); + if aliased { + assert!(renders_in_place, "{usage:?} in place without its check"); + assert_eq!((counted, in_place), ((0, 0, 0), 1), "{usage:?}"); + } else { + assert_eq!((counted, in_place), ((1, 0, 0), 0), "{usage:?}"); + } + } + } drop(texture); } messages.take_notices(); @@ -555,7 +579,7 @@ fn a_failed_check_keeps_the_shadow_and_no_record() { settled(&device); let report = device.in_place_check_report(); assert!( - report.iter().take(3).all(|line| !line.ends_with("Passed")), + report.iter().take(6).all(|line| !line.ends_with("Passed")), "{report:?}" ); let len = (7680 * 1080usize).next_multiple_of(GUEST_PAGE); @@ -600,7 +624,8 @@ fn a_failed_check_keeps_the_shadow_and_no_record() { { let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), in_place).unwrap(); let counts = device.work_counts(); - assert_eq!(counts.in_place_checks_recalled, 3); + // Each class's verdicts, for a texture that reads and one that renders. + assert_eq!(counts.in_place_checks_recalled, 6); assert_eq!(counts.in_place_checks_run, 0); assert!(device.settle_in_place_checks(std::time::Duration::ZERO)); assert_eq!(device.in_place_check_took(), None); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs index 73808f3a8..6f74da9c6 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs @@ -1,8 +1,9 @@ //! Device tests of 2D textures (and 2D arrays) over no-copy buffers on the device the cfg selects. //! A texture over the caller's host pages is a shadow image the encoders copy the texels into and -//! back (`shadowed-texture`), or under `HostPageTexturePolicy::InPlace` one that only reads is an -//! image aliasing the pages where the device's check passed: either reads and writes the caller's -//! bytes as Metal's texture over the buffer does. +//! back (`shadowed-texture`), or under `HostPageTexturePolicy::InPlace` one that reads or renders +//! and does not write through a shader is an image aliasing the pages where the device's check +//! passed for its access: either reads and writes the caller's bytes as Metal's texture over the +//! buffer does. //! //! - [`textures_over_no_copy_buffers_read_and_write_the_caller_s_pages`], under the validation //! layer: the consumer's surface formats (and `BGR10_XR`, an extended-range format held in an @@ -20,10 +21,10 @@ //! (`WorkCounts::shadowed_textures`) and made without zeroing its image (`shadows_zeroed`, //! `images_started_on_the_host`: its copy in writes every texel first), and making it, and //! making it again, asks the driver no format's modifier features (`modifier_feature_queries`); -//! under `InPlace`, once the device's check answered, one of `ShaderRead` usage alone is in place -//! (`vk_image` answers its image, `host_textures_in_place`) or a shadow counted by why, and every -//! other a shadow. The second making takes the same form. Each texture's form is printed -//! (`NOCOPY-TEXTURE`). +//! under `InPlace`, once the device's check answered, one without `ShaderWrite` usage (the +//! `ShaderRead` one, and the render target) is in place (`vk_image` answers its image, +//! `host_textures_in_place`) or a shadow counted by why, and every other a shadow. The second +//! making takes the same form. Each texture's form is printed (`NOCOPY-TEXTURE`). //! - [`two_slice_arrays_over_no_copy_buffers_read_and_write_the_caller_s_pages`], under the //! validation layer: two-slice `RGBA8Unorm` 2D arrays made by the linear call, a 4x4 sampled one //! and an 8x8 render target, read and written a slice at a time at Metal's slice places @@ -358,10 +359,10 @@ fn read_and_write_the_caller_s_pages_under( ); let shadowed = counted.shadowed_textures - before.shadowed_textures; let in_place = counted.host_textures_in_place - before.host_textures_in_place; - // Under `Shadow`, and for a texture that renders or writes, a shadow; under `InPlace` - // one that only reads may be in place, counted so. - let may_alias = - policy == HostPageTexturePolicy::InPlace && usage == TextureUsage::SHADER_READ; + // Under `Shadow`, and for a texture that writes through a shader, a shadow; under + // `InPlace` one that reads or renders may be in place, counted so. + let may_alias = policy == HostPageTexturePolicy::InPlace + && !usage.contains(TextureUsage::SHADER_WRITE); assert!( !made || may_alias, "{what}: a texture over host pages aliased" @@ -914,13 +915,36 @@ fn differing(a: &[u8], b: &[u8], texel: u64) -> (usize, Option) { /// blends over the left half, read through the texture and through the buffer in the same command /// buffer; a blit's write of the buffer, then a pass that loads it and blends over the right half, /// in one command buffer; and a pass that clears and blends over the left half. The pages hold the -/// reference's texels after each, and the bytes between the rows stay the caller's. The form is -/// printed (`NOCOPY-BLEND`). One test a format and pitch, each its own process. +/// reference's texels after each, and the bytes between the rows stay the caller's. Under each +/// setting of `host_page_textures`: under `InPlace`, once the device's check answered, the render +/// target is in place where its check passed for an image that renders. The form is printed +/// (`NOCOPY-BLEND`). One test a format and pitch, each its own process. fn passes_blend_load_and_store_as_private_textures(pf: PixelFormat, texel: u64, pad: u64) { + for policy in [ + HostPageTexturePolicy::Shadow, + HostPageTexturePolicy::InPlace, + ] { + passes_blend_load_and_store_under(pf, texel, pad, policy); + } +} + +/// [`passes_blend_load_and_store_as_private_textures`] on a device of `policy`. +fn passes_blend_load_and_store_under( + pf: PixelFormat, + texel: u64, + pad: u64, + policy: HostPageTexturePolicy, +) { let cache = ScratchCache::new().unwrap(); let messages = Messages::default(); { - let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { + options.policy.host_page_textures = policy; + }) + .unwrap(); + if policy == HostPageTexturePolicy::InPlace { + assert!(device.settle_in_place_checks(CHECK_WAIT)); + } let queue = device.new_command_queue().unwrap(); let pipeline = blending(&device, pf); let row = W * texel; @@ -940,10 +964,14 @@ fn passes_blend_load_and_store_as_private_textures(pf: PixelFormat, texel: u64, d.resource_options = ResourceOptions::private(); let private = device.new_texture(&d).unwrap(); let what = format!( - "{} {W}x{H}, rows of {bpr} bytes ({})", + "{policy:?}, {} {W}x{H}, rows of {bpr} bytes ({})", pf.name(), form(aliased(&texture)) ); + assert!( + policy == HostPageTexturePolicy::InPlace || !aliased(&texture), + "{what}: aliased under the shadow's setting" + ); let check = |round: &str, ours: &[u8], reference: &[u8]| { let (ours, reference) = (texel_rows(ours, bpr, row), texel_rows(reference, bpr, row)); let (count, first) = differing(&ours, &reference, texel); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs b/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs index ec496b5a6..075f31b8e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs @@ -10,8 +10,9 @@ //! //! Each texture is a shadow (no image over the pages: `vk_image` answers none) on the lane's //! devices, which take the exact answers (`HostPageTexturePolicy::Shadow`); the tests named -//! `_in_place` run on a device of `HostPageTexturePolicy::InPlace`, where a texture that only reads -//! is an image aliasing the pages if the device's check passed and its pitch is taken. Every step +//! `_in_place` run on a device of `HostPageTexturePolicy::InPlace`, where a texture that reads or +//! renders and does not write through a shader is an image aliasing the pages if the device's check +//! passed for its access and its pitch is taken. Every step //! reads and writes Metal's bytes at Metal's places, and no write reaches the bytes between the //! rows or past the last. The steps: //! @@ -460,8 +461,8 @@ pub(super) fn sampler(device: &Device, filter: SamplerMinMagFilter) -> SamplerSt /// `usage`: the pages hold a pattern of their own, the texels `texels_of(.., 1)` laid at the rows; /// with the buffer, the mapping and the pages as written. `None` where the device imports no host /// memory. It is a shadow, whatever its usage: counted so, and `vk_image` answers no image; on a -/// device that takes such textures in place ([`in_place_form`]) one that only reads may be in -/// place instead, counted so, and `vk_image` answers its image. +/// device that takes such textures in place ([`in_place_form`]) one that does not write through a +/// shader may be in place instead, counted so, and `vk_image` answers its image. fn surface(device: &Device, layout: &Layout, usage: TextureUsage) -> Option { let len = layout.len().next_multiple_of(GUEST_PAGE); let mapping = Mapping::anonymous(len); @@ -515,8 +516,8 @@ fn surface(device: &Device, layout: &Layout, usage: TextureUsage) -> Option