diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index c5b6ea526..ef13fdbb6 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -355,7 +355,8 @@ the record the pass is making. (`HostPageTexturePolicy::InPlace`) a texture there that samples, reads, renders into it or is written through a shader (of texels of 4, 8 or 16 bytes) is an image in place wherever the device makes it and its own check showed those operations keeping every byte for that kind of - pages, on a discrete GPU as on any other (run once per driver and release on a thread of its + pages (but the rows' padding of a texture over a buffer a kernel writes, which an x86 Mac's GPU + may change too: docs/API.md, section 10), on a discrete GPU as on any other (run once per driver and release on a thread of its own, kept in the shader cache). The runtime keeps a copy and announces it (`shadowed-texture`, naming why) for every other texture there (under `HostPageTexturePolicy::Shadow`, one a shader writes of 1- or 2-byte texels, one made before the check answered or whose check did not diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index d1107ae01..d3d7d79d8 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -185,12 +185,14 @@ pub(super) struct HostCell { /// An image in place over a buffer's host pages ([`HostCell`], `texture/in_place_image.rs`), /// which a rebind makes again over the new pages: the image (`texture.rs`'s `Image`), held weakly /// and by type erased as [`NotedTexture`] holds it, where its texels lie in bytes from the pages' -/// first byte, and how Metal lays them out from there. +/// first byte, how Metal lays them out from there, and whether their rows' padding is the +/// buffer's own (`in_place::Padding`). #[derive(Clone)] pub(super) struct InPlaceWatch { pub(super) image: Weak, pub(super) from_base: u64, pub(super) layout: crate::linear_plan::BufferLayout, + pub(super) padding_owned: bool, } impl InPlaceWatch { diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index f0d0e2e3e..536ba4d62 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -56,7 +56,7 @@ use super::degradation::Degradation; use super::device::lock; use super::error::{internal, invalid, nil, vulkan, Error, Problem, RuntimeGap}; use super::exit_guard; -use super::in_place::RowEnds; +use super::in_place::{Padding, RowEnds}; use super::key_hash::KeyMap; use super::linear_plan::{ apart_from_plane, is_linear, plan_buffer_texture, plane_rows_share_bytes, BufferFacts, @@ -1541,6 +1541,31 @@ impl Texels { } } + /// Whether a shader's writes may change the texels' rows' padding, in the device's lines of + /// memory of `line` bytes (`in_place::Padding::of`): rows over a buffer's bytes the CPU + /// addresses, no IOSurface plane's ([`Texels::padding_owned`]), whose rows, each to its + /// pitch, share no line with bytes past them. + pub(super) fn padding(&self, line: u64) -> Padding { + match self.buffer.contents() { + Some(at) => { + let start = at.as_ptr().addr() as u64; + Padding::of(start, &self.layout, line, self.padding_owned()) + } + None => Padding::Kept, + } + } + + /// Whether the texels' rows' padding is their buffer's own (`in_place::Padding`): they lie + /// over a buffer's rows, no IOSurface plane's, and the buffer holds their last row to its + /// pitch. + pub(super) fn padding_owned(&self) -> bool { + let to_pitch = BufferLayout { + row_bytes: self.layout.row_pitch, + ..self.layout + }; + !self.surface && to_pitch.end() <= self.buffer.length() + } + /// The texture's resource options (the `options` field), its hazard tracking mode resolved. pub(super) fn options(&self) -> ResourceOptions { self.options diff --git a/crates/metal2vulkan-runtime/src/in_place.rs b/crates/metal2vulkan-runtime/src/in_place.rs index b4f2c7ce5..9117ff225 100644 --- a/crates/metal2vulkan-runtime/src/in_place.rs +++ b/crates/metal2vulkan-runtime/src/in_place.rs @@ -48,11 +48,16 @@ //! the texels' address, offset and pitches), for each access the texture's declared usage (as //! Metal reports it, an `Unknown` one every usage) takes ([`Access::takes`]): it renders (`RenderTarget`), a shader //! writes it (`ShaderWrite` or `ShaderAtomic`, of texels of 4, 8 or 16 bytes, the widths the -//! check's kernel stores: [`STORED_TEXEL_BYTES`]), or it is sampled or read alone. Plain Metal -//! also writes through a texture beyond its declared usage, and renders into one made without -//! `RenderTarget`: such a write binds the texture's usage shadow (`texture/usage_shadow.rs`), and -//! such a pass renders through an attachment stand-in (`attachment_stand_in.rs`), since the -//! image has neither storage nor attachment usage; the copies of both touch texels alone. +//! check's kernel stores: [`STORED_TEXEL_BYTES`]), or it is sampled or read alone. Of a texture +//! a shader writes over a buffer's rows whose padding is free ([`Padding`]: real Macs' GPUs +//! disagree on those bytes under a kernel's writes, and the owner's ruling of 2026-11-07 takes +//! the x86 Macs' envelope), the check of writes is the one that lets a byte of the rows' +//! padding change ([`Access::BufferWrites`]); renders, and an IOSurface plane's rows, keep +//! every byte. Plain Metal also writes through a texture beyond its declared usage, and renders +//! into one made without `RenderTarget`: such a write binds the texture's usage shadow +//! (`texture/usage_shadow.rs`), and such a pass renders through an attachment stand-in +//! (`attachment_stand_in.rs`), since the image has neither storage nor attachment usage; the +//! copies of both touch texels alone. //! Elsewhere the texture is a shadow (`shadow.rs`), its notice naming why ([`ShadowCause`]) and //! counted by cause (`WorkCounts::host_texture_shadows_*`, and those that render apart). //! - **Before the verdict.** A texture made before its class's verdict for its access is known @@ -142,6 +147,12 @@ pub(crate) enum Access { /// Its usage writes it through a shader (`ShaderWrite` or `ShaderAtomic`, whatever else it /// holds): its image takes its first move and kernels' storage writes of its texels. Writes, + /// As [`Writes`](Self::Writes), of a texture whose rows' padding is free ([`Padding::Free`]): + /// its rounds are those of [`Writes`](Self::Writes), but a byte of its rows' padding (each + /// row's bytes after its last texel to its pitch, the last row's included) may change. A + /// usage never takes it alone: [`in_place`] asks it in the stead of + /// [`Writes`](Self::Writes) for such a texture. + BufferWrites, } /// The bytes of the texels a texture a shader writes may have to be in place: those the check's @@ -150,11 +161,17 @@ pub(crate) const STORED_TEXEL_BYTES: [u64; 3] = [4, 8, 16]; impl Access { /// Every access, in the order the check runs them and the record holds their verdicts. - pub(crate) const ALL: [Access; 3] = [Access::Reads, Access::Renders, Access::Writes]; + pub(crate) const ALL: [Access; 4] = [ + Access::Reads, + Access::Renders, + Access::Writes, + Access::BufferWrites, + ]; /// Whether a texture of Metal `usage` (as Metal reports it) takes this access: one that /// renders, one a shader writes (both, where it does both), or one that only samples or - /// reads. Each of its accesses' checks covers its first move. + /// reads. Each of its accesses' checks covers its first move. None takes + /// [`BufferWrites`](Self::BufferWrites) alone ([`in_place`]). pub(crate) fn takes(self, usage: TextureUsage) -> bool { let renders = usage.contains(TextureUsage::RENDER_TARGET); let writes = usage.intersects(TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC); @@ -162,6 +179,19 @@ impl Access { Access::Reads => !renders && !writes, Access::Renders => renders, Access::Writes => writes, + Access::BufferWrites => false, + } + } + + /// The accesses the check's rounds of this one give verdicts of, in [`ALL`](Self::ALL)'s + /// order: its own, and of [`Writes`](Self::Writes) those of + /// [`BufferWrites`](Self::BufferWrites) too, which has no rounds of its own. + pub(crate) fn answered(self) -> &'static [Access] { + match self { + Access::Reads => &[Access::Reads], + Access::Renders => &[Access::Renders], + Access::Writes => &[Access::Writes, Access::BufferWrites], + Access::BufferWrites => &[], } } @@ -171,6 +201,7 @@ impl Access { Access::Reads => 0, Access::Renders => 1, Access::Writes => 2, + Access::BufferWrites => 3, } } @@ -186,6 +217,10 @@ impl Access { "the first move and a kernel's storage writes of the texels of an image a shader \ writes" } + Access::BufferWrites => { + "the first move and a kernel's storage writes of the texels of an image a shader \ + writes over a buffer's rows, beside their padding" + } } } } @@ -252,6 +287,49 @@ impl RowEnds { } } +/// Whether a shader's writes of a texture's texels may change its rows' padding: each row's bytes +/// after its last texel to its pitch, the last row's included (the bytes between slices are no +/// row's). Metal leaves them to its GPU under a kernel's writes of a texture over a buffer: an +/// Intel UHD Graphics 630 (macOS 26.7.1) wrote back older values over the CPU's writes to them, +/// the last row's included, under such writes, where an M3 Max (macOS 27.0.1) and a Radeon Pro +/// 5300M kept them (`crates/metal2vulkan-conformance/probes/row_padding_writes.m`); every GPU +/// kept them under its draws, clears and stores, and an IOSurface plane's under kernels too. The +/// rule follows the x86 Macs' envelope: what one of them does to those bytes, a texture over a +/// buffer may do ([`Access::BufferWrites`]; docs/API.md, section 10, **Kernels**). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Padding { + /// Its rows' padding is kept, as every byte beside its texels is: an IOSurface plane's rows, + /// a texture whose buffer ends before its last row's pitch, or one whose texels and padding + /// share a line of the device's memory with bytes past them ([`Padding::of`]). + Kept, + /// A texture over a buffer's rows, its buffer holding its last row to its pitch, whose + /// texels and padding share no line with bytes past them: a shader's writes may change its + /// padding. + Free, +} + +impl Padding { + /// The padding of texels laid out as `layout` in a buffer whose first byte lies `start` + /// bytes past a multiple of `line` ([`RowEnds::of`]), where `owned` (they lie over a + /// buffer's rows, no IOSurface plane's, and the buffer holds their last row to its pitch): + /// free where the rows, each to its pitch, share no line with bytes past them. + pub(crate) fn of( + start: u64, + layout: &crate::linear_plan::BufferLayout, + line: u64, + owned: bool, + ) -> Padding { + let padded = crate::linear_plan::BufferLayout { + row_bytes: layout.row_pitch, + ..*layout + }; + match owned && RowEnds::of(start, &padded, line) == RowEnds::OnLines { + true => Padding::Free, + false => Padding::Kept, + } + } +} + /// The verdicts a device's check gives: one for each class, access and row ends, those of /// [`RowEnds::InLines`] first, then those of [`RowEnds::OnLines`], each class by class /// ([`PagesClass::ALL`]), each class's accesses in [`Access::ALL`]'s order. @@ -307,6 +385,7 @@ impl Verdict { pub(crate) struct PendingMove { pub(crate) class: PagesClass, pub(crate) rows: RowEnds, + pub(crate) padding: Padding, pub(crate) usage: TextureUsage, pub(crate) plan: crate::image_plan::ImagePlan, pub(crate) descriptor: crate::texture_descriptor::TextureDescriptor, @@ -424,15 +503,18 @@ impl ShadowCause { } /// Whether a texture over host pages of `class`, its texels lying in the device's lines as `rows` -/// says, of Metal `usage` (as Metal reports it) and texels of `texel` bytes, on a device of -/// `policy`, is tried as an image in place; else why it is a shadow (the module docs). `verdict` -/// answers the device's check for the class, each access the texture takes ([`Access::takes`]), -/// in [`Access::ALL`]'s order, and the row ends, asked only of a texture the policy and texel -/// width let through (a pending one starts the check), until one did not pass. +/// says, its rows' padding as `padding` says, of Metal `usage` (as Metal reports it) and texels +/// of `texel` bytes, on a device of `policy`, is tried as an image in place; else why it is a +/// shadow (the module docs). `verdict` answers the device's check for the class, each access the +/// texture takes ([`Access::takes`]), in [`Access::ALL`]'s order, and the row ends, asked only of +/// a texture the policy and texel width let through (a pending one starts the check), until one +/// did not pass: for a shader's writes of a texture whose padding is free, the verdict of +/// [`Access::BufferWrites`], which passes wherever that of [`Access::Writes`] does (the same +/// rounds give both, and it lets more change). pub(crate) fn in_place( policy: HostPageTexturePolicy, usage: TextureUsage, - (class, rows, texel): (PagesClass, RowEnds, u64), + (class, rows, texel, padding): (PagesClass, RowEnds, u64, Padding), mut verdict: impl FnMut(PagesClass, Access, RowEnds) -> Verdict, ) -> Result<(), ShadowCause> { if policy == HostPageTexturePolicy::Shadow { @@ -442,6 +524,10 @@ pub(crate) fn in_place( return Err(ShadowCause::StoreWidth(texel)); } for access in Access::ALL.into_iter().filter(|access| access.takes(usage)) { + let access = match (access, padding) { + (Access::Writes, Padding::Free) => Access::BufferWrites, + (access, _) => access, + }; match verdict(class, access, rows) { Verdict::Passed => {} Verdict::Pending => return Err(ShadowCause::CheckPending(class, access, rows)), @@ -591,7 +677,7 @@ impl Drop for Waiting<'_> { /// differs, and so does the version it holds). The runtime's own version is not in the record: a /// release that changes none of these keeps the verdicts the driver gave, so a device made after /// it reads them again rather than checking anew. -pub(crate) const CHECK_VERSION: u32 = 6; +pub(crate) const CHECK_VERSION: u32 = 7; /// A record's first bytes. const MAGIC: [u8; 8] = *b"M2VINPL\0"; @@ -668,7 +754,7 @@ pub(crate) fn record_name(identity: &DriverIdentity) -> String { /// magic 8 bytes "M2VINPL\0" /// version u32 CHECK_VERSION /// identity 32 bytes DriverIdentity::digest -/// verdicts 18 bytes one per class, access and row ends, VERDICTS' order (verdict_index) +/// verdicts 24 bytes one per class, access and row ends, VERDICTS' order (verdict_index) /// checksum 32 bytes SHA-256 of every byte before it /// ``` /// @@ -863,11 +949,14 @@ impl Device { /// The device's check's verdicts now, one line per class for a texture that reads /// (`Pointer: Passed`), then one per class for one that renders (`Pointer renders: Passed`), - /// then one per class for one a shader writes (`Pointer writes: Passed`), each for texels that - /// share a line with bytes beside them (`RowEnds::InLines`); then the same nine for texels - /// that share none (`Pointer, rows on lines: Passed`, `Pointer renders, rows on lines: - /// Passed`, `Pointer writes, rows on lines: Passed`); and what it found changed where one - /// failed. A runtime extension for the lanes that report it. + /// then one per class for one a shader writes (`Pointer writes: Passed`), then one per class + /// for one a shader writes over a buffer's rows whose padding may change (`Pointer buffer + /// writes: Passed`, `in_place::Padding`), each for texels that share a line with bytes beside + /// them (`RowEnds::InLines`); then the same twelve for texels that share none (`Pointer, rows + /// on lines: Passed`, `Pointer renders, rows on lines: Passed`, `Pointer writes, rows on + /// lines: Passed`, `Pointer buffer writes, rows on lines: Passed`); and what it found changed + /// where one failed (or where only a row's padding changed). A runtime extension for the + /// lanes that report it. #[doc(hidden)] pub fn in_place_check_report(&self) -> Vec { self.current().in_place_check_report_now() @@ -886,6 +975,7 @@ impl Device { Access::Reads => format!("{class:?}{lines}: {verdict:?}"), Access::Renders => format!("{class:?} renders{lines}: {verdict:?}"), Access::Writes => format!("{class:?} writes{lines}: {verdict:?}"), + Access::BufferWrites => format!("{class:?} buffer writes{lines}: {verdict:?}"), } }; let line = &line; diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index 3fe01fa46..d4e31243b 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -52,7 +52,14 @@ //! a driver's write of a block wider than a texel past a row's or the image's end shows, or one //! after another, and 1920x1080 at 4 bytes) [`ROUNDS`] times. Its rounds are stores: a program's //! atomics on such a texture are kernels' storage writes of its texels too, but none is among -//! the rounds. +//! the rounds. The same rounds give the verdicts of a shader's writes of a texture over a +//! buffer's rows whose padding is free ([`Access::BufferWrites`], `in_place::Padding`): a round +//! whose texels all read the kernel's bytes, and every byte but of its rows' padding (after a +//! row's last texel, before its pitch, the last row's included) the CPU's or the pattern, where +//! the shape's padding is free ([`Shape::padding`]), fails the one and keeps the other +//! ([`Round::Padded`]): its writer writes on past such a byte, and the rounds go on through +//! every shape for those verdicts. No round of its own runs for them, so the check takes no +//! longer than on a device whose every round kept every byte. //! - **Its buffers' addresses** lie outside the Metal address space (`AddressPlacement::Outside`, //! `address.rs`), each made as the product makes its class's otherwise: the check runs while //! the program makes its resources, so a range of the space it took would refuse a pin of the @@ -123,7 +130,9 @@ use crate::check_draw::CheckDraw; use crate::device::holds::Holder; use crate::exit_guard; use crate::host_memory::HostMemory; -use crate::in_place::{encode, mark_checking, record_name, Access, PagesClass, RowEnds, Verdict}; +use crate::in_place::{ + encode, mark_checking, record_name, Access, Padding, PagesClass, RowEnds, Verdict, +}; use crate::linear_plan::BufferLayout; use crate::values::ResourceOptions; use crate::{ @@ -279,18 +288,35 @@ impl Shape { && offset % self.bytes_per_row < self.width * self.texel } - /// How its texels lie in lines of `line` bytes ([`RowEnds::of`]): its texture starts the - /// window, which starts on a page. - pub(crate) fn rows(&self, line: u64) -> RowEnds { - let layout = BufferLayout { + /// Whether the window's byte at `offset` is one of its rows' padding: after a row's last + /// texel, before its pitch (the last row's included). + fn in_padding(&self, offset: u64) -> bool { + offset < self.bytes_per_row * self.height + && offset % self.bytes_per_row >= self.width * self.texel + } + + /// Its texels' layout in the window, which its texture starts. + fn layout(&self) -> BufferLayout { + BufferLayout { offset: 0, row_pitch: self.bytes_per_row, slice_pitch: self.bytes_per_row * self.height, row_bytes: self.width * self.texel, rows: self.height, slices: 1, - }; - RowEnds::of(0, &layout, line) + } + } + + /// How its texels lie in lines of `line` bytes ([`RowEnds::of`]): its texture starts the + /// window, which starts on a page. + pub(crate) fn rows(&self, line: u64) -> RowEnds { + RowEnds::of(0, &self.layout(), line) + } + + /// Whether its rows' padding is free in lines of `line` bytes ([`Padding::of`]): its texture + /// lies over a buffer's rows, whose window holds them to their pitch. + pub(crate) fn padding(&self, line: u64) -> Padding { + Padding::of(0, &self.layout(), line, true) } /// Whether a class's rounds take it, in lines of `line` bytes, after shapes whose texels share @@ -365,17 +391,24 @@ fn run(weak: crate::device::WeakDevice) { let mut stopped = false; for class in PagesClass::ALL { for access in Access::ALL { + // The accesses this one's rounds answer: none of an access with no rounds of its own. + let answered = access.answered(); + if answered.is_empty() { + continue; + } let Some(device) = weak.hold() else { return; }; let checks = &device.shared().in_place; - let pending = |rows| checks.verdict(class, access, rows) == Verdict::Pending; - if !RowEnds::ALL.into_iter().any(pending) { + let pending = |(access, rows)| checks.verdict(class, access, rows) == Verdict::Pending; + let each = + || (answered.iter()).flat_map(|&access| RowEnds::ALL.map(|rows| (access, rows))); + if !each().any(pending) { continue; } if stopped || word_overwritten(&device) { stopped = true; - for rows in RowEnds::ALL { + for (access, rows) in each() { checks.set(class, access, rows, Verdict::Unchecked); } continue; @@ -384,10 +417,12 @@ fn run(weak: crate::device::WeakDevice) { // The process is exiting, or the program let the device go: nothing is kept. return; }; - for rows in RowEnds::ALL { - let verdict = verdicts[rows.index()]; - checks.set(class, access, rows, verdict); - device.shared().counts.in_place_check_ran(verdict); + for (&access, verdicts) in answered.iter().zip(verdicts) { + for rows in RowEnds::ALL { + let verdict = verdicts[rows.index()]; + checks.set(class, access, rows, verdict); + device.shared().counts.in_place_check_ran(verdict); + } } // Shadows made before their verdicts that know them now may move in place. device.in_place_verdicts_given(); @@ -427,23 +462,27 @@ fn word_overwritten(device: &Device) -> bool { unsafe { device.shared().loader_word.overwritten() } } -/// The verdicts of `class` for `access` on `device`, by row ends ([`RowEnds::ALL`]'s order): -/// every shape's rounds, those of shapes whose texels share no line with bytes beside them first -/// ([`Shape::rows`]), until one fails, or until the device's loader word is found overwritten -/// (unchecked then where no round ran); [`verdicts`] gives them. `None` where the process is -/// exiting, or the program's last drop stopped the device's holds before a round +/// The verdicts of `class` on `device` for each access `access`'s rounds answer +/// ([`Access::answered`]), in that order, each by row ends ([`RowEnds::ALL`]'s order): every +/// shape's rounds, those of shapes whose texels share no line with bytes beside them first +/// ([`Shape::rows`]), until one changes a byte, or until the device's loader word is found +/// overwritten (unchecked then where no round ran); [`Tally::verdicts`] gives them. A round of +/// storage writes that changed no byte but of its shape's rows' padding, where that padding is +/// free ([`Shape::padding`]), fails [`Access::Writes`] for its row ends and counts for +/// [`Access::BufferWrites`] as a round that kept every byte, and the rounds go on. `None` where +/// the process is exiting, or the program's last drop stopped the device's holds before a round /// (`device/holds.rs`). -fn check_class(device: &Device, class: PagesClass, access: Access) -> Option<[Verdict; 2]> { +fn check_class(device: &Device, class: PagesClass, access: Access) -> Option> { let page = host_page(); let line = device.shared().in_place.line(); - let unchecked = [Verdict::Unchecked; 2]; + let unchecked = || vec![[Verdict::Unchecked; 2]; access.answered().len()]; let Some(pages) = ClassPages::make(device, class, BUFFER_BYTES) else { - return Some(unchecked); + return Some(unchecked()); }; // The command queue an image that renders takes its passes on, the check's own, and the // draw it takes after them. let mut renders = match access { - Access::Reads | Access::Writes => None, + Access::Reads | Access::Writes | Access::BufferWrites => None, Access::Renders => { let made = exit_guard::enter().map(|_busy| { let queue = device.new_command_queue_now()?; @@ -451,20 +490,21 @@ fn check_class(device: &Device, class: PagesClass, access: Access) -> Option<[Ve }); match made? { Ok(renders) => Some(renders), - Err(_) => return Some(unchecked), + Err(_) => return Some(unchecked()), } } }; // An image a shader writes takes the shapes its kernel stores, each with its view; those // whose texels share no line with bytes beside them first. let mut shapes: Vec<(Shape, Option)> = match access { - Access::Writes => STORE_SHAPES + Access::Writes | Access::BufferWrites => STORE_SHAPES .map(|(shape, texel)| (shape, Some(texel))) .to_vec(), Access::Reads | Access::Renders => SHAPES.map(|shape| (shape, None)).to_vec(), }; shapes.sort_by_key(|(shape, _)| shape.rows(line) != RowEnds::OnLines); - let mut made = [0; 2]; + let forced = device.shared().in_place.forced_failure(); + let mut tally = Tally::default(); // The texel sizes of the shapes whose texels share a line made so far (`Shape::runs`). let mut made_sharing = Vec::new(); for (shape, texel) in shapes { @@ -472,62 +512,127 @@ fn check_class(device: &Device, class: PagesClass, access: Access) -> Option<[Ve continue; } let rows = shape.rows(line); + // A round of storage writes over a shape whose rows' padding is free tells a change + // there apart. + let free = texel.is_some() && shape.padding(line) == Padding::Free; for round in 0..ROUNDS { if !device.holds_go_on(Holder::InPlaceCheck) { return None; } step_aside(device); if word_overwritten(device) { - return Some(unchecked); + return Some(unchecked()); } let outcome = { let _busy = exit_guard::enter()?; match texel { - Some(texel) => store_round(device, &pages, (shape, texel), round, page), + Some(texel) => store_round(device, &pages, (shape, texel, free), round, page), None => check_round(&pages, shape, round, page, renders.as_mut()), } }; - match outcome { + let made = |made_sharing: &mut Vec| { + if rows == RowEnds::InLines && !made_sharing.contains(&shape.texel) { + made_sharing.push(shape.texel); + } + }; + let ((offset, due, read), padding) = match outcome { Round::Kept => { - made[rows.index()] += 1; - if rows == RowEnds::InLines && !made_sharing.contains(&shape.texel) { - made_sharing.push(shape.texel); - } + tally.kept(rows, false); + made(&mut made_sharing); + continue; } Round::NotMade => break, - Round::Changed((offset, due, read)) => { - let image = shape.bytes_per_row * shape.height; - let place = match offset.checked_rem(shape.bytes_per_row) { - _ if offset >= image => "after the image", - Some(column) if column >= shape.width * shape.texel => "between two rows", - _ => "a texel", - }; - let operations = match access { - Access::Reads => "the first move", - Access::Renders => { - "the first move, feedback loop moves, a pass's clear and store or a \ - draw" - } - Access::Writes => "the first move or a kernel's storage writes", - }; - let lines = match rows { - RowEnds::InLines => "", - RowEnds::OnLines => ", rows on lines", - }; - device.shared().in_place.note(format!( - "{class:?}{lines}: {operations} of a {:?} image of {}x{} with rows {} \ - bytes apart changed byte {offset} ({place}) from {due:#04x} to \ - {read:#04x} in round {round}", - shape.format, shape.width, shape.height, shape.bytes_per_row - )); - let forced = device.shared().in_place.forced_failure(); - return Some(verdicts(made, Some(rows), forced)); + Round::Padded(changed) => { + made(&mut made_sharing); + // The first such round is noted; the rounds go on. + if !tally.kept(rows, true) { + continue; + } + (changed, true) } + Round::Changed(changed) => (changed, false), + }; + let image = shape.bytes_per_row * shape.height; + let place = match offset.checked_rem(shape.bytes_per_row) { + _ if offset >= image => "after the image", + Some(column) if column >= shape.width * shape.texel => "after a row's texels", + _ => "a texel", + }; + let operations = match access { + Access::Reads => "the first move", + Access::Renders => { + "the first move, feedback loop moves, a pass's clear and store or a draw" + } + Access::Writes | Access::BufferWrites => { + "the first move or a kernel's storage writes" + } + }; + let lines = match rows { + RowEnds::InLines => "", + RowEnds::OnLines => ", rows on lines", + }; + let alone = match padding { + true => ", and no byte but of its rows' padding", + false => "", + }; + device.shared().in_place.note(format!( + "{class:?}{lines}: {operations} of a {:?} image of {}x{} with rows {} bytes apart \ + changed byte {offset} ({place}) from {due:#04x} to {read:#04x} in round \ + {round}{alone}", + shape.format, shape.width, shape.height, shape.bytes_per_row + )); + if !padding { + return Some(tally.verdicts(access, Some(rows), forced)); } } } - let forced = device.shared().in_place.forced_failure(); - Some(verdicts(made, None, forced)) + Some(tally.verdicts(access, None, forced)) +} + +/// A class's rounds for an access so far (`check_class`): those that kept every byte, by row ends +/// ([`RowEnds::ALL`]'s order); those that changed no byte but of their shape's free padding +/// ([`Shape::padding`]) or none at all, by row ends; and the row ends of the first round that +/// changed a byte of that padding. +#[derive(Default)] +pub(crate) struct Tally { + kept: [u32; 2], + beside: [u32; 2], + padding: Option, +} + +impl Tally { + /// Count a round of shapes of `rows` row ends that kept every byte, or, where `padded`, that + /// changed none but of its shape's free padding: whether it is the first that changed one + /// there. + pub(crate) fn kept(&mut self, rows: RowEnds, padded: bool) -> bool { + self.beside[rows.index()] += 1; + if !padded { + self.kept[rows.index()] += 1; + return false; + } + let first = self.padding.is_none(); + self.padding.get_or_insert(rows); + first + } + + /// The verdicts of each access `access`'s rounds answer, in [`Access::answered`]'s order, on + /// a device made to fail its check where `forced`, where `changed` names the row ends of the + /// round that changed a byte but of its shape's free padding, where one did (which ends the + /// class's rounds): the access's own ([`verdicts`]), of its rounds that kept every byte, the + /// row ends of the first that changed any byte failed; then, of [`Access::Writes`], those of + /// [`Access::BufferWrites`], of its rounds that changed no byte but of that padding, those + /// of `changed` failed. + pub(crate) fn verdicts( + &self, + access: Access, + changed: Option, + forced: bool, + ) -> Vec<[Verdict; 2]> { + let own = verdicts(self.kept, self.padding.or(changed), forced); + let beside = verdicts(self.beside, changed, forced); + let answered = access.answered().len(); + [own, beside].into_iter().take(answered).collect() + } } /// The verdicts, by row ends ([`RowEnds::ALL`]'s order), of a class and access whose rounds kept @@ -547,11 +652,16 @@ pub(crate) fn verdicts(made: [u32; 2], changed: Option, forced: bool) - } /// What one round found. -enum Round { +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Round { /// The image's move kept every byte. Kept, /// The texture took no image in place (the device makes none of the shape there). NotMade, + /// A byte of its shape's rows' padding read other than the CPU left it, where a round of + /// storage writes tells that padding apart ([`Shape::padding`]), and every other byte read + /// right: where the first was, what was due, what was read. + Padded((u64, u8, u8)), /// A byte read other than the CPU left it: where, what was due, what was read. Changed((u64, u8, u8)), } @@ -595,7 +705,7 @@ fn check_round( let outcome = std::thread::scope(|scope| { let builder = std::thread::Builder::new().name("m2v-in-place-writes".to_owned()); let Ok(writer) = exit_guard::spawn_scoped(scope, builder, || { - bytes.write_until(&pattern, texels, (&stop, &started)) + bytes.write_until(&pattern, (texels, false), (&stop, &started)) }) else { return None; }; @@ -616,10 +726,7 @@ fn check_round( }; drop(texture); let texels = texels.map(|shape| (shape, Due::Zero)); - match bytes.compare(&pattern, texels, written) { - None => Round::Kept, - Some(changed) => Round::Changed(changed), - } + bytes.compare(&pattern, (texels, false), written) } /// Stops the round's writer as it goes: once the round's step returned, or where it unwinds. @@ -635,11 +742,12 @@ impl Drop for Stopping<'_> { /// caller's section: the pattern; a texture of shader write usage over it; the bytes of a buffer /// of `device`'s stored into its texels by a kernel, while the CPU writes the bytes beside them /// (between rows and after the image) and the image takes its first move; and the bytes -/// compared: each texel's the kernel's, each other byte the CPU's or the pattern. +/// compared: each texel's the kernel's, each other byte the CPU's or the pattern, a change of a +/// byte of the rows' padding told apart where `free` ([`Round::Padded`]). fn store_round( device: &Device, pages: &ClassPages, - (shape, texel): (Shape, ShadowTexelView), + (shape, texel, free): (Shape, ShadowTexelView, bool), round: usize, page: u64, ) -> Round { @@ -692,7 +800,7 @@ fn store_round( let outcome = std::thread::scope(|scope| { let builder = std::thread::Builder::new().name("m2v-in-place-writes".to_owned()); let Ok(writer) = exit_guard::spawn_scoped(scope, builder, || { - bytes.write_until(&pattern, Some(shape), (&stop, &started)) + bytes.write_until(&pattern, (Some(shape), free), (&stop, &started)) }) else { return None; }; @@ -706,17 +814,13 @@ fn store_round( return Round::NotMade; }; drop(texture); - let texels = Some((shape, Due::Stored)); - match bytes.compare(&pattern, texels, written) { - None => Round::Kept, - Some(changed) => Round::Changed(changed), - } + bytes.compare(&pattern, (Some((shape, Due::Stored)), free), written) } /// What a round's texels must read once it ended, where the writer passed them over: zero (a /// pass cleared them) or the bytes a kernel stored (`Pattern::stored`). #[derive(Clone, Copy)] -enum Due { +pub(crate) enum Due { Zero, Stored, } @@ -905,9 +1009,9 @@ fn dma_buf_pages(device: &Device, length: u64) -> Option { /// A window of a class's pages, from its byte 0. #[derive(Clone, Copy)] -struct Bytes { - start: NonNull, - length: u64, +pub(crate) struct Bytes { + pub(crate) start: NonNull, + pub(crate) length: u64, } // SAFETY: the window's pages stay mapped while the round uses them (its buffer holds them), and @@ -929,7 +1033,7 @@ const PERIOD: usize = 4099; /// A round's pattern: [`PERIOD`] bytes of a hash of their place and the round, repeated over the /// window. A byte the writer wrote holds it changed by its last sweep's [`mark`]. -struct Pattern { +pub(crate) struct Pattern { bytes: Vec, /// The bytes a kernel of a round of storage writes stores, by their place in the period: the /// pattern's, changed in four bits, so that each differs from the pattern. @@ -938,7 +1042,7 @@ struct Pattern { impl Pattern { /// The pattern of round `salt`. - fn new(salt: u64) -> Pattern { + pub(crate) fn new(salt: u64) -> Pattern { let bytes = (0..PERIOD as u64) .map(|offset| { let mixed = (offset ^ salt.rotate_left(17)).wrapping_mul(0x9E37_79B9_7F4A_7C15); @@ -950,7 +1054,7 @@ impl Pattern { } /// Its byte at `offset` of the window. - fn at(&self, offset: u64) -> u8 { + pub(crate) fn at(&self, offset: u64) -> u8 { self.bytes[(offset % PERIOD as u64) as usize] } @@ -973,12 +1077,14 @@ impl Pattern { /// What a round's writer wrote ([`Bytes::write_until`]): the sweep it was in as it stopped, how /// many of the stride's bytes that sweep reached (each byte before that one written by it, each -/// after by the sweep before), and the first byte it found other than it left it, where it found -/// one: its offset, what was due and what was read. -struct Written { - sweep: u64, - reached: u64, - changed: Option<(u64, u8, u8)>, +/// after by the sweep before), the first byte it found other than it left it, where it found one +/// (its offset, what was due and what was read), and the first of its shape's rows' padding it +/// found so, where it told that padding apart. +pub(crate) struct Written { + pub(crate) sweep: u64, + pub(crate) reached: u64, + pub(crate) changed: Option<(u64, u8, u8)>, + pub(crate) padding: Option<(u64, u8, u8)>, } /// What sweep `sweep` of a round's writer changes the pattern by: nothing before the first @@ -1039,7 +1145,8 @@ impl Bytes { /// pattern changed by [`mark`]`(k)`, and reads each byte before it writes it, which must still /// hold what the sweep before left there (the pattern before the first). `started` once the /// first byte is written. What it wrote, and the first byte it found otherwise, where it found - /// one (then it stops there). + /// one (then it stops there); but where `free`, a byte of the shape's rows' padding it found + /// otherwise is noted apart, the first of them, and written on as any other. /// /// A device that writes back bytes it read beside the texels (a whole line of a cache, say, of /// which the texels hold part) leaves there what they held when it read them. Where the writer @@ -1054,7 +1161,7 @@ impl Bytes { fn write_until( &self, pattern: &Pattern, - texels: Option, + (texels, free): (Option, bool), (stop, started): (&AtomicBool, &Barrier), ) -> Written { let stride = self.stride(); @@ -1065,6 +1172,8 @@ impl Bytes { started.wait(); } }; + let in_padding = |offset| free && texels.is_some_and(|shape| shape.in_padding(offset)); + let mut padding = None; let mut sweep = 1; loop { let (before, now) = (mark(sweep - 1), mark(sweep)); @@ -1078,13 +1187,16 @@ impl Bytes { // SAFETY: as in `fill`; the round's thread does not touch the bytes meanwhile. let read = unsafe { byte.read_volatile() }; if read != due { - started_once(); - let changed = Some((offset, due, read)); - return Written { - sweep, - reached: n, - changed, - }; + if !in_padding(offset) { + started_once(); + return Written { + sweep, + reached: n, + changed: Some((offset, due, read)), + padding, + }; + } + padding.get_or_insert((offset, due, read)); } // SAFETY: as above. unsafe { byte.write_volatile(pattern.at(offset) ^ now) }; @@ -1094,6 +1206,7 @@ impl Bytes { sweep, reached: n + 1, changed: None, + padding, }; } } @@ -1101,23 +1214,27 @@ impl Bytes { } } - /// The first byte that reads other than the writer and the round left it, after `written`: - /// its offset, what was due and what was read; `None` where every byte reads right. The first - /// byte the writer found changed, where it found one; else each byte it wrote must read what - /// its last sweep over it wrote (the stride's first `written.reached` bytes that sweep's, the + /// What the round found after `written` ([`Round`]): the first byte that reads other than + /// the writer and the round left it, its offset, what was due and what was read, where one + /// does ([`Round::Changed`]); else, where `free`, the first byte of the rows' padding of the + /// shape `texels` names that does ([`Round::Padded`]); else [`Round::Kept`]. The first byte + /// the writer found changed, where it found one; else each byte it wrote must read what its + /// last sweep over it wrote (the stride's first `written.reached` bytes that sweep's, the /// rest the sweep's before, where there was one), and is set back to the pattern as it is /// read; then every byte must read the pattern, compared a period at a time, but, where /// `texels` names the shape a pass cleared or a kernel stored, its texels, which must read /// what is due of them. - fn compare( + pub(crate) fn compare( &self, pattern: &Pattern, - texels: Option<(Shape, Due)>, + (texels, free): (Option<(Shape, Due)>, bool), written: Written, - ) -> Option<(u64, u8, u8)> { - if written.changed.is_some() { - return written.changed; + ) -> Round { + if let Some(changed) = written.changed { + return Round::Changed(changed); } + let in_padding = |offset| free && texels.is_some_and(|(shape, _)| shape.in_padding(offset)); + let mut padding = written.padding; let stride = self.stride(); let reached = match written.sweep { 1 => written.reached, @@ -1136,13 +1253,19 @@ impl Bytes { // SAFETY: as in `fill`; the writer was joined. let read = unsafe { self.byte(offset).read_volatile() }; if read != due { - return Some((offset, due, read)); + if !in_padding(offset) { + return Round::Changed((offset, due, read)); + } + padding.get_or_insert((offset, due, read)); } // SAFETY: as above. unsafe { self.byte(offset).write_volatile(pattern.at(offset)) }; } let Some((shape, due)) = texels else { - return self.matches(&pattern.bytes, 0, self.length); + return match self.matches(&pattern.bytes, 0, self.length) { + Some(changed) => Round::Changed(changed), + None => Round::Kept, + }; }; // Each row's texels read what is due, and the bytes after them to the next row the // pattern. @@ -1159,19 +1282,25 @@ impl Bytes { } Due::Stored => self.matches(&pattern.stored, start, start + row_bytes), }; - if changed.is_some() { - return changed; + if let Some(changed) = changed { + return Round::Changed(changed); } let next = start + shape.bytes_per_row; if let Some(changed) = self.matches(&pattern.bytes, start + row_bytes, next) { - return Some(changed); + if !free { + return Round::Changed(changed); + } + padding.get_or_insert(changed); } } - self.matches( - &pattern.bytes, - shape.bytes_per_row * shape.height, - self.length, - ) + let after = shape.bytes_per_row * shape.height; + if let Some(changed) = self.matches(&pattern.bytes, after, self.length) { + return Round::Changed(changed); + } + match padding { + Some(changed) => Round::Padded(changed), + None => Round::Kept, + } } /// The first byte from `from` to `to` that does not read `period` (a period's bytes, by their diff --git a/crates/metal2vulkan-runtime/src/tests/in_place.rs b/crates/metal2vulkan-runtime/src/tests/in_place.rs index b220c4584..745e1e82d 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place.rs @@ -9,7 +9,13 @@ //! for each access it takes (one that renders, `RenderTarget`, its render check; one a shader //! writes, its storage check; one that does neither, its read check), asked in that order until //! one did not pass, else a shadow naming that check's answer (pending, failed, unchecked), its -//! access and its row ends. +//! access and its row ends. A texture a shader writes whose rows' padding is free asks the +//! check of writes that lets that padding change in the stead of the one that keeps it. +//! - **The padding rule.** Rows' padding is free exactly over a buffer's own rows whose every row, +//! to its pitch, shares no line with bytes past them; a round of storage writes that changed +//! bytes of that padding alone (any row's, the last's included) fails the check of writes that +//! keeps it and counts for the one that lets it change, while a change past the last row's +//! pitch, of a texel, or of padding that is not free fails both. //! - **Row ends.** Texels share no line with bytes beside them exactly where their first byte, //! their end and, with bytes between rows (or slices), each row's (or slice's) start and end lie //! on a line; and the check's verdicts by row ends fail both where texels that share none @@ -23,13 +29,17 @@ use crate::in_place::{ decode, encode, in_place, record_name, verdict_index, Access, DriverIdentity, InPlaceChecks, - PagesClass, RowEnds, ShadowCause, Verdict, CHECK_VERSION, STORED_TEXEL_BYTES, VERDICTS, + Padding, PagesClass, RowEnds, ShadowCause, Verdict, CHECK_VERSION, STORED_TEXEL_BYTES, + VERDICTS, +}; +use crate::in_place_check::{ + verdicts, Bytes, Due, Pattern, Round, Shape, Tally, Written, SHAPES, STORE_SHAPES, }; -use crate::in_place_check::{verdicts, Shape, SHAPES, STORE_SHAPES}; use crate::linear_plan::BufferLayout; use metal2vulkan::device::HostPageTexturePolicy; use metal2vulkan::metal::TextureUsage; use sha2::{Digest, Sha256}; +use std::ptr::NonNull; use std::time::Duration; const ANSWERS: [Verdict; 4] = [ @@ -61,10 +71,11 @@ fn unchecked_width(usage: TextureUsage, texel: u64) -> Option { } } -/// The accesses whose checks `usage` asks, in their order: renders where it holds -/// `RenderTarget`, writes where it holds `ShaderWrite` or `ShaderAtomic`, reads where it holds +/// The accesses whose checks `usage` asks of a texture whose rows' padding is as `padding` says, +/// in their order: renders where it holds `RenderTarget`, writes where it holds `ShaderWrite` or +/// `ShaderAtomic` (those that let the padding change where it is free), reads where it holds /// neither. -fn accesses_of(usage: TextureUsage) -> Vec { +fn accesses_of(usage: TextureUsage, padding: Padding) -> Vec { let renders = usage.contains(TextureUsage::RENDER_TARGET); let writes = usage.intersects(TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC); let mut accesses = Vec::new(); @@ -75,7 +86,10 @@ fn accesses_of(usage: TextureUsage) -> Vec { accesses.push(Access::Renders); } if writes { - accesses.push(Access::Writes); + accesses.push(match padding { + Padding::Free => Access::BufferWrites, + Padding::Kept => Access::Writes, + }); } accesses } @@ -103,21 +117,25 @@ fn the_decision_takes_a_texture_whose_class_passed_each_of_its_accesses() { for reads in ANSWERS { for renders in ANSWERS { for writes in ANSWERS { - answers.push([reads, renders, writes]); + for buffer_writes in ANSWERS { + answers.push([reads, renders, writes, buffer_writes]); + } } } } - for (class, rows) in PagesClass::ALL - .into_iter() - .flat_map(|class| RowEnds::ALL.map(|rows| (class, rows))) - { + let each = PagesClass::ALL.into_iter().flat_map(|class| { + RowEnds::ALL.into_iter().flat_map(move |rows| { + [Padding::Kept, Padding::Free].map(|padding| (class, rows, padding)) + }) + }); + for (class, rows, padding) in each { for &usage in &usages { for texel in [1u64, 2, 4, 8, 16] { for answer in &answers { let of = |access: Access| answer[access.index()]; // Shadow: always the exact form, the check never asked. let asked = std::cell::RefCell::new(Vec::new()); - let pages = (class, rows, texel); + let pages = (class, rows, texel, padding); let policy = HostPageTexturePolicy::Shadow; let decided = in_place(policy, usage, pages, |_, access, _| { asked.borrow_mut().push(access); @@ -138,7 +156,7 @@ fn the_decision_takes_a_texture_whose_class_passed_each_of_its_accesses() { let (expected, due) = match unchecked_width(usage, texel) { Some(cause) => (Err(cause), Vec::new()), None => { - let accesses = accesses_of(usage); + let accesses = accesses_of(usage, padding); let first = accesses.iter().position(|&a| of(a) != Verdict::Passed); match first { None => (Ok(()), accesses), @@ -155,7 +173,8 @@ fn the_decision_takes_a_texture_whose_class_passed_each_of_its_accesses() { } } }; - let case = format!("{class:?} {rows:?} {usage:?} {texel} {answer:?}"); + let case = + format!("{class:?} {rows:?} {padding:?} {usage:?} {texel} {answer:?}"); assert_eq!(decided, expected, "{case}"); assert_eq!(*asked.borrow(), due, "{case}"); } @@ -182,6 +201,8 @@ fn every_shadow_cause_names_itself() { ShadowCause::StoreWidth(1), ShadowCause::CheckFailed(PagesClass::Pointer, Access::Renders, inside), ShadowCause::CheckFailed(PagesClass::Pointer, Access::Renders, on), + ShadowCause::CheckFailed(PagesClass::Pointer, Access::BufferWrites, inside), + ShadowCause::CheckPending(PagesClass::Fresh, Access::BufferWrites, on), ]; let words: Vec = causes.iter().map(ShadowCause::words).collect(); for (at, word) in words.iter().enumerate() { @@ -198,6 +219,8 @@ fn every_shadow_cause_names_itself() { assert!(words[4].contains("dma-bufs")); assert!(words[8].contains("not answered") && words[8].contains("storage writes")); assert!(words[12].contains("share a line") && words[13].contains("share no line")); + assert!(words[14].contains("over a buffer's rows, beside their padding")); + assert!(words[15].contains("not answered") && words[15].contains("over a buffer's rows")); } /// A driver identity, every field set. @@ -520,3 +543,190 @@ fn a_change_beside_texels_that_share_no_line_fails_both_row_ends() { assert_eq!(verdicts([0, 21], None, false), [Unchecked, Passed]); assert_eq!(verdicts([9, 0], None, false), [Passed, Unchecked]); } + +#[test] +fn rows_padding_is_free_over_a_buffer_s_own_rows_that_end_on_lines() { + let (kept, free) = (Padding::Kept, Padding::Free); + // The guest's surface: 3662 BGRA8 texels a row at a 14656-byte pitch, 2039 rows. Its texels + // share a line with its padding; its rows, each to its pitch, share none with bytes past them. + let surface = rows_of(0, 14648, 14656, 2039); + assert_eq!(RowEnds::of(0, &surface, 64), RowEnds::InLines); + assert_eq!(Padding::of(0, &surface, 64, true), free); + // Not the buffer's own rows (an IOSurface plane's, or a buffer that ends before the last + // row's pitch): kept. + assert_eq!(Padding::of(0, &surface, 64, false), kept); + // The last row's pitch ends inside a line: kept. 416 x 51 bytes end 32 bytes into a 64-byte + // line, and on a 16-byte one. + let tight = rows_of(0, 404, 416, 51); + assert_eq!(Padding::of(0, &tight, 64, true), kept); + assert_eq!(Padding::of(0, &tight, 16, true), free); + // The first texel off a line, by the buffer's address or by the texture's offset: kept; both + // together back on one: free. + assert_eq!(Padding::of(16, &surface, 64, true), kept); + assert_eq!( + Padding::of(0, &rows_of(16, 14648, 14656, 2039), 64, true), + kept + ); + assert_eq!( + Padding::of(16, &rows_of(48, 14648, 14656, 2039), 64, true), + free + ); + // A pitch off a line: a line between two rows holds one's padding and the next one's texels + // alone, so the padding is free where the rows start and end on lines. + assert_eq!(Padding::of(0, &rows_of(0, 256, 288, 16), 64, true), free); + // Bytes between slices are no row's padding: slices apart must each start and end on lines. + let slices = |slice_pitch| BufferLayout { + offset: 0, + row_pitch: 288, + slice_pitch, + row_bytes: 256, + rows: 4, + slices: 3, + }; + assert_eq!(Padding::of(0, &slices(1152), 64, true), free); + assert_eq!(Padding::of(0, &slices(1216), 64, true), free); + assert_eq!(Padding::of(0, &slices(1184), 64, true), kept); + // The check's storage shapes: free at 16-byte lines, and at 64-byte ones but for the pair at + // the 16-byte pitch of a driver that lays rows tight, whose rows end inside such a line. + for (shape, _) in STORE_SHAPES { + assert_eq!(shape.padding(16), free, "{shape:?}"); + let tight16 = shape.tight && shape.bytes_per_row % 64 != 0; + let due = match tight16 { + true => kept, + false => free, + }; + assert_eq!(shape.padding(64), due, "{shape:?}"); + } +} + +#[test] +fn a_round_of_storage_writes_tells_a_change_of_free_padding_apart() { + // A 101x51 shape of 4-byte texels at a 512-byte pitch, of the check's storage shapes: 404 + // bytes of texels a row, then 108 of padding, and the window's bytes after the image. + let (shape, _) = STORE_SHAPES[3]; + assert_eq!( + (shape.width, shape.height, shape.texel, shape.bytes_per_row), + (101, 51, 4, 512) + ); + assert_eq!(shape.padding(64), Padding::Free); + let (pitch, row) = (shape.bytes_per_row, shape.width * shape.texel); + let image = pitch * shape.height; + let length = image + 4096; + let pattern = Pattern::new(7); + // A round's compare of the window as it leaves it: the pattern, every texel zero (as after a + // pass's clear), the byte at `change` flipped where one is named, and `written` the writer's. + let compare = |change: Option, free: bool, written: Written| { + let mut window: Vec = (0..length).map(|offset| pattern.at(offset)).collect(); + for y in 0..shape.height { + window[(y * pitch) as usize..(y * pitch + row) as usize].fill(0); + } + if let Some(at) = change { + window[at as usize] ^= 0x01; + } + let bytes = Bytes { + start: NonNull::new(window.as_mut_ptr()).unwrap(), + length, + }; + bytes.compare(&pattern, (Some((shape, Due::Zero)), free), written) + }; + // The writer wrote nothing (its first sweep reached no byte) and found nothing. + let idle = || Written { + sweep: 1, + reached: 0, + changed: None, + padding: None, + }; + let flipped = |at: u64, base: u8| (at, base, base ^ 0x01); + assert_eq!(compare(None, true, idle()), Round::Kept); + // A byte of a row's padding, the first row's, the last row's and the last row's last before + // its pitch: padding alone where it is free, a change where it is not. + let last = (shape.height - 1) * pitch; + for at in [row, pitch + row + 50, last + row, image - 1] { + let changed = flipped(at, pattern.at(at)); + assert_eq!( + compare(Some(at), true, idle()), + Round::Padded(changed), + "{at}" + ); + assert_eq!( + compare(Some(at), false, idle()), + Round::Changed(changed), + "{at}" + ); + } + // The first byte past the last row's pitch, and a texel: a change either way. + let past = flipped(image, pattern.at(image)); + assert_eq!(compare(Some(image), true, idle()), Round::Changed(past)); + assert_eq!( + compare(Some(last + 4), true, idle()), + Round::Changed(flipped(last + 4, 0)) + ); + // What the writer found: a byte of the padding, kept to the end; another byte, a change. + let found = (row + 3, 0x11, 0x22); + let padded = || Written { + padding: Some(found), + ..idle() + }; + assert_eq!(compare(None, true, padded()), Round::Padded(found)); + assert_eq!(compare(Some(image), true, padded()), Round::Changed(past)); + let changed = Written { + changed: Some((image + 9, 0x11, 0x22)), + ..padded() + }; + assert_eq!( + compare(None, true, changed), + Round::Changed((image + 9, 0x11, 0x22)) + ); +} + +#[test] +fn a_round_that_changed_padding_alone_fails_only_the_check_of_writes_that_keeps_it() { + use Verdict::{Failed, Passed, Unchecked}; + let (inside, on) = (RowEnds::InLines, RowEnds::OnLines); + // The Iris Xe's walk: shapes whose texels share no line keep every byte; those that share + // one change their rows' padding alone (the line of a row's last texels, written back whole). + let mut tally = Tally::default(); + for _ in 0..12 { + assert!(!tally.kept(on, false)); + } + assert!(tally.kept(inside, true), "the first such round is noted"); + assert!(!tally.kept(inside, true)); + assert_eq!( + tally.verdicts(Access::Writes, None, false), + vec![[Failed, Passed], [Passed, Passed]] + ); + // The other accesses' rounds answer their own verdicts alone. + assert_eq!( + tally.verdicts(Access::Renders, None, false), + vec![[Failed, Passed]] + ); + // A byte past the padding changed too: both fail for its row ends. + assert_eq!( + tally.verdicts(Access::Writes, Some(inside), false), + vec![[Failed, Passed], [Failed, Passed]] + ); + // Padding changed beside texels that share no line: the check that keeps it fails for both + // row ends, the other passes. + let mut tally = Tally::default(); + assert!(tally.kept(on, true)); + assert!(!tally.kept(inside, false)); + assert_eq!( + tally.verdicts(Access::Writes, None, false), + vec![[Failed, Failed], [Passed, Passed]] + ); + assert_eq!( + tally.verdicts(Access::Writes, Some(on), false), + vec![[Failed, Failed], [Failed, Failed]] + ); + // Row ends no round kept are unchecked, and a forced failure fails the rest. + let mut tally = Tally::default(); + tally.kept(on, false); + assert_eq!( + tally.verdicts(Access::Writes, None, false), + vec![[Unchecked, Passed], [Unchecked, Passed]] + ); + assert_eq!( + tally.verdicts(Access::Writes, None, true), + vec![[Unchecked, Failed], [Unchecked, Failed]] + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/texture_placement.rs b/crates/metal2vulkan-runtime/src/tests/texture_placement.rs index e91aeb975..c5c95fb56 100644 --- a/crates/metal2vulkan-runtime/src/tests/texture_placement.rs +++ b/crates/metal2vulkan-runtime/src/tests/texture_placement.rs @@ -1,7 +1,7 @@ //! Where a texture over a buffer's bytes lies (`texture_placement.rs`): each route the making //! takes (`texture/route.rs`) answers its own placement, and every shadow cause its own reason. -use crate::in_place::{Access, PagesClass, Refusal, RowEnds, ShadowCause}; +use crate::in_place::{Access, Padding, PagesClass, Refusal, RowEnds, ShadowCause}; use crate::texture::{HostWay, Route}; use crate::{InPlaceAccess, InPlaceRefusal, InPlaceRowEnds, TexturePlacement, TextureShadowReason}; @@ -10,6 +10,7 @@ fn host(way: HostWay) -> Route { Route::Host { class: PagesClass::Pointer, rows: RowEnds::InLines, + padding: Padding::Kept, way, } } @@ -37,6 +38,7 @@ fn each_route_answers_its_own_placement() { (Access::Reads, InPlaceAccess::Reads), (Access::Renders, InPlaceAccess::Renders), (Access::Writes, InPlaceAccess::Writes), + (Access::BufferWrites, InPlaceAccess::Writes), ]; let rows = [ (RowEnds::InLines, InPlaceRowEnds::InLines), diff --git a/crates/metal2vulkan-runtime/src/tests/texture_placement_device.rs b/crates/metal2vulkan-runtime/src/tests/texture_placement_device.rs index b0cfe9fdd..788586d5c 100644 --- a/crates/metal2vulkan-runtime/src/tests/texture_placement_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/texture_placement_device.rs @@ -494,7 +494,7 @@ fn the_answer_is_the_route_the_texture_takes() { let public_access = match access { Access::Reads => InPlaceAccess::Reads, Access::Renders => InPlaceAccess::Renders, - Access::Writes => InPlaceAccess::Writes, + Access::Writes | Access::BufferWrites => InPlaceAccess::Writes, }; let (access, row_ends) = (public_access, public_rows(rows)); let due = match verdict { diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 4e611fcde..7db8ccf83 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -2360,6 +2360,7 @@ impl Device { Route::Host { class, rows, + padding, way: HostWay::InPlace { storable }, } => { let checking = in_place::checking(); @@ -2379,14 +2380,18 @@ impl Device { } Err((refusal, why)) => ShadowCause::Refused(refusal, why), }; - let shadowed = (class, rows, cause); + let shadowed = (class, (rows, padding), cause); self.host_shadowed(shadowed, (usage, &plan), descriptor, pending)? } Route::Host { class, rows, + padding, way: HostWay::Shadow(cause), - } => self.host_shadowed((class, rows, cause), (usage, &plan), descriptor, pending)?, + } => { + let shadowed = (class, (rows, padding), cause); + self.host_shadowed(shadowed, (usage, &plan), descriptor, pending)? + } Route::Device => { // Whether an image may hold the texels: none where their rows (or slices) lie // with the buffer's bytes between them (`linear_plan::holding`), and else why. @@ -2562,14 +2567,19 @@ impl Device { } /// A texture over host pages of `class`, its texels lying in the device's lines as `rows` - /// says, of `usage` and declared plan `plan` (`texture`), made with `descriptor`, is a shadow + /// says and its rows' padding as `padding` says (`in_place::Padding`), of `usage` and declared + /// plan `plan` (`texture`), made with `descriptor`, is a shadow /// for `cause`: counted by why, and where made before its class's verdict for its access, /// `pending` set to what it needs to move in place once the verdict passes. The shadow's /// notice's reason. Refused (internal) on the device's check's own thread, whose textures take /// the image in place. fn host_shadowed( &self, - (class, rows, cause): (PagesClass, in_place::RowEnds, ShadowCause), + (class, (rows, padding), cause): ( + PagesClass, + (in_place::RowEnds, in_place::Padding), + ShadowCause, + ), (usage, plan): (TextureUsage, &ImagePlan), descriptor: &TextureDescriptor, pending: &mut Option, @@ -2583,6 +2593,7 @@ impl Device { *pending = Some(in_place::PendingMove { class, rows, + padding, usage, plan: plan.clone(), descriptor: *descriptor, diff --git a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs index 9e3535526..5de95a069 100644 --- a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs @@ -53,7 +53,7 @@ use crate::device::lock; use crate::error::{vulkan, Error, RuntimeGap}; use crate::framebuffer_fetch::storage_candidate; use crate::image_plan::{ImageFacts, ImagePlan}; -use crate::in_place::{Access, PagesClass, Refusal, RowEnds}; +use crate::in_place::{Access, Padding, PagesClass, Refusal, RowEnds}; use crate::linear_plan::{check_linear_limits, linear_lack, BufferLayout, LinearLack}; use crate::shadow_copy_back::WordView; use crate::shadow_copy_in::CopyIn; @@ -307,6 +307,7 @@ impl Device { image: Arc::downgrade(&image_any), from_base: buffer_offset + layout.offset - base, layout, + padding_owned: texels.padding_owned(), }); } } @@ -794,25 +795,35 @@ impl Device { }) } - /// How the texels `watch` notes lie in the device's lines of memory (`in_place::RowEnds`): + /// How the texels `watch` notes lie in the device's lines of memory (`in_place::RowEnds`), + /// and whether a shader's writes may change their rows' padding (`in_place::Padding`): /// `from_base` past the pages' first byte, which starts a page. - fn watched_rows(&self, watch: &InPlaceWatch) -> RowEnds { + fn watched_rows(&self, watch: &InPlaceWatch) -> (RowEnds, Padding) { let start = watch.from_base - watch.layout.offset; - RowEnds::of(start, &watch.layout, self.shared().in_place.line()) + let line = self.shared().in_place.line(); + let padding = Padding::of(start, &watch.layout, line, watch.padding_owned); + (RowEnds::of(start, &watch.layout, line), padding) } /// Whether the device's check passed for fresh pages, each of `image`'s accesses and texels /// that lie in lines as `rows` says: an image of attachment usage renders, one of storage - /// usage is written, one of neither reads. - fn fresh_pages_take(&self, image: &Image, rows: RowEnds) -> bool { + /// usage is written, one of neither reads. The writes of one that does not render whose + /// rows' padding is free take the check that lets it change (`in_place::in_place`); one that + /// renders may hold the storage usage a render target takes where the check that keeps it + /// passed (`Device::storage_over_buffer`'s `storable`), which it asks. + fn fresh_pages_take(&self, image: &Image, (rows, padding): (RowEnds, Padding)) -> bool { use metal2vulkan::vk::ImageUsageFlags; let usage = image.plan().usage; let renders = usage.contains(ImageUsageFlags::COLOR_ATTACHMENT); let writes = usage.contains(ImageUsageFlags::STORAGE); + let written = match (padding, renders) { + (Padding::Free, false) => Access::BufferWrites, + _ => Access::Writes, + }; let accesses = [ (Access::Reads, !renders && !writes), (Access::Renders, renders), - (Access::Writes, writes), + (written, writes), ]; accesses.into_iter().all(|(access, takes)| { !takes diff --git a/crates/metal2vulkan-runtime/src/texture/route.rs b/crates/metal2vulkan-runtime/src/texture/route.rs index 2e63430c2..48f2cc23d 100644 --- a/crates/metal2vulkan-runtime/src/texture/route.rs +++ b/crates/metal2vulkan-runtime/src/texture/route.rs @@ -9,7 +9,7 @@ use super::image_error; use crate::buffer::CallerMemory; use crate::buffer_texture::Texels; use crate::image_plan::{plan_image, ImageFacts, ImagePlan}; -use crate::in_place::{self, Access, PagesClass, Refusal, RowEnds, ShadowCause, Verdict}; +use crate::in_place::{self, Access, Padding, PagesClass, Refusal, RowEnds, ShadowCause, Verdict}; use crate::texture_descriptor::{texture_usage, TextureDescriptor, TextureLayout}; use crate::texture_placement::TexturePlacement; use crate::{Device, Error}; @@ -24,10 +24,12 @@ pub(crate) enum Route { /// The buffer's bytes are no host pages: an image aliasing the buffer's memory where the /// device makes one on Metal's layout, else the shadow. Device, - /// Over host pages of `class`, its texels lying in the device's lines as `rows` says. + /// Over host pages of `class`, its texels lying in the device's lines as `rows` says, and + /// `padding` saying whether a shader's writes may change their rows' padding. Host { class: PagesClass, rows: RowEnds, + padding: Padding, way: HostWay, }, } @@ -106,10 +108,17 @@ impl Device { _ => return Route::Device, }; // How the texels lie in the device's lines of memory, each checked apart - // (`in_place::RowEnds`). - let rows = texels.rows(self.shared().in_place.line()); - let host = |way| Route::Host { class, rows, way }; - let pages = (class, rows, texels.texel_bytes()); + // (`in_place::RowEnds`), and whether a shader's writes may change their rows' padding + // (`in_place::Padding`). + let line = self.shared().in_place.line(); + let (rows, padding) = (texels.rows(line), texels.padding(line)); + let host = |way| Route::Host { + class, + rows, + padding, + way, + }; + let pages = (class, rows, texels.texel_bytes(), padding); let checking = in_place::checking(); let detached = texels.buffer.detached(); let policy = self.compile_device().policy().host_page_textures; diff --git a/crates/metal2vulkan-runtime/src/texture/storage_form.rs b/crates/metal2vulkan-runtime/src/texture/storage_form.rs index 05ecc20d3..a62ab4f50 100644 --- a/crates/metal2vulkan-runtime/src/texture/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/texture/storage_form.rs @@ -124,7 +124,7 @@ use crate::framebuffer_fetch::storage_candidate; use crate::heap_sets; use crate::image_barrier::{image_barrier, ImageDst}; use crate::image_plan::ImagePlan; -use crate::in_place::{self, Access as InPlaceAccess, PagesClass, RowEnds, Verdict}; +use crate::in_place::{self, Access as InPlaceAccess, Padding, PagesClass, RowEnds, Verdict}; use crate::memory::Placement; use crate::tracker::Access; use crate::values::StorageMode; @@ -176,6 +176,8 @@ struct MoveWait { class: PagesClass, /// How its texels lie in the device's lines of memory (`in_place::RowEnds`). rows: RowEnds, + /// Whether a shader's writes may change its rows' padding (`in_place::Padding`). + padding: Padding, usage: TextureUsage, /// The bytes of one of its texels. texel: u64, @@ -193,7 +195,7 @@ impl MoveWait { return None; } let policy = device.compile_device().policy().host_page_textures; - let pages = (self.class, self.rows, self.texel); + let pages = (self.class, self.rows, self.texel, self.padding); Some(in_place::in_place(policy, self.usage, pages, verdict).is_ok()) } } @@ -588,7 +590,12 @@ impl Texture { let checks = &image.device.shared().in_place; let verdict = |class, access, rows| checks.verdict(class, access, rows); let policy = image.device.compile_device().policy().host_page_textures; - let pages = (pending.class, pending.rows, texels.texel_bytes()); + let pages = ( + pending.class, + pending.rows, + texels.texel_bytes(), + pending.padding, + ); if texels.buffer.detached() || texels.buffer.copied() { return None; } @@ -767,6 +774,7 @@ impl Texture { texture: self.downgrade(), class: pending.class, rows: pending.rows, + padding: pending.padding, usage: pending.usage, texel: texels.texel_bytes(), }; diff --git a/crates/metal2vulkan-runtime/src/texture_placement.rs b/crates/metal2vulkan-runtime/src/texture_placement.rs index ba9a68a99..5c6f25390 100644 --- a/crates/metal2vulkan-runtime/src/texture_placement.rs +++ b/crates/metal2vulkan-runtime/src/texture_placement.rs @@ -105,7 +105,10 @@ pub enum InPlaceAccess { /// store operations and the feedback loop moves. Renders, /// Its usage writes it through a shader (`ShaderWrite` or `ShaderAtomic`): its image also - /// takes kernels' storage writes of its texels. + /// takes kernels' storage writes of its texels. Of a texture over a buffer's rows whose rows, + /// each to its pitch, start and end on a line, its buffer holding the last row to its pitch, + /// the check that lets those writes change the bytes between a row's texels and its pitch, + /// which Metal's GPUs differ on; else the one that keeps every byte beside the texels. Writes, } @@ -159,7 +162,7 @@ impl InPlaceAccess { match access { in_place::Access::Reads => InPlaceAccess::Reads, in_place::Access::Renders => InPlaceAccess::Renders, - in_place::Access::Writes => InPlaceAccess::Writes, + in_place::Access::Writes | in_place::Access::BufferWrites => InPlaceAccess::Writes, } } } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/in_place_rows.rs b/crates/metal2vulkan-validation/src/runtime_lane/in_place_rows.rs index a9480651e..6f1a8b514 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/in_place_rows.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/in_place_rows.rs @@ -1,8 +1,10 @@ //! The in-place check's verdict a texture over host pages takes (`Device::in_place_check_report`): //! its class's for its access, for texels that share a line of the device's memory //! (`Device::in_place_check_line`, its `nonCoherentAtomSize`) with bytes beside them, or for -//! texels that share none (the report's `, rows on lines` lines). Worked out here from the -//! texture's layout, apart from the runtime's own reckoning (`in_place::RowEnds::of`). +//! texels that share none (the report's `, rows on lines` lines); for a shader's writes of a +//! texture over a buffer's rows whose padding is free, the report's `buffer writes` lines. Worked +//! out here from the texture's layout, apart from the runtime's own reckoning +//! (`in_place::RowEnds::of`, `in_place::Padding::of`). use metal2vulkan_runtime::Device; @@ -18,6 +20,25 @@ pub(crate) fn on_lines(device: &Device, first: u64, row_bytes: u64, pitch: u64, on(first) && on(end) && (!rows_apart || (on(pitch) && on(first + row_bytes))) } +/// Whether a 2D texture over a buffer's rows (no IOSurface plane's), `rows` rows `pitch` apart +/// from `first` bytes past a page, whose buffer holds them to the last row's pitch (`held`), has +/// free padding (`in_place::Padding`): its rows, each to its pitch, start and end on a line of the +/// device's memory. A shader's writes of it take the report's `buffer writes` verdicts +/// ([`writes`]). +pub(crate) fn padding_free(device: &Device, first: u64, pitch: u64, rows: u64, held: bool) -> bool { + let line = device.in_place_check_line(); + held && first.is_multiple_of(line) && (first + rows * pitch).is_multiple_of(line) +} + +/// The report's name of `class`'s verdicts for a shader's writes of a texture whose padding is +/// free where `padding_free` ([`padding_free`]): `Pointer buffer writes`, else `Pointer writes`. +pub(crate) fn writes(class: &str, padding_free: bool) -> String { + match padding_free { + true => format!("{class} buffer writes"), + false => format!("{class} writes"), + } +} + /// Whether the device's check passed for `what` (`Pointer`, `Pointer renders`, `Fresh writes`, /// as the report names a class and access), for texels that share no line with bytes beside /// them where `on_lines`, else for those that share one. diff --git a/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs index 82c1720a3..35972e9b5 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs @@ -26,10 +26,12 @@ //! passed for an image a shader writes over the class (`Pointer writes: Passed`), each is in //! place (`vk_image` answers one; `host_textures_in_place`, `host_textures_in_place_written`) or //! a shadow its refusal counts; where it did not, a shadow counted by the check's answer, on a -//! discrete GPU as on any other. A kernel then writes every texel, with no usage shadow -//! (`undeclared-usage-shadow`): every texel of the pages holds the value, and the bytes between -//! the rows and past the last hold the pattern. Printed (`IN-PLACE-WRITTEN`): each texture's -//! path. +//! discrete GPU as on any other; where the rows' padding is free (`in_place::Padding`), the +//! verdict is the one that lets it change (`Pointer buffer writes: Passed`). A kernel then +//! writes every texel, with no usage shadow (`undeclared-usage-shadow`): every texel of the +//! pages holds the value, the bytes past the last row hold the pattern, and so do the bytes +//! between the rows but of a texture in place whose padding is free. Printed +//! (`IN-PLACE-WRITTEN`): each texture's path. //! - [`writes_and_passes_beyond_the_usage_take_their_shadows`], under the validation layer: an //! in-place 64x64 `RGBA16Float` texture of `ShaderRead` usage alone, with padded rows and with //! packed ones (where the device takes either in place), written by a kernel (no `ShaderWrite`) @@ -41,9 +43,9 @@ //! layer: a 64x64 `R32Uint` texture over a no-copy buffer of anonymous pages, of each usage that //! renders or writes, once the device's check answered: each is in place where the check passed //! over the class for each of its accesses (`Pointer renders: Passed` for one that renders, -//! `Pointer writes: Passed` for one a shader writes, `ShaderWrite` or `ShaderAtomic`; `vk_image` -//! answers one, `host_textures_in_place`, and `host_textures_in_place_written` for one a shader -//! writes), else a shadow counted by the check's answer or the device's refusal; under +//! `Pointer buffer writes: Passed` for one a shader writes, `ShaderWrite` or `ShaderAtomic`, its +//! rows' padding free; `vk_image` answers one, `host_textures_in_place`, and +//! `host_textures_in_place_written` for one a shader writes), else a shadow counted by the check's answer or the device's refusal; under //! `HostPageTexturePolicy::Shadow` every one is the exact form's (`host_texture_shadows_exact`). //! Each shadow that renders also counts in `host_texture_shadows_render_target`, and each one a //! shader writes in `host_texture_shadows_shader_write`. @@ -113,12 +115,33 @@ pub(super) fn passed(device: &Device, what: &str, buffer: &Buffer, (w, h, bpr): in_place_rows::passed(device, what, on_lines) } +/// Whether the device's check passed for a shader's writes over `class` (`Pointer`, ...) of a 2D +/// texture of `(w, h, bpr)` bytes at the start of `buffer`, which holds no IOSurface plane: those +/// that let its rows' padding change where it is free (`in_place_rows::padding_free`), else those +/// that keep it. +pub(super) fn writes_passed( + device: &Device, + class: &str, + buffer: &Buffer, + (w, h, bpr): Rows, +) -> bool { + let first = buffer.contents().map_or(0, |at| at.as_ptr() as u64); + let held = buffer.length() >= h * bpr; + let free = in_place_rows::padding_free(device, first, bpr, h, held); + passed( + device, + &in_place_rows::writes(class, free), + buffer, + (w, h, bpr), + ) +} + /// A 2D texture's rows: the bytes of a row's texels, its rows, and their pitch. pub(super) type Rows = (u64, u64, u64); /// The verdicts the device's check gives, each a line of its report before what it found -/// changed: three classes, three accesses, two row ends. -const VERDICTS: usize = 18; +/// changed: three classes, four accesses, two row ends. +const VERDICTS: usize = 24; /// The devices made again where load beside the submission checks split their import tax's tries /// ([`answered_device`]). @@ -676,7 +699,11 @@ fn written_textures_over_host_pages_take_the_path_their_checks_answered() { } Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), }; - let checked = passed(&device, "Pointer writes", &buffer, (w * 8, h, bpr)); + let checked = writes_passed(&device, "Pointer", &buffer, (w * 8, h, bpr)); + // Rows whose padding is free (`in_place::Padding`): in place, a shader's writes may + // change it, as Metal's do on an x86 Mac's GPU. + let first = buffer.contents().map_or(0, |at| at.as_ptr() as u64); + let free = in_place_rows::padding_free(&device, first, bpr, h, true); let before = device.work_counts(); let texture = written(&buffer, PixelFormat::RGBA16Float, (w, h, bpr)); let after = device.work_counts(); @@ -735,7 +762,8 @@ fn written_textures_over_host_pages_take_the_path_their_checks_answered() { } } let between = (y * bpr + w * 8) as usize..((y + 1) * bpr) as usize; - if now[between.clone()] != pattern[between] { + let kept = !(free && path == "in place"); + if kept && now[between.clone()] != pattern[between] { lapses.push(format!("{what}: row {y}'s padding")); } } @@ -915,7 +943,7 @@ fn textures_that_render_or_write_take_the_path_their_checks_answered() { // The verdicts its `R32Uint` texels take. let rows = (w * 4, h, bpr); let renders_in_place = passed(&device, "Pointer renders", &buffer, rows); - let writes_in_place = passed(&device, "Pointer writes", &buffer, rows); + let writes_in_place = writes_passed(&device, "Pointer", &buffer, rows); for usage in usages { let mut d = TextureDescriptor::texture_2d(PixelFormat::R32Uint, w, h, false); d.usage = usage; diff --git a/docs/API.md b/docs/API.md index 1398ba87a..feb0c6e7a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -354,7 +354,12 @@ that share none (their first byte, their end and, with bytes between rows, each end on a line): a device that writes back a texel's line whole puts an older value back over a CPU write in the first alone, as the Iris Xe's clear and store and draws do, so its render targets and written textures whose rows end on a line, a 3840x2160 `BGRA8Unorm` surface's among them, -take the image in place where the others keep the shadow. It runs +take the image in place where the others keep the shadow. A kernel's writes of a texture over a +buffer's rows (no IOSurface plane's) whose rows, each to its pitch, start and end on a line, its +buffer holding the last row to its pitch, may change the rows' padding (section 10, **Kernels**): +the same rounds give a second verdict for such textures, which a round that changed only bytes of +its rows' padding passes, so the Iris Xe's written textures over a buffer take the image in place +whatever their rows' ends. It runs on a thread of its own, which the first such texture starts; a texture made before its kind of pages and access has its verdict is a shadow, made without waiting for the check (`WorkCounts::host_texture_shadows_check_pending`), and moves in place, with no copy, at a quiet @@ -1545,7 +1550,9 @@ bound. (`HostPageTexturePolicy::Shadow`), a shader writes the texture's texels of 1 or 2 bytes, which the device's check stores none of, the device's check that the operations of an access of the texture (the first move; a render pass's load and store; a kernel's storage writes) keep every - byte over that kind of pages, for texels that share a line of the device's memory + byte (but, for a kernel's writes of a texture over a buffer's rows whose padding is free, that + padding: section 10, **Kernels**) over that kind of pages, for texels that share a line of the + device's memory (`nonCoherentAtomSize`) with bytes beside them or not as the texture's do, has not answered yet, found a byte changed or made no image, or no image in place serves the texels (its rows share bytes, the device lays no linear image's rows at @@ -4567,6 +4574,22 @@ each item named states the rule in full. **Kernels** +- **A kernel's writes of a texture over a buffer may change its rows' padding** (each row's bytes + after its last texel to its pitch, the last row's included), where the texture is an image in + place over host pages whose rows, each to its pitch, start and end on a line of the device's + memory (`nonCoherentAtomSize`), its buffer holding the last row to its pitch, and the device's + check found its kernel's storage writes changing no byte but of such padding (the check + report's `buffer writes` verdicts). Metal leaves those bytes to the GPU, and the rule follows + the x86 Macs' envelope. Measured over 100 rounds of each operation, the CPU writing the padding + while the GPU ran, `BGRA8Unorm` textures of 3662x64 and 61x64 over a buffer (14848 and 256-byte + pitches) and over an IOSurface (14656 and 256): an Intel UHD Graphics 630 (macOS 26.7.1) wrote + older values back over the CPU's writes to the padding of the textures over a buffer under a + kernel's writes (10,197 and 28,162 bytes, 304 and 307 of them in the last row), and over the + IOSurfaces and under a pass's clear and store or a draw kept every byte; an M3 Max (macOS + 27.0.1, arm64 and x86_64) kept every byte under each; a Radeon Pro 5300M (macOS 26.7.1), its + rows read once each operation completed, with no CPU write meanwhile, kept every byte under + each. A render target's rows, an IOSurface plane's, and the bytes past the last row's pitch or + between slices keep every byte (`crates/metal2vulkan-conformance/probes/row_padding_writes.m`). - **An imageblock's length rounds its cell as an M4 does** (`ComputePipelineState::imageblock_memory_length_for_dimensions`), never less than what a dispatch counts against the device's threadgroup memory. diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 012b940d4..2b2decf96 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -38,7 +38,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X | Batches of command buffers on one `VkQueue`, on a driver measured to start no kernel submission of a queue before the one before it completed (ANV, RADV and NVIDIA's; `batch_order.rs`), are ordered by their ends: each ends with a barrier ordering its work before every later command of its `VkQueue` (the exact form's end orders it before the host's reads and writes alone), so a batch that depends on an earlier one there begins with no barrier of its own, often no command buffer of barriers, and its first encoder's GPU start is written at the bottom of the pipe, once everything before it completed. Metal starts an independent command buffer committed behind running work while that work runs (an M3 Max under macOS 27.0.1, probe `gpustart`); those drivers ran two batches of independent work one after the other under every shape measured (no end barrier, the host's or the widened one; in one `vkQueueSubmit` or two, merged into one kernel submission or not), where two dispatches of one command buffer ran side by side. The runtime's: no pipeline differs. | `batch_order = BatchOrderPolicy::Ends` | `batch_order = BatchOrderPolicy::Exact`: a barrier for each dependency of a batch's work on an earlier batch's of its `VkQueue`, the end's barrier to the host's reads and writes alone, the GPU start written at the top of the pipe; every other driver takes it under either value | None: on those drivers each batch starts once the one before it completed under either value, so the work's order, its results and its GPU times are the same, and a batch's GPU start is the end of the work before it, when such a driver starts it. Not announced; `runtime_lane::commit_work` and `runtime_lane::gpu_times` test both values | UHD 770 (ANV, RPL-S), the consumer's frame shape over 520 host imports, 67 command buffers a frame, Grouped completion, the widened end barrier against the exact form (a probe build of each): with no fill ahead of each command buffer, 67.0 command buffers submitted a frame against 129.3-129.7, the GPU's span a frame 1.84-1.90 ms against 1.99-2.06 ms, a frame through completion 2.13-2.22 ms against 2.27-2.38 ms; with a 1 MiB fill ahead of each, 134.0 against 262.9, 8.03-8.22 ms against 8.32-8.42 ms, 9.00-9.15 ms against 9.25-9.36 ms. Radeon 780M (RADV, Mesa 26.0.8), this switch: with no fill, 67.0 against 128.9-129.0, a frame through completion 48.3-48.6 ms against 42.6-47.0 ms; with a 16 MiB fill committed at once, 134.0 against 251.0-251.1, 50.6-50.8 ms against 50.8-57.3 ms; committed every 1 ms, 134.0 against 249.7-250.2, 71.3-83.6 ms against 106.3-113.6 ms (each kernel submission there leaves about 2.5 ms of the GPU idle over 520 host imports, which sets these frames) | | Command queues on a device whose GPU idles when consecutive work comes from another `VkQueue` share `VkQueue`s by choice (`queue_share.rs`): the runtime's own self-check, not a `DriverFact` row, measures that idling once per driver, release and runtime on a thread of its own and keeps its verdict (`Idles`, `DoesNotIdle`, `Unchecked`) in the shader cache's directory, as the in-place check keeps its own (`queue_switch_check.rs`: 48.7 to 51.3 us a switch on the RTX 5080 Laptop GPU, NVIDIA 615.71.09, `Idles` above 20 us). A command queue that makes a command buffer while it holds no other uncompleted one moves onto the busy `VkQueue` of its family whose oldest batch has run under 0.5 ms, the most batches in flight first, so short command buffers of several queues run with no switch between them. A queue one of whose command buffers ran on the GPU for over 2 ms, by its own timestamps (not the host's view of how long it ran as its `VkQueue`'s oldest, which also holds its wait for the GPU to start it and the waiter's lateness to see it complete), is long: no queue joins its `VkQueue` while it lives, and it moves once more, at its next idle point, to an idle `VkQueue` no long or unshared queue holds. A queue whose command buffers must never wait behind another queue's (a compositor's beside an application's) is made with `Device::new_command_queue_unshared`: it never moves and no queue joins its `VkQueue`. Presenting queues and a queue that lent its `VkQueue` (`with_vk_queue`) never move. Before the verdict, and where it is not `Idles` or there are no two `VkQueue`s of one family (MoltenVK, RADV, lavapipe), every queue keeps the `VkQueue` it took at its creation; so does every queue of a device whose command buffers write no GPU timestamps it reads (`gpu_times_from_host`, or a driver whose timestamps wait for every queue's), which does not share and is counted (`WorkCounts::queue_sharing_untimed`). The runtime's: no pipeline differs. | `queue_sharing = QueueSharingPolicy::Adaptive` | `queue_sharing = QueueSharingPolicy::PerQueue`: each command queue keeps the `VkQueue` it took at its creation, round robin, and the check does not run | A command buffer waits behind the command buffers of the queues sharing its `VkQueue`, where Metal's queues wait for each other only inside one command. The residual stall: once per logical queue that goes long, for a queue that joined its `VkQueue` during its short phase, about one long command buffer's length: the command buffers committed behind that queue's first long one there wait for its whole length (and those behind its later ones while it holds work, until its next idle point). Measured on the RTX 5080 Laptop GPU beside an application that alternates draws with 30 ms command buffers: a shared compositor's commits at 4,800 a second had 64 completions over 10 ms, at most 26.4 to 30.1 ms, in each of 3 runs of each of two such shapes (one join each), against none over 10 ms under `PerQueue` in those 6 runs (at most 5.6 to 9.7 ms); with 2 ms of draws between long command buffers, none over 10 ms in 3 runs (at most 5.7 to 9.8 ms) against 7, 0 and 0 under `PerQueue` (at most 6.9 to 11.2 ms). On an unshared queue, 0 over 10 ms in every run. A command buffer's GPU start time includes the other queues' work before it. `QueueSharing` (`queue-sharing`), at the device's first join | Command buffers a second on the RTX 5080 Laptop GPU, one-draw command buffers, each thread its own queue, the default against `PerQueue`, runs after a lock hold's first: 8 threads with 3 in flight 50.7k to 54.7k against 27.4k to 28.0k (5 runs each); 8 threads with 1 in flight 47.0k to 50.1k against 13.9k to 14.3k (5); 2 threads with 3 in flight 28.0k to 53.7k against 21.4k to 28.0k (10 each, in turn, the default above `PerQueue` in each pair; no thread's queue marked long), and beside another process's 30 ms command buffers 5.1k to 6.7k against 4.0k to 4.1k (3 each; the host's view marked a thread's queue long in 1 of 3 runs, which then ran at `PerQueue`'s 4.1k); 2 threads with 1 in flight 16.9k to 20.7k against 10.1k to 11.5k (5); one thread over 16 queues in turn 21.7k to 43.3k against 10.2k to 11.1k, over 2,048 20.0k to 39.2k against 10.2k to 11.2k (4). Beside an application whose queue never shared with the compositor (isolation, 300 and 30 dispatches), both 0 over 10 ms | | A chain of `half` additions, subtractions and products on a device without `shaderFloat16` (vk12-floor, SwiftShader, Pascal; capability emulation: the module computes each in `float` and rounds it by the device's `OpQuantizeToF16`): an operation whose flags hold `contract` and `reassoc` and whose result only such operations read is held at `float` precision unrounded, so the chain rounds where a value leaves it (a store, an output, a conversion, a comparison, a call, a phi, a vector move, an operation without both flags), one quantize per exit instead of one per operation (`lower::arith::half_chain`). A device with `shaderFloat16` computes `half` alike under either value. | `half_chains = HalfChainPolicy::AtExits` | `half_chains = HalfChainPolicy::EachOperation`: every operation's result rounded to `half`, as the AIR computes it | The result may differ from the rounded operations' by the roundings the chain skips, each within half a unit in the last place of a `half` at its step, compounded along the chain; a value inside the chain past `half`'s range (65504) stays finite where the rounded operations reach infinity. Within the AIR's flags, which let a compiler regroup and fuse such operations. `FastMathRewrites` (`fast-math-rewrites`) | Not timed. Size on vk12-floor (the fixtures' SPIR-V words, the default against the accurate form): `hfb_filter_bank` 121,270 against 131,766 (1,024 quantizes against 2,464), `grd_half_many_samples` 82,019 against 84,627, `nan_half_fast` 9,808 against 9,832 | -| A texture that samples, reads, renders into it or is written through a shader (`ShaderWrite` or `ShaderAtomic` usage, of texels of 4, 8 or 16 bytes) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages) is a linear image aliasing the pages in place, where the device makes the image (its format and usage linear, at the pages' pitch) and its own check shows that the operations Vulkan lets read and write every byte bound to it leave every byte alone while the CPU writes beside it: the image's first move (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), and for one that renders a render pass's load and store operations and its moves into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` and back, and for one a shader writes a kernel's storage writes of its texels (which of a linear image a driver may widen past a texel), each access checked apart, and each apart for texels that share a line of the device's memory (`nonCoherentAtomSize`, "the size and alignment in bytes that bounds concurrent access to host-mapped device memory") with bytes beside them and for texels that share none (their start, their end and, with bytes between rows, each row's start and end on a line; `in_place::RowEnds`): a byte changed beside texels that share none fails both, one changed beside texels that share one fails those alone (the Iris Xe, ANV, Mesa 26.2.6, whose clear and store, and draws, write back whole the 64-byte line that holds a row's last texels, fails renders, and writes, for rows that end inside a line, a byte between rows changed, and passes both for rows that end on one: a 3840x2160 `BGRA8Unorm` surface's 15360-byte rows are 240 lines each). A deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's rulings (2026-10-26, and 2026-10-27 and 2026-11-07 for render targets and written textures: the GPU works on the caller's pages in place as a Mac's does, whatever a linear image costs it, on a discrete GPU too; `in_place.rs`). The check runs once per driver and driver version (its record named by the driver and the check's own version, not the runtime release), per class of pages, access and row ends, on a thread of its own, its verdicts kept in the shader cache's directory; a texture made before its verdict is a shadow, made without waiting for the check (its rounds take seconds on some devices and builds; `host_texture_shadows_check_pending`), and moves in place once its class's verdicts pass, at the commit of the device's only uncommitted command buffer, with no copy (`host_textures_moved_in_place`), its shadow's image freed once the command buffer that took the move completed (`host_texture_shadows_freed_after_move`), or, where a view made before the move presents it, a shadow made over it holds it as its truth, or the texture is untracked, once those and the texture went. A texture a shader writes of 1- or 2-byte texels (no check stores them), a check that failed or made no image, and a format, usage or pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`, those that render and those a shader writes counted apart in `host_texture_shadows_render_target` and `host_texture_shadows_shader_write`). On a discrete GPU a `Shared` texture and an IOSurface's are in place too, read across the bus, never copied to the device's memory for speed; a `Managed` texture over a no-copy buffer's bytes that only samples or reads, over memory that carries a log of its writes, is a device copy instead (`WorkCounts::device_copy_textures`), the GPU's copy of the two Metal keeps of a `Managed` resource on a Mac with a discrete GPU, its copies in only the rows the log reports changed. | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each, for an image that reads and one that renders (its pass a clear at load and a store, then a draw over its last column in a pass that loads and stores it; a resolve into it is not among the rounds), the CPU writing beside the texels sweep after sweep until each step completed, so that a device that writes back bytes it read beside them, wherever in the step, puts back an older value the check finds, and, for one a shader writes, of 4, 8 and 16-byte texels, rows apart (of widths no multiple of 4 and odd heights among them) or tight, and 1920x1080, each texel stored by a kernel through an unsigned-integer view (a program's atomics, and its stores through a float view, are not among the rounds); a driver whose operations changed a byte outside every round's window would undo a CPU write made meanwhile. Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer, and a render target's shadow copies it in, keeps it and merges it back at each render pass instance | +| A texture that samples, reads, renders into it or is written through a shader (`ShaderWrite` or `ShaderAtomic` usage, of texels of 4, 8 or 16 bytes) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages) is a linear image aliasing the pages in place, where the device makes the image (its format and usage linear, at the pages' pitch) and its own check shows that the operations Vulkan lets read and write every byte bound to it leave every byte alone while the CPU writes beside it: the image's first move (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), and for one that renders a render pass's load and store operations and its moves into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` and back, and for one a shader writes a kernel's storage writes of its texels (which of a linear image a driver may widen past a texel), each access checked apart, and each apart for texels that share a line of the device's memory (`nonCoherentAtomSize`, "the size and alignment in bytes that bounds concurrent access to host-mapped device memory") with bytes beside them and for texels that share none (their start, their end and, with bytes between rows, each row's start and end on a line; `in_place::RowEnds`): a byte changed beside texels that share none fails both, one changed beside texels that share one fails those alone (the Iris Xe, ANV, Mesa 26.2.6, whose clear and store, and draws, write back whole the 64-byte line that holds a row's last texels, fails renders, and writes, for rows that end inside a line, a byte between rows changed, and passes both for rows that end on one: a 3840x2160 `BGRA8Unorm` surface's 15360-byte rows are 240 lines each). A kernel's writes of a texture over a buffer's rows (no IOSurface plane's) whose rows, each to its pitch, start and end on a line, its buffer holding the last row to its pitch, take a verdict of their own from the same rounds, which a round that changed only bytes of its rows' padding (after a row's last texel, before its pitch, the last row's included) passes (`in_place::Padding`, `Access::BufferWrites`): Metal leaves those bytes to the GPU there (an Intel UHD Graphics 630 under macOS 26.7.1 wrote older values back over the CPU's writes to them under a kernel's writes of a texture over a buffer, the last row's included, where an M3 Max under macOS 27.0.1 and a Radeon Pro 5300M kept them, and all three kept them under draws, clears and stores and over IOSurfaces; `crates/metal2vulkan-conformance/probes/row_padding_writes.m`), and the rule follows the x86 Macs' envelope (docs/API.md, section 10, **Kernels**), so the Iris Xe's written textures over a buffer take the image in place whatever their rows' ends. A deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's rulings (2026-10-26, and 2026-10-27 and 2026-11-07 for render targets and written textures: the GPU works on the caller's pages in place as a Mac's does, whatever a linear image costs it, on a discrete GPU too; `in_place.rs`). The check runs once per driver and driver version (its record named by the driver and the check's own version, not the runtime release), per class of pages, access and row ends, on a thread of its own, its verdicts kept in the shader cache's directory; a texture made before its verdict is a shadow, made without waiting for the check (its rounds take seconds on some devices and builds; `host_texture_shadows_check_pending`), and moves in place once its class's verdicts pass, at the commit of the device's only uncommitted command buffer, with no copy (`host_textures_moved_in_place`), its shadow's image freed once the command buffer that took the move completed (`host_texture_shadows_freed_after_move`), or, where a view made before the move presents it, a shadow made over it holds it as its truth, or the texture is untracked, once those and the texture went. A texture a shader writes of 1- or 2-byte texels (no check stores them), a check that failed or made no image, and a format, usage or pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`, those that render and those a shader writes counted apart in `host_texture_shadows_render_target` and `host_texture_shadows_shader_write`). On a discrete GPU a `Shared` texture and an IOSurface's are in place too, read across the bus, never copied to the device's memory for speed; a `Managed` texture over a no-copy buffer's bytes that only samples or reads, over memory that carries a log of its writes, is a device copy instead (`WorkCounts::device_copy_textures`), the GPU's copy of the two Metal keeps of a `Managed` resource on a Mac with a discrete GPU, its copies in only the rows the log reports changed. | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each, for an image that reads and one that renders (its pass a clear at load and a store, then a draw over its last column in a pass that loads and stores it; a resolve into it is not among the rounds), the CPU writing beside the texels sweep after sweep until each step completed, so that a device that writes back bytes it read beside them, wherever in the step, puts back an older value the check finds, and, for one a shader writes, of 4, 8 and 16-byte texels, rows apart (of widths no multiple of 4 and odd heights among them) or tight, and 1920x1080, each texel stored by a kernel through an unsigned-integer view (a program's atomics, and its stores through a float view, are not among the rounds); a driver whose operations changed a byte outside every round's window would undo a CPU write made meanwhile. A kernel's writes of a texture over a buffer whose padding is free may change that padding, as an x86 Mac's GPU's do (above). Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer, and a render target's shadow copies it in, keeps it and merges it back at each render pass instance | | A render or compute state's creation hands the driver's making of its predicted pipeline (`pipeline/predicted.rs`, `pipeline/dispatch_making.rs`) to the runtime's pool, kept by the state as a draw's or dispatch's making is, and waits for it `pipeline_creation_wait` at most; a committed command buffer's recordings wait until its commit plus `pipeline_commit_wait` at most, one deadline its commands share, for its draws' and dispatches' (a compute encoder's, a render pass's tile dispatches) pipelines still being made (the scheduler wakes at the bound, `StepWaits::until`), an execution's replayed draws (`render/pending.rs`) among them, whose pipelines the commit's settle hands to the pool (a device replay's, one recording for every command, waits until made under either value), then record each such command as nothing: a draw's barriers and visibility query, a dispatch's barrier (a tile dispatch's copies into its scratch and back), no draw or dispatch, the command buffer running on without error. The making goes on, and the command buffers after it draw and dispatch with the pipeline once made. Metal compiles inside `newRenderPipelineState`, so no draw of a made state waits or is dropped; a host that creates a state inside a command buffer's encoding (the consumer creates a guest's state at an execution's first lookup of it) held that execution through the driver's whole compile: 11.59 s inside one execution on an M2 Pro (MoltenVK 1.4.2, a cold Metal compiler service; a sample of such a stall finds the compile's thread waiting in `MVKMetalCompiler::compile` for Metal's compiler), past the guest's 10 s FIFO check, which ended the guest's task. Each bound is 4.5 s: a creation and a commit may fall in one step of the guest's FIFO (a task's jobs run one after another, and a draw's own variant waits under its command buffer's bound), and no runtime call waits for both, so one step waits 9 s at most for makings, under that 10 s check. A creation waits on no command buffer's deadline and a `commit` on no creation's; a `commit` waits until its own deadline at most (it records there what it can, an execution of render commands the CPU writes among them), every other recording on the scheduler's thread, a host step's on one of the steps' threads. Made until made under either value, in the call that makes them: a draw that records nothing, one in a pass of custom sample positions and one recorded again into another instance of its pass (each in the draw's call or an execution's replay), a device replay's draws (in its `commit`), and a failed making made again (`PipelineWaitPolicy`'s docs). The runtime's: no pipeline differs. | `pipeline_waits = PipelineWaitPolicy::Bounded`, `pipeline_creation_wait = 4.5 s`, `pipeline_commit_wait = 4.5 s` | `pipeline_waits = PipelineWaitPolicy::Exact`: the creation makes its predicted pipeline before it returns (a render state's first key on its own thread, the rest on the pool, joined; a compute state's on its own thread), an execution's settle makes its replayed draws' pipelines at the commit, and a command buffer waits for each draw's and dispatch's pipeline until it is made | A draw whose pipeline was still being made `pipeline_commit_wait` after its command buffer's commit renders nothing in that command buffer (only there: later ones draw it), where Metal's renders: content drawn once (a layer, a glyph cache) stays without it until redrawn. A creation returns after `pipeline_creation_wait` at most with its making in flight (`WorkCounts::creations_left_making`). `DrawDroppedStillMaking` (`draw-dropped-still-making`), at each such draw where `DeviceOptions::announce_each` asks, else once per device; `CommandBuffer::dropped_draw` names the first with `VK_TIMEOUT`; `WorkCounts::draws_dropped_still_making`; `deferred_calls::a_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` and `under_the_exact_wait_a_held_making_holds_its_command_buffer_until_it_lands`. A dispatch whose pipeline was still being made then writes nothing in that command buffer, where Metal's runs: `DispatchDroppedStillMaking` (`dispatch-dropped-still-making`), `WorkCounts::dispatches_dropped_still_making`, the first named by `dropped_draw`; `deferred_calls::a_dispatch_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing`, `a_compute_state_s_creation_waits_its_bound_for_its_predicted_making` and `a_replayed_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` | No GPU cost. The exact form holds the creating thread, and the command buffer, for the whole compile: up to 11.59 s on the M2 Pro's cold boot (that boot's 2,483 render state creations, translation included: 300 over 16 ms, 151 over 100 ms, 14 over 250 ms, 3 over 1 s, the longest 11.59 s, 5.82 s and 1.17 s), where the default holds a creation for 4.5 s at most and a command buffer for 4.5 s from its commit, which drops the draws of the compiles that outlast those (2 of that boot's 2,483 were over 4.5 s) for the command buffers committed before they land; bounds of 1 s dropped 39 draws in a cold boot on the M2 Pro, and the guest's menu bar, drawn once, stayed half drawn | | A line Apple's `setLineWidth:` widens (`w' = floor(16 w) / 16`, other than 1), and a triangle's edge in fill mode `Lines`, is drawn by the device's own lines at `w'` wherever it draws that width (`wideLines`, `w'` in `lineWidthRange` and above 0), where Metal draws the parallelogram Vulkan's non-strict wide lines may be (`render/line_width.rs`). They are exactly it on a non-strict device whose wide lines are parallelograms (`strictLines` unset, `nonStrictWideLinesUseParallelogram` set) at a width above 1 on its `lineWidthGranularity`, unannounced there; elsewhere they differ: a strict device's rectangle with square ends (lavapipe, NVIDIA), lines Vulkan does not state as parallelograms (ANV, and every width below 1), a width rounded to the granularity. A mesh draw's lines and edges and a tessellated patch draw's edges take the device's lines under either value, the band not drawing them (at the nearest width they draw where they do not draw `w'`, announced `lines-at-nearest-width`: a known gap below). The runtime's: no pipeline's code differs. | `wide_lines = WideLinePolicy::Device` | `wide_lines = WideLinePolicy::Exact`: a draw of lines or edges the device's lines draw otherwise than Metal is the pipeline's band variant (`VariantKey::line_band`, `pipeline::link::band`) on a device with `tessellationShader` (the device's lines where it has none, or where the translator refuses the state's band or the draw's): two triangles over each line's parallelogram, and each triangle's three edges' parallelograms facing as the triangle, through a tessellation control and evaluation stage; every other width other than 1 is the band under either value | The lines can cover pixels the parallelogram does not, and miss others, at each end and along each edge: up to half the width past each end (square ends), and a rounded width. `DeviceWideLines` (`device-wide-lines`), at each such draw where `DeviceOptions::announce_each` asks, else once per device; `WorkCounts::device_wide_line_draws`, `line_band_draws`, `nearest_width_line_draws`; `runtime_lane::line_widths` (the band matches Metal's maps of lines and of triangles' edges, their facing, culling, flat inputs, primitive IDs and depth on MoltenVK under both values, which has no `wideLines`; a band of edges under a depth bias is announced `wide-edge-depth-bias`) | Not measured. Expected from the band's form: a second pipeline variant made for each render state that draws such lines or edges (its two synthesized stages), each line tessellated as a patch of two control points into four corners and each triangle as a patch of three into 21 triangles (12 degenerate), and a strip, loop or fan drawn as the list of its primitives | | A blit or fill through a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed (`allowGPUOptimizedContents`, 16 texels or more a side, neither `ShaderWrite` nor `PixelFormatView` usage, one sample, not over a buffer) is the device's copy, which keeps the bytes it moves, on every device: Metal's GPU blit into, out of or between such textures moves the texels through its compression, which writes each 16-bit field's low six bits cleared and the alpha code clamped to `[384, 894]`, and its fill clears the low six bits alone (an Apple M3 Max under macOS 27.0.1, every direction, storage mode, usage and size that decides the compression; CPU copies keep the bytes on Metal too). A pass's draws through such an attachment are the device-gap row below. The runtime's choice: no pipeline differs (`compressed_blit.rs`). | `extended_range_blits = ExtendedRangeBlitPolicy::Kept` | `extended_range_blits = ExtendedRangeBlitPolicy::Canonical`: after a blit writes such a texture's region, or a blit out of one writes a buffer's words, a texture over a buffer's or another texture's, a compute dispatch (`bind::extended_canonical_module`, `extended_canonical.rs`) rewrites the texels it wrote in Metal's encoding: in place in a buffer's bytes, an image's through a scratch buffer, a copy out and back around the dispatch; a fill's texel is encoded before it is written. A buffer whose words the device cannot bind (an offset or pitch off 4 bytes, a region past `maxStorageBufferRange`) and a texture over a buffer whose rows share bytes keep the bytes under either value, announced | Bytes no Metal write left (uploaded, CPU-copied or kernel-written texels: a field's low six bits, an alpha code outside `[384, 894]`) keep what Metal's blit would rewrite; a texel reads the same value either way, its low six bits unread and its alpha read clamped. `ExtendedRangeBitsKept` (`extended-range-bits-kept`), once per device; under `Canonical` not for the blits it makes exact; `runtime_lane::compressed_blits` (both values on MoltenVK), the conformance cases `compressed-blits-bgra10xr` and `compressed-blits-bgra10xr-srgb` | Measured, `Canonical` against `Kept`, on `Private` `BGRA10_XR` textures Metal keeps compressed (the sRGB twin and fills not measured), 256x256 and 2048x2048, one whole-texture blit a command buffer: p50 of 300 blits a run, the two values interleaved in one process, three runs a host. RTX 5080 Laptop (NVIDIA 615.71.09, the command buffer's GPU time): a buffer into the texture 23.5 against 11.5 us and 761 against 244 us from a `Private` buffer, 42 against 30 us and 1,945 against 1,176 us from a `Shared` one; the texture into a `Private` buffer 14.1 against 11.2 us and 287 against 246 us, into a `Shared` one, whose words the dispatch rewrites in system memory, 66 against 27 us and 3,386 against 1,182 us; texture into texture 22.5 against 9.7 us and 630 against 80 us. Apple M3 Max (MoltenVK 1.4.2, whose GPU times are the host's, so per blit of 16 in one command buffer), the same blits: into the texture +38 to +57 us and +536 to +548 us, out of it into a buffer +15 us and +84 to +94 us, texture into texture +46 to +48 us and +535 to +541 us. Every figure is above its `Kept` one in every run, by more than the runs' spread (under 1 us on the 5080): measurable at both sizes on both hosts. Into an image a blit adds a copy out into a scratch buffer of the region's size, the dispatch, a copy back and the barriers between them; into a buffer the dispatch and a barrier. The scratch is made without zeros, since the copy out writes every byte the dispatch and the copy back read; the figures above were taken while it was zeroed first, by a command buffer of its own (a fill on the 5080, a copy on MoltenVK). CPU from the command buffer's making through its commit, a blit alone: +1 to +3 us on the M3 Max, +1 to +127 us on the 5080, whose host other builds loaded; 16 blits into 2048x2048 images in one command buffer hold 16 scratch buffers of 32 MiB, and encoding each costs 141 to 165 us (5080) and 286 to 356 us (M3 Max), new memory blocks among it, against 2 to 6 us under `Kept`. Nothing for a texture Metal keeps uncompressed or of another format |