Commit Graph
219 Commits
Author SHA1 Message Date
Anees Iqbal d77bd86377 Compute half + - * and fma in 16 bits under the 16-bit float controls
On a device whose half roundings take the 16-bit float controls (RoundingModeRTE, DenormPreserve
and SignedZeroInfNanPreserve for 16 bits with shaderFloat16: ANV and RADV among the committed
profiles), a half + - * is now the device's 16-bit OpFAdd, OpFSub or Fma(a, b, -0.0), kept apart,
between exact conversions (ops::f16_binary, the form the measured MoltenVK fact already takes).
Where shaderFmaFloat16 is enabled too, a half fused multiply-add is OpFmaKHR on 16 bits (new
fma::Route::F16Khr), under either policy. Elsewhere the f32 operation and its rounding pair, the
round-to-odd routine and native device maths' Fma stay as they were.

Exact: Vulkan's precision table lists OpFAdd, OpFSub and OpFMul for half precision, and OpFmaKHR,
as correctly rounded, to nearest even under RoundingModeRTE, with denormals kept under
DenormPreserve and zero signs under SignedZeroInfNanPreserve, the modes the entry declares where it
computes in 16 bits (narrow::computes_in_16_bits). That is Metal's half arithmetic and Metal's
half fma, which the round-to-odd routine emulated. A NaN's bits are the device's, as the
controlled rounding's already are; Metal's NaN is selected around the instruction where the
profile asks for it. The half fma under native device maths no longer records NativeFma there.

Why: the device's compiler spent most of a large half fragment function's making on the f32 ->
f16 -> f32 rounding pairs, most of which follow a + - * or a fused multiply-add. On ANV a
consumer's largest fragment library made in about 4 s, and about 2.2 s without its rounding pairs.

New: VkFeature::ShaderFmaFloat16 (the Khronos table, enables, the ash and runtime feature chains,
derivation, the codec), OpFmaKHR's feature by its operands' width, the builder's OpFmaKHR on 16-bit
floats, and the owned fixture engine/hfb_filter_bank (a 32-case switch of runtime-sampler tap
loops and half arithmetic chains) with its engine inventory rows. The validation engine's enable
list enables shaderFmaFloat16 from VkPhysicalDeviceShaderFmaFeaturesKHR beside shaderFmaFloat32,
and the opened-chains pin records it for the profiles that list it. Docs: docs/FAST-PATHS.md's half
rounding row, and the NativeFma notice in artifact.rs and docs/API.md.

Verified, as the commits state:
- On the UHD 770 (ANV, Mesa 26.2.4) the fixture's fragment library made in 1.74-1.89 s against
  4.64-5.26 s before (3 alternating rounds, no driver caches), SIMD8 instructions 25,902 ->
  18,736, translation 0.17 s release; driver_deviations::half_arithmetic_answers_as_metal passes
  there.
- On the UHD 770 in the release m2v_gpu build, the groups that failed before the engine enabled
  the feature pass: candidate engine runs, platform enables and device, engine_render,
  engine_compute, engine_textures, acceptance_pipelines, the runtime lanes kernel_textures,
  sparse_textures, renders, argument_buffers and runtime_probe, and the half and fma driver
  deviations.
- Debug translator tests: engine_arith, lower::arith, the fma, derivation, device, ash_interop,
  cache and fast_paths tests, and the engine inventory's llvm_as parts; engine_native_half
  (counting the 16-bit operations and their exact conversions) and engine_spirv_cross_forms (no
  NativeFma where the half fma route is F16Khr), with fused and engine_arith, 213 passed.
- clippy of metal2vulkan.
2026-10-19 00:16:00 +03:00
Anees Iqbal b6addb96c0 Read storage without a format by its format's bit under VK_KHR_format_feature_flags2 or Vulkan 1.3
Vulkan enables the SPIR-V capabilities StorageImageReadWithoutFormat and
StorageImageWriteWithoutFormat by shaderStorageImage{Read,Write}WithoutFormat, by Vulkan 1.3, or
by VK_KHR_format_feature_flags2; under the last two each format's own
STORAGE_{READ,WRITE}_WITHOUT_FORMAT bit (VkFormatProperties3) says whether it may be accessed so.
Intel's ANV and SwiftShader lack shaderStorageImageReadWithoutFormat, and the translator took the
feature as the only route, so a storage read the shader cannot declare with a SPIR-V format was
refused there even where the format's own bit grants it. Metal accepts such reads: an A8Unorm
storage texture read, and a fetch of an A8Unorm color attachment through the pixel interlock.

Now:
- VkExtension::KhrFormatFeatureFlags2 joins the Khronos name table, the cache codec, the
  runtime's and the validation platform's extension tables and the enable facts (core in 1.3, no
  feature member). The runtime enables it below Vulkan 1.3 where the device lists it.
- A module's Requirements list the two capabilities without their feature
  (device::requirements::WITHOUT_FORMAT_CAPABILITIES), and DeviceProfile::check and
  DeviceDescription::required_enables resolve them on the device: the feature where the device has
  it, else nothing at Vulkan 1.3, else the extension. A device with none is refused naming the
  feature, as before.
- metal::format: a typed declaration stays preferred wherever SPIR-V names the format; the
  declarations SPIR-V cannot name (the storage choice, the fetch's storage form, the depth and
  stencil fallbacks, the slot's formatless refusal, the ulong form) go by the features or by the
  format's own bit.
- A heap stays on the features: a per-pipeline check of each member's bit is not built, and
  docs/FAST-PATHS.md's known gap says what the formats' bits leave refused on ANV.

Effect on the committed profiles, read at the runtime's Vulkan 1.2 with and without the
extension over every PixelFormat: on intel-irisxe-rplp-anv and intel-uhd770-rpls-anv an A8Unorm
storage texture read and read-write, and an A8Unorm color attachment fetch read and written,
single and multisampled, now compile (an A8_UNORM view declared without a format), and an A8Unorm
texture buffer takes the A8_UNORM view in place of R8_UNORM holding alpha in red (both Metal's
texels). On intel-irisxe-anv and swiftshader nothing lifts. Every other changed cell on the four
profiles (1280) keeps its refusal and now names the format's missing bit in place of the feature.
The engine fixture tables do not change on any profile. The validation platform's Vulkan 1.2
device contexts enable the extension where a profile lists it, and the opened-chains pin records
it (32 contexts on 16 profiles, one more extension each).

Verified, as the commits state: the unit tests device::tests::enables (the feature, the version or
the extension), metal::format (access by the format's bits with the extension),
lower::fragment::fetch (an A8Unorm attachment fetched by its own bit, the fetch tests at Vulkan 1.2
with and without the extension), spirv::requirements and spirv::serialize, and the
framebuffer-fetch compile test all pass; public_fixtures_engine parts 1-8 unchanged; the
per-profile census above, run as a temporary test; candidate::platform::enables::tests 21 of 21;
clippy. New lane runtime_lane::alpha_in_red::a8_storage_reads_without_the_feature_go_by_the_format_s_bit
(a device made without shaderStorageImageReadWithoutFormat, as ANV is, reads its own A8_UNORM by
the format's bit under the extension: Metal's (0, 0, 0, 0.6) and 178).
2026-10-19 00:16:00 +03:00
Anees Iqbal 9d2a757be3 Record more passes inline: memoryless DontCare colors, splits across the interlock, wide clears
The consumer's guest recorded only about 3 of its frame's roughly 32 render passes inline; every
other pass recorded its draws into a secondary command buffer that the recorder begins, replays
and ends and the pass's primary executes. On the Iris Xe a split instance costs 61 to 87 us of
encoding CPU in a secondary against 5 to 9 us inline. This packet counts why a pass is not
inline and removes the three reasons the guest's passes hit.

Counted:
- opens_inline returns the check that ruled a pass out (Result<(), NotInline>), its checks in
  the same order, and WorkCounts gains one count per reason: passes_not_inline_encoders,
  _layouts, _actions, _buffer_textures, _attachments, _draws, _memoryless, _storage, _stand_ins
  and _memoryless_writes. NotInline::Actions carries the first action ruled out
  (work_counts::ActionsRefused), counted in passes_not_inline_actions_dont_care_load,
  _unequal_reach, _nan_clear, _resolve and _store, which sum to passes_not_inline_actions.
- WorkCounts::tile_dispatches_recorded counts the tile dispatches render encoders record.

Recorded inline where they were not:
- A memoryless color loaded and stored DontCare (a 2D level and layer of a format that takes
  transfer writes) no longer rules the open out. The inline instance renders the transient image
  in place, clears it to zero (Metal's measured answer for a DontCare memoryless color in a pass
  that draws) and stores it DontCare. No inline instance writes a memoryless color: a first draw
  that writes one keeps the instance in a secondary, and a later one splits the pass before it
  (WorkCounts::inline_memoryless_write_splits). A backing that arrives after the inline instance
  is cleared, never copied into, so no instance reads what an earlier pass left in the queue's
  kept backing.
- An instance after a split also records inline where its shape is the first instance's except
  for the colors its draws leave out of the subpass for the pixel interlock, and the only
  stand-ins arriving with it are memoryless colors' backings loaded Clear. Each such shape takes
  its own render pass and framebuffer (inline_splits::Later), a left-out color's slot holding the
  device's placeholder, and arriving backings are cleared to the first instance's clear before
  the instance they arrive with. The copies before a kept instance are planned only where a
  shadowed texture was used, and kept draws reuse room the device keeps (at most 8 rooms of 64
  draws), so the move adds no allocation a frame.
- A pass whose Clear loads reach past the render area (Metal clears whole 32-pixel tiles)
  records its first instance inline over that reach, where every stored color is cleared to the
  same reach, none is loaded where the reach passes the render area, and each memoryless color is
  at least as large; its load operation's clear reaches what Metal's does, its draws' scissors
  stay inside the render area, and the pass plans no reach clears. Otherwise it records as
  before, counted as ActionsRefused::UnequalReach.

New owned fixture mli_memoryless_step (fragments mli_tag_step and mli_count_seed) with its engine
inventory rows. clear_reach.rs's docs say the inline instance's own clear past the render area
is unmeasured on MoltenVK.

Verified, as the commits state:
- Lane tests: inline_reasons (each reason and each action, a memoryless color beside a stored
  one, a later write that splits once, colors cleared past half their side, an unequal reach);
  framebuffer_fetch (memoryless tags loaded DontCare over two passes in turn: each pass records
  inline and splits once into an instance that also records inline, and the second pass would
  read 13c where it reads 11c if a backing kept the first pass's tag); clear_reach (colors whose
  clears reach alike record inline over their reach, each texture holding Metal's answer);
  tile_dispatches.
- On lavapipe the touched lanes pass (140 passed in the last run, with frame_costs' allocation
  and command-buffer checks), and the runtime's unit tests pass (1058). On the RX 7900 XTX (RADV)
  the touched lanes pass (134) with no VUID message; on the UHD 770 (ANV) they pass except four
  tests that need Metal observations the host's copy lacked, which pass on RADV.
- Composite bench (40 passes, 120 draws a frame): split instances recorded inline 0 to 38,
  secondaries executed 40-42 to 2-4, allocations 3774 to 3468 a frame on ANV and 3396 to 3244 on
  RADV. Part-area bench on RADV: passes recorded inline 20 to 95 a frame, secondary executions
  80 to 5, encoding CPU 1.91 to 1.69 ms, through completion 2.29 to 1.97 ms.
- The engine fixture inventory (LLVM 21); clippy in the plain, m2v_gpu and m2v_cpu_icd cfgs and
  Rustdoc.
2026-10-19 00:16:00 +03:00
Anees Iqbal e47fa7a846 Bench the encoding thread on the guest's frame shapes, over host pages and in composite passes
The validation lane frame_costs gains three ignored release runs, run by name, so the runtime's
encoding-thread cost can be compared on the shapes the consumer's guest submits:

- frame_costs_guest_passes times the plain device on the guest's frame shapes, with passes
  loading their layer in the guest's mix (15 clear, 4 load, 1 don't-care in 20): one image's 100
  one-draw passes, as 100 command buffers of one pass and as one command buffer of 100 passes,
  and another image's frame of 41 command buffers (9 with no pass, 32 with one pass, 277 draws,
  most of them in five big passes).
- frame_costs_host_pages times the window server's frame and that image's frame with the index
  and rectangle buffers as no-copy buffers over one host mapping, plus a third no-copy buffer over
  the whole mapping, so each draw's uses take the uses of the keys their bytes share, as the
  guest's buffers over its RAM do.
- frame_costs_guest_composite draws 40 command buffers of one pass shaped like the guest's
  composite passes: a BGRA8Unorm layer loaded and stored, a memoryless RGBA16Float scratch
  loaded and stored DontCare, one plain blended draw and two draws that fetch the layer, so a
  device that fetches through the pixel interlock splits each pass at the first fetch, as the
  guest's do. A second run swaps the scratch for a private texture cleared and stored. A new
  FRAME-COST line counts, a frame, the passes whose first instance recorded inline, those that
  did not by every reason, the split instances recorded inline, the instances ended unrun, and
  the replays' render pass begins and secondary executions.

The frame loop now walks a layout (command buffers, then passes, then draws), and the per-pass,
per-command-buffer and per-draw figures divide by that layout's counts; the window server's run
keeps its draws and its numbers. Validation only: no runtime change.

Verified, as the commits state: clippy of the validation crate, plain, m2v_gpu and m2v_cpu_icd.
On the RX 7900 XTX (RADV, release): the plain guest shapes 2.86 ms a frame and 38.0k user-space
instructions a draw, over host pages 3.83 ms and 41.9k, the other image over host pages 1.89 ms
and 40.8k; the composite with the memoryless scratch 0 passes inline, 80 render pass begins and
80 secondary executions, encoding thread 2.46 ms a frame, and with the scratch kept 38 inline,
80 begins, 42 executions, 2.14 ms (two rounds that agreed). On lavapipe the composite run passes
with 0 and 38 passes inline.
2026-10-19 00:16:00 +03:00
Anees Iqbal e357ba7f4f Record nothing for a render pass that changes no texel, as Metal keeps every texel of it
Once a frame the consumer's guest encodes two 1080p passes over its framebuffer's host pages that
draw nothing: one loaded DontCare and stored Store with no command, and one loaded Load and
stored Store with state calls only. Metal keeps every texel in such a pass: the M3 Max changed 0
of 8294400 bytes of a shared and an IOSurface 1920x1080 BGRA8Unorm texture under DontCare/Store,
Load/Store, Load/DontCare and DontCare/DontCare, in 1 and 3 passes. The runtime already gave
Metal's answer, but still recorded a render pass instance that loaded and stored every attachment
over the render area.

end_pass now returns before any recording where render/untouched.rs's changes_nothing holds:
- no draw call (an execution of render commands and a tile dispatch count as one) and no
  visibility result buffer;
- one render pass instance that nothing recorded into;
- every attachment but the hidden depth loaded Load or DontCare and stored Store or DontCare,
  with no resolve;
- no depth/stencil state with depth writes set in the pass (Metal stores such a depth's words
  without their signs even with no draw, which the runtime strips after the pass), and no depth
  whose Clear held a NaN (whose word the runtime writes before the pass).
Such a pass records no render pass instance, no shadow or stand-in copy and no tracker use of its
attachments; a secondary begun as it opened ends unrun and its pool goes back to the device's
spares. The encoder still holds its attachments until the command buffer completes, and its core
ends as before (fences, residency, uses), so ordering against later work stands. A Clear load, a
resolve, separate depth and stencil textures loaded DontCare, and the first group of a pass of
several color groups still record as before.

New WorkCounts field untouched_passes_skipped. render/untouched.rs, clear_reach.rs and the
counter's docs state the rule.

Why: on the Iris Xe such a pass cost 25 us of GPU time loaded Load/Store, and 42 us loaded
DontCare or over a padded surface (1920x1080 BGRA8, the GPU clock held at 300 MHz); skipped, the
Load/Store passes cost 12.1 us, the encoder's own empty command buffer.

Verified, as the commits state:
- runtime_lane::clear_reach::a_pass_that_changes_no_texel_records_nothing: DontCare/Store,
  Load/Store and Load/DontCare with no draw call, and a Load color beside a DontCare/Store depth
  that keeps 0.75, are skipped with their texels kept; a Clear load, a draw call of no vertex and
  a visibility result buffer are not. Without the change the counter stays 0 and the first four
  cases fail. All 7 clear_reach tests passed on the RTX 5080.
- The two depth conditions come from a first form's failures on the RX 7900 XTX
  (depth_denormals' NaN-clear and signless-store tests read the bytes the skip left). Five
  kept_buffer_bytes cases that failed there now assert the skip exactly for their no-draw passes
  and check their bytes as before.
- clippy plain, m2v_gpu and m2v_cpu_icd.
2026-10-19 00:16:00 +03:00
Anees Iqbal aa2be705d5 Let a new texture register while a batch is replayed or submitted, waiting for no submission
A batch's submission takes the new resources' first work (FirstMoves::take), which holds the
device's place in the submissions' order until its vkQueueSubmit returns, and every registration
of a new resource (a texture's, buffer's, fill's, bytes' or texels' first move, as a Shared or
Private texture is made) waited for that order, so that no texture's heap set elements were
written between a batch's take and its submission. Two things made a texture's making wait long
inside that span: the batch's deferred command buffers were replayed after the take, and
MoltenVK encodes a command buffer's Metal commands inside vkQueueSubmit on the calling thread (5
to 32 ms for 4096 to 65536 fills on the M3 Max). In the consumer's guest on the Iris Xe with
deferred recording, the guest's task thread blocked 1311 ms over 110 such waits (about 17 ms a
frame). Metal's makes wait for no submission.

Now:
- A batch's deferred command buffers replay before the take (crate::recorder::resolve on each,
  waiting for a replay in progress), with no lock a registration takes; their handles stay as
  encoded until the vkQueueSubmit, which finds them replayed. Only the barrier command buffers
  the submission records after the take replay inside the order. What replays, and the commands,
  are unchanged.
- On a device whose heap sets take writes while a command buffer that binds them is pending
  (descriptorBindingUpdateUnusedWhilePending: every committed profile but the Vulkan 1.2
  floor's), a batch holds the texture slots' writes over that span instead
  (FirstMoves::take_holding, heap_sets::hold): elements asked meanwhile are written in order as
  the hold ends, before the batch's place in the order goes, and a registration takes no place.
  A device without the feature keeps its registrations ordered (FirstMoves::ordered).
- New WorkCounts fields: heap_slot_writes_deferred (the writes a hold deferred) and
  registrations_waited (registrations that found a submission holding the order and waited for
  it, counted only where registrations are ordered).
- Docs: texture/first_move.rs's order, heap_sets.rs, and the lane's module docs.

Verified, as the commits state:
- runtime_lane::first_use::a_new_texture_waits_for_no_submission_s_replay times a Private
  texture's making (a Shared one moves on the host where VK_EXT_host_image_copy exists and never
  waited) and now asserts the making added no wait for a place, printing its time. On the 780M
  and RX 7900 XTX (RADV) it took 0.04 to 0.19 ms while the command buffer was scheduled 58 to 64
  ms after its commit; with the replay moved back after the take it took 56 to 60 ms.
- On the M3 Max through MoltenVK (60 makings after commits of 4096 to 65536 fills): before the
  slot-write hold 20 makings waited for the order, up to 13.0 ms; with it none waited, the
  slowest taking 0.158 ms.
- The FirstMoves unit tests, among them a registration that waits for no submission where batches
  hold the slots and one that waits where registrations are ordered, and the count's tests:
  first_move, heap_sets and exit_guard tests, 62 passed.
- runtime_lane::first_use's 11 tests on the UHD 770 and lavapipe. Beside 128 busy threads and as
  8 parallel copies, on lavapipe and the UHD 770, every run passed with 0 waits for a place
  (183 makings, the longest 0.55 ms on lavapipe and 0.23 ms on ANV); the earlier time-ratio
  failures were the host's load and the validation layer's lock, not a wait of the runtime's.
- clippy plain, --cfg m2v_gpu and --cfg m2v_cpu_icd; Rustdoc -D warnings.
2026-10-19 00:16:00 +03:00
Anees Iqbal 1ef457d88b Refuse an unordered framebuffer fetch and drop interlocked draws' barrier where the driver orders them
Three changes to framebuffer fetch and the pixel interlock.

1. An unordered framebuffer fetch is refused; FramebufferFetchPolicy is deleted. Metal orders a
   fragment function's read of its color attachment after every earlier fragment of the pixel,
   within a draw and across draws. Where a device offers neither ordered form
   (rasterization-order attachment access, or the pixel interlock's storage form where the
   pipeline's state lets it be exact), the opt-in FramebufferFetchPolicy::AcceptUnordered
   compiled the read as an unordered input attachment with a precision note. An unordered read
   can return the attachment before an earlier overlapping fragment's write: a different value
   in memory, not a rounding, which the owner's rule allows neither as a default nor as a
   switch. No exact form exists on such a device, so the fetch is refused there, as the default
   already did. The runtime never ran the unordered form, so no runtime behaviour changes.
   - Removed: DevicePolicy::framebuffer_fetch, the enum FramebufferFetchPolicy and its
     re-export (and its api_surface row), ProfileFields::framebuffer_fetch,
     PrecisionNote::UnorderedFramebufferFetch, and the runtime's note kind of that name, whose
     code metal2vulkan-degrade-unordered-framebuffer-fetch is retired; the runtime's
     framebuffer_fetch::ordered check; validation's --accept-unordered-fetch on corpus-vulkan,
     corpus-moltenvk and corpus-pipeline, and the device worker's framebuffer_fetch field.
   - lower::fragment::color refuses a read no ordered form serves (Unsupported{FramebufferFetch},
     naming both forms); lower::fragment::fetch refuses a blocked storage form with its blocker.
   - The profile's fields change, so every profile fingerprint does.

2. No barrier between interlocked draws' colors on a driver measured to order them. Between two
   draws of a render pass instance where the later one reaches a color in the fetch's
   interlocked storage form (or an extended-range color's half shadow) that the earlier one
   wrote, the runtime recorded a fragment-to-fragment storage barrier on every device. Vulkan
   orders such draws by the interlock alone (ordered interlock modes follow rasterization
   order, which follows primitive order through a subpass, and the interlocked storage image is
   decorated Coherent). A new answer fact, DriverFact::InterlockOrdersDraws, measured on ANV on
   the Iris Xe of Raptor Lake-P, drops that barrier there for these colors alone. The fragment
   imageblock's storage and the depth stand-in keep their barrier everywhere, as does every
   unmeasured driver. RADV on the Radeon 780M still needs the barrier: without it one blend
   table case leaves 19 of 495 band results wrong over 5 runs. New lanes:
   runtime_lane::interlocked_draw_order (every device, with its owned fixture ido_draw_order) and
   the ignored release bench runtime_lane::tile_path_costs (a window server's composite on
   Metal's tile path, fixture tgp_composite), with their engine inventory rows. A FAST-PATHS
   bullet records the barrier and the fact.

3. A left-out interlock color's framebuffer slot holds a placeholder image. A color attachment
   the draws read and write as a storage image in the interlock is left out of their subpass,
   but its framebuffer slot held a view of the very image the draws write, which the validation
   layer reads as VUID-vkCmdDraw-None-06537 for a draw recorded inline. The slot now holds a view
   of a placeholder that nothing reads or writes (DONT_CARE load and store, GENERAL layouts): the
   device keeps one for each format and sample count, plus one for each further color of that
   shape in the same framebuffer, grown to cover a larger framebuffer and freed once no
   framebuffer holds it; none is made per frame. A color whose draws use sample planes, and the
   planes' anchor, keep their own image's view. New WorkCounts fields
   storage_placeholders_made and storage_placeholder_attachments.

Verified, as the commits state:
- The translator's fetch tests (pipeline::compile ordering, engine_fragment, engine_moved_writers,
  device profile fingerprints and serde, fast_paths) keep the refusals; the raster-order-group
  read on a device with neither ordered form expects the fetch's own refusal naming both forms.
  Validation checks every public fetch case is refused on lunarg-desktop-baseline-2023 and
  vk12-floor, and that the command-line flag is gone.
- Iris Xe (ANV) with the fact in place: interlocked_draw_order 3 runs with every texel right,
  extended_range_blend_table 17 passed (0 of 495 bands wrong), framebuffer_fetch 49 passed. A
  1080p pass of 27 interlocked draws took about 1.08 million GPU cycles with the fact against
  1.46 million with the barrier forced (about 9 to 20 us a draw).
- The placeholder lane test (two RGBA32Uint colors over four passes and sizes): placeholders and
  slots (2, 2), (2, 4), (4, 6), (4, 8) through the interlock on the RX 7900 XTX (RADV) and the
  UHD 770 (ANV), none through input attachments, no validation message. On lavapipe 122 lane
  tests and 47 runtime render unit tests passed; on the RX 7900 XTX 94 lane tests passed.
- The engine inventory and llvm_as parts pass for the new fixtures; clippy in every
  configuration and Rustdoc -D warnings.
2026-10-19 00:16:00 +03:00
Anees Iqbal 6f3730abf7 Keep a queue's memoryless color backings across its passes and command buffers, one per shape
A pass that renders a memoryless color attachment into an image of its own (a framebuffer fetch
through the pixel interlock reads it, or the pass splits) made a fresh backing image for each
pass, held by its command buffer and freed when that completed. On a device without lazily
allocated memory (ANV), a 1920x1080 RGBA16Float attachment fetched by about ten passes a frame
made and freed a 16.8 MB image each pass, and the runtime's memory log on an Iris Xe showed a 64
MiB image block made and freed up to three times a second, each a fresh allocation the kernel
zeroes.

Now each command queue keeps those backings (attachment_stand_in::pooled_backing), keyed by the
attachment's pixel format, render format, samples, layers and extent. A pass takes a kept one
that backs no other attachment of the pass, else makes one and keeps it. The pool keeps at most
32 backings and at most 256 MiB beyond the one just made, the one taken least recently going
first, and goes with the queue; each command buffer still holds the backings it rendered into
until it completes. The count bound covers a compositor's frames on the consumer's macOS guest,
which render 11 to 14 extents of one memoryless RGBA16Float attachment a frame (about 40 MB
together): a bound of 8 evicted each backing before its next take. A memoryless depth or stencil
backing is still the pass's own.

Exact: Metal refuses a Load and a Store of a memoryless attachment, and a pass gives every texel a
draw can read a value before its draws (its Clear, or the zero its DontCare load clears to), so
no pass reads what another left in a backing. The passes of one queue that take a backing are
ordered by their uses of it.

New WorkCounts field pooled_backings_made. The memoryless-backed notice's cost text and its
docs/API.md catalogue entry say a color's backing is kept by its command queue.

Verified, as the commits state: clippy -D warnings for the runtime and validation crates, plain,
--cfg m2v_gpu and --cfg m2v_cpu_icd. The lane cases
framebuffer_fetch::a_queue_keeps_one_memoryless_backing_for_its_passes (three command buffers of
two passes over fresh memoryless attachments, the second loaded DontCare and read as zero: one
backing where the device announces memoryless-backed, none elsewhere) and
a_queue_keeps_a_memoryless_backing_for_each_shape_it_renders (12 sizes twice in turn, every texel
checked: 12 backings, where a bound of 8 makes 24) were added for the device batches.
2026-10-19 00:16:00 +03:00
Anees Iqbal e35bf78bd5 Shadow every padded texture over a buffer and every texture over host pages, keeping CPU writes
A texture over a buffer could be an image bound to the buffer's bytes: a padded texture that only
read (PaddedReadsPolicy::Alias, the default), and any 2D texture over a no-copy buffer's host
pages (a linear image, a DRM_FORMAT_MOD_LINEAR image at Metal's row pitch, or on MoltenVK a Metal
texture over the import's MTLBuffer). An image bound to imported memory starts UNDEFINED, and a
layout transition "may perform read and write accesses on all memory bound to the image
subresource range", so such an image kept Metal's bytes across its first move only through a
host keep (read the bytes, submit the move alone, wait, write back what changed), which undid a
CPU write made inside that window. Metal keeps every CPU write to bytes a command buffer does not
write: on the M3 Max, a kernel reading half a padded no-copy texture while the CPU rewrote the
bytes between its rows and its other rows kept every CPU byte in 10 of 10 rounds. Changing bytes
in memory is not a precision note, so under the owner's rules it may be neither a default nor a
switch; exact is the default, and cost chooses only among exact forms.

Now a padded texture over a buffer, and every 2D texture (or array) over a no-copy buffer's host
pages, imported by pointer or as dma-bufs, is a shadow on every device, whatever its usage: an
optimal image of the runtime's memory, copied in from the bytes before a use and merged back
after a write. Texture::vk_image answers None for such a texture.

Removed:
- DevicePolicy::padded_reads and the enum PaddedReadsPolicy (Alias, Shadow); its FAST-PATHS row,
  its tests::fast_paths choice and its api_surface row.
- The images over host pages: the linear image for host allocations, the DRM_FORMAT_MOD_LINEAR
  image over host allocations with its refusal memo, the modifier image over a buffer texture's
  own dma-buf, the Metal texture over the import's MTLBuffer on MoltenVK (VK_EXT_metal_objects is
  no longer enabled for it), and the one image shared by textures of one plan over one import.
- The first move's host keep, and its notice unrestored-first-move-bytes (Degradation
  UnrestoredFirstMoveBytes), retired.
- WorkCounts fields first_move_keeps, first_move_kept_bytes, first_move_restored_bytes,
  pitched_host_images, pitched_host_image_refusals, pitched_host_image_refusals_recalled,
  shared_alias_images and shared_alias_moves_waited.

Kept: the buffer's dma-buf import as the last resort where the pointer is refused, on any device;
the images of heap textures over host pages, including over dma-bufs (a heap resource's contents
are undefined until written, in Metal too); a linear image over a buffer of the runtime's own
memory (PREINITIALIZED), whose first move FAST-PATHS records as a one-line known gap.
ShadowedTexture (shadowed-texture) now also covers read-only padded textures.

Also: a staged shadow's copy back merges rows that lie one after another into one region (a
packed 1080p surface takes one region, not 1080), and two new counters size what a shadow kept
across a command buffer's passes could save: WorkCounts::shadow_attachment_passes and
shadow_attachment_textures.

Docs: docs/FAST-PATHS.md (the shadow bullet with its costs, the known gaps), docs/API.md
(section 1's texture paragraph, the shadowed-texture and dont-care-stand-in entries, the retired
code), docs/HOWTO.md section 6, the runtime README, linear_attachment.rs's module doc.

Cost, as measured: on the Iris Xe a frame sampling four BGRA8Unorm tiles over no-copy pages took
3.2-5.3 ms as shadows against 3.0-6.1 ms as images (textures made once) and 3.4-7.1 against
4.6-8.6 ms (made each frame). On the UHD 770 (ANV, release, alternated), one Load/Store pass into
the guest's 1080p surface took 1.89-1.97 ms as a shadow against 2.56-3.09 ms as the linear alias,
whose draws ran slowly in host memory; 12 passes 20.9-21.1 ms against 27.4-27.8 ms, at about 40 us
more CPU a pass.

Verified, as the commits state:
- runtime_lane::first_use_writes (new: another thread writes bytes of a texture over host pages
  that its first use does not read, from 2 ms before to 2 ms after the commit; every write stays)
  passes on the RTX 3090, the Radeon 780M and the UHD 770.
- runtime_lane::pitched_surfaces asserts a shadow for every surface (counted, vk_image None),
  including the CPU write beside a padded texture during its first use and the new counters;
  no_copy_textures asserts a shadow and no modifier queries; the keep, pitch-refusal and
  shared-image tests go with what they tested.
- The lanes restated for the shadows pass whole: dma_buf_imports 13, resource_ids 38,
  rotated_textures 7 and linear_attachments 20 on the RX 7900 XTX and the 780M (RADV), the UHD
  770 (ANV, with row_copies 2) and the RTX 3090.
- linear_attachments renders over a Shared buffer of the runtime's memory, so the linear
  attachment paths stay covered, each test asserting the way its passes took; 21 pass on the RTX
  3090, the 780M, the RX 7900 XTX and the UHD 770.
- Runtime and validation nextest without a device, 2306 passed; the translator's fast_paths,
  api_surface, published_crates, refusal and driver_facts tests, 34 passed; clippy in every
  configuration and Rustdoc -D warnings.
2026-10-19 00:16:00 +03:00
Anees Iqbal 1df750bbd4 Resolve multisampled color by the device's average by default, Metal's rule on ResolvePolicy::Exact
A pass that resolves a color attachment whose format has Metal's resolve rule at its sample count
drew the runtime's exact resolve after the pass on every device whose AVERAGE is not measured to
be Metal's (everything but MoltenVK): one more render pass instance per resolved attachment,
between full barriers, reading the stored samples as an input attachment. That form is exact
and costly in GPU time. By the owner's rule (fast by default, exact on request, both kept), the
device's resolve becomes the default, announced, and the exact resolve a switch.

- DevicePolicy gains resolve: ResolvePolicy { Device (default), Exact }, a runtime choice alone
  (no emitted code changes, no profile carries it). exact_answers() selects Exact.
- Under Device the attachment resolves in its pass by Vulkan's AVERAGE, announced as
  device-rounded-resolve (precision), whose reason names ResolvePolicy::Exact: no extra pass, and
  a render target needs no input attachment usage for the resolve. Under Exact everything is as
  before.
- Unchanged under both: a driver with DriverFact::ColorResolveAverageIsMetals (MoltenVK on
  Apple's GPUs) resolves in the pass with no notice, and an attachment a fetching pass's sample
  planes hold as it ends resolves from them by Metal's rule.
- device-rounded-resolve's docs and cost state the measured bound: one code for a unorm, snorm or
  packed 16-bit unorm channel, two for an sRGB channel; a float channel's last bits are counted,
  not bounded.
- Docs: a new docs/FAST-PATHS.md row for the switch; docs/API.md's policy bullet and the
  device-rounded-resolve and shader-resolve catalogue entries; color_resolve.rs, policy.rs and
  driver_facts.rs state both values. The api_surface table lists ResolvePolicy.

Why: the exact form's extra pass costs GPU time on every device but MoltenVK (a resolved pass's
command buffer 73-77 us against 51 us on the Iris Xe, 63-75 us against 45-48 us on the 780M), and
no driver measured matches Metal's rule, so none gains ColorResolveAverageIsMetals.

Measured, as the commit states (release builds, 1920x1080 frames of 97 command buffers, every
fourth pass resolving an RGBA8Unorm x4 attachment, the exact form against the device's,
alternated): GPU busy a frame on the Iris Xe (ANV) 2.52 and 2.41 ms -> 1.92 ms (the guest's
shape 3.04, 2.77 -> 2.44, 2.43 ms); on the Radeon 780M (RADV) 2.33 to 2.78 -> 2.00 to 2.13 ms; on
the RX 7900 XTX 1.38 -> 1.36 ms.

The device's average against Metal's rule: on RADV (780M and RX 7900 XTX), ANV (Iris Xe),
lavapipe and NVIDIA (RTX 5080 Laptop), unorm and snorm channels land one code below Metal's at a
tie (16-bit channels exact on NVIDIA), sRGB within one code both ways (up to two at 4 samples on
NVIDIA), packed formats within one, float channels differ in value.

Verified, as the commit states:
- The new lane runtime_lane::resolve_rounding::the_device_resolve_rounds_as_announced (default
  policy) passes on lavapipe, the RTX 5080, the 780M, the RX 7900 XTX and the Iris Xe: every
  closed format at 2 and 4 samples resolved by the device, device-rounded-resolve exactly where
  the fact is absent, and every difference against Metal's rule within the notice's bound.
- The exact form keeps its lanes: the validated options take exact_answers(), so
  resolve_rounding's other tests, degrade_notices, nan_resolves and framebuffer_fetch run under
  ResolvePolicy::Exact as before.
- tests::fast_paths (the switch, and that the choice keys no profile), the driver_facts tests,
  api_surface, the runtime's degradation and driver_defects tests; fmt, clippy in the three
  configurations, rustdoc.
2026-10-19 00:16:00 +03:00
Anees Iqbal bb4f53d209 Read a surface's own pixels through a snapshot at any area, where its image takes feedback loop usage
A draw that reads the texture its pass renders, at its own pixels after a barrier, takes a
snapshot drawn in its subpass, or splits the pass instance and reads a copy; both are exact. The
snapshot was open only to a texture of its own image, so a texture over a buffer's bytes always
split, and each split copies the bytes into the shadow before every instance after a barrier.
The consumer's guest renders its 1080p framebuffer, an IOSurface over host pages, this way.

Now:
- Device::storage_over_buffer tries the linear image that aliases a buffer's bytes with
  ATTACHMENT_FEEDBACK_LOOP_EXT usage first (it costs a linear image nothing; its memory is the
  buffer's), then makes it without where the driver refuses, and counts each image made with the
  usage in the new WorkCounts::feedback_loop_alias_images.
- Texture::snapshot_color reads such an aliasing image through a snapshot, as an image of its
  own, and a reader of a texture over bytes takes the snapshot at any area. The area rule for a
  texture of its own image is unchanged.
- Where the image lacks the usage (NVIDIA's drivers make it without), the surface's readers
  split, exactly as before.
- A pass with a depth or stencil attachment keeps every attachment reader on the split: the
  binder makes no snapshot variant for it, and a snapshot draw would write depth or stencil before
  the drawing draw. render/snapshot.rs's docs say so, and a lane case holds the behaviour.
- The attachment-read row of docs/FAST-PATHS.md states the crossover and the feedback loop
  condition.

Why: in the guest's frames the split's copies dominated (66 splits, 68.2 own-pixel reads and
16.6M texels of bounded copies a frame), while the readers' fragments touch about 1.5% of the
texels a split copies.

Verified, as the commits state:
- On the Iris Xe (release, the new ignored lane attachment_read_costs::snapshot_crossover, a 1080p
  surface over host pages, snapshot and split forced and alternated): the snapshot's GPU time per
  pass is 0.56x to 1.2x the split's; its worst case is a small scissor covered half or more,
  about 10 us a reader, and it is cheapest for sparse readers in big scissors, where the guest's
  readers sit.
- runtime_lane::snapshot_reads: readers over a surface take the snapshot where the image took
  the usage and the split elsewhere, with Metal's bytes either way. RTX 3090 and RTX 5080
  (aliased, no feedback usage) split and pass; the Iris Xe (aliased, feedback usage) takes the
  snapshot and passes; the other snapshot_reads tests pass on all three.
- The depth/stencil case (Less depth with and without writes, a stencil test that blends each
  pixel once): every reader splits and leaves Metal's texels on the Iris Xe, the RTX 3090 and
  the RTX 5080; all 7 snapshot_reads tests pass on the RTX 5080.
- clippy plain, m2v_gpu and m2v_cpu_icd.
2026-10-19 00:16:00 +03:00
Anees Iqbal 0b8edc87d3 Keep a queue's head and its draws from waiting on pipeline makings, and split each making's time
Metal makes a pipeline state at its creation, so no Metal submission waits for a making. Ours
waited in four places, and this packet removes each wait without changing which pipelines, keys,
memo entries or notices are made:

- A queue's head ranks first. The process's budget of pipeline makings gains a rank,
  Urgency::Head, between a host step's making and a committed command buffer's. Once a batch is
  first in its command queue's line, the scheduler raises the makings its host step records to it
  (CommandBufferShared::hasten_head), so a head's making goes before aged makings, earlier
  committed ones and a program's. The budget still decides only the order of driver calls: no
  turn past the budget, no preemption.
- A caller waiting for another's library lends its turn. Library::made, where another caller is
  making the same pipeline library, gives its thread's budget turn back for the wait
  (budget::without_turn) and takes one again at its rank after, so idle waiters no longer hold
  every turn while one of them compiles.
- Draws take the key's residual form while their own pipeline is made. A state's creation now
  makes its predicted key's residual form (every SpecKey::RangeAtBindOffset at 0), which reads
  the same bytes as the key at every bind offset inside the buffer. A draw whose own key's
  pipeline is not made, while its residual form's is, draws with the residual form at once
  (pipeline/render/residual.rs); its own key's making goes to the pool at Urgency::Ahead and
  later draws take it once made. An unbound constant slot now reads at its residual (pushed 0),
  so a draw that leaves such slots unbound takes the creation's key itself and makes nothing;
  the only cost is that such a read is no longer a constant ANV can push.
- A tile dispatch's pipelines are made on the pool. A render encoder's tile dispatch
  (dispatchThreadsPerTile and its region forms) hands each region's making to the device's pool,
  as a compute dispatch does, hastened to a committed command buffer's rank; its pass records
  later where a making is still in flight (render/pending_tile.rs). A failed making is made
  again by the recording, and where that fails the command buffer fails with
  CommandBufferError::PipelineCreation and failed_pipeline names the dispatch, as for a compute
  dispatch; the call no longer returns the driver's error. A pass whose first command is a tile
  dispatch executes an empty secondary where it met an internal error, and a dispatch after a
  pass's inline instances records in the pass's segment before its later instances.

With METAL2VULKAN_LOG_PIPELINES set (a default-off diagnostic), each render pipeline's creation
log line now splits its time: the digests, each part's library (made by this making, with its
record loaded or missed, or another caller's), and the link. Nothing is timed while the log is
off.

The pool's test hold counts its holders, so one test's drop no longer releases another test's
held makings.

New WorkCounts fields: residual_form_draws, residual_form_makings, pipeline_pool_busy and
tile_pipelines_pooled. Docs: docs/API.md (section 10 and the accepted differences),
FailedPipeline's docs, the METAL2VULKAN_LOG_PIPELINES entry in env_vars.rs. Exact either way, so
no FAST-PATHS row.

Why: on the consumer's cold boots on ANV's Iris Xe, the guest's command buffers were held 1.7 to
7.9 s between commit and submission while a queue's head waited for its pass's lazily made
pipeline behind makings no submission needed first. In one cold boot 413 of 565 draw makings
differed from a made pipeline only in RangeAtBindOffset (17.2 of 20.0 s of draw making), and one
tile dispatch's making blocked the guest's encoding thread for 3.46 s.

Verified, as the commits state:
- Budget tests: the ranks with a head's making, and a head's making ahead of aged and earlier
  committed ones (it was aged, committed, head); a waiter lends its turn (without the change the
  turn stays held). Device test tests::pipeline_wait_order: a queue's first held batch's making
  goes first in the pool; a hold of the pool lives until its own drop (fails with the old bool).
  With the shared hold, tests::dispatch_pending failed 3 of 3 runs on lavapipe and passed 3 of 3
  with the counted one.
- tests::uniform_bind_offsets (4, including draws taking the residual form with the pool held,
  exact pixels, two makings once released) and tests::inline_continues pass on lavapipe, the
  RTX 3090 and the UHD 770 (ANV); the validation lanes draw_work and made_at_creation (8) pass on
  lavapipe. With the residual form off, the new test's command buffer times out. A draw leaving
  constant slots unbound takes the creation's pipeline with no making (device test), and the
  slot-plan test expects the residual on every committed profile.
- tests::tile_pending: a tile dispatch hands one making to the pool and its command buffer
  completes after it with the fixture's exact stores; a released state stops its making and a
  dispatch that took it remakes its own. Both fail when the pipelines are made at the call.
- pipeline::creation_log's test of a making's split (no device).
- Lane and budget tests that counted while the pool still worked (framebuffer_fetch on the 780M,
  draw_work on the M3, the head-ranking test on the 780M) now wait for the pool to settle.
- fmt and clippy, plain, --cfg m2v_gpu and --cfg m2v_cpu_icd.
2026-10-19 00:16:00 +03:00
Anees Iqbal 6746e8a1ff Hold A8Unorm in R8_UNORM with alpha in red where the device has no A8_UNORM
Where the device has no A8_UNORM, an A8Unorm texture is held in R8_UNORM with Metal's alpha in red:
as a render target, through fetch and coverage by alpha, as a texture buffer, as an argument
buffer's storage texture, and multisampled, where fetch reads sample planes held in A8_UNORM and a
resolve follows Metal's unorm rule. The A8 lanes hold the device's resolve rounding and the sample
planes' typed refusal; the fixtures are listed with their printouts.

Folds in:
- Hold an A8Unorm texture in R8_UNORM with Metal's alpha in red where the device has no A8_UNORM
- Bless the golden tables and the A8-in-red fixture's printout
- List the A8-in-red fixture's rows in the engine expectations
- Fetch and cover by alpha through an A8Unorm attachment held in red, as Metal does
- Hold the A8 lanes to the device's resolve rounding and its sample planes' typed refusal
- Read and write an A8Unorm texture buffer through an R8_UNORM view where the device has no
  A8_UNORM, as Metal does
- Name texel_buffer_alpha_in_red in plain text in FormatEmulation::AlphaInRed's doc
- List the a8r_buffers fixture in the engine expectations and give it its golden printout
- Read and write an argument buffer's A8Unorm storage texture held in red, as Metal does
- Fetch a multisampled A8Unorm attachment through sample planes held in A8_UNORM, and resolve
  A8Unorm by Metal's unorm rule

Verified by each folded change's own checks; the tree this series ends on is the one verified
at the tip on six GPUs, the CPU suites and lint (see the tables commit).
2026-10-19 00:16:00 +03:00
Anees Iqbal 7db879f242 Release idle pointer imports on RADV 26.2.4, and say which RADV host stack loses GPU writes
On the Radeon 780M with RADV (Mesa 26.2.4), idle pointer imports are released where they follow
their address, as on the other measured drivers; docs/HOWTO.md says which RADV host stack loses GPU
writes under memory churn.

Folds in:
- Release idle pointer imports on RADV 26.2.4 on the Radeon 780M, where they follow their address
- Say which RADV host stack loses GPU writes under memory churn

Verified by each folded change's own checks; the tree this series ends on is the one verified
at the tip on six GPUs, the CPU suites and lint (see the tables commit).
2026-10-19 00:16:00 +03:00
Anees Iqbal a97f7c2757 Keep Metal's contract for host imports and shadows: no posted deallocator, no copy back over CPU bytes
Two fast paths that broke Metal's contract are gone: the posted deallocator of a released host
import and the shadow copy back over bytes the CPU may write. A released import is freed in the
call, as Metal frees it, and a shadow merges back only the bytes the GPU changed. The notice codes
of the two retired kinds are retired too, and the runtime holds the list of every notice code ever
issued so a retired code is never reused. The keep-alive lanes wait for the keep-alive that goes
with an import's free.

Folds in:
- Free a released host import on a handler thread by default (later removed)
- Copy a shadow back over bytes the CPU may write by default (later removed)
- Remove the shadow copy back over CPU-written bytes and the posted deallocator, which broke Metal's
  contract
- Wait for a keep-alive that goes with its import's posted free in the keep-alive lanes
- Retire the codes of the two removed notice kinds, and hold every code ever issued

Verified by each folded change's own checks; the tree this series ends on is the one verified
at the tip on six GPUs, the CPU suites and lint (see the tables commit).
2026-10-19 00:16:00 +03:00
Anees Iqbal 7335fae27d Tidy validation tooling: format-scout's YCbCr skips, the reviewed list's wording, linear probe images
Validation tooling only, no product change: format-scout skips Metal render passes into two-plane
YCbCr surfaces; the reviewed cutover list is rewritten without design citations or deleted policy
names; the runtime probe's DRM_FORMAT_MOD_LINEAR images start UNDEFINED.

Folds in:
- Skip format-scout's Metal render passes into two-plane YCbCr surfaces
- Rewrite the reviewed list without design citations or deleted policy names
- Start the runtime probe's DRM_FORMAT_MOD_LINEAR images UNDEFINED

Verified by each folded change's own checks; the tree this series ends on is the one verified
at the tip on six GPUs, the CPU suites and lint (see the tables commit).
2026-10-19 00:16:00 +03:00
Anees Iqbal f8af954378 Emulate Metal's anisotropic filter as one routine per shape, its offset the taps' Offset operand
Metal's anisotropic filter is emulated as one routine per shape, with its calls kept where the
driver keeps them (the RTX 5080), and an anisotropic sample's texel offset reaches the routine as
the taps' Offset operand.

Folds in:
- Emulate Metal's anisotropic filter as one routine per shape, its calls kept on the RTX 5080
- Pass an anisotropic sample's texel offset to its routine as the taps' Offset operand

Verified by each folded change's own checks; the tree this series ends on is the one verified
at the tip on six GPUs, the CPU suites and lint (see the tables commit).
2026-10-19 00:16:00 +03:00
Anees Iqbal 7da60560e0 Measure an at-once exit at the runtime's notice and register the exit hook after every instance
Process exit under load: an at-once exit's measure ends at the runtime's notice rather than at the
kernel's teardown, and the exit hook is registered again after every Vulkan instance the runtime
creates, so an instance made later cannot run its own teardown ahead of the runtime's.

Folds in:
- End an at-once exit's measure at the runtime's notice, not at the kernel's teardown
- Register the exit hook again after every instance the runtime creates

Verified by each folded change's own checks; the tree this series ends on is the one verified
at the tip on six GPUs, the CPU suites and lint (see the tables commit).
2026-10-19 00:16:00 +03:00
Anees Iqbal c9b0d74912 Record Vulkan commands off the encoding thread through deferred command buffers the recorder replays
Encoders log their commands into deferred command buffers, and the device's recorder thread replays
them into Vulkan once the command buffer is committed, so the encoding thread no longer calls the
driver for each command. Every recorded command goes through a slot of its device's; the recorder's
queue and the scheduler's inbox are sized for a frame's commits and grow ahead of them on the
recorder's thread; a commit's end allocates nothing; a render pass instance's secondary that nothing
executes is never replayed. The replays' commands are counted by kind, and the recorder's modules
are listed among those that may keep the device's functions.

Folds in:
- Route every command the runtime records through a slot of its device's
- List recorder/mod.rs among the modules that keep the device's functions
- List recorder/thunks.rs among the modules that keep the device's functions
- Record Vulkan commands off the encoding thread: encoders log into deferred command buffers, the
  device's recorder thread replays them once committed
- Grow the recorder's queue ahead of the commits, on the recorder's thread
- Give the scheduler's inbox and the recorder's queue room for a frame's commits from their making
- Count the commands the recorder's replays call, by kind
- Give a commit's tail log its fold's room when its encoder ends
- Never replay a render pass instance's secondary that nothing will execute
- Give new replays room to end each deferred command buffer as it is made, so a commit's end
  allocates nothing

Verified by each folded change's own checks; the tree this series ends on is the one verified
at the tip on six GPUs, the CPU suites and lint (see the tables commit).
2026-10-19 00:16:00 +03:00
Anees Iqbal 8e4f847155 Wake the scheduler and completion waiters only where a thread sleeps, and wait for event values on the GPU
The scheduler and completion paths wake only the thread a change is for: a condition variable per
waiter, notifications only where a thread sleeps, and a completion wakes the scheduler only when it
lets a held batch go. The scheduler's thread waits for the event values its heads await on the GPU
itself; a completed command buffer's queue slot goes back as its handlers return, before its
release; a handler-less transition to Scheduled runs on the scheduler's thread where its queue's
context is idle. Fewer cross-thread wakes on the commit and completion paths.

Folds in:
- Wake the scheduler at a completion only when it lets a held batch go, and notify a condvar only
  where a thread sleeps
- Let a submitted command buffer's waiters go a few submissions into a scheduler pass
- Notify an event's host waits only where one sleeps, and make the completion-wake lane fail without
  its fix
- Let the scheduler's thread wait for the event values its heads await on the GPU itself, nudged by
  its wakers
- Hold the host-signal check to what each wait path does, with no commit racing the host's signal
- Give a completed command buffer's queue slot back as its completed handlers return, before its
  release
- Wake only the completion waiter a change is for, each on a condition variable of its own
- Size the host-signal test's long command buffer to last 0.3 s of GPU time on every device
- Run a handler-less transition to Scheduled on the scheduler's thread where its queue's context is
  idle
- Time a slow commit's round again where the kernel counts no wait for a CPU

Verified by each folded change's own checks; the tree this series ends on is the one verified
at the tip on six GPUs, the CPU suites and lint (see the tables commit).
2026-10-19 00:16:00 +03:00
Anees Iqbal f29872bd92 Sample extended-range textures as Metal does across mip levels, array layers and 3D
Extended-range textures sample as Metal does at every mip level and array layer and in 3D under no
mip filter or a nearest one. The emulated sample is one routine per shape, its constant texel offset
passed as an argument; a linear sample takes its exact sum from each tap's codes, undecoded, and its
value on the grid by a multiplication by 1/255 with an exact correction. Draws whose variant takes a
two-plane extended-range texture slot are counted.

Folds in:
- Sample extended-range textures' mip levels and array layers as Metal does
- Sample extended-range 3D textures as Metal does under no mip filter or a nearest one
- Emulate an extended-range sample as one routine per shape where the driver keeps calls, its
  constant texel offset the call's argument
- Hand a linear extended-range sample's exact sum each tap's grid steps from its codes, undecoded
- Take a linear extended-range sample's value on its grid by a multiplication by 1/255 and an exact
  correction
- Count draws whose variant takes a two-plane extended-range texture slot

Verified by each folded change's own checks; the tree this series ends on is the one verified
at the tip on six GPUs, the CPU suites and lint (see the tables commit).
2026-10-19 00:16:00 +03:00
Anees Iqbal 3bb4722d9f Release idle pointer imports where they follow their address, keep deallocator timing Metal's across rebinds and detaches, and cut host-import work
No-copy buffers and host imports now cost the kernel and the encoding thread less, and their
deallocators run in the call Metal runs them in, including when a detach races a commit.

What changes:
- Idle pointer imports. A no-copy buffer's own pointer import is releasable, as its dma-buf
  import was: while only blits read it and no pending command buffer holds it, the residency
  thread releases it after its idle window (2 s, doubling at each import again up to 64 s), and the
  next blit imports it again at the same pointer. Only where the new measured fact
  DriverFact::PointerImportsFollowTheirAddress holds (ANV 26.2.4 on the Iris Xe; lavapipe 26.0.8
  to 26.2.4): there a pointer import reads the pages mapped at its address at each submission, so
  an import again reads what the kept one would. A refused re-import fails the blit's call, typed.
- Deallocator timing. A released import hands its keep-alive and deallocators to the objects a
  command buffer still holds, so they run as that memory is freed (or parked and announced, as a
  kept import's). A committed but unsubmitted command buffer holds a blit's import objects weakly,
  so a rebind or detach before its first submission runs the deallocator in its call, as Metal
  does. A detach racing a commit on another thread runs the deallocator in one of the two calls:
  a let-go mark on the pages and the commit's hold count, both sequentially consistent, make each
  side see the other, and a commit that sees the mark replays its own command buffer at once. The
  live list re-reads a buffer's pages where a detach moved them meanwhile. HostDeallocatorDelayed
  is no longer announced for these races.
- Fewer kernel queries. A no-copy buffer asks the kernel about its mappings (PROCMAP_QUERY) only
  where it makes its own import; a rebind onto a live buffer's bytes lies in that buffer's import
  and asks nothing; /proc/self/maps stays open for the queries (reopened in a forked process).
  Three blit paths that read the caller's buffer as a read apart now read it as blits, so their
  imports stay releasable.
- Fewer rewrites and lookups. A rebind or detach rewrites only the heap slots of textures over the
  bytes it moved; host-page alias lookups visit only the length classes that hold ranges and keep
  each range's overlapping ranges; a binding and a descriptor each read where a no-copy buffer lies
  once.
- Counters (WorkCounts): host_imports_used and host_imports_read_apart (with its six reasons),
  host_imports_kept_for_fds and kept imports by cause (of_heap, rebound, pointer, no_stand_in),
  heap_slots_rewritten, host_mappings_queried (Linux; 0 elsewhere), host_range_lookups,
  host_remaps_reported, host_remaps_over_imports, host_imports_remapped, host_pointer_imports_made
  and _bytes_made, no_copy_lies_read, host_imports_rebound_unlisted, host_rebind_imports_made and
  _covered.
- Docs: docs/HOWTO.md on both kinds of release, the RLIMIT_NOFILE soft limit a program raises
  itself and the new gauges; a FAST-PATHS known gap that a buffer made before a remap reads the new
  pages on drivers whose pointer imports follow their address, where Metal keeps the old ones
  (HostMemory::new's contract forbids such a remap); the rustdoc of host_range_remapped.

Why: ANV over i915 lists every VkDeviceMemory in every execbuffer, and a pointer import costs about
0.19 us an execbuffer; the consumer's guest keeps hundreds of no-copy buffers live and uses few in
a frame. Its swap thread spent 1.54 ms of kernel time a frame querying mappings of a buffer that
joined a live import. And a released import's deallocator unmapped pages under a live userptr,
losing the device.

Verified:
- Iris Xe, a guest-shaped lane of 520 pointer imports and 43 command buffers a frame, the idle
  ones released: objects per execbuffer 536 -> 51, ioctl 4.24-4.31 -> 0.85-1.09 ms a frame,
  scheduler CPU 4.96-5.05 -> 1.33-1.74 ms a frame, frame p50 5.27-5.43 -> 2.70-3.11 ms.
- The fact, probed outside the runtime on the Iris Xe and through tests::pointer_residency on it
  and lavapipe: a kept import read the pages a remap put at its address.
- The detach race on the Iris Xe and RTX 5080 under the validation layer: without the fix 3 of 3
  runs failed (deallocators late or on another thread); with it 12 of 12 runs, 15,360 races, each
  deallocator in the detach or the commit, never late.
- A second no-copy buffer over 2040 scattered mappings: 415-418 us -> 0.3-0.6 us. A rebind with
  1024 other live textures: 4766 -> 49 us. Alias lookups: a draw -5.3% instructions on host-page
  frames (RX 7900 XTX).
- Device and unit tests: freed_memory, pointer_residency, host_residency, blit_holds,
  encoder_holds, host_import_counts, host_aliases (up to 45 passed per run); lanes rebinds,
  rebind_reach, detach, detach_textures, host_memory, no_copy_heaps, dma_buf_imports, draw_work
  (74 passed on lavapipe, 30 on the Iris Xe for the deallocator fixes). clippy -D warnings (plain,
  m2v_gpu, m2v_cpu_icd) and rustdoc.
2026-10-19 00:16:00 +03:00
Anees Iqbal f514cb9a7d Cut shadowed textures' copies to what their commands touch, merge back every buffer another writer may write, and count copies by cause
A texture over a buffer's bytes or another image whose own image is a shadow now copies in, keeps,
merges and copies back only the texels its commands reach, with fewer barriers, descriptor pools
and scratch fills, and merges its writes back wherever another writer may write the bytes during
the run.

What changes:
- Which shadows merge. A shadow merges back (kept before the first command that writes through
  it, only the words its commands changed reaching the bytes) over every buffer's bytes but a
  tracked Private or Memoryless buffer the runtime made: Shared buffers and host pages as before,
  and now Managed buffers (on unified memory the CPU writes the GPU's memory, and without it a
  later upload may run on another queue) and untracked buffers another queue may write. A tracked
  Private buffer's shadow, a command replacing every texel, an image's shadow, and turned and
  two-plane textures still copy back. A merge goes in place wherever the texture's first and last
  words lie in the buffer and the bytes lie in pages; only a first byte inside a word, a staging
  buffer or a last word past the buffer still merges through a copy, a new FAST-PATHS known gap
  since that round trip can undo another writer's write between its copies.
- Correct merges. A command that replaces every texel followed by one that writes part of it is
  copied back before the keep, so the merge carries the later writes. A merge of a part leaves a
  twin stale there alone. A detached buffer's shadow binds no stand-in (the null handle while
  detached), so no merge binds a range past a 256-byte stand-in.
- Cut copies. A read inside a rectangle keeps the rest of the changed rectangle for the next read;
  an image's one-level, one-slice shadow cuts its copies in as a buffer texture's do; a keep and
  merge are cut to the rectangle the encoder's commands write in, in bands within the device's
  limits; a loaded shadowed colour's copies are cut to its draws' scissors also in passes that
  clear another attachment or take a reach clear (Vulkan's scissor test leaves coverage outside
  at 0).
- Cheaper copies. On ANV (DriverFact::ShadowCopyBackDispatchFaster, now every ANV device measured)
  a merge's keep and changed copy are the copy back's dispatch, and a cut merge reads the changed
  texels straight from the shadow's integer view (bind::shadow_merge_image_module), with no copy
  after the commands. On the UHD 770 (new DriverFact::ShadowCopyInDispatchFaster) a merged
  shadow's copy in and its keep are one dispatch (bind::shadow_copy_in_module), its 4-byte view
  R8G8B8A8_UINT because ANV drops a storage image's compression for an R32 view. The shadow
  kernels take a bind::ShadowTexelView. A cut merge's scratch is kept for the next merges and not
  zeroed. The shadow kernels and a linear attachment's merge push their descriptors where the
  device pushes set 0, so a shadowed pass makes no descriptor pool. A run of shadow copies in an
  unordered encoder shares one barrier before and one after, keeping a barrier only between copies
  that touch the same memory and one writes.
- Counters (WorkCounts): every copy in by why it is made and by what holds the texture's truth,
  first copies apart (shadow_texels_first_copied_in_*, shadow_texels_recopied_*,
  shadow_texels_copied_in_images, shadow_texels_bounded_copied_in), shadow_texels_kept,
  shadow_merge_copies_dispatched, shadow_merges_fetched, shadow_copies_in_dispatched,
  shadow_merge_scratches_reused and _zeroed, owned_descriptor_pools, how passes take shadowed
  colours (shadow_attachment_loads_*, _clears, _clears_in_part), shadows_sharing_truth, and the
  tiles a loaded colour's scissors cover against their bounds.
- Docs: shadow.rs and shadow_merge.rs module rules, API.md's shadow entries, FAST-PATHS' costs of
  matching Metal and known gaps; the snapshot rule's figure is now an upper bound.

Why: Metal writes only the texels a command writes, and another writer may write bytes no command
touches during a run. On an M3 Max under macOS 27.0.1, a fill of an untracked Private buffer from
a second queue ran inside a first queue's kernel or render pass 5 times of 6 and both texels kept
their writes, as did a CPU write to a Managed buffer; a tracked Private buffer's fill always ran
after. And in the consumer's Finder drag on the Iris Xe, whole 1080p shadow copies were most of
the composite command buffers' GPU time.

Verified:
- Iris Xe, four shadowed textures a frame over anonymous pages, commit to completion: merged passes
  that draw 11.7-11.8 ms -> 5.0-5.4 ms and scissored ones 11.3-11.4 -> 3.6-3.9 ms across the
  dispatched copies, cut keeps and fetched merges; a 1080p Load pass's GPU time 4572 -> 3484 us
  with the fetched merge.
- UHD 770: a 1080p Load/Store pass 2390 -> 1683 us GPU with the fetched merge; a 1080p Load pass
  1.64-1.67 -> 1.43 ms with the fused copy in; the kept scratch took a 1080p Load pass 4205-4755 ->
  2626-3595 us commit to completion (RX 7900 XTX 4112-4392 -> 1628-1697 us). Shared barriers saved
  about 0.65 us of GPU time per barrier removed on the Iris Xe (680 -> 120 barriers a frame).
- runtime_lane::pitched_surfaces 28 of 28 on the UHD 770, Iris Xe, Radeon 780M, RX 7900 XTX and
  lavapipe, with merges under changing scissors, split instances and two textures over one buffer
  matching a private texture's bytes; under synchronization validation with no message. The shadow
  lanes 123 to 132 of 123 to 132 on the M3 Max, lavapipe, Iris Xe and RADV; extended_range_blends,
  linear_attachments and padded_loads on the RTX 5080 with no validation message.
- Unit tests: tests::shadow (24), clear_reach, owned_pushes, shadow kernels through all four views
  on the CPU interpreter, driver_facts. clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd), rustdoc.
2026-10-19 00:16:00 +03:00
Anees Iqbal ca8340b4ee Group ready batches into one kernel submission on Mesa's drivers, and order a queue's batches by their ends
On ANV over i915 every kernel submission lists every VkDeviceMemory of the device, at a cost per
object; the consumer's guest drag on the Iris Xe had 302 entries per execbuffer (260 of them host
imports) at 112 to 128 execbuffers a frame. The runtime now makes fewer kernel submissions and
fewer command buffers per frame, under two new runtime policies.

What changes:
- DevicePolicy::completion, CompletionPolicy { Grouped (default), Exact }; exact_answers()
  selects Exact. Under Grouped, on a driver whose queue merges consecutive submits (Mesa's common
  queue: ANV, RADV, lavapipe, NVK and the rest), the scheduler holds ready batches of one VkQueue
  and submits up to four in one vkQueueSubmit, only the last signalling, so Mesa merges them into
  one kernel submission:
  - a batch whose only signals are events' joins, the group's end signalling each event to the
    highest index held; a batch waiting for a signal the group holds sends the group first;
  - only a group's first member may wait for anything not yet seen complete, since Mesa gathers
    every member's waits before the first member's commands; a later waiter goes alone after the
    group in the same call. Metal never holds one command buffer back for another's wait;
  - batches that cannot join (first work, binary semaphores, fences, sparse updates, wrapped
    images, storage-form switches) submit the held group first;
  - a pass that finds nothing ready keeps the group held while two or more earlier submissions of
    its queue are not seen complete, gated on the second-to-last, so commits arriving meanwhile
    join. It goes once full, when a head waits for the GPU, or when a thread waits for one of its
    command buffers;
  - a held batch that ends its command buffer turns Scheduled, takes its kernel end time and runs
    its submission handlers as it is held, so waitUntilScheduled returns at once, as Metal
    schedules a command buffer committed behind running work within 0.2 ms;
  - submission checks run ahead for up to three batches behind a line's head, so checked command
    buffers are found ready together; a failed group restores its waits, signals its last value
    and fails each member once; the group's submission allocates nothing.
  New degradation kind grouped-completion (Precision), announced once per device: a group's
  members but the last are seen complete late, by at most three later batches' GPU time plus one
  completion turn, and intermediate event values are seen late, never wrong.
- An event-signalling batch's end goes into its work's last command buffer, as every other batch's,
  unless its signal must wait for another queue's earlier signal.
- DevicePolicy::batch_order, BatchOrderPolicy { Ends (default), Exact }; exact_answers() selects
  Exact. On ANV, RADV and NVIDIA's driver, measured to run a queue's submissions one after another,
  each batch ends with a barrier to every later command of its queue, the tracker takes an earlier
  batch of that queue as ordered (no barrier per dependency), and a batch's start timestamp with
  nothing planned before it is written at the bottom of the pipe. Other drivers and Exact keep the
  barriers per dependency.
- WorkCounts: grouped_submissions, batches_grouped, group_ends_full / _wait / _apart /
  _first_work / _drained / _checks / _held, event_waits_met, batches_with_none_pending and kin by
  pending depth, groups_kept_pending and groups_sent_for_waits; frame_costs prints them, with
  kernel submissions and ioctl time where the i915 execbuffer script is loaded, and gains guest-
  shaped legs over 260 and 520 host imports.
- Docs: FAST-PATHS rows for both policies (the grouping row with the guest's frame rates), API.md
  entries, add_submission_handler's doc, the runtime README and the scheduler modules' docs.

Why: each fewer kernel submission saves the scheduler thread an ioctl of about 80 to 130 us there,
and each barrier per dependency buys nothing on drivers that run a queue's submissions in order.
The bound of four was kept: eight measured about three fewer submissions a frame for twice the
completion lateness and no frame-time change.

Verified:
- Iris Xe, guest shape over 520 host imports, Grouped against Exact: 26.2-26.7 execbuffers a frame
  against 67.0, ioctl 2.77-2.81 against 6.89-6.96 ms, scheduler 52-53 against 122-123 us per
  command buffer, through completion 5.98 against 8.70 ms a frame.
- UHD 770, the held group at a 1 ms commit pace: 25.0 kernel submissions a frame against 58.1,
  scheduler 67-82 against 113-124 us per command buffer, the same frame time and GPU idle;
  completion seen 1.82-1.86 ms after GPU end against 0.43-0.46 ms.
- In the guest on the Iris Xe, Grouped made 24.4-27.5 kernel submissions a frame against Exact's
  42.4-43.8 and saved 0.4-1.7 ms of scheduler CPU a frame; the frame rate was alike within
  boot-to-boot noise (15.7-17.3 against 16.4-17.6 fps).
- runtime_lane::grouped_submissions (held signals on one and two queues, waiters leading, groups
  held behind running work with and without submission handlers and checks, both policies, the
  validation layer silent): 19 of 19 on ANV and lavapipe; the held-handler case fails without its
  change. commit_work, gpu_times, grouped_submissions, queue_order, events and first-use lanes 77 of
  77 on the Radeon 780M, RX 7900 XTX and RTX 5080; under synchronization validation 34 of 34 on
  the UHD 770. The runtime's device tests 1066 of 1066 on ANV; the unit suites 4534 of 4534.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
2026-10-19 00:16:00 +03:00
Anees Iqbal ed3ca3aa1f Push set 0 where the device has the push command, read uniform buffers at constant offsets, and share pipeline layouts
A draw's and a dispatch's set 0 is pushed where the device can, its uniform buffers are read at
constant offsets where the binding allows, and alike pipeline layouts are one object, so switches
between alike states keep set 0.

What changes:
- Pushed set 0. Where the device has vkCmdPushDescriptorSet (Vulkan 1.4 or VK_KHR_push_descriptor),
  a variant whose set 0 fits maxPushDescriptors, takes no set or binding flags and binds at one
  bind point makes set 0 a push descriptor set layout. Its draws, dispatches and tile dispatches
  push set 0's writes instead of allocating, writing and binding a set. Draws push incrementally:
  only the writes that differ from what set 0 holds, as Vulkan allows until the set is disturbed;
  baked samplers are pushed with every full push, as Vulkan requires. Every other variant and
  every device without the command keeps the allocate-write-bind path. vkCmdPushDescriptorSetKHR
  joins the exit guard's table and the device's priming. WorkCounts draws_pushing_set_zero,
  set_zero_writes_pushed and dispatches_pushing_set_zero.
- Two driver defects, both typed RuntimeDriverDefect variants:
  - PushedBufferSizesUnset on MoltenVK (every release): its pushed sets leave the buffers'
    sizes unfilled, so a runtime array length reads 0. MoltenVK binds set 0 from pools.
  - PushedDescriptorsStaleAfterPipelineBinds on ANV: a descriptor kept across a pipeline bind
    reads zeros. There the first push after each pipeline bind carries at least one write.
- Uniform reads. Each uniform-view slot declares a specialization, SpecKey::RangeAtBindOffset:
  where its descriptor range starts at the bind offset (inline bytes, an unbound slot, or a bind
  offset the views' base alignment A divides), a read takes the Metal offset alone, a constant
  for a constant member, so ANV pushes the constants into registers. Elsewhere it adds the
  residual as before. Both forms are exact.
- Bind-offset classes. A bind offset is classed only by what a plan reads: A where the slot reads
  through a uniform view and A divides it, else its alignment up to 4 for the vertex fetch. A slot
  bound at an offset A does not divide leaves the specialized slots for good, so a slot at moving
  offsets keeps one shape and one pipeline. The debug check of a table brought in place compares
  those slots.
- Shared pipeline layouts. The device keys set and pipeline layouts by everything their creation
  takes (sets, bindings, baked sampler handles, push-constant ranges), so variants defined alike
  share one VkPipelineLayout; set 0 and the push constants then survive a pipeline bind between
  them. WorkCounts pipeline_layouts_made and pipeline_layouts_shared, and set_zero_equal_shape_switches,
  set_zero_writes_on_equal_shape_switches and set_zero_writes_if_shapes_shared for the switches
  between layouts of one set-0 shape that are still apart. A new bench, frame_costs_alternating.
- New owned fixture engine/ubo_bind_offsets; docs/API.md states the alignment and the mask.

Why: on an RTX 5080 laptop GPU in runtime D3, vkCmdBindDescriptorSets waits about 973 ms for the
GPU to wake after 20 s idle, and vkCmdPushDescriptorSet 0.02 ms. ANV loads a uniform buffer ahead
of the shader only for constant offsets: the guest's display present spent 18 of its 29 sends on
uniform loads. And the guest pushed 597 set-0 writes a frame on switches between alike layouts,
where 244 would do.

Verified:
- RTX 5080 laptop after 20 s idle: a draw's call 957-974 ms binding set 0, 0.20-0.25 ms pushing it.
  draw_work and dispatch_work 14 passed on it and on lavapipe, both taking the push path, and the
  bind path with the extension withheld.
- On the M3 Max, the push path failed 30 of 61 tests (runtime array lengths reading 0) and crashed
  Metal's compiler service on render variants; with set 0 bound on MoltenVK they pass as before.
- Iris Xe, 1080p passes of a full-screen draw: a float4x3 matrix and two packed_float3 per pixel
  691.6 -> 407.7 us (-41%), twelve float4 451.0 -> 429.7 us; INTEL_DEBUG showed 21 sends -> 3.
  RADV was unchanged. With the offset classes, a guest-shaped bench's encoding thread went from
  5.65-5.70 back to 5.16-5.45 ms a frame and 194 pipeline lookups a frame to 0.
- The ANV defect: unorm_depth_bias failed 3 of 3 without the guard, passed 3 of 3 with it, on the
  Iris Xe and the UHD 770.
- Shared layouts, frame_costs_alternating: set-0 writes 1920 -> 1320 a frame and draw states 2600
  -> 2000 on RADV and ANV; a draw -2.3% instructions on both. On lavapipe (debug) the runtime unit
  tests 1057 passed and every runtime lane test passed but for failures that reproduce without the
  change; on RADV 115 lane tests passed, no VUID message.
- Unit tests: engine_access, bind::plan::slots, bind_shape_of, render::bound, argument_table,
  driver_defects; uniform_bind_offsets device tests on lavapipe and ANV. clippy -D warnings (plain,
  m2v_gpu, m2v_cpu_icd) and rustdoc.
2026-10-19 00:15:59 +03:00
Anees Iqbal d485925af2 Keep the commit path off the GPU's wake and the scheduler's lock: cached uploads, timestamps at completion, primaries begun ahead
A command buffer's encoding, commit and property reads now make no call that waits for a
powered-down GPU or for the scheduler's submission, as Metal's return at once.

What changes:
- Upload arenas (argument, handle and root tables, constant blobs, neutral buffers, status words)
  take host-cached, host-coherent system memory (MemoryClass::Shared) instead of write-combined
  memory, which preferred device-local memory on a discrete GPU. Unified-memory devices are
  unchanged; a device with no host-cached coherent memory keeps its device-local type. No flush is
  needed: Vulkan defines coherent memory as needing none, and a submission orders the host's
  earlier writes. New WorkCounts::upload_chunks_in_device_memory.
- The calibration pair that places GPU times on the host clock (vkGetCalibratedTimestampsKHR) is
  read by the completion turn, not at commit. The placement and its pair cache are unchanged;
  UncalibratedGpuTimes now says the calibration failed as the command buffer completed.
- A completed command buffer's settled spare pool begins one primary ahead on the completing
  thread, with the spares' lock released and only where no thread waits on the command buffer's
  gate, so the next command buffer's first encoder records into it instead of beginning one. The
  pool passes between threads under the spares' lock, which is all vkBeginCommandBuffer's
  external synchronization asks. WorkCounts primaries_begun_ahead and
  encoder_primaries_begun_ahead.
- A timed command buffer's timestamp slot is reset on the host (vkResetQueryPool, a Vulkan 1.2
  required feature the runtime enables) as it takes the slot, so no command buffer the GPU runs
  resets a query; an adopted device keeps the command resets. WorkCounts
  timestamp_slots_reset_on_host.
- kernelStartTime and kernelEndTime are two atomics beside the command buffer's state, and status
  and error an atomic and a once-set error published at each transition, so a read waits for no
  replay or submission and a commit takes no new lock. An Error status always finds its error.
- WorkCounts counts the command buffers begun by what they were begun for (encoders, segments,
  continuations, secondaries, batch work and barriers, kept barriers, internal), printed by
  frame_costs.
- docs/HOWTO.md notes NVIDIA's runtime D3 wake (about 1 s after about 15 s idle) and how a host
  that wants none keeps the GPU powered; never required.

Why: on an RTX 5080 laptop GPU in runtime D3, the first write into device-local host-visible
memory after 20 s idle waited 977 ms for the wake, and so did the commit's timestamp read (a
commit took 973-977 ms; Metal's returns at once). On ANV a begin clears the command state, 8 to 20
us each, 0.80 ms of the Iris guest's 17 ms frame. And the scheduler holds the state lock through a
batch's replay and submission, so a status or kernel-time read waited 60-65 ms behind 131,072
fills.

Verified:
- RX 7900 XTX, release A/B: encoding-thread CPU 5.27 -> 4.79 ms a frame with cached uploads, the
  vertex-heavy GPU time unchanged (28.18 -> 28.19 ms); draws_setting_bytes_write_no_device_local_memory
  fails without the change on the XTX, RTX 3090 and RTX 5080.
- RTX 5080 laptop: a frame's commit after 20 s idle 973-977 ms -> 0.02-0.03 ms; the wake is now in
  the wait, as Metal's commit-and-wait shows it. gpu_times and degrade_notices 27 passed on it and
  on lavapipe. Host-reset slots saved about 1-2 us of GPU time a command buffer there; neutral on
  the Iris Xe.
- Iris Xe: encoding-thread CPU 4.96 -> 4.62 ms a frame and a pass open 5.71 -> 2.77 us with
  primaries begun ahead; 95.85 of 97 encoders a frame took one.
- runtime_lane::property_reads on the RX 7900 XTX and Radeon 780M fails without the change (reads
  of 60.3-65.1 ms) and passes with it (longest read 0.022-0.097 ms); on the M3 Max under MoltenVK
  it passed with 0 slow reads and the commit allocation bound held at 4.00. A new test checks
  status reads Completed in the completed handler, after the wait and in a deallocator.
- Unit tests: spares, gate, exit_guard, gpu_time, completion, command_buffer (up to 218 passed
  per run); clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
2026-10-19 00:15:59 +03:00
Anees Iqbal 437e37cb59 Keep the driver's compression for textures Metal compresses, the uncompressed heap image behind HeapCompressionPolicy
On a compressing driver (ANV's CCS on the Iris Xe), textures the runtime made uncompressed for
reasons that no longer hold now keep the driver's compression.

What changes:
- A device's own texture without allowGPUOptimizedContents makes its image from the descriptor's
  usage alone (TextureDescriptor::own_image_usage), not with PixelFormatView usage, so the driver
  keeps it compressed. Its layout is never visible (no size answer, no aliasing; views, blits and
  fresh contents follow the descriptor), so this is exact. Heap, sparse and shared textures keep the
  PixelFormatView image. On MoltenVK, whose blits of a compressed RG11B10Float or RGB9E5Float
  texture rewrite texels (RuntimeDriverDefect::CompressedImageCopiesRewriteTexels), such a texture
  keeps the uncompressed image, deciding from the image the device's Metal would compress.
- A heap's colour texture that Metal itself compresses (by heap_tiled::metal_compresses_layout)
  takes the driver's optimal, compressed image by default, announced once as the new degradation
  kind heap-texture-compressed (Precision). New DevicePolicy::heap_compression,
  HeapCompressionPolicy { Compressed (default), Uncompressed }; exact_answers() selects
  Uncompressed, the host-transfer or linear image that keeps aliased writes visible byte for byte.
  It is the runtime's choice alone and keys no profile. Textures Metal keeps uncompressed keep
  that form under both values.
- optimized-depth-stencil-texture is announced only for heap textures and heap size answers, the
  only places the difference shows; a device's own or shared depth texture no longer announces it.
- Docs: a FAST-PATHS row with both forms' costs, the API.md catalogue entries, and the docs of
  allow_gpu_optimized_contents, the degradation and DriverFact::DepthStencilImagesStayGpuOptimized.

Why: the uncompressed form costs a 2048x2048 RGBA8Unorm render target's clear 676 us against 27 us
compressed on the Iris Xe. And Metal does not show aliased writes over a texture it compresses
either: on an M3 Max under macOS 27.0.1, a buffer fill over a compressed texture's bytes made every
covered texel of drawn content read opaque magenta, never the written value; only clear-only
content and uncompressed (ShaderWrite) textures showed the write. So the uncompressed heap image
matched Metal only for clear-only content.

Verified:
- runtime_lane::heap_textures::heap_compression_costs (new, ignored) on the Iris Xe, release, ABAB:
  compressed clear 26.9 us and copy 647.7-649.1 us; uncompressed clear 676.2-676.5 us and copy
  673.9-693.2 us.
- On ANV: the new heap test (compressed textures kept 4096 to 9696 texels unchanged under an
  aliasing write, uncompressed ones 0; notice counts exact), the heap_textures, heap_layouts,
  heap_metal_sizes, compressed_blits, fresh_contents and mipmaps_exact lanes, 53 passed, 0 failed.
- runtime_lane::compressed_blits on the M3 Max caught the MoltenVK blit defect (an RG11B10Float
  byte read back as 224 where Metal keeps 250), which the uncompressed image fixes.
- The translator's fast_paths and driver_facts tests (17) and api_surface (11) on gem10; the
  runtime's image_plan and texture_descriptor tests; clippy -D warnings (m2v_gpu).
2026-10-19 00:15:59 +03:00
Anees Iqbal 79f4341b9a Order fence stages and draw-to-draw hazards inside a render pass as Metal does, and document the sync layer's blind spots
Synchronization inside and around render passes now follows Metal's ordering more closely, and
the lane's synchronization checks report only real hazards.

What changes:
- Fence stages. A render encoder's waitForFence:beforeStages: and updateFence:afterStages: now
  cover only the stages they name (tracker::FenceUse): a wait before the fragment stage leaves the
  pass's vertex work free to run earlier, and an update after the vertex stage lets a later
  encoder's wait go ahead before the fragments finish. Each barrier names its stages explicitly,
  since Vulkan's access scopes include only stages explicitly specified; every stage outside the
  draws stays covered, so the runtime's own copies and dispatches around the pass are ordered.
  Compute and blit encoders keep every stage.
- Indirect arguments. A draw that writes memory an earlier draw of its render pass instance read
  as indirect arguments first records an execution dependency from DRAW_INDIRECT to its writes'
  stages (Vulkan: write-after-read needs only an execution dependency), inside a subpass
  self-dependency every pass carries.
- Pre-raster writes. A draw whose fragments touch memory an earlier draw of the instance wrote
  before rasterization first records a memory dependency from those stages' SHADER_WRITE to
  FRAGMENT_SHADER, inside a third self-dependency over the stages the device enabled. Metal runs
  every draw's vertex, object and mesh functions of a pass before any fragments. The opposite
  order stays announced as FragmentsBeforeGeometry.
  For both, a draw whose pipeline is being made records the barrier in its own secondary, an
  instance kept for inline recording keeps it, and an execution of render commands starts from
  its instance's kept uses. Every pass of a device carries all three dependencies, so passes of
  one shape stay compatible.
- Validation lane: pipelines made with rasterization-order attachment access are named
  RASTER_ORDER_PIPELINE where the instance reports messages (vkSetDebugUtilsObjectNameEXT joins the
  exit guard's table), and the layer's read-after-write report on their input attachment reads
  passes as a known layer gap: the spec gives such pipelines a framebuffer-local dependency, which
  the layer's synchronization code does not read. The lane's sync switch takes the layer's default
  submission-time validation instead of a setting newer layers deprecate, and its docs name two
  more layer limits (whole descriptor ranges taken as accessed, indirect counts not read).

Why: the fence stages are Metal's, measured on an M3 Max under macOS 27.0.1 (each case 3 of 3);
Metal reads a draw's arguments before a later draw of the encoder writes them; and the validation
layer reported the two draw-to-draw hazards on RADV, which reads indirect arguments in place.

Verified:
- runtime_lane::fence_stages on the Iris Xe (ANV): both tests passed; the vertex function did not
  run early there (a whole-pipeline stall fits), so the overlap is expected only on drivers that
  honour a barrier's destination stages, not measured. The tracker tests passed.
- Synchronization validation on the Radeon 780M (RADV, layer 1.4.341): without the runtime
  changes, indirect_draws fails 2 of 5 and pass_start_reads 3 of 6 on the two hazards; with them
  the whole runtime lane ran 1565, 10 failed, each on its own earlier hazard, and no VUID message.
  On the UHD 770 host the product suites 4987 of 4987 and validation 1328 of 1328 passed.
- The six framebuffer_fetch lanes under the sync switch on lavapipe; raster_order_gap unit tests;
  the priming check.
2026-10-19 00:15:59 +03:00
Anees Iqbal ef7fe8aa56 Hold what a blit, a per-sample copy and an indirect sparse update use until the command buffer completes
Metal's command buffer retains what its encoders were given until it completes, so a program may
release a buffer or texture once it committed. Two paths did not hold theirs:
- A blit between a buffer and a multisampled texture, emulated per sample, retained only its
  copy's plan (the raw VkBuffer and its own images), not the program's Buffer or the texture.
- An indirect sparse mapping update's host step replaced the update with the updates its arguments
  state; where they state none, nothing held the texture and buffer, and the replaced update was
  dropped under the command buffer's state lock, so a no-copy buffer's last release could run its
  deallocator under that lock.

What changes:
- EncoderCore::blit_at, the one way a blit command takes a buffer's VkBuffer, retains the buffer
  until completion, so every blit path holds it; the per-sample copy holds the texture it copies
  into or out of.
- read_mappings moves the replaced sparse update into the command buffer's retained list,
  released at completion outside the lock.
- A buffer or texture these commands used is now released at completion rather than at the
  program's release.

Why: the consumer's resource synchronization on an RTX 5080 copies a multisampled Depth32Float
texture into a no-copy buffer over guest pages, commits, waits until scheduled and drops the
buffer. The import was freed 3 ms after the commit, and the copy engine's write at its first page
faulted 285 ms later and lost the device. METAL2VULKAN_LOG_MEMORY placed the fault at offset 0 of
the freed import and showed the next import mapped at the same address: with that mapping first,
the copy would have written into other guest memory silently.

Verified:
- tests::blit_holds (device test): each leg puts the blit behind 1 GiB of fills, commits, waits
  until scheduled, releases the no-copy buffer and asserts its deallocator has not run while
  pending, then checks the bytes in the host pages (buffer to and from no-copy, fill, multisampled
  R32Uint both ways, multisampled Depth32Float set Volatile after release).
- tests::encoder_holds (device tests), one leg per way a command reaches memory: draws reading
  vertex, fragment, index and indirect buffers, a draw into a texture over a no-copy buffer,
  dispatches, an indirect dispatch, use_resource and use_heap reaches, an indirect command
  buffer's dispatch, and sparse indirect updates that map a level and that map nothing. While
  pending, the deallocator has not run and every watched object lives.
- Before the fix, on lavapipe under the validation layer 17 passed and 2 failed (the sparse
  update's lost texture, and a heap's placed buffer, which Metal's contract does not hold either
  and the test no longer watches); on the Iris Xe 18 passed, 1 failed (the placed buffer).
- The fixed runtime built under m2v_gpu and m2v_cpu_icd with clippy -D warnings clean; the fixed
  legs ran in the following device batches.
2026-10-19 00:15:59 +03:00
Anees Iqbal 2b97fc1cf0 Render packed 16-bit, 8-bit sRGB and RGB9E5 attachments the device cannot render through integer views of their words
The RTX 5080 samples A1BGR5Unorm, ABGR4Unorm (and every other 16-bit packed order), R8Unorm_sRGB,
RG8Unorm_sRGB and RGB9E5Float but renders none of them, and lavapipe renders neither 8-bit sRGB
format. A render target, clear or draw of such a texture was refused as the device lacking the
format, which ends the guest of any app that renders to one. They now render through an R8_UINT,
R16_UINT or R32_UINT view of the same bits, the fragment function writing Metal's word.

What changes:
- metal::format::WordAttachment (public, with WordField): a format's fields in its word (packed
  16-bit layouts named from the least significant bit, Srgb8, Rgb9e5). WordAttachment::of holds
  where the device samples the format (or its UNORM twin), does not render it, and renders the
  word's integer format: derived from format features alone, on every driver.
- Translator: LoweringInputs::word_colors names such attachments. The fragment output to one is
  declared as a uint and each return stores Metal's word: a packed channel h(x) to nearest even,
  NaN 0, clamped to [0, 1], times the maximum code, rounded to even; an sRGB channel through
  Metal's twelve-bit table; RGB9E5 by the truncating kernel-write rule (shared with the storage
  write, lower::texture::rgb9e5_word). The cache codec carries the new fields.
- Partial write masks and blends:
  - in the pixel interlock (where the device orders fetch through it alone), a packed 16-bit or
    8-bit sRGB word's partial mask merges the kept fields from the word read first;
  - a packed 16-bit word's blend other than One/Zero decodes each code as Metal's blend reads
    it, h(c / m), blends in half as the 8-bit unorm blend does and encodes Metal's word. Metal's
    tile holds a pass's earlier result finer than the codes, so this is a near-equivalent within
    one code, recorded as PrecisionNote::DeviceColorConversion and announced; the exact form (the
    extended-range half shadow taken by word attachments) is a FAST-PATHS "not built yet" row;
  - where fetch reads rasterization-order input attachments (lavapipe), an 8-bit sRGB word's
    partial mask merges over its input attachment (new RuntimeFact::WordInputMerge), per sample in
    a multisampled pipeline.
- Runtime: the texture's image keeps its own format, sampled and blitted natively, made mutable
  with extended usage and the word view listed; the pass's attachment is the view; a pass clear
  writes the word of Metal's clear.
- New degradation kind shared-exponent-kept (Precision): Metal's tile store normalizes a loaded
  RGB9E5 word whose largest mantissa is below 256 in each tile a draw reaches, which a Vulkan pass
  keeps; announced at each such draw, with a FAST-PATHS row.
- DeviceColorConversion's rustdoc states that Metal blends a packed 16-bit attachment against its
  tile's finer values within a pass.
- Still refused, recorded as FAST-PATHS known gaps: colour inputs and resolves of word
  attachments, blended or fetched sRGB words, an output of fewer than four lanes for a blended
  packed word, RGB9E5 half outputs, blends, masks, inputs and resolves.
- New owned fixture engine/wm_samples and runtime_lane::word_samples for the multisampled merge.

Why: these formats are Metal render targets the guest uses, and the device holds and samples them;
only rendering them directly is missing.

Metal's rules, measured with plain Metal on the M3 Max under macOS 27.0.1: 65,536 float4 and half4
outputs and 4,096 clear colours per packed format, 0 texels off the rule; a One/Zero blend stores
the same bytes; the blend sweep (2,891 states, 8,192 random pixels, four packed formats, half and
float, fast and safe maths) gave Metal's code in every channel without fast maths and within one
code under it; within a pass Metal's tile holds a packed attachment finer than its codes (blends
in one pass follow the unrounded value, across two passes the stored codes); RGB9E5 draws and
clears 65,536 of each, 0 off.

Verified:
- Translator and runtime unit filters on gem10: 162 of 162 and 258 of 258 (word attachments),
  394 (partial masks in the interlock), 370 and 422 (blends, including 864 words the M3 stored
  checked on the interpreter), 538 (sRGB and RGB9E5 words), 38 and 108 (input-attachment merge).
- On lavapipe: runtime_lane::color_writes 5 passed, RG8UnormSRGB under the red mask 0 of 107,814
  channels off where it was refused before; word_samples, 64 texels of 4 samples merged, the edge
  texels keeping both greens; public_fixtures_engine with the new rows.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
2026-10-19 00:15:59 +03:00
Anees Iqbal 697c55d514 Announce a loaded snorm or RGB9E5 attachment's kept codes, and store them as Metal's tile store does under TileStorePolicy::Exact
Metal's pass, once it draws, writes each 32x32 tile a draw reaches back through its texels'
values: a signed normalized channel's minimum code (-128, -32768) reads as -1.0 and is stored as
the code above it, and an RGB9E5Float word whose largest mantissa is below 256 under an exponent
above 0 is stored normalized. A Vulkan pass's load and store keep those bytes.

What changes:
- New degradation kind snorm-minimum-kept (Precision), announced at every draw and indirect
  execution in a pass that loads a single-sampled R8, RG8, RGBA8, R16, RG16 or RGBA16 Snorm colour
  attachment and keeps it, naming each such attachment. It joins shared-exponent-kept for RGB9E5.
- New DevicePolicy::tile_store, TileStorePolicy { Device (default), Exact }; exact_answers()
  selects Exact. It is the runtime's choice alone and keys no profile. Under Exact the load pass
  that already rewrites extended-range, padded and bfloat attachments also takes a single-sampled
  snorm or RGB9E5Float attachment in the tiles the pass's draws reach, with two new
  bind::unused_bits_module rules (SnormMinimum, SharedExponent; the module is keyed by
  PixelFormat), and nothing is announced. An attachment the load pass cannot take keeps the
  device's load and store, announced.
- New answer fact DriverFact::TileStoreIsMetals for MoltenVK 1.4.1 on Apple's GPUs: its render
  pass is a Metal render pass, so its tile store is Metal's for both kinds. There neither value
  adds a load pass or a notice.
- Docs: one FAST-PATHS row for the switch, its cost the load pass's measured GPU time; a known gap
  for lavapipe, which states no blend for any snorm format, so a blending snorm pipeline is
  refused there; API.md's policy bullet and catalogue entries; the unreached-tiles-rewritten text.

Why: a code no Metal write leaves, but uploaded or copied bytes may hold, reads back differently
after a drawing pass. The exact form costs a copy of the render area through a dispatch before
every such pass, so the device's store stays the default, announced, and Metal's store is a
switch away.

Verified:
- Metal's behaviour probed on an M3 Max under macOS 27.0.1 (70x40 targets of five snorm formats):
  a pass that draws nothing moves no code; a tiny triangle moves every minimum code of its first
  32x32 tile and none elsewhere; a blended full-target draw moves all of them; a blit there and
  back moves none. The guest's sweep showed the same on R8Snorm and RG8Snorm.
- Unit tests: unused_bits (both rules against CPU models over every code, the M3's example
  RGB9E5 word, the masked-tile rewrite), fast_paths (the row, no profile key), driver_facts,
  api_surface, owned_divisions: 38 passed on gem10.
- runtime_lane::snorm_tile_store under Device and Exact for both kinds, asserting load-pass
  counts, bytes and notices: on lavapipe with padded_loads, extended_range_blends and the notice
  site check, 15 passed (Exact took the load pass, Device announced); on the M3 Max under
  MoltenVK 1.4.1, 4 passed through the fact (no load pass, no notice) and 11 more beside them.
- The load pass's cost (FAST-PATHS): on the Radeon 780M, a 1080p pass per frame of BGRA10_XR
  1958.8 us against RGBA16Float's 135.3 us; the snorm and RGB9E5 cases take the same pass, not
  timed alone.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
2026-10-19 00:15:59 +03:00
Anees Iqbal 2423b8de61 Keep the Iris Xe's depth fast: DontCare stores, sampled usage for hierarchical depth, multisampled depth held out of GENERAL
Three measured cost facts for ANV (Mesa 26.2.4) on the Iris Xe of RPL-P (0xa7a0), each a pure fast
path that keeps every texel and the order of every use: no policy switch, notice or ledger row.

What changes:
- DriverFact::DontCareStoreIsOneOfMetals gains a row for this GPU: an attachment a pass stores
  DontCare is Vulkan's DONT_CARE there, as on the UHD 770 and the Radeon 780M.
- New DriverFact::SampledDepthKeepsHiZ. ANV turns off a single-sample depth image's hierarchical
  depth and compression in GENERAL (the layout every runtime image rests in) for an image of
  transfer-source usage, but keeps its write-through form on for one of sampled usage. Where the
  fact holds, a single-sample depth attachment plan the device samples takes SAMPLED too
  (image_plan::hiz_candidate), heap textures and the runtime's own depth images included; the heap
  size answer comes from the same plan. Memory size and alignment are equal with and without it.
- New DriverFact::MultisampledDepthFasterOutOfGeneral. A multisampled depth image renders very
  slowly in GENERAL on this GPU, since the write-through hierarchical depth is single-sample only.
  Where the fact holds:
  - each render pass instance holds a multisampled depth attachment in
    DEPTH_STENCIL_ATTACHMENT_OPTIMAL, moved from GENERAL by a barrier before it and back after
    it (the feedback-loop mechanism, generalized to moved images; WorkCounts
    depth_attachments_moved);
  - the device's own Private multisampled depth texture stays in the attachment layout between
    encoders that only render it (texture/held_depth.rs). The scheduler moves it at encoder
    boundaries, before any encoder that uses it otherwise, as a tracked write of the whole image so
    the hazard tracker orders it against every use on every queue. A pass holds only when nothing
    else in its encoder touches the image; a later use breaking a hold fails the encoder's end
    with a visible internal error. WorkCounts depth_instances_held and held_depths_released.
  - An instance an execution of render commands joins, inline instances and the resolve-after
    instance stay in GENERAL. Layout transitions preserve contents unless the old layout is
    UNDEFINED (Vulkan, Synchronization, Image Layout Transitions).
- New measurement runtime_lane::depth_costs (ignored by default).

Why: in GENERAL these depth attachments lose the hierarchical depth test, so the depth test
rejects no fragment a block at a time; and moving back to GENERAL after every pass costs a full
hierarchical-depth resolve, about 1.95 ms a pass at 1080p with 4 samples.

Verified, release, on the Iris Xe:
- runtime_lane::dont_care_stores: every texel of its twelve kept cases was the earlier or the
  stored one, none other.
- A 1080p heap Depth32Float at 32 layers: 4.72-5.66 -> 0.82-0.87 ms with sampled usage. A 4x
  Depth32Float at 32 layers: 12.14 -> 1.44-1.52 ms moved per instance; held between encoders, 1
  layer 2.56 -> 0.62 ms and 32 layers 4.35 -> 2.38 ms (GPU clock fixed at 300 MHz). Batches that do
  not name the depth showed no CPU difference above noise.
- runtime_lane::msaa_depth_moves 9 of 9 under the validation layer with the counters checked (a
  blit between passes, a resolve in its pass, frames, reads after each pass, two queues ordered by
  an event, a split pass, an argument-buffer read with useResource, an encoder that also binds its
  depth, an indirect-command-buffer execution); the depth, resolve, snapshot, clear-reach,
  memoryless and fence-stage lanes passed. On the Radeon 780M and RTX 3090: msaa_depth_moves 9 of
  9 with the fact off and every counter 0. Runtime unit filters 134 passed.
- The RTX 3090 measured neutral for both depth facts, and the RX 7900 XTX keeps DontCare as STORE
  (not a measured identity), so neither is listed.
- Unaudited: no lane covers a tile dispatch in a held pass.
2026-10-19 00:15:59 +03:00
Anees Iqbal 86b5d6faf3 Cut the encoding thread's allocations, locks and copies per draw and per render pass
A draw, a pass open and a pass end on the encoding thread now do far less work that no answer
needs. Every change records the same commands in the same order, retains and lets go of the same
objects at the same points, and announces the same notices with the same text.

What changes:
- Kept objects. The device keeps every VkRenderPass it makes, by everything it is made of (at most
  256, destroyed with the device), so passes alike make none (WorkCounts::render_passes_made). A
  pipeline state keeps the last four pipelines its draws found, not only the last one. A device's
  depth-range facts are read once at its making. A pass layout's kept-attachment notices
  (extended-range-bits-kept, snorm-minimum-kept, shared-exponent-kept) are decided once per
  layout, dropped wherever the layout changes, and checked against a fresh decision at every draw
  in debug builds.
- Storage reused. Each draw's commands (push bytes and writes, descriptor ranges, extents, uses)
  are written over the last draw's storage; push field bytes sit in place up to 32 bytes; a draw's
  host-memory uses go into a vector its encoder keeps; the pass layout and pass-start tables move
  as boxes, not 700-byte values.
- Lists in place. A pass's shape lists, default viewport and scissor, first drawn rectangle,
  colour sets (as bit masks), clear values and attachment extents are held in place, bounded by the
  eight colour attachments; a pass end makes no list it would leave empty; a draw's attachment
  reads are checked one attachment at a time; a command buffer's dynamic states are bits.
- Fewer locks. A render encoder retains its own argument tables through its exclusive borrow, with
  no lock; set 0 is allocated under the bind's lock; the settled variant and plan move out instead
  of cloning; a draw's pipeline state, variant objects, VkPipeline and samplers are retained once
  per encoder, the first eight of each kind in place. A draw's use keys are kept and named only
  where the last command's use there took another key. The latest used memo entry stays where it
  lies when it is used again.
- Fewer commands. A stencil state whose front and back values match is set by one command with
  VK_STENCIL_FACE_FRONT_AND_BACK, which the Vulkan specification defines as updating both faces.
- The recorded-state checks are #[inline], so their cost no longer depends on which codegen unit
  holds them.
- runtime_lane::frame_costs' allocation bounds drop to the new counts (pass open 14 -> 4.5, pass
  end 40 -> 19, a draw's bounds with them) and fail without these cuts. The pass-open bound allows
  one more allocation on Apple's platforms, where Rust's standard library boxes a mutex at its
  first lock.

Why: the consumer's guest is bound by its encoding thread. Its task thread spent 6.61 ms a frame
in draws and 1.77 ms in pass ends, and allocation, B-tree lookups, memmoves and locked instructions
were large shares of both.

Verified:
- Allocations (counting allocator): on the RX 7900 XTX (RADV), a guest-shaped pass's draw 39.70 ->
  32.70 for the reused commands and a pass open 11 -> 5 for the lists in place; on the UHD 770
  (ANV), a pass end 22.43 -> 16.91 and a pass open 5.00 -> 4.00, the same on lavapipe (debug).
- User-space instructions, release A/B medians: render passes kept, a frame -1.9% on the Iris Xe
  (about 113 vkCreateRenderPass2 calls a frame before, none after); the boxed moves and depth-range
  facts about -2% a draw each on the RX 7900 XTX and -1.2..-1.5% on the UHD 770; the kept notices
  -0.9% a draw on the UHD 770; locked instructions per process 22.45M -> 21.73M on the UHD 770.
- Unit tests: field_bytes_hold_what_they_were_made_of, equal_faces_take_one_stencil_command,
  depth_ranges, using_the_latest_entry_again_keeps_the_order, and the graphics binder's tests
  checking every instantiation written over earlier commands equals a fresh one. Lane tests in
  draw_work (a pass drawing as the one before makes no render pass; a state switching keys finds
  its pipelines again).
- On lavapipe (debug): the runtime unit suite 1066 passed; the stand-in, extended, split, inline,
  tile, reformat, snapshot, held-depth, feedback, instance, render-pass and frame-cost lanes 228 of
  234 (the 6 failures passed when rerun alone with the validation binaries built). The notices'
  lanes 38 passed on lavapipe (debug, the assertion at every draw) and on the UHD 770. The
  pass-open bound passed on the M3 Max under MoltenVK.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
2026-10-19 00:15:59 +03:00
Anees Iqbal bc50be430d Log device memory behind METAL2VULKAN_LOG_MEMORY, keep two empty pooled blocks, pool neutral images on ANV and RADV
Three changes to how the runtime holds device memory, and a diagnostic to see it.

What changes:
- METAL2VULKAN_LOG_MEMORY, a default-off diagnostic (set to anything but empty or 0). A device
  logs one line per VkDeviceMemory it allocates, imports or frees, through its message sink at
  Info severity (id metal2vulkan-memory), else on stderr: what it is (a pooled or dedicated block,
  a host-memory import with its host address, a dma-buf import), its handle, memory type, bytes
  and device address range. Memory with the device-address flag but no buffer of addresses is
  asked through a buffer made over it and destroyed at once; on NVIDIA that address is the GPU
  virtual address a fault report names. A block parked until the batches in flight complete is
  named as it starts to wait. Each pooled placement of at least 4 MiB also prints a line as it is
  placed and as it is returned. Off, nothing changes: the switch is read once, no buffer is made
  and no line formatted. Documented in env_vars.rs and docs/API.md.
- A pool keeps up to two empty pooled blocks (at most 128 MiB a pool), where it kept one. Every
  kept empty block but one goes once it stayed empty for one second, checked as a placement
  returns, and every kept empty block of a memory type goes before a block of that type fails to
  be made, and the make is tried again. New WorkCounts pooled_memory_blocks_made and
  pooled_memory_blocks_freed.
- Neutral images and interlocked passes' storage placeholders take a pooled block of images on
  ANV and RADV, and a block of their own elsewhere (memory::binds_wait, from the driver id).

Why:
- An RTX 5080 run of the consumer lost its device on a copy engine's write to an unmapped page,
  and the fault report names only a GPU virtual address; the log places it against the memory the
  runtime held.
- With one kept empty block, the block made so the encodings find room was mostly the kept one,
  so a frame's buffers returned each frame cost a vkAllocateMemory and a vkFreeMemory a frame (a
  guest boot on ANV showed the alternation in its buffer pool through the log).
- ANV on i915 and RADV on amdgpu list every VkDeviceMemory in every kernel submission at a cost
  per object; in the consumer's frames on the UHD 770 those images were 15 of the 17 dedicated
  blocks. A bind into a block with queued work waits for that work on NVIDIA's driver, and
  lavapipe waits for its queue lock at the view's making, so those keep their own blocks.

Verified:
- tests/memory_log.rs (device test): a block's address asked through a buffer made over it equals
  its buffer of addresses' address; a CPU test holds a placement line's words.
- runtime_lane::pool_churn (new): seven 9 MiB private buffers a frame, filled, waited for and
  dropped; over 32 frames no pooled block made or freed. Blocks made and freed a frame went 1.00 /
  1.00 -> 0.00 / 0.00 on RADV (RX 7900 XTX) and ANV (UHD 770); the test took 1.20 and 0.96 s
  before and 0.52 and 0.47 s after on ANV. tests::memory (17) passed.
- A probe outside the runtime measured a bind into a block with pending work at 0.2-1.8 us and
  the view at 1.8-5.1 us on ANV (UHD 770), 0.0-0.6 us and 0.6-2.0 us on RADV (Radeon 780M and RX
  7900 XTX), the submission still pending after both, as with a fresh block. The kernel_textures
  neutral lane now checks that a pipeline state's neutral images add no dedicated block on ANV and
  RADV; it, the first-use neutral lane and the placeholder framebuffer lane passed on the UHD 770;
  the runtime's heap and memory unit tests 83 passed.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
2026-10-19 00:15:59 +03:00
Anees Iqbal efe0d2ad4a Accept the offset-less form of a 2D or 3D texture atomic by its declaration
The AIR that macOS 26.6.1's Metal on x86-64 hands its device, for a library whose own
declarations pass it so, leaves the offset position out of every 2D, 2D array and 3D texture
atomic:

  air.atomic_fetch_max_explicit_texture_2d.u.v4i32
    v4i32 (ptr addrspace(1), <2 x i32> coord, <4 x i32> value, i32, i32)

where Xcode's AIR passes (tex, coord, <2 x i32> offset, value, order, access). The decoder knew
only the offset form, so the declaration classified as a mismatch and the guest's
newComputePipelineState failed (18 of the 38 texture atomic cells of a sweep on the RTX 5080).

What changes: Texture::alternative() offers a legacy template for a 2D or 3D atomic, as for the
legacy texture read, and its layout leaves the offset out. classify() tries the current form, then
the legacy one, so the declaration picks the form. The lowering already treats a missing offset as
zero. 1D, 1D array and buffer atomics keep their one offset-less form.

Why: these are valid declarations Metal accepts; refusing them failed the guest's pipelines.

Verified:
- families_tests::atomic_forms_are_chosen_by_the_declaration: every operation (fetch ops,
  exchange, load, store, compare_exchange_weak, the ulong max, 16-bit coordinates) on 2D, 2D array
  and 3D shapes classifies the offset-less declaration as the legacy form; a 1D atomic declared
  with an extra position stays a mismatch.
- engine_texture_atomic_unk::legacy_texture_atomics_without_the_offset_compile_alike: our own
  fixtures, rewritten at test time without the offset, compile on the same profiles as the
  originals with the same strategies, image atomic opcode counts and image formats.
- The release command line translated the five libraries the guest's sweep dumped on the RTX 5080
  laptop profile; the owned verifier and spirv-val (vulkan1.2 and vulkan1.4) passed. The guest's
  libraries were read only on the host that ran them; nothing of them is committed.
- clippy -D warnings (plain and m2v_gpu) and nextest --no-run on gem10.
2026-10-19 00:15:59 +03:00
Anees Iqbal 25e4162cf6 Write, sample and resolve 8-bit sRGB and RGB9E5 textures through UNORM or integer views with Metal's codes
Where a device cannot store, sample or render an 8-bit sRGB or shared-exponent format directly,
the texture now goes through a view of a format the device does handle, and the shader applies
Metal's own encode or decode. Before, these textures were refused or read wrong values with no
notice.

What changes:
- Storage. An R8Unorm_sRGB or RG8Unorm_sRGB storage texture on a device without sRGB storage (the
  RTX 5080) writes through its R8_UNORM or R8G8_UNORM view with Metal's sRGB encode, and a
  read_write read decodes through Metal's table, as RGBA8Unorm_sRGB already did. The sRGB format
  stays the image's own wherever the device holds it, so the texture keeps its render-target
  usage; the UNORM twin is the image's format only where the device holds no sRGB image at all.
  A BGRA8Unorm_sRGB storage texture whose twin needs storage access without a format (ARL,
  Pascal, ANV on the Iris Xe for read_write) falls back to an Rgba8 view that encodes, then swaps
  red and blue (StorageImageClass::SrgbEncodeBgra).
- Shared exponent. An RGB9E5Float storage slot takes a new class, SharedExponentBits, on every
  device: an R32_UINT view whose word the shader computes in integer arithmetic with Metal's
  truncating encode, since Vulkan's conversion rounds each mantissa up where Metal truncates.
- Sampling. A device that samples an sRGB format's UNORM twin but not the format (the RTX 5080
  with RG8Unorm_sRGB) samples the twin, and the function decodes with Metal's table (a new
  srgb_twins variant set), announced SrgbTexelDecode. A swizzle that moves alpha into a colour
  channel, or a colour into alpha, decodes before swizzling. A float gather decodes by Metal's
  table on every device without Metal's own sampler unit. Under SamplingPolicy::Exact a runtime
  sampler's one-texel sample reads the slot's raw view and decodes its code through Metal's table.
  Device::pixel_format_capabilities answers Filter for such a texture by the twin's filter.
- Resolves. The exact shader resolve of an 8-bit sRGB attachment reads its samples and writes its
  result through views in the UNORM twin, so codes move as an 8-bit unorm channel's do, with no
  midpoint or linear-value table. The stored codes are unchanged.
- Docs: the FAST-PATHS native sRGB row covers the twin's filtered sample (exact for one texel and
  adjacent codes, up to 0.286 off between codes 0 and 255); known gaps scope a runtime sampler's
  nearest sample under native sampling.

Why: the consumer's guest on the RTX 5080 refused kernel writes to these formats and pipelines
sampling them, and an in-guest comparison under exact sampling showed BC sRGB cells off.

Metal's rules, probed on the M3 Max under macOS 27.0.1: an sRGB write clamps to [0, 1], scales by
4095 to nearest even and stores the largest code whose table step is at most that index, alpha
x255 to nearest even; a read is step / 4095. An RGB9E5 write clamps each channel to [0, 65408],
takes the exponent of the largest and truncates each mantissa; 0 of 65,536 float and 65,536 half
texels off, and every read exact.

Verified:
- New lane runtime_lane::shared_exponent_storage, and srgb_storage widened to R8 and RG8 and to a
  device without storage access without a format (lavapipe), against Metal's bytes.
- On the Iris Xe (ANV): runtime_lane::resolve_rounding 5 passed, 0 channels off Metal's rule for
  every closed format at 2 and 4 samples, sRGB included; the runtime's own BGRA8UnormSRGB 4x
  resolve at 1080p went from about 2.2x an RGBA8Unorm resolve's GPU time to about the same
  (2138 -> 1635 us for the write side alone, edge-dense 4193 -> 2638 us).
- Translator unit filters on gem10: 42 of 42 (shared exponent, image plans, storage choices), 58
  of 58 (sRGB raw, fast paths, the sRGB filter), 251 (sRGB, linear and sampler, the raw one-texel
  sample tests among them, which fail without the change), bind::color_resolve 25 passed; runtime
  image_plan 31 of 31.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
2026-10-19 00:15:59 +03:00
Anees Iqbal 5c799f55e3 Keep a render encoder's bind state across draws and encoders, re-reading only what changed
A render encoder's draws now carry their bind state forward and do again only the work a call or
a buffer move made necessary. The Vulkan calls, their arguments and order, and every
Metal-visible result are those of a draw that worked everything out afresh.

What changes:
- The kept bind state (live_bind.rs) and the bind memo of image views and sampler descriptions
  (binding::BindMemo) outlive their encoder: an ended render encoder gives both to its device
  (at most four of each, in the shared cell its draws lock), and the next render encoder starts
  from them. The memo keeps a view by its texture's address with the texture held weakly, so it
  keeps no texture alive.
- Up to seven more bind states are set aside, one for each pipeline state the encoder drew
  lately, so a draw that switches back to a pipeline state starts from that state's own, its
  shape kept and its tables read through its own interface.
- A draw's bind shape is kept where it changes only values no shape reads (a stencil reference,
  blend color, depth/stencil state, viewport count, heap placement and the like).
- Stage tables carry a stamp drawn afresh at every call that may change what they bind; a table
  whose stamp, interface, address-mode maps and the process's count of no-copy buffer moves are
  those it was read at is not read or retained again. Debug builds still check every skipped
  table whole against the kept one.
- A draw whose stages, uses and resident keys are the last noted command's is not noted in its
  encoder again; its host-alias uses are worked out only for a draw that is noted.
- The device's sampler states are taken only where one was made or went since the listing (a
  count of their slots' changes); a texture's binding facts are worked out at its first read and
  kept; a command's first use of a resource is held inline.
- A draw's uses, descriptor writes, pushed set 0 and vertex buffers are written over the last
  draw's storage in the kept bind state; its colour sets (zeroed, dropped, interlocked, the
  extended-range shadows) are compared in place and copied only where they differ; its zeroed and
  dropped colours are read where the encoder keeps them, copying none.
- WorkCounts: draw_shapes_found, argument_samplers_taken, bind_views_worked_out,
  stage_tables_read and commands_noted_as_before, printed per frame by runtime_lane::frame_costs,
  which gains the repeating and resident benches. Its draw allocation bounds drop to the new
  counts, so they fail without these cuts.

Why: the consumer's guest spends most of its encoding thread in draws. In its profiles the work
these cuts remove (stage-table reads, retains, use notes, shape lookups at pipeline switches,
sampler and view lookups) was several percent of the thread, and the shape lookups alone about
0.55 ms of a frame's 1.22 ms in settle_draw. The answers rarely change between draws: 43% of an
Iris guest's draws follow a draw with no call between them.

Verified:
- Release A/B on frame_costs benches, medians: on the Iris Xe (ANV), a draw's user-space
  instructions 50.95k -> 49.83k for the kept state, 55.3k -> 54.4k for the sampler and fact cut,
  and a frame's 29.76M -> 28.68M (-3.6%) on the repeating bench; on the UHD 770, -1.2..-1.7% a
  draw for the kept vectors and -2.3% a draw for the in-place colour sets; on the RX 7900 XTX
  (RADV), frame CPU 4.99 -> 4.82 ms for the kept state and -1.2..-2.4% a draw for the kept
  vectors. Shapes found a frame 201 -> 134 on the plain bench with the set-aside states.
- Allocations a draw (counting allocator): 24.60 -> 23.60 on RADV for the kept state, 30.13 ->
  27.13 on Iris for the sampler and fact cut, 9.55 -> 6.55 on ANV for the kept vectors.
- New lane tests in runtime_lane::draw_work (shapes kept under value changes and across pipeline
  switches, sampler states taken only on change, no view worked out by a pass binding as the one
  before, tables read only where a call changed them, no colour set copied), render_arguments
  (draws reaching a resident buffer noted once: fails without the change on the RX 7900 XTX under
  the validation layer), address_maps (rebinding between a mapped texture and its twin keeps each
  view and sampler), and unit tests texture_facts, noted_apart and host_aliases. The draw_work
  lane passed on ANV (release, 22 tests) and lavapipe (debug); the bind memo test 5 runs each on
  the RX 7900 XTX and Radeon 780M.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc. The guest's gain was estimated
  from its profiles, not measured in the guest.
2026-10-19 00:15:59 +03:00
Anees Iqbal 8584aa58b8 Give the half-rounding row's cost as measured on the RTX 3090, a GPU the row covers
docs/FAST-PATHS.md's half-rounding row (a half result computed in float rounds through the
device's conversion, not Metal's integer rounding) quoted its cost on the RTX 5080. Its cost cell
now gives the RTX 3090's, on NVIDIA 615.71.09 with DriverWorkaround::HalfConversionPairFolded,
where the row applies. Every NVIDIA GPU on the proprietary driver keeps that workaround; translation
is unchanged.

The cell, default against HalfRoundingPolicy::Exact, median created time and GPU time per draw:
- A2X: 1.39-1.42 s -> 10.09-10.14 s; GPU 0.137-0.153 -> 1.27-1.36 ms;
- Xgc14: 1.15-1.16 -> 1.16-1.19 s; Xgc15 (three states): 0.81-0.87 -> 0.82-0.86 s; GPU unchanged.
Peak RSS for A2X went from 0.55 to 0.83 GB.

Why: a ledger row's cost should be measured on a GPU the row covers.

Verified: measured with scripts/making-bench on gem10's RTX 3090, two release corpus-draw-ab
builds (the default, and a measurement-only build whose default half rounding is Exact, never
committed); each state made cold in its own process, two combos each, 10 timed draws.
2026-10-19 00:15:59 +03:00
Anees Iqbal 930d746df7 Read ASTC, ETC2/EAC, PVRTC and 4:2:2 textures the device lacks through twins of Metal's decode
On a device without a texture's compressed or chroma format, the runtime now makes the texture and
reads it as Metal does. Before, such a texture was refused at its making (ASTC, ETC2/EAC) or at its
first read (PVRTC, 4:2:2, held for copies alone). The consumer's guest on the RTX 5080 stopped at
ASTC_8x8_LDR, PVRTC_RGB_2BPP and EAC_R11Unorm. NVIDIA, RADV and lavapipe have none of these formats,
and Vulkan's 4:2:2 formats need a sampler Y'CbCr conversion whose chroma reconstruction is the
implementation's.

What changes:
- The store. The blocks lie in a carrier image of the same block bytes and shape (a compressed
  format the device copies: BC1, BC4, BC7, BC3, BC2, BC5, ETC2, EAC or ASTC 4x4; R8G8 for 4:2:2).
  replace_region, get_bytes, blits, fills and texture copies move Metal's blocks unchanged.
- The twin. Reads go to a decoded twin holding Metal's decode, kept in step on the GPU as a BC
  texture's twin is: a decode pass after a blit, a texture copy or a submitted CPU copy, and a CPU
  decode on the device's decode thread after a host write. No write costs a GPU-to-CPU round trip.
  A write's decode covers whole levels for PVRTC and whole rows for 4:2:2, whose texels read their
  neighbours. A new texture's twin starts at the decode of zero blocks (magenta for ASTC's error
  block), not at zeros.
- The decoders, our own, written from the Khronos ASTC specification, the Khronos Data Format
  Specification's ETC2 and EAC chapters, and Metal's measured answers for PVRTC1 and 4:2:2:
  bind::AstcDecode, EtcDecode, PvrtcDecode and ChromaDecode, with their GPU kernels
  astc_decode_module, etc_decode_module, pvrtc_decode_module and chroma_decode_module on the block
  decode's bindings (new api_surface rows, with AstcTexels, EtcTexels and DecodedTexelsPolicy).
- Metal's decode, matched: an ASTC LDR channel is (C >> 4) / 4095 of the 16-bit interpolated C;
  an 8-bit ETC2/EAC channel c / 255, an 11-bit one c / 2047 (signed c / 1023); PVRTC upscales
  colours A and B from the four block centres around a texel and blends them by its index; a 4:2:2
  texel takes its own green, and red and blue (3c + n + 2) >> 2 of its pair and the pair beside it.
- sRGB forms. The ASTC, PVRTC and ETC2/EAC sRGB formats read their twin's codes raw through an
  R8G8B8A8_UNORM view and decode them through Metal's table, as the 8-bit and BC sRGB formats do:
  reads, nearest samples and gathers exact, with no precision notice. Linear samples keep the
  device's sRGB filter (the exact sum under SamplingPolicy::Exact). A device that has the ASTC
  block keeps its own sRGB decode. The linear PVRTC and 8-bit linear ETC2/EAC formats take BC1 to
  BC3's Argb8 texel class, so under TexelConversionPolicy::Exact their reads are Metal's c / 255.
- The switch: DevicePolicy::decoded_texels, DecodedTexelsPolicy { Compact (default), Exact };
  exact_answers() selects Exact. Compact holds an ASTC LDR twin in 8-bit codes nearest Metal's
  12-bit value (at most 1/510 off) and an EAC 11-bit twin in the nearest 16-bit codes, announced
  decoded-texel-precision. Exact holds their floats. PVRTC, the 8-bit ETC2/EAC formats, the ASTC
  sRGB formats and 4:2:2 are exact under both. Tested by fast_paths; a FAST-PATHS row.
- Views in the other colour space. An ASTC texture viewed in its other colour space reads a second
  twin, made at the first such view: Metal reads that view exactly as a texture of the view's
  format over the same blocks, and the two forms widen endpoints apart, so one twin cannot serve
  both. Its decodes are queued on the device and recorded by the next batch with work. Counted by
  WorkCounts::second_twins, second_twin_checks and second_twin_decodes. PVRTC and 8-bit ETC2/EAC
  views of the other colour space share the one twin.
- Copies between a compressed texture and an uncompressed one whose texel is the block's bytes
  (BC1 or ETC2 with RG32Uint, BC7 or ASTC with RGBA32Uint) run with Metal's rule: every coordinate
  in the destination's texels, a block per texel. They were refused as formats of different units.
- Notices: carried-decoded-twin (Performance) on every twinned texture; decoded-texel-precision
  (Precision) only for an ASTC LDR or EAC 11-bit twin under Compact.
- Typed refusals: RuntimeGap::DecodedHeapTexture (a heap's ASTC texture, a sparse heap's carried
  texture; the heap size query refuses alike); views of the ASTC HDR form, of another footprint or
  PVRTC block, and of an EAC 11-bit format as its other signedness (Unsupported(TextureView));
  copies between PVRTC and an uncompressed format, between two compressed formats of one block size
  and different extents, and level or slice copies between compressed and uncompressed formats
  (NotImplemented(Format)). A device with the native format keeps the direct path.
- Docs: the API.md catalogue entries, the FAST-PATHS decoded_texels row and known gaps, and the
  module docs of astc.rs, etc.rs, pvrtc.rs, chroma_pairs.rs and decoded_twin.rs.

Why: Metal makes, reads and samples these textures on Apple GPUs, and the consumer's guest uses
them; the desktop Vulkan drivers have no such formats.

Verified:
- Metal's answers, probed on an M3 Max under macOS 27.0.1: ASTC (seeded random blocks, all 14
  footprints, linear and sRGB, read as float and half) bit for bit, digests pinned by
  seeded_blocks_read_as_metal_read_them; ETC2/EAC (4096 random blocks of each of the ten formats)
  digests equal; PVRTC (all eight formats) every digest equal; 4:2:2 every read, sample and gather
  bit for bit what an RGBA8Unorm texture of the decoded codes answers; the copy rule on every listed
  pair both ways.
- On the CPU SPIR-V interpreter each GPU kernel writes the CPU decode on every texel: ASTC on every
  footprint, linear and sRGB, Float and Unorm8, with blocks covering all 16 endpoint modes, every
  partition count, dual plane and void extent; ETC on every decode and both texel forms; PVRTC on
  every format. The kernels are valid on every committed profile.
- Runtime unit filters 63 passed and translator unit filters 183 passed (ETC2/EAC); the runtime's
  unit suite 952 of 953 (the one failure the recorder's module-list test, fixed with the recorder).
- On lavapipe: chroma_pairs, pvrtc_textures, the mipmap, fill, buffer-texture and degrade-notice
  lanes, 45 passed; format_copies, the whole module. A lavapipe batch caught PVRTC codes read one
  ulp high under exact answers, fixed by the Argb8 class.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc on ms01 and gem10.
2026-10-19 00:15:59 +03:00
Anees Iqbal 6b322fb50f Cut the cold making of half-heavy shaders on ANV and RADV: controlled half rounding and the device's half widening
On Intel's ANV, CoreAnimation's A2Xghfc fragment shader (313k words) took
about 14 s to make cold, for each of three states. The consumer's x86 macOS
guest stalled with "no completion in 10 s" on its first boot. Native Metal
makes it in 0.48-0.56 s on the M3. brw (Mesa's Intel backend) spends that
time in its register allocator. Its interference build is quadratic in
instruction count, it spills, and it retries several scheduling modes. Most
of its input was our half arithmetic. Two cuts, each the cheaper form, are
taken on ANV and RADV.

1. A half result computed in float rounds through the device's conversion
   pair under the float controls (QuantizeForm::Controlled). It replaces
   OpQuantizeToF16 plus a denormal arm, about 11 NIR operations per lane.
   - The form: an OpFConvert to 16 bits and back, each decorated
     NoContraction, in an entry that declares RoundingModeRTE,
     DenormPreserve and SignedZeroInfNanPreserve for 16 bits, plus the
     modes the device's independence ties to them (ANV: RTE for 32 and 64
     bits; RADV: RTE and DenormPreserve for 64 bits). The modes are
     declared post-lowering (new ExecMode kinds), and the requirements
     carry the FloatControl properties.
   - Exact by the Vulkan spec under either HalfRoundingPolicy: conversions
     are correctly rounded, and NoContraction forbids folding the pair. No
     fact, no note.
   - A new DriverWorkaround, HalfConversionPairFolded, keyed on NVIDIA's
     proprietary driver, keeps NVIDIA on its previous forms. NVIDIA
     615.71.09 on the RTX 3090 folds the pair even under NoContraction and
     every mode combination, and the PackHalf2x16 and u16-bitcast forms
     fold the same way: 2,231,288,832 of 2^32 narrowings unrounded. A
     plain-Vulkan repro gives 16,775,680 of 2^24 unrounded on the 3090 and
     0 on ANV.
2. A half read from its bits (a load, a reinterpretation, a texel's bits) is
   the device's widening under NanMinMaxPolicy::Native, the default: each
   u32 lane is bitcast to f16x2 and converted to 32 bits, in place of a
   12-op integer decode. A half texel takes that conversion's NaN (no keep).
   - Every non-NaN half is exact by the spec: DenormPreserve covers
     "values obtained via unpacking an integer into a vector of values
     with smaller bit width".
   - A NaN's bits are the device's, recorded as NativeNanEncoding
     (native-nan-encoding), now also announced on ANV and RADV pipelines
     that decode halves. A half stored back unchanged keeps its bits.
   - NanMinMaxPolicy::Exact keeps the integer decode and the keep. There,
     every half widened to float answers Metal's 0x7fc00000 for a NaN, as
     the M3 does over every pattern from memory, constant memory, selects
     and texels.

Where brw's time went, measured on A2X (a2x-s96): after cut 1, 49.6k NIR
operations, of which the rounding pairs were about 10.7k, half decodes from
memory 8.6k and texel NaN keeps 2.6k. The rest was below 5% each.

Exactness probes:
- Cut 1 (candidate half(x) over all 2^32 f32, and half + - * over every
  pair): 0 non-NaN mismatches on ANV Iris Xe (Mesa 26.2.4), RADV 780M
  (Mesa 26.2.4), and the 780M and RX 7900 XTX (Mesa 26.0.8).
- Cut 2 (every half pattern): 0 non-NaN differences on ANV and RADV.
- The M3 confirms Metal equals the integer reference everywhere.

Cold making (A2X, base against each cut):
- ANV Iris Xe: 13.6-14.3 s, then 5.75-6.16 s, then 4.06-4.36 s. Peak RSS
  1.28 GB, then 0.50, then 0.35. GPU time per draw 4.62 -> 4.48 ms.
- RADV 780M: 0.80-0.84 s, then 0.53-0.55 s, then 0.38-0.47 s. GPU time per
  draw 4.05 -> 3.43 ms after cut 1, then within its clock states' spread.
In the consumer's cold boots on ms01 (Iris Xe), A2X went from 14 s per
state, plus two 38 s remakes, to 4.0-4.3 s. The suite's pipeline making went
from 126 s to 16.7 s, with no stall. Repeat boots show metalwin unaffected:
its frame rate follows other GPU work at session start, not this change.

Tests:
- engine_native_half: the controlled conversion, and a half read from memory
  under both NaN settings, NaNs stored back.
- device::tests::profile::nvidia_carries_the_folded_half_conversion_pair.
- lower::arith::tests: narrow, round_texel, half_texel, texel_round.
- spirv::requirements; spirv::builder::ops.
- Updated expectations: engine_arith half rounding, engine_spirv_cross_forms
  fma, engine_metal_routines frexp (the device's NaN under the default,
  Metal's under Exact).
- The validation lanes driver_deviations and native_maths expect the
  controlled form.

Docs: the FAST-PATHS half-rounding row (scope) and a new row for the
widening; the NativeHalfConversion and NativeNanEncoding entries in API.md and
their rustdoc; HalfRoundingPolicy and NanMinMaxPolicy rustdoc; HOWTO's driver
note; REFUSALS regenerated. A known gap is added to the texel-NaN row: on
ANV a 16-bit float NaN texel kept as half reads back 0xFE00 from ANV's image
decode, even under Exact (announced as device-nan-encoding). SEMANTICS_VERSION
1759, runtime pin recomputed, RUNTIME_VERSION unchanged.

Tables: the golden hashes, 274-389 cells on each ANV and RADV column across
both cuts, and NVIDIA's profile fingerprints, whose words are unchanged. The
authored compile census: artifact hashes on the 780M and RPL-P ANV columns,
with no status change. No MoltenVK, lavapipe or floor cell moves.

Verified on development-fast (batches f18-f24): every lane green on the RTX
3090, ANV Iris Xe, RX 7900 XTX, both 780Ms, lavapipe and the M3 Max, plus the
CPU suites, case qualification, clippy in every configuration, docs and
packaging. Not run on the RTX 5080 Laptop (host offline; whether its driver
keeps the pair is unmeasured).
2026-10-17 11:14:51 +03:00
Anees Iqbal b7da00074a Filter a two-plane YCbCr texture with the device's sampler by default, Metal's filter behind YCbCrFilterPolicy::Exact
A draw that bound a two-plane YCbCr texture (YCBCR8_420_2P and its kin) at a
linearly sampled slot made a second VkPipeline at the draw. The slot's YCbCr
variant (RuntimeFact::YCbCrTexture) emulated Metal's filter of the format, and
the state's creation never predicts it, since the predicted key binds no
texture. On ANV, CoreAnimation's A2Xghfc paid 37.8 s for that second making,
inside a command buffer, past the x86 guest's 10 s watchdog.

Under the owner's rule (fast by default, exact on request, both kept, the
difference logged), the default is now the device's own filter. A new
DevicePolicy field, ycbcr_filter, selects the form:

- YCbCrFilterPolicy::Device, the default.
  - On a device that samples natively (ANV, RADV, NVIDIA, lavapipe),
    ProfileFields::ycbcr_variant is false. The slot records no fact and is
    filtered by the device like any other, and a draw takes the pipeline its
    state's creation made. The module's PrecisionNote::DeviceSampling
    (device-sampling) states the bound.
  - On MoltenVK, Metal's own sampler filters the slot's converted view
    (RGBA16Float on the 1/2048 grid, RGBA32Float on 1/8192).
    lower::sampler::linear::metal_filtered_ycbcr records the
    HalfSampleFilter/FloatSampleFilter note under the bound format alone
    (SpecKey::BoundTexelFormat). The runtime's degrade_bound_formats
    announces it as ycbcr-filter-not-exact, naming the slot and the format.
    A one-texel half sample on the 8192 grid records HalfTexelConversion
    under that format and is announced at the draw.
- YCbCrFilterPolicy::Exact keeps the variant: Metal's filter, through one
  pipeline made at the first draw binding such a texture.
  DevicePolicy::exact_answers() sets it. On MoltenVK, SamplingPolicy::Exact
  takes the variant too. Over a compiler limit, the native-sampling fallback
  (ReducedForms) drops it with sampling and reports it.

Bound of the default, in codes of 1/255. Each figure is the largest
difference of any channel over five surfaces (420v/420f; BT.601, BT.709,
BT.2020), 65,536 random coordinates and 960 on the 1/256 grid, float and half
results. Measured against Metal's sum (checked equal to metal_step):
- NVIDIA RTX 3090 (615.71.09): 1.183
- ANV Iris Xe RPL-P (Mesa 26.2.4): 1.058
- RADV 780M and RX 7900 XTX (Mesa 26.0.8): 0.877
- lavapipe (Mesa 26.2.4): 0.872
- MoltenVK against Metal's own YCbCr filter (M3 Max, macOS 27.0.1, plain
  Metal): 0.1245 for RGBA16Float and half results; 0.0157 for RGBA32Float
  float results.

Reproducer (corpus-draw-ab on ANV, cold, a2x-s96 with
RGBA8Unorm:linear@3=YCBCR8_420_2P): before, two pipelines (13.9 s at
creation, 37.8 s at the draw), 52.3 s wall, 3.23 GB. After, one pipeline
(13.9 s), 14.3 s wall, 1.30 GB.

Tests of both settings:
- a_device_takes_the_ycbcr_variant_only_under_the_exact_filter (lavapipe and
  MoltenVK).
- The runtime lane's default tests on native-sampling devices and on
  MoltenVK: no pipeline at the YCbCr draw, bit for bit the RGBA16Float twin's
  draw, the expected announcements once. The exact twins expect the variant.
- fingerprint_covers_every_policy_field.
- metal_s_own_answers_key_the_same_under_either_choice.
- The notes test helper (engine_linear_half::notes_bound) now gives
  BoundTexelFormat the bound texture's class, as the runtime does.

Docs: the FAST-PATHS row and its MoltenVK bound, the API.md
ycbcr-filter-not-exact, device-sampling and half-texel-conversion entries,
the policy, profile-field, fact, lowering and runtime-kind rustdoc, and
REFUSALS regenerated. SEMANTICS_VERSION 1757, RUNTIME_VERSION 1314, runtime
pin recomputed.

Tables: the golden hashes (38 cells per natively sampling column, both tables;
every profile's fingerprint for the new policy field, MoltenVK's again for its
default) and the authored compile census (187 cases on 10 native-sampling
columns, 193 on moltenvk-m3). All are artifact hashes, with no status change.

Verified on development-fast (batches f15-f19, f24): every lane green on the
RTX 3090, ANV Iris Xe, RX 7900 XTX, both 780Ms, lavapipe and the M3 Max
(MoltenVK), plus the CPU suites, case qualification, clippy in every
configuration, docs and packaging. Not run on the RTX 5080 Laptop (host
offline). The consumer measured YCbCrFilterPolicy::Exact on MoltenVK as byte
for byte the previous variant (80 of 80 tests on the M3).
2026-10-17 11:14:19 +03:00
Anees Iqbal 01841476dd Compute Metal's 8-bit unorm blend of a fetched attachment for every factor, mask and blend color
Through the pixel interlock (RADV, ANV, NVIDIA, MoltenVK) a fetched attachment is a storage image,
so the shader computes Metal's blend. For R8Unorm, RG8Unorm, RGBA8Unorm and BGRA8Unorm only
premultiplied source-over with every channel written was built; every other blend, any write mask
that keeps a channel, and the blend color stayed FramebufferFetch / NotImplemented at the color.

What: Blend::unorm8 now plans every factor and operation but the second source's, under any write
mask, with the blend color, through the 16-bit planner's forms as Metal's compiler builds them for
an 8-bit unorm attachment (Family::Unorm8, measured, below):
- an inner sum adds the destination's atoms before the source's (Order::Destination);
- a lerp takes y from the destination's product first; alpha takes no lerp of the destination
  alpha beside itself or held by both products;
- of an added pair, the destination's product is rounded first where unorm8_rank(fs) >= rank(fd)
  (tables per half/float arithmetic and color/alpha);
- alpha shares the one minus the blend alpha, source alpha and destination alpha (SourceAlpha-
  Saturated's too) that stored color lanes compute; with no color channel stored, the one minus
  an alpha the color channels' destination factor is; a min or max computes no factor. A shared
  one minus blocks a lerp of the blend or destination alpha and stays whole where added from the
  destination's product;
- a write mask of one color channel plans that channel as a scalar (Order::Scalar: Da, D, Sa,
  S): no splat rules, but a one minus an alpha that its destination factor is, or that alpha's
  factors compute (alpha stored or not), stays whole and takes no lerp.
blend_unorm8 reads the blend color from PushField::HalfBlendColor's f32 words: NaN to 0, clamped
to [0, 1], rounded to half in half arithmetic; OneMinusBlendColor reads h(1 - h(c)) (f(1 - c) in
float) under either math. fetch.rs pushes the field where the blend reads it and merges the
channels the mask leaves out after the blend, as the 16-bit form does. Because Metal's forms depend
on the mask, compiled_write_mask splits a blended RGBA8Unorm/BGRA8Unorm attachment's partial-mask
class in three (alpha alone, one color channel with or without alpha, two or more color channels);
other formats keep one partial class. Without that split a one-channel mask compiled under the
two-channel class and missed Metal's code in 64 of 4096 texels on the 3090 and the 780M. Without fast math every
state takes the rounded forms. Refused, NotImplemented(FramebufferFetch): a second-source factor;
under fast math a lerp, common factor or contracted pair into R8Unorm or RG8Unorm (Metal sums
those in forms of their own, EV FB8-r8-m3); every other format, now named in FAST-PATHS' known
gap with the source-over survey's result (10-bit unorm and RGBA8Snorm fit the 8-bit model with
their clamps; the 16-bit norms and RGBA32Float blend in float even for half4; their factor sets
are not measured). No PrecisionNote or DevicePolicy kind is added: every built blend is exact.

Metal's arithmetic, plain Metal on the M3 Max (macOS 27.0.1), our own MSL, 512 x 512 targets: every
destination code against every source alpha code (two blocks) plus random blocks with sources out
of range, infinite or NaN; half4 and float4, fast and safe; BGRA8Unorm unless named:
- EV FB8-sw2-m3 (seed 388824, blend color 0.3/0.6/0.9/0.45): every factor/operation pair for color
  beside source-over alpha (676), the reverse (676), and the same pair for both (677).
- EV FB8-rnd1-m3 (seed 424242, color 0.7/0.15/0.55/0.8): 600 random state pairs.
- EV FB8-mk1-m3 (seeds 1000 + mask): masks 1 to 14, 300 random states each.
- EV FB8-bc1-m3 (seeds 2001-2003): blend colors past both ends of every channel.
- EV FB8-sc1-m3 (seed 7): one color channel: all 153 color keys with a lerp or common-factor
  candidate beside 13 alpha keys (none, OMSA, OMDA, OMBA, OMSC, OMDC, OMBC, mixes), masks B and B+A.
- EV FB8-ao1-m3 (seed 9): alpha alone: all 432 alpha keys with a lerp, common or contracted form
  beside 8 color keys.
- EV FB8-mk3-m3 (seeds 1000 + mask): masks 1, 2, 3, 4, 5, 8, 9 under two random sets of 300.
- EV FB8-mm1-m3: a min or max beside one-minus factors, full mask, one channel and alpha alone.
- EV FB8-r8-m3 (seed 3001): R8Unorm and RG8Unorm, same/color/random400: safe math exact in every
  state; fast-math misses only lerp, common and contracted forms; single, fused, zero and min/max
  forms exact in every state.
The model fits every state of each EV (0 mismatched channels), and the Rust planner's plans equal
the model's on 240,480 states (each sweep state under ten masks with and without alpha, plus the
explorer states, half/float x fast/safe), compared through a scratch dump.

Tests: arith::tests::blend8 adds the interpreter over a state of each rule (source alpha over,
the blend color's lerps with a color past both ends, blue alone, alpha alone; half and float, fast
and safe) against hand-written Metal arithmetic, and the no-alpha refusals; tests::engine_fetch_blend8
compiles eight other blends and masks (blend color pushes HalfBlendColor, nothing announced) on
every interlock committed profile and keeps second-source factors refused; engine_fragment's
interlock test now expects RGBA8Unorm's blend computed. runtime_lane::framebuffer_fetch::blend8
adds other_blends_masks_and_the_blend_color_store_metals_blend: the four states into BGRA8Unorm
through each fixture's half4 and float4 loads on the device, every texel against the model.

Verified on gem10 at the content of this commit (WIP a395835, plus REFUSALS regenerated):
- cargo fmt --check; clippy --workspace --all-targets --all-features -D warnings in plain,
  --cfg m2v_gpu and --cfg m2v_cpu_icd; rustdoc -D warnings.
- metal2vulkan nextest -E 'test(/eight_bit|blend8|blend16|fetch/)': 90 of 90 passed.
- metal2vulkan-validation -E 'test(/eight_bit|framebuffer_fetch/)' (release, m2v_gpu) on the RTX
  3090: 56 of 56. Every draw went through the pixel interlock with Metal's 4096/4096 texels and
  nothing announced: the 24 source-over draws and the 16 new ones (four states x two fixtures x
  half4/float4). On lavapipe (m2v_cpu_icd): 56 of 56; the device blends through input attachments
  and announces HalfOutputFastMathBlend and DeviceColorConversion.
- The 780M was held by reims-vgpu at the final run. One run earlier, before the mask-class split,
  it agreed texel for texel with the 3090, including the one-channel miss the split fixes.

SEMANTICS_VERSION 1754 -> 1755: the translation of these blends and the mask classes changes.
RUNTIME_VERSION and the runtime-sources pin are unchanged. docs: the FAST-PATHS known gap (what is
built, what is refused, and the other formats' survey), the API.md degrade catalogue, and
REFUSALS.md regenerated.
2026-10-17 11:13:19 +03:00
Anees Iqbal ea89d3f8ed Mark the project beta in the README
The README's status notice said alpha; the user moved the project to beta. The rest of the notice
(the API, command line, pipeline JSON and SPIR-V may change during 0.x) stands.
2026-10-17 06:44:08 +03:00
Anees Iqbal bc90b127f1 Compute Metal's 8-bit unorm source-over blend of a fetched attachment in the shader
The x86 macOS guest refused a render pipeline on every interlock device (RADV, ANV, NVIDIA,
MoltenVK): framebuffer fetch of a BGRA8Unorm color 0 blended One / OneMinusSourceAlpha (add,
color and alpha, mask 0xf) beside an RGBA16Float color 1 of mask none was
FramebufferFetch / NotImplemented at Color(0). Through the pixel interlock the fetched attachment
is a storage image, so no Vulkan blend applies and the shader must compute Metal's blend; only
the extended-range and 16-bit float blends were built.

What: Blend::unorm8 plans premultiplied source-over into R8Unorm, RG8Unorm, RGBA8Unorm and
BGRA8Unorm storing every channel, half4 and float4 outputs, fast and safe math, through the 16-bit
float planner's forms. blend_unorm8 clamps the output to [0, 1] (NaN to 0), reads the texel's code
exactly (RoundEven(texel * 255), then the existing exact division to f32, then half for a half4
output), and blends in the output's type: fast math fuses (h(fma(d, h(1 - a), s))), safe math
rounds each step (h(s + h(d * h(1 - a))), likewise in float). fetch::unorm8_blended then rounds the
result's code by Metal's 8-bit unorm write (color_write's Unorm{8} rule). The blend takes channels
in Metal's order from read_texel and hands them to emit_return's metal_order exchange, so ANV's
RGBA twin of a BGRA8Unorm attachment takes it unchanged. Any other blend of an 8-bit unorm
attachment, a write mask that keeps one of its channels, and every other format stay refused as
before (FramebufferFetch / NotImplemented). The color write plan treats a shader-blended 8-bit
channel as rounded in the shader, so it records no device-conversion note. No PrecisionNote or
DevicePolicy kind is added: the blend is exact.

Metal's arithmetic, measured with plain Metal on the M3 Max (macOS 27.0.1), our own MSL of the
guest's shape:
- EV FB8-dec1-m3 (seed 1): a fetch of every code reads h(c / 255) as half4 and f(c / 255) as
  float4, every channel of every format. A plain write stores the code of the value clamped to
  [0, 1] (NaN to 0) times 255, the exact product rounded half up.
- EV FB8-sw1-m3 (seeds 1000 * run + (output is float), runs 0 to 3; 4096 x 961 targets): every
  half alpha in [0, 1] (15,361) against every destination code of each channel, four source draws
  per pair (aimed within four ulps of a code midpoint, 2% out of range, infinite or NaN). That is
  63 million channels per variant (BGRA8Unorm, RGBA8Unorm, RG8Unorm, R8Unorm x half4, float4 x
  fast, safe), and the model above gives Metal's code in every channel: 0 mismatches.
- EV FB8-fold1-m3 (seed 7, 2048 x 2048): nine products and sums of the output, the fetched color
  among them, half4 and float4, fast and safe. The clamp keeps all of them out of the blend, so
  fbl8_over_product is exact too (16-bit float folds it).

Tests: arith::tests::blend8 runs the interpreter over every alpha code's value against every
destination code (half and float, fast and safe, BGRA8Unorm and R8Unorm), and checks that another
blend, mask or format is refused. tests::engine_fetch_blend8 compiles the guest's shape on every
interlock committed profile (BGRA8Unorm on each, the ANV profile asserted, no skip) for four
formats and six entries, plus the whole guest pipeline. It asserts the storage form, no note,
link and validation, and that other blends stay refused at Color(0). At d188d8b771 (before this
change) a_blended_eight_bit_unorm_fetch_computes_metals_blend fails with the guest's refusal
("unsupported: FramebufferFetch; needs NotImplemented ... color attachment 0", amd-780m-radv
BGRA8Unorm). The fixtures fbl_fetch_blend8 and fbl_fetch_blend8_safe (our own MSL, regenerated
by scripts/regen-air-fixtures) feed runtime_lane::framebuffer_fetch::blend8, which draws each
entry into the four formats on the device and compares every texel with the model; their
golden printouts (tests/air_input) come from bless_engine_goldens under the pinned LLVM 21.

Verified (gem10, release where a GPU runs):
- clippy --workspace --all-targets --all-features -D warnings in plain, --cfg m2v_gpu and
  --cfg m2v_cpu_icd; rustdoc -D warnings.
- metal2vulkan nextest -E 'test(/eight_bit|blend16|fetch/)': 87 of 87 passed; -E 'test(/air_input/)'
  with METAL2VULKAN_TEST_REQUIRE_PINNED_LLVM=1: 7 of 7 passed.
- metal2vulkan-validation -E 'test(/eight_bit|framebuffer_fetch/)', 55 of 55 passed, on the RTX
  3090 (NVIDIA ICD) and on lavapipe (m2v_cpu_icd, LP_NUM_THREADS=1). On the 3090 every one of
  the 24 fixture x format draws went through the pixel interlock with Metal's 4096/4096 texels
  and nothing announced.

SEMANTICS_VERSION 1753 -> 1754 (translation of this shape changes). RUNTIME_VERSION and the
runtime-sources pin are unchanged. docs: FAST-PATHS known gaps (the interlock blend's coverage),
the API.md degrade catalogue (HalfOutputFastMathBlend), REFUSALS.md regenerated.


The blessed tables come in the same commit: golden_hashes.tsv gains 16 rows for
fbl_fetch_blend8 and fbl_fetch_blend8_safe, public_fixture_expectations_engine.tsv their 16
inventory rows in fixture order, and authored-compile.tsv only its product fingerprint (no cell
moves). Batch verification on development-fast: the fetch and blend filters green on the RX 7900
XTX, the 780M, the Iris Xe, the RTX 3090, lavapipe and the M3; the full suites at the bless green
on the Iris Xe, the XTX, the 780M and the M3 (7259 and 7274 tests). The RTX 5080 was not run.
2026-10-17 06:13:23 +03:00
Anees Iqbal fc9147534d Fetch a BGRA-order attachment through its RGBA twin without format-less reads
On a device that orders framebuffer fetch through the pixel interlock but
has no shaderStorageImageReadWithoutFormat (ANV), a fetched BGRA8Unorm or
BGR10A2Unorm color attachment was refused: SPIR-V names no image format
for B8G8R8A8_UNORM or A2R10G10B10_UNORM_PACK32, so neither the typed nor
the format-less declaration reached it. A guest pipeline of a fetched
BGRA8Unorm color 0 beside an RGBA16Float color 1 was refused on the Iris
Xe and aborted the consumer.

What changed:

- One public decision for the fetch storage view's format,
  StorageAttachmentUse::view_alias_of(format, profile) (the old
  uint_view_of took no profile). An 8-bit sRGB attachment keeps its
  unsigned-integer view. A BGRA-order format the device accesses without
  a format keeps its own format (RADV, NVIDIA, MoltenVK unchanged). One
  no declaration reaches takes its RGBA-order twin (R8G8B8A8_UNORM,
  A2B10G10R10_UNORM_PACK32) where the twin declares and stores. The
  compile layer (lower/fragment/fetch.rs) and the runtime
  (framebuffer_fetch::storage_view_format) both call it.
- The fragment reads and writes such an attachment through the twin,
  exchanging red and blue in the shared read and write helpers
  (read_texel, metal_order), so every read, written value, kept channel
  and per-sample plane sees Metal's channel order.
- The runtime makes the views: a BGRA8Unorm render target's free STORAGE
  candidate is made mutable to the twin (so ANV fetches it in place),
  and stand-ins and sample planes take the twin as their storage view.
- StorageAttachmentUse::format_usages names the view's format (the one
  the storage image is bound in), not the attachment's.
- Public rename: StorageAttachmentUse::uint_view and
  WriteSource::TileAttachment::uint_view become view_alias (serde keeps
  the old name as an alias), with StorageAttachmentUse::with_view_alias
  and view_alias_of.
- The refusal names both routes where neither reaches (a BGR10A2Unorm
  attachment without shaderStorageImageExtendedFormats).

The class, on a device without format-less storage reads: a fetch of a
16-bit packed attachment (B5G6R5Unorm, A1BGR5Unorm, ABGR4Unorm,
BGR5A1Unorm) stays a typed FramebufferFetch refusal, and a read of an
argument buffer's writable texture a typed ArgumentBufferTextures one;
both are FAST-PATHS known gaps. Kernel slots, tile passes and the depth
and stencil stand-ins already declare typed first.

SEMANTICS_VERSION 1753, RUNTIME_VERSION 1313, runtime-sources pin
recomputed. REFUSALS.md regenerated; docs/API.md says which view the
storage form binds.

Verified:

- Metal (M3 Max, macOS 27.0.1, our own MSL probe under the Mac GPU
  lock): BGRA8Unorm and RGBA8Unorm targets, 1x and 4x, masks of every
  channel and of red and alpha, one to three fetch_ordered draws: every
  byte matches the model the device test checks (c read as c/255,
  halved, written as the exact product with 255 rounded to nearest).
- ms01, Iris Xe (ANV, Mesa 26.2.4), release, --cfg m2v_gpu:
  runtime_lane::framebuffer_fetch::bgra passes with Metal's bytes in
  every case beside an RGBA16Float color 1 that keeps its clear. The
  BGRA8Unorm pipelines are made with view_alias R8G8B8A8_UNORM (4
  pipelines); single-sampled targets are fetched in place (no storage
  form switch, no fetch-through-scratch notice), 4x through sample
  planes viewed in R8G8B8A8_UNORM. The fetch lane
  (runtime_lane::framebuffer_fetch::, 47 tests) and
  tests::srgb_fetch_images pass there too: 48 of 48.
- ms01, debug: lower::fragment::fetch::tests (new: the twin on each
  of four ANV profiles for BGRA8Unorm and BGR10A2Unorm at 1x, in planes, under
  reads, writes and a red-and-blue mask; format-less profiles
  unchanged; both routes named; the refused class),
  engine_fragment::a_fetched_bgra_attachment_is_viewed_in_its_rgba_twin
  (the consumer's two-attachment shape on intel-irisxe-anv, 1x, 4x and
  a partial mask, the SPIR-V validated against the profile), with
  engine_fragment, engine_tile, cache::tests, pipeline::api_tests,
  pipeline::link::tests, fast_paths and api_surface: 217 of 217 pass.
  With the twin decision forced off, the five new translator tests
  fail, the consumer shape refused as on the Iris Xe (FramebufferFetch
  needs AnyOf([[ShaderStorageImageReadWithoutFormat]])).
- clippy --workspace --all-targets --all-features -D warnings clean
  plain, with --cfg m2v_gpu and with --cfg m2v_cpu_icd.
2026-10-17 06:13:23 +03:00
Anees Iqbal cc961dc744 Keep zero signs where an Exact answer needs them, and end a busy exit at once on Linux
One squash of development-fast d8546c940b..46649e335d (5 commits); the
tree equals 46649e335d.

- Exact float maths (FloatMathsPolicy::Exact off MoltenVK): a module whose
  checked product, checked OpFmaKHR or fma routine (Wide, Soft, HalfOdd)
  answers Metal's zero of its sign now declares SignedZeroInfNanPreserve at
  the routine's widths, or records DeviceSignedZeroInfNan where the device
  lacks the mode. A fast-math kernel declared no mode, so Vulkan let the
  device answer either zero sign: the RTX 3090 answered -0 where Metal
  answers +0. The default policy and MoltenVK are unchanged.
- Exit on Linux (glibc): an exit while the driver still runs the runtime's
  work (a section, a making, or a CPU device's work) ends at once with the
  exit's status and one line on standard error, as Metal's exit does not
  wait; the exit handlers registered before the runtime's do not run in
  that case (docs/API.md, Process exit). An idle exit is unchanged; macOS
  keeps its waits. The exit lane test expects the new ending.
- The exact golden hashes and the authored compile census re-blessed.

Verified at 46649e335d (batch f10), all green: RTX 5080 7248/7248,
RTX 3090 7248/7248, M3 7263/7263, Iris Xe, RX 7900 XTX and 780M
7248/7248 each, fuzz 8/8 on every venue; lavapipe 3823/3823, product
4824/4824, CPU validation 1331/1331; fmt, clippy (4 configurations),
Rustdoc, packaging, qualification, refusals, the API reference check and
doctests.
2026-10-16 20:54:15 +03:00
Anees Iqbal 20bd3793f3 Exact tiny products and fma, Metal's 16-bit blend zeros and new depth pattern, new notices, the ANV compiler-bound fallback, exit and barrier fixes
One squash of development-fast c66863112e..d8546c940b (27 commits); the
tree equals d8546c940b.

Exact float maths (FloatMathsPolicy::Exact only; the fast default is
unchanged):
- A tiny float product and OpFmaKHR flush to zero as Metal does; the
  native default announces the device's rounding first
  (float-tininess-after-rounding). The check is the compact form; its
  compile cost is recorded in docs/FAST-PATHS.md, and the check's own
  scaling multiply is NoContraction.

Now Metal's:
- A fetched 16-bit float blend's lone term takes Metal's zero under fast
  math (R16Float and RG16Float read alpha as 1).
- A new Private Depth32Float or Depth32Float_Stencil8 target's NaN pattern
  is switched on at the pass that loads it; where the device's test is not
  Metal's it is announced (signed-depth-test), and a clamping device
  announces fresh-pattern-zeroed.
- A render-target barrier from the fragment stage to an earlier stage
  orders the later passes' attachments.

New notices for differences that were silent: unmeasured group
speculation, an anisotropic sampler without mips (MoltenVK), a draw's
attachment read in place, a sample level the device's arithmetic chooses
(exact sampling off MoltenVK), and exact forms dropped to fit ANV's
compiler.

Crash and exit fixes:
- ANV: a render pipeline whose largest stage passes 400,000 words under
  exact forms is retranslated with them dropped until it fits
  (ExactFormsOverCompilerLimit), instead of a SIGSEGV in Mesa's register
  allocator.
- The exit hook sees a making that ends as it looks, and drains a CPU
  device's work at its first run only.

Measurements: the commit hand-off cost on the Iris Xe; the M3 under macOS
27.0.1 places heap blocks and copies compressed textures as the M4 does.

Tests fixed (heap-shadow fence, attachment-read routes, freed-memory
thread, depth pattern per device class, the new kind's lane site) and the
golden hashes, engine inventory and authored compile census blessed.

Verified at d8546c940b (batch f7): RTX 5080, M3, Iris Xe, RX 7900 XTX and
780M green; lavapipe 3822/3822, product 4821/4821, CPU validation
1331/1331, fuzz, fmt, clippy (4 configurations), Rustdoc, packaging,
qualification, refusals and the API reference check green; RTX 3090
7244/7245. Stress soaks of the runtime crate x2 clean on the 5080, XTX,
780M and Iris Xe.

Known open: on the RTX 3090 an Exact checked OpFmaKHR can answer -0 where
Metal answers +0 (the kernel's fast math declares no
SignedZeroInfNanPreserve); the fix is in progress. Not yet run: consumer
boots on this tree and the private-corpus translation census.
2026-10-16 18:45:39 +03:00
Anees Iqbal 29d3ebb22e Fix the consumer's first-move SIGBUS and deallocator fatal, restore the release door, announce the tessellator's triangle order
One commit of the 4 on development-fast (0175289314..c66863112e), squashed at the user's request:
the pin reims-vgpu tested clean.

Runtime:
- A texture's first move over host pages writes back only the bytes the move changed, and only
  where the kernel says the process may write them (mach_vm_region on macOS, the maps query on
  Linux). Before, it wrote back every kept byte: a SIGBUS on read-only pages on MoltenVK, and a
  hang under QEMU, whose handler retried the store. A changed byte over pages the host cannot
  write stays as the move left it, announced (unrestored-first-move-bytes; not observed on any
  venue). WorkCounts::first_move_restored_bytes. HostMemory::new states the Linux contract that
  imported pages stay writable.
- A no-copy buffer released while a submitted command buffer's live buffers' table lists its
  pages runs its deallocator at the release when the caller gave a keep-alive, which keeps the
  pages mapped until the import is freed. Only a release without one waits and announces
  host-deallocator-delayed. Before, the keep-alive case was announced too, which the consumer
  treats as fatal.
- Memory::free_then renamed release_then: it calls no Vulkan entry point, so the release door's
  source scan holds again.
(RUNTIME_VERSION 1303.)

Translator: PrecisionNote::TessellationTriangleOrder, recorded on a pipeline drawn through the
device's tessellation stages where the tessellator is not Apple's
(DriverWorkaround::TessellatorNotMetals): a patch's triangle order, first corners and ring joins
are the device's. The emulation without tessellationShader draws Metal's order and records none.
(SEMANTICS 1740, ARTIFACT_FORMAT 420.)

Docs: API.md's catalogue, FAST-PATHS.md's known gaps, REFUSALS.md.

Verified on development-fast:
- the runtime crate and runtime_lane x3 on the RX 7900 XTX, Radeon 780M and RTX 3090 at
  0175289314 (red only on the release-door scan, then fixed and checked);
- the tessellation note's lanes on the RTX 5080 and M3 (111/111 each);
- the keep-alive lanes on the XTX and 780M (152/152 each), the 5080 and lavapipe, its new test
  failing without the fix;
- both fixes' lanes on lavapipe 197/197, RTX 5080 195/195, Iris Xe 195/195 and M3 194/194; the
  read-only test aborts with SIGBUS on the M3 without the fix;
- reims-vgpu at this tree: cold x86-64 macOS 26 boots clean on the Iris Xe and the 780M, 2711/2711
  of its tests.
Not re-blessed here: the golden hashes' profile fingerprints and tessellation cells that the new
workaround moves; the bless is on development-fast.
The tree is development-fast's at c66863112e.
2026-10-16 13:06:03 +03:00
Anees Iqbal 0175289314 Batch the development-fast round: tessellation without tessellationShader, primitive ids, mesh tooling, color groups, the vk12 floor, runtime timing and teardown fixes
One commit of the 247 on development-fast (720ef1ce9a..9f46fdf80d), squashed at the user's request.

Translator:
- Tessellation on a device without tessellationShader: Metal's tessellator emitted as SPIR-V, a
  one-workgroup scan placing each patch's triangles in Metal's order, and the post-tessellation
  function as a plain vertex stage (EmulatedTessellationDraws; SEMANTICS 1739, ARTIFACT_FORMAT 419).
- [[primitive_id]] on a device without geometry or tessellation shaders, as a flat varying the
  vertex function writes; indexed lists, lines and points drawn de-indexed (RuntimeGap::PrimitiveIdIndices).
- Fragment functions of more colors than the device draws at once, compiled in color groups
  (PrecisionNote::ColorAttachmentGroups).
- Object functions' threadgroup memory from the render encoder; a kernel's mesh draws from an
  indirect command buffer; mesh payload sizing.
- The Vulkan 1.2 floor profile (vk12-floor) and the gates it needs; Metal 27.0.1 answers as the M3 Max.
- Overflow tests in the runtime-built modules by the product's high word (NVIDIA's compiler fails
  the division form), guarded crate-wide by tests::owned_divisions.

Runtime:
- Color-group passes replayed per group over twin depth/stencil; snapshot and copy-back cost cuts.
- Command buffers finish on the queue waiter that saw them; the waiter holds no device handle, so
  a program's drop after its wait is the device's last.
- Every object an encoder was handed held until its command buffer completes; deallocator order
  and announcements.
- Driver defects recorded and announced: ANV counts a visibility sample once per color output
  (visibility-count-per-color); MoltenVK fails pending work when memory that held a device-address
  buffer is freed, so freed memory waits for the work in flight (host-deallocator-delayed).
- RenderCommandEncoder::set_object_threadgroup_memory_length; Visibility::counting().

Validation: mesh tooling (object, mesh and ICB-mesh cases on both executors), the authoring
census closed, the queue storm judged in Metal's unit, load-robust exits and indirect-census
bounds, and the golden hashes, printouts, fixture inventory and authored compile census blessed.

Docs: FAST-PATHS.md trimmed to a ledger of what is true now; API.md's catalogue and accepted
differences, REFUSALS.md and METAL-COVERAGE.md current.

Verified on development-fast before the squash: the full suites on the RTX 5080, RTX 3090,
RX 7900 XTX, Radeon 780M, Iris Xe, lavapipe and the M3 (MoltenVK and the Metal oracle), lint in
every configuration, rustdoc, doc tests, packaging and public case qualification; the timing and
teardown lanes x5 on every venue; the authoring-capability census 16656/16656 with 0 unresolved,
the vk12-floor translation census at 6139 translated with the slowest row 794 ms and peak 126 MiB.
The tree is development-fast's at 9f46fdf80d.
2026-10-16 11:12:03 +03:00
Anees Iqbal 720ef1ce9a Bless the authored compile census, the golden hashes and the fixture expectations
The round's tables, left stale through its work and blessed once at its final tree.

Bless the authored compile census at the batch tree:
corpus/authored-compile.tsv, rewritten by `corpus-triage --audit
authored-compile --bless` at the round's product tree on homelab-ms01 (the private
corpus there, fleet-census's index copy, default --jobs=20).

The census at this tree:
- 2,231 cases x 21 profile-legs = 46,851 cells: 45,530 compiled, 1,321
  refused, 117 uncovered (host-replayed command buffers).
- failed 0, regressions 0.
- Private sources: 1,203 read by the index's byte ranges, 0 by shard.

24 cell moves, all on vk12-floor and roadmap-2022, from the status word
the batch binds by descriptor on a device without buffer device
addresses (fix-status). They equal the dry run's 24 at the macOS 27 work's tip.
- 18 refused -> compiled:
  - FunctionConstantArgument (needs BufferDeviceAddress + ShaderInt64
    on vk12-floor, ShaderInt64 on roadmap-2022): 4 cases x 2 legs = 8.
  - SeqCstFence (same needs): 8 cases on roadmap-2022, 2 on vk12-floor.
- 6 refusals changed on vk12-floor, all SeqCstFence needs
  BufferDeviceAddress + ShaderInt64 -> CoherentMemory needs
  VulkanMemoryModel. What the device truly lacks once the status word
  needs no address.
- No compiled cell refused.

597 artifact= digests of the C3 venues' compiled cells rewritten (412
case lines), and artifacts_at moves to this build:
  product=3918e6c5...fe42e executor=vulkan-engine-v180
  -> product=15b6df4e2bd0cb440724ffe07ba95f1ccf6d0a5dd7fb5055598e70c877596734
     executor=vulkan-engine-v181

Verified on ms01 at the round's product tree:
- the --bless run: 2m29s, peak RSS 267 MB, rc 0, written=true;
- then the census again without --bless: rc 0, differences 0,
  artifacts_at_this_build=true, moved_artifacts 0 (a warm run: every
  cell from the index's cache under this build's census key, 1 s).

Bless the golden hashes and the fixture expectations at the round's final tree:
Both tables were left stale through the round's batches and are blessed once,
here, on macOS (which assembles the .air.ll fixtures with xcrun metal-as):
the golden table by bless_golden_hashes, the expectations table by taking each
failing part's observed rows.

Every key changed in the golden table (each profile's fingerprint moved, the
fixtures' sources too), so the bless's own unchanged-key check covers nothing.
The table was instead checked by value against fd22785008, cell by cell per
fixture, subject and profile:
- 104 cells: fix-status's .ll cells (the execution status bound where the
  device addresses no buffer), each to exactly the value fleet-gate listed;
- 99 cells: their .air.ll twins on the same profiles, each to its .ll twin's
  value (kernel_absent_texture_reads_zero has no twin);
- 127 cells: moltenvk-m3 alone, from the profile's recapture under macOS
  27.0.1, whose deviceID is now MoltenVK's shared Apple identity 0x1B000209.
  Every one now equals its moltenvk-m4 cell (rtl_cube_grad_fragment's two
  among them, refused as UnmeasuredDeviation(GraphicsCubeGradientRoute));
  no moltenvk-m4 cell moved;
- no other value moved; 840 cells are new (xr_bicubic, smw_writers,
  smw_unread and kernel_icb_encode_plain_setters_air_2_5 entries: 440 .ll,
  400 .air.ll), none gone.

The expectations table, by value against both the committed table and
fd22785008: 82 cells in 18 rows, all on lunarg-desktop-baseline-2023,
roadmap-2022, swiftshader, vk12-bare and vk12-floor but the last two:
- 50 .ll cells, fleet-gate's (SeqCstFence -> ok for a27_memory_order,
  a4_device_fence and device_fence_store; function_constant_interface's three
  kernels and rfs_absent_reads' three and kernel_absent_texture_reads_zero
  from Unsupported{FunctionConstantArgument} to ok, or to
  NeedsInput{StorageTextureFormat} on roadmap-2022 and vk12-bare);
- 30 .air.ll twins of function_constant_interface and rfs_absent_reads;
- 2 moltenvk-m3 cells: rtl_cube_grad_fragment's .ll and .air.ll, ok ->
  Unsupported{SamplerAnisotropy; UnmeasuredDeviation(GraphicsCubeGradientRoute)}.
Nothing moved on a profile that addresses buffers; no key is new or gone
against the committed table.

Verified on the M3 Max host (macOS 27.0.1, Xcode 27.0), release build at the round's product tree: the golden bless passed with no fixture skipped, and every
public_fixtures_engine part was run before the update to collect the rows;
the full M3 round on this commit reruns golden_hashes and both table families.
2026-10-14 20:17:45 +03:00