Files
metal2vulkan/docs/HOWTO.md
T
Anees Iqbal 30c8b4bff8 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.
2026-10-14 20:17:38 +03:00

14 KiB

Integrating metal2vulkan

The checklist around the library: the tools each piece needs, caching, failures, isolating a compile, host memory a driver refuses, and checking an integration. The API itself is API.md; the runtime's is its README.

1. Tools

The libraries read AIR bitcode (a metallib, a bitcode wrapper or a raw module) and run no external tool. The command line (feature cli) runs two, both optional:

  • llvm-as (LLVM 21 or newer) to assemble an LLVM text input (.ll). Not needed for a metallib or bitcode.
  • spirv-val (SPIRV-Tools) to check each module it writes. When it is missing the tool says so and still writes the modules, which the library has verified itself.

Put them on PATH, or name each one:

export METAL2VULKAN_LLVM_AS=/path/to/llvm-as
export METAL2VULKAN_SPIRV_VAL=/path/to/spirv-val

The runtime opens the Vulkan loader when it makes a device (or takes the consumer's vkGetInstanceProcAddr when it adopts one). Nothing links against Vulkan at build time.

2. Compile

From the command line, see the README. From Rust, API.md walks the flow in the order a consumer meets it:

  1. A device: describe the Vulkan device as created and choose a policy.
  2. A library: parse a metallib or AIR bitcode.
  3. A compute pipeline or a render pipeline, under a Budget.
  4. The interface and the plan: the layout, what each slot binds, what a dispatch or draw needs.
  5. At bind time: descriptor writes and push-constant bytes from what is bound.

Every air.simd_* operation keeps Metal's 32-lane simdgroup; there is no option to use the driver's subgroup width instead.

To read AIR without translating it (list a metallib's functions, decode a module into typed IR, read its entry points' bindings, canonicalize an entry under function-constant values), depend on metal2vulkan-air. Use the same version as metal2vulkan, which pins it exactly; the translator's input errors are that crate's types.

3. Cache

The translator keeps no cache; it gives you keys and encodings to keep one (API.md section 7):

  • A key is a SHA-256 of the inputs, cache::SEMANTICS_VERSION and the device's profile fingerprint, known before compiling.
  • A decode checks the format and semantics versions, the key, the profile fingerprint and a checksum. Every ArtifactError is a cache miss: compile again and replace the entry.
  • The versions move independently: the crate's (the API), SEMANTICS_VERSION (the output; a bump misses every cached artifact), ARTIFACT_FORMAT_VERSION (the encoding) and RUNTIME_VERSION (what the runtime does with an unchanged artifact).

The runtime's shader cache

The runtime keeps every shader it translates on disk, as Metal programs get from the OS, so a second process does not translate it again. It cannot be turned off.

  • Where. By default ~/Library/Caches/metal2vulkan on macOS, $XDG_CACHE_HOME/metal2vulkan elsewhere, or ~/.cache/metal2vulkan when XDG_CACHE_HOME is unset. ShaderCacheOptions (in DeviceOptions, or RawDevice for an adopted device) names another directory. Several processes and builds may share it; each build reads only its own translations.
  • How much. At most capacity bytes on disk (25 GiB by default), least recently used first; another build's entries go after 30 days unused. In memory, at most memory_capacity bytes (256 MiB by default): a pipeline state made again takes its translation from there without reading the disk.
  • The driver's pipeline cache. Each pipeline is made with a VkPipelineCache of its own, seeded from a record named by what the making reads (its SPIR-V, layout and state, and the driver's identity) and written back only when the making added to it. After an update of metal2vulkan, a pipeline whose SPIR-V and state did not change is made from its record; a driver update starts empty. On drivers that report pipelineBinaryInternalCacheControl (NVIDIA's), a device the runtime makes turns the driver's own internal cache off; an adopted device keeps what its creator chose.
  • When it fills or a write fails. Each device says so once, through its MessageSink (or on stderr) as a Warning whose id_name is metal2vulkan-shader-cache-evicted or metal2vulkan-shader-cache-write-failed. Match on id_name, never on the text. Later events are counted in Device::shader_cache_statistics.
  • Failures. Making or adopting a device fails with Error::ShaderCache when the directory cannot be made or written. After that, a failed read or write only costs a translation.
  • Cold runs. To measure with nothing cached, give the device an empty directory, and turn the driver's own shader cache off (__GL_SHADER_DISK_CACHE=0 for NVIDIA, MESA_SHADER_CACHE_DISABLE=true for Mesa). Give each test its own directory.
  • It is a cache. Deleting the directory, or any file in it, is always safe.

4. Handle failures

Every failure is a typed value; match variants, never messages (API.md section 8).

  • A refusal names what would change the answer: the feature the device lacks, the pipeline input the compile needs, or a limit.
  • A deadline or a cancellation (Error::Budget, Error::Cancelled) is transient: retry later. Every other error is the answer for that input and device and may be cached as one (error.retry(), error.is_permanent_for()).
  • Never use a module from a compile that returned an error.
  • The command line prints metal2vulkan: FALLBACK (<why>), exits 2, and writes a repro bundle (the input, the profile, repro.sh, failure.txt) under $TMPDIR/metal2vulkan-repros, or METAL2VULKAN_REPRO_DIR.

5. Bound a compile

Every compile runs in-process under the caller's Budget: a wall deadline (Budget::standard() is 20 seconds), a CancelToken any thread may trigger, a deterministic work-unit cap and a byte ledger charged before each input-sized allocation. A panic inside a compile becomes Error::Internal. That is enough for a consumer that trusts its process.

When an abort, a stack overflow or a failed allocation in the compiler must not take the consumer down, or a hard memory ceiling must hold, compile in a child process:

  1. Spawn one worker per compile in its own process group, with the input in a file and the result written to a file. Send the library bytes, the entry and descriptor, and the device description and policy (with feature serde they serialize; equal description and policy give the same profile fingerprint and keys).
  2. In the child, install a counting global allocator that refuses allocations above a budget, build the Device, and compile with the same Budget.
  3. In the parent, poll the deadline, cancellation and the process group's resident memory. On a breach, kill the whole group and remove its scratch files. A result that arrives late is a timeout.
  4. Load the result with PipelineArtifact::from_bytes against the parent's own Device, and check that its key is the one the parent computed (Device::compute_pipeline_key, render_pipeline_key).
  5. Classify as in-process: a typed error is the answer; a deadline, cancellation or killed child is transient.

The validation crate's worker (crates/metal2vulkan-validation/src/worker/) implements this, under 20 seconds and 500 MiB per attempt.

6. Host memory a driver refuses

Device::new_buffer_with_bytes_no_copy, new_heap_with_bytes_no_copy and the rebind_bytes_no_copy calls import the caller's pages by their pointer (VK_EXT_external_memory_host). Some drivers refuse the pointer of shared memory: RADV (AMD on Linux) imports a pointer through amdgpu's userptr, which takes anonymous pages only, so it refuses MAP_SHARED mappings of a memfd, a shared memory object or any file (QEMU's memory-backend-memfd,share=on guest RAM among them) with Unsupported, HostMemory. NVIDIA and lavapipe import the same memory.

A consumer whose memory is such a mapping passes HostMemory::with_dma_buf(pointer, source) instead of HostMemory::new(pointer). The runtime still imports the pointer first, exactly as without a source, and calls the source only where the device refuses it: for dma-bufs of the pages the range touches, and again once for each texture's image over its own pages in them. The rustdoc of HostMemory::with_dma_buf, DmaBufSource and DmaBufRequest is the contract: when the source is called, the chunks it answers, and what is refused. In short, answer each DmaBufRequest with dma-bufs of exactly the pages asked for, in order, split only at multiples of its granule. Where the granule is less than the length (64 KiB on RADV of Mesa 26.2.4, 4 KiB on 26.0.8), several chunks are bound to one sparse buffer and must total the length rounded up to the granule: pad the last with a scratch page of your own, repeated. A texture's request takes one chunk, of the same file pieces the buffer's chunks hold there.

On Linux, udmabuf makes such a dma-buf of the file pieces behind the pages: open /dev/udmabuf (the process needs read and write access to it) and issue UDMABUF_CREATE_LIST with one item per run of contiguous file pages; the memfd must be sealed against shrinking (F_SEAL_SHRINK, as QEMU seals it) and not against writing. The consumer knows the pieces behind every byte; the runtime runs no udmabuf code. Each udmabuf takes at most list_limit items and size_limit_mb MiB (the module's parameters under /sys/module/udmabuf/parameters, 1024 and 64 by default). Keep each chunk within the host's limits as they are: read them, never assume them raised. Scattered memory needs many items: a macOS desktop guest of 14 GiB was measured importing up to 63.3 MiB in one object, in up to 16,201 separate 4 KiB runs, with 19 to 29 of its imports past 1024 runs; at a 64 KiB granule such an object takes 16 chunks.

A texture over such memory is an image over a dma-buf of its own pages where the device also lists 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), 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 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 (runtime_lane::surface_texture_costs::pitch_classes, nine formats, four usages, rows padded by each power of two from 16 to 4096 bytes):

  • ANV (Mesa 26.2.4) packs its own rows tight and takes every pitch asked.
  • NVIDIA (615.71.09) aligns its own rows to 128 bytes and takes any larger pitch for a texture it samples or writes, in BGRA8Unorm, RGBA8Unorm, RGB10A2Unorm, RGBA16Float, R8Unorm and RG8Unorm; not for a render target, and not in R16Float, R32Float or RGBA32Float, whose DRM_FORMAT_MOD_LINEAR tiling it gives no sampling or transfers.
  • RADV (Mesa 26.2.4) aligns its own rows to 256 bytes, refuses a pitch that is not a multiple of 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 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

spirv-val checks structural validity, not agreement with Metal:

spirv-val --target-env vulkan1.2 output.spv

device.profile().spirv_validation() names the environments and relaxations a module compiled for the device is valid under; the command line runs each.

For a claim about behavior, follow VALIDATION.md: a synthetic regression test, the golden output hashes where output must not move, and an authored case run on Metal and Vulkan where it should.