diff --git a/crates/metal2vulkan-runtime/src/attachment_stand_in.rs b/crates/metal2vulkan-runtime/src/attachment_stand_in.rs index b74df68ec..2459898f5 100644 --- a/crates/metal2vulkan-runtime/src/attachment_stand_in.rs +++ b/crates/metal2vulkan-runtime/src/attachment_stand_in.rs @@ -45,6 +45,10 @@ //! through their combined scratch image (`depth_stencil_scratch.rs`), which copies them alike. A //! texture whose format the device does not copy both ways, and a memoryless one, stay refused //! (`NotImplemented(Render)`). +//! - **A texture over a buffer a pass does not store** (`DontCare`, or `MultisampleResolve`), whose +//! image is linear over the buffer's bytes: Metal leaves the buffer's bytes, so the pass renders +//! it through the image its texture keeps, copied into where the pass loads it (`Load`), and +//! never back (`kept_bytes.rs`). //! - **A pass's hidden depth and stencil**. In a pass without a depth/stencil attachment, plain //! Metal tests a draw whose state uses depth or the stencil against a hidden depth of `float`, //! 1.0 at the pass's start, and a stencil of 0, kept per sample through the pass. Such a draw @@ -130,6 +134,10 @@ pub(super) enum Cause { /// A bound linear attachment's image its texture keeps (`linear_attachment.rs`, which /// announces it under its own kinds). Linear, + /// The image a texture over a buffer keeps for a pass that does not store it, so that the + /// buffer keeps its bytes (`kept_bytes.rs`, which announces it, `dont-care-stand-in`): copied + /// into where the pass loads it, and never back. + KeptBytes, } impl StandIn { @@ -182,7 +190,8 @@ impl KeptBacking { /// (`linear_attachment.rs`), copied in where the pass loads it and back where it stores it, as a /// texture without render target usage is: the copies, and the clears of the tiles a `DontCare` /// load reaches (`clear_reach.rs`), give each pass all it reads of the backing first, so one serves -/// them too. +/// them too. So does a texture over a buffer that a pass does not store (`kept_bytes.rs`), copied +/// in where the pass loads it and never back: nothing reads what such a pass leaves there. pub(super) fn kept_backing( maker: &CommandBuffer, own: &Target, diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index f29b014fa..6282298f5 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -53,7 +53,7 @@ //! otherwise than Metal where the device makes it (`texture.rs`, `texture/shared.rs`, //! `texture/heap.rs`). -use super::attachment_stand_in::Cause; +use super::attachment_stand_in::{Cause, StandIn}; use super::color_resolve; use super::device::{DebugMessage, Device, MessageKind, MessageSeverity}; use super::fragment_imageblock::PassImageblock; @@ -625,7 +625,9 @@ degradations! { /// texels unless its tiler overflows. Only on a driver measured to keep the earlier texel /// or the stored one at each texel (`DriverFact::DontCareStoreIsOneOfMetals`); every other /// device stores it (`STORE`), Metal's answer where its tiler overflows - /// (`render_target.rs`). + /// (`render_target.rs`). Not a texture over a buffer the pass renders through an image it + /// copies nothing back from (a shadow, a stand-in: `kept_bytes.rs`), which keeps the + /// buffer's bytes, Metal's answer; only one whose image the pass renders in place. DontCareStore = "dont-care-store", Precision, "the attachment's texels after the pass are each its earlier texel or the one the \ pass rendered, both Metal's answers, but not always the one Metal's tiler keeps"; @@ -1397,6 +1399,19 @@ degradations! { LinearAttachmentClearCopies = "linear-attachment-clear-copies", Performance, "the pass clears an image of the device's and copies it back after, as clearing the \ texture's linear image in place costs more"; + /// A pass renders a color attachment that it stores with `DontCare` (or resolves alone, + /// `MultisampleResolve`) and whose texture's image lies over the buffer the texture lies + /// in (a linear image over an ordinary buffer's memory, a no-copy buffer's host pages, a + /// dma-buf's, a surface's; on MoltenVK, a Metal texture over a no-copy or surface buffer's + /// `MTLBuffer`) through an image its texture keeps, so that the buffer keeps its bytes, as + /// Metal's does (`kept_bytes.rs`): rendered in place, the pass would write them. Not where + /// the pass hands the attachment to a driver that stores `DONT_CARE` as Metal's own + /// `DontCare` (`DriverFact::DontCareStoreIsMetals`), one render pass instance the driver + /// runs unbroken: Metal keeps the bytes itself. + DontCareStandIn = "dont-care-stand-in", Performance, + "an image of the attachment's size, which its texture keeps for the queue, renders the \ + pass; a `Load` copies the buffer's texels over the render area into it before the \ + pass, and nothing is copied back"; /// A no-copy buffer or heap released with a deallocator and no keep-alive /// ([`KeepAlive`](crate::KeepAlive)) while the device's import of its pages is still held: /// a command buffer submitted before a texture over them was released may still read @@ -3131,32 +3146,13 @@ impl Device { StoreAction::DontCare | StoreAction::MultisampleResolve ) }; - // On a driver that stores `DONT_CARE` as Metal's own `DontCare` on the same GPU - // (`DriverFact::DontCareStoreIsMetals`), what a pass it runs whole hands it so is stored - // as Metal's. But an attachment the pass clears, draws nothing into, and resolves alone: - // Metal leaves the clear in it where it compresses the texture and keeps its texels where - // it does not (EVs DGC-dcs1-m4, DGC-dcs2-m4), and the driver's image of the texture may - // be compressed otherwise. - let handed = whole - .filter(|_| { - self.properties() - .driver_facts - .contains(&DriverFact::DontCareStoreIsMetals) - }) - .map(|whole| { - ( - render_target::handed_dont_care(self, layout, whole.shape), - whole.drew, - ) - }); // Whether the attachment `pick` names, loaded by `load` and stored by `store`, is stored - // as Metal's. + // as Metal's (`HandedToMetal`). + let handed = HandedToMetal::of(self, layout, whole); let metals = |pick: &dyn Fn(&HandedDontCare) -> bool, load, store| { - handed.as_ref().is_some_and(|(handed, drew)| { - let resolved_clear = - load == LoadAction::Clear && store == StoreAction::MultisampleResolve; - pick(handed) && (*drew || !resolved_clear) - }) + handed + .as_ref() + .is_some_and(|handed| handed.stores(pick, load, store)) }; // An attachment cleared and resolved into another pixel format by a pass without a draw // call renders into a backing of its own, which copies nothing back: its texture keeps @@ -3165,14 +3161,20 @@ impl Device { color.clears_and_resolves_across_formats() && color.stand_in.as_ref().is_some_and(|s| !s.copies()) }; + // A texture over a buffer rendered through an image the pass copies nothing back from + // where it does not store it (a shadow, `render/shadows.rs`; a stand-in, which copies + // back only what Metal stores) keeps the buffer's bytes, Metal's answer (`kept_bytes.rs`). + let keeps_bytes = |target: &Target, stand_in: Option<&StandIn>| { + let own = stand_in.map_or(target, |s| &s.own); + own.texture.buffer_texels().is_some() + && (stand_in.is_some_and(StandIn::copies) || own.texture.shadow().is_some()) + }; let color = layout.colors.iter().enumerate().find_map(|(index, color)| { color .as_ref() .filter(|color| !color.memoryless && dont_care(color.store) && !kept(color)) - .filter(|color| { - let pick = |h: &HandedDontCare| h.colors.get(index).copied().unwrap_or(false); - !metals(&pick, color.load, color.store) - }) + .filter(|color| !keeps_bytes(&color.target, color.stand_in.as_ref())) + .filter(|color| !handed.as_ref().is_some_and(|h| h.color(index, color))) .map(|color| { ( StoredAttachment::Color(index), @@ -3191,6 +3193,7 @@ impl Device { // program's (`DepthStencilTarget::hidden`). let aspect = depth_stencil .filter(|ds| ds.separate.is_none() && !ds.hidden) + .filter(|ds| !keeps_bytes(&ds.target, ds.stand_in.as_ref())) .and_then(|ds| { let stored_stencil = patterned.is_some(); let picks: [(&str, _, fn(&HandedDontCare) -> bool); 2] = [ @@ -3268,6 +3271,56 @@ pub(super) struct WholePass<'a> { pub(super) drew: bool, } +/// What a pass recorded whole ([`WholePass`]) hands a driver that stores `DONT_CARE` as Metal's +/// own `DontCare` on the same GPU (`DriverFact::DontCareStoreIsMetals`): the attachments it +/// stores so, as Metal's (`Device::degrade_pass`; a texture over a buffer keeps its bytes there, +/// `kept_bytes.rs`). But an attachment the pass clears, draws nothing into, and resolves alone: +/// Metal leaves the clear in it where it compresses the texture and keeps its texels where it +/// does not (EVs DGC-dcs1-m4, DGC-dcs2-m4), and the driver's image of the texture may be +/// compressed otherwise. +pub(super) struct HandedToMetal { + /// The attachments the pass hands the driver as `DONT_CARE`. + handed: HandedDontCare, + /// The pass draws. + drew: bool, +} + +impl HandedToMetal { + /// What `layout`'s pass, recorded `whole`, hands `device`'s driver as Metal's; `None` for a + /// pass not recorded whole or a driver without the fact. + pub(super) fn of( + device: &Device, + layout: &PassLayout, + whole: Option, + ) -> Option { + let facts = &device.properties().driver_facts; + whole + .filter(|_| facts.contains(&DriverFact::DontCareStoreIsMetals)) + .map(|whole| HandedToMetal { + handed: render_target::handed_dont_care(device, layout, whole.shape), + drew: whole.drew, + }) + } + + /// Whether the attachment `pick` names, loaded by `load` and stored by `store`, is stored as + /// Metal's. + fn stores( + &self, + pick: &dyn Fn(&HandedDontCare) -> bool, + load: LoadAction, + store: StoreAction, + ) -> bool { + let resolved_clear = load == LoadAction::Clear && store == StoreAction::MultisampleResolve; + pick(&self.handed) && (self.drew || !resolved_clear) + } + + /// Whether color attachment `index`, `color`, is stored as Metal's. + pub(super) fn color(&self, index: usize, color: &ColorTarget) -> bool { + let pick = |h: &HandedDontCare| h.colors.get(index).copied().unwrap_or(false); + self.stores(&pick, color.load, color.store) + } +} + /// A depth or stencil resolve mode as a notice names it. fn resolve_mode(mode: ResolveMode) -> String { if mode == ResolveMode::None { @@ -3584,8 +3637,8 @@ impl Device { ), ) }); - } else if stand_in.cause == Cause::Linear { - // Announced where `linear_attachment.rs` chose the kept image. + } else if matches!(stand_in.cause, Cause::Linear | Cause::KeptBytes) { + // Announced where `linear_attachment.rs` or `kept_bytes.rs` chose the kept image. } else if memoryless && (index.is_some_and(fetched) || (index.is_none() && shadow) || !chosen) { diff --git a/crates/metal2vulkan-runtime/src/kept_bytes.rs b/crates/metal2vulkan-runtime/src/kept_bytes.rs new file mode 100644 index 000000000..f75dca739 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/kept_bytes.rs @@ -0,0 +1,168 @@ +//! Textures over buffers that a render pass does not store: the buffer keeps its bytes. +//! +//! **Metal's answer** (the DontCare-store probe, an M3 Max under macOS 27.0.1, each case 20 times +//! alike): after a pass whose color attachment over a buffer is stored `DontCare`, the buffer +//! holds the bytes it held before the pass in every texel; Metal writes neither the rendered nor +//! the clear value, and no byte between the rows. So it was in 660 passes over a texture at its +//! first use, 72 after a pass that stored it (which keep that pass's bytes), 72 beside a second +//! attachment stored with `Store` (which holds the rendered value), 98 that clear and draw +//! nothing, and 24 over IOSurfaces: 16x16, 333x77, 1307x512 at rows of 5248 bytes, and 2048x2048, +//! tight and padded; `BGRA8Unorm`, `RGBA8Unorm`, `BGRA8Unorm_sRGB`, `RGBA16Float` and `R8Unorm`; +//! shared, no-copy and IOSurface buffers; every load action; a draw over the whole texture, half +//! of it, a corner, or none. And so it was with a memory barrier between two draws (the barrier +//! probe, the same GPU, 20 times alike): over buffers, render targets, textures or the buffer +//! alone, from the fragment stage to the vertex or the fragment stage, where a Vulkan pass splits +//! or MoltenVK restarts its Metal pass. A `Store` there leaves the rendered texels, and outside the +//! buffer's (`Load`) or the clear value (`Clear`). The one exception: the first pass in a process +//! to overflow Apple's tiler (some 2 to 4 million triangle-tile entries) leaves the rendered +//! texels, in every texel, all or nothing; the driver then grows its tiler's buffer for the rest of +//! the process. No call predicts or detects it, and the runtime does not model it: its answer is +//! the buffer's bytes, exactly. `MultisampleResolve`, which stores nothing of the attachment, +//! leaves it the same way: a texture over a buffer is never multisampled, so such an attachment is +//! a single-sampled one whose texels are copied into its resolve texture (`resolve.rs`). +//! +//! - **A shadowed texture** (`shadow.rs`) renders into its shadow, which the pass copies back only +//! where it stores it (`render/shadows.rs`): the buffer keeps its bytes. So does a planar +//! surface's depth or stencil texture, which renders through its tiled twin, a shadow +//! (`texture/surface_depth.rs`), and any texture over a buffer the pass renders through a +//! stand-in (`attachment_stand_in.rs`), which copies back only what Metal stores. +//! - **A texture whose image lies over its buffer** (`Texture::image_over_buffer`: a linear image +//! over the buffer's memory, an ordinary buffer's, a no-copy buffer's host pages, a dma-buf's, +//! a surface's, a texture buffer's attachment twin among them; or, on MoltenVK, a Metal texture +//! over a no-copy or surface buffer's `MTLBuffer`) would have the pass render into the buffer's +//! bytes. Where the pass does not store it, it renders through the image its texture keeps for +//! the queue instead (`attachment_stand_in::kept_backing`, [`Cause::KeptBytes`]): a `Load` +//! copies the buffer's texels over the render area into that image before the pass; a `Clear` +//! or a `DontCare` load is the image's own first operation, by the rules a `DontCare` load +//! follows elsewhere; nothing is copied back, and the image's own store is `DONT_CARE` +//! (`render_target.rs`): nothing reads what a pass leaves there. A pass that stores the +//! attachment renders it in place, as before, at no cost. Announced once (`dont-care-stand-in`, +//! performance), and counted per pass (`WorkCounts::kept_bytes_passes`). +//! - **Handed to Metal's own `DontCare`**: on a driver that stores `DONT_CARE` as Metal's own on +//! the same GPU (`DriverFact::DontCareStoreIsMetals`, MoltenVK on the M4 and the M3 Max), a pass +//! recorded as one render pass instance with nothing that restarts the driver's Metal pass +//! hands the attachment to Metal, which keeps the buffer's bytes itself (`HandedToMetal`): it +//! renders in place, at no cost, and is neither announced nor counted. A pass split into +//! instances, or restarted, stores the attachment between them, so it renders through the kept +//! image as on any other driver. One that runs one more instance after its last to resolve +//! (`render.rs`), which this cannot see, stays in place, and `dont-care-store` announces it. +//! - **Decided as the pass ends** ([`settle`]), once its store actions are known (a late one from +//! `set_color_store_action`, and `Unknown`, which stores as `DontCare`): the draws record against +//! the compatible pass, which a stand-in of the attachment's format and samples keeps, and the +//! framebuffer is made then. But where a draw of the pass took a view of the attachment's image +//! (a framebuffer fetch reading it in place, as an input attachment or a storage image, its +//! sample planes, a draw rendering it in another format through a view, its extended-range +//! shadow), where the pass executes render commands (whose draws record against the encoder's +//! layout as the execution was encoded, `render/executions.rs`), where the device renders the +//! texture's image only beside other linear ones (`VK_NV_linear_color_attachment`'s rule, +//! `linear_attachment.rs`) and a draw took a view of another such attachment in place, which +//! would then have to render apart, and where its image or its format copies no texels and the +//! pass loads it: there the pass renders in place, and `dont-care-store` announces the texels it +//! rendered there, Metal's answer where its tiler overflows. + +use super::attachment_stand_in::{self, Cause, StandIn}; +use super::command_buffer::CommandBuffer; +use super::degradation::Degradation; +use super::error::{Error, RuntimeGap}; +use super::linear_attachment; +use super::render_pass::ColorTarget; +use super::render_values::{LoadAction, StoreAction}; + +/// Whether a pass stores nothing of `color`: `DontCare`, or `MultisampleResolve` (as `Unknown` +/// stores once the pass ends). +fn unstored(color: &ColorTarget) -> bool { + matches!( + color.store, + StoreAction::DontCare | StoreAction::MultisampleResolve + ) +} + +/// Render each color attachment among `colors`, a pass's as it ends, that the pass does not +/// store and whose texture's image lies over its buffer's bytes, through the image its texture +/// keeps for `maker`'s queue (the module docs): but where the pass hands it to the driver's +/// `DONT_CARE` as Metal's own `DontCare` (`handed`, `HandedToMetal`), a draw took a view of its +/// image (`viewed`), the pass executes render commands (`executes`), or another color in place +/// is bound by `VK_NV_linear_color_attachment`'s rule and the pass cannot render it apart +/// (`taken`, as `linear_attachment::settle` asks it). Announced, and counted. +pub(super) fn settle( + maker: &CommandBuffer, + colors: &mut [Option], + executes: bool, + handed: impl Fn(usize) -> bool, + viewed: impl Fn(usize) -> bool, + taken: impl Fn(usize) -> bool, +) -> Result<(), Error> { + if executes { + return Ok(()); + } + let device = maker.device(); + // The colors a draw took a view of that render in place under the extension's rule: one + // rendered through a kept image beside them would leave them to render apart, which + // `linear_attachment::settle` refuses. + let mut held = Vec::new(); + for (index, color) in colors.iter().enumerate() { + let Some(color) = color else { + continue; + }; + if color.stand_in.is_none() + && taken(index) + && linear_attachment::bound(device, &color.target)? + { + held.push(index); + } + } + let queue = maker.command_queue().id(); + let mut kept = false; + for (index, color) in colors.iter_mut().enumerate() { + let Some(color) = color else { + continue; + }; + if !unstored(color) + || color.stand_in.is_some() + || !color.target.texture.image_over_buffer() + || handed(index) + || viewed(index) + || held.iter().any(|&other| other != index) + { + continue; + } + if color.load == LoadAction::Load + && attachment_stand_in::check_copies(&color.target).is_err() + { + continue; + } + let own = color.target.clone(); + // A format the device copies no image of keeps the pass in place. + let backing = match attachment_stand_in::kept_backing(maker, &own, queue, true) { + Ok(backing) => backing, + Err(Error::NotImplemented(RuntimeGap::Render)) => continue, + Err(error) => return Err(error), + }; + let (format, store) = (own.texture.pixel_format(), color.store); + device.degrade(Degradation::DontCareStandIn, || { + ( + format!( + "a {format:?} texture over a buffer's bytes, color attachment {index} of a \ + render pass" + ), + format!( + "the pass stores it with `{store:?}`, after which Metal's texture over a \ + buffer holds the buffer's bytes, and the texture's image lies over them, so \ + the pass renders into an image the texture keeps" + ), + ) + }); + color.target = backing; + color.stand_in = Some(StandIn { + own, + cause: Cause::KeptBytes, + area: None, + }); + held.retain(|&other| other != index); + kept = true; + } + if kept { + device.shared().counts.kept_bytes_pass(); + } + Ok(()) +} diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 934eea473..4781491b2 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -113,6 +113,7 @@ mod indirect_command_buffer; mod indirect_dispatch; mod indirect_execute; mod interop; +mod kept_bytes; mod key_hash; mod library; mod linear_attachment; diff --git a/crates/metal2vulkan-runtime/src/linear_attachment.rs b/crates/metal2vulkan-runtime/src/linear_attachment.rs index 4401b348b..56508e92b 100644 --- a/crates/metal2vulkan-runtime/src/linear_attachment.rs +++ b/crates/metal2vulkan-runtime/src/linear_attachment.rs @@ -31,7 +31,10 @@ //! Each announces `linear-attachment-copies` (`Degradation::LinearAttachmentCopies`), naming the //! rule. A device whose linear tiling has the color attachment feature renders a linear image //! beside any other, so no attachment is bound there; a format whose linear tiling has neither -//! keeps its texture's shadow (`shadowed-texture`). +//! keeps its texture's shadow (`shadowed-texture`). On every device, a pass that does not store +//! such an attachment renders it through the image its texture keeps, copied nothing back, so +//! that its buffer keeps its bytes (`kept_bytes.rs`, settled before these as the pass ends): an +//! attachment that is not linear beside the others. //! //! **Where the rule allows it, the pass renders in place** ([`choose`], as it ends). A pass that //! loads a bound attachment renders it in place: a copy of it into the image its texture keeps diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 91e9bc503..325ab8dc5 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -261,7 +261,7 @@ use super::color_reformat::{self, Routing}; use super::color_resolve::{self, ShaderResolves}; use super::command_buffer::CommandBuffer; use super::deferred::Deferred; -use super::degradation::{BoundFormats, Degradation, SplitCauses, WholePass}; +use super::degradation::{BoundFormats, Degradation, HandedToMetal, SplitCauses, WholePass}; use super::depth_stand_in::DepthStandIn; use super::depth_stencil::{DepthStencilState, FailingDraw}; use super::depth_stencil_resolve::DrawnResolve; @@ -279,6 +279,7 @@ use super::function_table::VisibleFunctionTable; use super::heap_sets; use super::index_bounds::{self, BoundsPass, BoundsSteps}; use super::index_rewrite::{self, RewritePass, RewriteSteps}; +use super::kept_bytes; use super::linear_attachment; use super::linear_merge::LinearMerge; use super::live_bind::{LiveBind, Reshape}; @@ -1088,6 +1089,10 @@ pub struct RenderCommandEncoder { /// What the pass's draws write of each color, and blend, for the choice of a bound linear /// attachment's rendering (`linear_attachment::Coverage`). coverage: linear_attachment::Coverage, + /// The color indices a draw of the pass read as input attachments (framebuffer fetch's input + /// form): its descriptor sets view the attachment's image, which then stays the pass's + /// (`kept_bytes.rs`). + inputs_read: BTreeSet, /// The pass has a draw call, whether or not it draws anything, or an execution of render /// commands: Metal's pass rewrites the unused bits of an extended-range or padded attachment /// it loads in the tiles its draws reach (`render/unused_bits_load.rs`). @@ -1372,6 +1377,7 @@ impl CommandBuffer { drew: false, drawn: clear_reach::DrawnArea::default(), coverage: linear_attachment::Coverage::default(), + inputs_read: BTreeSet::new(), rewrites_unused_bits: false, extended_written: cleared_off_codes(descriptor), extended, @@ -3033,6 +3039,7 @@ impl RenderCommandEncoder { drew, drawn, coverage, + inputs_read, rewrites_unused_bits, residency, extended, @@ -3131,12 +3138,16 @@ impl RenderCommandEncoder { reformats.filter(|r| r.copies).map(|r| r.index).collect() }) .collect(); - let taken: BTreeSet = (0..layout.colors.len()) + // The colors a draw took a view of: read as input attachments or in the pixel + // interlock, as sample planes, through a view of another format, or its extended-range + // shadow. A pass whose draws fetch through input attachments counts every color taken + // for its bound linear ones (`linear_attachment.rs`). + let viewed: BTreeSet = (0..layout.colors.len()) .filter(|&index| { let planes = layout.colors[index] .as_ref() .is_some_and(|color| color.planes.is_some()); - layout.fetch_inputs + inputs_read.contains(&(index as u32)) || planes || extended.made(index as u32) || instances.iter().any(|instance| { @@ -3148,6 +3159,46 @@ impl RenderCommandEncoder { }) }) .collect(); + let taken: BTreeSet = match layout.fetch_inputs { + true => (0..layout.colors.len()).collect(), + false => viewed.clone(), + }; + // Whether a draw renders views, and the pass executes render commands, whose commands + // record later, whatever they record (`render/executions.rs`). + let views = instances + .iter() + .any(|instance| instance.views != ViewSetup::default()); + let executes = !executions.is_empty(); + // Nothing recorded restarts a driver's Metal pass (`WholePass`). + let unbroken = + !executes && !driver_restarts && !views && layout.sample_positions.is_empty(); + // The colors a pass of one unbroken instance hands a driver that stores `DONT_CARE` as + // Metal's own `DontCare` so (`HandedToMetal`): none on another driver. + let whole = match instances.as_slice() { + [only] if unbroken => Some(WholePass { + shape: &only.shape, + drew, + }), + _ => None, + }; + let handed = HandedToMetal::of(core.device(), &layout, whole); + let handed: BTreeSet = (layout.colors.iter().enumerate()) + .filter_map(|(index, color)| Some((index, color.as_ref()?))) + .filter(|&(index, color)| handed.as_ref().is_some_and(|h| h.color(index, color))) + .map(|(index, _)| index) + .collect(); + // A texture over a buffer the pass does not store renders through an image its texture + // keeps, so the buffer keeps its bytes, as Metal's does, where the pass does not hand it + // to Metal's own `DontCare` and no draw took a view of its image (`kept_bytes.rs`). + // Before the linear attachments settle: it is not linear. + kept_bytes::settle( + core.command_buffer(), + &mut layout.colors, + executes, + |index| handed.contains(&index), + |index| viewed.contains(&index), + |index| taken.contains(&index), + )?; linear_attachment::settle( core.command_buffer(), &mut layout.colors, @@ -3784,11 +3835,6 @@ impl RenderCommandEncoder { offset: vk::Offset2D { x: 0, y: 0 }, extent: vk::Extent2D { width, height }, }; - let viewed = instances - .iter() - .any(|instance| instance.views != ViewSetup::default()); - // An execution's commands record later, whatever they record (`render/executions.rs`). - let executes = !executions.is_empty(); if let Some(first) = &first_texel_copies { core.shadow_copies(first); } @@ -4045,12 +4091,7 @@ impl RenderCommandEncoder { // unwritten pattern (`fresh_unwritten.rs`). FreshUnwritten::resolved(&device, &resolved, layout.extent)?; // The pass's one instance, where nothing recorded restarts a driver's Metal pass. - let whole = (shapes.len() == 1 - && !executes - && !driver_restarts - && !viewed - && layout.sample_positions.is_empty()) - .then(|| WholePass { + let whole = (shapes.len() == 1 && unbroken).then(|| WholePass { shape: &shapes[0], drew, }); @@ -4064,7 +4105,7 @@ impl RenderCommandEncoder { dispatches: dispatch_count, barriers: barrier_splits, tile_memory: tile_memory_splits, - viewed, + viewed: views, }, ); device.degrade_planes(&layout); @@ -6082,6 +6123,9 @@ impl RenderCommandEncoder { }; fetched.sort_unstable(); fetched.dedup(); + if self.layout.fetch_inputs { + self.inputs_read.extend(fetched.iter().copied()); + } // A draw that reads and writes some of the instance's interlocked colors and writes none // of the others records in it, as one that reads them all would. if !self.layout.fetch_inputs && self.fits_storage(&fetched, graphics.color_outputs) { diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index 2284a90c1..b365450dd 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -2076,6 +2076,9 @@ impl RenderExecution { drew: true, drawn: crate::clear_reach::DrawnArea::unbounded(), coverage: crate::linear_attachment::Coverage::unbounded(), + // A pass that executes render commands keeps its attachments over buffers in place + // (`kept_bytes.rs`), whatever its draws read. + inputs_read: BTreeSet::new(), // The encoder that executes the commands records the pass's load pass // (`defer_execution`); this one records only the commands' draws. rewrites_unused_bits: false, diff --git a/crates/metal2vulkan-runtime/src/render/shadows.rs b/crates/metal2vulkan-runtime/src/render/shadows.rs index 0ebaca479..d09983e55 100644 --- a/crates/metal2vulkan-runtime/src/render/shadows.rs +++ b/crates/metal2vulkan-runtime/src/render/shadows.rs @@ -12,8 +12,10 @@ //! copied in before the first, so a load, a clear, and the texels the pass leaves alone are the //! buffer's; copied back at the end where the pass stores it (`Store`, //! `StoreAndMultisampleResolve`) or resolves into it. A `DontCare` store copies nothing back: the -//! buffer keeps its bytes, Metal's answer (TOB probe 1). A texture over a buffer with an aliasing -//! image renders into that image: the buffer's bytes, with no copy. +//! buffer keeps its bytes, Metal's answer (TOB probe 1, and the DontCare-store probe, +//! `kept_bytes.rs`). A texture over a buffer with an aliasing image renders into that image: +//! the buffer's bytes, with no copy; but a pass that does not store it renders through an image +//! its texture keeps, from which nothing is copied back either (`kept_bytes.rs`). //! - **Two ways.** An instance that writes through a shadowed texture (in a draw, or as an //! attachment it stores) and also writes its bytes another way keeps the texture before it //! and merges it after it, as `shadow.rs` does for a command: the merge goes between it and the diff --git a/crates/metal2vulkan-runtime/src/render_target.rs b/crates/metal2vulkan-runtime/src/render_target.rs index 30029f3f0..0310edd4b 100644 --- a/crates/metal2vulkan-runtime/src/render_target.rs +++ b/crates/metal2vulkan-runtime/src/render_target.rs @@ -78,20 +78,23 @@ //! unless its tiler overflows, when it writes the rendered ones (measured), a choice no program //! sees or controls; so is `MultisampleResolve`'s, whose samples Metal leaves undefined. On //! MoltenVK on the Apple M4 and M3 Max it is Metal's own store where the pass's one instance -//! hands it so ([`handed_dont_care`], `DriverFact::DontCareStoreIsMetals`). A resolve attachment -//! is written whole over the render area (`DONT_CARE` then `STORE`), but an aspect of a -//! depth/stencil resolve that does not resolve keeps its texels. An aspect of the attached -//! texture's Metal format that no attachment names keeps its texels (loaded and stored); an -//! aspect only the Vulkan format has (the depth of a `Stencil8` texture held in a combined -//! format) is `DONT_CARE` both ways. +//! hands it so ([`handed_dont_care`], `DriverFact::DontCareStoreIsMetals`). A texture over a +//! buffer, which Metal leaves holding the buffer's bytes, renders through an image the pass +//! copies nothing back from (its shadow, or the image it keeps: `kept_bytes.rs`): the buffer's +//! bytes, exactly. A resolve attachment is written whole over the render area (`DONT_CARE` then +//! `STORE`), but an aspect of a depth/stencil resolve that does not resolve keeps its texels. +//! An aspect of the attached texture's Metal format that no attachment names keeps its texels +//! (loaded and stored); an aspect only the Vulkan format has (the depth of a `Stencil8` texture +//! held in a combined format) is `DONT_CARE` both ways. //! - **Where `DONT_CARE` is no answer of Metal's**. Vulkan leaves a `DONT_CARE` attachment's //! contents undefined, and a driver may leave a third answer, neither texel Metal keeps (NVIDIA's //! left a pass's clear under its draw). Metal's `DontCare` and `MultisampleResolve` are //! `DONT_CARE` only on a driver measured to keep one of Metal's two answers //! (`DriverFact::DontCareStoreIsOneOfMetals`) or to store as Metal's own //! (`DriverFact::DontCareStoreIsMetals`); every other device stores the attachment (`STORE`), -//! the answer Metal gives where its tiler overflows ([`DontCare`]). A memoryless attachment -//! and the hidden depth and stencil keep `DONT_CARE`: no texture of the program's holds them. +//! the answer Metal gives where its tiler overflows ([`DontCare`]). A memoryless attachment, +//! the hidden depth and stencil, and the image a texture over a buffer keeps for a pass that +//! does not store it (`kept_bytes.rs`) keep `DONT_CARE`: no texture of the program's holds them. //! - **The compatible pass** has the same formats and sample counts with every operation `LOAD` //! and `STORE`: render pass compatibility ignores the operations, so the draws' secondary //! command buffer and the encoder's graphics pipelines record against it while the store @@ -102,6 +105,7 @@ //! first needs one and destroyed with the device, for at most [`KEPT_SHAPES`] shapes; an //! encoder of a shape past them makes its own, which its command buffer holds so. +use super::attachment_stand_in::Cause; use super::attachmentless; use super::binding_view::VkView; use super::device::lock; @@ -750,11 +754,18 @@ pub(super) fn final_pass( } /// The operations of color attachment `color` in an instance at `at`, the sample planes' -/// `anchor` or not, its `DontCare` `dont_care`'s. An attachment the exact resolve reads after the -/// pass keeps its samples for it, and one whose texels are copied as its resolve its texels. +/// `anchor` or not, its `DontCare` `dont_care`'s, but the image a texture over a buffer keeps for +/// a pass that does not store it, which nothing reads after the pass (`kept_bytes.rs`). An +/// attachment the exact resolve reads after the pass keeps its samples for it, and one whose +/// texels are copied as its resolve its texels. fn color_ops(color: &ColorTarget, anchor: bool, at: Position, dont_care: DontCare) -> Ops { let exact = color.resolve.as_ref().is_some_and(|r| r.shader.is_some()) || color.copied_resolve.is_some(); + let unheld = color.memoryless + || color + .stand_in + .as_ref() + .is_some_and(|s| s.cause == Cause::KeptBytes); if anchor { ANCHORED } else { @@ -762,7 +773,7 @@ fn color_ops(color: &ColorTarget, anchor: bool, at: Position, dont_care: DontCar load: load_at(color.load, at), store: match exact { true => vk::AttachmentStoreOp::STORE, - false => store_at(color.store, at, dont_care.unless(color.memoryless)), + false => store_at(color.store, at, dont_care.unless(unheld)), }, stencil_load: vk::AttachmentLoadOp::DONT_CARE, stencil_store: vk::AttachmentStoreOp::DONT_CARE, diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 70b570f1b..4eb021def 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -4161,6 +4161,16 @@ impl Texture { matches!(self.0.storage, Storage::Alias { .. }) && self.linear_image().unwrap_or(false) } + /// Whether the texture's image lies over its buffer's bytes now: an aliasing image, linear + /// or a Metal texture over the import's `MTLBuffer` (`AliasKind`), not presenting a stand-in + /// while its bytes are detached (`detach.rs`), so a pass that renders it writes those bytes. + pub(super) fn image_over_buffer(&self) -> bool { + match &self.0.storage { + Storage::Alias { image, .. } => lock(&image.detached).is_none(), + _ => false, + } + } + /// Whether the texture is a buffer's bytes: a texture buffer or a shadowed texture. pub(super) fn over_buffer(&self) -> bool { !matches!(self.0.storage, Storage::Image(_)) diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 37422a6eb..ffecda142 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -82,6 +82,7 @@ pub(crate) struct Counters { graphics_pipelines_looked_up: AtomicU64, linear_passes_in_place: AtomicU64, linear_passes_through_copies: AtomicU64, + kept_bytes_passes: AtomicU64, draw_states_recorded: AtomicU64, host_deallocators_delayed: AtomicU64, dma_buf_imports: AtomicU64, @@ -432,6 +433,12 @@ impl Counters { counter.fetch_add(1, Ordering::Relaxed); } + /// A pass rendered a texture over a buffer it does not store through the image its texture + /// keeps (`kept_bytes.rs`). + pub(crate) fn kept_bytes_pass(&self) { + self.kept_bytes_passes.fetch_add(1, Ordering::Relaxed); + } + /// Draws recorded `count` state commands into their secondary command buffers /// (`render::Recording::record`). pub(crate) fn draw_states_recorded(&self, count: u64) { @@ -816,6 +823,10 @@ pub struct WorkCounts { /// Those that rendered one through the image its texture keeps: copied in and its changed /// words merged back, or cleared there and copied back. pub linear_passes_through_copies: u64, + /// Passes that rendered a color attachment over a buffer's bytes, which they do not store + /// (`DontCare`, `MultisampleResolve`), through the image its texture keeps, so that the buffer + /// keeps its bytes (`kept_bytes.rs`). + pub kept_bytes_passes: u64, /// State commands draws recorded into their secondary command buffers: pipeline binds, /// descriptor set binds, their push constants, vertex and index buffer binds, and dynamic /// states. None for a command that sets what its command buffer already holds from an @@ -983,6 +994,7 @@ impl Device { linear_passes_through_copies: counters .linear_passes_through_copies .load(Ordering::Relaxed), + kept_bytes_passes: counters.kept_bytes_passes.load(Ordering::Relaxed), draw_states_recorded: counters.draw_states_recorded.load(Ordering::Relaxed), host_deallocators_delayed: counters.host_deallocators_delayed.load(Ordering::Relaxed), dma_buf_imports: counters.dma_buf_imports.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 7222e2ec9..513c52bdb 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -d077af133e55b9ed68869d29612022113e8d92c04237b39c4c586a12f3ca5b7d +1bbe379e845c25efa74ffdd0256e63edef72c27cb9ace422eac12610f6dff16a diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case/metal_import_gap.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case/metal_import_gap.rs index ea9a7af8b..eb3c329ac 100644 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case/metal_import_gap.rs +++ b/crates/metal2vulkan-validation/src/candidate/runtime_case/metal_import_gap.rs @@ -12,12 +12,13 @@ //! only `vkBindImageMemory` marks bound (Vulkan-ValidationLayers v1.4.357, //! `layers/state_tracker/image_state.cpp`, the `Image` constructors; its Metal code there handles //! exports alone, `GetMetalExport`; unchanged in main of 2026-10-07). So every barrier, view, -//! framebuffer and descriptor of such an image reports it "used with no memory bound". +//! framebuffer and descriptor of such an image, and every copy from it, reports it "used with no +//! memory bound". //! //! The runtime makes such an image for a texture over a no-copy buffer on a driver that runs on //! Metal (`runtime/src/metal_texture.rs`) and names it [`NAME`] where its instance reports //! messages (`runtime/src/host_memory.rs`, `METAL_TEXTURE_IMAGE`). [`shape`] matches exactly the -//! four messages the layer gives such an image, and only when the image they name bears that +//! five messages the layer gives such an image, and only when the image they name bears that //! name; [`read`] keys the layer releases whose source was read with the gap in place. On any //! other release such a message fails, marked "re-read the image state in layer X.Y.Z", so a //! fixed or changed layer is checked again rather than trusted. @@ -25,12 +26,15 @@ use ash::vk; /// The messages the layer gives an image it believes unbound, as the lanes saw them on MoltenVK -/// (EV `ZCI-mvkprobe1-mvk4`): a barrier, a view, a framebuffer attachment, a descriptor. -const ID_NAMES: [&str; 4] = [ +/// (EV `ZCI-mvkprobe1-mvk4`): a barrier, a view, a framebuffer attachment, a descriptor; and the +/// source of an image copy, as the kept-bytes lanes saw it there (a pass copying the texels of +/// such a texture into the image its texture keeps, `runtime/src/kept_bytes.rs`). +const ID_NAMES: [&str; 5] = [ "VUID-VkImageMemoryBarrier-image-01932", "VUID-VkImageViewCreateInfo-image-01020", "UNASSIGNED-VkFramebufferCreateInfo-BoundResourceFreedMemoryAccess", "UNASSIGNED-VkDescriptorImageInfo-BoundResourceFreedMemoryAccess", + "VUID-vkCmdCopyImage-srcImage-07966", ]; /// The runtime's name for an image made of a Metal texture (`runtime/src/host_memory.rs`, @@ -49,7 +53,7 @@ pub(super) const SOURCE: &str = "Vulkan-ValidationLayers v1.4.357 \ layers/state_tracker/image_state.cpp, vvl::Image::Image: the memory tracker is chosen from \ the create flags alone; no VkImportMetalTextureInfoEXT handling"; -/// Whether a message with this id name and text is the gap's: one of the four messages, about a +/// Whether a message with this id name and text is the gap's: one of the five messages, about a /// `VkImage` the runtime named [`NAME`], used with no memory bound: the `VkImage` the text names /// last before that phrase must bear the name. pub(super) fn shape(id_name: &str, text: &str) -> bool { @@ -96,6 +100,12 @@ mod tests { "vkCreateImageView(): pCreateInfo->image {image} used with no memory bound. \ Memory should be bound by calling vkBindImageMemory()." ), + "VUID-vkCmdCopyImage-srcImage-07966" => format!( + "vkCmdCopyImage(): srcImage {image} used with no memory bound. Memory should be \ + bound by calling vkBindImageMemory().\nThe Vulkan spec states: If srcImage is \ + non-sparse then the image or each specified disjoint plane must be bound \ + completely and contiguously to a single VkDeviceMemory object" + ), _ => format!( "vkCreateFramebuffer(): pCreateInfo->pAttachments[0] {image} used with no memory \ bound. Memory should be bound by calling vkBindImageMemory()." diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index e16714c35..471193aeb 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -365,6 +365,8 @@ mod inline_bytes; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod int_attributes; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod kept_buffer_bytes; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod kept_variants; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod kernel_imageblocks; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_renders.rs b/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_renders.rs index d5d6bd245..803d96af1 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_renders.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_renders.rs @@ -364,11 +364,14 @@ fn each_kind(device: &Device, cases: impl Fn(&Lane, Kind)) { } /// A texture over a buffer as a color attachment stores Metal's bytes: clears at rows of 32, -/// 256 and 16 bytes write the texel rows alone; a `DontCare` store leaves the bytes; a load keeps -/// the texels a draw leaves; a view of the texture's own format renders into it; slice 1 of a -/// linear array renders there (TOB probe 1's `r.clear*`, `r.load_draw`, `r.clear_draw`, -/// `r.dontcare_full`, `r.view_same`, `r.slice1`). After a `DontCare` load, the texels outside -/// the draw are the buffer's or zero (Metal's), which is printed (`r.dontcare_half`). +/// 256 and 16 bytes write the texel rows alone; a `DontCare` store leaves the bytes, after a clear +/// with no draw, a clear and a draw over the whole texture, a `DontCare` load and a draw over its +/// left half, and a load and a draw over the whole (the DontCare-store probe, an M3 Max under +/// macOS 27.0.1, 20 times each alike); a load keeps the texels a draw leaves; a view of the +/// texture's own format renders into it; slice 1 of a linear array renders there (TOB probe 1's +/// `r.clear*`, `r.load_draw`, `r.clear_draw`, `r.dontcare_full`, `r.view_same`, `r.slice1`). +/// After a `DontCare` load, the texels outside the draw are the buffer's or zero (Metal's), which +/// is printed (`r.dontcare_half`). #[test] fn attachments_over_buffers_store_metals_bytes() { on_device(|device| each_kind(device, attachments)); @@ -398,6 +401,20 @@ fn attachments(lane: &Lane, kind: Kind) { lane.run(&descriptor, |_, _, _| {}).unwrap(); Expect::of(&b.model).check(&b.bytes(), &name("clear_dontcare")); } + for (case, load, rect) in [ + ("clear_draw_dontcare", LoadAction::Clear, FULL), + ("dontcare_half_dontcare", LoadAction::DontCare, LEFT), + ("load_draw_dontcare", LoadAction::Load, FULL), + ] { + let b = Held::new(device, kind).unwrap(); + let t = over(&b, BPR); + let descriptor = pass(&t, load, StoreAction::DontCare, CLEAR); + lane.run(&descriptor, |l, e, h| { + l.rect(e, h, &solid, rect, Some(COLOR)) + }) + .unwrap(); + Expect::of(&b.model).check(&b.bytes(), &name(case)); + } for case in ["load_draw", "clear_draw", "dontcare_full", "view_same"] { let mut b = Held::new(device, kind).unwrap(); if case != "clear_draw" { diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index aa8a71f43..aa47f9417 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -92,7 +92,9 @@ //! does in `compressed_decode` ([`BLOCK_DECODES`]) and writes into their decoded twins behind //! work in flight there ([`BEHIND_WRITES`]), passes rendering a linear image apart in //! `linear_attachments` ([`LINEAR_COPIES`]) and those rendering one through copies as they clear -//! it and no command of them may read it, there too ([`CHOSEN_COPIES`]), the device's +//! it and no command of them may read it, there too ([`CHOSEN_COPIES`]), passes rendering a texture +//! over a buffer they do not store through the image its texture keeps in `kept_buffer_bytes` +//! ([`KEPT_BYTES`]), the device's //! first sparse texture on a driver whose first sparse resource waits for every queue's work in //! `first_use` ([`FIRST_SPARSE`]), //! and @@ -150,6 +152,7 @@ use super::indirect_command_buffers::{PAST_RECORD, UNMEASURED_IDENTIFIERS}; use super::indirect_dispatches::INDIRECT_DISPATCHES; use super::indirect_executions::{NIL_OFFSETS, RELEASED_STATES}; use super::indirect_host_steps::HOST_STEPS; +use super::kept_buffer_bytes::KEPT_BYTES; use super::linear_attachments::{CHOSEN_COPIES, LINEAR_COPIES}; use super::mesh_draws::EMULATED_MESH; use super::mipmaps_exact::{M3_MIPMAPS, TIE_MIPMAPS}; @@ -496,6 +499,7 @@ fn every_kind_has_a_site_a_lane_test_takes() { &PAST_METAL_SIZES, &LINEAR_COPIES, &CHOSEN_COPIES, + &KEPT_BYTES, &DELAYED_DEALLOCATORS, &MISPLACED, &DEPTH_DENORMALS, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs index 993054ae0..0b817ef18 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs @@ -155,7 +155,7 @@ fn udmabuf_openable(test: &str) -> bool { struct Memfd { fd: OwnedFd, len: usize, - whole: View, + pub(super) whole: View, } /// What a test's source saw: each request, with the number of chunks it answered (0 for an @@ -383,7 +383,7 @@ impl View { } /// A copy of the view's bytes `range`. - fn read(&self, range: std::ops::Range) -> Vec { + pub(super) fn read(&self, range: std::ops::Range) -> Vec { assert!(range.start <= range.end && range.end <= self.len); // SAFETY: the range lies in the view; each test orders the accesses. unsafe { @@ -392,7 +392,7 @@ impl View { } /// Write `bytes` into the view at `offset`. - fn write(&self, offset: usize, bytes: &[u8]) { + pub(super) fn write(&self, offset: usize, bytes: &[u8]) { assert!(offset + bytes.len() <= self.len); // SAFETY: as in `read`. unsafe { @@ -487,7 +487,7 @@ fn check_route( } /// A no-copy buffer over `length` bytes of `view` from `offset`, with `source`. -fn no_copy( +pub(super) fn no_copy( device: &Device, view: &View, offset: usize, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs index c2ae2cde9..1e1684a57 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs @@ -52,6 +52,14 @@ //! `frame_costs_announced` measure one alone, in a process of its own, for a profile of it //! (`perf record -g` of the test's process). //! +//! `frame_costs_over_buffers` measures the plain device with window layers that are textures over +//! `Shared` buffers at tight rows (2048 bytes, which RADV and ANV render in place, as linear images +//! over the buffers' memory) in place of private textures, their passes loaded and stored, loaded +//! and stored `DontCare`, and cleared and stored `DontCare`, each on a device of its own: what a +//! pass that does not store such a layer costs, rendered through the image its texture keeps so +//! that the buffer keeps its bytes. Its lines also give a frame's wall time through its last +//! command buffer's completion, the GPU's work included. +//! //! Ignored by default: a measurement, not a check. Run it by name with `--run-ignored all`, in a //! build with `--cfg m2v_system_alloc` for the times, whose lib test binary keeps the system //! allocator as a consumer's process does (the counting one costs the draw path about a sixth of @@ -155,38 +163,66 @@ const COMMIT_ALLOCATIONS: f64 = 6.0; #[cfg(not(m2v_system_alloc))] const SUBMIT_ALLOCATIONS: f64 = 20.0; -/// One run's device and commits: whether the device announces every precision kind, and whether -/// each command buffer commits with a submission check ([`Checks`]). +/// One run's device, commits and layers: whether the device announces every precision kind, +/// whether each command buffer commits with a submission check ([`Checks`]), and what the window +/// layers are. #[derive(Clone, Copy)] struct Run { announced: bool, checked: bool, + layers: Layers, } impl Run { const PLAIN: Run = Run { announced: false, checked: false, + layers: Layers::Private, }; const CHECKED: Run = Run { announced: false, checked: true, + layers: Layers::Private, }; const ANNOUNCED: Run = Run { announced: true, checked: false, + layers: Layers::Private, }; - fn label(self) -> &'static str { - match (self.announced, self.checked) { + /// The plain device's run with layers over buffers, its passes loading and storing them so. + const fn over_buffers(load: LoadAction, store: StoreAction) -> Run { + Run { + layers: Layers::OverBuffers(load, store), + ..Run::PLAIN + } + } + + fn label(self) -> String { + let device = match (self.announced, self.checked) { (false, false) => "plain", (false, true) => "checked", (true, false) => "announced", (true, true) => "announced checked", + }; + match self.layers { + Layers::Private => device.to_owned(), + Layers::OverBuffers(load, store) => { + format!("{device}, layers over buffers, {load:?} load, {store:?} store") + } } } } +/// What the window layers are, and how a pass that is not resolved loads and stores its layer. +#[derive(Clone, Copy, Debug)] +enum Layers { + /// Private textures, loaded and stored. + Private, + /// Textures over `Shared` buffers at tight rows, loaded and stored by these. + OverBuffers(LoadAction, StoreAction), +} + /// The submissions the checks of a checked run saw: each the encoders it named, noted under a /// lock, as the consumer's check notes each submission it lets run. #[derive(Default)] @@ -222,6 +258,9 @@ struct Pipelines { /// The device, its queue, and what the frames draw with. struct Workload { device: Device, + layers: Layers, + /// The buffers the layers lie over, where they do. + layer_buffers: Vec, queue: CommandQueue, /// A checked run's submissions checked. checks: Option>, @@ -305,6 +344,20 @@ fn target(device: &Device, samples: u64) -> Texture { device.new_texture(&descriptor).unwrap() } +/// A `TARGET_SIDE` square `BGRA8Unorm_sRGB` render target over a new `Shared` buffer at tight +/// rows, and the buffer. +fn target_over_buffer(device: &Device) -> (Texture, Buffer) { + let rows = 4 * TARGET_SIDE; + let buffer = device + .new_buffer(rows * TARGET_SIDE, ResourceOptions::shared()) + .unwrap(); + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::BGRA8UnormSRGB, TARGET_SIDE, TARGET_SIDE, false); + descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + descriptor.resource_options = buffer.resource_options(); + (buffer.new_texture(&descriptor, 0, rows).unwrap(), buffer) +} + /// `ZwdShape`'s bytes: draw `n`'s box in a pass of the target's size, a fill and an outline. fn shape(n: usize) -> [u8; SHAPE_BYTES] { let x = (n % 8) as f32 * 60.0; @@ -335,7 +388,7 @@ fn shape(n: usize) -> [u8; SHAPE_BYTES] { } impl Workload { - fn new(device: Device, checked: bool) -> Workload { + fn new(device: Device, checked: bool, layers: Layers) -> Workload { let library = |name: &str| { device.new_library_with_air(&llvm_assemble(&engine_dir().join(name)).unwrap()) }; @@ -383,14 +436,23 @@ impl Workload { }) .flat_map(f32::to_le_bytes) .collect(); + let (targets, layer_buffers) = match layers { + Layers::Private => ( + (0..TARGETS).map(|_| target(&device, 1)).collect(), + Vec::new(), + ), + Layers::OverBuffers(..) => (0..TARGETS).map(|_| target_over_buffer(&device)).unzip(), + }; Workload { + layers, + layer_buffers, queue: device.new_command_queue().unwrap(), checks: checked.then(Arc::default), pipelines, sampler, textures, mask: sampled(&device, [255, 255, 255, 128]), - targets: (0..TARGETS).map(|_| target(&device, 1)).collect(), + targets, multisampled: target(&device, 4), indices: buffer_with(&device, &indices).unwrap(), rects: buffer_with(&device, &rects).unwrap(), @@ -398,8 +460,9 @@ impl Workload { } } - /// Pass `pass`'s descriptor: its layer loaded and stored, or, for a resolved pass, the - /// 4-sample texture cleared and resolved into the layer. + /// Pass `pass`'s descriptor: its layer loaded and stored (by the layers' actions where they + /// lie over buffers), or, for a resolved pass, the 4-sample texture cleared and resolved into + /// the layer. fn pass(&self, pass: usize) -> RenderPassDescriptor { let mut descriptor = RenderPassDescriptor::new(); let color = &mut descriptor.color_attachments[0]; @@ -411,9 +474,14 @@ impl Workload { color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); color.store_action = StoreAction::MultisampleResolve; } else { + let (load, store) = match self.layers { + Layers::Private => (LoadAction::Load, StoreAction::Store), + Layers::OverBuffers(load, store) => (load, store), + }; color.texture = Some(layer); - color.load_action = LoadAction::Load; - color.store_action = StoreAction::Store; + color.load_action = load; + color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + color.store_action = store; } descriptor } @@ -540,6 +608,7 @@ impl Workload { .map(|(before, after)| after.since(before)); let last = last.unwrap(); last.wait_until_completed_for(WAIT).unwrap(); + frame.done = start.elapsed(); assert_eq!(last.status(), CommandBufferStatus::Completed); frame } @@ -716,6 +785,8 @@ struct Frame { commit: Vec, wall: Duration, cpu: Duration, + /// Through the last command buffer's completion. + done: Duration, /// The command buffers its passes' openings, their draws, their ends and its commits began, /// in that order, where it read the work counts ([`Workload::frame_reading`]); none /// elsewhere. @@ -917,7 +988,11 @@ fn measure(runs: &[Run]) { for &run in runs { let cache = ScratchCache::new().unwrap(); let heard = Heard::default(); - let work = Workload::new(device(&cache, run.announced, &heard), run.checked); + let work = Workload::new( + device(&cache, run.announced, &heard), + run.checked, + run.layers, + ); let label = run.label(); let name = work.device.name().to_owned(); let ms = |d: Duration| d.as_secs_f64() * 1e3; @@ -964,12 +1039,14 @@ fn measure(runs: &[Run]) { let counted: Vec = (0..COUNTED).map(|_| work.frame_reading(reads)).collect(); let [cpu, cpu_high] = percentiles(frames.iter().map(|f| ms(f.cpu)).collect()); let [wall, wall_high] = percentiles(frames.iter().map(|f| ms(f.wall)).collect()); + let [done, done_high] = percentiles(frames.iter().map(|f| ms(f.done)).collect()); eprintln!( "FRAME-COST {name} {label}: {BUFFERS} command buffers of one pass of {DRAWS} indexed \ draws a frame, every {RESOLVED}th pass resolved, {WARM} untimed and {TIMED} timed \ frames: the encoding thread's CPU {cpu:.2} ms a frame (p90 {cpu_high:.2}), wall \ - {wall:.2} ms (p90 {wall_high:.2}), {} a frame; {:.1} us of CPU a draw over the \ - frame; {:.1} notices a frame", + {wall:.2} ms (p90 {wall_high:.2}), through completion {done:.2} ms (p90 \ + {done_high:.2}), {} a frame; {:.1} us of CPU a draw over the frame; {:.1} notices \ + a frame", blocks(&frames), cpu * 1e3 / (BUFFERS * DRAWS) as f64, (notices - notices_before) as f64 / TIMED as f64, @@ -1080,7 +1157,7 @@ fn measure(runs: &[Run]) { "FRAME-COST {name} {label}: the other threads a command buffer: {threads}; \ {allocations}" ); - if run.announced { + if run.announced || work.layer_buffers.len() == TARGETS { for (kind, (count, _)) in heard.lock().unwrap().iter() { eprintln!( "FRAME-COST {name} {label}: heard {} {count} times", @@ -1142,13 +1219,23 @@ fn frame_costs_announced() { measure(&[Run::ANNOUNCED]); } +#[test] +#[ignore = "a measurement, not a check: run by name with --run-ignored all"] +fn frame_costs_over_buffers() { + measure(&[ + Run::over_buffers(LoadAction::Load, StoreAction::Store), + Run::over_buffers(LoadAction::Load, StoreAction::DontCare), + Run::over_buffers(LoadAction::Clear, StoreAction::DontCare), + ]); +} + /// One frame of a plain device, once every pipeline is made and every pool piece done, its /// allocations counted; and the device's name. #[cfg(not(m2v_system_alloc))] fn counted() -> (String, Frame) { let cache = ScratchCache::new().unwrap(); let heard = Heard::default(); - let work = Workload::new(device(&cache, false, &heard), false); + let work = Workload::new(device(&cache, false, &heard), false, Layers::Private); for _ in 0..WARM { work.frame(); } @@ -1203,7 +1290,7 @@ fn a_frame_s_draws_and_pass_ends_allocate_within_their_bounds() { fn a_frame_s_passes_and_commits_begin_their_command_buffers_within_their_bound() { let cache = ScratchCache::new().unwrap(); let heard = Heard::default(); - let work = Workload::new(device(&cache, false, &heard), false); + let work = Workload::new(device(&cache, false, &heard), false, Layers::Private); // Every pipeline made, and every pool piece done, before the frame that counts. for _ in 0..WARM { work.frame(); @@ -1269,7 +1356,7 @@ fn a_frame_s_pass_opens_allocate_within_their_bound() { fn a_frame_s_commits_allocate_within_their_bound() { let cache = ScratchCache::new().unwrap(); let heard = Heard::default(); - let work = Workload::new(device(&cache, false, &heard), true); + let work = Workload::new(device(&cache, false, &heard), true, Layers::Private); // Every pipeline made, and every pool piece done, before the frames that count. for _ in 0..WARM { work.frame(); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/kept_buffer_bytes.rs b/crates/metal2vulkan-validation/src/runtime_lane/kept_buffer_bytes.rs new file mode 100644 index 000000000..ea8368e19 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/kept_buffer_bytes.rs @@ -0,0 +1,1105 @@ +//! Device tests of textures over buffers that a render pass does not store, on the device the cfg +//! selects, under the validation layer: the DontCare-store probe's cases (an Apple M3 Max under +//! macOS 27.0.1, each case 20 times alike), where Metal leaves the buffer's bytes in every texel +//! after a pass that stores its color attachment over them `DontCare`, and no byte between the +//! rows changes. +//! +//! Each case fills a buffer with the bytes `(7i + 3) mod 256`, makes a 2D texture over it at +//! offset 0, and runs one pass that loads the texture by `Load`, `Clear` (to 0.5 in every channel) +//! or `DontCare`, draws a rectangle of 64/255 in every channel over the whole texture, its left +//! half, its top left corner (at most 32x32) or nowhere, and stores it `DontCare`. Every byte of +//! the buffer must be the one it held before the pass. The probe's sweep, cut to the runtime's +//! questions: +//! +//! - **Every format** ([`FORMATS`]: `BGRA8Unorm`, `RGBA8Unorm`, `BGRA8Unorm_sRGB`, `RGBA16Float`, +//! `R8Unorm`), over an ordinary `Shared` buffer and a no-copy buffer of host pages: 16x16 at +//! tight rows and 64x32 at rows a multiple of 256 bytes (at which RADV renders a linear image +//! over the buffer), each load action and full, half and no coverage; 1307x512 at padded rows +//! (5248 bytes for `BGRA8Unorm`, as a window server's tile, the probe's rows for the others), +//! each load action at half coverage and a corner; and, for `BGRA8Unorm` and `RGBA16Float`, +//! 333x77 at odd rows, each load action at a corner. +//! - **After a stored render** (`BGRA8Unorm`, `RGBA16Float`, `R8Unorm`): a pass loads the texture, +//! draws 32/255 over it and stores it, then the case's pass: the buffer keeps the first pass's +//! bytes. +//! - **Beside a second attachment** stored `Store` (the same three formats): an ordinary texture +//! of the format, cleared to zero, which the draw writes 96/255 into: it holds them, and the +//! buffer keeps its bytes. +//! - **Over a surface's plane** (`Buffer::new_texture_with_iosurface_plane` over a managed +//! no-copy buffer, as a consumer stands one in for an IOSurface): `BGRA8Unorm` at 16x16 (rows of +//! 64 bytes), 64x32 (rows of 256) and 1307x512 (rows of 5248), each load action at full, half and +//! no coverage. +//! - **Store actions**: `Unknown` left at the pass's end, and `Unknown` set to `DontCare` as the +//! pass ends (`set_color_store_action`), keep the bytes; `Unknown` set to `Store` stores the +//! draw. `MultisampleResolve` of the single-sampled attachment into an ordinary texture keeps +//! the buffer's bytes and resolves the draw (plain Metal's answer, its validation off); +//! `StoreAndMultisampleResolve` stores and resolves it; each at 16x16 and at 64x32. One +//! 2048x2048 `BGRA8Unorm` pass over tight rows keeps the bytes too. +//! - **Through a barrier**: the draw, a barrier, and the draw again, where Metal keeps the +//! buffer's bytes as well (the barrier probe, the same M3 Max, 20 times alike, over buffers, +//! render targets, textures and the buffer alone): a barrier over buffers, which splits the pass +//! into two render pass instances, and one over the render targets, where MoltenVK restarts its +//! Metal pass; `BGRA8Unorm` and `RGBA16Float` at 16x16 and 64x32, each load action at full and +//! half coverage, over ordinary, no-copy and (`BGRA8Unorm`) surface buffers. +//! - **Over dma-buf pages** (`HostMemory::with_dma_buf`, on Linux where `/dev/udmabuf` opens): +//! a `BGRA8Unorm` texture over a no-copy buffer of memfd pages, which RADV makes an image over +//! a dma-buf of its own pages, and a device that imports the pointer an image over the +//! pointer's. +//! +//! The controls store the same passes with `Store`: the draw's texels are the rendered value (the +//! bytes the same draw stores into an ordinary texture of the format), and outside the draw the +//! buffer's (`Load`) or the clear value's (`Clear`, the bytes a clear stores there), every byte +//! between the rows the buffer's. +//! +//! The runtime renders such a pass through an image the pass copies nothing back from: the +//! texture's shadow where it has one (announced `shadowed-texture` as the texture is made), else, +//! as the texture's image lies over the buffer (linear, or on MoltenVK a Metal texture over its +//! `MTLBuffer`), through an image its texture keeps, which it +//! announces as `dont-care-stand-in` ([`KEPT_BYTES`]) and counts +//! (`WorkCounts::kept_bytes_passes`); but where the device renders the image only beside other +//! linear ones (NVIDIA's `VK_NV_linear_color_attachment`) and the pass has a second attachment, +//! through the image the pass renders it apart in (`linear-attachment-copies`), which copies back +//! only what the pass stores; and where the driver stores `DONT_CARE` as Metal's own `DontCare` +//! (`DriverFact::DontCareStoreIsMetals`, MoltenVK on the M3 Max and the M4) and the pass is one +//! render pass instance the driver runs unbroken, in place, handed to Metal, which keeps the bytes +//! (a pass through a barrier, or whose resolve copies the attachment's texels, renders through the +//! kept image there too). The device announces these kinds at each occurrence here +//! (`DeviceOptions::announce_each`): each pass announces `dont-care-stand-in` and counts one pass +//! exactly where its texture is neither shadowed, rendered apart nor handed to Metal, a `Store` +//! control neither; no +//! pass announces `dont-care-store`, Metal's answer being exact. Each case prints its form +//! (`KEPT-BYTES`). +//! +//! Metal's one exception, the first pass in a process to overflow its tiler (some 2 to 4 million +//! triangle-tile entries), which leaves the rendered texels, is not modelled: no case comes near. + +use super::degrade_notices::{counts, on_device_with}; +#[cfg(target_os = "linux")] +use super::dma_buf_imports::{udmabuf_openable, Calls, Memfd}; +use super::host_memory::{host_page, no_copy, not_importable, Mapping}; +use super::{Messages, WAIT}; +use crate::air_library::AirLibrary; +use metal2vulkan::device::DriverFact; +use metal2vulkan::metal::{BarrierScope, PixelFormat, PrimitiveType, RenderStages, TextureUsage}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use metal2vulkan_devtools::llvm_assemble_text; +use metal2vulkan_runtime::{ + Buffer, ClearColor, CommandBufferStatus, CommandQueue, Deallocator, Degradation, Device, + IoSurfacePlane, Library, LoadAction, PipelineOptions, Region, RenderCommandEncoder, + RenderPassDescriptor, RenderPipelineState, ResourceOptions, StoreAction, Texture, + TextureDescriptor, +}; +use std::collections::BTreeMap; + +/// The kind a pass that renders a texture over a buffer through the image its texture keeps +/// announces. +pub(super) const KEPT_BYTES: [Degradation; 1] = [Degradation::DontCareStandIn]; + +/// The probe's formats and the bytes of a texel of each. +const FORMATS: [(PixelFormat, u64); 5] = [ + (PixelFormat::BGRA8Unorm, 4), + (PixelFormat::RGBA8Unorm, 4), + (PixelFormat::BGRA8UnormSRGB, 4), + (PixelFormat::RGBA16Float, 8), + (PixelFormat::R8Unorm, 1), +]; + +/// The probe's values: the draw's, a stored render's before it, the clear's, and the second +/// attachment's. +const RENDER: f32 = 64.0 / 255.0; +const PRIOR: f32 = 32.0 / 255.0; +const CLEAR: f64 = 0.5; +const SECOND: f32 = 96.0 / 255.0; + +/// `MTLResourceStorageModeManaged`. +const MANAGED: u64 = 1 << 4; + +/// The probe's functions, written here: a rectangle from corner `r.xy` to corner `r.zw` (two +/// triangles of six vertices), a fragment function returning `c[0]`, and one returning `c[0]` to +/// color 0 and `c[1]` to color 1. +const AIR: &str = r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +define <{ <4 x float> }> @kb_rect(i32 %vid, ptr addrspace(2) %r) { + %c = load <4 x float>, ptr addrspace(2) %r, align 16 + %odd = and i32 %vid, -3 + %one_or_three = icmp eq i32 %odd, 1 + %four = icmp eq i32 %vid, 4 + %right = or i1 %one_or_three, %four + %two = icmp eq i32 %vid, 2 + %pair = and i32 %vid, -2 + %four_or_five = icmp eq i32 %pair, 4 + %up = or i1 %two, %four_or_five + %x0 = extractelement <4 x float> %c, i64 0 + %y0 = extractelement <4 x float> %c, i64 1 + %x1 = extractelement <4 x float> %c, i64 2 + %y1 = extractelement <4 x float> %c, i64 3 + %x = select i1 %right, float %x1, float %x0 + %y = select i1 %up, float %y1, float %y0 + %px = insertelement <4 x float> , float %x, i64 0 + %p = insertelement <4 x float> %px, float %y, i64 1 + %out = insertvalue <{ <4 x float> }> undef, <4 x float> %p, 0 + ret <{ <4 x float> }> %out +} + +define <4 x float> @kb_one(<4 x float> %position, ptr addrspace(2) %c) { + %v = load <4 x float>, ptr addrspace(2) %c, align 16 + ret <4 x float> %v +} + +define <{ <4 x float>, <4 x float> }> @kb_two(<4 x float> %position, ptr addrspace(2) %c) { + %v0 = load <4 x float>, ptr addrspace(2) %c, align 16 + %at1 = getelementptr inbounds <4 x float>, ptr addrspace(2) %c, i64 1 + %v1 = load <4 x float>, ptr addrspace(2) %at1, align 16 + %out0 = insertvalue <{ <4 x float>, <4 x float> }> undef, <4 x float> %v0, 0 + %out = insertvalue <{ <4 x float>, <4 x float> }> %out0, <4 x float> %v1, 1 + ret <{ <4 x float>, <4 x float> }> %out +} + +!air.vertex = !{!0} +!air.fragment = !{!5, !10} +!air.version = !{!20} +!air.language_version = !{!21} +!0 = !{ptr @kb_rect, !1, !3} +!1 = !{!2} +!2 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!3 = !{!4, !9} +!4 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"vid"} +!9 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"r"} +!5 = !{ptr @kb_one, !6, !8} +!6 = !{!7} +!7 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!8 = !{!13, !14} +!10 = !{ptr @kb_two, !11, !8} +!11 = !{!7, !12} +!12 = !{!"air.render_target", i32 1, i32 0, !"air.arg_type_name", !"float4"} +!13 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!14 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"c"} +!20 = !{i32 2, i32 8, i32 0} +!21 = !{!"Metal", i32 4, i32 0, i32 0} +"#; + +/// What a case's buffer is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + /// An ordinary `Shared` buffer. + Shared, + /// A no-copy buffer over fresh anonymous host pages. + NoCopy, + /// A managed no-copy buffer standing for an IOSurface, the texture over its plane 0. + Surface, +} + +/// Where the case's draw lies: the probe's pixel rectangles from the texture's top left corner. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Coverage { + Full, + Half, + /// The top left quarter, at most 32x32 texels. + Corner, + /// No draw. + None, +} + +impl Coverage { + /// The far corner of the draw's pixel rectangle over a `w` x `h` texture; `None` for no draw. + fn corner(self, (w, h): (u64, u64)) -> Option<(u64, u64)> { + match self { + Coverage::Full => Some((w, h)), + Coverage::Half => Some((w / 2, h)), + Coverage::Corner => Some(((w / 2).min(32), (h / 2).min(32))), + Coverage::None => None, + } + } + + fn covers(self, extent: (u64, u64), x: u64, y: u64) -> bool { + self.corner(extent).is_some_and(|(x1, y1)| x < x1 && y < y1) + } +} + +/// What comes before the case's pass, or beside it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Variant { + FirstUse, + /// A pass loads the texture, draws [`PRIOR`] over all of it and stores it first. + RenderedOnce, + /// An ordinary texture of the format is color attachment 1, cleared to zero and stored, the + /// draw writing [`SECOND`] into it. + SecondAttachment, + /// The draw again after a barrier over buffers, from the fragment stage to the vertex stage, + /// which splits the pass into two render pass instances, the first storing the attachment. + Split, + /// The draw again after a barrier over the render targets, from the fragment stage to the + /// fragment stage, where MoltenVK restarts its Metal pass, storing the attachment. + Restarted, +} + +impl Variant { + /// The barrier the variant's pass draws again after, and its stages. + fn barrier(self) -> Option<(BarrierScope, RenderStages)> { + match self { + Variant::Split => Some((BarrierScope::BUFFERS, RenderStages::VERTEX)), + Variant::Restarted => Some((BarrierScope::RENDER_TARGETS, RenderStages::FRAGMENT)), + _ => None, + } + } +} + +/// A case's texture: its extent and the bytes between its rows' starts. +#[derive(Clone, Copy, Debug)] +struct Shape { + extent: (u64, u64), + rows: u64, +} + +/// What a pass counted (`WorkCounts::kept_bytes_passes`) and announced. +struct Seen { + counted: u64, + notices: BTreeMap, +} + +/// A buffer of the pattern and the texture over it. +struct Over { + buffer: Buffer, + texture: Texture, + /// The buffer's bytes. + len: usize, + /// Whether the device announced the texture shadowed. + shadowed: bool, +} + +/// The lane's device, its message sink, a queue, the functions, and each format's reference +/// texels and pipelines, made at first use. +struct Lane<'a> { + device: &'a Device, + /// The driver stores `DONT_CARE` as Metal's own `DontCare` + /// (`DriverFact::DontCareStoreIsMetals`). + metals: bool, + messages: &'a Messages, + queue: CommandQueue, + library: Library, + formats: BTreeMap, +} + +/// A format's pipelines (one color attachment, two) and the bytes a texel of it stores for the +/// draw ([`RENDER`]), a clear ([`CLEAR`]), the stored render ([`PRIOR`]) and the second +/// attachment's draw ([`SECOND`]), on the device. +struct Format { + bpp: u64, + one: RenderPipelineState, + two: RenderPipelineState, + rendered: Vec, + cleared: Vec, + prior: Vec, + second: Vec, +} + +/// A pass's color attachment 0: its texture, load and store actions. +struct Attachment<'t> { + texture: &'t Texture, + load: LoadAction, + store: StoreAction, +} + +/// The byte `i` of a case's buffer of texels of `pf`: `(7i + 3) mod 256`, but that an +/// `RGBA16Float` texel's halves are no NaN or infinity (bit 6 of each high byte clear), as a pass +/// that stores the texture may rewrite a NaN's bits on some devices (lavapipe quiets a signalling +/// one, announced `device-nan-encoding`), which is not this lane's question. +fn pattern(pf: PixelFormat, i: usize) -> u8 { + let byte = (7 * i + 3) as u8; + match pf == PixelFormat::RGBA16Float && i % 2 == 1 { + true => byte & 0xbf, + false => byte, + } +} + +fn floats(values: &[f32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +impl<'a> Lane<'a> { + fn new(device: &'a Device, messages: &'a Messages) -> Lane<'a> { + let library = device + .new_library_with_air(&llvm_assemble_text(AIR).unwrap()) + .unwrap(); + Lane { + device, + metals: (device.properties().driver_facts).contains(&DriverFact::DontCareStoreIsMetals), + messages, + queue: device.new_command_queue().unwrap(), + library, + formats: BTreeMap::new(), + } + } + + /// A pipeline drawing [`AIR`]'s rectangle into `colors` attachments of `pf`. + fn pipeline(&self, pf: PixelFormat, colors: usize) -> RenderPipelineState { + let function = |name: &str| { + StageSource::Function( + self.library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let mut descriptor = RenderPipelineDescriptor::new(function("kb_rect")); + descriptor.fragment = Some(function(match colors { + 1 => "kb_one", + _ => "kb_two", + })); + for slot in &mut descriptor.color_attachments[..colors] { + *slot = Some(ColorAttachmentDescriptor::new(pf)); + } + self.device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() + } + + /// `pf`'s pipelines and reference texels, made at first use. + fn format(&mut self, pf: PixelFormat) -> &Format { + if !self.formats.contains_key(&pf) { + let bpp = FORMATS.iter().find(|f| f.0 == pf).unwrap().1; + let one = self.pipeline(pf, 1); + let two = self.pipeline(pf, 2); + let mut format = Format { + bpp, + one, + two, + rendered: Vec::new(), + cleared: Vec::new(), + prior: Vec::new(), + second: Vec::new(), + }; + format.rendered = self.reference(&format, pf, Some(RENDER)); + format.cleared = self.reference(&format, pf, None); + format.prior = self.reference(&format, pf, Some(PRIOR)); + format.second = self.reference(&format, pf, Some(SECOND)); + self.formats.insert(pf, format); + } + &self.formats[&pf] + } + + /// The bytes texel (1, 1) of an ordinary `Shared` 4x4 texture of `pf` holds after a pass that + /// draws `value` over all of it (a `DontCare` load), or clears it ([`CLEAR`]) where `None`, + /// and stores it. + fn reference(&self, format: &Format, pf: PixelFormat, value: Option) -> Vec { + let mut d = TextureDescriptor::texture_2d(pf, 4, 4, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::shared(); + let texture = self.device.new_texture(&d).unwrap(); + let (load, coverage) = match value { + Some(_) => (LoadAction::DontCare, Coverage::Full), + None => (LoadAction::Clear, Coverage::None), + }; + let color = Attachment { + texture: &texture, + load, + store: StoreAction::Store, + }; + self.pass( + &format.one, + &color, + None, + coverage, + (value.unwrap_or(0.0), 0.0), + |_| {}, + ); + let bpp = format.bpp; + let mut bytes = vec![0; (16 * bpp) as usize]; + texture + .get_bytes(&mut bytes, 4 * bpp, 0, Region::new_2d(0, 0, 4, 4), 0, 0) + .unwrap(); + bytes[(5 * bpp) as usize..(6 * bpp) as usize].to_vec() + } + + /// Encode one pass of `color` (cleared to [`CLEAR`]) and `second` (cleared to zero and + /// stored), drawing `pipeline`'s rectangle over `coverage` of `color`'s texture in `values` + /// (colors 0 and 1), `end` encoding the pass's last commands; commit it and wait. + fn pass( + &self, + pipeline: &RenderPipelineState, + color: &Attachment<'_>, + second: Option<&Texture>, + coverage: Coverage, + (c0, c1): (f32, f32), + end: impl FnOnce(&mut RenderCommandEncoder), + ) { + let mut descriptor = RenderPassDescriptor::new(); + let target = &mut descriptor.color_attachments[0]; + target.texture = Some(color.texture.clone()); + target.load_action = color.load; + target.store_action = color.store; + target.clear_color = ClearColor::new(CLEAR, CLEAR, CLEAR, CLEAR); + if let Some(second) = second { + let target = &mut descriptor.color_attachments[1]; + target.texture = Some(second.clone()); + target.load_action = LoadAction::Clear; + target.store_action = StoreAction::Store; + target.clear_color = ClearColor::new(0.0, 0.0, 0.0, 0.0); + } + self.encode(&descriptor, |e| { + let (w, h) = (color.texture.width(), color.texture.height()); + if let Some((x1, y1)) = coverage.corner((w, h)) { + let rect = [ + -1.0, + 1.0, + 2.0 * x1 as f32 / w as f32 - 1.0, + 1.0 - 2.0 * y1 as f32 / h as f32, + ]; + e.set_render_pipeline_state(pipeline).unwrap(); + e.set_vertex_bytes(&floats(&rect), 0).unwrap(); + e.set_fragment_bytes(&floats(&[c0, c0, c0, c0, c1, c1, c1, c1]), 0) + .unwrap(); + e.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + } + end(e); + }); + } + + /// Encode `descriptor`'s pass by `body` in a command buffer of its own, commit it and wait. + fn encode( + &self, + descriptor: &RenderPassDescriptor, + body: impl FnOnce(&mut RenderCommandEncoder), + ) { + let command_buffer = self.queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(descriptor).unwrap(); + body(&mut encoder); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(command_buffer.error(), None); + } + + /// A buffer of `kind` of the pattern and a texture of `pf` and `shape` over it at offset 0; + /// `None` where the device imports no host pages. + fn over(&self, kind: Kind, pf: PixelFormat, shape: Shape) -> Option { + let (w, h) = shape.extent; + let len = (shape.rows * h) as usize; + let (buffer, len) = match kind { + Kind::Shared => { + let options = ResourceOptions::shared(); + (self.device.new_buffer(len as u64, options).unwrap(), len) + } + Kind::NoCopy | Kind::Surface => { + let len = len.next_multiple_of(host_page()); + let mapping = Mapping::anonymous(len); + let pointer = mapping.pointer(); + let release: Deallocator = Box::new(move |_, _| drop(mapping)); + let options = match kind { + Kind::Surface => ResourceOptions::from_raw(MANAGED).unwrap(), + _ => ResourceOptions::default(), + }; + // SAFETY: the mapping stays mapped until the deallocator, which owns it, runs. + match unsafe { no_copy(self.device, pointer, len, options, Some(release)) } { + Ok(buffer) => (buffer, len), + Err(error) => { + assert!(not_importable(&error), "{error:?}"); + return None; + } + } + } + }; + let bytes: Vec = (0..len).map(|i| pattern(pf, i)).collect(); + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer's own bytes, which no command uses yet. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), len) }; + buffer.did_modify_range(0..len as u64).unwrap(); + // What making the buffer announced. + counts(&self.messages.take_notices()); + let mut d = TextureDescriptor::texture_2d(pf, w, h, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let texture = match kind { + Kind::Surface => buffer + .new_texture_with_iosurface_plane(&d, IoSurfacePlane::new(0, shape.rows, false)), + _ => buffer.new_texture(&d, 0, shape.rows), + } + .unwrap(); + let shadowed = + counts(&self.messages.take_notices()).contains_key(&Degradation::ShadowedTexture); + Some(Over { + buffer, + texture, + len, + shadowed, + }) + } + + /// The buffer's bytes. + fn bytes(&self, over: &Over) -> Vec { + let contents = over.buffer.contents().unwrap(); + // SAFETY: the buffer's own bytes; no command that writes them is pending. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), over.len).to_vec() } + } + + /// Run `pass`: what it counted and announced, which [`Lane::announced`] checks once the + /// buffer's bytes are. + fn run(&self, pass: impl FnOnce()) -> Seen { + let before = self.device.work_counts().kept_bytes_passes; + pass(); + Seen { + counted: self.device.work_counts().kept_bytes_passes - before, + notices: counts(&self.messages.take_notices()), + } + } + + /// Check what a pass that rendered the texture of `over` counted and announced (`seen`): one + /// whose store keeps the buffer's bytes (`keeps`: `DontCare`, `MultisampleResolve`, `Unknown`) + /// rendered through the image the texture keeps exactly where the texture is not shadowed + /// (announced and counted once), and nothing else; one that stores it, nothing. But where the + /// device renders the texture's image only beside other linear ones + /// (`VK_NV_linear_color_attachment`'s rule) and the pass has a second attachment, the pass + /// renders it apart (`linear-attachment-copies`), through an image that copies back only what + /// the pass stores: neither announced nor counted. And where the driver stores `DONT_CARE` as + /// Metal's own `DontCare` and the pass, one render pass instance the driver runs unbroken, + /// hands it the attachment so (`whole`: no barrier, no resolve copying its texels), the + /// pass renders it in place, Metal keeping the bytes: neither announced nor counted. + fn announced(&self, case: &str, over: &Over, (keeps, whole): (bool, bool), seen: Seen) { + let Seen { counted, notices } = seen; + let apart = notices.contains_key(&Degradation::LinearAttachmentCopies); + let handed = keeps && whole && self.metals && !over.shadowed; + let kept = keeps && !over.shadowed && !apart && !handed; + let form = match (keeps, over.shadowed, apart, handed) { + (_, true, _, _) => "shadowed", + (_, false, true, _) => "apart, beside a second attachment", + (_, false, false, true) => "in place, handed to Metal's own DontCare", + (true, false, false, false) => "through the kept image", + (false, false, false, false) => "in place", + }; + eprintln!("KEPT-BYTES {case} on {}: {form}", self.device.name()); + assert_eq!(counted, u64::from(kept), "{case}: kept-bytes passes"); + assert_eq!( + notices.get(&Degradation::DontCareStandIn).copied(), + kept.then_some(1), + "{case}: {notices:?}" + ); + assert!( + !notices.contains_key(&Degradation::DontCareStore), + "{case}: {notices:?}" + ); + } +} + +/// Check `got`, a buffer's bytes after a pass over a texture of `shape` and `bpp` at offset 0, +/// against `before`, its bytes before it: texel (x, y) is `want(x, y)` (`None` for `before`'s), +/// every other byte `before`'s. +fn check( + case: &str, + got: &[u8], + before: &[u8], + (shape, bpp): (Shape, u64), + want: impl Fn(u64, u64) -> Option>, +) { + let mut expected = before.to_vec(); + let (w, h) = shape.extent; + for y in 0..h { + for x in 0..w { + if let Some(texel) = want(x, y) { + let at = (y * shape.rows + x * bpp) as usize; + expected[at..at + bpp as usize].copy_from_slice(&texel); + } + } + } + if let Some(i) = (0..got.len()).find(|&i| got[i] != expected[i]) { + let (y, column) = (i as u64 / shape.rows, i as u64 % shape.rows); + let place = match (y < h, column / bpp) { + (true, x) if x < w => format!("texel ({x}, {y})"), + _ => "between the rows".to_owned(), + }; + let changed = (0..got.len()).filter(|&i| got[i] != expected[i]).count(); + panic!( + "{case}: byte {i} ({place}) is {:#04x}, Metal's {:#04x} (the buffer's {:#04x}); \ + {changed} bytes differ", + got[i], expected[i], before[i] + ); + } +} + +/// One case: the pass over a texture of `pf` and `shape` over a buffer of `kind`, `variant` +/// before or beside it, stored `DontCare`, keeps the buffer's bytes; and where `control`, the same +/// pass stored `Store` leaves Metal's bytes (the module docs). +fn case( + lane: &mut Lane<'_>, + (pf, kind, shape): (PixelFormat, Kind, Shape), + (load, coverage, variant): (LoadAction, Coverage, Variant), + control: bool, +) { + let (w, h) = shape.extent; + let name = format!( + "{pf:?} {w}x{h} (rows of {}) over a {kind:?} buffer, {load:?} load, {coverage:?} draw, \ + {variant:?}", + shape.rows + ); + let stores = match control { + true => &[StoreAction::DontCare, StoreAction::Store][..], + false => &[StoreAction::DontCare][..], + }; + for &store in stores { + let case = format!("{name}, {store:?} store"); + let Some(over) = lane.over(kind, pf, shape) else { + eprintln!("{case}: no {kind:?} buffer on {}", lane.device.name()); + return; + }; + let format = lane.format(pf); + let (bpp, rendered, cleared) = + (format.bpp, format.rendered.clone(), format.cleared.clone()); + let (one, two) = (format.one.clone(), format.two.clone()); + let (prior, second_texel) = (format.prior.clone(), format.second.clone()); + if variant == Variant::RenderedOnce { + let before = lane.bytes(&over); + let color = Attachment { + texture: &over.texture, + load: LoadAction::Load, + store: StoreAction::Store, + }; + let first = format!("{case}: the stored render before it"); + let seen = + lane.run(|| lane.pass(&one, &color, None, Coverage::Full, (PRIOR, 0.0), |_| {})); + check(&first, &lane.bytes(&over), &before, (shape, bpp), |_, _| { + Some(prior.clone()) + }); + lane.announced(&first, &over, (false, true), seen); + } + let second = (variant == Variant::SecondAttachment).then(|| { + let mut d = TextureDescriptor::texture_2d(pf, w, h, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::shared(); + lane.device.new_texture(&d).unwrap() + }); + let before = lane.bytes(&over); + let color = Attachment { + texture: &over.texture, + load, + store, + }; + let pipeline = match second { + Some(_) => &two, + None => &one, + }; + let keeps = store == StoreAction::DontCare; + let seen = lane.run(|| { + lane.pass( + pipeline, + &color, + second.as_ref(), + coverage, + (RENDER, SECOND), + |e| { + if let Some((scope, before)) = variant.barrier() { + e.memory_barrier_with_scope(scope, RenderStages::FRAGMENT, before); + e.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + } + }, + ) + }); + let got = lane.bytes(&over); + match keeps { + true => check(&case, &got, &before, (shape, bpp), |_, _| None), + false => check(&case, &got, &before, (shape, bpp), |x, y| { + match (coverage.covers(shape.extent, x, y), load) { + (true, _) => Some(rendered.clone()), + (false, LoadAction::Clear) => Some(cleared.clone()), + (false, _) => None, + } + }), + } + let whole = variant.barrier().is_none(); + lane.announced(&case, &over, (keeps, whole), seen); + if let (Some(second), Some(_)) = (&second, coverage.corner(shape.extent)) { + let mut texel = vec![0; bpp as usize]; + second + .get_bytes(&mut texel, w * bpp, 0, Region::new_2d(0, 0, 1, 1), 0, 0) + .unwrap(); + assert_eq!( + texel, second_texel, + "{case}: the second attachment's texel (0, 0)" + ); + } + } +} + +/// Run `test` on a validated device announcing [`KEPT_BYTES`], `dont-care-store`, +/// `shadowed-texture` and `linear-attachment-copies` at each occurrence. +fn on_lane(test: impl FnOnce(&mut Lane<'_>)) { + let each = [ + Degradation::DontCareStandIn, + Degradation::DontCareStore, + Degradation::ShadowedTexture, + Degradation::LinearAttachmentCopies, + ]; + on_device_with( + |options| options.announce_each = each.into_iter().collect(), + |device, messages| { + // What the device announced as it was made. + messages.take_notices(); + test(&mut Lane::new(device, messages)); + }, + ); +} + +const LOADS: [LoadAction; 3] = [LoadAction::Load, LoadAction::Clear, LoadAction::DontCare]; + +/// The probe's 16x16 texture at tight rows (16-byte aligned); a 64x32 one at rows a multiple of +/// 256 bytes, tight but for `R8Unorm` (the rows at which RADV renders a linear image over the +/// buffer, where it shadows the others); and the probe's 1307x512 at padded rows: 5248 bytes for +/// `BGRA8Unorm`, else the texels' bytes and one more, rounded up to 64. +fn sizes(pf: PixelFormat, bpp: u64) -> [Shape; 3] { + let padded = match pf { + PixelFormat::BGRA8Unorm => 5248, + _ => (1307 * bpp + 1).next_multiple_of(64), + }; + [ + Shape { + extent: (16, 16), + rows: (16 * bpp).next_multiple_of(16), + }, + Shape { + extent: (64, 32), + rows: (64 * bpp).next_multiple_of(256), + }, + Shape { + extent: (1307, 512), + rows: padded, + }, + ] +} + +/// The sweep of one format over ordinary and no-copy buffers (the module docs), each `Load` and +/// `Clear` case controlled by `Store`. +fn sweep(pf: PixelFormat) { + on_lane(|lane| { + let bpp = FORMATS.iter().find(|f| f.0 == pf).unwrap().1; + let [tight, aligned, padded] = sizes(pf, bpp); + for kind in [Kind::Shared, Kind::NoCopy] { + for load in LOADS { + let control = load != LoadAction::DontCare; + for shape in [tight, aligned] { + for coverage in [Coverage::Full, Coverage::Half, Coverage::None] { + let at = (load, coverage, Variant::FirstUse); + case(lane, (pf, kind, shape), at, control); + } + } + for coverage in [Coverage::Half, Coverage::Corner] { + let at = (load, coverage, Variant::FirstUse); + case(lane, (pf, kind, padded), at, control); + } + if matches!(pf, PixelFormat::BGRA8Unorm | PixelFormat::RGBA16Float) { + let odd = Shape { + extent: (333, 77), + rows: (333 * bpp).next_multiple_of(16), + }; + let at = (load, Coverage::Corner, Variant::FirstUse); + case(lane, (pf, kind, odd), at, false); + } + } + } + }); +} + +/// The probe's sweep in `BGRA8Unorm` keeps the buffer's bytes (the module docs). +#[test] +fn dont_care_stores_keep_the_bytes_of_bgra8_unorm_textures_over_buffers() { + sweep(PixelFormat::BGRA8Unorm); +} + +/// The probe's sweep in `RGBA8Unorm` keeps the buffer's bytes (the module docs). +#[test] +fn dont_care_stores_keep_the_bytes_of_rgba8_unorm_textures_over_buffers() { + sweep(PixelFormat::RGBA8Unorm); +} + +/// The probe's sweep in `BGRA8Unorm_sRGB` keeps the buffer's bytes (the module docs). +#[test] +fn dont_care_stores_keep_the_bytes_of_bgra8_unorm_srgb_textures_over_buffers() { + sweep(PixelFormat::BGRA8UnormSRGB); +} + +/// The probe's sweep in `RGBA16Float` keeps the buffer's bytes (the module docs). +#[test] +fn dont_care_stores_keep_the_bytes_of_rgba16_float_textures_over_buffers() { + sweep(PixelFormat::RGBA16Float); +} + +/// The probe's sweep in `R8Unorm` keeps the buffer's bytes (the module docs). +#[test] +fn dont_care_stores_keep_the_bytes_of_r8_unorm_textures_over_buffers() { + sweep(PixelFormat::R8Unorm); +} + +/// After a pass that loads the texture, draws over it and stores it, a pass storing it +/// `DontCare` keeps the stored bytes; beside an ordinary attachment stored `Store`, which holds +/// the draw, it keeps the buffer's (the probe's `rendered-once` and `second-attachment`, in +/// `BGRA8Unorm`, `RGBA16Float` and `R8Unorm`, at 16x16, 64x32 and 1307x512). +#[test] +fn dont_care_stores_keep_the_bytes_after_a_stored_render_and_beside_a_stored_attachment() { + on_lane(|lane| { + for (pf, bpp) in [FORMATS[0], FORMATS[3], FORMATS[4]] { + let [tight, aligned, padded] = sizes(pf, bpp); + for kind in [Kind::Shared, Kind::NoCopy] { + for variant in [Variant::RenderedOnce, Variant::SecondAttachment] { + for load in LOADS { + for shape in [tight, aligned] { + let at = (load, Coverage::Full, variant); + case(lane, (pf, kind, shape), at, false); + } + } + let at = (LoadAction::Load, Coverage::Half, variant); + case( + lane, + (pf, kind, padded), + at, + variant == Variant::SecondAttachment, + ); + } + } + } + }); +} + +/// A `BGRA8Unorm` texture over a surface's plane keeps the surface's bytes, at 16x16 over rows of +/// 64 bytes, at 64x32 over rows of 256 and at 1307x512 over rows of 5248, each load action at full, +/// half and no coverage; the `Load` and `Clear` cases controlled by `Store` (the probe's IOSurface +/// cases, and the rows at which RADV renders a linear image over the surface). +#[test] +fn dont_care_stores_keep_the_bytes_of_a_surface() { + on_lane(|lane| { + let pf = PixelFormat::BGRA8Unorm; + for shape in sizes(pf, 4) { + for load in LOADS { + for coverage in [Coverage::Full, Coverage::Half, Coverage::None] { + let at = (load, coverage, Variant::FirstUse); + case( + lane, + (pf, Kind::Surface, shape), + at, + load != LoadAction::DontCare, + ); + } + } + } + }); +} + +/// A pass that draws, then draws again after a barrier, storing a texture over a buffer +/// `DontCare`, keeps the buffer's bytes as the unbroken pass does (Metal's answer, measured with +/// barriers over buffers, render targets, textures and the buffer alone: the barrier probe, the +/// M3 Max under macOS 27.0.1, 20 times alike): a barrier over buffers, which splits the pass into +/// two render pass instances, and one over the render targets, where MoltenVK restarts its Metal +/// pass. In `BGRA8Unorm` and `RGBA16Float` over ordinary and no-copy buffers, and `BGRA8Unorm` +/// over a surface's plane, at 16x16 and 64x32, each load action at full and half coverage; the +/// `Load` and `Clear` cases controlled by `Store`. +#[test] +fn dont_care_stores_keep_the_bytes_through_a_barrier() { + on_lane(|lane| { + for (pf, bpp) in [FORMATS[0], FORMATS[3]] { + let [tight, aligned, _] = sizes(pf, bpp); + let kinds: &[Kind] = match pf { + PixelFormat::BGRA8Unorm => &[Kind::Shared, Kind::NoCopy, Kind::Surface], + _ => &[Kind::Shared, Kind::NoCopy], + }; + for &kind in kinds { + for variant in [Variant::Split, Variant::Restarted] { + for load in LOADS { + for shape in [tight, aligned] { + for coverage in [Coverage::Full, Coverage::Half] { + let at = (load, coverage, variant); + let control = load != LoadAction::DontCare; + case(lane, (pf, kind, shape), at, control); + } + } + } + } + } + } + }); +} + +/// The store actions that store nothing of a texture over a buffer keep its bytes, and those +/// that store it store the draw (the module docs): `Unknown` at the pass's end, set to `DontCare` +/// or `Store` as it ends; a single-sampled `MultisampleResolve` into an ordinary texture, which +/// holds the draw, and `StoreAndMultisampleResolve`. And one 2048x2048 pass keeps the bytes. +#[test] +fn store_actions_that_store_nothing_keep_the_bytes() { + on_lane(|lane| { + let (pf, bpp) = FORMATS[0]; + let format = lane.format(pf); + let (one, rendered) = (format.one.clone(), format.rendered.clone()); + let [tight, aligned, _] = sizes(pf, bpp); + let cases = [Kind::Shared, Kind::NoCopy].map(|kind| [(kind, tight), (kind, aligned)]); + for (kind, shape) in cases.into_iter().flatten() { + let (w, h) = shape.extent; + for (what, store, late) in [ + ("Unknown", StoreAction::Unknown, None), + ( + "Unknown, then DontCare", + StoreAction::Unknown, + Some(StoreAction::DontCare), + ), + ( + "Unknown, then Store", + StoreAction::Unknown, + Some(StoreAction::Store), + ), + ] { + let case = format!("{pf:?} over a {kind:?} buffer, {what}"); + let Some(over) = lane.over(kind, pf, shape) else { + eprintln!("{case}: no {kind:?} buffer on {}", lane.device.name()); + continue; + }; + let before = lane.bytes(&over); + let color = Attachment { + texture: &over.texture, + load: LoadAction::Clear, + store, + }; + let stored = late == Some(StoreAction::Store); + let seen = lane.run(|| { + lane.pass(&one, &color, None, Coverage::Half, (RENDER, 0.0), |e| { + if let Some(late) = late { + e.set_color_store_action(late, 0).unwrap(); + } + }) + }); + let cleared = lane.format(pf).cleared.clone(); + check( + &case, + &lane.bytes(&over), + &before, + (shape, bpp), + |x, _| match (stored, x < w / 2) { + (false, _) => None, + (true, true) => Some(rendered.clone()), + (true, false) => Some(cleared.clone()), + }, + ); + lane.announced(&case, &over, (!stored, true), seen); + } + for store in [ + StoreAction::MultisampleResolve, + StoreAction::StoreAndMultisampleResolve, + ] { + let case = format!("{pf:?} over a {kind:?} buffer, {store:?}"); + let Some(over) = lane.over(kind, pf, shape) else { + continue; + }; + let mut d = TextureDescriptor::texture_2d(pf, w, h, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::shared(); + let resolve = lane.device.new_texture(&d).unwrap(); + let before = lane.bytes(&over); + let mut descriptor = RenderPassDescriptor::new(); + let target = &mut descriptor.color_attachments[0]; + target.texture = Some(over.texture.clone()); + target.load_action = LoadAction::Clear; + target.store_action = store; + target.clear_color = ClearColor::new(CLEAR, CLEAR, CLEAR, CLEAR); + target.resolve_texture = Some(resolve.clone()); + let resolves_alone = store == StoreAction::MultisampleResolve; + let seen = lane.run(|| { + lane.encode(&descriptor, |e| { + e.set_render_pipeline_state(&one).unwrap(); + e.set_vertex_bytes(&floats(&[-1.0, 1.0, 1.0, -1.0]), 0) + .unwrap(); + e.set_fragment_bytes(&floats(&[RENDER; 8]), 0).unwrap(); + e.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + }) + }); + check(&case, &lane.bytes(&over), &before, (shape, bpp), |_, _| { + (!resolves_alone).then(|| rendered.clone()) + }); + // The resolve copies the attachment's texels, so the pass stores them. + lane.announced(&case, &over, (resolves_alone, false), seen); + let mut texels = vec![0; (w * h * bpp) as usize]; + resolve + .get_bytes(&mut texels, w * bpp, 0, Region::new_2d(0, 0, w, h), 0, 0) + .unwrap(); + assert!( + texels.chunks(bpp as usize).all(|texel| texel == rendered), + "{case}: the resolve texture holds the draw" + ); + } + } + let big = Shape { + extent: (2048, 2048), + rows: 2048 * bpp, + }; + let at = (LoadAction::Load, Coverage::Half, Variant::FirstUse); + case(lane, (pf, Kind::Shared, big), at, false); + }); +} + +/// A `BGRA8Unorm` 64x32 texture over a no-copy buffer of memfd pages, rows 256 bytes apart (an +/// image over a dma-buf of its own pages on RADV, which imports them so; the pointer elsewhere), +/// keeps the pages' bytes through a pass that clears it, draws over half of it and stores it +/// `DontCare`, and a `Store` control stores the draw and the clear. Skipped where +/// `/dev/udmabuf` cannot be opened. +#[cfg(target_os = "linux")] +#[test] +fn dont_care_stores_keep_the_bytes_of_dma_buf_pages() { + const TEST: &str = "dma-buf pages"; + if !udmabuf_openable(TEST) { + return; + } + on_lane(|lane| { + let (pf, bpp) = FORMATS[0]; + let shape = Shape { + extent: (64, 32), + rows: 256, + }; + let (w, h) = shape.extent; + let len = (shape.rows * h) as usize; + let format = lane.format(pf); + let (one, rendered, cleared) = ( + format.one.clone(), + format.rendered.clone(), + format.cleared.clone(), + ); + for store in [StoreAction::DontCare, StoreAction::Store] { + let case = format!("{TEST}, {store:?} store"); + let ram = Memfd::new(len); + let pages = ram.view(&[(0, len)]); + let before: Vec = (0..len).map(|i| pattern(pf, i)).collect(); + ram.whole.write(0, &before); + let calls = Calls::default(); + let source = ram.source(&pages, &calls); + let buffer = + super::dma_buf_imports::no_copy(lane.device, &pages, 0, len, source).unwrap(); + counts(&lane.messages.take_notices()); + let mut d = TextureDescriptor::texture_2d(pf, w, h, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&d, 0, shape.rows).unwrap(); + let shadowed = + counts(&lane.messages.take_notices()).contains_key(&Degradation::ShadowedTexture); + let over = Over { + buffer, + texture, + len, + shadowed, + }; + let color = Attachment { + texture: &over.texture, + load: LoadAction::Clear, + store, + }; + let keeps = store == StoreAction::DontCare; + let seen = + lane.run(|| lane.pass(&one, &color, None, Coverage::Half, (RENDER, 0.0), |_| {})); + let got = ram.whole.read(0..len); + check(&case, &got, &before, (shape, bpp), |x, _| { + match (keeps, x < w / 2) { + (true, _) => None, + (false, true) => Some(rendered.clone()), + (false, false) => Some(cleared.clone()), + } + }); + lane.announced(&case, &over, (keeps, true), seen); + drop(over); + eprintln!("{case}: the source's calls {:?}", calls.lock().unwrap()); + } + }); +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 9f9cbc06c..76af84fa9 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 399; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1184; +pub const RUNTIME_VERSION: u32 = 1185; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/docs/API.md b/docs/API.md index da7982e72..3f9f9f4b2 100644 --- a/docs/API.md +++ b/docs/API.md @@ -984,9 +984,17 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. answer confirms at this count. - `metal2vulkan-degrade-dont-care-store` (precision). `DontCareStore`: An attachment stored with `DontCare` (or the multisampled attachment of `MultisampleResolve`) is Vulkan's `DONT_CARE`, where - Apple's GPU keeps the earlier texels unless its tiler overflows. Cost: the attachment's texels - after the pass are each its earlier texel or the one the pass rendered, both Metal's answers, but - not always the one Metal's tiler keeps. + Apple's GPU keeps the earlier texels unless its tiler overflows. Not a texture over a buffer: Metal + leaves the buffer's bytes in it (on an M3 Max, every texel of 926 such passes alike, and of 36 + with a memory barrier between two draws, 20 times each, but that the first pass in a process to + overflow Apple's tiler leaves the rendered texels, which no call can predict or detect), and the + runtime gives the buffer's bytes, exactly, through an image the pass copies nothing back from + (`dont-care-stand-in` below, or the texture's shadow), or by handing the attachment to Metal's + own `DontCare` where the driver stores it so; only where the pass cannot (a draw took a view of + the texture's own image before its store action was known, the pass executes render commands, + or the device copies no image of the format) does the pass render in place, announced so. Cost: + the attachment's texels after the pass are each its earlier texel or the one the pass rendered, + both Metal's answers, but not always the one Metal's tiler keeps. - `metal2vulkan-degrade-dont-care-load-tiles` (precision). `DontCareLoadTiles`: An attachment loaded with `DontCare` and stored, in a pass that draws, is cleared before the draws to zero (a color) or its clear value (depth, stencil) over the render area and the tiles past it a clear reaches, where @@ -1504,6 +1512,17 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. place: it clears an image its texture keeps and copies it back after, as clearing a linear image of host memory in place measured slower than that copy. Cost: the pass clears an image of the device's and copies it back after, as clearing the texture's linear image in place costs more. +- `metal2vulkan-degrade-dont-care-stand-in` (performance). `DontCareStandIn`: A pass renders a color + attachment that it stores with `DontCare` (or resolves alone, `MultisampleResolve`) and whose + texture's image lies over the buffer the texture lies in (a linear image over an ordinary buffer's + memory, a no-copy buffer's host pages, a dma-buf's, a surface's; on MoltenVK, a Metal texture over + a no-copy or surface buffer's `MTLBuffer`) through an image its texture keeps, so that the buffer + keeps its bytes, as Metal's does: rendered in place, the pass would write them. A pass that stores + the attachment renders it in place, at no cost; so does one that hands it to a driver that stores + `DONT_CARE` as Metal's own `DontCare` (MoltenVK on the M3 Max and the M4), as one render pass + instance the driver runs unbroken, where Metal keeps the bytes itself. Cost: an image of the + attachment's size, which its texture keeps for the queue, renders the pass; a `Load` copies the + buffer's texels over the render area into it before the pass, and nothing is copied back. - `metal2vulkan-degrade-host-deallocator-delayed` (precision). `HostDeallocatorDelayed`: A no-copy buffer or heap released with a deallocator and no keep-alive (`KeepAlive`) while the device's import of its pages is still held: a command buffer submitted before a texture over them was @@ -2041,6 +2060,16 @@ each item named states the rule in full. - **A blit copy of 24-bit depth between textures of different formats is refused**: Apple's reference GPUs make no `Depth24Unorm_Stencil8` texture, so there is no Metal answer to match. +**Render passes** + +- **A texture over a buffer that a pass stores `DontCare` keeps the buffer's bytes**, in every + texel, with or without memory barriers between the pass's draws: Metal's answer, but that the + first pass in a process to overflow Apple's tiler (some 2 to 4 million triangle-tile entries) + leaves the rendered texels in every texel, which no call can predict or detect. The runtime does + not model the overflow, but where it hands the attachment to Metal's own `DontCare` (MoltenVK), + which decides it. A pass that renders such a texture in place otherwise announces + `dont-care-store`. + **Heaps and memory** - **A heap's size and alignment answers are the device's own** diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index d3f18807c..5023e2ada 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -104,6 +104,17 @@ driver's. Each is open work. copied at each use (`shadowed-texture-view`): about 50 to 95 µs a command buffer for a 64x64 texture, measured on the M3 Max and M4 (MoltenVK) and the Radeon 780M. Making the texture with `PixelFormatView` usage avoids it. +- **A pass that loads a texture over a buffer and does not store it** renders through an image its + texture keeps, the buffer's texels copied into it first (`dont-care-stand-in`), so that the + buffer keeps its bytes as Metal's does. In the frame-cost benchmark's window server frame (67 + passes, 50 of them over a 512x512 `BGRA8Unorm_sRGB` layer that is a texture over a `Shared` + buffer), loading the layer and storing it `DontCare` takes about 0.5 ms more of the encoding + thread a frame and 0.6 ms more through the GPU's completion than rendering it in place on the + Iris Xe (ANV), some 10 µs a pass each; on a busy Radeon 780M (RADV) a pass's end takes 8 to 18 + µs more. A pass that clears the layer and stores it `DontCare` costs no more (on ANV, 1.1 ms of + the encoding thread and 2.7 ms through completion less a frame, as nothing is copied back), and + one that stores it renders in place at no added cost. Where MoltenVK runs the pass as one + unbroken instance, Metal keeps the bytes at no cost. - **A cold pipeline making on NVIDIA grows with a module's sampling sites.** NVIDIA's compiler (615.71.09) takes about 1 s for macOS 26's largest CoreAnimation fragment (210,033 words) on the RTX 5080 Laptop GPU, made once per cold cache (the first boot, and after an update changes the