diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 1f0083568..a264cdb6a 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -353,13 +353,15 @@ the record the pass is making. a long buffer's fresh pages, an image bound to them would start `UNDEFINED`, and Vulkan lets its first move, and a render pass's load and store, rewrite any byte bound to it: by default (`HostPageTexturePolicy::InPlace`) a texture there that samples, reads, renders into it or is - written through a shader (of texels of 4, 8 or 16 bytes) is an image in place wherever the + written through a shader (of texels of 1, 2, 4, 8 or 16 bytes, the narrow ones checked apart) + 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 (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 + writes of texels of a width the check stores none of, one made before the check answered or + whose check did not pass), where the device's linear images cannot hold Metal's layout, and where the rows lie with bytes between them (but over a buffer whose maker declared them unobserved, `BufferDescriptor::padding_unobserved`, below). On a discrete GPU, a `Managed` texture diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 2b029bc60..efa32e221 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -189,14 +189,16 @@ 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, how Metal lays them out from there, and whether their rows' padding is the -/// buffer's own (`in_place::Padding`). +/// first byte, how Metal lays them out from there, whether their rows' padding is the buffer's +/// own (`in_place::Padding`), and the bytes of one texel (whose width picks the check of a +/// shader's writes, `in_place::Access::written`). #[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, + pub(super) texel: u64, } impl InPlaceWatch { diff --git a/crates/metal2vulkan-runtime/src/in_place.rs b/crates/metal2vulkan-runtime/src/in_place.rs index 6abfe2900..043ee7318 100644 --- a/crates/metal2vulkan-runtime/src/in_place.rs +++ b/crates/metal2vulkan-runtime/src/in_place.rs @@ -47,12 +47,15 @@ //! whose check passed, for texels that lie in lines as the texture's do ([`RowEnds::of`], from //! 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. Of a texture +//! writes it (`ShaderWrite` or `ShaderAtomic`, of texels of 1, 2, 4, 8 or 16 bytes, the widths +//! the check's kernel stores: [`STORED_TEXEL_BYTES`]; those of 1 or 2 bytes by a check of their +//! own, [`Access::NarrowWrites`], so a driver's writes of such texels decide none of the wider +//! ones'), 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 +//! padding change ([`Access::BufferWrites`], [`Access::NarrowBufferWrites`]); 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 @@ -153,25 +156,44 @@ pub(crate) enum Access { /// usage never takes it alone: [`in_place`] asks it in the stead of /// [`Writes`](Self::Writes) for such a texture. BufferWrites, + /// As [`Writes`](Self::Writes), of a texture of 1- or 2-byte texels + /// ([`NARROW_TEXEL_BYTES`]), checked apart in rounds of their own that store such texels: a + /// driver may write a narrow texel through a wider access than a 4-byte one's. A usage never + /// takes it alone: [`in_place`] asks it in the stead of [`Writes`](Self::Writes) for such a + /// texture ([`Access::written`]). + NarrowWrites, + /// As [`BufferWrites`](Self::BufferWrites), of a texture of 1- or 2-byte texels: its rounds + /// are those of [`NarrowWrites`](Self::NarrowWrites), but a byte of its rows' padding may + /// change. + NarrowBufferWrites, } /// The bytes of the texels a texture a shader writes may have to be in place: those the check's -/// kernel stores ([`Access::Writes`]; the crate-owned copy-in kernel's unsigned-integer views). -pub(crate) const STORED_TEXEL_BYTES: [u64; 3] = [4, 8, 16]; +/// kernel stores ([`Access::Writes`] and [`Access::NarrowWrites`]; the crate-owned copy-in +/// kernel's unsigned-integer views). +pub(crate) const STORED_TEXEL_BYTES: [u64; 5] = [1, 2, 4, 8, 16]; + +/// The bytes of the texels the check's narrow rounds store ([`Access::NarrowWrites`]), apart +/// from the others' ([`Access::Writes`]). +pub(crate) const NARROW_TEXEL_BYTES: [u64; 2] = [1, 2]; impl Access { /// Every access, in the order the check runs them and the record holds their verdicts. - pub(crate) const ALL: [Access; 4] = [ + pub(crate) const ALL: [Access; 6] = [ Access::Reads, Access::Renders, Access::Writes, Access::BufferWrites, + Access::NarrowWrites, + Access::NarrowBufferWrites, ]; /// 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. None takes - /// [`BufferWrites`](Self::BufferWrites) alone ([`in_place`]). + /// [`BufferWrites`](Self::BufferWrites) or the narrow accesses alone ([`in_place`] asks the + /// one of its texels and padding in the stead of [`Writes`](Self::Writes), + /// [`Access::written`]). 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); @@ -179,19 +201,38 @@ impl Access { Access::Reads => !renders && !writes, Access::Renders => renders, Access::Writes => writes, - Access::BufferWrites => false, + Access::BufferWrites | Access::NarrowWrites | Access::NarrowBufferWrites => false, } } + /// The check of a shader's writes of texels `texel` bytes wide, of a texture whose rows' + /// padding is as `padding` says: [`Writes`](Self::Writes) of texels of 4, 8 or 16 bytes, + /// [`NarrowWrites`](Self::NarrowWrites) of those of 1 or 2 ([`NARROW_TEXEL_BYTES`]), each's + /// form that lets the padding change where it is free; `None` for a width the check's kernel + /// stores none of ([`STORED_TEXEL_BYTES`]). + pub(crate) fn written(texel: u64, padding: Padding) -> Option { + if !STORED_TEXEL_BYTES.contains(&texel) { + return None; + } + Some(match (NARROW_TEXEL_BYTES.contains(&texel), padding) { + (false, Padding::Kept) => Access::Writes, + (false, Padding::Free) => Access::BufferWrites, + (true, Padding::Kept) => Access::NarrowWrites, + (true, Padding::Free) => Access::NarrowBufferWrites, + }) + } + /// 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. + /// order: its own, and of [`Writes`](Self::Writes) and [`NarrowWrites`](Self::NarrowWrites) + /// those of [`BufferWrites`](Self::BufferWrites) and + /// [`NarrowBufferWrites`](Self::NarrowBufferWrites) too, which have no rounds of their 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 => &[], + Access::NarrowWrites => &[Access::NarrowWrites, Access::NarrowBufferWrites], + Access::BufferWrites | Access::NarrowBufferWrites => &[], } } @@ -202,6 +243,8 @@ impl Access { Access::Renders => 1, Access::Writes => 2, Access::BufferWrites => 3, + Access::NarrowWrites => 4, + Access::NarrowBufferWrites => 5, } } @@ -221,6 +264,14 @@ impl Access { "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" } + Access::NarrowWrites => { + "the first move and a kernel's storage writes of the 1- or 2-byte texels of an \ + image a shader writes" + } + Access::NarrowBufferWrites => { + "the first move and a kernel's storage writes of the 1- or 2-byte texels of an \ + image a shader writes over a buffer's rows, beside their padding" + } } } } @@ -397,7 +448,8 @@ pub(crate) enum ShadowCause { /// The device's policy asks the shadow (`HostPageTexturePolicy::Shadow`). Exact, /// Its usage writes it through a shader, and its texels are of a width (the bytes given) the - /// check's kernel stores none of ([`STORED_TEXEL_BYTES`]): no check covers its writes. + /// check's kernel stores none of ([`STORED_TEXEL_BYTES`]): no check covers its writes. Every + /// width a buffer backs (1, 2, 4, 8 and 16 bytes) is stored; this names one outside them. StoreWidth(u64), /// Its class's check for its access, of texels that lie in lines as its own do, has not /// answered yet. @@ -475,8 +527,8 @@ impl ShadowCause { .to_owned(), ShadowCause::StoreWidth(bytes) => format!( "its usage writes it through a shader (ShaderWrite or ShaderAtomic), and the \ - device's check of storage writes stores texels of 4, 8 and 16 bytes, not of \ - {bytes}: no check covers a driver's writes of such texels beside them" + device's check of storage writes stores texels of 1, 2, 4, 8 and 16 bytes, not \ + of {bytes}: no check covers a driver's writes of such texels beside them" ), ShadowCause::CheckPending(class, access, rows) => format!( "the device's check of {} over {}, for {}, has not answered yet", @@ -508,9 +560,11 @@ impl ShadowCause { /// 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). +/// did not pass: for a shader's writes, the verdict of the check of its texels' width and +/// padding ([`Access::written`]): of 1- or 2-byte texels [`Access::NarrowWrites`]', and of a +/// texture whose padding is free [`Access::BufferWrites`]' (or [`Access::NarrowBufferWrites`]'), +/// which passes wherever the one that keeps the padding does (the same rounds give both, and it +/// lets more change). pub(crate) fn in_place( policy: HostPageTexturePolicy, usage: TextureUsage, @@ -520,12 +574,13 @@ pub(crate) fn in_place( if policy == HostPageTexturePolicy::Shadow { return Err(ShadowCause::Exact); } - if Access::Writes.takes(usage) && !STORED_TEXEL_BYTES.contains(&texel) { + let written = Access::written(texel, padding); + if Access::Writes.takes(usage) && written.is_none() { 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, + let access = match (access, written) { + (Access::Writes, Some(written)) => written, (access, _) => access, }; match verdict(class, access, rows) { @@ -538,6 +593,25 @@ pub(crate) fn in_place( Ok(()) } +/// Whether an image in place of a texture of Metal `usage` that renders, over host pages of +/// `class`, its texels of `texel` bytes lying in the device's lines as `rows` says, takes the +/// storage usage too: where no shader writes it by its usage (whose own check covers such +/// writes), and `verdict` passed the check of a shader's writes of texels of its width that keeps +/// every byte beside them ([`Access::written`] of [`Padding::Kept`]: a render target's rows keep +/// their padding). A draw that reads such a texture through a snapshot fetches it in the pixel +/// interlock through that usage (`render/snapshot.rs`), and with it a shader's writes reach the +/// texels in place, as the check's writes do. +pub(crate) fn storable( + usage: TextureUsage, + (class, rows, texel): (PagesClass, RowEnds, u64), + mut verdict: impl FnMut(PagesClass, Access, RowEnds) -> Verdict, +) -> bool { + Access::Renders.takes(usage) + && !Access::Writes.takes(usage) + && Access::written(texel, Padding::Kept) + .is_some_and(|written| verdict(class, written, rows) == Verdict::Passed) +} + /// A device's check verdicts (`DeviceShared::in_place`): one per class, access and row ends /// ([`VERDICTS`]), and whether its check started and settled. pub(crate) struct InPlaceChecks { @@ -677,7 +751,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 = 8; +pub(crate) const CHECK_VERSION: u32 = 9; /// A record's first bytes. const MAGIC: [u8; 8] = *b"M2VINPL\0"; @@ -754,7 +828,7 @@ pub(crate) fn record_name(identity: &DriverIdentity) -> String { /// magic 8 bytes "M2VINPL\0" /// version u32 CHECK_VERSION /// identity 32 bytes DriverIdentity::digest -/// verdicts 24 bytes one per class, access and row ends, VERDICTS' order (verdict_index) +/// verdicts 36 bytes one per class, access and row ends, VERDICTS' order (verdict_index) /// checksum 32 bytes SHA-256 of every byte before it /// ``` /// @@ -951,12 +1025,14 @@ impl Device { /// (`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`), 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. + /// writes: Passed`, `in_place::Padding`), then the same two for one of 1- or 2-byte texels + /// (`Pointer narrow writes: Passed`, `Pointer narrow buffer writes: Passed`), each for texels + /// that share a line with bytes beside them (`RowEnds::InLines`); then the same eighteen 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`, `Pointer narrow writes, rows on lines: Passed`, `Pointer narrow 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() @@ -976,6 +1052,10 @@ impl Device { Access::Renders => format!("{class:?} renders{lines}: {verdict:?}"), Access::Writes => format!("{class:?} writes{lines}: {verdict:?}"), Access::BufferWrites => format!("{class:?} buffer writes{lines}: {verdict:?}"), + Access::NarrowWrites => format!("{class:?} narrow writes{lines}: {verdict:?}"), + Access::NarrowBufferWrites => { + format!("{class:?} narrow 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 111bb0ccf..a0f6f7ae8 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -50,7 +50,12 @@ //! class runs every shape of [`STORE_SHAPES`] (texels of 4, 8 and 16 bytes, the widths the //! kernel's views store, rows apart, some of a width no multiple of 4 and an odd height, so that //! 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 +//! after another, and 1920x1080 at 4 bytes) [`ROUNDS`] times. Texels of 1 and 2 bytes +//! ([`Access::NarrowWrites`]) take rounds of their own, of [`NARROW_STORE_SHAPES`], through the +//! kernel's `R8_UINT` and `R16_UINT` views (each texel a word of its buffers): a driver may +//! store such a texel through an access wider than it, a word or more, over the texels beside +//! it and past a row's end, which no wider texel's store shows, so their verdicts are their own +//! and a byte one of their rounds changed fails no verdict of wider texels'. 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 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 @@ -206,6 +211,56 @@ pub(crate) const SHAPES: [Shape; 15] = [ shape(PixelFormat::BGRA8Unorm, 4, 3840, 2160, 15360), ]; +/// The shapes the check of storage writes of 1- and 2-byte texels writes +/// ([`Access::NarrowWrites`]), each with the view its kernel stores through (`R8_UINT`, `R16_UINT`: +/// `in_place::NARROW_TEXEL_BYTES`), as [`STORE_SHAPES`] lays its own out: rows one after another, +/// rows apart at the 256-byte pitch of the guests' 1- and 2-byte textures a shader writes (32x32 +/// `R8Unorm` and `A8Unorm` among them), of widths whose rows end inside a 4-byte word and odd +/// heights, so that a driver's store of a word or a block past a row's or the image's end shows, +/// at the 16-byte pitch a driver that lays rows tight lays them at and at the 64-byte pitch of one +/// that lays them at the next multiple of 64 (run as there: [`Shape::runs`]), and one 1024x1024 +/// surface of 1-byte texels, last, the size of the largest such guest texture. A shape the device +/// makes no image of in place, or no dispatch over (a device without +/// `shaderStorageImageExtendedFormats`, whose kernels of those views it refuses), is skipped. +pub(crate) const NARROW_STORE_SHAPES: [(Shape, ShadowTexelView); 9] = [ + ( + shape(PixelFormat::R8Uint, 1, 256, 16, 256), + ShadowTexelView::R8Uint, + ), + ( + shape(PixelFormat::R16Uint, 2, 128, 16, 256), + ShadowTexelView::R16Uint, + ), + ( + shape(PixelFormat::R8Uint, 1, 61, 37, 256), + ShadowTexelView::R8Uint, + ), + ( + shape(PixelFormat::R16Uint, 2, 45, 29, 256), + ShadowTexelView::R16Uint, + ), + ( + tight(PixelFormat::R8Uint, 1, 101, 51, 112), + ShadowTexelView::R8Uint, + ), + ( + tight(PixelFormat::R16Uint, 2, 33, 17, 80), + ShadowTexelView::R16Uint, + ), + ( + tight(PixelFormat::R8Uint, 1, 101, 51, 128), + ShadowTexelView::R8Uint, + ), + ( + tight(PixelFormat::R16Uint, 2, 33, 17, 128), + ShadowTexelView::R16Uint, + ), + ( + shape(PixelFormat::R8Uint, 1, 1024, 1024, 1024), + ShadowTexelView::R8Uint, + ), +]; + /// The shapes the check of storage writes writes ([`Access::Writes`]), each with the view its /// kernel stores through: texels of 4, 8 and 16 bytes (`in_place::STORED_TEXEL_BYTES`, the /// crate-owned copy-in kernel's views), with rows one after another and with bytes between them @@ -468,8 +523,9 @@ fn word_overwritten(device: &Device) -> bool { /// ([`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 +/// free ([`Shape::padding`]), fails [`Access::Writes`] (or [`Access::NarrowWrites`]) for its row +/// ends and counts for [`Access::BufferWrites`] (or [`Access::NarrowBufferWrites`]) 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> { @@ -482,7 +538,11 @@ fn check_class(device: &Device, class: PagesClass, access: Access) -> Option None, + Access::Reads + | Access::Writes + | Access::BufferWrites + | Access::NarrowWrites + | Access::NarrowBufferWrites => None, Access::Renders => { let made = exit_guard::enter().map(|_busy| { let queue = device.new_command_queue_now()?; @@ -494,12 +554,15 @@ fn check_class(device: &Device, class: PagesClass, access: Access) -> Option>() + }; let mut shapes: Vec<(Shape, Option)> = match access { - Access::Writes | Access::BufferWrites => STORE_SHAPES - .map(|(shape, texel)| (shape, Some(texel))) - .to_vec(), + Access::Writes | Access::BufferWrites => stored(&STORE_SHAPES), + Access::NarrowWrites | Access::NarrowBufferWrites => stored(&NARROW_STORE_SHAPES), Access::Reads | Access::Renders => SHAPES.map(|shape| (shape, None)).to_vec(), }; shapes.sort_by_key(|(shape, _)| shape.rows(line) != RowEnds::OnLines); @@ -566,6 +629,9 @@ fn check_class(device: &Device, class: PagesClass, access: Access) -> Option { "the first move or a kernel's storage writes" } + Access::NarrowWrites | Access::NarrowBufferWrites => { + "the first move or a kernel's storage writes of 1- or 2-byte texels" + } }; let lines = match rows { RowEnds::InLines => "", @@ -619,9 +685,10 @@ impl Tally { /// 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. + /// row ends of the first that changed any byte failed; then, of [`Access::Writes`] and + /// [`Access::NarrowWrites`], those of [`Access::BufferWrites`] and + /// [`Access::NarrowBufferWrites`], of its rounds that changed no byte but of that padding, + /// those of `changed` failed. pub(crate) fn verdicts( &self, access: Access, @@ -768,8 +835,10 @@ fn store_round( return Round::NotMade; }; // The bytes the kernel stores, row after row, and the part it keeps them in too: buffers - // outside the Metal address space, as the check's are (the module docs). - let row = shape.width * shape.texel; + // outside the Metal address space, as the check's are (the module docs). A texel takes the + // view's words there: a 1- or 2-byte texel a whole word, its bytes low and zero above them. + let held = 4 * u64::from(texel.words()); + let row = shape.width * held; let length = row * shape.height; let buffer = || device.new_buffer_placed(length, ResourceOptions::shared(), AddressPlacement::Outside); @@ -780,18 +849,23 @@ fn store_round( return Round::NotMade; }; for y in 0..shape.height { - let mut to = (y * row) as usize; - for (from, count) in pattern.spans(y * shape.bytes_per_row, row as usize) { - // SAFETY: the source's bytes `to..to + count`, mapped and writable, which nothing else - // uses yet; the pattern's bytes are apart from them. - unsafe { - std::ptr::copy_nonoverlapping( - pattern.stored[from..].as_ptr(), - words.as_ptr().add(to), - count, - ) - }; - to += count; + let from = y * shape.bytes_per_row; + let to = (y * row) as usize; + if held == shape.texel { + // SAFETY: the source's row `to..to + row`, of its `length`, mapped and writable, + // which nothing else uses yet. + unsafe { pattern.store_row(from, row, words, to) }; + continue; + } + for x in 0..shape.width { + let mut word = [0u8; 4]; + for (at, byte) in word.iter_mut().enumerate().take(shape.texel as usize) { + *byte = pattern.stored_at(from + x * shape.texel + at as u64); + } + let at = to + (x * held) as usize; + // SAFETY: the source's 4 bytes from `at`, of its `length`, mapped and writable, which + // nothing else uses yet. + unsafe { std::ptr::copy_nonoverlapping(word.as_ptr(), words.as_ptr().add(at), 4) }; } } let stop = AtomicBool::new(false); @@ -1060,6 +1134,33 @@ impl Pattern { self.bytes[(offset % PERIOD as u64) as usize] } + /// The byte a kernel stores at `offset` of the window. + fn stored_at(&self, offset: u64) -> u8 { + self.stored[(offset % PERIOD as u64) as usize] + } + + /// Copy the bytes a kernel stores at the window's `length` bytes from `offset` into `to`'s + /// bytes from `at`, a period's run at a time. + /// + /// # Safety + /// + /// `to`'s bytes `at..at + length` are mapped and writable, and nothing else uses them + /// meanwhile. + unsafe fn store_row(&self, offset: u64, length: u64, to: NonNull, mut at: usize) { + for (from, count) in self.spans(offset, length as usize) { + // SAFETY: the caller's bytes `at..at + count` of `to`, within its contract's; the + // pattern's bytes are apart from them. + unsafe { + std::ptr::copy_nonoverlapping( + self.stored[from..].as_ptr(), + to.as_ptr().add(at), + count, + ) + }; + at += count; + } + } + /// The window's bytes `offset..offset + length` as runs within one period, in order: each /// run's first place in the period and its length. fn spans(&self, offset: u64, length: usize) -> impl Iterator { diff --git a/crates/metal2vulkan-runtime/src/tests/in_place.rs b/crates/metal2vulkan-runtime/src/tests/in_place.rs index 745e1e82d..764832d8b 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place.rs @@ -3,14 +3,18 @@ //! //! - **The decision.** Under `HostPageTexturePolicy::Shadow` every texture is a shadow, the check //! never asked; under `InPlace` a texture a shader writes (`ShaderWrite`, `ShaderAtomic`, -//! `Unknown`, whatever else it holds) of texels the check's kernel stores none of (1 or 2 -//! bytes) is one counted by its width, the check never asked; and every other texture is tried -//! in place exactly where its class's check passed, for texels that lie in lines as its own do, -//! 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. 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. +//! `Unknown`, whatever else it holds) of texels of a width the check's kernel stores none of +//! (none of 1, 2, 4, 8 and 16 bytes) is one counted by its width, the check never asked; and +//! every other texture is tried in place exactly where its class's check passed, for texels +//! that lie in lines as its own do, for each access it takes (one that renders, +//! `RenderTarget`, its render check; one a shader writes, the storage check of its texels' +//! width, those of 1 or 2 bytes apart from the rest; 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. 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. A texture that renders takes the storage usage too exactly where no +//! shader writes it by its usage and the storage check of its texels' width that keeps every +//! byte passed. //! - **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 @@ -28,12 +32,13 @@ //! - **A waiter** for one verdict wakes as that verdict is given, or as the check settles. use crate::in_place::{ - decode, encode, in_place, record_name, verdict_index, Access, DriverIdentity, InPlaceChecks, - Padding, PagesClass, RowEnds, ShadowCause, Verdict, CHECK_VERSION, STORED_TEXEL_BYTES, - VERDICTS, + decode, encode, in_place, record_name, storable, verdict_index, Access, DriverIdentity, + InPlaceChecks, Padding, PagesClass, RowEnds, ShadowCause, Verdict, CHECK_VERSION, + NARROW_TEXEL_BYTES, STORED_TEXEL_BYTES, VERDICTS, }; use crate::in_place_check::{ - verdicts, Bytes, Due, Pattern, Round, Shape, Tally, Written, SHAPES, STORE_SHAPES, + verdicts, Bytes, Due, Pattern, Round, Shape, Tally, Written, NARROW_STORE_SHAPES, SHAPES, + STORE_SHAPES, }; use crate::linear_plan::BufferLayout; use metal2vulkan::device::HostPageTexturePolicy; @@ -71,11 +76,23 @@ fn unchecked_width(usage: TextureUsage, texel: u64) -> Option { } } -/// 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, padding: Padding) -> Vec { +/// The check of a shader's writes of texels of `texel` bytes, a width the check's kernel stores, +/// of a texture whose rows' padding is as `padding` says: those of 1 or 2 bytes apart from the +/// rest, each in the form that lets the padding change where it is free. +fn writes_of(texel: u64, padding: Padding) -> Access { + match (NARROW_TEXEL_BYTES.contains(&texel), padding) { + (false, Padding::Kept) => Access::Writes, + (false, Padding::Free) => Access::BufferWrites, + (true, Padding::Kept) => Access::NarrowWrites, + (true, Padding::Free) => Access::NarrowBufferWrites, + } +} + +/// The accesses whose checks `usage` asks of a texture of texels of `texel` bytes whose rows' +/// padding is as `padding` says, in their order: renders where it holds `RenderTarget`, writes +/// where it holds `ShaderWrite` or `ShaderAtomic` (of its texels' width, [`writes_of`]), reads +/// where it holds neither. +fn accesses_of(usage: TextureUsage, padding: Padding, texel: u64) -> Vec { let renders = usage.contains(TextureUsage::RENDER_TARGET); let writes = usage.intersects(TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC); let mut accesses = Vec::new(); @@ -86,14 +103,18 @@ fn accesses_of(usage: TextureUsage, padding: Padding) -> Vec { accesses.push(Access::Renders); } if writes { - accesses.push(match padding { - Padding::Free => Access::BufferWrites, - Padding::Kept => Access::Writes, - }); + accesses.push(writes_of(texel, padding)); } accesses } +/// The answer after `verdict` in [`ANSWERS`]' order (the last's, the first): the narrow checks' +/// answers in the decision's test, so that each differs from its wider twin's. +fn next(verdict: Verdict) -> Verdict { + let at = ANSWERS.iter().position(|&answer| answer == verdict); + ANSWERS[(at.unwrap_or(0) + 1) % ANSWERS.len()] +} + #[test] fn the_decision_takes_a_texture_whose_class_passed_each_of_its_accesses() { let mut usages = each_usage(); @@ -112,13 +133,15 @@ fn the_decision_takes_a_texture_whose_class_passed_each_of_its_accesses() { | TextureUsage::SHADER_ATOMIC, ); usages.push(TextureUsage::empty()); - // Each access's verdict, every one of them with every other. + // Each access's verdict, every one of them with every other; the narrow checks' each the + // answer after its wider twin's, so that each takes every answer and differs from the twin's. let mut answers = Vec::new(); for reads in ANSWERS { for renders in ANSWERS { for writes in ANSWERS { for buffer_writes in ANSWERS { - answers.push([reads, renders, writes, buffer_writes]); + let narrow = [next(writes), next(buffer_writes)]; + answers.push([reads, renders, writes, buffer_writes, narrow[0], narrow[1]]); } } } @@ -130,7 +153,9 @@ fn the_decision_takes_a_texture_whose_class_passed_each_of_its_accesses() { }); for (class, rows, padding) in each { for &usage in &usages { - for texel in [1u64, 2, 4, 8, 16] { + // A 3-byte texel, of no format a buffer backs, stands for a width the kernel stores + // none of. + for texel in [1u64, 2, 3, 4, 8, 16] { for answer in &answers { let of = |access: Access| answer[access.index()]; // Shadow: always the exact form, the check never asked. @@ -156,7 +181,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, padding); + let accesses = accesses_of(usage, padding, texel); let first = accesses.iter().position(|&a| of(a) != Verdict::Passed); match first { None => (Ok(()), accesses), @@ -177,6 +202,29 @@ fn the_decision_takes_a_texture_whose_class_passed_each_of_its_accesses() { format!("{class:?} {rows:?} {padding:?} {usage:?} {texel} {answer:?}"); assert_eq!(decided, expected, "{case}"); assert_eq!(*asked.borrow(), due, "{case}"); + // The storage usage of a texture that renders: the check of its texels' + // width that keeps every byte, where no shader writes it by its usage. + let renders = usage.contains(TextureUsage::RENDER_TARGET); + let writes = + usage.intersects(TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC); + let stores = STORED_TEXEL_BYTES.contains(&texel); + let due = renders + && !writes + && stores + && of(writes_of(texel, Padding::Kept)) == Verdict::Passed; + let asked = std::cell::RefCell::new(Vec::new()); + let takes = + storable(usage, (class, rows, texel), |of_class, access, of_rows| { + assert_eq!((of_class, of_rows), (class, rows)); + asked.borrow_mut().push(access); + of(access) + }); + assert_eq!(takes, due, "storable: {case}"); + let wanted = match renders && !writes && stores { + true => vec![writes_of(texel, Padding::Kept)], + false => Vec::new(), + }; + assert_eq!(*asked.borrow(), wanted, "storable: {case}"); } } } @@ -203,6 +251,9 @@ fn every_shadow_cause_names_itself() { ShadowCause::CheckFailed(PagesClass::Pointer, Access::Renders, on), ShadowCause::CheckFailed(PagesClass::Pointer, Access::BufferWrites, inside), ShadowCause::CheckPending(PagesClass::Fresh, Access::BufferWrites, on), + ShadowCause::CheckFailed(PagesClass::Pointer, Access::NarrowWrites, inside), + ShadowCause::Unchecked(PagesClass::DmaBuf, Access::NarrowBufferWrites, on), + ShadowCause::StoreWidth(3), ]; let words: Vec = causes.iter().map(ShadowCause::words).collect(); for (at, word) in words.iter().enumerate() { @@ -214,6 +265,9 @@ fn every_shadow_cause_names_itself() { } assert!(words[0].contains("HostPageTexturePolicy::Shadow")); assert!(words[1].contains("ShaderWrite") && words[1].contains("not of 2")); + assert!(words[16].contains("1- or 2-byte texels") && !words[16].contains("over a buffer")); + assert!(words[17].contains("1- or 2-byte texels") && words[17].contains("over a buffer")); + assert!(words[18].contains("1, 2, 4, 8 and 16 bytes, not of 3")); assert!(words[2].contains("not answered") && words[3].contains("not answered")); assert!(words[3].contains("render pass")); assert!(words[4].contains("dma-bufs")); @@ -434,7 +488,11 @@ fn shapes_at_a_driver_s_own_pitch_run_only_where_none_of_their_texel_size_was_ma tried.iter().filter(at).count() }; let store: Vec = STORE_SHAPES.iter().map(|(shape, _)| *shape).collect(); - for shapes in [SHAPES.to_vec(), store] { + let narrow: Vec = NARROW_STORE_SHAPES + .iter() + .map(|(shape, _)| *shape) + .collect(); + for shapes in [SHAPES.to_vec(), store, narrow] { let tight = |multiple| { shapes .iter() @@ -514,16 +572,19 @@ fn texels_share_no_line_exactly_where_each_gap_starts_and_ends_on_one() { shape.bytes_per_row == pitch && shape.rows(line) == inside }; assert!(SHAPES.iter().any(at), "{multiple}-byte rows"); - assert!( - STORE_SHAPES.iter().any(|(shape, _)| at(shape)), - "{multiple}-byte rows" - ); + for stored in [&STORE_SHAPES[..], &NARROW_STORE_SHAPES[..]] { + let shapes = stored.iter().map(|(shape, _)| shape); + assert!(shapes.clone().any(at), "{multiple}-byte rows"); + } } // At the 256-byte lines of a device whose atom is that long, two still share none. assert!(rows(256).iter().filter(|&&rows| rows == on).count() >= 2); - // And each row ends has shapes of the check of storage writes. + // And each row ends has shapes of each check of storage writes. for rows in RowEnds::ALL { assert!(STORE_SHAPES.iter().any(|(shape, _)| shape.rows(64) == rows)); + assert!(NARROW_STORE_SHAPES + .iter() + .any(|(shape, _)| shape.rows(64) == rows)); } } @@ -588,7 +649,7 @@ fn rows_padding_is_free_over_a_buffer_s_own_rows_that_end_on_lines() { 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 { + for (shape, _) in STORE_SHAPES.into_iter().chain(NARROW_STORE_SHAPES) { assert_eq!(shape.padding(16), free, "{shape:?}"); let tight16 = shape.tight && shape.bytes_per_row % 64 != 0; let due = match tight16 { @@ -695,6 +756,11 @@ fn a_round_that_changed_padding_alone_fails_only_the_check_of_writes_that_keeps_ tally.verdicts(Access::Writes, None, false), vec![[Failed, Passed], [Passed, Passed]] ); + // The narrow check's rounds answer its own two alike, for 1- and 2-byte texels. + assert_eq!( + tally.verdicts(Access::NarrowWrites, None, false), + vec![[Failed, Passed], [Passed, Passed]] + ); // The other accesses' rounds answer their own verdicts alone. assert_eq!( tally.verdicts(Access::Renders, None, false), @@ -730,3 +796,39 @@ fn a_round_that_changed_padding_alone_fails_only_the_check_of_writes_that_keeps_ vec![[Unchecked, Failed], [Unchecked, Failed]] ); } + +/// Each check of storage writes stores its texels' width through a view of that width: the narrow +/// shapes 1- and 2-byte texels (`R8Uint` through `R8_UINT`, `R16Uint` through `R16_UINT`), each a +/// word of the kernel's buffers, with rows that end inside a word and odd heights among each +/// width's; the others 4, 8 and 16 bytes, each its view's words. Every narrow shape's window fits +/// a class's buffer. +#[test] +fn each_check_of_storage_writes_stores_its_texels_width() { + use metal2vulkan::bind::ShadowTexelView; + use metal2vulkan::metal::PixelFormat; + for (shape, view) in NARROW_STORE_SHAPES { + let due = match shape.texel { + 1 => (PixelFormat::R8Uint, ShadowTexelView::R8Uint), + 2 => (PixelFormat::R16Uint, ShadowTexelView::R16Uint), + other => panic!("a narrow shape of {other}-byte texels"), + }; + assert_eq!((shape.format, view), due, "{shape:?}"); + assert_eq!(view.words(), 1, "{shape:?}"); + assert!(shape.width * shape.height * 4 <= 40 << 20, "{shape:?}"); + } + for (shape, view) in STORE_SHAPES { + assert!(!NARROW_TEXEL_BYTES.contains(&shape.texel), "{shape:?}"); + assert_eq!(4 * u64::from(view.words()), shape.texel, "{shape:?}"); + } + for texel in NARROW_TEXEL_BYTES { + let ends_inside = |(shape, _): &&(Shape, ShadowTexelView)| { + shape.texel == texel + && !(shape.width * shape.texel).is_multiple_of(4) + && shape.height % 2 == 1 + }; + assert!( + NARROW_STORE_SHAPES.iter().any(|shape| ends_inside(&shape)), + "{texel}-byte texels" + ); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/in_place_storage.rs b/crates/metal2vulkan-runtime/src/tests/in_place_storage.rs index 3ac89934d..355acca47 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place_storage.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place_storage.rs @@ -1,8 +1,8 @@ //! A render target over host pages in place (`texture/in_place_image.rs`) takes the storage usage //! a snapshot's fetch of it in the pixel interlock reads through (`render/snapshot.rs`) only where -//! the device's check passed for a shader's writes over such pages, and for a texel the check's -//! kernel stores: with that usage a shader writes its texels in place. Its image's plan says which -//! usages it took. +//! the device's check passed for a shader's writes over such pages of texels of its width (those +//! of 1 byte checked apart from those of 4 and 8): with that usage a shader writes its texels in +//! place. Its image's plan says which usages it took. //! //! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. The device's shader cache is a fresh @@ -10,7 +10,7 @@ use super::blit_holds::{device, over_host, Host, Scratch}; use crate::framebuffer_fetch::through_storage; -use crate::in_place::Access; +use crate::in_place::{Access, Padding}; use crate::TextureDescriptor; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use metal2vulkan::vk::ImageUsageFlags; @@ -54,6 +54,7 @@ fn a_render_target_in_place_takes_the_storage_usage_only_where_writes_passed() { (PixelFormat::RGBA8Unorm, 4), (PixelFormat::BGRA8Unorm, 4), (PixelFormat::RGBA16Float, 8), + (PixelFormat::R8Unorm, 1), ] { let mut descriptor = TextureDescriptor::texture_2d(format, SIDE, SIDE, false); descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; @@ -73,8 +74,10 @@ fn a_render_target_in_place_takes_the_storage_usage_only_where_writes_passed() { passed(Access::Renders, SIDE * texel), "{format:?}: in place where the check did not pass for render targets" ); + let written = Access::written(texel, Padding::Kept); + let writes = written.is_some_and(|written| passed(written, SIDE * texel)); assert!( - !storage || (passed(Access::Writes, SIDE * texel) && feedback && fetches), + !storage || (writes && feedback && fetches), "{format:?}: the storage usage where the check did not pass for a shader's \ writes, or with no fetch to read through it" ); diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index ff18b144a..58306d1d0 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -277,6 +277,8 @@ mod multisample_buffer_layouts; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod nan_signs; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod narrow_writes_device; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod neutral_zeros_shared; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod no_copy_lies; diff --git a/crates/metal2vulkan-runtime/src/tests/narrow_writes_device.rs b/crates/metal2vulkan-runtime/src/tests/narrow_writes_device.rs new file mode 100644 index 000000000..f59203e8b --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/narrow_writes_device.rs @@ -0,0 +1,294 @@ +//! Textures of 1- and 2-byte texels a shader writes over host pages, in place where the device's +//! check passed for such writes (`in_place::Access::NarrowWrites`): the x86 macOS guests' 32x32 +//! `R8Unorm` and `A8Unorm` textures at 256 bytes a row, and the same shape of `RG8Unorm` and +//! `R16Unorm`, of `ShaderRead` and `ShaderWrite` usage, over a no-copy buffer of host pages from +//! its first byte. Before the check stored such texels every one was a shadow +//! (`host_texture_shadows_store_width`). +//! +//! - **The narrow verdicts.** Once the device's check settled, its report answers the narrow +//! accesses of every class and row ends (`Pointer narrow writes: ...`), none pending. Printed +//! with the check's time. +//! - **The path its verdict gives.** Each texture takes the verdict of its class, its texels' row +//! ends and its rows' padding for 1- and 2-byte texels (`narrow buffer writes` where its padding +//! is free, `in_place::Padding`): in place where it passed (`vk_image` answers one; +//! `host_textures_in_place`, `host_textures_in_place_written`), or a shadow its refusal counts +//! where the device makes no image at its pitch; a shadow counted by the check's answer where it +//! did not pass; never one counted by its width. Its placement query, asked before, answers in +//! place exactly where it is. +//! - **Writes reach the bytes.** A kernel then writes a color at every texel (`a8r_write`), each +//! format's of 1.0 and 0.0 alone, which every device converts exactly (an `A8Unorm` texture's +//! alpha 1.0 and red 0.0, so a write of red reads 0): every texel of the pages holds the +//! format's bytes of it, the bytes past the last row the pattern, and the bytes between the +//! rows the pattern where the padding is kept. Where it is free the writes may change it, as an +//! x86 Mac's GPU does; printed, with whether they kept it. +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects; the device's shader cache is a fresh +//! directory, so its check runs. Printed (`NARROW-WRITES`). + +use super::blit_holds::{device, over_host, Host, Scratch, BYTES, WAIT}; +use super::encoder_holds::library; +use crate::in_place::{Access, Padding, PagesClass, RowEnds, Verdict}; +use crate::linear_plan::BufferLayout; +use crate::{ + Buffer, ComputePipelineState, PipelineOptions, Size, Texture, TextureDescriptor, + TexturePlacement, WorkCounts, +}; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use std::sync::atomic::AtomicUsize; +use std::sync::Arc; +use std::time::Duration; + +/// The guests' shape: width, height, and bytes a row. +const WIDTH: u64 = 32; +const HEIGHT: u64 = 32; +const PITCH: u64 = 256; + +/// The byte each texel holds before the kernel writes it: neither 0x00 nor 0xff. +const BEFORE: u8 = 0x5a; + +/// How long the device's in-place check may take to settle. +const SETTLE: Duration = Duration::from_secs(120); + +/// Each format: its texel's bytes, the color the kernel writes, and the bytes of it a texel holds. +const FORMATS: [(PixelFormat, u64, [f32; 4], &[u8]); 4] = [ + (PixelFormat::R8Unorm, 1, [1.0, 0.0, 0.0, 0.0], &[0xff]), + (PixelFormat::A8Unorm, 1, [0.0, 0.0, 0.0, 1.0], &[0xff]), + ( + PixelFormat::RG8Unorm, + 2, + [0.0, 1.0, 0.0, 0.0], + &[0x00, 0xff], + ), + ( + PixelFormat::R16Unorm, + 2, + [1.0, 0.0, 0.0, 0.0], + &[0xff, 0xff], + ), +]; + +/// The byte of the pattern every byte that is no texel holds at `offset`: a count no row pitch +/// or texel lines up with. +fn pattern(offset: u64) -> u8 { + (offset.wrapping_mul(7) % 251) as u8 ^ 0x81 +} + +/// The host bytes of the no-copy buffer: the texels [`BEFORE`], every other byte [`pattern`]. +fn fill(host: &Host, texel: u64) -> Vec { + let bytes: Vec = (0..BYTES as u64) + .map( + |at| match at < HEIGHT * PITCH && at % PITCH < WIDTH * texel { + true => BEFORE, + false => pattern(at), + }, + ) + .collect(); + let words: Vec = bytes + .chunks_exact(4) + .map(|word| u32::from_le_bytes([word[0], word[1], word[2], word[3]])) + .collect(); + host.set(0, &words); + bytes +} + +/// A copy of the no-copy buffer's bytes, which no command writes meanwhile. +fn read(buffer: &Buffer) -> Vec { + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer's contents span its length, and no command runs over them while the test + // reads them (it waits for its command buffers); they are copied out at once. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }.to_vec() +} + +/// The guests' descriptor of `format`: 32x32, `ShaderRead` and `ShaderWrite`, the buffer's +/// options. +fn descriptor(buffer: &Buffer, format: PixelFormat) -> TextureDescriptor { + let mut d = TextureDescriptor::texture_2d(format, WIDTH, HEIGHT, false); + d.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + d.resource_options = buffer.resource_options(); + d +} + +/// The shadows over host pages counted by why between `before` and `after`: refused an image, +/// by the check's answer, and by their texels' width. +fn shadows(before: &WorkCounts, after: &WorkCounts) -> (u64, u64, u64) { + let refused = |counts: &WorkCounts| { + counts.host_texture_shadows_refused_rows + + counts.host_texture_shadows_refused_detached + + counts.host_texture_shadows_refused_image + + counts.host_texture_shadows_refused_pitch + + counts.host_texture_shadows_refused_placement + + counts.host_texture_shadows_refused_source + + counts.host_texture_shadows_refused_dma_buf + }; + let by_check = |counts: &WorkCounts| { + counts.host_texture_shadows_check_pending + + counts.host_texture_shadows_check_failed + + counts.host_texture_shadows_unchecked + }; + let width = |counts: &WorkCounts| counts.host_texture_shadows_store_width; + ( + refused(after) - refused(before), + by_check(after) - by_check(before), + width(after) - width(before), + ) +} + +/// The kernel that writes the color at `buffer(0)` at every texel of `texture(0)`. +fn writer(device: &crate::Device) -> ComputePipelineState { + let function = library(device, "engine/a8r_targets.ll") + .new_function_with_name("a8r_write") + .unwrap(); + device + .new_compute_pipeline_state_with_function(&function, &PipelineOptions::default()) + .unwrap() +} + +/// `kernel` writing `color` at every texel of `texture`, waited for. +fn write( + queue: &crate::CommandQueue, + kernel: &ComputePipelineState, + texture: &Texture, + color: [f32; 4], +) { + let bytes: Vec = color.iter().flat_map(|c| c.to_le_bytes()).collect(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(kernel).unwrap(); + encoder.set_texture(Some(texture), 0).unwrap(); + encoder.set_bytes(&bytes, 0).unwrap(); + encoder + .dispatch_threads(Size::new(WIDTH, HEIGHT, 1), Size::new(8, 8, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); +} + +#[test] +fn narrow_written_textures_take_the_path_their_narrow_check_answered() { + let host = Host::new(); + let scratch = Scratch::new("narrow-writes"); + let device = device(&scratch.0); + let runs = Arc::new(AtomicUsize::new(0)); + let Some(buffer) = over_host(&device, &host, &runs) else { + return; + }; + let name = device.name(); + assert!(device.settle_in_place_checks(SETTLE), "the check settled"); + let report = device.in_place_check_report(); + let narrow: Vec<&String> = report + .iter() + .filter(|line| line.contains("narrow")) + .collect(); + for line in &narrow { + println!("NARROW-WRITES on {name}: {line}"); + } + println!( + "NARROW-WRITES on {name}: the check took {:?}", + device.in_place_check_took() + ); + // Three classes, two narrow accesses, two row ends; none pending. + assert_eq!(narrow.len(), 12, "{report:?}"); + assert!( + narrow.iter().all(|line| !line.ends_with("Pending")), + "{narrow:?}" + ); + let queue = device.new_command_queue().unwrap(); + let kernel = writer(&device); + let class = match buffer.over_dma_buf() { + true => PagesClass::DmaBuf, + false => PagesClass::Pointer, + }; + let mut lapses = Vec::new(); + for (format, texel, color, due) in FORMATS { + let before_bytes = fill(&host, texel); + let layout = BufferLayout { + offset: 0, + row_pitch: PITCH, + slice_pitch: PITCH * HEIGHT, + row_bytes: WIDTH * texel, + rows: HEIGHT, + slices: 1, + }; + let start = buffer.contents().map_or(0, |at| at.as_ptr().addr() as u64); + let checks = &device.shared().in_place; + let line = checks.line(); + let rows = RowEnds::of(start, &layout, line); + let padding = Padding::of(start, &layout, line, !buffer.copied()); + let access = Access::written(texel, padding).unwrap(); + assert!( + matches!(access, Access::NarrowWrites | Access::NarrowBufferWrites), + "{format:?}: {access:?}" + ); + let verdict = checks.verdict(class, access, rows); + let d = descriptor(&buffer, format); + let asked = buffer.texture_placement(&d, 0, PITCH).unwrap(); + let before = device.work_counts(); + let texture = buffer.new_texture(&d, 0, PITCH).unwrap(); + let after = device.work_counts(); + let aliased = after.host_textures_in_place - before.host_textures_in_place; + let written = after.host_textures_in_place_written - before.host_textures_in_place_written; + let (refused, by_check, width) = shadows(&before, &after); + // SAFETY: the handle is only compared, while the texture lives. + let image = unsafe { texture.vk_image() }; + let path = match (image.is_some(), aliased, written, refused, by_check) { + (true, 1, 1, 0, 0) => "in place", + (false, 0, 0, 1, 0) => "refused", + (false, 0, 0, 0, 1) => "shadow", + _ => "inconsistent", + }; + let what = format!("{format:?} {WIDTH}x{HEIGHT}/{PITCH}"); + println!( + "NARROW-WRITES on {name}: {what} over {class:?}: {access:?} {rows:?} {verdict:?}; \ + asked {asked:?}; made {path} (in place {aliased}, written {written}, refused \ + {refused}, by the check {by_check}, by width {width})" + ); + let right = match verdict { + Verdict::Passed => path == "in place" || path == "refused", + _ => path == "shadow", + }; + if !right || width != 0 { + lapses.push(format!( + "{what}: {path} by width {width}, the verdict {verdict:?}" + )); + } + if (asked == TexturePlacement::InPlace) != (path == "in place") { + lapses.push(format!("{what}: asked {asked:?}, made {path}")); + } + write(&queue, &kernel, &texture, color); + let now = read(&buffer); + let mut texels_right = true; + let mut padding_kept = true; + for y in 0..HEIGHT { + for x in 0..WIDTH { + let at = (y * PITCH + x * texel) as usize; + let read = &now[at..at + texel as usize]; + if read != due { + texels_right = false; + lapses.push(format!("{what}: texel {x},{y} reads {read:?}")); + } + } + let between = (y * PITCH + WIDTH * texel) as usize..((y + 1) * PITCH) as usize; + if now[between.clone()] != before_bytes[between] { + padding_kept = false; + } + } + let free = padding == Padding::Free && path == "in place"; + if !padding_kept && !free { + lapses.push(format!("{what}: the rows' padding changed")); + } + let past = (HEIGHT * PITCH) as usize..now.len(); + if now[past.clone()] != before_bytes[past] { + lapses.push(format!("{what}: the bytes past the last row changed")); + } + println!( + "NARROW-WRITES on {name}: {what}: every texel {due:?} {texels_right}, padding \ + {padding:?}, kept {padding_kept}" + ); + drop(texture); + } + drop(buffer); + assert!(lapses.is_empty(), "{}", lapses.join("\n")); +} diff --git a/crates/metal2vulkan-runtime/src/tests/texture_placement.rs b/crates/metal2vulkan-runtime/src/tests/texture_placement.rs index ab9c8e13f..1d9a733a2 100644 --- a/crates/metal2vulkan-runtime/src/tests/texture_placement.rs +++ b/crates/metal2vulkan-runtime/src/tests/texture_placement.rs @@ -50,6 +50,8 @@ fn each_route_answers_its_own_placement() { (Access::Renders, InPlaceAccess::Renders), (Access::Writes, InPlaceAccess::Writes), (Access::BufferWrites, InPlaceAccess::Writes), + (Access::NarrowWrites, InPlaceAccess::Writes), + (Access::NarrowBufferWrites, 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 849aa288e..143e7b13f 100644 --- a/crates/metal2vulkan-runtime/src/tests/texture_placement_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/texture_placement_device.rs @@ -506,7 +506,10 @@ fn the_answer_is_the_route_the_texture_takes() { let public_access = match access { Access::Reads => InPlaceAccess::Reads, Access::Renders => InPlaceAccess::Renders, - Access::Writes | Access::BufferWrites => InPlaceAccess::Writes, + Access::Writes + | Access::BufferWrites + | Access::NarrowWrites + | Access::NarrowBufferWrites => InPlaceAccess::Writes, }; let (access, row_ends) = (public_access, public_rows(rows)); let due = match verdict { diff --git a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs index 3c348acc1..bc523305c 100644 --- a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs @@ -359,6 +359,7 @@ impl Device { from_base: buffer_offset + layout.offset - base, layout, padding_owned: texels.padding_owned(), + texel: texels.texel_bytes(), }); } } @@ -479,16 +480,12 @@ impl Device { /// Whether a shader's writes of `texels` of a texture that does not render, over host pages /// of `class`, may reach them in place: they are of a width the device's check's kernel stores /// (`in_place::STORED_TEXEL_BYTES`), and its check passed for such writes over the class, of - /// texels that lie in lines as these do, those that let their rows' padding change where it is - /// free (`in_place::in_place`). + /// texels of their width that lie in lines as these do, those that let their rows' padding + /// change where it is free (`in_place::Access::written`, as `in_place::in_place` asks it). fn writes_reach(&self, texels: &Texels, class: PagesClass) -> bool { - if !in_place::STORED_TEXEL_BYTES.contains(&texels.texel_bytes()) { - return false; - } let line = self.shared().in_place.line(); - let written = match texels.padding(line) { - Padding::Free => Access::BufferWrites, - Padding::Kept => Access::Writes, + let Some(written) = Access::written(texels.texel_bytes(), texels.padding(line)) else { + return false; }; let rows = texels.rows(line); self.shared().in_place.verdict(class, written, rows) == Verdict::Passed @@ -1058,39 +1055,50 @@ impl Device { } /// 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, Padding) { + /// whether a shader's writes may change their rows' padding (`in_place::Padding`), and the + /// bytes of one texel: `from_base` past the pages' first byte, which starts a page. + fn watched_rows(&self, watch: &InPlaceWatch) -> (RowEnds, Padding, u64) { let start = watch.from_base - watch.layout.offset; 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) + ( + RowEnds::of(start, &watch.layout, line), + padding, + watch.texel, + ) } /// 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. 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 where the check that keeps it passed (the route's - /// `storable`, `texture/route.rs`), which it asks. - fn fresh_pages_take(&self, image: &Image, (rows, padding): (RowEnds, Padding)) -> bool { + /// of `texel` bytes that lie in lines as `rows` says: an image of attachment usage renders, + /// one of storage usage is written, one of neither reads. The writes take the check of the + /// texels' width (`in_place::Access::written`), and of one that does not render whose rows' + /// padding is free the form that lets it change (`in_place::in_place`); one that renders may + /// hold the storage usage a render target takes where the form that keeps it passed + /// (`in_place::storable`), which it asks. + fn fresh_pages_take( + &self, + image: &Image, + (rows, padding, texel): (RowEnds, Padding, u64), + ) -> 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 padding = match renders { + true => Padding::Kept, + false => padding, }; let accesses = [ - (Access::Reads, !renders && !writes), - (Access::Renders, renders), - (written, writes), + (Some(Access::Reads), !renders && !writes), + (Some(Access::Renders), renders), + (Access::written(texel, padding), writes), ]; accesses.into_iter().all(|(access, takes)| { !takes - || self.in_place_verdict(PagesClass::Fresh, access, rows) - == crate::in_place::Verdict::Passed + || access.is_some_and(|access| { + self.in_place_verdict(PagesClass::Fresh, access, rows) + == crate::in_place::Verdict::Passed + }) }) } diff --git a/crates/metal2vulkan-runtime/src/texture/route.rs b/crates/metal2vulkan-runtime/src/texture/route.rs index 663df2374..6b743d6a0 100644 --- a/crates/metal2vulkan-runtime/src/texture/route.rs +++ b/crates/metal2vulkan-runtime/src/texture/route.rs @@ -216,15 +216,9 @@ impl Device { }; match in_place::in_place(policy, usage, pages, verdict) { // A texture that renders takes the storage usage too where the check passed for a - // shader's writes over the class and its texel is one the check's kernel stores: a - // draw that reads it through a snapshot fetches it in the pixel interlock through that - // usage (`render/snapshot.rs`), and with it a shader's writes reach the texels in - // place, as the check's writes do. + // shader's writes of its texels over the class (`in_place::storable`). Ok(()) => host(HostWay::InPlace { - storable: Access::Renders.takes(usage) - && !Access::Writes.takes(usage) - && in_place::STORED_TEXEL_BYTES.contains(&pages.2) - && verdict(class, Access::Writes, rows) == Verdict::Passed, + storable: in_place::storable(usage, (class, rows, pages.2), verdict), }), Err(cause) => host(HostWay::Shadow(cause)), } diff --git a/crates/metal2vulkan-runtime/src/texture/storage_form.rs b/crates/metal2vulkan-runtime/src/texture/storage_form.rs index a62ab4f50..deebb81a5 100644 --- a/crates/metal2vulkan-runtime/src/texture/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/texture/storage_form.rs @@ -601,10 +601,8 @@ impl Texture { } in_place::in_place(policy, pending.usage, pages, verdict).ok()?; // As the texture would have taken it as it was made (`Device::storage_over_buffer`). - let storable = InPlaceAccess::Renders.takes(pending.usage) - && !InPlaceAccess::Writes.takes(pending.usage) - && in_place::STORED_TEXEL_BYTES.contains(&pages.2) - && verdict(pending.class, InPlaceAccess::Writes, pending.rows) == Verdict::Passed; + let made = (pending.class, pending.rows, pages.2); + let storable = in_place::storable(pending.usage, made, verdict); Some(Wanted::Move { texels: Arc::clone(texels), pending: pending.clone(), diff --git a/crates/metal2vulkan-runtime/src/texture_placement.rs b/crates/metal2vulkan-runtime/src/texture_placement.rs index ec68eb88c..fc831bc2d 100644 --- a/crates/metal2vulkan-runtime/src/texture_placement.rs +++ b/crates/metal2vulkan-runtime/src/texture_placement.rs @@ -62,8 +62,9 @@ pub enum TextureShadowReason { /// (`HostPageTexturePolicy::Shadow`, one of `DevicePolicy::exact_answers`). Policy, /// A shader writes the texture (`ShaderWrite` or `ShaderAtomic`), and its texels are - /// `texel_bytes` wide, a width of which the check's kernel stores none (it stores 4, 8 and 16 - /// bytes): no check covers a driver's writes of such texels. + /// `texel_bytes` wide, a width of which the check's kernel stores none (it stores 1, 2, 4, 8 + /// and 16 bytes, every width a buffer backs): no check covers a driver's writes of such + /// texels. StoreWidth { /// The bytes of one texel. texel_bytes: u64, @@ -127,10 +128,11 @@ 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. 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. + /// takes kernels' storage writes of its texels, checked by their width: texels of 1 or 2 + /// bytes apart from those of 4, 8 or 16. 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, } @@ -186,7 +188,10 @@ impl InPlaceAccess { match access { in_place::Access::Reads => InPlaceAccess::Reads, in_place::Access::Renders => InPlaceAccess::Renders, - in_place::Access::Writes | in_place::Access::BufferWrites => InPlaceAccess::Writes, + in_place::Access::Writes + | in_place::Access::BufferWrites + | in_place::Access::NarrowWrites + | in_place::Access::NarrowBufferWrites => InPlaceAccess::Writes, } } } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index dd896218c..1e8af2d65 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -6175,8 +6175,8 @@ pub struct WorkCounts { /// whatever else it holds; an `Unknown` usage among them). pub host_texture_shadows_shader_write: u64, /// Textures over host pages made shadows because their usage writes them through a shader - /// and their texels are of a width the device's check of storage writes stores none of - /// (texels of 1 or 2 bytes: it stores those of 4, 8 and 16). + /// and their texels are of a width the device's check of storage writes stores none of (it + /// stores those of 1, 2, 4, 8 and 16 bytes, every width a buffer backs). pub host_texture_shadows_store_width: u64, /// Textures over host pages made shadows because the device's check of their class and an /// access of theirs (one that reads, renders or a shader writes) had not answered yet (a 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 7227f0ace..08a91679e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs @@ -157,8 +157,8 @@ pub(super) fn writes_passed( 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, four accesses, two row ends. -const VERDICTS: usize = 24; +/// changed: three classes, six accesses, two row ends. +const VERDICTS: usize = 36; /// The devices made again where load beside the submission checks split their import tax's tries /// ([`answered_device`]). @@ -1293,8 +1293,9 @@ fn a_failed_check_keeps_the_shadow_and_no_record() { let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), in_place).unwrap(); let counts = device.work_counts(); // Each class's verdicts, for a texture that reads, one that renders and one a shader - // writes, each for texels that share a line with bytes beside them and for texels that - // share none. + // writes (of 4-, 8- or 16-byte texels and of 1- or 2-byte ones, each with its padding + // kept or free), each for texels that share a line with bytes beside them and for texels + // that share none. assert_eq!(counts.in_place_checks_recalled, VERDICTS as u64); assert_eq!(counts.in_place_checks_run, 0); assert!(device.settle_in_place_checks(std::time::Duration::ZERO)); diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index 1b83318f8..350ffe916 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -305,11 +305,11 @@ pub enum HostPageTexturePolicy { /// driver and release, shows that the first move of such an image leaves every byte alone /// while the CPU writes beside it, for a texture that renders, its render passes' load and /// store operations and its moves into the feedback loop layout and back too, and for one a - /// shader writes (`ShaderWrite` or `ShaderAtomic`, of texels of 4, 8 or 16 bytes), a kernel's - /// storage writes of its texels; and where the device makes the image (its format and usage - /// linear) and lays it out at the buffer's row pitch. Elsewhere, and for a texture a shader - /// writes of 1- or 2-byte texels, the shadow below. A texture made before the check's verdict - /// is known is a shadow too. + /// shader writes (`ShaderWrite` or `ShaderAtomic`, of texels of 1, 2, 4, 8 or 16 bytes, those + /// of 1 or 2 checked apart), a kernel's storage writes of its texels; and where the device + /// makes the image (its format and usage linear) and lays it out at the buffer's row pitch. + /// Elsewhere the shadow below. A texture made before the check's verdict is known is a shadow + /// too. #[default] InPlace, /// A shadow on every device: an image of the runtime's own memory the encoders copy the diff --git a/docs/API.md b/docs/API.md index 6842eed83..ea164587a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -330,15 +330,15 @@ and write every byte bound to it, where Metal keeps every CPU write to bytes a c not write; a render pass's load and store operations may too, for an image it renders. Under the default `HostPageTexturePolicy::InPlace` the runtime relies on the driver there, checked: a texture over host pages whose declared usage samples, reads, renders into it or writes it through a shader -(`ShaderWrite` or `ShaderAtomic`, of texels of 4, 8 or 16 bytes) is a linear image aliasing the -pages (one over dma-buf pages a `DRM_FORMAT_MOD_LINEAR` image over a dma-buf of its own pages, acquired +(`ShaderWrite` or `ShaderAtomic`, of texels of 1, 2, 4, 8 or 16 bytes) is a linear image aliasing +the pages (one over dma-buf pages a `DRM_FORMAT_MOD_LINEAR` image over a dma-buf of its own pages, acquired from `VK_QUEUE_FAMILY_FOREIGN_EXT`) wherever the device makes such an image and its own check passed for that kind of pages and each of its accesses (`WorkCounts::host_textures_in_place`, `dma_buf_textures_in_place`, `fresh_page_textures_in_place`, and `host_textures_in_place_written` for one a shader writes), on a discrete GPU as on any other. A texture that renders takes the feedback loop usage where the device makes the image with it, and the storage usage too where the -check passed for a shader's writes over that kind of pages and its texels are of 4, 8 or 16 bytes -(with it a shader writes the texels in place, as one declared to), so a draw that reads it after +check passed for a shader's writes of texels of its width over that kind of pages (with it a shader +writes the texels in place, as one declared to), so a draw that reads it after a render-target barrier reads it through a snapshot (`WorkCounts::feedback_loop_alias_images`); without the storage usage such a draw splits its pass. The check makes such images of every texel size, small and 3840x2160, over each kind of pages while a @@ -348,7 +348,11 @@ their first move, their moves into the feedback loop layout and back, and a rend clears and stores them, while the CPU writes the bytes between their rows and after them; and for one a shader writes, images made with `ShaderWrite` usage, whose every texel a kernel stores through an unsigned-integer view of 4, 8 or 16-byte texels while the CPU writes the bytes beside -them (a program's atomics are among no round). Each verdict is given apart for texels that share +them (a program's atomics are among no round), and apart from those, images of 1- and 2-byte +texels stored through `R8_UINT` and `R16_UINT` views, rows of which end inside a 4-byte word: a +driver may store a narrow texel through a wider access, so 1- and 2-byte texels take verdicts of +their own, and a byte their rounds changed keeps no wider texel's texture a shadow (a device +without `shaderStorageImageExtendedFormats` leaves them unchecked). Each verdict is given apart for texels that share a line of the device's memory (`nonCoherentAtomSize` bytes) with bytes beside them and for texels that share none (their first byte, their end and, with bytes between rows, each row's start and end on a line): a device that writes back a texel's line whole puts an older value back over a @@ -374,8 +378,9 @@ write reaches them as it reaches the buffer's. Every other texture over host pages is a shadow (`shadowed-texture`, the notice naming why): under `HostPageTexturePolicy::Shadow` (`DevicePolicy::exact_answers`); one a shader writes of texels of -1 or 2 bytes, which the check's kernel stores none of; one made before the check for an access of -its answered, or where it failed or made no image; and one no image in place serves (its format or +a width the check's kernel stores none of (none of 1, 2, 4, 8 and 16 bytes); one made before the +check for an access of its answered, or where it failed or made no image; and one no image in +place serves (its format or usage the device makes no linear image of, the bytes' pitch, placement or memory, or over dma-buf pages no dma-buf of the texture's own pages). `WorkCounts::host_texture_shadows_*` counts each reason apart (the texel width, `_store_width`), and of them all those whose usage renders into diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 79e2f2918..165c5b22e 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 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 texture that samples, reads, renders into it or is written through a shader (`ShaderWrite` or `ShaderAtomic` usage, of texels of 1, 2, 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 (a shader's writes of 1- or 2-byte texels apart from those of wider ones, which a driver may store through a wider access), 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 texels of a width no check stores (none of 1, 2, 4, 8 and 16 bytes), 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, and apart of 1- and 2-byte texels, rows apart at a 256-byte pitch (of rows that end inside a 4-byte word and odd heights) or tight, and 1024x1024, 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 | diff --git a/docs/HOWTO.md b/docs/HOWTO.md index a56436ef9..27a2e38b5 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -297,9 +297,10 @@ command buffer does not write. By default (`HostPageTexturePolicy::InPlace`) the runtime relies on the driver there, checked. A texture whose declared usage samples, reads, renders into it or writes it through a shader (of -texels of 4, 8 or 16 bytes) is a linear image aliasing the pages wherever the device makes one and -its own check passed for that kind of pages (pointer imports, dma-buf imports, fresh pages) and -each of its accesses (a texture that renders, and one a shader writes, are checked apart), on a +texels of 1, 2, 4, 8 or 16 bytes) is a linear image aliasing the pages wherever the device makes +one and its own check passed for that kind of pages (pointer imports, dma-buf imports, fresh +pages) and each of its accesses (a texture that renders, and one a shader writes, are checked +apart, and a shader's writes of 1- or 2-byte texels apart from wider ones'), on a discrete GPU as on any other: the check makes such images while a CPU thread writes beside their texels and passes a kind only where every first move (and render pass, for one that renders, and kernel's storage writes, for one a shader writes) kept every byte. It runs on a thread of its own, started by the first such texture, once per driver and @@ -319,8 +320,8 @@ verdicts are known. A program that routes each surface either to a texture over copy of its own asks `Buffer::texture_placement` (or `texture_placement_with_iosurface_plane`) with the arguments it would make the texture with: the answer (`TexturePlacement`: in place, pending, a shadow and why, no host pages, another shape) is the making's own decision, so no report -string needs parsing. A texture a shader writes of 1- or 2-byte -texels (`host_texture_shadows_store_width`), one the check failed or could not cover, and one +string needs parsing. A texture a shader writes of texels of a width the check stores none of +(`host_texture_shadows_store_width`), one the check failed or could not cover, and one no image in place serves (a pitch the device's linear images do not take -- `host_texture_shadows_refused_pitch`; over dma-buf pages, a source that makes no one dma-buf of the texture's own pages, as a chunked `udmabuf` import does -- `host_texture_shadows_refused_source`)