diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index efa32e221..7278c3244 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -234,15 +234,20 @@ pub(super) struct NotedTexture { /// Whether its image's stand-in has a sink (its plan has `STORAGE` usage): a read through a /// storage-class element there reads what an unnamed write left (`Device::note_stale`). sink: bool, + /// Whether its image keeps its own texels while the bytes are detached, presenting no + /// stand-in: a tiled texture's, whose first level a detach loads with the bytes' last texels + /// (`Texture::keep_first_level`). + keeps: bool, } impl NotedTexture { - /// `texture`, whose image is `image`, of object `id`; `exact` and `sink` as the fields say. + /// `texture`, whose image is `image`, of object `id`; `exact`, `sink` and `keeps` as the + /// fields say. pub(super) fn new( texture: Weak, image: Weak, id: ObjectId, - (exact, sink): (bool, bool), + (exact, sink, keeps): (bool, bool, bool), ) -> NotedTexture { NotedTexture { texture, @@ -250,6 +255,7 @@ impl NotedTexture { id, exact, sink, + keeps, } } @@ -258,6 +264,12 @@ impl NotedTexture { self.sink } + /// Whether its image keeps its own texels while the bytes are detached + /// (`NotedTexture::keeps`). + pub(super) fn keeps(&self) -> bool { + self.keeps + } + /// Whether the texture lives. fn lives(&self) -> bool { self.texture.strong_count() > 0 @@ -270,12 +282,13 @@ impl NotedTexture { } impl TexturesOver { - /// The images of the live textures, each once, by type erased; and whether a stand-in of - /// zero bytes presents each exactly (`NotedTexture::exact`). + /// The images of the live textures that present stand-ins while the bytes are detached (all + /// but those that keep their own, `NotedTexture::keeps`), each once, by type erased; and + /// whether a stand-in of zero bytes presents each exactly (`NotedTexture::exact`). pub(super) fn images(&self) -> (Vec>, bool) { let mut images: Vec> = Vec::new(); let mut exact = true; - for noted in self.noted.iter().filter(|noted| noted.lives()) { + for noted in self.textures().filter(|noted| !noted.keeps) { let Some(image) = noted.image.upgrade() else { continue; }; @@ -291,6 +304,13 @@ impl TexturesOver { pub(super) fn textures(&self) -> impl Iterator { self.noted.iter().filter(|noted| noted.lives()) } + + /// The live textures whose images keep their own texels while the bytes are detached + /// (`NotedTexture::keeps`), by type erased. + pub(super) fn keeping(&self) -> Vec> { + let keeps = self.textures().filter(|noted| noted.keeps); + keeps.filter_map(|noted| noted.texture.upgrade()).collect() + } } /// How many times a no-copy buffer of the process (or a no-copy heap's own buffer) came to lie diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index 3f659e7f0..3993d512e 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -503,10 +503,17 @@ impl Buffer { /// at once; a view in a format the image takes no Vulkan view of, and a binding beyond the /// texture's usage, are refused (`Unsupported`), where a texture of one level over a buffer /// takes them through a shadow of the bytes; and while the buffer's bytes are detached - /// (`detach_backing`) every level reads the stand-in's zeros, as a one-level texture over - /// them does. Announced once (`shadowed-texture`, naming the levels), counted in - /// `WorkCounts::shadowed_textures`, its copies in `WorkCounts::shadow_texels_copied_in` and - /// `shadow_texels_copied_back` (its first level's texels alone). + /// (`detach_backing`) its first level reads their last texels, which the detach loads into + /// its image, where a texture over the bytes alone presents a stand-in of zeros: an unnamed + /// read reads them, and so does `get_bytes`, whose write of that level, `replace_region`, is + /// refused meanwhile (`NotImplemented(DetachedTexelAccess)`), as a one-level texture's is. Its + /// other levels keep their texels through the detach, read and written as before, as a Mac's + /// texture's own memory holds them. Announced once (`shadowed-texture`, naming the levels), + /// counted in `WorkCounts::shadowed_textures`, its copies in + /// `WorkCounts::shadow_texels_copied_in` and `shadow_texels_copied_back` (its first level's + /// texels alone). A command's use of its other levels alone takes no copy (a blit into or + /// out of one, a pass into one, `generate_mipmaps`' writes), and its copies back and merges + /// dispatch and fetch through views of its first level as a one-level texture's do. /// /// Refused as [`new_texture`](Self::new_texture) is, but for the levels: more levels than the /// extent's full chain (`Invalid`, `TextureProblem`), and a texture buffer of more than one diff --git a/crates/metal2vulkan-runtime/src/detach.rs b/crates/metal2vulkan-runtime/src/detach.rs index c0b7e2126..422358f9a 100644 --- a/crates/metal2vulkan-runtime/src/detach.rs +++ b/crates/metal2vulkan-runtime/src/detach.rs @@ -64,6 +64,13 @@ //! names it fails as one naming the buffer does. A texture being made over the bytes refuses //! the detach (`NotImplemented(DetachTextures)`), and no texture is made over detached bytes //! yet. +//! - **Tiled textures** (`Buffer::new_tiled_texture`, more than one level): the image of its own +//! that holds every level presents no stand-in. The detach loads its first level with the +//! bytes' texels as they are then, before anything changes (`Texture::keep_first_level`), so +//! while they are detached an unnamed read and `get_bytes` read their last texels there, where +//! a texture over the bytes alone reads zeros, and its other levels keep their texels, as a +//! Mac's texture's own memory does. Its first level copies the bytes in again at its first use +//! once they lie in pages. //! - **Attaching again.** `rebind_bytes_no_copy` gives a detached buffer or heap pages again. use super::buffer::{Buffer, Detached, HostCell, Lying}; @@ -73,7 +80,7 @@ use super::error::{invalid, Error, Problem, RuntimeGap}; use super::heap::Heap; use super::rebind::{RebindProblem, StaleTexture, Unexact}; use super::resource::ObjectId; -use super::texture::stand_in::TextureImages; +use super::texture::stand_in::{keep_first_levels, TextureImages}; use super::Device; use std::any::Any; use std::sync::atomic::Ordering; @@ -183,6 +190,11 @@ impl Device { let Lying::In(from) = cell.lying() else { return Ok(true); }; + // A tiled texture over the bytes keeps its own image while they are detached: its first + // level takes their texels now, which it holds meanwhile (`Texture::keep_first_level`). + // Read with no lock of the cell's held. + let keeping = cell.settled().map(|textures| textures.keeping()); + keep_first_levels(keeping.unwrap_or_default())?; // No texture is being made over the bytes while this is held, and those over them // present stand-ins once they are detached, each made now, before anything changes. let no_textures = || Error::NotImplemented(RuntimeGap::DetachTextures); @@ -201,8 +213,10 @@ impl Device { let gone = images.present_stand_ins(stand_ins); let texels = cell.texels(); // Pages a submitted command buffer made resident stay Metal's textures' unnamed reads; - // and a stand-in's sink holds what unnamed writes left. - let stale = textures.textures().flat_map(|noted| { + // and a stand-in's sink holds what unnamed writes left. A texture whose image keeps its + // own texels presents no stand-in. + let presenting = textures.textures().filter(|noted| !noted.keeps()); + let stale = presenting.flat_map(|noted| { let pages = resident.then_some(Unexact::StalePages); let sink = noted.sink().then_some(Unexact::StorageSink); let (texture, id) = (noted.texture(), noted.id); diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 4b4511af8..d451adf29 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1913,7 +1913,11 @@ pub enum RuntimeGap { /// `Texture::replace_region` or `get_bytes` of a texture whose bytes (a no-copy buffer's or /// heap's) are detached (`detach_backing`). Metal's CPU access reaches the pages the texture /// took as it was made (a heap's texture, the pages the heap was made over), measured on an - /// M4 under macOS 27.0.1; the runtime keeps no pages of detached bytes. + /// M4 under macOS 27.0.1; the runtime keeps no pages of detached bytes. A tiled texture of more + /// than one level (`Buffer::new_tiled_texture`) keeps its own image meanwhile: only a + /// `replace_region` of its first level is refused, whose `get_bytes` reads the bytes' last + /// texels, which the detach loaded into the image, and its other levels are read and written + /// there. DetachedTexelAccess, /// A use of a texture of a depth or stencil format (`Depth16Unorm`, `Depth32Float`, /// `Depth32Float_Stencil8`, `Stencil8`, `X32_Stencil8`) over a plane of a surface with planes diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 7b493e452..5c347c1fd 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -2536,8 +2536,11 @@ impl Device { }); let views = (words, unorm); let copies = texels.shadow_copies(image.raw.get(), image.identity, aspects, views)?; - // Its copies keep its own image, which it presents again once the bytes lie in pages. - self.stand_in_while_detached(&texels.buffer, &image)?; + // Its copies keep its own image, which it presents again once the bytes lie in pages. A + // tiled texture's image keeps every level while they are detached, presenting none. + if levels == 1 { + self.stand_in_while_detached(&texels.buffer, &image)?; + } // A device copy degrades nothing: it holds the bytes wherever a command reads them. if device_copy { self.shared().counts.device_copy_texture(); @@ -4414,15 +4417,18 @@ impl Texture { } // A texture over host pages' bytes, or in a heap over them (a view of one too): a // detach of them makes its image present a stand-in (`stand_in.rs`). + // A tiled texture's image keeps every level instead, its first loaded with the bytes' + // last texels (`Texture::keep_first_level`). if let Some((bytes, image, exact)) = texture.image_over_bytes() { let sink = image.plan().usage.contains(ImageUsageFlags::STORAGE); + let keeps = texture.tiled_levels(); let shared: Arc = Arc::clone(&texture.0) as _; let image: Arc = Arc::clone(image) as _; bytes.note_texture(NotedTexture::new( Arc::downgrade(&shared), Arc::downgrade(&image), texture.0.object_id, - (exact, sink), + (exact, sink, keeps), )); } if let IdUse::Program(placement) = id_use { @@ -4544,12 +4550,52 @@ impl Texture { /// copies keep its first level's texels in step with the bytes (`blit.rs`'s **Heap /// shadows**). `None` for a texture of an image alone. pub(super) fn blit_texels(&self) -> Option<&Texels> { - match self.storage() { - Storage::Shadow { image, .. } if image.plan().levels > 1 => None, - _ => self.buffer_texels(), + match self.tiled_levels() { + true => None, + false => self.buffer_texels(), } } + /// Whether the texture is a tiled one of more than one level over a buffer's bytes, or a view + /// of one (`Buffer::new_tiled_texture`): one image of its own holds every level, its first a + /// copy of the bytes. + pub(super) fn tiled_levels(&self) -> bool { + matches!(self.storage(), Storage::Shadow { image, .. } if image.plan().levels > 1) + } + + /// Whether the texture is a tiled one's ([`tiled_levels`](Self::tiled_levels)) whose bytes are + /// detached (`detach.rs`): its image's first level holds their last texels meanwhile, which its + /// CPU reads read ([`keep_first_level`](Self::keep_first_level)). + fn first_level_kept(&self) -> bool { + match self.storage() { + Storage::Shadow { texels, .. } => self.tiled_levels() && texels.buffer.detached(), + _ => false, + } + } + + /// Load a tiled texture's first level ([`tiled_levels`](Self::tiled_levels)) into its image + /// as its bytes hold it now, before a detach lets go of them (`detach.rs`): while they are + /// detached the image presents no stand-in, its later levels its own texels and its first + /// level the bytes' last, which its unnamed reads and `get_bytes` read. Nothing for another + /// texture, or a view (its first level is its root's). + pub(crate) fn keep_first_level(&self) -> Result<(), Error> { + let Storage::Shadow { texels, .. } = self.storage() else { + return Ok(()); + }; + if !self.tiled_levels() || self.0.parent.is_some() { + return Ok(()); + } + let unit = texels.unit(); + let [across, down] = unit.extent.map(u64::from); + let (width, height) = (self.width(), self.height()); + let row = width.div_ceil(across) * u64::from(unit.bytes); + let mut bytes = vec![0; (row * height.div_ceil(down)) as usize]; + let region = Region::new_2d(0, 0, width, height); + self.get_bytes(&mut bytes, row, 0, region, 0, 0)?; + let upload = Upload::Slice(&bytes); + self.replace((region, 0, 0), upload, (row, 0), Writes::FirstLevelKept) + } + /// Whether the texture's image is a linear image over its buffer's bytes now: an aliasing /// image (not a shadow, not a texture buffer), not presenting a stand-in while its bytes are /// detached (`detach.rs`), so a write of those bytes is a write of its texels. @@ -5414,8 +5460,15 @@ impl Texture { /// Refused (`NotImplemented(DetachedTexelAccess)`) while the bytes the texture is over (its /// root's, for a view) are detached (`detach.rs`): Metal's CPU access reaches the pages the - /// texture took as it was made, which the runtime does not keep. - fn refuse_detached_texels(&self) -> Result<(), Error> { + /// texture took as it was made, which the runtime does not keep. But a tiled texture's + /// ([`tiled_levels`](Self::tiled_levels)), whose image keeps every level meanwhile: a read of + /// any level and a write of a level past the first (its `level`, of `write`), which its image + /// alone holds, as a Mac's texture's own memory does. + fn refuse_detached_texels(&self, level: u64, write: bool) -> Result<(), Error> { + let first = u64::from(self.0.record.base_level) + level == 0; + if self.tiled_levels() && !(write && first) { + return Ok(()); + } let root = self.root(); let detached = match root.storage() { Storage::Texels(texels) @@ -5742,7 +5795,8 @@ impl Texture { bytes_per_image: u64, ) -> Result<(), Error> { let upload = Upload::Slice(bytes); - self.replace(region, level, slice, upload, bytes_per_row, bytes_per_image) + let pitches = (bytes_per_row, bytes_per_image); + self.replace((region, level, slice), upload, pitches, Writes::Program) } /// [`replace_region`](Self::replace_region) from bytes at a pointer (a runtime extension, @@ -5766,18 +5820,18 @@ impl Texture { bytes, copy: OnceCell::new(), }; - self.replace(region, level, slice, upload, bytes_per_row, bytes_per_image) + let pitches = (bytes_per_row, bytes_per_image); + self.replace((region, level, slice), upload, pitches, Writes::Program) } - /// `replace_region` from `bytes`, whichever form (the two above). + /// `replace_region` from `bytes`, whichever form (the two above), of `region` of `level` and + /// `slice`, rows and images the `pitches` apart, as `writes` says. fn replace( &self, - region: Region, - level: u64, - slice: u64, + (region, level, slice): (Region, u64, u64), bytes: Upload<'_>, - bytes_per_row: u64, - bytes_per_image: u64, + (bytes_per_row, bytes_per_image): (u64, u64), + writes: Writes, ) -> Result<(), Error> { const CALL: &str = "replace_region"; let Some(copy) = @@ -5785,7 +5839,9 @@ impl Texture { else { return Ok(()); }; - self.refuse_detached_texels()?; + if writes == Writes::Program { + self.refuse_detached_texels(level, true)?; + } if copy .host .host_len() @@ -5813,8 +5869,12 @@ impl Texture { let image = match self.storage() { Storage::Image(image) => image, // A tiled texture's levels past the first lie in its image alone - // (`Buffer::new_tiled_texture`). - Storage::Shadow { image, .. } if image_region.level > 0 => image, + // (`Buffer::new_tiled_texture`), and its first too as a detach loads it there. + Storage::Shadow { image, .. } + if image_region.level > 0 || writes == Writes::FirstLevelKept => + { + image + } Storage::Texels(texels) | Storage::Alias { texels, .. } | Storage::Shadow { texels, .. } => { @@ -5970,7 +6030,7 @@ impl Texture { else { return Ok(()); }; - self.refuse_detached_texels()?; + self.refuse_detached_texels(level, false)?; if copy .host .host_len() @@ -6128,8 +6188,10 @@ impl Texture { let image = match self.storage() { Storage::Image(image) => image, // A tiled texture's levels past the first lie in its image alone - // (`Buffer::new_tiled_texture`). - Storage::Shadow { image, .. } if image_region.level > 0 => image, + // (`Buffer::new_tiled_texture`), and its first too while its bytes are detached. + Storage::Shadow { image, .. } if image_region.level > 0 || self.first_level_kept() => { + image + } Storage::Texels(texels) | Storage::Alias { texels, .. } | Storage::Shadow { texels, .. } => { @@ -6425,6 +6487,17 @@ impl HostCopy { } } +/// Who writes through `Texture::replace`. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Writes { + /// The program's `replace_region`: refused where the texture's bytes are detached but at a + /// tiled texture's level past its first (`Texture::refuse_detached_texels`). + Program, + /// A detach's load of a tiled texture's first level into its image + /// (`Texture::keep_first_level`), which the image holds while the bytes are detached. + FirstLevelKept, +} + /// What `replaceRegion` reads (`Texture::replace`): a slice, or bytes at a pointer /// ([`HostBytes`]), read once: straight into the packed rows where nothing read them before, /// else into `copy` the first time a form needs them whole, which every later read reads. diff --git a/crates/metal2vulkan-runtime/src/texture/stand_in.rs b/crates/metal2vulkan-runtime/src/texture/stand_in.rs index 87a45cdc5..48b718063 100644 --- a/crates/metal2vulkan-runtime/src/texture/stand_in.rs +++ b/crates/metal2vulkan-runtime/src/texture/stand_in.rs @@ -1,6 +1,7 @@ //! The images a texture over detached bytes presents: a stand-in of its image's plan, zero and //! never written, which its views, its heap-set elements and its attachments name while its bytes -//! are detached (`detach.rs`). +//! are detached (`detach.rs`). A tiled texture of more than one level keeps its own image instead, +//! its first level loaded with the bytes' last texels ([`keep_first_levels`]). //! //! - **What Metal answers** (an M4 under macOS 27.0.1): a texture over detached //! bytes keeps its descriptor's metadata (every size and level query answers it, its views' @@ -268,6 +269,20 @@ impl Device { } } +/// Load the first level of each tiled texture of `textures` (a buffer's, by type erased: +/// `buffer::TexturesOver::keeping`) into its image as the bytes hold it now, before a detach lets +/// go of them (`detach.rs`, `Texture::keep_first_level`): such a texture keeps its own image while +/// they are detached, presenting no stand-in. Refused as the loads are (out of memory), before +/// anything is detached. +pub(crate) fn keep_first_levels(textures: Vec>) -> Result<(), Error> { + for erased in textures { + if let Ok(shared) = erased.downcast::() { + super::Texture(shared).keep_first_level()?; + } + } + Ok(()) +} + /// The images of the textures over a buffer's host pages (`buffer::TexturesOver`), as a detach /// and a reattach take them (`detach.rs`, `buffer_descriptor.rs`), and whether a stand-in of /// zero bytes presents each exactly. diff --git a/docs/API.md b/docs/API.md index 6f469d749..21ff1db81 100644 --- a/docs/API.md +++ b/docs/API.md @@ -431,7 +431,12 @@ command boundaries, not an alias, and a CPU write made while a command buffer th reaches it at the next copy in. Its other levels are its image's own memory, zero when made in a `Shared` or `Managed` texture; blits (`generate_mipmaps` among them) and functions use every level, and `get_bytes` and `replace_region` reach the first level in the bytes and the others in the -image. A texture of one level is `new_texture`'s, in place where that is. +image. A command that uses its other levels alone copies nothing. While the buffer's bytes are +detached (`detach_backing`) it keeps its own image: its first level holds the bytes' last texels, +which the detach loads into it and which an unnamed read and `get_bytes` read (a `replace_region` +of that level is refused, `NotImplemented(DetachedTexelAccess)`), where a texture over the bytes +alone presents a stand-in of zeros; its other levels keep their texels, read and written as before. +A texture of one level is `new_texture`'s, in place where that is. On a discrete GPU, a `Managed` texture over a no-copy buffer's bytes (not an IOSurface plane's) that only samples or reads, whose policy takes the image in place, over memory that carries a log of its writes (`HostMemory::with_dirty_pages`), tracked, one slice laid out as one copy, is instead