From 30c8b4bff85dd1900bceed1938da0cb16f62a504 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 14 Oct 2026 17:01:33 +0300 Subject: [PATCH] Shadow a padded texture over a buffer exactly, and cut the shadow's cost The padded-texture work packet. A texture over a buffer whose image would hold bytes that are not its texels is drawn through a shadow image with exact copies, since a render pass or a layout transition may write those bytes. Then the shadow's cost is cut, exactly: no copies for a pass that reaches no tile, a copy back bounded by the draws' scissors, and cost lines that show each part. Shadow a texture over a buffer whose image would hold bytes that are not its texels: A texture over a buffer is a linear (or DRM_FORMAT_MOD_LINEAR) image over the buffer's bytes only where every byte of the image's subresources is one of its texels: its rows lie one after another (or it has one), its slices likewise, and its last subresource ends at its texels' last byte or before. Anything else is the shadow, whose copies address the buffer's texels alone. The Metal texture over an MTLBuffer (MoltenVK) is exempt: every write through it is Metal's own. Why: Vulkan lets a render pass's load and store operations "read and write back any memory locations within the image subresource bound for that attachment" (renderpass.adoc, Load and Store Operations), and VkSubresourceLayout's size "includes any extra memory that is required based on rowPitch", so the bytes between padded rows lie inside the subresource. Metal leaves them as the program writes them. No query promises otherwise, so no image may alias padded rows. Bytes past every subresource stay allowed: Memory Aliasing bounds the bytes a write through an image affects to "those overlapped by the image subresources that were written". Measured on lavapipe (Mesa 26.2.4 llvmpipe, gem10) at the round's base: pitched_surfaces' 657x128/5312 RGBA16Float tile took lavapipe's own linear image (its pitch 660 texels rounded to 64 bytes is the lane's 5312), and a clear-blend-store pass rewrote 13 padding bytes in 13 rows (row 3 byte 5265 0x7c -> 0x7e: texels 657..659 of its 4-texel blocks read and written back, signaling NaNs quieted). The reliance predates 1cf79a9617 (own linear images whose pitch equals bytesPerRow, the dma-buf explicit planes); 1cf79a9617 made it every padded surface on ANV and NVIDIA's wider pitches. How: linear_plan's padding() and texels_alone(), used by alias_image (before any image is made), aliases() (now given the subresource's size), host_alias_unbound (the own linear image's fit and the pitched image's), the dma-buf alias (before the pages' source is asked, counted as a fallback; its plane's size checked for textures over buffers, not heaps') and the rebind (the alias kind keeps the texels' layout). Importer::makes_modifier_images, a duplicate of makes_dma_buf_images, is folded into it. RUNTIME_VERSION 1188. Tests: the aliases unit test covers padded rows, slices apart, a one-row pitch, a subresource past the texels and a whole-array report. pitched_surfaces checks the pages after every step (now naming the changed bytes outside the texels), asserts padded rows are never aliased off MoltenVK, adds a load-blend-DontCare step, packed layouts of 510 and 126 rows and of 200, and a fragment function's writes over six layouts (shader read/write usage). no_copy_textures asserts padded rows shadow off MoltenVK (it asserted ANV's pitched image); dma_buf_imports' 60-texel case now shadows. Docs: API.md (the extension paragraph and the shadowed-texture entry), ShadowedTexture's rustdoc, HOWTO.md section 6, Texture::vk_image, dma_buf.rs, and a known-gap entry in FAST-PATHS.md with ANV's cost (making the browser tile ~135 us as a shadow vs ~41 us as a pitched image, 1cf79a9617's numbers). Verified on lavapipe (gem10, release, --cfg m2v_cpu_icd, LP_NUM_THREADS=1): runtime_lane's pitched_surfaces, no_copy_textures, buffer_texture_blits, dma_buf_imports, linear_attachments, buffer_textures, buffer_texture_order, buffer_texture_renders, dont_care_stores, kept_buffer_bytes, rotated_textures, and tests::linear_plan / degradation: 137 of 140 passed; a_half_float_tile passes (it failed at the base), every padded layout is shadowed, 300x200/1200 is a pitched image. The three failures: the runtime-sources pin (written here), and the two packed odd-height layouts, 658x126/5264 (rows 126..127 past the texture rewritten) and 1308x510/5232 (SIGSEGV, rows 510..511 written past the mapping): a lavapipe defect of explicit DRM_FORMAT_MOD_LINEAR planes, handled in the next part. GPU lanes (ANV, RADV, NVIDIA, MoltenVK) not run yet. Make no explicit-plane modifier image of an odd height where lavapipe renders rows past it: RuntimeDriverDefect::ExplicitPlaneRowsPastHeight: a DRM_FORMAT_MOD_LINEAR image whose one plane the caller lays out (VkImageDrmFormatModifierExplicitCreateInfoEXT) is rendered in blocks of 4 rows, its rows past its height up to a multiple of 4 written past its subresource and past its memory requirements. On a driver with the defect (lavapipe, MESA_LLVMPIPE, every release until a probe finds one clean) neither host_pitched_image nor the dma-buf image (textures over buffers and heaps' textures alike) is made of a height that is no multiple of 4: the texture takes its shadow, announced as shadowed-texture with the defect named. The trigger is structural (the image's height); the driver's own linear images are untouched, as they report the rounded rows in their subresource (the previous part's texels_alone then shadows them). Why: a write past an image's own memory is a spec violation no query reveals. Measured on lavapipe (Mesa 26.2.4, llvmpipe LLVM 23.1.1 256 bits, gem10, release, LP_NUM_THREADS=1) at the previous commit, pitched_surfaces' packed odd-height layouts, each a pitched image (pitched host images 1): 658x126/5264 RGBA16Float, a load-blend-store pass rewrote 21 bytes of rows 126..127 past the texture (signaling NaNs quieted); 1308x510/5232 BGRA8Unorm, the same pass wrote rows 510..511 past the no-copy buffer's mapping and the process took SIGSEGV. lavapipe 26.0.8 is unprobed. How: Device::explicit_plane_rows (dma_buf.rs), asked by host_pitched_image and dma_buf_image_unbound after their format checks. The registry entry and its test, the variant's rustdoc, ShadowedTexture's rustdoc and API.md's shadowed-texture entry. No refusal is added, so docs/REFUSALS.md has no row for it (refusal_surface.py --check passes); the api_surface table names the enum, not its variants. RUNTIME_VERSION 1189. Verified: see the landing run (lavapipe, the pitched_surfaces odd-height layouts shadowed and passing). Record that an image over host-pointer pages keeps its bytes past its first move only by drivers: A known gap in docs/FAST-PATHS.md, and a lane check that turns a driver that drops the bytes into a visible failure. No behaviour changes (no RUNTIME_VERSION bump): whether every texture over pointer-imported pages becomes a shadow is the owner's call. The gap: an image of host allocations must start UNDEFINED (VUID-VkImageCreateInfo-pNext-01443), and a transition from UNDEFINED "will cause the contents of the image's memory to be undefined" (resources.adoc, VkImageLayout). Memory imported from a host pointer "shares ownership of the memory between the host and the Vulkan implementation", with host access synchronized as for any memory (memory.adoc, VkImportMemoryHostPointerInfoEXT), so the external-memory acquire from VK_QUEUE_FAMILY_EXTERNAL/FOREIGN is not blessed for it. sync2's ignored-layout barrier keeps contents but leaves the image UNDEFINED, invalid to use as GENERAL. Paths that rely on the drivers: host_linear_image, host_pitched_image, and metal_alias_image (VkImportMetalTextureInfoEXT says nothing of contents). Spec-backed: dma-buf images, acquired from VK_QUEUE_FAMILY_FOREIGN_EXT in GENERAL (the external memory chapter's ownership transfer and its note that the UNDEFINED initial layout is a placeholder), and the runtime's own linear images, made PREINITIALIZED. The check: pitched_surfaces::a_texture_s_first_use_reads_the_bytes_it_was_made_over makes a texture over each layout and reads it first through its image (a fragment function's read) before anything else touches the pages: the read must be the pages' texels and the pages unchanged. Verified: see the landing run (lavapipe). Expect a shadow wherever no linear image holds a texture's texels alone: The runtime aliases a texture over an ordinary buffer with a linear image only where the image's subresource holds the texture's texels and nothing else (linear_plan::texels_alone): no padding between rows, the driver's row pitch Metal's, and no subresource bytes past the last texel. The lanes' expectation helper, buffer_texture_blits::linear_rows_differ, compared only the driver's row pitch, so on lavapipe, whose linear 64x2 RGBA8Uint at a 256-byte pitch reports a 1024-byte subresource (its height rounded up to 4 rows) while the texels end at 512, resource_ids expected no shadow and failed with "announced past []: [ShadowedTexture, UnnamedShadowedTexture]". The helper now applies the same rule: rows with bytes between them, a subresource offset other than 0, a row pitch other than the buffer's, or a subresource size past (height - 1) * row + width * texel. It takes the texel size, which every caller knows. The callers' expectations move the same way: resource_ids' 64-texel rows (the size rule), buffer_texture_blits' 4x4 textures at 32-byte rows and the IOSurface planes at 9, 20 and 40 bytes, and view_reinterpretation's rows 16 bytes past their texels (the padding rule, which shadows them on every device). Verified on gem10's lavapipe (Mesa 26.2.4, --cfg m2v_cpu_icd, LP_NUM_THREADS=1, release): the focused filter over pitched_surfaces, no_copy_textures, buffer_texture_blits, dma_buf_imports, linear_attachments, buffer_textures, buffer_texture_order, buffer_texture_renders, dont_care_stores, kept_buffer_bytes, rotated_textures, resource_ids, view_reinterpretation and the runtime's linear_plan, degradation and driver_defects tests: 186 of 187 pass, resource_ids' a_buffer_under_a_texture_goes_at_its_release_whatever_keeps_the_image among them; the one failure is the runtime-sources pin, which moves with this work (below). Test-only: no runtime source changes. Name the layout transitions as what may write a padded texture's padding: A texture over a buffer whose rows (or slices) lie with bytes between them is a shadow off MoltenVK, since an image over those rows would hold the bytes between them in its subresource. The shadowed-texture notice gave one reason for every such texture: Vulkan lets a render pass's load and store operations write those bytes back. That cannot apply to a texture without RenderTarget usage, which never becomes an attachment, and ms01's A/B saw read-only padded textures shadowed under that reason. For such a texture the basis is the layout-transition rule (the Synchronization chapter's Image Layout Transitions): "Image layout transitions may perform read and write accesses on all memory bound to the image subresource range", and "If the old layout is VK_IMAGE_LAYOUT_UNDEFINED, the contents of that range may be discarded". Every image takes one transition before any use: its first move into GENERAL, from UNDEFINED for imports (VUID-VkImageCreateInfo-pNext-01443) or PREINITIALIZED for ordinary buffers. No descriptor or copy takes an image in either layout, and host image copy's transition is a transition too. So no transition-free path exists for a read-only linear image, and the shadow stays. After the first move every runtime image rests in GENERAL, so no later barrier transitions it; copies and shader accesses touch texels alone (the Memory Model: "A memory operation must not affect memory at a memory location not within its set of memory locations"). linear_plan::padding now takes whether the texture renders (RenderTarget usage). Its reason names the layout transitions, its first move among them, and for a render target also the render pass's load and store operations. The doc comment quotes both texts. The ShadowedTexture rustdoc, docs/API.md's catalogue entry, docs/HOWTO.md, docs/FAST-PATHS.md's known gap, and the dma_buf.rs and linear_plan.rs module docs say the same. Tests: - tests::linear_plan::a_padded_texture_s_shadow_names_what_may_write_its_padding checks both reasons' exact text. - The lane test pitched_surfaces::a_padded_texture_s_shadow_names_what_may_write_its_padding makes the browser's 1307x512/5248 tile over an ordinary buffer, which shadows on every device, MoltenVK included. It runs a fresh device per usage (ShaderRead; RenderTarget | ShaderRead) and checks the shadowed-texture notice's reason. RUNTIME_VERSION 1190 (fleet/round's 1189 + 1). The runtime-sources pin is recomputed at this tree. Verified on gem10's lavapipe (Mesa 26.2.4, llvmpipe LLVM 23.1.1, --cfg m2v_cpu_icd, LP_NUM_THREADS=1, release). The focused filter (pitched_surfaces, no_copy_textures, buffer_texture_blits, dma_buf_imports, linear_attachments, buffer_textures, buffer_texture_order, buffer_texture_renders, dont_care_stores, kept_buffer_bytes, rotated_textures, resource_ids, view_reinterpretation, and the runtime's linear_plan, degradation and driver_defects tests) ran 189 tests. 188 passed, both new tests among them, printing: - ShaderRead: "its rows lie 5248 bytes apart, 5228 bytes of texels each: an image over them holds the bytes between them, which Vulkan lets its layout transitions read and write, its first move from the layout it is made in among them" - RenderTarget: "... which Vulkan lets its layout transitions read and write, and a render pass's load and store operations write back" The one failure was the runtime-sources pin before this commit set it (860ca881...). Clippy with all features (no cfg) is clean. Take the surface texture cost frame apart, per part and per texture: surface_texture_costs measures a browser-like frame: five surface textures over new no-copy buffers, each loaded and stored by a pass that draws nothing, then each blitted into a private texture. On ANV, ms01 measured commit-to-completion rising by about 2.8 ms a frame where four of them became shadows. That number alone cannot say where the time goes: the shadows' copies in and back, their making and release, or work beside them. It also cannot say why the packed 1024x512/4096 tile, which stays the driver's own linear image in both forms, took longer to make. The new ignored measurement surface_texture_cost_parts (run by name, release, as the others) runs the frame over anonymous pages in parts: - Empty: the textures made and released around an empty command buffer. - PassesStored: Load/Store passes, i.e. a shadow's copy in and copy back. - PassesNotStored: Load/DontCare passes, a copy in only. - PassesDrawn: Load passes that blend a rectangle and store, as a browser's passes draw. - Blits: the blits alone, which read a texture over a buffer as its bytes. - Both: the original frame. It runs over every layout, then over the packed layouts alone, so no shadow is made beside them. Per set and part it prints (SURFTEX-PART): the forms; each texture's making median and p90; the frame's release, encoding, commit-to-completion and process CPU time; and the per-frame work counts. frame() takes the part, and surface_texture_costs passes Part::Both, so its own output is unchanged. Test-only. It compiles at fleet/base as well (it names nothing newer), so the same measurement runs on the earlier form. Checked with clippy --cfg m2v_gpu, all targets and features, -D warnings, on gem10. Copy no shadow in or back for an attachment a pass that reaches no tile loads: A texture over a buffer whose image would hold bytes that are not its texels is a shadow: an image of its own that encoders copy the texels into before use and back after a write. A render pass copied its shadowed color attachment in before the pass and back after it whenever it loaded and stored it, even where the pass reached no tile: no draw call, or draw calls that draw nothing (clear_reach::PassReach::Nothing). Such a pass changes no texel: - Metal loads and stores only the tiles a draw reaches (PassReach's EVs). - Vulkan's load and store write back what they read: "Load operations only update values within the defined render area", and store operations alike. So the copies moved a texture's every texel twice for nothing. On ANV, surface_texture_costs' frame (whose passes draw nothing) paid that for four padded surfaces since they became shadows. attachment_shadows now takes no use of such an attachment: a color attachment of a pass that reaches no tile, that loads it (Load, also a DontCare load the pass loads), stores it Store or DontCare, resolves nothing, and has no stand-in or planes, where the shadow is a plain image of a buffer's bytes (ShadowTarget::Image, writes kept). No copy in, nothing dirty, no copy back. Rotated, converted and image shadows keep their copies. The pass still renders into the shadow image, whose attachment uses order it as before. Every later use copies in again, since the shadow was never marked current. New public counter WorkCounts::shadow_copies: copies between a shadowed texture's truth and its shadow that encoders planned (in, back, keep and merge). It is counted where EncoderCore plans them and at each of the three end-of-encoder finishes. Lane test pitched_surfaces::a_pass_that_draws_nothing_copies_no_shadow: the browser's 1307x512/5248 tile over an ordinary buffer (a shadow on every device). Load/Store and Load/DontCare passes that draw nothing plan 0 copies and leave every byte of the buffer. A pass that blends a rectangle plans 2 (in and back). Without this change, the expected counts for the two empty passes are 2 and 1. This shrinks surface_texture_costs' frame, whose passes draw nothing, not a browser's, whose passes draw. surface_texture_cost_parts' PassesDrawn part measures that apart. RUNTIME_VERSION and the runtime-sources pin move with this work (below). Verified on gem10's lavapipe (Mesa 26.2.4, --cfg m2v_cpu_icd, LP_NUM_THREADS=1, release): the earlier focused filter plus the runtime's shadow tests ran 200 tests, 199 passed, the new test among them. The one failure was the pin. clippy -D warnings, all targets and features, is clean with no cfg and with --cfg m2v_gpu. Copy back only the texels inside a pass's draws' scissors: A shadowed texture's copy back after a render pass moved every texel from the shadow image to the buffer. On ANV that write-back is the shadow's cost: ms01's surface_texture_cost_parts put a stored shadow at about 0.8 ms of commit-to-completion a frame (1307x512 BGRA8). A pass that loads a color attachment changes no texel outside its draws' scissors: - "Samples with coordinates outside the scissor rectangle at the corresponding ViewportIndex will have their coverage set to 0" (the Fragment Operations chapter's Scissor Test). - "Load operations only update values within the defined render area" and "Store operations only update values within the defined render area" (the Render Pass chapter), writing back what they read. - Each Vulkan scissor is Metal's rectangle clipped to the pixels its viewport overlaps (render_state.rs's implicit scissor), so Metal's draw writes no pixel past it either. The image's other texels are what the last copy in left, which the buffer still holds, and a write of the bytes another way leaves the image stale, so they need no copy back. How: - ShadowUse gains an area: where a command writes through the texture, where it bounds that. render.rs passes the bounds of the pass's DrawnArea (its draws' Vulkan scissors) for a pass whose draws reach tiles, unless a reach clear runs before the pass, together with which color attachments the encoder set to Load, read before the DontCare loads and reach clears change any. attachment_shadows gives that area to a loaded color attachment with no resolve, stand-in or planes that is the whole of a one-level, one-slice texture. - join and ShadowSync::after keep the rectangle bounding the writes since the last copy back, or none where one does not bound them. copy_back puts it on the ShadowCopy. - record() cuts the one region of a ShadowTarget::Image without staging to it, by part_of: the buffer offset moved to the rectangle's first texel at the region's row length, clamped to the image. ShadowTarget::Image now carries its texel size (none for a heap's depth or stencil shadow, which takes no area). - Copies in still move every texel. New public counter WorkCounts::shadow_texels_copied_back: the texels copies back of buffers' textures' images move. Tests: - tests::shadow::a_copy_back_covers_only_where_the_commands_wrote: areas through ShadowSync and join. - tests::shadow::a_part_of_a_region_starts_at_its_first_texel: the region arithmetic, clamping, empty parts and tight rows. - Lane pitched_surfaces::a_pass_copies_back_only_the_texels_its_scissors_reach: the browser's 1307x512/5248 tile over an ordinary buffer (a shadow on every device), blended under a 300x200 scissor, moves 60000 texels back. The buffer then holds a private texture's blend inside the scissor and every other byte as it was. Unscissored, the pass moves all 669184. docs/FAST-PATHS.md's known gaps record the race the bound leaves: Metal stores only the 32x32 tiles a primitive touches (reims-vgpu's padding probe, M3 Max, macOS 27.0.1). A concurrent CPU write to an undrawn texel in an untouched tile inside the scissors can be undone here, where Metal keeps it. No copy reaches the bytes between rows. The batch's version commit moves RUNTIME_VERSION; the runtime-sources pin follows it. Verified on gem10's lavapipe (Mesa 26.2.4, --cfg m2v_cpu_icd, LP_NUM_THREADS=1, release). The shadow lanes (the previous part's list, plus scissors and capture_reach where they exist) and the runtime's shadow, shadow_stencil, linear_plan, degradation and driver_defects tests ran 319 tests, and 318 passed, the three new ones among them. The one failure was the runtime-sources pin. clippy -D warnings, all targets and features, --cfg m2v_gpu, is clean. Measure a scissored drawn pass and a shadow's copies alone: Two additions to the surface texture cost measurements, both ignored and run by name in release builds. surface_texture_cost_parts gains PassesScissored: the drawn pass (Load, a rectangle blended over the left half, Store) under a scissor of the left half, as a browser's pass redrawing a damaged part of a tile draws. With the previous part, its shadows copy back only the scissored half. PassesDrawn's default scissor covers the whole tile, so its copy back moves every texel. shadow_copy_costs times each copy alone in its own command buffer, committed and waited for, on the browser's 1307x512 BGRA8 tile at 5248-byte rows: - a private texture made as a shadow is (render target and shader read) into a no-copy buffer over anonymous pages: a copy back's way; - the pages into the texture: a copy in's way; - the texture into a private buffer and into a Shared buffer; - a private buffer into the pages, and back. It prints SURFTEX-COPY lines with commit-to-completion medians and p90s. These tell the image's tiling (detiling) from the pages' memory (writes into imported host memory) as the cause of ANV's copy back. Test-only. clippy -D warnings with --cfg m2v_gpu, all targets and features, is clean on gem10. Print a frame's shadow copies and the texels its copies back move in the surface cost lines: What: the surface texture cost lines' per-frame work counts (SURFTEX-COST, SURFTEX-PART) now end with the shadow copies the encoders planned and the texels their copies back moved, both per frame. Why: a change to how a shadow's image is made or copied must leave the copies and the texels they move as they were; the cost lines then show it beside the times, in the same run. Verified: test-only; built and run with the measurements on Linux hosts in the next steps (no build on the Mac). Wrap the surface texture costs' SURFTEX-QUERY sentence at 100 columns: The commit that added a frame's shadow copies to the cost lines left the module doc's SURFTEX-QUERY sentence on one 154-column line; the tree wraps doc comments at 100. Doc only. Verified: awk finds no line of the file over 100 columns but the ignored-tests sentence (110), which predates that commit; cargo fmt --all leaves the tree unchanged. Versions: RUNTIME_VERSION 1202 -> 1203. RUNTIME_VERSION moves: padded textures over buffers are drawn through shadows, and the shadows' copies change. crates/metal2vulkan-validation/runtime-sources.sha256 holds 52d6ce1648b67055d046e043e6d1cd126e0a8315d04a922261df93ad0a25f734, the hash of this tree's runtime inputs (runtime-pin.py, which reproduces build.rs's). Version numbers quoted above are the values the work's branch built with. Each part's Verified lines name the tree it ran at. --- .../src/buffer_texture.rs | 1 + .../metal2vulkan-runtime/src/clear_reach.rs | 14 + .../metal2vulkan-runtime/src/degradation.rs | 17 +- crates/metal2vulkan-runtime/src/dma_buf.rs | 50 +- .../src/driver_defects.rs | 18 + crates/metal2vulkan-runtime/src/encoder.rs | 11 + .../metal2vulkan-runtime/src/host_memory.rs | 13 +- crates/metal2vulkan-runtime/src/interop.rs | 11 +- .../metal2vulkan-runtime/src/linear_plan.rs | 100 ++- crates/metal2vulkan-runtime/src/render.rs | 24 +- .../src/render/executions.rs | 1 + .../src/render/shadows.rs | 76 +- crates/metal2vulkan-runtime/src/shadow.rs | 146 +++- .../src/tests/driver_defects.rs | 7 +- .../src/tests/linear_plan.rs | 135 +++- .../metal2vulkan-runtime/src/tests/shadow.rs | 111 +++ crates/metal2vulkan-runtime/src/texture.rs | 132 ++-- .../metal2vulkan-runtime/src/texture/heap.rs | 2 + .../metal2vulkan-runtime/src/work_counts.rs | 21 + .../runtime-sources.sha256 | 2 +- .../src/runtime_lane/buffer_texture_blits.rs | 27 +- .../src/runtime_lane/dma_buf_imports.rs | 21 +- .../src/runtime_lane/no_copy_textures.rs | 22 +- .../src/runtime_lane/pitched_surfaces.rs | 657 +++++++++++++++--- .../src/runtime_lane/resource_ids.rs | 8 +- .../src/runtime_lane/surface_texture_costs.rs | 360 +++++++++- .../src/runtime_lane/view_reinterpretation.rs | 4 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/error/mod.rs | 7 + docs/API.md | 38 +- docs/FAST-PATHS.md | 40 ++ docs/HOWTO.md | 36 +- 32 files changed, 1801 insertions(+), 313 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index 7fd5f28f0..2872bb7b8 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -1248,6 +1248,7 @@ impl Texels { image, regions, staging, + texel: Some(self.texel_bytes), }, alias: self.buffer.alias().map(|alias| alias.key), }, diff --git a/crates/metal2vulkan-runtime/src/clear_reach.rs b/crates/metal2vulkan-runtime/src/clear_reach.rs index b01a12e1c..40aacd572 100644 --- a/crates/metal2vulkan-runtime/src/clear_reach.rs +++ b/crates/metal2vulkan-runtime/src/clear_reach.rs @@ -323,6 +323,20 @@ impl DrawnArea { } } + /// The rectangle `[x0, y0, x1, y1)` bounding every rectangle, half-open in the render area's + /// pixels: `None` where the area bounds nothing, or holds no rectangle. + pub(super) fn bounds(&self) -> Option<[u32; 4]> { + if self.whole { + return None; + } + self.rects + .iter() + .copied() + .reduce(|[a0, a1, a2, a3], [b0, b1, b2, b3]| { + [a0.min(b0), a1.min(b1), a2.max(b2), a3.max(b3)] + }) + } + /// Bound nothing: the draws may write anywhere in the render area. pub(super) fn everywhere(&mut self) { self.whole = true; diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index dd74ad17f..efeebc250 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -219,13 +219,24 @@ macro_rules! degradations { degradations! { runtime { - /// A 2D texture over a buffer is a shadow image: no linear image of the device lays its - /// texels out as Metal does in the buffer's memory (over a no-copy buffer's imported + /// A 2D texture over a buffer is a shadow image: its rows (or an array's slices) lie with + /// the buffer's bytes between them, which an image over them would hold in its + /// subresource, where Vulkan lets the image's layout transitions (its first move among + /// them, which a texture that only reads takes too) read and write any byte of its + /// subresources, and a render pass's load and store operations read and write back any + /// byte of an attachment's image subresource, and Metal leaves them as the program writes + /// them (but where the device's image of it is a Metal texture over the + /// buffer, on MoltenVK); or no linear image of the device + /// lays its texels out as Metal does in the buffer's memory, holding no byte past them + /// (over a no-copy buffer's imported /// host memory, no linear image made for host allocations does: neither the driver's own /// nor, where the device enables `VK_EXT_image_drm_format_modifier`, a /// `DRM_FORMAT_MOD_LINEAR` image laid out at Metal's row pitch, which the driver may refuse /// for the texture's format, usage or pitch, and which the runtime makes of no depth or - /// stencil format), or the buffer is over + /// stencil format, nor of a height that is no multiple of 4 where the driver renders an + /// explicit plane's rows past its height + /// ([`metal2vulkan::error::RuntimeDriverDefect::ExplicitPlaneRowsPastHeight`])), or the + /// buffer is over /// the caller's `VkBuffer`, whose memory backs no image of the runtime's, or over host /// pages imported as dma-bufs (`HostMemory::with_dma_buf`) where the device makes no image /// over a dma-buf of the texture's own pages (the notice names why). Also a heap's depth diff --git a/crates/metal2vulkan-runtime/src/dma_buf.rs b/crates/metal2vulkan-runtime/src/dma_buf.rs index ce227e927..92bd6e9a2 100644 --- a/crates/metal2vulkan-runtime/src/dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/dma_buf.rs @@ -43,9 +43,13 @@ //! other layout (`VK_ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT`): the runtime asks the //! driver and takes its answer, never a rule of its own. The source is called only once the image //! is made and checked; the import keeps it, and goes after the image. Counted: -//! `WorkCounts::dma_buf_images`. Over pages imported by their pointer, a texture over a buffer -//! whose rows the driver's linear image lays out otherwise (ANV packs them tight) is likewise a -//! `DRM_FORMAT_MOD_LINEAR` image, its plane at the texture's pitches, made for host allocations +//! `WorkCounts::dma_buf_images`. A texture whose rows (or slices) lie with the buffer's bytes +//! between them takes no such image, nor one whose plane holds bytes past its texels: Vulkan +//! lets an image's layout transitions and a render pass's load and store operations write any +//! byte of its subresource (`linear_plan::padding`, `texels_alone`); it is a shadow, the source +//! not asked, counted as a fallback. Over pages imported by their pointer, a texture over a +//! buffer, its rows packed, whose rows the driver's linear image lays out otherwise is likewise +//! a `DRM_FORMAT_MOD_LINEAR` image, its plane at the texture's pitches, made for host allocations //! ([`ModifierMemory::Host`]) and bound in the buffer's import, its features and limits checked //! the same way (`texture.rs`'s `host_pitched_image`; counted: //! `WorkCounts::pitched_host_images`), where the driver takes that layout. Measured @@ -90,11 +94,14 @@ use super::error::{invalid, vulkan, Error, Problem}; use super::exit_guard::{self, Call}; use super::host_memory::{based_size, import_refused, not_importable, ImportWindow, Importer}; use super::image_plan::{ImageFacts, ImagePlan}; -use super::linear_plan::{check_linear_limits, tiling_lack, viewed_formats, LinearLack}; +use super::linear_plan::{ + check_linear_limits, texels_alone, tiling_lack, viewed_formats, BufferLayout, LinearLack, +}; use super::memory::{ImportFailure, MemoryClass, Placement}; use super::Device; use crate::release; use ash::vk; +use metal2vulkan::error::RuntimeDriverDefect; use metal2vulkan::vk::{Format, FormatFeatureFlags2, ImageCreateFlags, SampleCountFlags}; use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; use std::ptr::NonNull; @@ -610,6 +617,10 @@ pub(super) struct DmaBufTexels<'a> { pub(super) row_pitch: u64, /// The bytes from a slice's first texel to the next slice's, for a plan of several layers. pub(super) slice_pitch: u64, + /// For a texture over a buffer, its texels' layout, which the image's plane holds alone + /// (`linear_plan::texels_alone`): the buffer's other bytes are the program's. `None` for a + /// heap's texture, whose image's bytes are its own. + pub(super) alone: Option, } /// A texture's image over dma-buf pages, made and bound ([`Device::dma_buf_image`]): its @@ -712,6 +723,9 @@ impl Device { Ok(checked) => checked, Err(why) => return Ok(Err(why)), }; + if let Some(why) = self.explicit_plane_rows(plan) { + return Ok(Err(why)); + } let offset = texels.at % page; let array_pitch = if plan.layers > 1 { texels.slice_pitch @@ -760,6 +774,15 @@ impl Device { report.offset, report.row_pitch, report.array_pitch, texels.row_pitch )); } + if let Some(layout) = &texels.alone { + if !texels_alone(layout, report.size, report.array_pitch) { + return refuse(format!( + "the driver's plane takes {} bytes, past the texels' {}", + report.size, + layout.end() - layout.offset + )); + } + } // The pages from the texels' first, through the image's memory. let first = texels.at - offset; let length = match requirements.size.checked_next_multiple_of(page) { @@ -1198,6 +1221,25 @@ impl Device { } } +impl Device { + /// Why the device makes no `DRM_FORMAT_MOD_LINEAR` image of `plan` with an explicit plane, + /// where its driver renders such an image's rows past its height + /// ([`RuntimeDriverDefect::ExplicitPlaneRowsPastHeight`]) and the plan's height is no multiple + /// of 4: `None` elsewhere. + pub(super) fn explicit_plane_rows(&self, plan: &ImagePlan) -> Option { + let defect = RuntimeDriverDefect::ExplicitPlaneRowsPastHeight; + let height = plan.extent[1]; + (!height.is_multiple_of(4) && self.properties().driver_defects.contains(&defect)).then( + || { + format!( + "the driver renders an explicit DRM_FORMAT_MOD_LINEAR plane's rows past its \ + height of {height} to a multiple of 4 ({defect:?})" + ) + }, + ) + } +} + /// The memory a `DRM_FORMAT_MOD_LINEAR` image is made for: a dma-buf of its own pages /// ([`Device::dma_buf_image`]), or a no-copy buffer's host pages imported by their pointer, where /// the image lays its rows out at Metal's pitch (`texture.rs`'s `host_pitched_image`). diff --git a/crates/metal2vulkan-runtime/src/driver_defects.rs b/crates/metal2vulkan-runtime/src/driver_defects.rs index 7baa371d8..d88bee3c4 100644 --- a/crates/metal2vulkan-runtime/src/driver_defects.rs +++ b/crates/metal2vulkan-runtime/src/driver_defects.rs @@ -195,6 +195,19 @@ pub(super) struct Affected { /// (`generated_execute.rs`). Every RADV GPU and release but the measured identity found clean, /// the 780M at 26.2.4, takes it; the RX 7900 XTX is no measured identity, so it takes it at /// every release. +/// +/// `ExplicitPlaneRowsPastHeight`: +/// - Mesa's lavapipe (`MESA_LLVMPIPE`): a `DRM_FORMAT_MOD_LINEAR` image made for host allocations +/// with an explicit plane at a texture's packed rows, reported at `rows × rowPitch` bytes in its +/// subresource and within its memory requirements, is rendered in blocks of 4 rows: a pass that +/// loads, blends and stores a 658x126 `RGBA16Float` tile (rows of 5264 bytes) rewrote rows 126 +/// and 127 past it (signaling NaNs quieted), and one over a 1308x510 `BGRA8Unorm` tile (rows of +/// 5232 bytes) wrote rows 510 and 511 past the no-copy buffer's mapping, and the process took a +/// `SIGSEGV` (`runtime_lane::pitched_surfaces`, packed odd-height layouts). Its own linear images +/// report the rounded rows in their subresource. Measured on 26.2.4 (llvmpipe, LLVM 23.1.1, 256 +/// bits; gem10): known broken through 26.2.4; 26.0.8 unprobed. Nothing is refused: no such +/// image of a height that is no multiple of 4 is made there (`dma_buf.rs`'s +/// `explicit_plane_rows`), and the texture takes its shadow. pub(super) const AFFECTED: &[Affected] = &[ Affected { defect: RuntimeDriverDefect::MultisampledDepthStencilColourCopies, @@ -252,6 +265,11 @@ pub(super) const AFFECTED: &[Affected] = &[ driver: DriverId::MOLTENVK, clean: &[], }, + Affected { + defect: RuntimeDriverDefect::ExplicitPlaneRowsPastHeight, + driver: DriverId::MESA_LLVMPIPE, + clean: &[], + }, Affected { defect: RuntimeDriverDefect::ImplicitPreprocessAfterExecutionSet, driver: DriverId::MESA_RADV, diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 480925224..1194f7855 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -706,6 +706,8 @@ impl EncoderCore { let copies = self.shadows.before(shadows, uses, |copies| { ShadowMerge::new(&device, copies).map(Arc::new) })?; + let texels = copies.iter().map(ShadowCopy::texels_back).sum(); + (device.shared().counts).shadow_copies_planned(copies.len(), texels); for copy in &copies { if let Step::Keep(merge) = ©.step { self.retain(Arc::clone(merge)); @@ -875,6 +877,9 @@ impl EncoderCore { && !self.taken.named_pins().is_empty() }); let copies = self.shadows.finish(); + let texels = copies.iter().map(ShadowCopy::texels_back).sum(); + let counts = &self.device().shared().counts; + counts.shadow_copies_planned(copies.len(), texels); self.shadow_copies(&copies); // SAFETY: as in `barrier`. unsafe { self.device().shared().vk().end_command_buffer(self.raw) }.map_err(vulkan)?; @@ -973,6 +978,9 @@ impl EncoderCore { /// buffer: its first encoding kept none of those, so its place stays as it was. pub(super) fn finish_replay(mut self) -> Result { let copies = self.shadows.finish(); + let texels = copies.iter().map(ShadowCopy::texels_back).sum(); + let counts = &self.device().shared().counts; + counts.shadow_copies_planned(copies.len(), texels); self.shadow_copies(&copies); // SAFETY: as in `barrier`. unsafe { self.device().shared().vk().end_command_buffer(self.raw) }.map_err(vulkan)?; @@ -1054,6 +1062,9 @@ impl EncoderCore { /// back are copied back, then a barrier to everything recorded after it. pub(super) fn end_segment(mut self) -> Result { let copies = self.shadows.finish(); + let texels = copies.iter().map(ShadowCopy::texels_back).sum(); + let counts = &self.device().shared().counts; + counts.shadow_copies_planned(copies.len(), texels); self.shadow_copies(&copies); self.barrier(Barrier::everything()); // SAFETY: as in `barrier`. diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 3dc905cdc..995fa5daa 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -614,19 +614,14 @@ impl Importer { } /// Whether the device makes images over dma-bufs of host pages (`dma_buf.rs`): it imports - /// dma-bufs and enables `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign`. + /// dma-bufs and enables `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign` + /// (`create.rs`'s `dma_buf_image_names`). A texture over host pages imported by their pointer + /// may then be a `DRM_FORMAT_MOD_LINEAR` image at Metal's row pitch too (`texture.rs`'s + /// `host_pitched_image`). pub(super) fn makes_dma_buf_images(&self) -> bool { self.dma_buf_images } - /// Whether the device enables `VK_EXT_image_drm_format_modifier` (with the dma-buf route's - /// image extensions, `create.rs`'s `dma_buf_image_names`): a texture over host pages imported - /// by their pointer may then be a `DRM_FORMAT_MOD_LINEAR` image at Metal's row pitch - /// (`texture.rs`'s `host_pitched_image`). - pub(super) fn makes_modifier_images(&self) -> bool { - self.dma_buf_images - } - /// The memory types the dma-buf `fd` can be imported into (`vkGetMemoryFdPropertiesKHR`); /// `ERROR_FEATURE_NOT_PRESENT` where the device imports no dma-bufs. /// diff --git a/crates/metal2vulkan-runtime/src/interop.rs b/crates/metal2vulkan-runtime/src/interop.rs index caabb8cd4..b9e879336 100644 --- a/crates/metal2vulkan-runtime/src/interop.rs +++ b/crates/metal2vulkan-runtime/src/interop.rs @@ -107,10 +107,13 @@ impl Texture { /// A texture over a buffer's bytes whose image aliases them gives a linear image: of /// `VK_IMAGE_TILING_LINEAR`, or of `VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT` with /// `DRM_FORMAT_MOD_LINEAR` and one memory plane laid out at the texels' offset and the - /// texture's `bytes_per_row`. The second is the image over host pages imported as dma-bufs - /// (`HostMemory::with_dma_buf`), and over a no-copy buffer's host pages where the driver's own - /// linear image lays its rows out otherwise than `bytes_per_row` (ANV packs them tight; - /// `WorkCounts::pitched_host_images` counts them). Ask such an image's layout of its memory + /// texture's `bytes_per_row`. Such a texture's rows lie one after another and its image's + /// subresource holds no byte but its texels: a texture whose rows lie with the buffer's bytes + /// between them gives none (it is a shadow, `shadowed-texture`) but on MoltenVK, whose image + /// is a Metal texture over the buffer. The second is the image over host pages imported as + /// dma-bufs (`HostMemory::with_dma_buf`), and over a no-copy buffer's host pages where the + /// driver's own linear image lays its rows out otherwise than `bytes_per_row` + /// (`WorkCounts::pitched_host_images` counts them). Ask such an image's layout of its memory /// plane (`VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT`, not the color aspect), and its modifier /// with `vkGetImageDrmFormatModifierPropertiesEXT`. /// diff --git a/crates/metal2vulkan-runtime/src/linear_plan.rs b/crates/metal2vulkan-runtime/src/linear_plan.rs index dc06cc670..63ea3f324 100644 --- a/crates/metal2vulkan-runtime/src/linear_plan.rs +++ b/crates/metal2vulkan-runtime/src/linear_plan.rs @@ -117,9 +117,13 @@ //! **Aliasing**. A 2D texture or array over a buffer is a linear image bound to the buffer's memory //! where the device's linear image has every feature its optimal image has for the texture's uses //! (it lacks nothing, [`linear_lack`]), and the image the device made, at the pitch it chose -//! itself, sits exactly on Metal's layout ([`aliases`]). Otherwise it is a shadow image the -//! encoders copy from and to the buffer (`shadow.rs`), which is exact for Metal's defined -//! behaviour. +//! itself, sits exactly on Metal's layout and holds no byte but the texels ([`aliases`]): a +//! texture whose rows or slices lie with the buffer's bytes between them is never one +//! ([`padding`]), as Vulkan lets an image's layout transitions, and a render pass's load and store +//! operations, write every byte of its subresource, and Metal leaves those bytes as the program +//! writes them. Otherwise it is a shadow image the encoders copy from and to the buffer +//! (`shadow.rs`), whose copies address the buffer's texels alone, which is exact for Metal's +//! defined behaviour. use super::chroma_pairs::is_four_two_two; use super::copy_plan::block_extent; @@ -679,12 +683,14 @@ pub(super) fn check_linear_limits( /// A linear image the device made for a texture over a buffer, as Vulkan reports it: its memory /// requirements' alignment and size, and the layout of its first subresource -/// (`vkGetImageSubresourceLayout`). +/// (`vkGetImageSubresourceLayout`), its bytes (`subresource`, `VkSubresourceLayout::size`) among +/// them. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct LinearImage { pub(super) alignment: u64, pub(super) size: u64, pub(super) offset: u64, + pub(super) subresource: u64, pub(super) row_pitch: u64, pub(super) array_pitch: u64, } @@ -692,10 +698,10 @@ pub(super) struct LinearImage { /// Whether `image`, bound where `layout` starts in its buffer's memory (`memory_offset` in the /// memory block), holds exactly Metal's texels in the `room` bytes from there to the end of the /// buffer's memory: the binding is a multiple of the image's alignment, its texels start at the -/// binding, its row pitch is Metal's and so is its slice pitch where it has several slices, and -/// its memory stays in the buffer's. A driver may report a pitch other than the one asked of it -/// (NVIDIA does for explicit layouts it does not support), so the image's own report -/// decides. +/// binding, its row pitch is Metal's and so is its slice pitch where it has several slices, its +/// subresources hold no byte but the texture's texels ([`texels_alone`]), and its memory stays in +/// the buffer's. A driver may report a pitch other than the one asked of it (NVIDIA does for +/// explicit layouts it does not support), so the image's own report decides. pub(super) fn aliases( layout: &BufferLayout, memory_offset: u64, @@ -707,5 +713,83 @@ pub(super) fn aliases( && image.offset == 0 && image.row_pitch == layout.row_pitch && (layout.slices == 1 || image.array_pitch == layout.slice_pitch) + && texels_alone(layout, image.subresource, image.array_pitch) && image.size <= room } + +/// Why no image over `layout`'s texels holds them alone, where its rows or slices lie with bytes +/// between them that are not texels (the buffer's, which Metal's writes of the texture never +/// reach): `None` where they lie one after another, or the texture has one row (one slice). +/// `renders`: the texture's usage holds `RenderTarget`, so a render pass may take its image as an +/// attachment. +/// +/// An image whose rows lie `row_pitch` apart holds those bytes in its subresource +/// (`VkSubresourceLayout`: "size includes any extra memory that is required based on rowPitch"), +/// and Vulkan lets two kinds of operation write them, against which no query of the device states +/// otherwise: +/// +/// - Every image's layout transitions, its first move into `GENERAL` among them (the +/// Synchronization chapter's Image Layout Transitions): "Image layout transitions may perform +/// read and write accesses on all memory bound to the image subresource range", and "If the old +/// layout is VK_IMAGE_LAYOUT_UNDEFINED, the contents of that range may be discarded". No +/// operation lets an image be read before it leaves `UNDEFINED` or `PREINITIALIZED`, the layouts +/// it is made in, so a texture that only reads takes a transition too. +/// - A render pass's attachments (the Render Pass chapter's Load Operations, Store Operations and +/// Multisample Resolve Operations): "any writes performed by a load operation (as defined by its +/// access masks) to a given attachment may read and write back any memory locations within the +/// image subresource bound for that attachment", and a store and a resolve operation alike. +/// +/// A copy and a shader's read or write of the image touch its texels alone (the Memory +/// Model: "A memory operation must not affect memory at a memory location not within its set of +/// memory locations"). So such a texture is a shadow: a write back of what was read would undo the +/// program's write of the bytes meanwhile, which Metal keeps, and lavapipe reads the bytes its +/// 4-texel blocks reach past a row's texels and writes them back, a signaling NaN's bits quieted. +pub(super) fn padding(layout: &BufferLayout, renders: bool) -> Option { + let (rows, slices) = apart(layout); + let apart = if rows { + format!( + "its rows lie {} bytes apart, {} bytes of texels each", + layout.row_pitch, layout.row_bytes + ) + } else if slices { + format!( + "its slices lie {} bytes apart, {} rows {} bytes apart each", + layout.slice_pitch, layout.rows, layout.row_pitch + ) + } else { + return None; + }; + let writers = if renders { + "its layout transitions read and write, and a render pass's load and store operations \ + write back" + } else { + "its layout transitions read and write, its first move from the layout it is made in \ + among them" + }; + Some(format!( + "{apart}: an image over them holds the bytes between them, which Vulkan lets {writers}" + )) +} + +/// Whether a linear image over `layout`'s texels, whose subresources take `size` bytes each from +/// the first texel of their slice, `array_pitch` apart, holds no byte but the texture's texels: +/// the texels lie with no byte between them ([`padding`]), and its last subresource ends at their +/// last byte or before. A driver may lay rows out past the texture's (lavapipe rounds the height +/// up to 4), where the buffer's later bytes lie (a surface's next plane). A byte of the image's +/// memory past every subresource is no texel's, and no write through the image reaches it: +/// Vulkan's Memory Aliasing has the bytes a write through an image affects be "those overlapped +/// by the image subresources that were written". A driver that reports one array's whole bytes +/// as its first subresource's has the array refused (the texture is a shadow). +pub(super) fn texels_alone(layout: &BufferLayout, size: u64, array_pitch: u64) -> bool { + let texels = layout.end() - layout.offset; + let last = array_pitch.saturating_mul(layout.slices - 1); + apart(layout) == (false, false) && last.saturating_add(size) <= texels +} + +/// Whether `layout`'s rows, and its slices, lie with bytes between them that are not texels. +fn apart(layout: &BufferLayout) -> (bool, bool) { + let rows = layout.rows > 1 && layout.row_pitch != layout.row_bytes; + let slices = + layout.slices > 1 && layout.slice_pitch != layout.row_pitch.saturating_mul(layout.rows); + (rows, slices) +} diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 325ab8dc5..870bdb104 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -3253,6 +3253,16 @@ impl RenderCommandEncoder { // tiles their primitives touch, at most those their viewports and scissors reach, and // none where those reach none. let reach = clear_reach::PassReach::of(&layout, called, drew); + // The color attachments the pass loads as the encoder set them, before its `DontCare` + // loads and reach clears below give any a clear before the pass and a load + // (`render/shadows.rs` bounds the others' copies back by the draws' scissors). + let loaded_colors: Vec = (layout.colors.iter()) + .map(|color| { + color + .as_ref() + .is_some_and(|color| color.load == LoadAction::Load) + }) + .collect(); let tiles = match reach { clear_reach::PassReach::Draws => drawn.tiles(&layout), _ => None, @@ -3733,8 +3743,18 @@ impl RenderCommandEncoder { order.extend(after.map(|dispatch| (&dispatch.shadows, true))); } let reached = reach != clear_reach::PassReach::Nothing; - let planned = - shadows::plan(&mut core, order.iter().map(|&(s, _)| s), &layout, reached)?; + // Where nothing but the draws writes the loaded colors: no reach clear before the + // pass. + let drawn_bounds = match (reach, &reach_clears) { + (clear_reach::PassReach::Draws, None) => drawn.bounds(), + _ => None, + }; + let planned = shadows::plan( + &mut core, + order.iter().map(|&(s, _)| s), + &layout, + (reached, drawn_bounds.map(|area| (area, &loaded_colors[..]))), + )?; let (mut texel_copies, mut dispatch_copies) = (Vec::new(), Vec::new()); for (&(_, of_dispatch), copies) in order.iter().zip(planned) { match of_dispatch { diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index b365450dd..458c57171 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -633,6 +633,7 @@ impl RenderCommandEncoder { writes, overwrites: false, kept: false, + area: None, }; shadow::join(&mut shadows, &used); } diff --git a/crates/metal2vulkan-runtime/src/render/shadows.rs b/crates/metal2vulkan-runtime/src/render/shadows.rs index d09983e55..57a37868c 100644 --- a/crates/metal2vulkan-runtime/src/render/shadows.rs +++ b/crates/metal2vulkan-runtime/src/render/shadows.rs @@ -13,7 +13,13 @@ //! buffer's; copied back at the end where the pass stores it (`Store`, //! `StoreAndMultisampleResolve`) or resolves into it. A `DontCare` store copies nothing back: the //! buffer keeps its bytes, Metal's answer (TOB probe 1, and the DontCare-store probe, -//! `kept_bytes.rs`). A texture over a buffer with an aliasing image renders into that image: +//! `kept_bytes.rs`). A pass that reaches no tile (`clear_reach::PassReach::Nothing`) leaves a +//! color attachment it loads, resolves nothing from and stores (or stores `DontCare`) as it was, +//! as Metal loads and stores only the tiles a draw reaches: where its texture's shadow is an +//! image of a buffer's bytes, nothing is copied in or back. A pass whose draws do reach tiles +//! changes a color attachment it loads (as the encoder set its load, with no clear before the +//! pass) only inside its draws' scissors (`clear_reach::DrawnArea`): only those texels are +//! copied back. A texture over a buffer with an aliasing image renders into that image: //! the buffer's bytes, with no copy; but a pass that does not store it renders through an image //! its texture keeps, from which nothing is copied back either (`kept_bytes.rs`). //! - **Two ways.** An instance that writes through a shadowed texture (in a draw, or as an @@ -43,7 +49,7 @@ use crate::error::Error; use crate::render_pass::{PassLayout, Target}; use crate::render_values::{LoadAction, StoreAction}; use crate::resource::ResourceKey; -use crate::shadow::{self, ShadowCopy, ShadowUse}; +use crate::shadow::{self, ShadowCopy, ShadowTarget, ShadowUse}; use crate::tracker::{Access, Use, UseRange}; use ash::vk; use metal2vulkan::metal::TextureType; @@ -223,14 +229,16 @@ impl InstanceShadows { /// The copies before each of `instances` of a pass of `layout` (its render pass instances and /// tile dispatches, in order), planned through `core`'s shadowed textures /// (`EncoderCore::plan_shadows`), the attachments a use of each, a pass whose draws reach tiles -/// where `reached` (`clear_reach::PassReach`). +/// where `reached` (`clear_reach::PassReach`), inside `drawn` where its draws' scissors bound +/// them (`clear_reach::DrawnArea::bounds`) and nothing but they write the color attachments it +/// names as loaded by index (their loads as the encoder set them). pub(super) fn plan<'a>( core: &mut EncoderCore, instances: impl Iterator, layout: &PassLayout, - reached: bool, + (reached, drawn): (bool, Option<([u32; 4], &[bool])>), ) -> Result>, Error> { - let attachments = attachment_shadows(layout, reached); + let attachments = attachment_shadows(layout, reached, drawn); let attached = crate::render_target::attachment_uses(layout)?; let mut copies = Vec::new(); for instance in instances { @@ -247,7 +255,7 @@ pub(super) fn plan<'a>( /// Whether a pass of `layout` has a shadowed attachment or resolve target. pub(super) fn attachments_shadowed(layout: &PassLayout) -> bool { - !attachment_shadows(layout, true).is_empty() + !attachment_shadows(layout, true, None).is_empty() } /// A color attachment of `layout`'s pass that the pass loads and stores and loads other than by @@ -280,8 +288,13 @@ pub(super) fn loaded_apart(layout: &PassLayout) -> Option { /// attachment's are heap shadows (`texture/heap.rs`): its texture, each aspect's where the two are /// different textures, the texture a stand-in renders for, and its resolve targets. A color /// attachment of a pass whose draws reach no tile (`reached` false) is left in place -/// ([`ShadowUse::kept`]). -fn attachment_shadows(layout: &PassLayout, reached: bool) -> Vec { +/// ([`ShadowUse::kept`]). A color attachment `drawn` names as loaded changes only inside its +/// rectangle, which bounds the draws' scissors ([`ShadowUse::area`]). +fn attachment_shadows( + layout: &PassLayout, + reached: bool, + drawn: Option<([u32; 4], &[bool])>, +) -> Vec { let mut shadows = Vec::new(); let stores = |store: StoreAction| { matches!( @@ -316,6 +329,7 @@ fn attachment_shadows(layout: &PassLayout, reached: bool) -> Vec { writes, overwrites, kept: false, + area: None, }; shadow::join(&mut shadows, &used); } @@ -332,12 +346,14 @@ fn attachment_shadows(layout: &PassLayout, reached: bool) -> Vec { writes: true, overwrites: false, kept: false, + area: None, }; shadow::join(&mut shadows, &used); } } } - for color in layout.colors.iter().flatten() { + let colors = layout.colors.iter().enumerate(); + for (index, color) in colors.filter_map(|(index, color)| Some((index, color.as_ref()?))) { let stores = matches!( color.store, StoreAction::Store | StoreAction::StoreAndMultisampleResolve | StoreAction::Unknown @@ -346,14 +362,47 @@ fn attachment_shadows(layout: &PassLayout, reached: bool) -> Vec { && color.stand_in.is_none() && color.planes.is_none() && whole(&color.target, layout); + // A pass that reaches no tile and loads the attachment leaves its texels as they were: + // Metal loads and stores only the tiles a draw reaches (`clear_reach::PassReach`), and + // Vulkan's load and store write back what they read. Nothing resolves from it, so the + // pass needs none of the texels: a texture over a buffer's bytes in its own image takes + // no copy in, and nothing is copied back. + let untouched = !reached + && color.load == LoadAction::Load + && matches!(color.store, StoreAction::Store | StoreAction::DontCare) + && color.resolve.is_none() + && color.copied_resolve.is_none() + && color.stand_in.is_none() + && color.planes.is_none(); + // A pass that loads the attachment changes no texel outside its draws' scissors: a + // fragment's samples outside the scissor rectangle "will have their coverage set to 0" + // (the Fragment Operations chapter's Scissor Test), and its load and store write back + // what they read (as above). Each Vulkan scissor is Metal's rectangle clipped to the + // pixels its viewport overlaps (`render_state.rs`), which Metal's draw writes no pixel + // past, and `drawn` bounds them all. So only the texels inside it are copied back, of + // the attachment's texture where it is the whole of a one-level, one-slice texture. + let loaded = drawn.filter(|(_, loaded)| loaded.get(index) == Some(&true)); + let area = loaded.map(|(area, _)| area).filter(|_| { + color.load == LoadAction::Load + && color.resolve.is_none() + && color.copied_resolve.is_none() + && color.stand_in.is_none() + && color.planes.is_none() + && one_image(&color.target) + }); let own = color.stand_in.as_ref().map(|s| &s.own); for target in std::iter::once(&color.target).chain(own) { if let Some(copies) = target.texture.shadow() { + let plain = matches!(copies.target(), Some(ShadowTarget::Image { .. })); + if untouched && plain && !copies.drops_writes { + continue; + } let used = ShadowUse { copies: Arc::clone(copies), writes: stores, overwrites, kept: !reached, + area, }; shadow::join(&mut shadows, &used); } @@ -370,6 +419,7 @@ fn attachment_shadows(layout: &PassLayout, reached: bool) -> Vec { writes: true, overwrites: false, kept: false, + area: None, }; shadow::join(&mut shadows, &used); } @@ -381,6 +431,13 @@ fn attachment_shadows(layout: &PassLayout, reached: bool) -> Vec { /// Whether `target` is the whole of its texture, a 2D texture of one level, and the pass's /// render area covers it: a clear of it replaces every texel. fn whole(target: &Target, layout: &PassLayout) -> bool { + one_image(target) + && [target.texture.width(), target.texture.height()] == layout.extent.map(u64::from) +} + +/// Whether `target` is the whole of its texture, a 2D texture of one level and one slice, whose +/// pixels are its texels. +fn one_image(target: &Target) -> bool { let texture = &target.texture; texture.texture_type() == TextureType::Type2D && texture.mipmap_level_count() == 1 @@ -388,7 +445,6 @@ fn whole(target: &Target, layout: &PassLayout) -> bool { && target.level == 0 && target.layer == 0 && target.layers == 1 - && [texture.width(), texture.height()] == layout.extent.map(u64::from) } #[cfg(test)] diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index 601016ee4..9e37fb96d 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -14,7 +14,10 @@ //! - **Copy back** what a command wrote through the texture before the next command that touches //! the bytes some other way, and at the end of the encoder (orchestrator, 2026-10-04: at the //! end of the encoder that writes through the texture, not of the command buffer). A copy moves -//! only the texels' rows, never the bytes between them. +//! only the texels' rows, never the bytes between them; a copy back of a one-level, one-slice +//! texture's image, only the texels inside the rectangle its writers since the last bound their +//! writes to, where each bounds them ([`ShadowUse::area`]: a pass's attachment it loads, inside +//! its draws' scissors), as the image's other texels are what the last copy in left. //! - **Ordering.** A copy is a command of the encoder with uses of both the buffer's bytes and the //! image, so the tracker orders it against the encoder's other commands and other encoders' //! like any use: the texture and its buffer are one resource to it. In an encoder whose @@ -237,6 +240,10 @@ pub(super) enum ShadowTarget { image: vk::Image, regions: Vec, staging: Option, + /// The bytes of one of its texels in the buffer, by which a copy back of a part of the + /// texture ([`ShadowCopy::area`]) offsets its region; `None` where no copy of it is + /// bounded (a heap's depth or stencil texture, which is no color attachment). + texel: Option, }, /// A texture buffer's staging buffer, which its bindings view. Buffer(ShadowStaging), @@ -487,6 +494,40 @@ pub(super) struct ShadowCopy> { pub(super) step: Step, /// A copy in before a command that leaves the texels in place ([`ShadowUse::kept`]). pub(super) kept: bool, + /// A copy back of the texels inside `[x0, y0, x1, y1)` of a one-level, one-slice texture's + /// image alone, where the commands since the last copy back wrote through it there and + /// nowhere else ([`ShadowUse::area`]); `None` for every texel. + pub(super) area: Option<[u32; 4]>, +} + +impl ShadowCopy { + /// The texels a copy back of a 2D texture's image over a buffer's bytes moves (its every + /// region's, or its one region's inside [`area`](Self::area)): 0 for every other copy. + pub(super) fn texels_back(&self) -> u64 { + let Some(ShadowTarget::Image { + regions, + staging, + texel, + .. + }) = self.copies.target() + else { + return 0; + }; + if !matches!(self.step, Step::Back) { + return 0; + } + let texels = |r: &vk::BufferImageCopy| { + let e = r.image_extent; + u64::from(e.width) * u64::from(e.height) * u64::from(e.depth) + }; + // As `record` cuts the region. + match (self.area, staging, regions.as_slice(), texel) { + (Some(area), None, [region], Some(texel)) => { + part_of(region, area, *texel).as_ref().map_or(0, texels) + } + _ => regions.iter().map(texels).sum(), + } + } } impl ShadowCopy { @@ -685,7 +726,20 @@ impl ShadowCopy { image, regions, staging, - } => (*image, regions, staging.as_ref()), + texel, + } => { + let regions = match (self.area, staging, regions.as_slice(), *texel) { + (Some(area), None, [region], Some(texel)) if !into_shadow => { + match part_of(region, area, texel) { + Some(part) => std::borrow::Cow::Owned(vec![part]), + // The commands wrote no texel. + None => return, + } + } + _ => std::borrow::Cow::Borrowed(regions.as_slice()), + }; + (*image, regions, staging.as_ref()) + } ShadowTarget::Rotated { image, staging, @@ -774,7 +828,7 @@ impl ShadowCopy { texels, image, vk::ImageLayout::GENERAL, - regions, + ®ions, ); } else { device.cmd_copy_image_to_buffer( @@ -782,7 +836,7 @@ impl ShadowCopy { image, vk::ImageLayout::GENERAL, texels, - regions, + ®ions, ); if let Some(staging) = staging { Barrier::everything().record(device, command_buffer); @@ -793,6 +847,40 @@ impl ShadowCopy { } } +/// `region` (a one-level, one-slice texture's every texel, `texel` bytes each in the buffer) cut +/// to the texels inside `[x0, y0, x1, y1)`: `None` where none lies there. +pub(super) fn part_of( + region: &vk::BufferImageCopy, + [x0, y0, x1, y1]: [u32; 4], + texel: u64, +) -> Option { + let extent = region.image_extent; + let (x1, y1) = (x1.min(extent.width), y1.min(extent.height)); + if x0 >= x1 || y0 >= y1 { + return None; + } + let row = match region.buffer_row_length { + 0 => extent.width, + row => row, + }; + Some(vk::BufferImageCopy { + buffer_offset: region.buffer_offset + + (u64::from(y0) * u64::from(row) + u64::from(x0)) * texel, + buffer_row_length: row, + image_offset: vk::Offset3D { + x: region.image_offset.x + x0 as i32, + y: region.image_offset.y + y0 as i32, + z: region.image_offset.z, + }, + image_extent: vk::Extent3D { + width: x1 - x0, + height: y1 - y0, + depth: extent.depth, + }, + ..*region + }) +} + /// Whether a command that uses the shadowed textures `shadows` and has `uses` writes the bytes /// of `shadows[i]` two ways: through it, and through `uses` or another shadowed texture over /// them (the module's rules). @@ -854,19 +942,26 @@ pub(super) fn copies_used<'a>( writes, overwrites: false, kept: false, + area: None, }); } shadows } /// Add `shadow` to `shadows`: once per shadowed texture, writing through it when either use -/// writes, and overwriting it, or leaving its texels in place, only when both do. +/// writes (where both write, inside the rectangle bounding both areas), and overwriting it, or +/// leaving its texels in place, only when both do. pub(super) fn join(shadows: &mut Vec, shadow: &ShadowUse) { match shadows .iter_mut() .find(|other| other.copies.shadow_key == shadow.copies.shadow_key) { Some(other) => { + other.area = match (other.writes, shadow.writes) { + (true, true) => bounding(other.area, shadow.area), + (false, true) => shadow.area, + (_, false) => other.area, + }; other.writes |= shadow.writes; other.overwrites &= shadow.overwrites; other.kept &= shadow.kept; @@ -876,6 +971,7 @@ pub(super) fn join(shadows: &mut Vec, shadow: &ShadowUse) { writes: shadow.writes, overwrites: shadow.overwrites, kept: shadow.kept, + area: shadow.area, }), } } @@ -887,6 +983,8 @@ struct Entry { current: bool, /// A command wrote through the texture since the last copy back. dirty: bool, + /// Where those commands wrote through it, where they bound it ([`ShadowUse::area`]). + area: Option<[u32; 4]>, /// The scratch the image was kept in before a command that writes its bytes two ways, until /// the merge after it. merge: Option, @@ -906,8 +1004,19 @@ pub(super) struct ShadowUse { /// The command leaves the texture's texels in place, but where it overwrites them: a render /// pass that draws nothing, of an attachment it renders. A rotated texture's copy in then /// turns its texels by the inverse of its store (`rotated::Turn::Keep`), where Metal's pass - /// loads them otherwise. + /// loads them otherwise. (An attachment such a pass loads, whose shadow is an image of a + /// buffer's bytes, takes no use at all: `render/shadows.rs`.) pub(super) kept: bool, + /// Where the command writes through the texture, where it bounds that: the texels inside + /// `[x0, y0, x1, y1)` of a one-level, one-slice texture's image (a pass's attachment it + /// loads, which only its draws' scissors change, `render/shadows.rs`); `None` for anywhere. + pub(super) area: Option<[u32; 4]>, +} + +/// The rectangle bounding `a` and `b`, each `[x0, y0, x1, y1)`; `None` (anywhere) where either is. +fn bounding(a: Option<[u32; 4]>, b: Option<[u32; 4]>) -> Option<[u32; 4]> { + let ([a0, a1, a2, a3], [b0, b1, b2, b3]) = (a?, b?); + Some([a0.min(b0), a1.min(b1), a2.max(b2), a3.max(b3)]) } /// The shadowed textures one encoder used, and the copies they need (the module's rules), `M` @@ -938,6 +1047,7 @@ impl ShadowSync { copies: Arc::clone(copies), current: false, dirty: false, + area: None, merge: None, }); self.entries.len() - 1 @@ -948,7 +1058,10 @@ impl ShadowSync { /// Copy back entry `i` (dirty): its image's bytes replace the buffer's, so every other /// texture over them is no longer current. One kept before a command that wrote its bytes /// two ways is merged instead, and is then no longer current either: the buffer holds the - /// other way's writes too. + /// other way's writes too. A copy back covers only the area the commands wrote in, where + /// they bound it: the image's other texels are what the last copy in left, which the + /// buffer still holds (a write of its bytes another way leaves the image stale, and copies + /// in again before the next use). fn copy_back(&mut self, i: usize, copies: &mut Vec>) { let entry = &mut self.entries[i]; let step = match &entry.merge { @@ -960,12 +1073,18 @@ impl ShadowSync { } None => Step::Back, }; + let area = match step { + Step::Back => entry.area, + _ => None, + }; entry.dirty = false; + entry.area = None; let written = Arc::clone(&entry.copies); copies.push(ShadowCopy { copies: Arc::clone(&written), step, kept: false, + area, }); for (j, other) in self.entries.iter_mut().enumerate() { if j != i && other.copies.shares_truth(&written) { @@ -1034,6 +1153,7 @@ impl ShadowSync { copies: Arc::clone(&shadow.copies), step: Step::Into, kept: shadow.kept, + area: None, }); } self.entries[i].current = true; @@ -1046,6 +1166,7 @@ impl ShadowSync { copies: shadow, step: Step::Keep(merge), kept: false, + area: None, }); } Ok(copies) @@ -1067,9 +1188,16 @@ impl ShadowSync { for shadow in shadows.iter().filter(|shadow| shadow.writes) { let i = self.entry(&shadow.copies); // Writes Metal drops are not copied back, and the image no longer holds the bytes. + let entry = &mut self.entries[i]; match shadow.copies.drops_writes { - true => self.entries[i].current = false, - false => self.entries[i].dirty = true, + true => entry.current = false, + false => { + entry.area = match entry.dirty { + true => bounding(entry.area, shadow.area), + false => shadow.area, + }; + entry.dirty = true; + } } } } diff --git a/crates/metal2vulkan-runtime/src/tests/driver_defects.rs b/crates/metal2vulkan-runtime/src/tests/driver_defects.rs index fa4c01962..2d5c0a20c 100644 --- a/crates/metal2vulkan-runtime/src/tests/driver_defects.rs +++ b/crates/metal2vulkan-runtime/src/tests/driver_defects.rs @@ -18,13 +18,14 @@ const COPY_REWRITES: RuntimeDriverDefect = RuntimeDriverDefect::CompressedImageC const NAN_COPIES: RuntimeDriverDefect = RuntimeDriverDefect::MultisampledCopiesConvertFloatNans; const LATE_READS: RuntimeDriverDefect = RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal; const PREPROCESS: RuntimeDriverDefect = RuntimeDriverDefect::ImplicitPreprocessAfterExecutionSet; +const PAST_HEIGHT: RuntimeDriverDefect = RuntimeDriverDefect::ExplicitPlaneRowsPastHeight; /// Every committed profile's driver has its defects at every release and GPU but those a probe /// found clean: MoltenVK the multisampled depth/stencil colour copies, the inexact depths past /// `[0, 1]`, the crashing 2D views of a 3D image in lazily allocated memory, the pipeline cache /// compiled at load, the copies of compressed images that rewrite texels and the reads of command -/// buffers after their signal; lavapipe the colour copies and the depth/stencil resolve of the -/// first layer and level; RADV the multisampled copies that convert float NaNs, and the implicit +/// buffers after their signal; lavapipe the colour copies, the depth/stencil resolve of the +/// first layer and level and the explicit plane's rows past its height; RADV the multisampled copies that convert float NaNs, and the implicit /// preprocessing after an execution set on every GPU but the 780M at 26.2.4, measured clean; ANV /// the compressed image's short size on every GPU (Arrow Lake's, not measured, too); NVIDIA's the /// stencil colour copies on every GPU but the RTX 5080 Laptop GPU at 615.71.09, measured clean (the @@ -51,7 +52,7 @@ fn the_committed_profiles_drivers_have_their_defects() { LATE_READS, ] } - Some(DriverId::MESA_LLVMPIPE) => vec![COPIES, RESOLVES], + Some(DriverId::MESA_LLVMPIPE) => vec![COPIES, RESOLVES, PAST_HEIGHT], Some(DriverId::MESA_RADV) if (desc.device_id, desc.driver_version) == (0x15bf, MESA_26_2_4) => { diff --git a/crates/metal2vulkan-runtime/src/tests/linear_plan.rs b/crates/metal2vulkan-runtime/src/tests/linear_plan.rs index 7189253d4..3aaac8841 100644 --- a/crates/metal2vulkan-runtime/src/tests/linear_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/linear_plan.rs @@ -4,9 +4,9 @@ use super::super::image_plan::plan_image; use super::super::linear_plan::{ - aliases, check_linear_limits, linear_alignment, linear_lack, plan_buffer_texture, BufferFacts, - BufferLayout, BufferRefusal, BufferTexture, BufferTextureCall, BufferTextureProblem, - LinearImage, LinearLack, Placed, LINEAR_ALIGNMENT, + aliases, check_linear_limits, linear_alignment, linear_lack, padding, plan_buffer_texture, + BufferFacts, BufferLayout, BufferRefusal, BufferTexture, BufferTextureCall, + BufferTextureProblem, LinearImage, LinearLack, Placed, LINEAR_ALIGNMENT, }; use super::super::texture_descriptor::{no_texture_alone, TextureDescriptor}; use super::super::values::StorageMode; @@ -677,14 +677,14 @@ fn an_array_ends_where_metal_lets_it() { } /// A linear image aliases a texture's place in its buffer only where every one of its reports -/// is Metal's layout's. +/// is Metal's layout's, and its subresources hold no byte but the texture's texels. #[test] fn a_linear_image_aliases_only_metals_layout() { let single = BufferLayout { offset: 256, row_pitch: 80, slice_pitch: 320, - row_bytes: 68, + row_bytes: 80, rows: 4, slices: 1, }; @@ -692,6 +692,7 @@ fn a_linear_image_aliases_only_metals_layout() { alignment: 16, size: 320, offset: 0, + subresource: 320, row_pitch: 80, array_pitch: 320, }; @@ -727,24 +728,102 @@ fn a_linear_image_aliases_only_metals_layout() { } )); assert!(!aliases(&single, 4096, 319, &image)); + // Memory past the subresource, within the buffer's: no write through the image reaches it. + assert!(aliases( + &single, + 4096, + 4096, + &LinearImage { + size: 4096, + ..image + } + )); + // A subresource past the texels (lavapipe's rows rounded up to 4, of a texture of 3). + let three = BufferLayout { rows: 3, ..single }; + assert!(!aliases(&three, 4096, 320, &image)); + assert!(aliases( + &three, + 4096, + 320, + &LinearImage { + subresource: 240, + ..image + } + )); + // Rows with the buffer's bytes between them, at Metal's pitch and the image's alike. + let padded = BufferLayout { + row_bytes: 68, + ..single + }; + assert!(!aliases(&padded, 4096, 320, &image)); + assert!(padding(&padded, true).is_some()); + assert!(padding(&single, true).is_none()); + // One row has nothing between rows, but its pitch's padding past the texels. + let row = BufferLayout { + rows: 1, + slice_pitch: 80, + ..padded + }; + assert!(padding(&row, true).is_none()); + assert!(!aliases( + &row, + 4096, + 80, + &LinearImage { + size: 80, + subresource: 80, + ..image + } + )); + assert!(aliases( + &row, + 4096, + 80, + &LinearImage { + size: 80, + subresource: 68, + ..image + } + )); // An array's slices at Metal's stride, and at no other. let slices = BufferLayout { slices: 3, - slice_pitch: 384, ..single }; - let stacked = LinearImage { - size: 1088, - array_pitch: 384, - ..image - }; - assert!(aliases(&slices, 4096, 1088, &stacked)); + let stacked = LinearImage { size: 960, ..image }; + assert!(aliases(&slices, 4096, 960, &stacked)); assert!(!aliases( &slices, 4096, + 960, + &LinearImage { + array_pitch: 384, + ..stacked + } + )); + // Slices with the buffer's bytes between them (an array's slices rounded up to 128). + let apart = BufferLayout { + slice_pitch: 384, + ..slices + }; + assert!(padding(&apart, true).is_some()); + assert!(!aliases( + &apart, + 4096, 1088, &LinearImage { - array_pitch: 320, + size: 1088, + array_pitch: 384, + ..image + } + )); + // A driver that reports the array's whole bytes as its first subresource's. + assert!(!aliases( + &slices, + 4096, + 960, + &LinearImage { + subresource: 960, ..stacked } )); @@ -760,6 +839,36 @@ fn a_linear_image_aliases_only_metals_layout() { )); } +/// A texture over padded rows is a shadow for the operations Vulkan lets write the padding: a +/// texture that only reads names its image's layout transitions (its first move among them), not a +/// render pass, which no image of its takes; a render target names both. +#[test] +fn a_padded_texture_s_shadow_names_what_may_write_its_padding() { + let padded = BufferLayout { + offset: 0, + row_pitch: 80, + slice_pitch: 320, + row_bytes: 68, + rows: 4, + slices: 1, + }; + let reads = padding(&padded, false).unwrap(); + assert_eq!( + reads, + "its rows lie 80 bytes apart, 68 bytes of texels each: an image over them holds the \ + bytes between them, which Vulkan lets its layout transitions read and write, its first \ + move from the layout it is made in among them" + ); + assert!(!reads.contains("render pass"), "{reads}"); + let renders = padding(&padded, true).unwrap(); + assert_eq!( + renders, + "its rows lie 80 bytes apart, 68 bytes of texels each: an image over them holds the \ + bytes between them, which Vulkan lets its layout transitions read and write, and a render \ + pass's load and store operations write back" + ); +} + /// A linear image serves a texture where its tiling has every feature the optimal one has for /// the texture's uses, in every format it is viewed as; the formats a device's linear tiling /// lacks send the texture to a shadow image. diff --git a/crates/metal2vulkan-runtime/src/tests/shadow.rs b/crates/metal2vulkan-runtime/src/tests/shadow.rs index bbb5b116f..2120cac23 100644 --- a/crates/metal2vulkan-runtime/src/tests/shadow.rs +++ b/crates/metal2vulkan-runtime/src/tests/shadow.rs @@ -34,6 +34,7 @@ fn shadow_joined( image: vk::Image::null(), regions: Vec::new(), staging: None, + texel: Some(4), }, alias, }, @@ -69,6 +70,7 @@ fn through(texture: &Arc, writes: bool) -> (ShadowUse, Use) -> Vec> { + sync.finish().iter().map(|copy| copy.area).collect() +} + +/// A copy back covers only where the commands since the last wrote through the texture, where +/// each bounds its writes (a pass's attachment it loads, inside its draws' scissors): the +/// rectangle bounding their areas, or every texel where one does not bound them. A copy in is of +/// every texel, and joining a use that reads keeps the area of the one that writes. +#[test] +fn a_copy_back_covers_only_where_the_commands_wrote() { + let buffer = ResourceKey::new(); + let t = shadow(buffer, 256..1280); + let writing = |area: Option<[u32; 4]>| ShadowUse { + copies: Arc::clone(&t), + writes: true, + overwrites: false, + kept: false, + area, + }; + let (_, written) = through(&t, true); + let run = |areas: &[Option<[u32; 4]>]| { + let mut sync = ShadowSync::::default(); + for &area in areas { + let shadows = [writing(area)]; + let uses = [written.clone()]; + let copies = sync.before(&shadows, &uses, |_| Ok(0)).unwrap(); + assert!(copies.iter().all(|copy| copy.area.is_none()), "a copy in"); + sync.after(&shadows, &uses); + } + back_areas(&mut sync) + }; + assert_eq!(run(&[Some([0, 0, 8, 4])]), [Some([0, 0, 8, 4])]); + assert_eq!( + run(&[Some([0, 0, 8, 4]), Some([4, 2, 16, 8])]), + [Some([0, 0, 16, 8])] + ); + assert_eq!(run(&[Some([0, 0, 8, 4]), None]), [None]); + assert_eq!(run(&[None]), [None]); + // Joined with a use that reads, the write keeps its area; with another write that does not + // bound it, it has none. + let mut joined = vec![writing(Some([2, 2, 6, 6]))]; + shadow::join(&mut joined, &through(&t, false).0); + assert_eq!(joined[0].area, Some([2, 2, 6, 6])); + let mut joined = vec![through(&t, false).0]; + shadow::join(&mut joined, &writing(Some([2, 2, 6, 6]))); + assert_eq!(joined[0].area, Some([2, 2, 6, 6])); + shadow::join(&mut joined, &through(&t, true).0); + assert_eq!(joined[0].area, None); +} + +/// A copy back of a part of a one-level, one-slice texture's image is its region cut to the +/// rectangle: the buffer's offset moved to the rectangle's first texel at the region's row length, +/// clamped to the image, and nothing where no texel lies inside. +#[test] +fn a_part_of_a_region_starts_at_its_first_texel() { + let region = vk::BufferImageCopy { + buffer_offset: 256, + buffer_row_length: 20, + buffer_image_height: 0, + image_subresource: vk::ImageSubresourceLayers { + aspect_mask: vk::ImageAspectFlags::COLOR, + mip_level: 0, + base_array_layer: 0, + layer_count: 1, + }, + image_offset: vk::Offset3D::default(), + image_extent: vk::Extent3D { + width: 16, + height: 8, + depth: 1, + }, + }; + let part = shadow::part_of(®ion, [2, 1, 6, 3], 4).unwrap(); + assert_eq!(part.buffer_offset, 256 + (20 + 2) * 4); + assert_eq!(part.buffer_row_length, 20); + assert_eq!( + ( + part.image_offset.x, + part.image_offset.y, + part.image_offset.z + ), + (2, 1, 0) + ); + assert_eq!( + ( + part.image_extent.width, + part.image_extent.height, + part.image_extent.depth + ), + (4, 2, 1) + ); + let clamped = shadow::part_of(®ion, [12, 6, 40, 40], 4).unwrap(); + assert_eq!( + (clamped.image_extent.width, clamped.image_extent.height), + (4, 2) + ); + assert!(shadow::part_of(®ion, [16, 0, 20, 8], 4).is_none()); + assert!(shadow::part_of(®ion, [3, 3, 3, 5], 4).is_none()); + // A region of tight rows (row length 0) steps by its width. + let tight = vk::BufferImageCopy { + buffer_row_length: 0, + ..region + }; + let part = shadow::part_of(&tight, [0, 2, 16, 3], 4).unwrap(); + assert_eq!(part.buffer_offset, 256 + 2 * 16 * 4); +} + /// A shadow whose writes Metal drops (a rotated texture's functions' image) is copied in as any /// shadow, never copied back, and copied in again at its next use after a command that wrote /// through it; a command writing it and its bytes another way is no two-way write. @@ -223,6 +333,7 @@ fn a_use_that_overwrites_every_texel_takes_no_copy_in() { writes, overwrites: true, kept: false, + area: None, }; let (_, written) = through(&t, true); for stores in [true, false] { diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index f0743b11d..165d4b4ad 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -82,7 +82,10 @@ use super::image_plan::{ check_image_limits, plan_image, plan_images, plan_texture_images, DepthImageFacts, ImageFacts, ImagePlan, ImageRefusal, }; -use super::linear_plan::{aliases, check_linear_limits, linear_lack, LinearImage, LinearLack}; +use super::linear_plan::{ + aliases, check_linear_limits, linear_lack, padding, texels_alone, BufferLayout, LinearImage, + LinearLack, +}; use super::memory::{MemoryClass, Placement}; use super::metal_texture::{self, MetalOver}; use super::mipmap::MipmapChecks; @@ -737,8 +740,9 @@ pub(super) enum AliasKind { /// their pointer, one made for host allocations and bound in the pages' import /// ([`Device::alias_image`]); over pages imported as dma-bufs, a `DRM_FORMAT_MOD_LINEAR` image /// bound to a dedicated import of a dma-buf of its own pages - /// ([`Device::dma_buf_alias_image`]). A rebind makes the kind its new pages take. - Linear { row_pitch: u64, slice_pitch: u64 }, + /// ([`Device::dma_buf_alias_image`]). A rebind makes the kind its new pages take, over the + /// same texels (`layout`, whose offset is in the buffer the texture was made over). + Linear { layout: BufferLayout }, /// A Metal texture over the import's `MTLBuffer` (`metal_texture.rs`). Metal(MetalOver), } @@ -2221,14 +2225,17 @@ impl Device { if host && self.exports_metal() { return self.metal_alias_image(plan, layout, descriptor, texels); } + let renders = descriptor.usage.contains(TextureUsage::RENDER_TARGET); + if let Some(why) = padding(&texels.layout, renders) { + return Ok(Err(why)); + } let who = if host { "the buffer is a no-copy buffer, and the device" } else { "the device" }; let made = if host { - let (row_pitch, slice_pitch) = (texels.layout.row_pitch, texels.layout.slice_pitch); - self.host_alias_unbound(&plan, row_pitch, slice_pitch, facts)? + self.host_alias_unbound(&plan, &texels.layout, facts)? } else if let Some(LinearLack { format, features }) = linear_lack(&plan, facts) { Err( LinearRefusal::Need(LinearNeed::Features { format, features }) @@ -2260,14 +2267,16 @@ impl Device { alignment: requirements.alignment, size: requirements.size, offset: report.offset, + subresource: report.size, row_pitch: report.row_pitch, array_pitch: report.array_pitch, }; let why = if !aliases(&texels.layout, memory_offset, room, &image) { Some(format!( "{who}'s linear image of the texture lays its texels out otherwise than Metal \ - at the texels' offset and row pitch (rows {} bytes apart, aligned to {})", - report.row_pitch, requirements.alignment + at the texels' offset and row pitch, or holds other bytes than its texels \ + (rows {} bytes apart, a subresource of {} bytes, aligned to {})", + report.row_pitch, report.size, requirements.alignment )) } else if requirements.memory_type_bits & (1 << type_index) == 0 { Some(format!( @@ -2334,8 +2343,7 @@ impl Device { from_base: memory_offset - base, texture_type: layout.texture_type, kind: AliasKind::Linear { - row_pitch: texels.layout.row_pitch, - slice_pitch: texels.layout.slice_pitch, + layout: texels.layout, }, }); } @@ -2449,16 +2457,23 @@ impl Device { "a texture over dma-buf pages the buffer does not lie in", )); }; + // Rows (or slices) with the buffer's bytes between them take no image (`linear_plan.rs`): + // the pages' source is not asked. + let renders = descriptor.usage.contains(TextureUsage::RENDER_TARGET); + if let Some(why) = padding(&texels.layout, renders) { + self.shared().counts.dma_buf_image_fell_back(); + return Ok(Err(why)); + } let base = texels.buffer.pages_base()?; let (_, buffer_offset, _) = texels.buffer.memory(); let from_base = buffer_offset + texels.layout.offset - base; - let (row_pitch, slice_pitch) = (texels.layout.row_pitch, texels.layout.slice_pitch); let place = crate::dma_buf::DmaBufTexels { pages: imports, type_index, at: start + from_base, - row_pitch, - slice_pitch, + row_pitch: texels.layout.row_pitch, + slice_pitch: texels.layout.slice_pitch, + alone: Some(texels.layout), }; let made = match self.dma_buf_image(plans, facts, &place)? { Ok(made) => made, @@ -2490,8 +2505,7 @@ impl Device { from_base, texture_type: layout.texture_type, kind: AliasKind::Linear { - row_pitch, - slice_pitch, + layout: texels.layout, }, }); Ok(Ok(image)) @@ -2702,26 +2716,26 @@ impl Device { })) } - /// The unbound image of `plan` made for host allocations whose texels lie at Metal's layout - /// in a no-copy buffer's pages, its rows `row_pitch` apart (and slices `slice_pitch`): the - /// driver's linear image ([`Device::host_linear_image`]) where it lays them out so, its - /// subresource at offset 0; else, where the device enables `VK_EXT_image_drm_format_modifier`, - /// a `DRM_FORMAT_MOD_LINEAR` image whose one plane the runtime lays out at those pitches + /// The unbound image of `plan` made for host allocations whose texels lie at Metal's `layout` + /// in a no-copy buffer's pages, its rows `layout.row_pitch` apart (and slices + /// `layout.slice_pitch`), holding no byte but them (`linear_plan::texels_alone`): the driver's + /// linear image ([`Device::host_linear_image`]) where it lays them out so, its subresource at + /// offset 0; else, where the device enables `VK_EXT_image_drm_format_modifier`, a + /// `DRM_FORMAT_MOD_LINEAR` image whose one plane the runtime lays out at those pitches /// ([`Device::host_pitched_image`]). Why not, each attempt's refusal named, where the device /// makes neither. The caller checks the image's alignment, size and memory types against the /// buffer's. fn host_alias_unbound( &self, plan: &ImagePlan, - row_pitch: u64, - slice_pitch: u64, + layout: &BufferLayout, facts: &ImageFacts<'_>, ) -> Result, Error> { - let slices = plan.layers.max(plan.extent[2]); let lies = |report: &vk::SubresourceLayout| { report.offset == 0 - && report.row_pitch == row_pitch - && (slices == 1 || report.array_pitch == slice_pitch) + && report.row_pitch == layout.row_pitch + && (layout.slices == 1 || report.array_pitch == layout.slice_pitch) + && texels_alone(layout, report.size, report.array_pitch) }; let made = match linear_lack(plan, facts) { Some(LinearLack { format, features }) => { @@ -2739,40 +2753,45 @@ impl Device { unsafe { release::object(self.shared().vk(), made.raw) }; format!( "its linear image for host allocations lays rows {} bytes apart (slices {}) \ - from offset {}", - made.report.row_pitch, made.report.array_pitch, made.report.offset + from offset {}, a subresource of {} bytes", + made.report.row_pitch, + made.report.array_pitch, + made.report.offset, + made.report.size ) } Err(refusal) => refusal.describe(plan, true), }; Ok(self - .host_pitched_image(plan, row_pitch, slice_pitch, facts)? + .host_pitched_image(plan, layout, facts)? .map_err(|pitched| format!("{linear}; and {pitched}"))) } /// A `DRM_FORMAT_MOD_LINEAR` image of `plan` made for host allocations, unbound, whose one - /// plane lies at offset 0 with rows `row_pitch` apart (and slices `slice_pitch`, for a plan of - /// several layers): a texture over a no-copy buffer's host pages where the driver's own linear - /// image lays its rows out otherwise than Metal (ANV packs them tight, where a surface's rows - /// are padded). Its memory requirements and its plane's layout as the driver reports them, - /// starting `UNDEFINED` as Vulkan has an image of external memory made. Why not where the - /// device does not enable the extension, makes no such image for host allocations + /// plane lies at offset 0 with rows `texels.row_pitch` apart (and slices `texels.slice_pitch`, + /// for a plan of several layers), holding no byte but the texels: a texture over a no-copy + /// buffer's host pages, its rows one after another, where the driver's own linear image lays + /// them out otherwise (further apart, its row pitch rounded up to an alignment of its own). + /// Its memory requirements and its plane's layout as the driver reports + /// them, starting `UNDEFINED` as Vulkan has an image of external memory made. Why not where + /// the device does not enable the extension, makes no such image for host allocations /// (`Device::modifier_image_checks`), refuses the layout, lays it out otherwise (NVIDIA lays - /// rows closer than its own linear image's at its own), or asks a dedicated allocation of it: - /// the runtime asks the driver and takes its answer, never a rule of its own. A layout the - /// driver refused is kept and refused again unasked (`texture/pitch_refusals.rs`). + /// rows closer than its own linear image's at its own) or past the texels + /// (`linear_plan::texels_alone`), or asks a dedicated allocation of it: the runtime asks the + /// driver and takes its answer, never a rule of its own. A layout the driver refused is kept + /// and refused again unasked (`texture/pitch_refusals.rs`). #[cfg(unix)] fn host_pitched_image( &self, plan: &ImagePlan, - row_pitch: u64, - slice_pitch: u64, + texels: &BufferLayout, facts: &ImageFacts<'_>, ) -> Result, Error> { use crate::dma_buf::{memory_plane_0, ModifierMemory, DRM_FORMAT_MOD_LINEAR}; + let (row_pitch, slice_pitch) = (texels.row_pitch, texels.slice_pitch); let raw_device = self.shared().vk(); let enabled = (self.shared().host_import.as_ref()) - .is_ok_and(|importer| importer.makes_modifier_images()); + .is_ok_and(|importer| importer.makes_dma_buf_images()); if !enabled { return Ok(Err( "the device enables no VK_EXT_image_drm_format_modifier for an image at Metal's \ @@ -2798,6 +2817,9 @@ impl Device { Ok(view_formats) => view_formats, Err(why) => return Ok(Err(why)), }; + if let Some(why) = self.explicit_plane_rows(plan) { + return Ok(Err(why)); + } let array_pitch = if plan.layers > 1 { slice_pitch } else { 0 }; let planes = [vk::SubresourceLayout { offset: 0, @@ -2858,6 +2880,13 @@ impl Device { {row_pitch} and slices {array_pitch} apart", report.offset, report.row_pitch, report.array_pitch )) + } else if !texels_alone(texels, report.size, report.array_pitch) { + Some(format!( + "the driver's DRM_FORMAT_MOD_LINEAR plane for host allocations takes {} bytes, \ + past the texels' {}", + report.size, + texels.end() - texels.offset + )) } else { None }; @@ -2880,8 +2909,7 @@ impl Device { fn host_pitched_image( &self, _plan: &ImagePlan, - _row_pitch: u64, - _slice_pitch: u64, + _texels: &BufferLayout, _facts: &ImageFacts<'_>, ) -> Result, Error> { Ok(Err( @@ -2936,11 +2964,8 @@ impl Device { swaps.push(ImageSwap::acquired(image, objects, pages, family)); continue; } - let (row_pitch, slice_pitch) = match &watch.kind { - AliasKind::Linear { - row_pitch, - slice_pitch, - } => (*row_pitch, *slice_pitch), + let layout = match &watch.kind { + AliasKind::Linear { layout } => *layout, AliasKind::Metal(over) => { let made = self.metal_image(image.plan(), over, watch.texture_type, memory, at)?; @@ -2959,8 +2984,8 @@ impl Device { }; // Its rows (and slices) lie as the old image's did: the texture's, in the driver's // linear image where it lays them out so, else in a `DRM_FORMAT_MOD_LINEAR` image - // at those pitches. - let made = self.host_alias_unbound(image.plan(), row_pitch, slice_pitch, &facts)?; + // at those pitches; either holding no byte but the texels. + let made = self.host_alias_unbound(image.plan(), &layout, &facts)?; let Ok(LinearMade { raw, requirements, @@ -3035,19 +3060,16 @@ impl Device { continue; }; // A Metal texture's rebind to dma-buf pages is refused as the swaps are made. - let AliasKind::Linear { - row_pitch, - slice_pitch, - } = watch.kind - else { + let AliasKind::Linear { layout } = watch.kind else { continue; }; let texels = crate::dma_buf::DmaBufTexels { pages: imports, type_index: placement.type_index(), at: pointer.as_ptr() as u64 + watch.from_base, - row_pitch, - slice_pitch, + row_pitch: layout.row_pitch, + slice_pitch: layout.slice_pitch, + alone: Some(layout), }; let Ok((_, made)) = self.dma_buf_image(&[image.plan()], &facts, &texels)? else { return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs index e22617718..12104275c 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap.rs @@ -1915,6 +1915,7 @@ impl Device { at, row_pitch: natural.row_pitch, slice_pitch: natural.slice_pitch, + alone: None, }; Ok((self.dma_buf_image(&[plan], facts, &texels)?).map(|(_, made)| made)) } @@ -2533,6 +2534,7 @@ impl Device { image, regions, staging: None, + texel: None, }, // A heap's bytes join no other memory (`host_aliases.rs`). alias: None, diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 575976283..7fda01bbe 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -95,6 +95,8 @@ pub(crate) struct Counters { modifier_feature_queries: AtomicU64, shadowed_textures: AtomicU64, shadows_zeroed: AtomicU64, + shadow_copies: AtomicU64, + shadow_texels_copied_back: AtomicU64, replay_logs_kept: AtomicU64, replay_log_bytes: AtomicU64, encoders_reencoded: AtomicU64, @@ -526,6 +528,14 @@ impl Counters { } } + /// An encoder planned `n` copies between shadowed textures' truths and their shadows + /// (`shadow.rs`), whose copies back of buffers' textures' images move `texels_back` texels. + pub(crate) fn shadow_copies_planned(&self, n: usize, texels_back: u64) { + self.shadow_copies.fetch_add(n as u64, Ordering::Relaxed); + self.shadow_texels_copied_back + .fetch_add(texels_back, Ordering::Relaxed); + } + /// A command buffer kept an ended encoder's log of `bytes` bytes (`replay.rs`). pub(crate) fn replay_log_kept(&self, bytes: usize) { self.replay_logs_kept.fetch_add(1, Ordering::Relaxed); @@ -929,6 +939,15 @@ pub struct WorkCounts { /// Every other shadow's copy in writes each texel before any command reads it, so its image /// starts as its memory lies. pub shadows_zeroed: u64, + /// Copies between a shadowed texture's truth and its shadow that encoders planned + /// (`shadow.rs`): copies in before a command, copies back after one or as the encoder ends, + /// and the keeps and merges of a command that writes the bytes two ways. Each is a command of + /// its encoder over the texture's texels. + pub shadow_copies: u64, + /// The texels those copies back move from a 2D texture's image to its buffer's bytes (a + /// texture over a buffer, a no-copy buffer or an IOSurface plane): every texel, or those + /// inside the rectangle bounding a pass's draws' scissors over an attachment it loads. + pub shadow_texels_copied_back: u64, /// Ended compute and blit encoders whose logs their command buffers kept, as a rebind before /// the first submission may encode them again (`replay.rs`), and the bytes of those logs. pub replay_logs_kept: u64, @@ -1085,6 +1104,8 @@ impl Device { modifier_feature_queries: counters.modifier_feature_queries.load(Ordering::Relaxed), shadowed_textures: counters.shadowed_textures.load(Ordering::Relaxed), shadows_zeroed: counters.shadows_zeroed.load(Ordering::Relaxed), + shadow_copies: counters.shadow_copies.load(Ordering::Relaxed), + shadow_texels_copied_back: counters.shadow_texels_copied_back.load(Ordering::Relaxed), replay_logs_kept: counters.replay_logs_kept.load(Ordering::Relaxed), replay_log_bytes: counters.replay_log_bytes.load(Ordering::Relaxed), encoders_reencoded: counters.encoders_reencoded.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index e08a2460a..5eb89e9dc 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -e3dcf31f158430ce425ce93bb0b5a8c9af8370167738acca8292cd7d78363888 +52d6ce1648b67055d046e043e6d1cd126e0a8315d04a922261df93ad0a25f734 diff --git a/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_blits.rs b/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_blits.rs index e9a210ff4..746823e80 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_blits.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/buffer_texture_blits.rs @@ -31,14 +31,18 @@ const USAGE: TextureUsage = TextureUsage::SHADER_READ .union(TextureUsage::SHADER_WRITE) .union(TextureUsage::PIXEL_FORMAT_VIEW); -/// Whether `device`'s driver lays the rows of a linear 2D image of `pf`, `width` x `height` -/// texels, otherwise than `row` bytes apart, read through Vulkan apart from the runtime: then no -/// linear image of the device aliases a texture over a buffer whose rows are `row` bytes apart, -/// and the texture is a shadow image (`shadowed-texture`). +/// Whether no linear 2D image of `pf` on `device`, `width` x `height` texels of `texel` bytes, +/// holds a texture's texels alone over an ordinary buffer whose rows lie `row` bytes apart, as the +/// runtime's rule has it (`linear_plan::aliases`): where the rows lie with bytes between them, or +/// where the driver's own image, read through Vulkan apart from the runtime, starts its texels +/// past its binding, lays its rows otherwise than `row` bytes apart, or holds bytes past its last +/// texel in its subresource (lavapipe's does, its height rounded up to 4 rows). The texture is then +/// a shadow image (`shadowed-texture`). pub(super) fn linear_rows_differ( device: &Device, pf: PixelFormat, [width, height]: [u32; 2], + texel: u64, row: u64, ) -> bool { let format = metal2vulkan::metal::format::direct_format(pf).expect("a format a buffer backs"); @@ -67,7 +71,7 @@ pub(super) fn linear_rows_differ( }; // SAFETY: an image of the test's own on the live device, made, read and destroyed here; none // of the device's objects is destroyed. - let pitch = unsafe { + let layout = unsafe { let raw = device.raw(); let image = raw .device @@ -75,9 +79,14 @@ pub(super) fn linear_rows_differ( .expect("a linear image"); let layout = raw.device.get_image_subresource_layout(image, subresource); raw.device.destroy_image(image, None); - layout.row_pitch + layout }; - pitch != row + let row_bytes = u64::from(width) * texel; + let texels = u64::from(height - 1) * row + row_bytes; + (height > 1 && row != row_bytes) + || layout.offset != 0 + || layout.row_pitch != row + || layout.size > texels } /// The probe's buffer pattern. @@ -891,7 +900,7 @@ fn an_overlapping_texel_copy_is_announced_once() { let first = forced(&[ ( Degradation::ShadowedTexture, - linear_rows_differ(&device, PixelFormat::RGBA8Unorm, [4, 4], 32), + linear_rows_differ(&device, PixelFormat::RGBA8Unorm, [4, 4], 4, 32), ), ( Degradation::SharedInSystemMemory, @@ -984,7 +993,7 @@ fn iosurface_planes_lie_where_metal_puts_them() { } let shadowed = planes .iter() - .any(|&(pf, _, _, bpr)| linear_rows_differ(&device, pf, [4, 4], bpr)); + .any(|&(pf, texel, _, bpr)| linear_rows_differ(&device, pf, [4, 4], texel, bpr)); let first = forced(&[ (Degradation::ShadowedTexture, shadowed), ( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs index fdf23de5f..a7ea699b4 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs @@ -1199,15 +1199,16 @@ fn check_texture_request( } /// Textures over a no-copy buffer of memfd memory (the consumer's display-path surfaces), rows 256 -/// bytes apart: where the device imports the buffer's pages as dma-bufs (RADV), each is an image of -/// `DRM_FORMAT_MOD_LINEAR` bound to a dedicated import of a dma-buf of its own pages, which the -/// source is asked for once, counted, its plane at the texels' offset in their first page: over one -/// page; over three, a page into the buffer; 256 bytes into a page; one a shader writes, whose -/// modifier's storage features above bit 31 the device reports only in the 64-bit list -/// (`STORAGE_*_WITHOUT_FORMAT`, which the optimal tiling has). One 64 bytes into a page, at which -/// RADV lays no plane (Mesa 26.2.4 and 26.0.8 took plane offsets that are multiples of 256 and -/// refused 4 to 128 and 4032), takes its shadow instead, the source not called, counted as a -/// fallback. Each reads the bytes the CPU wrote; the CPU's later writes, with no call between, are +/// bytes apart: where the device imports the buffer's pages as dma-bufs (RADV), each whose rows +/// are 256 bytes of texels is an image of `DRM_FORMAT_MOD_LINEAR` bound to a dedicated import of a +/// dma-buf of its own pages, which the source is asked for once, counted, its plane at the texels' +/// offset in their first page: over three pages, a page into the buffer; 256 bytes into a page; +/// one a shader writes, whose modifier's storage features above bit 31 the device reports only in +/// the 64-bit list (`STORAGE_*_WITHOUT_FORMAT`, which the optimal tiling has). One over one page, +/// whose rows of 240 bytes of texels have 16 of the file's between them, and one 64 bytes into a +/// page, of 64-byte rows, take their shadows instead (an image over them would hold the bytes +/// between the rows, which Vulkan lets a render pass write back), the source not called, counted +/// as fallbacks. Each reads the bytes the CPU wrote; the CPU's later writes, with no call between, are /// what the next command buffer reads (the image rests in `GENERAL` after its one acquire from the /// foreign queue family); a blit's write into it lands in the file's pages at the texels' places, /// the padding past each row keeping the CPU's bytes; the same texture made again asks the driver @@ -1248,7 +1249,7 @@ fn a_texture_over_dma_buf_pages_is_an_image_over_its_own_pages() { "one page", read_only(PixelFormat::RGBA8Unorm, 60, 16), 0, - true, + false, false, ), ( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs index 8f70d1337..0f072af59 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs @@ -21,9 +21,10 @@ //! `vk_image` answers its own image over the pages, shadowed where it answers none, and the //! images the making counted (`WorkCounts::pitched_host_images`, `shadowed_textures`). A shadow //! is made without zeroing its image (`shadows_zeroed`, `images_started_on_the_host`: its copy -//! in writes every texel first); on ANV, whose own linear images pack rows tight, a padded -//! texture is an image at Metal's row pitch (`DRM_FORMAT_MOD_LINEAR`), never a shadow; and -//! making the same texture again asks the driver no format's modifier features +//! in writes every texel first); a padded texture is a shadow but on a driver that runs on +//! Metal (a linear image over the pages would hold the bytes between the rows, which Vulkan +//! lets a render pass write back); and making the same texture again asks the driver no +//! format's modifier features //! (`modifier_feature_queries`), nor a layout at Metal's row pitch it refused //! (`pitched_host_image_refusals`, `pitched_host_image_refusals_recalled`), and takes the same //! form. @@ -195,10 +196,11 @@ fn padding(bytes: &[u8], bpr: u64, row: u64) -> Vec { .collect() } -/// Whether the device is ANV, whose own linear images pack rows tight: a texture over host -/// pages with padded rows is there an image at Metal's row pitch. -fn anv(device: &Device) -> bool { - device.properties().description.driver_id == Some(DriverId::INTEL_OPEN_SOURCE_MESA) +/// Whether the device runs on Metal (MoltenVK), where a texture over host pages is an image of a +/// Metal texture over the buffer, which keeps the bytes between its rows as Metal does: anywhere +/// else a texture over padded rows is a shadow. +fn on_metal(device: &Device) -> bool { + device.properties().description.driver_id == Some(DriverId::MOLTENVK) } /// A `Shared` buffer holding `bytes`. @@ -356,10 +358,10 @@ fn read_and_write_the_caller_s_pages(pf: PixelFormat, texel: u64, pad: u64) { "{what}: the shadow's image was zeroed on the host" ); } - if pad != 0 && anv(&device) { + if pad != 0 && !on_metal(&device) { assert!( - made && pitched == 1, - "{what}: on ANV not an image at Metal's row pitch (aliased {made}, pitched \ + !made && pitched == 0, + "{what}: rows with bytes between them aliased by a linear image (pitched \ images {pitched})" ); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs b/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs index 4678df2d9..dbe3939cf 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs @@ -4,11 +4,17 @@ //! no-copy buffer of private anonymous pages, at one of [`LAYOUTS`]: the browser's 1307x512 //! `BGRA8Unorm` tile with rows of 5248 bytes (its texels 5228), and the same tile and others with //! rows padded to 16, 256 and 512 bytes, a small tile, a full-width strip, and an `RGBA16Float` -//! tile, so the rows' padding takes each power of two from 16 to 512 bytes. +//! tile, so the rows' padding takes each power of two from 16 to 512 bytes; and tiles whose rows +//! lie one after another, of a height that is no multiple of 4, with the pages' later bytes past +//! their last row (a surface's next plane). //! //! Whatever form the device gives the texture (its own linear image, a `DRM_FORMAT_MOD_LINEAR` //! image laid out at Metal's row pitch, or a shadow), every step reads and writes Metal's bytes at -//! Metal's places, and no write reaches the bytes between the rows: +//! Metal's places, and no write reaches the bytes between the rows or past the last. A texture +//! whose rows lie with bytes between them is never a linear image over the pages (Vulkan lets an +//! image's layout transitions, and a render pass's load and store operations, write every byte of +//! its subresource), but on a driver that runs on Metal, whose image is a Metal texture over the +//! buffer: //! //! - **reads**: a blit out, `get_bytes`, a fragment function's `read`, and its `sample` through a //! nearest sampler give the caller's texels; a linear sampler gives what it gives over a private @@ -17,13 +23,21 @@ //! - **writes**: a blit of a buffer into the texture, `replace_region` of a box at an odd origin, //! and a blit of a private texture's box into it land in the pages; //! - **renders**: a pass that loads, blends a rectangle and stores, and one that clears, blends and -//! stores, leave in the pages what they leave in a private texture of the same texels; +//! stores, leave in the pages what they leave in a private texture of the same texels; one that +//! loads, blends and stores `DontCare` leaves the pages as they were, as Apple's GPU leaves the +//! attachment's earlier texels; //! - **blits out**: a box at an odd origin copied into a private texture holds the pages' texels. //! +//! [`a_fragment_function_s_writes_leave_the_bytes_between_rows`] makes the textures with shader +//! read and write usage instead, and writes every texel through a fragment function's `write`: the +//! pages' texels are a private texture's after the same writes, and no other byte changes. +//! +//! [`a_padded_texture_s_shadow_names_what_may_write_its_padding`] checks the shadow's reason over +//! an ordinary buffer's padded rows: a texture that only reads names its layout transitions, a +//! render target a render pass's load and store operations too. +//! //! Printed per layout (`PITCHED-SURFACE`): the form, the images the making counted -//! (`WorkCounts::pitched_host_images`, `shadowed_textures`), and a shadow's reason. On ANV, whose -//! own linear images pack rows tight, every layout is an image at Metal's row pitch, never a -//! shadow. +//! (`WorkCounts::pitched_host_images`, `shadowed_textures`), and a shadow's reason. use super::host_memory::{counting, no_copy, not_importable, Mapping, GUEST_PAGE}; use super::no_copy_textures::{blending, floats, staged}; @@ -38,7 +52,7 @@ use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ BlitOption, Buffer, ClearColor, CommandQueue, Degradation, Device, IoSurfacePlane, LoadAction, Origin, PipelineOptions, Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions, - SamplerState, Size, StoreAction, Texture, TextureDescriptor, + SamplerState, ScissorRect, Size, StoreAction, Texture, TextureDescriptor, }; /// A surface's plane: its name, pixel format and texel bytes, width, height and bytes per row. @@ -73,10 +87,15 @@ impl Layout { fn len(&self) -> usize { (self.bpr * self.h) as usize } + + /// Whether the rows lie with bytes between them that are not texels. + fn padded(&self) -> bool { + self.bpr != self.row() + } } /// The layouts, each its own test. -const LAYOUTS: [Layout; 8] = [ +const LAYOUTS: [Layout; 11] = [ // The browser's tile: rows padded to 64 bytes (5248 = 41 x 128). Layout::bgra8("1307x512/5248", 1307, 512, 5248), // Rows padded to 16 bytes (5232 = 327 x 16). @@ -100,6 +119,20 @@ const LAYOUTS: [Layout; 8] = [ h: 128, bpr: 5312, }, + // Rows one after another (a surface's rows are multiples of 16 bytes), 510 of them: a + // driver's image of 512 reaches past the texels. + Layout::bgra8("1308x510/5232", 1308, 510, 5232), + // Rows one after another, of a whole number of cache lines (1200 = 18.75 x 64). + Layout::bgra8("300x200/1200", 300, 200, 1200), + // An `RGBA16Float` tile, rows one after another, 126 of them. + Layout { + name: "658x126/5264 RGBA16Float", + pf: PixelFormat::RGBA16Float, + texel: 8, + w: 658, + h: 126, + bpr: 5264, + }, ]; /// Texels of `layout` for `n` bytes, varied by `k`, each a value every read, sample and blend @@ -152,6 +185,32 @@ fn differing(a: &[u8], b: &[u8], texel: u64) -> (usize, Option) { (count, first) } +/// Where `now` differs from `expected` outside `layout`'s texels, in words: how many bytes, the +/// rows they lie in, and the first, with its place in its row and the bytes it holds. +fn padding_changes(layout: &Layout, now: &[u8], expected: &[u8]) -> String { + let (bpr, row) = (layout.bpr as usize, layout.row() as usize); + let changed: Vec = (0..now.len().min(expected.len())) + .filter(|&i| now[i] != expected[i] && (i % bpr >= row || i / bpr >= layout.h as usize)) + .collect(); + let Some(&first) = changed.first() else { + return "none outside the texels".to_owned(); + }; + let rows: std::collections::BTreeSet = changed.iter().map(|i| i / bpr).collect(); + let end = (first + 8).min(now.len()); + format!( + "{} bytes outside the texels in {} rows (rows {:?}..={:?}), the first at row {} byte {} \ + (a row's texels end at byte {row}), now {:02x?}, was {:02x?}", + changed.len(), + rows.len(), + rows.first(), + rows.last(), + first / bpr, + first % bpr, + &now[first..end], + &expected[first..end] + ) +} + /// The bytes of a `Shared` buffer, which no command uses now. fn bytes_of(buffer: &Buffer) -> Vec { let contents = buffer.contents().unwrap(); @@ -302,11 +361,11 @@ fn drawn( } /// A pass over `texture` that loads it (clears it to (0.1, 0.2, 0.3, 0.4) where `clear`), blends -/// `color` over the rectangle `corners` and stores. +/// `color` over the rectangle `corners` and stores (by `store`). fn blend_pass( queue: &CommandQueue, pipeline: &RenderPipelineState, - texture: &Texture, + (texture, store): (&Texture, StoreAction), clear: bool, (corners, color): ([f32; 4], [f32; 4]), ) { @@ -321,7 +380,7 @@ fn blend_pass( } else { LoadAction::Load }; - attachment.store_action = StoreAction::Store; + attachment.store_action = store; attachment.clear_color = ClearColor::new(0.1, 0.2, 0.3, 0.4); let command_buffer = queue.command_buffer().unwrap(); let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); @@ -343,10 +402,141 @@ fn sampler(device: &Device, filter: SamplerMinMagFilter) -> SamplerState { device.new_sampler_state(&d).unwrap() } -/// Whether the device is ANV, whose own linear images pack rows tight: a texture over host pages -/// with padded rows is there an image at Metal's row pitch. -fn anv(device: &Device) -> bool { - device.properties().description.driver_id == Some(DriverId::INTEL_OPEN_SOURCE_MESA) +/// Whether the device runs on Metal (MoltenVK), where a texture over host pages is an image of a +/// Metal texture over the buffer, which keeps the bytes between its rows as Metal does. +fn on_metal(device: &Device) -> bool { + device.properties().description.driver_id == Some(DriverId::MOLTENVK) +} + +/// A texture of `layout` over a no-copy buffer of new anonymous pages, made as a surface's with +/// `usage`: the pages hold a pattern of their own, the texels `texels_of(.., 1)` laid at the rows; +/// with the buffer, the mapping and the pages as written. `None` where the device imports no host +/// memory. Its form is checked against the making's counts: a shadow counted where it is not +/// aliased, and never a linear image over padded rows off Metal. +fn surface(device: &Device, layout: &Layout, usage: TextureUsage) -> Option { + let len = layout.len().next_multiple_of(GUEST_PAGE); + let mapping = Mapping::anonymous(len); + // The pages: texels a blend keeps finite, and the bytes between the rows a pattern of + // their own, which no write through the texture reaches. + let mut pages = counting(len, 7); + lay( + layout, + &mut pages, + &texels_of(layout, (layout.row() * layout.h) as usize, 1), + ); + mapping.write(0, &pages); + // SAFETY: the mapping outlives the buffer and the texture (dropped first, by `Surface`). + let made = unsafe { + no_copy( + device, + mapping.pointer(), + len, + ResourceOptions::default(), + None, + ) + }; + let buffer = match made { + Ok(buffer) => buffer, + Err(error) if not_importable(&error) => { + eprintln!("PITCHED-SURFACE: the device imports no host memory: {error:?}"); + return None; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = usage; + d.resource_options = buffer.resource_options(); + let before = device.work_counts(); + let texture = buffer + .new_texture_with_iosurface_plane(&d, IoSurfacePlane::new(0, layout.bpr, false)) + .unwrap(); + let counted = device.work_counts(); + let pitched = counted.pitched_host_images - before.pitched_host_images; + let shadowed = counted.shadowed_textures - before.shadowed_textures; + // SAFETY: the handle is only compared, while the texture lives. + let aliased = unsafe { texture.vk_image() }.is_some(); + let what = format!("{} ({}, {usage:?})", layout.name, layout.pf.name()); + assert_eq!( + u64::from(!aliased), + shadowed, + "{what}: aliased {aliased}, but {shadowed} shadows counted" + ); + assert!( + !(aliased && layout.padded()) || on_metal(device), + "{what}: rows with bytes between them aliased by a linear image (pitched images \ + {pitched})" + ); + Some(Surface { + texture, + buffer, + mapping, + pages, + len, + what, + form: (aliased, pitched, shadowed), + }) +} + +/// A texture over a no-copy buffer's pages ([`surface`]). +struct Surface { + texture: Texture, + buffer: Buffer, + mapping: Mapping, + /// The pages as written before the texture was made. + pages: Vec, + /// The pages' bytes. + len: usize, + /// The layout, format and usage, in words. + what: String, + /// Whether it is aliased, and the pitched images and shadows its making counted. + form: (bool, u64, u64), +} + +impl Surface { + /// Check that the pages hold `expected`: its texels (by `layout`), then every byte. + fn check(&self, layout: &Layout, step: &str, expected: &[u8]) { + let what = &self.what; + let now = self.mapping.read(0..self.len); + let (count, first) = differing(&rows(layout, &now), &rows(layout, expected), layout.texel); + assert!( + count == 0, + "{what}, {step}: {count} texels in the pages differ from Metal's, the first at texel \ + {first:?}" + ); + assert!( + now == expected, + "{what}, {step}: the bytes between the rows (or past the last) changed: {}", + padding_changes(layout, &now, expected) + ); + } + + /// Print the form and a shadow's reason (`PITCHED-SURFACE`), and drop the texture, then the + /// buffer, then the pages. + fn report(self, device: &Device, messages: &Messages) { + let (aliased, pitched, shadowed) = self.form; + let reason = messages + .take_notices() + .into_iter() + .filter_map(|message| message.degradation) + .find(|notice| notice.degradation == Degradation::ShadowedTexture) + .map(|notice| format!(": {}", notice.reason)) + .unwrap_or_default(); + eprintln!( + "PITCHED-SURFACE on {}: {}: {} (pitched host images {pitched}, shadows \ + {shadowed}){reason}", + device.name(), + self.what, + if aliased { "aliased" } else { "shadowed" }, + ); + let Surface { + texture, + buffer, + mapping, + .. + } = self; + drop((texture, buffer)); + drop(mapping); + } } /// The module docs' steps over a texture of `layout` over a no-copy buffer: each read gives the @@ -358,76 +548,15 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { { let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); let queue = device.new_command_queue().unwrap(); - let (n, texel) = (layout.len(), layout.texel); - let len = n.next_multiple_of(GUEST_PAGE); - let mapping = Mapping::anonymous(len); - // The pages: texels a blend keeps finite, and the bytes between the rows a pattern of - // their own, which no write through the texture reaches. - let mut pages = counting(len, 7); - lay( - &layout, - &mut pages, - &texels_of(&layout, (layout.row() * layout.h) as usize, 1), - ); - mapping.write(0, &pages); - // SAFETY: the mapping outlives the buffer and the texture (dropped first, below). - let made = unsafe { - no_copy( - &device, - mapping.pointer(), - len, - ResourceOptions::default(), - None, - ) + let texel = layout.texel; + let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + let Some(surface) = surface(&device, &layout, usage) else { + return; }; - let buffer = match made { - Ok(buffer) => buffer, - Err(error) if not_importable(&error) => { - eprintln!("PITCHED-SURFACE: the device imports no host memory: {error:?}"); - return; - } - Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), - }; - let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); - d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; - d.resource_options = buffer.resource_options(); - let before = device.work_counts(); - let texture = buffer - .new_texture_with_iosurface_plane(&d, IoSurfacePlane::new(0, layout.bpr, false)) - .unwrap(); - let counted = device.work_counts(); - let pitched = counted.pitched_host_images - before.pitched_host_images; - let shadowed = counted.shadowed_textures - before.shadowed_textures; - // SAFETY: the handle is only compared, while the texture lives. - let aliased = unsafe { texture.vk_image() }.is_some(); - let what = format!("{} ({})", layout.name, layout.pf.name()); - assert_eq!( - u64::from(!aliased), - shadowed, - "{what}: aliased {aliased}, but {shadowed} shadows counted" - ); - if anv(&device) { - assert!( - aliased && pitched == 1, - "{what}: on ANV not an image at Metal's row pitch (aliased {aliased}, pitched \ - images {pitched})" - ); - } + let (texture, what) = (&surface.texture, &surface.what); // The pages as Metal leaves them, after each step. - let mut expected = pages.clone(); - let check = |step: &str, expected: &[u8]| { - let now = mapping.read(0..len); - let (count, first) = differing(&rows(&layout, &now), &rows(&layout, expected), texel); - assert!( - count == 0, - "{what}, {step}: {count} texels in the pages differ from Metal's, the first at \ - texel {first:?}" - ); - assert!( - now == expected, - "{what}, {step}: the bytes between the rows (or past the last) changed" - ); - }; + let mut expected = surface.pages.clone(); + let check = |step: &str, expected: &[u8]| surface.check(&layout, step, expected); let read = |step: &str, ours: &[u8], theirs: &[u8]| { let (count, first) = differing(ours, theirs, texel); assert!( @@ -438,7 +567,7 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { // Reads of the caller's bytes as they were before the texture was made. let texels = rows(&layout, &expected); - read("a blit out", &blit_out(&queue, &layout, &texture), &texels); + read("a blit out", &blit_out(&queue, &layout, texture), &texels); let mut got = vec![0u8; texels.len()]; let whole = Region::new_2d(0, 0, layout.w, layout.h); texture @@ -448,7 +577,7 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { let reads = reading(&device, layout.pf, "tob_read"); read( "a fragment function's read", - &drawn(&queue, &layout, &reads, &texture, None), + &drawn(&queue, &layout, &reads, texture, None), &texels, ); let samples = reading(&device, layout.pf, "tob_sample"); @@ -456,13 +585,13 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { let linear = sampler(&device, SamplerMinMagFilter::Linear); read( "a nearest sample", - &drawn(&queue, &layout, &samples, &texture, Some(&nearest)), + &drawn(&queue, &layout, &samples, texture, Some(&nearest)), &texels, ); let private = private_with(&queue, &layout, &texels); read( "a linear sample, against a private texture's", - &drawn(&queue, &layout, &samples, &texture, Some(&linear)), + &drawn(&queue, &layout, &samples, texture, Some(&linear)), &drawn(&queue, &layout, &samples, &private, Some(&linear)), ); check("the reads", &expected); @@ -470,21 +599,21 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { // The caller's later bytes, read by a sample and a blit. let later = texels_of(&layout, texels.len(), 2); lay(&layout, &mut expected, &later); - mapping.write(0, &expected); + surface.mapping.write(0, &expected); read( "a nearest sample of the caller's later bytes", - &drawn(&queue, &layout, &samples, &texture, Some(&nearest)), + &drawn(&queue, &layout, &samples, texture, Some(&nearest)), &later, ); read( "a blit out of the caller's later bytes", - &blit_out(&queue, &layout, &texture), + &blit_out(&queue, &layout, texture), &later, ); // Writes: a blit of a buffer, `replace_region` of a box, a blit of a private texture's box. let written = texels_of(&layout, later.len(), 3); - blit_in(&queue, &layout, &texture, &written); + blit_in(&queue, &layout, texture, &written); lay(&layout, &mut expected, &written); check("a blit's write", &expected); let (bx, by, bw, bh) = (3, 5, layout.w / 2 + 1, layout.h / 3 + 1); @@ -503,7 +632,7 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { blit_box( &queue, (&source, Origin::new(fx, fy, 0)), - (&texture, Origin::new(tx, ty, 0)), + (texture, Origin::new(tx, ty, 0)), size, ); let from = blit_out(&queue, &layout, &source); @@ -524,8 +653,14 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { ("a pass that loads, blends and stores", false, left), ("a pass that clears, blends and stores", true, right), ] { - blend_pass(&queue, &blend, &reference, clear, rect); - blend_pass(&queue, &blend, &texture, clear, rect); + blend_pass( + &queue, + &blend, + (&reference, StoreAction::Store), + clear, + rect, + ); + blend_pass(&queue, &blend, (texture, StoreAction::Store), clear, rect); lay( &layout, &mut expected, @@ -533,6 +668,15 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { ); check(step, &expected); } + // A pass that does not store leaves the pages as they were. + blend_pass( + &queue, + &blend, + (texture, StoreAction::DontCare), + false, + left, + ); + check("a pass that loads, blends and stores DontCare", &expected); // A blit of the texture's box out into a private texture. let (fx, fy) = (layout.w / 4 + 1, 3); @@ -540,7 +684,7 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { let out = private_with(&queue, &layout, &vec![0; later.len()]); blit_box( &queue, - (&texture, Origin::new(fx, fy, 0)), + (texture, Origin::new(fx, fy, 0)), (&out, Origin::new(0, 0, 0)), size, ); @@ -556,22 +700,305 @@ fn reads_writes_and_renders_as_metal(layout: Layout) { ); } check("the last blit", &expected); - // A shadow's reason, as the device announced it. - let reason = messages - .take_notices() - .into_iter() - .filter_map(|message| message.degradation) - .find(|notice| notice.degradation == Degradation::ShadowedTexture) - .map(|notice| format!(": {}", notice.reason)) - .unwrap_or_default(); - eprintln!( - "PITCHED-SURFACE on {}: {what}: {} (pitched host images {pitched}, shadows \ - {shadowed}){reason}", - device.name(), - if aliased { "aliased" } else { "shadowed" }, + surface.report(&device, &messages); + } + let messages = messages.take(); + assert!( + messages.is_empty(), + "the validation layer reported: {messages:#?}" + ); +} + +/// A texture of `layout` over a no-copy buffer whose first use reads it through its image (a +/// fragment function's `read`), before any command reads or writes the pages another way: the +/// image's first move to `GENERAL` (from `UNDEFINED`, as Vulkan has an image of host allocations +/// made, `VUID-VkImageCreateInfo-pNext-01443`) keeps the bytes, which Vulkan does not promise +/// ("doing so will cause the contents of the image's memory to be undefined", docs/FAST-PATHS.md's +/// known gaps). A driver that discards them fails here: the read differs from the texels, or the +/// pages change. +fn first_use_reads_the_bytes(layout: Layout) { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let queue = device.new_command_queue().unwrap(); + let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + let Some(surface) = surface(&device, &layout, usage) else { + return; + }; + let texels = rows(&layout, &surface.pages); + let reads = reading(&device, layout.pf, "tob_read"); + let read = drawn(&queue, &layout, &reads, &surface.texture, None); + let (count, first) = differing(&read, &texels, layout.texel); + assert!( + count == 0, + "{}, its first use: {count} texels read differ from the pages', the first at texel \ + {first:?}", + surface.what + ); + surface.check(&layout, "its first use", &surface.pages); + surface.report(&device, &messages); + } + let messages = messages.take(); + assert!( + messages.is_empty(), + "the validation layer reported: {messages:#?}" + ); +} + +/// [`first_use_reads_the_bytes`] over each of [`LAYOUTS`]: an aliased texture's image moves at its +/// first use (a shadow's copy in reads the pages through a buffer). +#[test] +fn a_texture_s_first_use_reads_the_bytes_it_was_made_over() { + for layout in LAYOUTS { + first_use_reads_the_bytes(layout); + } +} + +/// A texture over a buffer's padded rows (the browser's tile, [`LAYOUTS`]' first) is a shadow on +/// every device, its buffer an ordinary one's, which no image of Metal's aliases either; and its +/// `shadowed-texture` notice names what Vulkan lets write the padding: for a texture that only +/// reads, its image's layout transitions (the first move from the layout it is made in), never a +/// render pass, which no image of its takes; for a render target, a render pass's load and store +/// operations too. Each usage on a device of its own, which announces the kind once. +#[test] +fn a_padded_texture_s_shadow_names_what_may_write_its_padding() { + let layout = LAYOUTS[0]; + assert!(layout.padded(), "{}", layout.name); + for (usage, renders) in [ + (TextureUsage::SHADER_READ, false), + ( + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + true, + ), + ] { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + // What the device announced as it was made. + messages.take_notices(); + let buffer = device + .new_buffer(layout.bpr * layout.h, ResourceOptions::default()) + .unwrap(); + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = usage; + d.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&d, 0, layout.bpr).unwrap(); + // SAFETY: the handle is only compared, while the texture lives. + let aliased = unsafe { texture.vk_image() }.is_some(); + assert!(!aliased, "{} ({usage:?}): aliased", layout.name); + let reason = messages + .take_notices() + .into_iter() + .filter_map(|message| message.degradation) + .find(|notice| notice.degradation == Degradation::ShadowedTexture) + .map(|notice| notice.reason) + .unwrap_or_else(|| { + panic!("{} ({usage:?}): no shadowed-texture notice", layout.name) + }); + eprintln!( + "PITCHED-SURFACE on {}: {} ({usage:?}), an ordinary buffer's: shadowed: {reason}", + device.name(), + layout.name + ); + let rows = format!( + "its rows lie {} bytes apart, {} bytes of texels each", + layout.bpr, + layout.row() + ); + assert!(reason.contains(&rows), "{usage:?}: {reason}"); + assert!( + reason.contains("its layout transitions read and write"), + "{usage:?}: {reason}" + ); + assert_eq!( + reason.contains("a render pass's load and store operations write back"), + renders, + "{usage:?}: {reason}" + ); + drop((texture, buffer)); + } + let messages = messages.take(); + assert!( + messages.is_empty(), + "the validation layer reported: {messages:#?}" + ); + } +} + +/// A pass over a shadowed texture (the browser's padded tile over an ordinary buffer, a shadow on +/// every device) that loads it and draws nothing leaves its texels as they were, as Metal's leaves +/// the tiles no draw reaches: it takes no copy in and no copy back (`WorkCounts::shadow_copies`), +/// whether it stores the attachment or stores it `DontCare`, and the buffer keeps every byte. A +/// pass that draws a rectangle copies in before it and back after it. +#[test] +fn a_pass_that_draws_nothing_copies_no_shadow() { + let layout = LAYOUTS[0]; + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let queue = device.new_command_queue().unwrap(); + let len = layout.bpr * layout.h; + let buffer = device.new_buffer(len, ResourceOptions::default()).unwrap(); + let bytes = texels_of(&layout, len as usize, 3); + let contents = buffer.contents().unwrap(); + // SAFETY: a new `Shared` buffer of `len` bytes, which no command uses yet. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&d, 0, layout.bpr).unwrap(); + // SAFETY: the handle is only compared, while the texture lives. + assert!(unsafe { texture.vk_image() }.is_none(), "a shadow"); + let copies = || device.work_counts().shadow_copies; + for store in [StoreAction::Store, StoreAction::DontCare] { + let before = copies(); + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(texture.clone()); + attachment.load_action = LoadAction::Load; + attachment.store_action = store; + let command_buffer = queue.command_buffer().unwrap(); + let encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.end_encoding().unwrap(); + run(&command_buffer); + assert_eq!(copies() - before, 0, "{store:?}: a pass drawing nothing"); + assert!( + bytes_of(&buffer) == bytes, + "{store:?}: the buffer's bytes changed" + ); + } + let before = copies(); + let blend = blending(&device, layout.pf); + let rect = ([-1.0, -1.0, 0.0, 1.0], [0.25, 0.5, 0.75, 0.5]); + blend_pass(&queue, &blend, (&texture, StoreAction::Store), false, rect); + assert_eq!( + copies() - before, + 2, + "a pass drawing a rectangle: in and back" ); drop((texture, buffer)); - drop(mapping); + } + let messages = messages.take(); + assert!( + messages.is_empty(), + "the validation layer reported: {messages:#?}" + ); +} + +/// A pass that loads a shadowed texture (the browser's padded tile over an ordinary buffer, a +/// shadow on every device) and draws under a scissor copies back only the texels inside it +/// (`WorkCounts::shadow_texels_copied_back`): a fragment outside the scissor has no coverage, and +/// the pass's load and store write back what they read. The buffer holds the blend inside the +/// scissor, as a private texture of the same texels blended alike does, and every other byte as +/// it was. Without a scissor, the copy back moves every texel. +#[test] +fn a_pass_copies_back_only_the_texels_its_scissors_reach() { + let layout = LAYOUTS[0]; + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let queue = device.new_command_queue().unwrap(); + let len = layout.bpr * layout.h; + let buffer = device.new_buffer(len, ResourceOptions::default()).unwrap(); + let bytes = texels_of(&layout, len as usize, 5); + let contents = buffer.contents().unwrap(); + // SAFETY: a new `Shared` buffer of `len` bytes, which no command uses yet. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&d, 0, layout.bpr).unwrap(); + // SAFETY: the handle is only compared, while the texture lives. + assert!(unsafe { texture.vk_image() }.is_none(), "a shadow"); + let private = private_with(&queue, &layout, &rows(&layout, &bytes)); + let blend = blending(&device, layout.pf); + let corners = staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])); + let color = staged(&device, &floats([0.25, 0.5, 0.75, 0.5])); + let scissor = ScissorRect::new(100, 40, 300, 200); + let draw = |target: &Texture, scissor: Option| { + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(target.clone()); + attachment.load_action = LoadAction::Load; + attachment.store_action = StoreAction::Store; + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&blend).unwrap(); + if let Some(scissor) = scissor { + encoder.set_scissor_rect(scissor).unwrap(); + } + encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + encoder.set_fragment_buffer(Some(&color), 0, 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + run(&command_buffer); + }; + let moved = || device.work_counts().shadow_texels_copied_back; + let before = moved(); + draw(&texture, Some(scissor)); + assert_eq!(moved() - before, 300 * 200, "a scissored pass"); + draw(&private, Some(scissor)); + let mut expected = bytes.clone(); + lay(&layout, &mut expected, &blit_out(&queue, &layout, &private)); + let now = bytes_of(&buffer); + let (count, first) = differing( + &rows(&layout, &now), + &rows(&layout, &expected), + layout.texel, + ); + assert!( + count == 0, + "{count} texels differ from the private texture's, the first at texel {first:?}" + ); + assert!(now == expected, "the bytes between the rows changed"); + let before = moved(); + draw(&texture, None); + assert_eq!(moved() - before, layout.w * layout.h, "an unscissored pass"); + drop((texture, buffer, private)); + } + let messages = messages.take(); + assert!( + messages.is_empty(), + "the validation layer reported: {messages:#?}" + ); +} + +/// A texture of `layout` over a no-copy buffer, with shader read and write usage, written at every +/// texel by a fragment function's `write` (`tob_write`): the pages' texels are what a private +/// texture of the same texels holds after the same writes, and no other byte of the pages changes. +fn writes_as_metal(layout: Layout) { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let queue = device.new_command_queue().unwrap(); + let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + let Some(surface) = surface(&device, &layout, usage) else { + return; + }; + let mut expected = surface.pages.clone(); + let texels = rows(&layout, &expected); + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = usage; + d.resource_options = ResourceOptions::private(); + let reference = device.new_texture(&d).unwrap(); + blit_in(&queue, &layout, &reference, &texels); + let writes = reading(&device, layout.pf, "tob_write"); + drawn(&queue, &layout, &writes, &reference, None); + drawn(&queue, &layout, &writes, &surface.texture, None); + lay( + &layout, + &mut expected, + &blit_out(&queue, &layout, &reference), + ); + surface.check(&layout, "a fragment function's writes", &expected); + surface.report(&device, &messages); } let messages = messages.take(); assert!( @@ -601,4 +1028,16 @@ per_layout! { a_full_width_strip_reads_writes_and_renders_as_metal => 5; a_narrow_tile_reads_writes_and_renders_as_metal => 6; a_half_float_tile_reads_writes_and_renders_as_metal => 7; + a_tile_of_510_packed_rows_reads_writes_and_renders_as_metal => 8; + a_small_tile_of_packed_rows_reads_writes_and_renders_as_metal => 9; + a_half_float_tile_of_126_packed_rows_reads_writes_and_renders_as_metal => 10; +} + +/// A fragment function's writes over [`LAYOUTS`]: padded rows (a browser's tile, a narrow tile, a +/// half-float tile) and packed ones of a height that is no multiple of 4, and of one that is. +#[test] +fn a_fragment_function_s_writes_leave_the_bytes_between_rows() { + for index in [0, 6, 7, 8, 9, 10] { + writes_as_metal(LAYOUTS[index]); + } } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs b/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs index 9cfda4e02..2a62d23f8 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs @@ -129,12 +129,12 @@ fn heap_texture_kinds(device: &Device, descriptor: &TextureDescriptor) -> BTreeS } /// The kinds a texture over a buffer of [`RGBA8Uint`](PixelFormat::RGBA8Uint) rows -/// [`ROW_BYTES`] apart, [`ROW_TEXELS`] wide and 2 high, forces where its device's linear rows lie -/// otherwise ([`linear_rows_differ`]): its shadow (`shadowed-texture`), and the heap set holding -/// it as its ID's holder (`UNNAMED_SHADOWS`). +/// [`ROW_BYTES`] apart, [`ROW_TEXELS`] wide and 2 high, forces where no linear image of its device +/// holds its texels alone ([`linear_rows_differ`]): its shadow (`shadowed-texture`), and the heap +/// set holding it as its ID's holder (`UNNAMED_SHADOWS`). fn row_shadow_kinds(device: &Device) -> Vec { let rows = [ROW_TEXELS as u32, 2]; - match linear_rows_differ(device, PixelFormat::RGBA8Uint, rows, ROW_BYTES) { + match linear_rows_differ(device, PixelFormat::RGBA8Uint, rows, 4, ROW_BYTES) { true => [Degradation::ShadowedTexture, UNNAMED_SHADOWS[0]].into(), false => Vec::new(), } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs index 513fe8b18..bce26589a 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs @@ -24,8 +24,8 @@ //! process's CPU time; and the device's work counts per frame that the path moves (dma-buf images //! and fallbacks, shadows and those zeroed as made, images at Metal's row pitch over host pages //! and the driver's refusals of them, asked and recalled, images started on the host, internal -//! submissions). `SURFTEX-QUERY` lines print what the driver answers for a `DRM_FORMAT_MOD_LINEAR` -//! image of host allocations. +//! submissions, shadows' copies and the texels their copies back move). `SURFTEX-QUERY` lines +//! print what the driver answers for a `DRM_FORMAT_MOD_LINEAR` image of host allocations. //! //! [`pitch_classes`] asks which row pitches the device lays a texture over a no-copy buffer's //! host pages at: for each of a few formats and usages (a device each), widths, and pitches of @@ -38,20 +38,29 @@ //! own linear image does not alias took one answer; per format and usage (`SURFTEX-PITCH-RULE`) //! the classes at Metal's pitch, shadowed and mixed, and the reason the first shadow announced. //! -//! Both are ignored by default: measurements, not checks. Run them by name with `--run-ignored all`, in a +//! [`surface_texture_cost_parts`] takes the frame apart over anonymous pages: the textures' making +//! around an empty command buffer, the passes that store, the passes that store `DontCare`, the +//! passes that draw and store, the blits, and both, so a shadow's copies in and back show apart +//! from the rest (`SURFTEX-PART`). +//! +//! [`shadow_copy_costs`] times a shadow's copies alone, and the same bytes moved between other +//! memories, to tell the image's tiling from the pages' memory (`SURFTEX-COPY`). +//! +//! All four are ignored by default: measurements, not checks. Run them by name with `--run-ignored all`, in a //! build with `--cfg m2v_system_alloc`, whose lib test binary keeps the system allocator as a //! consumer's process does. use super::dma_buf_imports::{udmabuf_openable, Calls, Memfd, View}; use super::host_memory::{host_page, Mapping, GUEST_PAGE}; +use super::no_copy_textures::{blending, floats, staged}; use super::{validated_device_with, Messages, ScratchCache, WAIT}; use crate::gpu::TEST_DEVICE; use ash::vk; -use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan_runtime::{ - Buffer, CommandQueue, Device, HostMemory, IoSurfacePlane, LoadAction, Origin, - RenderPassDescriptor, ResourceOptions, Size, StoreAction, Texture, TextureDescriptor, - WorkCounts, + BlitOption, Buffer, CommandQueue, Device, HostMemory, IoSurfacePlane, LoadAction, Origin, + RenderPassDescriptor, RenderPipelineState, ResourceOptions, ScissorRect, Size, StoreAction, + Texture, TextureDescriptor, WorkCounts, }; use std::time::Instant; @@ -162,29 +171,104 @@ fn aliased(texture: &Texture) -> bool { unsafe { texture.vk_image() }.is_some() } -/// One frame's work over `textures`: a pass loading and storing each, and a blit reading each into -/// its private texture of `privates`, in one command buffer, committed and waited for. The host's -/// time encoding, and from the commit until the wait returned. -fn frame(queue: &CommandQueue, textures: &[Texture], privates: &[Texture]) -> (f64, f64) { +/// What a frame encodes over its textures: [`Part::Both`] is the consumer's frame, the others +/// its parts apart ([`surface_texture_cost_parts`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Part { + /// Nothing: an empty command buffer, committed and waited for, after the textures are made. + Empty, + /// A pass loading and storing each texture: a shadow's copy in before it and copy back after. + PassesStored, + /// A pass loading each texture and storing it `DontCare`: a shadow's copy in, and no copy back. + PassesNotStored, + /// A pass loading each texture, blending a rectangle over its left half, and storing it, as a + /// browser's pass draws: a shadow's copy in and copy back. + PassesDrawn, + /// As [`Part::PassesDrawn`], under a scissor of the left half, as a browser's pass redrawing a + /// damaged part of a tile draws. + PassesScissored, + /// A blit reading each texture into its private texture, which reads a texture over a buffer + /// as its bytes: no shadow's copy. + Blits, + /// The passes that store, then the blits. + Both, +} + +/// A pipeline blending a rectangle over a `BGRA8Unorm` attachment, and its rectangle's corners +/// and color ([`Part::PassesDrawn`]). +struct Drawing { + pipeline: RenderPipelineState, + corners: Buffer, + color: Buffer, +} + +impl Drawing { + fn new(device: &Device) -> Drawing { + Drawing { + pipeline: blending(device, PixelFormat::BGRA8Unorm), + corners: staged(device, &floats([-1.0, -1.0, 0.0, 1.0])), + color: staged(device, &floats([0.25, 0.5, 0.75, 0.5])), + } + } +} + +/// One frame's `part` of the work over `textures`: a pass loading and storing each, and a blit +/// reading each into its private texture of `privates`, in one command buffer, committed and +/// waited for; a drawn pass draws through `drawing`. The host's time encoding, and from the commit +/// until the wait returned. +fn frame( + queue: &CommandQueue, + textures: &[Texture], + privates: &[Texture], + (part, drawing): (Part, Option<&Drawing>), +) -> (f64, f64) { let began = Instant::now(); let command_buffer = queue.command_buffer().unwrap(); - for texture in textures { + let store_action = match part { + Part::PassesStored | Part::PassesDrawn | Part::PassesScissored | Part::Both => { + Some(StoreAction::Store) + } + Part::PassesNotStored => Some(StoreAction::DontCare), + Part::Empty | Part::Blits => None, + }; + for texture in textures.iter().filter(|_| store_action.is_some()) { let mut pass = RenderPassDescriptor::new(); let attachment = &mut pass.color_attachments[0]; attachment.texture = Some(texture.clone()); attachment.load_action = LoadAction::Load; - attachment.store_action = StoreAction::Store; - let encoder = command_buffer.render_command_encoder(&pass).unwrap(); + attachment.store_action = store_action.unwrap_or(StoreAction::Store); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + if matches!(part, Part::PassesDrawn | Part::PassesScissored) { + let drawing = drawing.expect("a drawn pass's pipeline"); + encoder + .set_render_pipeline_state(&drawing.pipeline) + .unwrap(); + if part == Part::PassesScissored { + let left = ScissorRect::new(0, 0, texture.width() / 2, texture.height()); + encoder.set_scissor_rect(left).unwrap(); + } + encoder + .set_vertex_buffer(Some(&drawing.corners), 0, 0) + .unwrap(); + encoder + .set_fragment_buffer(Some(&drawing.color), 0, 0) + .unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + } encoder.end_encoding().unwrap(); } - let mut blit = command_buffer.blit_command_encoder().unwrap(); - for (texture, private) in textures.iter().zip(privates) { - let size = Size::new(texture.width(), texture.height(), 1); - let origin = Origin::new(0, 0, 0); - blit.copy_from_texture_to_texture(texture, 0, 0, origin, size, private, 0, 0, origin) - .unwrap(); + if matches!(part, Part::Blits | Part::Both) { + let mut blit = command_buffer.blit_command_encoder().unwrap(); + for (texture, private) in textures.iter().zip(privates) { + let size = Size::new(texture.width(), texture.height(), 1); + let origin = Origin::new(0, 0, 0); + blit.copy_from_texture_to_texture(texture, 0, 0, origin, size, private, 0, 0, origin) + .unwrap(); + } + blit.end_encoding().unwrap(); } - blit.end_encoding().unwrap(); let encoded = since(began); let committed = Instant::now(); command_buffer.commit().unwrap(); @@ -200,7 +284,7 @@ fn counts_per_frame(before: &WorkCounts, after: &WorkCounts, frames: usize) -> S "shadowed textures {:.2} (zeroed {:.2}), pitched host images {:.2} (refused {:.2}, \ recalled {:.2}), dma-buf images {:.2}, dma-buf image fallbacks {:.2}, dma-buf imports \ {:.2}, images started on the host {:.2}, internal submissions {:.2}, staging submissions \ - {:.2}", + {:.2}, shadow copies {:.2} (texels copied back {:.0})", per(after.shadowed_textures, before.shadowed_textures), per(after.shadows_zeroed, before.shadows_zeroed), per(after.pitched_host_images, before.pitched_host_images), @@ -224,6 +308,11 @@ fn counts_per_frame(before: &WorkCounts, after: &WorkCounts, frames: usize) -> S ), per(after.internal_submissions, before.internal_submissions), per(after.staging_submissions, before.staging_submissions), + per(after.shadow_copies, before.shadow_copies), + per( + after.shadow_texels_copied_back, + before.shadow_texels_copied_back + ), ) } @@ -382,7 +471,7 @@ fn surface_texture_costs() { textures.push(texture); buffers.push(buffer); } - let (encoded, waited) = frame(&queue, &textures, &privates); + let (encoded, waited) = frame(&queue, &textures, &privates, (Part::Both, None)); for (index, (texture, buffer)) in textures.into_iter().zip(buffers).enumerate() { let began = Instant::now(); drop((texture, buffer)); @@ -441,6 +530,231 @@ fn surface_texture_costs() { println!("SURFTEX-NOTICES on {}: {notices:?}", device.name()); } +/// [`surface_texture_costs`]' frame over anonymous pages, a new buffer and texture of each of +/// [`LAYOUTS`] each frame, taken apart ([`Part`]): the textures made and released around an empty +/// command buffer, the passes that store, the passes that store `DontCare`, the passes that draw a +/// rectangle and store (also under a scissor of the left half), the blits, and both; +/// then the same over the packed layouts alone, which no shadow is made beside. Where a texture is +/// a shadow, the passes that store less the empty frame are its copies in and back and the pass, +/// the passes that do not store less the empty frame its copies in and the pass; the blits read +/// the bytes either way. Printed per set and part (`SURFTEX-PART`): the textures' forms, the +/// medians and 90th percentiles of each one's making (its buffer and texture), of the frame's +/// release, encoding, commit to completion and process CPU time, and the work counts per frame. +#[test] +#[ignore = "a release-mode measurement: run by name"] +fn surface_texture_cost_parts() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { + options.layers.clear(); + }) + .unwrap(); + messages.take_notices(); + let queue = device.new_command_queue().unwrap(); + let lens: Vec = LAYOUTS + .iter() + .map(|&(_, _, h, bpr)| Surface::len(bpr, h)) + .collect(); + let privates: Vec = LAYOUTS + .iter() + .map(|&(_, w, h, _)| { + let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, w, h, false); + d.usage = TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::private(); + device.new_texture(&d).unwrap() + }) + .collect(); + let surfaces: Vec = lens + .iter() + .map(|&len| Surface::Anonymous(Mapping::anonymous(len))) + .collect(); + // Every layout, then the packed ones alone (rows one after another, no texture a shadow). + let every: Vec = (0..LAYOUTS.len()).collect(); + let packed: Vec = every + .iter() + .copied() + .filter(|&index| LAYOUTS[index].3 == LAYOUTS[index].1 * 4) + .collect(); + let parts = [ + Part::Empty, + Part::PassesStored, + Part::PassesNotStored, + Part::PassesDrawn, + Part::PassesScissored, + Part::Blits, + Part::Both, + ]; + let drawing = Drawing::new(&device); + let drawing = Some(&drawing); + for (set, chosen) in [("every layout", &every), ("packed layouts", &packed)] { + let privates: Vec = chosen.iter().map(|&i| privates[i].clone()).collect(); + for part in parts { + let mut forms = Vec::new(); + let mut makes = vec![Vec::new(); chosen.len()]; + let (mut releases, mut encodes, mut waits, mut cpus) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut before = device.work_counts(); + for k in 0..WARM + FRAMES { + if k == WARM { + before = device.work_counts(); + } + let cpu = process_cpu_us(); + let mut made = Vec::new(); + for (at, &index) in chosen.iter().enumerate() { + let (_, w, h, bpr) = LAYOUTS[index]; + let began = Instant::now(); + let buffer = surfaces[index].buffer(&device, lens[index], None); + let texture = plane_texture(&buffer, w, h, bpr); + if k >= WARM { + makes[at].push(since(began)); + } + made.push((texture, buffer)); + } + if k == 0 { + forms = made + .iter() + .map(|(texture, _)| if aliased(texture) { 'a' } else { 's' }) + .collect(); + } + let textures: Vec = + made.iter().map(|(texture, _)| texture.clone()).collect(); + let (encoded, waited) = frame(&queue, &textures, &privates, (part, drawing)); + let began = Instant::now(); + drop((textures, made)); + let released = since(began); + if k >= WARM { + releases.push(released); + encodes.push(encoded); + waits.push(waited); + cpus.push(process_cpu_us() - cpu); + } + } + let after = device.work_counts(); + let forms: String = forms.into_iter().collect(); + let makes: Vec = chosen + .iter() + .zip(makes) + .map(|(&index, times)| { + let (median, p90) = median_p90(times); + format!("{} {median:.0} (p90 {p90:.0})", LAYOUTS[index].0) + }) + .collect(); + let (release, release90) = median_p90(releases); + let (encode, encode90) = median_p90(encodes); + let (wait, wait90) = median_p90(waits); + let (cpu, cpu90) = median_p90(cpus); + println!( + "SURFTEX-PART on {}: {set}, {part:?}, forms {forms} (a aliased, s shadowed): \ + making us {}; release {release:.0} us (p90 {release90:.0}), encode {encode:.0} us \ + (p90 {encode90:.0}), commit to completion {wait:.0} us (p90 {wait90:.0}), process \ + CPU {cpu:.0} us (p90 {cpu90:.0}); per frame: {}", + device.name(), + makes.join(", "), + counts_per_frame(&before, &after, FRAMES), + ); + } + } + drop(surfaces); + let notices = super::degrade_notices::counts(&messages.take_notices()); + println!("SURFTEX-NOTICES on {}: {notices:?}", device.name()); +} + +/// What a shadow's copies cost apart from the passes around them, on the browser's 1307x512 +/// `BGRA8Unorm` tile at rows of 5248 bytes: each copy alone in a command buffer, committed and +/// waited for, between a private texture made as a shadow is (render target and shader read +/// usage) and a no-copy buffer over anonymous pages (a copy back's way, and a copy in's), and, to +/// tell the image's tiling from the pages' memory, between the texture and a private buffer and a +/// `Shared` one, and between a private buffer and the pages. Printed per copy +/// (`SURFTEX-COPY`): the median and 90th percentile of commit to completion. +#[test] +#[ignore = "a release-mode measurement: run by name"] +fn shadow_copy_costs() { + const BLITS: usize = 50; + let (w, h, bpr) = (1307, 512, 5248); + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { + options.layers.clear(); + }) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let len = Surface::len(bpr, h); + let pages = Surface::Anonymous(Mapping::anonymous(len)); + let host = pages.buffer(&device, len, None); + let private = device + .new_buffer(len as u64, ResourceOptions::private()) + .unwrap(); + let shared = device + .new_buffer(len as u64, ResourceOptions::shared()) + .unwrap(); + let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, w, h, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::private(); + let image = &device.new_texture(&d).unwrap(); + let size = Size::new(w, h, 1); + let origin = Origin::new(0, 0, 0); + // Each copy: the texture into a buffer, a buffer into the texture, or one buffer into another. + let copies: [(&str, Option<&Buffer>, Option<&Buffer>); 6] = [ + ("image to pages (a copy back)", None, Some(&host)), + ("pages to image (a copy in)", Some(&host), None), + ("image to private buffer", None, Some(&private)), + ("image to shared buffer", None, Some(&shared)), + ("private buffer to pages", Some(&private), Some(&host)), + ("pages to private buffer", Some(&host), Some(&private)), + ]; + for (name, from, to) in copies { + let mut waits = Vec::new(); + for k in 0..WARM + BLITS { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + match (from, to) { + (None, Some(to)) => blit.copy_from_texture_to_buffer( + image, + 0, + 0, + origin, + size, + to, + 0, + bpr, + bpr * h, + BlitOption::None, + ), + (Some(from), None) => blit.copy_from_buffer_to_texture( + from, + 0, + bpr, + bpr * h, + size, + image, + 0, + 0, + origin, + BlitOption::None, + ), + (Some(from), Some(to)) => blit.copy_from_buffer_to_buffer(from, 0, to, 0, bpr * h), + (None, None) => unreachable!("every copy has a buffer"), + } + .unwrap(); + blit.end_encoding().unwrap(); + let committed = Instant::now(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + if k >= WARM { + waits.push(since(committed)); + } + } + let (wait, wait90) = median_p90(waits); + println!( + "SURFTEX-COPY on {}: {name}, {w}x{h} at {bpr} bytes a row: commit to completion \ + {wait:.0} us (p90 {wait90:.0})", + device.name() + ); + } + // The copies, then the buffers, then the pages they lie over go, in that order. +} + /// The formats [`pitch_classes`] asks about, with their texel bytes. const SWEPT_FORMATS: [(PixelFormat, u64); 9] = [ (PixelFormat::BGRA8Unorm, 4), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/view_reinterpretation.rs b/crates/metal2vulkan-validation/src/runtime_lane/view_reinterpretation.rs index a2268bfbb..dda0fb51e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/view_reinterpretation.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/view_reinterpretation.rs @@ -650,14 +650,14 @@ fn a_shadowed_view_answers_as_a_view_of_the_image_does() { host_access_through_a_view(&device); // The view's shadow where withheld, nothing of it where the device views the image; // and what the steps force: the texture over a buffer's shadow where no linear image - // lays its rows as Metal does, and the `Shared` buffers' system memory. + // holds its texels alone, and the `Shared` buffers' system memory. let kinds: &[Degradation] = if withheld { &VIEW_SHADOWS } else { &[] }; let row = SIDE * 4 + 16; let side = SIDE as u32; let first = forced(&[ ( Degradation::ShadowedTexture, - linear_rows_differ(&device, PixelFormat::RGBA8Unorm, [side, side], row), + linear_rows_differ(&device, PixelFormat::RGBA8Unorm, [side, side], 4, row), ), ( Degradation::SharedInSystemMemory, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 290bf4baf..f389668cb 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 399; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1202; +pub const RUNTIME_VERSION: u32 = 1203; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index fa674f167..b42725d92 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -836,6 +836,13 @@ pub enum RuntimeDriverDefect { /// the runtime preprocesses every execution of an indirect command buffer's range apart /// (`vkCmdPreprocessGeneratedCommandsEXT`) before the first of them runs. ImplicitPreprocessAfterExecutionSet, + /// A render pass over an image of `VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT` whose one plane + /// the caller laid out (`VkImageDrmFormatModifierExplicitCreateInfoEXT`) writes the rows past + /// its height up to a multiple of 4, past its subresource and its memory requirements (into + /// another resource's bytes, or unmapped memory). Nothing is refused: the runtime makes no + /// such image of a height that is no multiple of 4 there, and a texture over a buffer or a + /// heap's pages takes its shadow (`shadowed-texture`). + ExplicitPlaneRowsPastHeight, } /// One device capability a refusal can name. diff --git a/docs/API.md b/docs/API.md index 72d087fd0..b3c521e17 100644 --- a/docs/API.md +++ b/docs/API.md @@ -145,9 +145,9 @@ or fingerprint: among it the extensions of its dma-buf fallback for no-copy memo the device refuses (`HostMemory::with_dma_buf`), `VK_EXT_external_memory_dma_buf` with `VK_KHR_external_memory_fd`, and `VK_EXT_image_drm_format_modifier` with `VK_EXT_queue_family_foreign` beside them, wherever a device lists them. With them enabled, a -texture over a no-copy buffer's pages imported by their pointer is also a `DRM_FORMAT_MOD_LINEAR` -image made for host allocations at Metal's row pitch where the driver's own linear image lays its -rows out otherwise (ANV packs them tight) and the driver takes that layout, of a format with no depth +texture over a no-copy buffer's pages imported by their pointer, its rows packed, is also a +`DRM_FORMAT_MOD_LINEAR` image made for host allocations at Metal's row pitch where the driver's own +linear image lays its rows out otherwise and the driver takes that layout, of a format with no depth or stencil component (Vulkan has no query of where such a format's memory plane lies, so the runtime makes no `DRM_FORMAT_MOD_LINEAR` image of one) (`WorkCounts::pitched_host_images`; HOWTO.md section 6 lists what each measured driver takes). @@ -694,18 +694,26 @@ how to avoid it in full. [FAST-PATHS.md](FAST-PATHS.md) lists which notes the de fast forms record, and each `PrecisionNote`'s rustdoc states its bound. - `metal2vulkan-degrade-shadowed-texture` (performance). `ShadowedTexture`: A 2D texture over a - buffer is a shadow image: no linear image of the device lays its texels out as Metal does in the - buffer's memory (over a no-copy buffer's imported host memory, no linear image made for host - allocations does: neither the driver's own nor, where the device enables - `VK_EXT_image_drm_format_modifier`, a `DRM_FORMAT_MOD_LINEAR` image laid out at Metal's row - pitch, which the driver may refuse for the texture's format, usage or pitch, and which the - runtime makes of no depth or stencil format; - `WorkCounts::pitched_host_images` counts those made, `pitched_host_image_refusals` those the - driver refused), or the buffer is over the caller's `VkBuffer`, whose memory backs no image of - the runtime's, or over host pages imported as dma-bufs (`HostMemory::with_dma_buf`) where the - device makes no image over a dma-buf of the texture's own pages (the notice names why; - `WorkCounts::dma_buf_image_fallbacks` counts it). Cost: its texels are copied into an image before - each use and back after each write. + buffer is a shadow image: its rows (or an array's slices) lie with the buffer's bytes between + them, which an image over them would hold in its subresource, where Vulkan lets the image's + layout transitions (its first move among them, which a texture that only reads takes too) read + and write any byte of its subresources, and a render pass's load and store operations read and + write back any byte of an attachment's image subresource, and Metal leaves them as the program + writes them (but where the device's image of it is a Metal + texture over the buffer, on MoltenVK); or no linear image of the device lays its texels out as + Metal does in the buffer's memory, holding no byte past them (over a no-copy buffer's imported + host memory, no linear image made for host allocations does: neither the driver's own nor, where + the device enables `VK_EXT_image_drm_format_modifier`, a `DRM_FORMAT_MOD_LINEAR` image laid out + at Metal's row pitch, which the driver may refuse for the texture's format, usage or pitch, and + which the runtime makes of no depth or stencil format, nor of a height that is no multiple of 4 + where the driver renders an explicit plane's rows past its height + (`RuntimeDriverDefect::ExplicitPlaneRowsPastHeight`, lavapipe); `WorkCounts::pitched_host_images` + counts those made, `pitched_host_image_refusals` those the driver refused), or the buffer is + over the caller's `VkBuffer`, whose memory backs no image of the runtime's, or over host pages + imported as dma-bufs (`HostMemory::with_dma_buf`) where the device makes no image over a dma-buf + of the texture's own pages (the notice names why; `WorkCounts::dma_buf_image_fallbacks` counts + it). + Cost: its texels are copied into an image before each use and back after each write. - `metal2vulkan-degrade-staged-texture-buffer` (performance). `StagedTextureBuffer`: A texture buffer is viewed through a staging buffer: its texels start where the device views none (`minTexelBufferOffsetAlignment`). Cost: its texels are copied into a staging buffer before each diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 1ee773aa6..dabee97ee 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -144,6 +144,46 @@ driver's. Each is open work. the encoding thread and 2.7 ms through completion less a frame, as nothing is copied back), and one that stores it renders in place at no added cost. Where MoltenVK runs the pass as one unbroken instance, Metal keeps the bytes at no cost. +- **A texture over a buffer whose rows lie with bytes between them** (a guest browser's padded + surfaces, an array whose slices are rounded up to 128 bytes) is a shadow on every device but + MoltenVK (`shadowed-texture`), its texels copied in before each use and back after each write. + An image over those rows would hold the bytes between them in its subresource, where Metal + leaves them as the program writes them, and Vulkan lets two kinds of operation write them: the + image's layout transitions "may perform read and write accesses on all memory bound to the image + subresource range", and every image takes one, its first move from the layout it is made in, + before any use (so a texture that only reads is a shadow too); and a render pass's load and store + operations "read and write back any memory locations within the image subresource bound for that + attachment" (lavapipe writes back those its 4-texel blocks reach, a signaling NaN's bits + quieted). No query of the device's promises otherwise. On ANV (Mesa 26.2.4) making the browser's 1307x512 + tile took about 135 µs as a shadow against 41 µs as an image at its row pitch. Packed rows + (`bytes_per_row` the texels' bytes) avoid it where the device lays an image's rows there. +- **A shadow's copy back after a pass that draws covers every texel inside the draws' + scissors**, where Metal's store writes back only the 32x32 tiles a draw's primitives touch + (reims-vgpu's padding probe on an M3 Max, macOS 27.0.1: a tile with geometry stores its + undrawn texels back, a tile without stores nothing, and the bytes between rows are never + written). Without a CPU write to the texture's texels during the pass, both leave the same + bytes. With one, to an undrawn texel in a tile no primitive touches but inside the scissors, the + copy back can undo it where Metal keeps it: the host does not know which tiles the primitives + touch. A pass that reaches no tile copies nothing back, and no copy reaches the bytes between + rows. +- **A texture's image over pages imported by their pointer keeps their bytes past its first + move only because the drivers do.** Vulkan makes an image of host allocations start in + `UNDEFINED` (`VUID-VkImageCreateInfo-pNext-01443`), and a move from `UNDEFINED` "will cause the + contents of the image's memory to be undefined"; memory imported from a host pointer "shares + ownership of the memory between the host and the Vulkan implementation", host access as to any + memory, so no queue-family acquire from outside keeps them either. That holds for the driver's + own linear image for host allocations (`texture.rs`'s `host_linear_image`), the + `DRM_FORMAT_MOD_LINEAR` image at Metal's row pitch (`host_pitched_image`), and, on MoltenVK, + the image of a Metal texture over the import's `MTLBuffer` (`metal_alias_image`; Vulkan says + nothing of such an image's contents). lavapipe (Mesa 26.2.4) keeps the bytes + (`runtime_lane::pitched_surfaces::a_texture_s_first_use_reads_the_bytes_it_was_made_over`, a + first use that reads through the image, fails where a driver drops them). Spec-backed: an + image over a dma-buf of its own pages, which its first move acquires from + `VK_QUEUE_FAMILY_FOREIGN_EXT` in `GENERAL` (the external memory chapter: "acquire exclusive + ownership in the destination instance or API", the `UNDEFINED` initial layout "a placeholder"), + and a linear image of the runtime's own memory, made `PREINITIALIZED`. The exact form, a shadow + of every texture over such pages (on ANV a tile's making about 135 µs against 41 µs, and a copy + in and back at each use), is the owner's call. - **A cold pipeline making on NVIDIA grows with a module's sampling sites.** NVIDIA's compiler (615.71.09) takes about 1 s for macOS 26's largest CoreAnimation fragment (210,033 words) on the RTX 5080 Laptop GPU, made once per cold cache (the first boot, and after an update changes the diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 17f33eaf0..e5ce063bc 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -170,13 +170,29 @@ A texture over such memory is an image over a dma-buf of its own pages where the `VK_EXT_image_drm_format_modifier` and `VK_EXT_queue_family_foreign` (RADV does). RADV (Mesa 26.2.4 and 26.0.8) lays such an image's plane only at an offset in its page that is a multiple of 256 bytes, with rows a multiple of 256 bytes apart: keep a texture's offset and `bytes_per_row` so (a -4 KiB-aligned surface with 256-byte-aligned rows always is). Elsewhere the texture takes a shadow of -the bytes, announced (`shadowed-texture`, naming why), and a rebind that cannot make the image again -is refused (`NotImplemented(RebindTextures)`). `WorkCounts::dma_buf_imports`, -`dma_buf_sparse_buffers`, `dma_buf_images` and `dma_buf_image_fallbacks` count what the route did. +4 KiB-aligned surface with 256-byte-aligned rows always is), with no byte between its rows (below). +Elsewhere the texture takes a shadow of the bytes, announced (`shadowed-texture`, naming why), and a +rebind that cannot make the image again is refused (`NotImplemented(RebindTextures)`). +`WorkCounts::dma_buf_imports`, `dma_buf_sparse_buffers`, `dma_buf_images` and +`dma_buf_image_fallbacks` count what the route did. -A texture over pages imported by their pointer aliases them where the device lays an image's rows -at the texture's `bytes_per_row`: the driver's own linear image, or, where that lays its rows +A texture over a buffer's bytes is an image over them only where its rows lie one after another +(`bytes_per_row` is its texels' bytes, or it has one row; an array's slices likewise) and the +image holds no byte past its texels. A texture whose rows lie with bytes between them, as a guest +browser's padded surfaces' do, is a shadow (`shadowed-texture`) on every device but MoltenVK, whose +image is a Metal texture over the buffer: an image at that pitch holds the bytes between the rows +in its subresource (`VkSubresourceLayout`: "size includes any extra memory that is required based +on rowPitch"), and Vulkan lets two kinds of operation write them, where Metal leaves them as the +program writes them. The image's layout transitions "may perform read and write accesses on all +memory bound to the image subresource range", and every image takes one, its first move from the +layout it is made in, before any use, so a texture that only reads is a shadow too. A render pass's +load and store operations "read and write back any memory locations within the image subresource +bound for that attachment" (lavapipe writes back the bytes its 4-texel blocks reach past a row, a +signaling NaN's bits quieted). No query of the device's states otherwise. To keep a surface +aliased, lay its rows packed. + +Over pages imported by their pointer, such a texture aliases them where the device lays an image's +rows at the texture's `bytes_per_row`: the driver's own linear image, or, where that lays its rows otherwise, a `DRM_FORMAT_MOD_LINEAR` image at that pitch, which the driver may refuse (and which the runtime makes of no depth or stencil format, as it makes no image over a dma-buf of one: Vulkan has no query of where such a format's memory plane lies). Measured @@ -192,9 +208,11 @@ each power of two from 16 to 4096 bytes): 256, and asks a dedicated allocation of an image at any other, so it takes no pitch but its own. The own rows' alignments are as measured for `BGRA8Unorm`. Elsewhere the texture is a shadow -(`shadowed-texture`): a `BGRA8Unorm` surface whose rows are its texels' bytes rounded up to 256 -bytes on RADV, or 128 on NVIDIA, is aliased. `WorkCounts::pitched_host_images` and -`pitched_host_image_refusals` count the images at Metal's pitch made and refused. +(`shadowed-texture`): a `BGRA8Unorm` surface with packed rows takes the driver's own linear image +on RADV where its texels' bytes are a multiple of 256, and on NVIDIA where they are a multiple of +128 (their own rows' alignments). +`WorkCounts::pitched_host_images` and `pitched_host_image_refusals` count the images at Metal's +pitch made and refused. ## 7. Check the integration