From f9bc470d7cde6a6b5fc8db75b239af2dd9949452 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 7 Nov 2026 14:15:54 -0800 Subject: [PATCH] Move a shadow made before its pages' in-place verdict in place once it passes A texture over host pages made before its class's in-place verdicts were known is a shadow (CheckPending): an unknown, not a lack. Under the owner's 11-07 ruling a shadow is only for accesses that cannot be done in place, so such a shadow must not stay one for life because it was made early. Each such shadow now waits for its class's verdicts (StorageForms::moves). The check's thread, at each verdict, decides from facts stored with the wait (class, usage, texel bytes) and takes no handle of a program's texture. Where the verdicts take an image in place, the texture waits for the storage-form switch. At the commit of the device's only uncommitted command buffer, the switch makes the image in place exactly as the texture's making makes it: the declared plan, with feedback loop and storage usage where the device makes them so, and noted for a rebind and its first move. Where every encoder ran, the texture presents it from then on (TextureShared::moved; every storage read goes through Texture::storage). It is counted in host_textures_in_place and in the new WorkCounts::host_textures_moved_in_place, and its slots are written again. No texel is copied: between encoders the shadow holds nothing the buffer lacks, and the image in place is the buffer's bytes, whose uses hazard tracking orders after earlier copies back and merges. A view made before the move keeps the shadow. A shadow with a usage or render shadow, over detached or copied bytes, or whose image the device refuses stays a shadow. The shadow's image is kept with the texture until it goes. Test: runtime_lane::in_place_textures::a_texture_made_before_its_verdict_moves_in_place_once_it_passes (under the validation layer). Docs: storage_form.rs and in_place.rs module docs, FAST-PATHS in-place row, HOWTO, API.md. (cherry picked from commit 605d0444de1ad1a9b93e02649db7e1b2fda18e93) --- crates/metal2vulkan-runtime/src/in_place.rs | 18 +- .../src/in_place_check.rs | 3 + crates/metal2vulkan-runtime/src/texture.rs | 127 +++++--- .../src/texture/attached_reads.rs | 2 +- .../src/texture/attributes.rs | 2 +- .../src/texture/copy_images.rs | 2 +- .../src/texture/first_move_lifetimes.rs | 2 +- .../metal2vulkan-runtime/src/texture/heap.rs | 4 +- .../src/texture/in_place_image.rs | 6 +- .../src/texture/rotation.rs | 2 +- .../src/texture/shared.rs | 4 +- .../src/texture/storage_form.rs | 276 ++++++++++++++++-- .../src/texture/usage_shadow.rs | 6 +- .../src/texture/view_shadow.rs | 12 +- .../src/texture/ycbcr_image.rs | 10 +- .../metal2vulkan-runtime/src/work_counts.rs | 17 +- .../src/runtime_lane/in_place_textures.rs | 206 +++++++++++++ crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/API.md | 4 +- docs/FAST-PATHS.md | 2 +- docs/HOWTO.md | 10 +- 21 files changed, 616 insertions(+), 100 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/in_place.rs b/crates/metal2vulkan-runtime/src/in_place.rs index 6ea015430..8cebfc366 100644 --- a/crates/metal2vulkan-runtime/src/in_place.rs +++ b/crates/metal2vulkan-runtime/src/in_place.rs @@ -52,8 +52,11 @@ //! Elsewhere the texture is a shadow (`shadow.rs`), its notice naming why ([`ShadowCause`]) and //! counted by cause (`WorkCounts::host_texture_shadows_*`, and those that render apart). //! - **Before the verdict.** A texture made before its class's verdict for its access is known -//! waits for nothing: it is a shadow for its life ([`ShadowCause::CheckPending`], counted apart), -//! and the first such texture starts the check on a thread of its own. Its making waits for no +//! waits for nothing: it is a shadow ([`ShadowCause::CheckPending`], counted apart), and the +//! first such texture starts the check on a thread of its own. Once its class's verdicts are +//! known, it moves in place where they pass, at the commit of the device's only uncommitted +//! command buffer (`texture/storage_form.rs`, `WorkCounts::host_textures_moved_in_place`), and +//! stays a shadow where they do not, as a texture made then would be. Its making waits for no //! check: the check's rounds take seconds on some devices and builds (1.8 s for the first //! texture, waited for, on a Radeon 780M in a debug build), past what a program's first texture //! may take, a guest's message that makes one among them. A device whose record holds the @@ -228,6 +231,17 @@ impl Verdict { } } +/// What a shadow over host pages made before its class's verdict for its access +/// ([`ShadowCause::CheckPending`]) needs to move in place once the verdicts pass +/// (`texture/storage_form.rs`): its class and usage, its declared plan and its descriptor, which +/// the image in place is made of as the texture's would have been. +pub(crate) struct PendingMove { + pub(crate) class: PagesClass, + pub(crate) usage: TextureUsage, + pub(crate) plan: crate::image_plan::ImagePlan, + pub(crate) descriptor: crate::texture_descriptor::TextureDescriptor, +} + /// Why a texture over host pages is a shadow and not an image in place. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum ShadowCause { diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index 6a2369054..72a489407 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -281,6 +281,8 @@ fn run(weak: crate::device::WeakDevice) { let checks = &device.shared().in_place; checks.set(class, access, verdict); device.shared().counts.in_place_check_ran(verdict); + // Shadows made before their verdicts that know them now may move in place. + device.in_place_verdicts_given(); } } let Some(device) = weak.hold() else { @@ -307,6 +309,7 @@ fn run(weak: crate::device::WeakDevice) { .write_record_soon(&record_name(&identity), bytes); } checks.settle(Some(started.elapsed())); + device.in_place_verdicts_given(); } /// Whether the runtime found `device`'s loader word overwritten (`loader_word.rs`): the check then diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 1e60ee82d..eb05c795f 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -395,6 +395,13 @@ pub struct Texture(Arc); pub(super) struct TextureShared { storage: Storage, + /// The storage a shadow over host pages made before its pages' in-place verdict moved to + /// once the verdict passed (`texture/storage_form.rs`): an image in place over its texels, + /// which the texture presents from then on instead of `storage` ([`Texture::storage`]). + moved: OnceLock, + /// What such a shadow needs to move in place (`in_place::PendingMove`), while it may: `None` + /// for every other texture, and once it moved or its verdicts kept it a shadow. + pending_move: Mutex>, /// What this texture presents of its image. record: ViewRecord, /// The texture a view was made from (`parentTexture`). @@ -465,7 +472,13 @@ impl Drop for TextureShared { Storage::Image(image) | Storage::Alias { image, .. } | Storage::Shadow { image, .. } => { - (&image.device, Some(Box::new(Arc::clone(image)))) + // A shadow that moved in place keeps its image in place too, which the + // command buffers since read through its ID (`texture/storage_form.rs`). + let moved = match self.moved.get() { + Some(Storage::Alias { image, .. }) => Some(Arc::clone(image)), + _ => None, + }; + (&image.device, Some(Box::new((Arc::clone(image), moved)))) } Storage::Texels(texels) => (texels.buffer.device(), None), }; @@ -2215,18 +2228,26 @@ impl Device { id_use: IdUse, ) -> Result { let record = ViewRecord::of_descriptor(layout, descriptor); - let storage = self.storage_over_buffer(call, Arc::new(texels), descriptor, layout)?; - Ok(Texture::made(self, storage, record, None, id_use)) + let mut pending = None; + let over = (Arc::new(texels), &mut pending); + let storage = self.storage_over_buffer(call, over, descriptor, layout)?; + let texture = Texture::made(self, storage, record, None, id_use); + // A shadow made before its pages' in-place verdict moves in place once it passes. + if let Some(pending) = pending { + texture.wait_to_move_in_place(pending); + } + Ok(texture) } /// The storage of a texture of `descriptor` (checked as `layout`) over `texels`, as /// [`new_texture_over_buffer`](Self::new_texture_over_buffer) makes it: an aliasing image (one /// in place over host pages), else a shadow (announced once, counted by why over host pages). - /// Refused as it is. + /// A shadow over host pages made before their class's verdict for its access sets `pending` + /// to what it needs to move in place once the verdict passes. Refused as it is. fn storage_over_buffer( &self, call: &'static str, - texels: Arc, + (texels, pending): (Arc, &mut Option), descriptor: &TextureDescriptor, layout: &TextureLayout, ) -> Result { @@ -2353,6 +2374,14 @@ impl Device { "the in-place check's texture takes no image in place", )); } + if let ShadowCause::CheckPending(..) = cause { + *pending = Some(in_place::PendingMove { + class, + usage, + plan: plan.clone(), + descriptor: *descriptor, + }); + } let renders = in_place::Access::Renders.takes(usage); let accesses = (renders, in_place::Access::Writes.takes(usage)); self.shared().counts.host_texture_shadowed(&cause, accesses); @@ -4242,6 +4271,8 @@ impl Texture { }; let texture = Texture(Arc::new(TextureShared { storage, + moved: OnceLock::new(), + pending_move: Mutex::new(None), record, parent, id, @@ -4257,7 +4288,7 @@ impl Texture { facts: OnceLock::new(), planes_in_place, })); - if let Some(objects) = texture.0.storage.objects() { + if let Some(objects) = texture.storage().objects() { objects.object_made(); } // A texture over host pages' bytes, or in a heap over them (a view of one too): a @@ -4299,13 +4330,19 @@ impl Texture { if self.0.parent.is_some() { return Err(internal("a range token for a texture view")); } - match self.0.storage.objects() { + match self.storage().objects() { Some(objects) => objects.keep(token), None => Err(internal("a range token for a texture over a buffer")), } } /// The texture object `shared` names, while it lives (a slot's holder, `resource_ids.rs`). + /// The texture's storage: the one it was made with, or the image in place a shadow made + /// before its pages' in-place verdict moved to (`TextureShared::moved`). + fn storage(&self) -> &Storage { + self.0.moved.get().unwrap_or(&self.0.storage) + } + pub(super) fn upgrade(shared: &Weak) -> Option { shared.upgrade().map(Texture) } @@ -4352,7 +4389,7 @@ impl Texture { /// The texture's image. Refused for a texture buffer, which has none (`NotImplemented`): a /// call that needs one is not built on texture buffers. fn image(&self) -> Result<&Arc, Error> { - match &self.0.storage { + match self.storage() { Storage::Image(image) | Storage::Alias { image, .. } | Storage::Shadow { image, .. } => Ok(image), @@ -4362,7 +4399,7 @@ impl Texture { /// The buffer's bytes a texture buffer is, or `None` for a texture with an image. pub(super) fn texels(&self) -> Option<&Texels> { - match &self.0.storage { + match self.storage() { Storage::Image(_) | Storage::Alias { .. } | Storage::Shadow { .. } => None, Storage::Texels(texels) => Some(texels), } @@ -4372,7 +4409,7 @@ impl Texture { /// texture or array with an aliasing or a shadow image), or `None` for a texture of an image /// alone. pub(super) fn buffer_texels(&self) -> Option<&Texels> { - match &self.0.storage { + match self.storage() { Storage::Image(_) => None, Storage::Texels(texels) | Storage::Alias { texels, .. } @@ -4384,21 +4421,21 @@ impl Texture { /// 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. pub(super) fn aliases_buffer(&self) -> bool { - matches!(self.0.storage, Storage::Alias { .. }) && self.linear_image().unwrap_or(false) + matches!(self.storage(), Storage::Alias { .. }) && self.linear_image().unwrap_or(false) } /// Whether a pass that renders the texture renders its buffer's bytes: in place, its image /// lying over them now ([`image_over_buffer`](Self::image_over_buffer)), or through the /// shadow image the encoders copy them into and back (`shadow.rs`), which the pass renders. pub(crate) fn renders_bytes(&self) -> bool { - self.image_over_buffer() || matches!(self.0.storage, Storage::Shadow { .. }) + self.image_over_buffer() || matches!(self.storage(), Storage::Shadow { .. }) } /// Whether the texture's image lies over its buffer's bytes now: an aliasing image, not /// presenting a stand-in while its bytes are detached (`detach.rs`), so a pass that renders it /// writes those bytes. pub(super) fn image_over_buffer(&self) -> bool { - match &self.0.storage { + match self.storage() { Storage::Alias { image, .. } => lock(&image.detached).is_none(), _ => false, } @@ -4406,14 +4443,14 @@ impl Texture { /// Whether the texture is a buffer's bytes: a texture buffer or a shadowed texture. pub(super) fn over_buffer(&self) -> bool { - !matches!(self.0.storage, Storage::Image(_)) + !matches!(self.storage(), Storage::Image(_)) } /// The copies of a shadowed texture, of a texture buffer viewed through a staging buffer /// (`Texels::into_texture_buffer`), or of a heap's depth or stencil texture held as a shadow of /// the heap's bytes (`texture/heap.rs`), or `None` for another texture. pub(super) fn shadow(&self) -> Option<&Arc> { - match &self.0.storage { + match self.storage() { Storage::Shadow { copies, .. } => Some(copies), Storage::Texels(texels) => texels.staged(), Storage::Image(image) => match &image.owner { @@ -4427,7 +4464,7 @@ impl Texture { /// Whether two textures (or views) hold their texels in one image or buffer. pub(super) fn same_storage(&self, other: &Texture) -> bool { - match (&self.0.storage, &other.0.storage) { + match (self.storage(), other.storage()) { (Storage::Image(a), Storage::Image(b)) => { Arc::ptr_eq(view_shadow::truth(a), view_shadow::truth(b)) } @@ -4496,7 +4533,7 @@ impl Texture { /// texture's first byte in it; `None` for any other texture, a view and a two-plane texture /// of more levels or slices among them. pub(super) fn heap_planes(&self) -> Option<(&Heap, u64)> { - match &self.0.storage { + match self.storage() { Storage::Image(image) if self.0.parent.is_none() => match &image.owner { Owner::HeapShadow(shadow) if shadow.copies.holds_blit_rows() => { Some((self.0.heap.as_ref()?, shadow.place.offset)) @@ -4512,7 +4549,7 @@ impl Texture { /// the texture's first byte in it, and their layout; `None` for any other texture, a view /// among them. pub(super) fn heap_two_planes(&self) -> Option<(&Heap, u64, &TwoPlaneHeapLayout)> { - match &self.0.storage { + match self.storage() { Storage::Image(image) if self.0.parent.is_none() => match &image.owner { Owner::HeapShadow(shadow) => { let layout = shadow.copies.plane_layout()?; @@ -4526,7 +4563,7 @@ impl Texture { /// The image whose bytes a blit of the texture addresses: a view shadow's texture's. fn kept_image(&self) -> Option<&Arc> { - match &self.0.storage { + match self.storage() { Storage::Image(image) => Some(view_shadow::truth(image)), Storage::Alias { image, .. } | Storage::Shadow { image, .. } => Some(image), Storage::Texels(_) => None, @@ -4843,7 +4880,7 @@ impl Texture { /// A sparse texture's image beyond the `VkImage` (`sparse/texture.rs`); `None` for a texture /// that is not sparse. pub(super) fn sparse_image(&self) -> Option<&SparseImage> { - match &self.0.storage { + match self.storage() { Storage::Image(image) => match &image.owner { Owner::Sparse(sparse) => Some(sparse), _ => None, @@ -4857,7 +4894,7 @@ impl Texture { /// may be `Access::NONE`). pub(super) fn bound_use(&self, read: Access, write: Access) -> Use { let record = &self.0.record; - let image = match &self.0.storage { + let image = match self.storage() { Storage::Image(image) | Storage::Shadow { image, .. } => image, // An aliasing image's uses are uses of the buffer's bytes it lies in. Storage::Texels(texels) | Storage::Alias { texels, .. } => { @@ -4889,7 +4926,7 @@ impl Texture { access: Access, write: bool, ) -> Result, Error> { - if let Storage::Alias { texels, .. } = &self.0.storage { + if let Storage::Alias { texels, .. } = self.storage() { return Ok(if write { texels.bound_use(Access::NONE, access) } else { @@ -4920,7 +4957,7 @@ impl Texture { impl Texture { /// `device`. pub fn device(&self) -> &Device { - match &self.0.storage { + match self.storage() { Storage::Image(image) | Storage::Alias { image, .. } | Storage::Shadow { image, .. } => &image.device, @@ -5018,7 +5055,7 @@ impl Texture { /// ([`hazard_tracking_mode`](Self::hazard_tracking_mode), `Identity::new`). Measured on an /// Apple M3 Max under macOS 27.0.1. pub fn resource_options(&self) -> ResourceOptions { - let options = match &self.0.storage { + let options = match self.storage() { Storage::Image(image) => image.options, Storage::Texels(texels) | Storage::Alias { texels, .. } @@ -5043,7 +5080,7 @@ impl Texture { /// `hazardTrackingMode`: `Tracked` or `Untracked`, `Default` resolved as Metal resolves it. pub fn hazard_tracking_mode(&self) -> HazardTrackingMode { - let tracked = match &self.0.storage { + let tracked = match self.storage() { Storage::Image(image) | Storage::Alias { image, .. } | Storage::Shadow { image, .. } => image.identity.tracked, @@ -5058,7 +5095,7 @@ impl Texture { /// `allowGPUOptimizedContents`. pub fn allow_gpu_optimized_contents(&self) -> bool { - match &self.0.storage { + match self.storage() { Storage::Image(image) => image.allow_gpu_optimized_contents, Storage::Texels(texels) | Storage::Alias { texels, .. } @@ -5179,7 +5216,7 @@ impl Texture { /// for it (`texture/heap.rs`); `None` for any other texture, a texture over a buffer the /// program placed in a heap included. fn heap_texels(&self) -> Option<&Buffer> { - match &self.0.storage { + match self.storage() { Storage::Texels(texels) if texels.home == TexelsHome::Heap => Some(&texels.buffer), Storage::Image(_) | Storage::Texels(_) @@ -5194,7 +5231,7 @@ impl Texture { if let Some(heap) = self.heap() { return TextureMemory::Heap(heap); } - match &self.0.storage { + match self.storage() { Storage::Texels(texels) | Storage::Alias { texels, .. } | Storage::Shadow { texels, .. } => TextureMemory::Buffer(&texels.buffer), @@ -5247,7 +5284,7 @@ impl Texture { /// texture took as it was made, which the runtime does not keep. fn refuse_detached_texels(&self) -> Result<(), Error> { let root = self.root(); - let detached = match &root.0.storage { + let detached = match root.storage() { Storage::Texels(texels) | Storage::Alias { texels, .. } | Storage::Shadow { texels, .. } => texels.buffer.detached(), @@ -5268,13 +5305,13 @@ impl Texture { /// there); and whether a stand-in of zero bytes presents the image exactly (not one of /// texels its copies convert from the bytes, `stand_in.rs`). fn image_over_bytes(&self) -> Option<(&Buffer, &Arc, bool)> { - let (image, exact) = match &self.0.storage { + let (image, exact) = match self.storage() { Storage::Alias { image, .. } | Storage::Image(image) => (image, true), Storage::Shadow { image, copies, .. } => (image, !copies.converts()), Storage::Texels(_) => return None, }; let root = self.root(); - let bytes = match &root.0.storage { + let bytes = match root.storage() { Storage::Alias { texels, .. } | Storage::Shadow { texels, .. } => &texels.buffer, Storage::Image(_) => root.heap_place().and(root.0.heap.as_ref())?.bytes()?, Storage::Texels(_) => return None, @@ -5284,7 +5321,7 @@ impl Texture { /// Where an automatic or placement heap's texture (or a view of one) lies. fn heap_place(&self) -> Option<&heap::HeapPlace> { - self.0.storage.heap_place() + self.storage().heap_place() } /// `parentTexture`: the texture a view was made from (a view of a view has that view). @@ -5436,7 +5473,7 @@ impl Texture { // as `Depth32Float_Stencil8` over them in its GPU's own layout, no defined answer (an M4 // under macOS 27.0.1), and stops every other format ("not castable"). Only its own format // views it. - let own_x32 = matches!(&self.0.storage, + let own_x32 = matches!(self.storage(), Storage::Image(image) if image.plan().pixel_format == PixelFormat::X32Stencil8); if own_x32 && record.pixel_format != PixelFormat::X32Stencil8 { use super::view_plan::ViewProblem; @@ -5461,7 +5498,7 @@ impl Texture { // ETC2 or EAC format's sRGB form's codes are its linear form's). A view of an ASTC // texture in its other colour space reads the carrier's second twin, made now where it // has none (`texture/decoded_twin.rs`). - if let Storage::Image(image) = &self.0.storage { + if let Storage::Image(image) = self.storage() { let truth = view_shadow::truth(image); let pf = record.pixel_format; let astc = super::astc::decode_of(truth.plan()).map(|held| (held, AstcDecode::of(pf))); @@ -5490,7 +5527,7 @@ impl Texture { // bits, which its bindings take as the image in its own format through a swizzle and a // pass renders through a shadow; a binding's own view is checked again where it is made. A texture buffer's view is a // texel buffer view of the same bytes, which takes any format of its class. - let apart = match &self.0.storage { + let apart = match self.storage() { Storage::Texels(_) => false, Storage::Image(image) | Storage::Alias { image, .. } @@ -5506,7 +5543,7 @@ impl Texture { record.read_as = Some(read_as); storage } else if !apart { - self.0.storage.clone() + self.storage().clone() } else if let Some((image, read_as)) = self.read_through(&record) { self.device().shared().counts.view_through_swizzle_made(); record.read_as = Some(read_as); @@ -5640,7 +5677,7 @@ impl Texture { } None => bytes, }; - let image = match &self.0.storage { + let image = match self.storage() { Storage::Image(image) => image, Storage::Texels(texels) | Storage::Alias { texels, .. } @@ -5817,7 +5854,7 @@ impl Texture { // are the heap's bytes, which `read_region` reads (as `replace_region` writes them), and // a level it does not hold (a mipmapped texture's later one) lies in the image alone. let heap_shadow = matches!( - &self.0.storage, + self.storage(), Storage::Image(image) if matches!( &image.owner, Owner::HeapShadow(shadow) if shadow.holds(image.plan(), &image_region) @@ -5878,7 +5915,7 @@ impl Texture { /// and no wait, as Metal's `getBytes` of such a texture waits for no GPU work; else through a /// staging buffer, by a submission waited for. fn read_color_words(&self, region: &ImageRegion, words: &mut [u8]) -> Result<(), Error> { - let Storage::Image(image) = &self.0.storage else { + let Storage::Image(image) = self.storage() else { return Err(internal("a two-plane texture's copy without its image")); }; // A shadowed view's texels are its texture's (`texture/view_shadow.rs`). @@ -5952,7 +5989,7 @@ impl Texture { host: &HostLayout, bytes: &mut [u8], ) -> Result<(), Error> { - let image = match &self.0.storage { + let image = match self.storage() { Storage::Image(image) => image, Storage::Texels(texels) | Storage::Alias { texels, .. } @@ -6039,7 +6076,7 @@ impl Texture { // A memoryless texture buffer's CPU access faults in plain Metal's call (SIGSEGV, an M3 // Max under macOS 27.0.1): refused. Another memoryless texture's moves nothing (below). let memoryless = self.is_memoryless(); - if memoryless && !matches!(self.0.storage, Storage::Image(_)) { + if memoryless && !matches!(self.storage(), Storage::Image(_)) { return Err(invalid(call, Problem::StorageMode)); } self.check_rotated_reach()?; @@ -6047,7 +6084,7 @@ impl Texture { // a `Private` IOSurface plane's `getBytes` and `replaceRegion` read and write the // surface's bytes on plain Metal. A texture over a `Private` buffer takes // its storage mode, and is refused as a private texture is. - let reached = match &self.0.storage { + let reached = match self.storage() { Storage::Image(_) => false, Storage::Texels(texels) | Storage::Alias { texels, .. } @@ -6060,7 +6097,7 @@ impl Texture { aspects(pf) .is_some_and(|a| a.contains(ImageAspectFlags::DEPTH | ImageAspectFlags::STENCIL)) }; - let (unit, over_buffer) = match &self.0.storage { + let (unit, over_buffer) = match self.storage() { // A two-plane texture's CPU copies move plane 0's color words (`two_planes.rs`); a // heap's lies apart from the heap's bytes (`texture/heap.rs`). Storage::Image(_) if two_planes::holds_planes(record.pixel_format) => { @@ -6121,7 +6158,7 @@ impl Texture { let pitch = cpu_order.map_or(bytes_per_row, |[across, _]| across * u64::from(unit.bytes)); // Metal's answer for a two-plane texture is measured for rows and images a whole row // and image apart or more, by 4-byte multiples. - let planes = matches!(self.0.storage, Storage::Image(_)) + let planes = matches!(self.storage(), Storage::Image(_)) && two_planes::holds_planes(record.pixel_format); if planes { let s = super::copy_plan::shape(region.size, &unit); @@ -6183,7 +6220,7 @@ impl Texture { } // A 2-bit PVRTC texture's carrier halves its regions' x (`pvrtc.rs`); an ASTC texture's // carrier holds each block in 4 x 4 of its texels (`astc.rs`). - let planned = match &self.0.storage { + let planned = match self.storage() { Storage::Image(image) if holds_blocks(image.plan()) || super::astc::decode_of(image.plan()).is_some() => { diff --git a/crates/metal2vulkan-runtime/src/texture/attached_reads.rs b/crates/metal2vulkan-runtime/src/texture/attached_reads.rs index cbd7a8ef2..7ae8b58fc 100644 --- a/crates/metal2vulkan-runtime/src/texture/attached_reads.rs +++ b/crates/metal2vulkan-runtime/src/texture/attached_reads.rs @@ -285,7 +285,7 @@ impl Texture { /// texture's own first level and slice, so the binding's level 0 at a fragment's /// coordinate is the attachment's texel at that pixel. pub(crate) fn snapshot_color(&self, layout: &PassLayout) -> Option { - let image = match &self.0.storage { + let image = match self.storage() { Storage::Image(image) | Storage::Shadow { image, .. } => image, Storage::Alias { image, .. } if self.image_over_buffer() => image, _ => return None, diff --git a/crates/metal2vulkan-runtime/src/texture/attributes.rs b/crates/metal2vulkan-runtime/src/texture/attributes.rs index 3c607ccfa..903691ba4 100644 --- a/crates/metal2vulkan-runtime/src/texture/attributes.rs +++ b/crates/metal2vulkan-runtime/src/texture/attributes.rs @@ -88,7 +88,7 @@ impl Texture { if self.0.parent.is_some() { return None; } - match &self.0.storage { + match self.storage() { Storage::Image(image) => match &image.owner { Owner::Runtime { shareable, diff --git a/crates/metal2vulkan-runtime/src/texture/copy_images.rs b/crates/metal2vulkan-runtime/src/texture/copy_images.rs index 286286a6c..40b9b5150 100644 --- a/crates/metal2vulkan-runtime/src/texture/copy_images.rs +++ b/crates/metal2vulkan-runtime/src/texture/copy_images.rs @@ -78,7 +78,7 @@ fn covers(have: &ImageKey, want: &ImageKey) -> bool { /// The bytes of memory of `texture`'s image, where the runtime placed it in memory of its own; 0 /// for any other. fn image_bytes(texture: &Texture) -> u64 { - match &texture.0.storage { + match texture.storage() { Storage::Image(image) => match &image.owner { Owner::Runtime { placement, .. } => placement.size(), _ => 0, diff --git a/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs b/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs index 71448d537..03bcce076 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move_lifetimes.rs @@ -115,7 +115,7 @@ fn texels() -> Vec { /// The image `texture`'s storage holds, as an alias of a buffer's bytes or as its own. fn image_of(texture: &Texture) -> Option<&Arc> { - match &texture.0.storage { + match texture.storage() { Storage::Alias { image, .. } | Storage::Image(image) => Some(image), Storage::Texels(_) | Storage::Shadow { .. } => None, } diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs index feec9515c..4ec450138 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap.rs @@ -3190,7 +3190,7 @@ impl Device { let (textures, _) = heap.textures_from(0); let mut swaps: Vec = Vec::new(); for texture in &textures { - let Storage::Image(image) = &texture.0.storage else { + let Storage::Image(image) = texture.storage() else { continue; }; let Owner::Heap(place) = &image.owner else { @@ -3264,7 +3264,7 @@ impl Device { .facts(self.compile_device().profile()); let (textures, _) = heap.textures_from(0); for texture in &textures { - let Storage::Image(image) = &texture.0.storage else { + let Storage::Image(image) = texture.storage() else { continue; }; let Owner::Heap(place) = &image.owner else { diff --git a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs index c3d8a680a..241b65653 100644 --- a/crates/metal2vulkan-runtime/src/texture/in_place_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/in_place_image.rs @@ -77,7 +77,7 @@ impl Texture { /// call waits for (`Image::settle`): the device's check's round (`in_place_check.rs`). `None` /// where the texture is no image aliasing its bytes. pub(crate) fn settle_in_place(&self) -> Option> { - match &self.0.storage { + match self.storage() { Storage::Alias { image, .. } => Some(image.settle()), _ => None, } @@ -90,7 +90,7 @@ impl Texture { /// `None` where the texture is no image aliasing its bytes, or its image has no feedback loop /// usage. pub(crate) fn settle_feedback_moves(&self) -> Option> { - let Storage::Alias { image, .. } = &self.0.storage else { + let Storage::Alias { image, .. } = self.storage() else { return None; }; let plan = image.plan(); @@ -131,7 +131,7 @@ impl Texture { texel: ShadowTexelView, (width, height): (u32, u32), ) -> Option> { - let Storage::Alias { image, .. } = &self.0.storage else { + let Storage::Alias { image, .. } = self.storage() else { return None; }; use metal2vulkan::vk::{ diff --git a/crates/metal2vulkan-runtime/src/texture/rotation.rs b/crates/metal2vulkan-runtime/src/texture/rotation.rs index ed90a7e79..5adbbca18 100644 --- a/crates/metal2vulkan-runtime/src/texture/rotation.rs +++ b/crates/metal2vulkan-runtime/src/texture/rotation.rs @@ -165,7 +165,7 @@ impl Texture { call: &'static str, record: &ViewRecord, ) -> Result { - let Storage::Shadow { texels, .. } = &self.0.storage else { + let Storage::Shadow { texels, .. } = self.storage() else { return Err(internal("a rotated texture without its plane's rows")); }; let rotation = record.presented.rotation; diff --git a/crates/metal2vulkan-runtime/src/texture/shared.rs b/crates/metal2vulkan-runtime/src/texture/shared.rs index d12c5859a..a5eb62a19 100644 --- a/crates/metal2vulkan-runtime/src/texture/shared.rs +++ b/crates/metal2vulkan-runtime/src/texture/shared.rs @@ -166,7 +166,7 @@ impl Device { } let record = &texture.0.record; self.check_texture_placement(CALL, placement, record.usage, record.texture_type)?; - let storage = match &texture.0.storage { + let storage = match texture.storage() { Storage::Image(image) => Storage::Image(Arc::clone(image)), Storage::Texels(texels) => Storage::Texels(Arc::clone(texels)), Storage::Alias { .. } | Storage::Shadow { .. } => { @@ -188,7 +188,7 @@ impl Texture { /// never a view. pub fn is_shareable(&self) -> bool { self.0.parent.is_none() - && match &self.0.storage { + && match self.storage() { Storage::Image(image) => { matches!( image.owner, diff --git a/crates/metal2vulkan-runtime/src/texture/storage_form.rs b/crates/metal2vulkan-runtime/src/texture/storage_form.rs index 90b36b953..6f4ee2ed9 100644 --- a/crates/metal2vulkan-runtime/src/texture/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/texture/storage_form.rs @@ -5,6 +5,32 @@ //! a later commit gives it an image with `STORAGE`, its texels copied in once, and every later pass //! fetches it in place. //! +//! The same switch moves a shadow over host pages in place: a texture made before its pages' +//! in-place verdicts were known is a shadow (`ShadowCause::CheckPending`, `in_place.rs`), an +//! unknown and not a lack, so it waits for them, and a later commit gives it the image in place +//! over its texels that it would have had, had they been known as it was made. +//! +//! - **Moves in place.** Such a shadow waits in [`StorageForms::moves`] until its pages' class +//! knows every verdict (`Device::in_place_verdicts_given`, at each verdict the check gives, +//! from its thread, and at the texture's making, which take no handle of a program's texture). +//! Where its usage and those verdicts take an image in place (`in_place::in_place`), as they +//! would for a texture made then, it waits for a switch; else it stays a shadow, as such a +//! texture is. At the switch's commit the image in place is made as the texture's making makes +//! it (`Device::in_place_image`: the declared plan, with the feedback loop usage and the +//! storage usage where the device makes them so, noted for a rebind and for its first move); +//! where the device makes none (a refused pitch, its placement), or the buffer's bytes were +//! detached or copied meanwhile, or a binding or a pass took a usage or render shadow of it, it +//! stays a shadow for good. Where every encoder of the switch's command buffer ran, the texture +//! presents the image in place from then on (`TextureShared::moved`), counted as a texture in +//! place over its class is, and in `WorkCounts::host_textures_moved_in_place`; its slots' +//! elements are written again as a storage form's are. No copy moves texels: between encoders +//! the shadow holds nothing the buffer lacks (`shadow.rs`, "The buffer is the truth"), and the +//! image in place is the buffer's bytes, whose uses hazard tracking orders after the shadow's +//! copies back and merges of every command buffer committed before (both name the buffer's +//! bytes). A view made of the texture before the move keeps the shadow, which goes on copying +//! in and back as a shadow over the same bytes beside an image in place does. The shadow's +//! image stays with the texture until it goes. +//! //! - **Which textures.** A texture's own image (not a view's), the runtime's in memory of its own //! (not shareable, not a heap's, a buffer's or the caller's), `Private`, its hazards tracked, //! whose plan [`storage_candidate`] gives `STORAGE`, and whose `VkImage` @@ -83,12 +109,14 @@ use crate::framebuffer_fetch::storage_candidate; use crate::heap_sets; use crate::image_barrier::{image_barrier, ImageDst}; use crate::image_plan::ImagePlan; +use crate::in_place::{self, Access as InPlaceAccess, PagesClass, Verdict}; use crate::memory::Placement; use crate::tracker::Access; use crate::values::StorageMode; use crate::work_counts::Counters; use crate::Device; use ash::vk; +use metal2vulkan::metal::TextureUsage; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, Weak}; use std::time::{Duration, Instant}; @@ -113,12 +141,46 @@ pub(crate) struct StorageForms { changed: Condvar, /// The textures waiting, and the switch under way: the switch's lock. waiting: Mutex, + /// The shadows over host pages made before their pages' in-place verdicts, until their + /// class's verdicts are known (`Device::in_place_verdicts_given`): then those whose verdicts + /// pass wait in [`waiting`](Self::waiting) to move in place, and the others stay shadows. + moves: Mutex>, /// Run by [`close`](Self::close) right after the flag dropped and the lock went, before /// the wake: where a thread that ends a switch may be held up (`tests/storage_forms.rs`). #[cfg(test)] pause: Option>, } +/// A shadow over host pages made before its pages' in-place verdicts, waiting for them +/// ([`StorageForms::moves`]): what decides whether it moves once they are known, read with no +/// handle of the texture taken, so the thread that gives a verdict never holds a program's +/// texture (whose last handle would then go on that thread, its ID given back after the +/// program's release). +struct MoveWait { + texture: Weak, + class: PagesClass, + usage: TextureUsage, + /// The bytes of one of its texels. + texel: u64, +} + +impl MoveWait { + /// Whether it moves, once its class knows every verdict: `None` while one is pending; else + /// whether its usage and those verdicts take an image in place (`in_place::in_place`), as + /// they would for a texture made now. + fn moves(&self, device: &Device) -> Option { + let checks = &device.shared().in_place; + let verdict = |class, access| checks.verdict(class, access); + let pending = |access| verdict(self.class, access) == Verdict::Pending; + if InPlaceAccess::ALL.into_iter().any(pending) { + return None; + } + let policy = device.compile_device().policy().host_page_textures; + let pages = (self.class, self.texel); + Some(in_place::in_place(policy, self.usage, pages, verdict).is_ok()) + } +} + /// What [`StorageForms`]'s lock guards. #[derive(Default)] struct Waiting { @@ -188,11 +250,26 @@ impl Drop for Freed { } /// A texture's storage form, made and its copy recorded into the committing command buffer's -/// last part, to swap in once the commit submitted it. +/// last part, or a shadow's image in place, made, to swap in once the commit submitted it. pub(crate) struct Prepared { texture: Texture, - plan: ImagePlan, - swapped: Arc>, + kind: Kind, +} + +/// What a [`Prepared`] swaps in. +enum Kind { + /// A fetched render target's storage form: its plan, and its image. + Form { + plan: ImagePlan, + swapped: Arc>, + }, + /// A shadow's move in place (the module docs): the aliasing image's storage, until it moves + /// in, and what its count takes (the pages' class, whether the image is pitched, whether a + /// shader writes the texture). + Move { + storage: Mutex>, + counted: (PagesClass, bool, bool), + }, } /// A switch under way (the module docs): its flag is up, and the textures it took from the @@ -282,7 +359,7 @@ impl Texture { if self.0.parent.is_some() { return; } - let Storage::Image(image) = &self.0.storage else { + let Storage::Image(image) = self.storage() else { return; }; let form = &image.form; @@ -333,8 +410,10 @@ impl Texture { /// buffer's last part); `None` where the device refuses it, or the texture may no longer /// take it. fn prepare_storage_form(&self, core: &mut EncoderCore) -> Option { - let Storage::Image(image) = &self.0.storage else { - return None; + let image = match self.storage() { + Storage::Image(image) => image, + Storage::Shadow { .. } => return self.prepare_move(), + _ => return None, }; if image.form.taken.get().is_some() || image.form.exported.load(Ordering::Relaxed) { return None; @@ -412,10 +491,91 @@ impl Texture { core.retain(Arc::clone(&swapped)); Some(Prepared { texture: self.clone(), - plan, - swapped, + kind: Kind::Form { plan, swapped }, }) } + + /// The image in place over a shadow's texels that it moves to (the module docs), made as + /// the texture's would have been had its pages' verdicts been known as it was made; `None` + /// where it may move no more (it moved, its image was handed out, its verdicts or its bytes + /// keep it a shadow, or the device makes no such image), and it stops waiting then. + fn prepare_move(&self) -> Option { + let Storage::Shadow { image, texels, .. } = &self.0.storage else { + return None; + }; + let mut pending = lock(&self.0.pending_move); + let made = pending.as_ref().and_then(|pending| { + if self.0.moved.get().is_some() || self.shadowed_again() { + return None; + } + let device = &image.device; + let checks = &device.shared().in_place; + let verdict = |class, access| checks.verdict(class, access); + let policy = device.compile_device().policy().host_page_textures; + let (class, usage) = (pending.class, pending.usage); + let pages = (class, texels.texel_bytes()); + let bytes = &texels.buffer; + if bytes.detached() || bytes.copied() { + return None; + } + in_place::in_place(policy, usage, pages, verdict).ok()?; + // As the texture would have taken it as it was made (`Device::storage_over_buffer`). + let storable = InPlaceAccess::Renders.takes(usage) + && !InPlaceAccess::Writes.takes(usage) + && in_place::STORED_TEXEL_BYTES.contains(&pages.1) + && verdict(class, InPlaceAccess::Writes) == Verdict::Passed; + let facts = (device.shared().textures).facts(device.compile_device().profile()); + let made = (&**texels, class, storable); + let descriptor = &pending.descriptor; + let (alias, pitched) = device + .in_place_image(&pending.plan, descriptor, made, &facts) + .ok()? + .ok()?; + let storage = Storage::Alias { + image: alias, + texels: Arc::clone(texels), + }; + Some(Kind::Move { + storage: Mutex::new(Some(storage)), + counted: (class, pitched, InPlaceAccess::Writes.takes(usage)), + }) + }); + if made.is_none() { + *pending = None; + } + drop(pending); + Some(Prepared { + texture: self.clone(), + kind: made?, + }) + } + + /// Whether a binding or a pass took an image of the texture's other than its shadow, made + /// from it, which a move would leave behind: a usage shadow (`texture/usage_shadow.rs`) or a + /// render shadow (`texture/ycbcr_image.rs`). + fn shadowed_again(&self) -> bool { + self.0.usage_shadow.get().is_some() || lock(&self.0.render_shadow).is_some() + } + + /// Wait, a shadow over host pages made before its pages' in-place verdicts, to move in + /// place once they pass (the module docs): `pending` what it moves with. + pub(crate) fn wait_to_move_in_place(&self, pending: in_place::PendingMove) { + let Storage::Shadow { texels, .. } = &self.0.storage else { + return; + }; + let wait = MoveWait { + texture: self.downgrade(), + class: pending.class, + usage: pending.usage, + texel: texels.texel_bytes(), + }; + *lock(&self.0.pending_move) = Some(pending); + let device = self.device(); + let forms = &device.shared().textures.storage_forms; + lock(&forms.moves).push(wait); + // The verdicts may have come since it asked them. + device.in_place_verdicts_given(); + } } /// One copy of every level, all layers at once, of an image of `plan`'s shape, of `aspects`. @@ -450,7 +610,10 @@ impl Prepared { /// its storage form's, where it swapped in; `None` where the texture's image was handed out /// meanwhile, the made image then going with the command buffer. fn swap_in(&self) -> Option<(u64, u64)> { - let Storage::Image(image) = &self.texture.0.storage else { + let Kind::Form { plan, swapped } = &self.kind else { + return None; + }; + let Storage::Image(image) = self.texture.storage() else { return None; }; let Owner::Runtime { placement: old, .. } = &image.owner else { @@ -460,13 +623,13 @@ impl Prepared { if image.form.exported.load(Ordering::Relaxed) || image.form.taken.get().is_some() { return None; } - let mut swapped = lock(&self.swapped); + let mut swapped = lock(swapped); let bytes = swapped.memory.placement.size(); // The image frees its storage form's memory from now on (`Image::drop`); its first // memory goes with its first `VkImage`, as the command buffer completes. let made = std::mem::replace(&mut swapped.memory.placement, old.handed_over()); let taken = Taken { - plan: self.plan.clone(), + plan: plan.clone(), placement: made, }; if let Err(taken) = image.form.taken.set(taken) { @@ -485,6 +648,25 @@ impl Prepared { .extend(views.drain().map(|(_, view)| view)); Some((old.size(), bytes)) } + + /// Move a shadow in place (the module docs): from now on the texture presents the image in + /// place over its texels (`TextureShared::moved`). Whether it moved: not where a binding or + /// a pass took another image of it meanwhile, the image made then going with the command + /// buffer. + fn move_in(&self) -> bool { + let Kind::Move { storage, .. } = &self.kind else { + return false; + }; + let texture = &self.texture; + if texture.shadowed_again() { + return false; + } + let Some(storage) = lock(storage).take() else { + return false; + }; + *lock(&texture.0.pending_move) = None; + texture.0.moved.set(storage).is_ok() + } } impl Device { @@ -548,6 +730,41 @@ impl Device { drop(riding); } + /// The device's in-place check gave a verdict, or settled (`in_place_check.rs`): each shadow + /// made before its pages' verdicts whose class knows them all now stops waiting for them, to + /// wait for a switch that moves it in place where they pass, or to stay a shadow where they do + /// not (the module docs); those gone stop waiting. No texture's handle is taken: the caller + /// may be the check's thread. One lock where no shadow waits. + pub(crate) fn in_place_verdicts_given(&self) { + let forms = &self.shared().textures.storage_forms; + let mut ready = Vec::new(); + { + let mut moves = lock(&forms.moves); + if moves.is_empty() { + return; + } + moves.retain(|wait| { + if wait.texture.strong_count() == 0 { + return false; + } + match wait.moves(self) { + None => true, + Some(moves) => { + if moves { + ready.push(Weak::clone(&wait.texture)); + } + false + } + } + }); + } + if !ready.is_empty() { + let mut waiting = lock(&forms.waiting); + waiting.textures.extend(ready); + forms.wanted.store(waiting.textures.len(), Ordering::SeqCst); + } + } + /// Whether a texture waits for its storage form: one atomic read, each commit's gate. pub(crate) fn storage_forms_wanted(&self) -> bool { let forms = &self.shared().textures.storage_forms; @@ -608,22 +825,37 @@ impl Device { ) { let shared = self.shared(); let forms = &shared.textures.storage_forms; - let swapped: Vec<(&Prepared, (u64, u64))> = if ran && !waiting.given_up { - prepared - .iter() - .filter_map(|form| form.swap_in().map(|bytes| (form, bytes))) - .collect() - } else { - let again = prepared.iter().map(|form| form.texture.downgrade()); - waiting.textures.extend(again); - Vec::new() - }; - if !swapped.is_empty() { + let (swapped, moved): (Vec<(&Prepared, (u64, u64))>, Vec<&Prepared>) = + if ran && !waiting.given_up { + let swapped = prepared + .iter() + .filter_map(|form| form.swap_in().map(|bytes| (form, bytes))) + .collect(); + (swapped, prepared.iter().filter(|p| p.move_in()).collect()) + } else { + let again = prepared.iter().map(|form| form.texture.downgrade()); + waiting.textures.extend(again); + (Vec::new(), Vec::new()) + }; + if !swapped.is_empty() || !moved.is_empty() { // The texture slots' elements view the new images; no command buffer that may read // them is pending (the module docs). lock(&shared.resource_ids).renew_textures(); heap_sets::renew(self); } + // Each move is counted as a texture in place over its class is, before the flag drops. + for form in &moved { + if let Kind::Move { counted, .. } = &form.kind { + let (class, pitched, written) = *counted; + shared.counts.host_texture_in_place(class, pitched, written); + shared.counts.host_texture_moved_in_place(); + let feedback = metal2vulkan::vk::ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT; + let plan = form.texture.image_plan(); + if plan.is_ok_and(|plan| plan.usage.contains(feedback)) { + shared.counts.feedback_loop_alias_image(); + } + } + } // The lock goes, then the announcements, which run the program's callback. forms.close(waiting, &shared.counts, swapped.len()); for (form, (old_bytes, bytes)) in swapped { diff --git a/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs b/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs index 5b7c1bb85..da662f204 100644 --- a/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs +++ b/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs @@ -84,7 +84,7 @@ impl Texture { true => (ImageUsageFlags::STORAGE, TextureUsage::SHADER_WRITE), false => (ImageUsageFlags::SAMPLED, TextureUsage::SHADER_READ), }; - match &self.0.storage { + match self.storage() { Storage::Image(image) | Storage::Alias { image, .. } | Storage::Shadow { image, .. } => { @@ -251,7 +251,7 @@ impl Texture { if record.presented.rotation != 0 { return Err(Error::NotImplemented(RuntimeGap::RotatedTexture)); } - let (image, copies, truth) = match &self.0.storage { + let (image, copies, truth) = match self.storage() { Storage::Image(image) => { let base = match &image.owner { Owner::ViewShadow(shadow) => &shadow.base, @@ -302,7 +302,7 @@ impl Texture { (None, None), )?; // The texture's own image lies in the bytes too where it aliases them. - if matches!(self.0.storage, Storage::Alias { .. }) { + if matches!(self.storage(), Storage::Alias { .. }) { copies.backing = copies.backing.aliased(); } ( diff --git a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs index 6d8276c0a..2e174d8fe 100644 --- a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs +++ b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs @@ -117,7 +117,7 @@ impl Texture { if let Some(storage) = self.converted_view(call, record) { return storage; } - match &self.0.storage { + match self.storage() { Storage::Image(image) => { let base = match &image.owner { Owner::ViewShadow(shadow) => &shadow.base, @@ -156,8 +156,10 @@ impl Texture { let layout = descriptor .check(self.device().properties().texture_rules()) .map_err(|_| refused(None))?; + // A view's storage never moves in place (`texture/storage_form.rs`). + let over = (Arc::clone(texels), &mut None); self.device() - .storage_over_buffer(call, Arc::clone(texels), &descriptor, &layout) + .storage_over_buffer(call, over, &descriptor, &layout) } // A texture buffer's views are texel buffer views of its bytes, which take any // format of its class (`Texture::view`). @@ -172,7 +174,7 @@ impl Texture { &self, record: &ViewRecord, ) -> Option<(Arc, (PixelFormat, TextureSwizzleChannels))> { - let Storage::Image(image) = &self.0.storage else { + let Storage::Image(image) = self.storage() else { return None; }; let base = truth(image); @@ -195,7 +197,7 @@ impl Texture { self.0.record.read_as?; Some(Texture::made( self.device(), - self.0.storage.clone(), + self.storage().clone(), self.0.record.bound(), Some(self.clone()), IdUse::Runtime, @@ -214,7 +216,7 @@ impl Texture { if let Some(shadow) = held.as_ref() { return Ok(shadow.clone()); } - let Storage::Image(image) = &self.0.storage else { + let Storage::Image(image) = self.storage() else { return Err(internal("a view read through its image without one")); }; let record = ViewRecord { diff --git a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs index 48b8f9f5e..99ecb94d4 100644 --- a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs @@ -461,7 +461,7 @@ impl Texture { call: &'static str, record: &ViewRecord, ) -> Option> { - let Storage::Shadow { texels, copies, .. } = &self.0.storage else { + let Storage::Shadow { texels, copies, .. } = self.storage() else { return None; }; let ShadowSource::Converted { conversion, .. } = &copies.source else { @@ -535,7 +535,7 @@ impl Texture { call: &'static str, record: &ViewRecord, ) -> Option> { - let Storage::Shadow { texels, copies, .. } = &self.0.storage else { + let Storage::Shadow { texels, copies, .. } = self.storage() else { return None; }; let ShadowSource::Converted { conversion, .. } = &copies.source else { @@ -601,7 +601,7 @@ impl Texture { /// Whether this two-plane YCbCr texture reads each code alone, over a surface of a P3 matrix /// (`ycbcr.rs`): a pass that loads it loads nothing measured. pub(crate) fn ycbcr_codes_alone(&self) -> bool { - let Storage::Shadow { copies, .. } = &self.0.storage else { + let Storage::Shadow { copies, .. } = self.storage() else { return false; }; let ShadowSource::Converted { conversion, .. } = &copies.source else { @@ -625,7 +625,7 @@ impl Texture { let pf = self.0.record.pixel_format; let gap = || Error::Unsupported(Unsupported::not_implemented(Feature::Format).naming_format(pf)); - let Storage::Shadow { texels, copies, .. } = &self.0.storage else { + let Storage::Shadow { texels, copies, .. } = self.storage() else { return Err(gap()); }; let ShadowSource::Converted { conversion, .. } = &copies.source else { @@ -736,7 +736,7 @@ impl Texture { let pf = self.0.record.pixel_format; let gap = || Error::Unsupported(Unsupported::not_implemented(Feature::Format).naming_format(pf)); - let Storage::Shadow { texels, copies, .. } = &self.0.storage else { + let Storage::Shadow { texels, copies, .. } = self.storage() else { return Err(gap()); }; let ShadowSource::Converted { conversion, .. } = &copies.source else { diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 5bd0677ad..7b7dd01de 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -379,6 +379,7 @@ pub(crate) struct Counters { in_place_checks_failed: AtomicU64, in_place_checks_unchecked: AtomicU64, in_place_checks_recalled: AtomicU64, + host_textures_moved_in_place: AtomicU64, fresh_page_buffers_made: AtomicU64, fresh_page_bytes: AtomicU64, new_buffer_bytes_cleared: AtomicU64, @@ -2999,6 +3000,12 @@ impl Counters { (self.in_place_checks_recalled).fetch_add(1, Ordering::Relaxed); } + /// A shadow over host pages made before its pages' in-place verdicts moved in place once + /// they passed (`texture/storage_form.rs`). + pub(crate) fn host_texture_moved_in_place(&self) { + (self.host_textures_moved_in_place).fetch_add(1, Ordering::Relaxed); + } + /// A buffer was made in `bytes` of fresh pages it imported, which read zero unwritten /// (`fresh_pages.rs`). pub(crate) fn fresh_page_buffer_made(&self, bytes: u64) { @@ -5911,7 +5918,8 @@ pub struct WorkCounts { 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 - /// first session's, before the verdicts are kept). + /// first session's, before the verdicts are kept): each moves in place once they pass + /// (`host_textures_moved_in_place`). pub host_texture_shadows_check_pending: u64, /// Textures over host pages made shadows because the device's check of their class and /// access found a byte changed. @@ -5960,6 +5968,11 @@ pub struct WorkCounts { /// Classes and accesses whose verdict was read from the record of an earlier check of the /// same driver, device and runtime: no check ran for them. pub in_place_checks_recalled: u64, + /// Textures over host pages made shadows before their pages' in-place verdicts (counted in + /// `host_texture_shadows_check_pending`) that moved in place once the verdicts passed, at + /// the commit of the device's only uncommitted command buffer (`texture/storage_form.rs`): + /// each is counted in `host_textures_in_place` too from then on. + pub host_textures_moved_in_place: u64, /// Buffers of the runtime's own made in fresh anonymous pages imported by their pointer /// (`VK_EXT_external_memory_host`), which read zero with nothing written: host-visible ones /// longer than half a pooled block, not of a heap, where the device takes such pages. A @@ -7186,6 +7199,8 @@ impl Device { in_place_checks_failed: counters.in_place_checks_failed.load(Ordering::Relaxed), in_place_checks_unchecked: counters.in_place_checks_unchecked.load(Ordering::Relaxed), in_place_checks_recalled: counters.in_place_checks_recalled.load(Ordering::Relaxed), + host_textures_moved_in_place: (counters.host_textures_moved_in_place) + .load(Ordering::Relaxed), fresh_page_buffers_made: counters.fresh_page_buffers_made.load(Ordering::Relaxed), fresh_page_bytes: counters.fresh_page_bytes.load(Ordering::Relaxed), new_buffer_bytes_cleared: counters.new_buffer_bytes_cleared.load(Ordering::Relaxed), 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 d735462c4..ca71fd3fa 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/in_place_textures.rs @@ -46,6 +46,20 @@ //! `HostPageTexturePolicy::Shadow` every one is the exact form's (`host_texture_shadows_exact`). //! Each shadow that renders also counts in `host_texture_shadows_render_target`, and each one a //! shader writes in `host_texture_shadows_shader_write`. +//! - [`a_texture_made_before_its_verdict_moves_in_place_once_it_passes`], under the validation +//! layer: on a device whose check has not run, a 256x64 `BGRA8Unorm` texture of `ShaderRead` and +//! `RenderTarget` usage over a no-copy buffer of anonymous pages, of packed rows, is a shadow +//! made before its verdict (`host_texture_shadows_check_pending`; `vk_image` answers none), and a +//! blit reads the pages' bytes through it. Once the check answered, a texture of the same shape +//! over other pages takes the path its verdicts give, and by the end of the next command buffer +//! (a blit that reads the first texture, committed while no other is open) the first has moved +//! to it: where the second is in place, the first is in place, moved at that commit or at one +//! of the check's own passes, each committed while no other command buffer was open +//! (`host_textures_moved_in_place`, `host_textures_in_place`; `vk_image` answers one); a blit +//! then reads a CPU write made after +//! its commit and before it runs with no shadow copy (`shadow_copies`), and a pass that clears +//! and stores it writes the clear into the pages, every byte past its texels kept; else it stays +//! a shadow, no move counted. Printed (`IN-PLACE-MOVE`): each texture's path and the counts. //! - [`a_failed_check_keeps_the_shadow_and_no_record`], under the validation layer: a device made //! to fail its check (`DeviceOptions::fail_in_place_check`) answers failed or unchecked for every //! class and makes such a texture a shadow counted as the failed check's, never in place, and @@ -163,6 +177,15 @@ pub(super) fn sampled( buffer.new_texture(&d, 0, bpr).unwrap() } +/// A texture of `format`, `w` by `h`, of `ShaderRead` and `RenderTarget` usage, over `buffer` +/// with rows `bpr` apart. +fn rendered(buffer: &Buffer, format: PixelFormat, (w, h, bpr): (u64, u64, u64)) -> Texture { + let mut d = TextureDescriptor::texture_2d(format, w, h, false); + d.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + d.resource_options = buffer.resource_options(); + buffer.new_texture(&d, 0, bpr).unwrap() +} + /// A texture of `format`, `w` by `h`, of `ShaderRead` and `ShaderWrite` usage, over `buffer` with /// rows `bpr` apart. fn written(buffer: &Buffer, format: PixelFormat, (w, h, bpr): (u64, u64, u64)) -> Texture { @@ -379,6 +402,189 @@ fn sampled_textures_over_host_pages_take_the_path_their_check_answered() { assert!(lapses.is_empty(), "{}", lapses.join("\n")); } +/// The path of a texture over host pages: its image in place (`vk_image` answers one) or a shadow. +fn path_of(texture: &Texture) -> &'static str { + // SAFETY: the handle is only compared, while the texture lives. + match unsafe { texture.vk_image() } { + Some(_) => "in place", + None => "shadow", + } +} + +#[test] +fn a_texture_made_before_its_verdict_moves_in_place_once_it_passes() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let mut lapses = Vec::new(); + { + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), in_place).unwrap(); + let queue = device.new_command_queue().unwrap(); + let hold = device.new_shared_event().unwrap(); + let (format, texel, w, h) = (PixelFormat::BGRA8Unorm, 4u64, 256u64, 64u64); + let bpr = w * texel; + let shape = (w, h, texel); + let len = ((bpr * h) as usize + GUEST_PAGE).next_multiple_of(GUEST_PAGE); + let mappings = [Mapping::anonymous(len), Mapping::anonymous(len)]; + let mut buffers = Vec::new(); + for mapping in &mappings { + // SAFETY: the mappings outlive the buffers and the textures (dropped first). + match unsafe { + no_copy( + &device, + mapping.pointer(), + len, + ResourceOptions::default(), + None, + ) + } { + Ok(buffer) => buffers.push(buffer), + Err(error) if not_importable(&error) => { + eprintln!("IN-PLACE-MOVE: the device imports no host memory: {error:?}"); + return; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + } + } + let write = |buffer: &Buffer, bytes: &[u8]| { + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer's first `len` bytes, which no command uses meanwhile (a blit + // that reads them waits for the event the CPU signals after this). + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) } + }; + let pages = |buffer: &Buffer| -> Vec { + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer's first `len` bytes, which no command writes any longer. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), len) }.to_vec() + }; + // A blit's read of `texture`, its command buffer committed while no other is open. + let read = |texture: &Texture| -> Vec { + let out = device + .new_buffer(bpr * h, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(w, h, 1), + &out, + 0, + bpr, + bpr * h, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + let contents = out.contents().unwrap(); + // SAFETY: the buffer's `bpr * h` bytes, which no command writes any longer. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), (bpr * h) as usize) }.to_vec() + }; + let first = counting(len, 7); + write(&buffers[0], &first); + let before = device.work_counts(); + let early = rendered(&buffers[0], format, (w, h, bpr)); + let made = device.work_counts(); + let pending = + made.host_texture_shadows_check_pending - before.host_texture_shadows_check_pending; + let early_path = path_of(&early); + if (early_path, pending) != ("shadow", 1) { + lapses.push(format!( + "made before its verdict: {early_path}, counted pending {pending}" + )); + } + if read(&early) != texels_of(&first, shape, bpr) { + lapses.push("before the verdict: a blit read other than the pages".to_owned()); + } + let before = device.work_counts(); + settled(&device); + // A quiet commit after the verdicts moves the first texture where a texture made now is + // in place: the check's own (its passes are committed while no other command buffer is + // open) or the program's next. + let moved_by_the_check = + device.work_counts().host_textures_moved_in_place - before.host_textures_moved_in_place; + let late = rendered(&buffers[1], format, (w, h, bpr)); + let late_path = path_of(&late); + let moved_read = read(&early); + let after = device.work_counts(); + let moved = after.host_textures_moved_in_place - before.host_textures_moved_in_place; + // Counted in place as it moved, beside the second where that is in place. + let late_in_place = u64::from(late_path == "in place"); + let in_place = after.host_textures_in_place - before.host_textures_in_place - late_in_place; + let path = path_of(&early); + eprintln!( + "IN-PLACE-MOVE on {}: made before its verdict: {early_path} (pending {pending}); one \ + made after it: {late_path}; the first after the next commit: {path} (moved {moved}, \ + {moved_by_the_check} of them at the check's commits, in place {in_place})", + device.name() + ); + if moved_read != texels_of(&first, shape, bpr) { + lapses.push("at the move: a blit read other than the pages".to_owned()); + } + let expected = match late_path { + "in place" => ("in place", 1, 1), + _ => ("shadow", 0, 0), + }; + if (path, moved, in_place) != expected { + lapses.push(format!( + "after the next commit: {path} (moved {moved}, in place {in_place}), where one \ + made after the verdict is {late_path}" + )); + } + // A CPU write made after the commit and before the blit runs, read with no copy. + let later = counting(len, 101); + let before = device.work_counts(); + let held = read_held(&queue, &early, shape, &hold, 1, || { + write(&buffers[0], &later) + }); + let after = device.work_counts(); + let copies = after.shadow_copies - before.shadow_copies; + if held != texels_of(&later, shape, bpr) { + lapses.push("after the move: a blit read other than the CPU wrote".to_owned()); + } + eprintln!( + "IN-PLACE-MOVE on {}: a held read after it took {copies} shadow copies", + device.name() + ); + if path == "in place" && copies != 0 { + lapses.push(format!("in place, a read took {copies} shadow copies")); + } + // A pass that clears and stores it: the clear in the pages, the bytes past them kept. + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(early.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(0.0, 1.0, 0.0, 1.0); + let command_buffer = queue.command_buffer().unwrap(); + let encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + let cleared = pages(&buffers[0]); + let green = [0x00, 0xff, 0x00, 0xff]; + let texels = (bpr * h) as usize; + if !cleared[..texels].chunks(4).all(|t| t == green) { + lapses.push("the pass's clear is not in the pages".to_owned()); + } + if cleared[texels..] != later[texels..] { + lapses.push("the pass changed a byte past the texels".to_owned()); + } + drop((early, late, buffers)); + drop(mappings); + for notice in messages.take_notices() { + eprintln!("IN-PLACE-MOVE notice: {}", notice.text); + } + } + layer_reported_nothing_at_all(&messages); + assert!(lapses.is_empty(), "{}", lapses.join("\n")); +} + /// The `RGBA16Float` texel the kernel writes and the pass clears to: `half4(0.25, 0.5, 0.75, 1)`. const VALUE: [u8; 8] = [0x00, 0x34, 0x00, 0x38, 0x00, 0x3a, 0x00, 0x3c]; diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 5bcf9e607..686b6bc0c 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2796,6 +2796,7 @@ field metal2vulkan-runtime::WorkCounts.images_started_on_the_host pub images_sta field metal2vulkan-runtime::WorkCounts.in_place_checks_failed pub in_place_checks_failed: u64 field metal2vulkan-runtime::WorkCounts.in_place_checks_passed pub in_place_checks_passed: u64 field metal2vulkan-runtime::WorkCounts.in_place_checks_recalled pub in_place_checks_recalled: u64 +field metal2vulkan-runtime::WorkCounts.host_textures_moved_in_place pub host_textures_moved_in_place: u64 field metal2vulkan-runtime::WorkCounts.in_place_checks_run pub in_place_checks_run: u64 field metal2vulkan-runtime::WorkCounts.in_place_checks_unchecked pub in_place_checks_unchecked: u64 field metal2vulkan-runtime::WorkCounts.indirect_chunks_kept pub indirect_chunks_kept: u64 diff --git a/docs/API.md b/docs/API.md index 0a4525483..659f024ab 100644 --- a/docs/API.md +++ b/docs/API.md @@ -346,7 +346,9 @@ through an unsigned-integer view of 4, 8 or 16-byte texels while the CPU writes them (a program's atomics are among no round). It runs on a thread of its own, which the first such texture starts; a texture made before its kind of pages and access has its verdict is a shadow, made without waiting for the check -(`WorkCounts::host_texture_shadows_check_pending`). It runs once per driver and driver version: its +(`WorkCounts::host_texture_shadows_check_pending`), and moves in place, with no copy, at a quiet +commit once its kind's verdicts pass (`WorkCounts::host_textures_moved_in_place`; docs/HOWTO.md +says which commits). It runs once per driver and driver version: its verdicts are kept in the shader cache's directory, named by the driver and the check's own version, not the runtime's (a device without one checks once per process), and recalled as the next device is made diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index d4e84712f..caabd5b4f 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. 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 and access, 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`). 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; a resolve into it is not among the rounds), and, for one a shader writes, of 4, 8 and 16-byte texels, rows apart (of widths no multiple of 4 and odd heights among them) or tight, and 1920x1080, each texel stored by a kernel through an unsigned-integer view (a program's atomics, and its stores through a float view, are not among the rounds); a driver whose operations changed a byte outside every round's window would undo a CPU write made meanwhile. Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer, and a render target's shadow copies it in, keeps it and merges it back at each render pass instance | +| A texture that samples, reads, renders into it or is written through a shader (`ShaderWrite` or `ShaderAtomic` usage, of texels of 4, 8 or 16 bytes) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages) is a linear image aliasing the pages in place, where the device makes the image (its format and usage linear, at the pages' pitch) and its own check shows that the operations Vulkan lets read and write every byte bound to it leave every byte alone while the CPU writes beside it: the image's first move (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), and for one that renders a render pass's load and store operations and its moves into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` and back, and for one a shader writes a kernel's storage writes of its texels (which of a linear image a driver may widen past a texel), each access checked apart. 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 and access, 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 kept until the texture goes. 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; a resolve into it is not among the rounds), and, for one a shader writes, of 4, 8 and 16-byte texels, rows apart (of widths no multiple of 4 and odd heights among them) or tight, and 1920x1080, each texel stored by a kernel through an unsigned-integer view (a program's atomics, and its stores through a float view, are not among the rounds); a driver whose operations changed a byte outside every round's window would undo a CPU write made meanwhile. Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer, and a render target's shadow copies it in, keeps it and merges it back at each render pass instance | | A 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 3c0776a88..5afcef8e5 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -306,9 +306,13 @@ kernel's storage writes, for one a shader writes) kept every byte. It runs on a driver version; with a shader-cache directory its verdicts are kept there, named by the driver and the check's own version (not the runtime release), and recalled as the next device is made, else it runs once per process. A texture made before its verdict is a shadow, made without waiting for -the check (`WorkCounts::host_texture_shadows_check_pending`): a program that makes such textures -as it starts (a compositor's framebuffers) and wants them in place on a driver's first run starts -the check earlier, for instance as it makes the device, with `Device::settle_in_place_checks` and a +the check (`WorkCounts::host_texture_shadows_check_pending`), and moves in place once its kind's +verdicts pass, with no copy (`WorkCounts::host_textures_moved_in_place`), at a quiet commit: one +made while no other command buffer of the device is uncommitted, that waits for no event and binds +no texture by its ID, while none that does is still running (a program that never commits so +keeps them shadows). A program that makes such textures as it starts (a compositor's +framebuffers) and wants them in place from their first use on a driver's first run starts the +check earlier, for instance as it makes the device, with `Device::settle_in_place_checks` and a zero timeout, which waits for nothing. 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 no image in place serves (a pitch the device's linear images do not take --