Commit Graph
50 Commits
Author SHA1 Message Date
Anees Iqbal 54e399ca25 Draw indirect mesh grids as Metal does, through an arguments pass on mesh-shader devices
The steps this packet landed as, in order:
- Regenerate the refusal surface after the indirect mesh draws
- Read the task limits through the profile's public limits in the mesh draws lane
- Name VK_EXT_post_depth_coverage in the candidate's enable list
- Re-bless the opened chains, and let a late depth test behind an imageblock writer link
- Withhold the mesh shader extension's features with it in the mesh lane

Content: the tree of `development` at 3e1d7fbbe1, unchanged.
2026-10-26 13:19:06 +02:00
Anees Iqbal 1391e59bce Read uploads from a pointer once, so a guest's bytes need no copy first
The steps this packet landed as, in order:
- Detach lane: take a split's first submission as done as Metal's probe did
- Run protection options as Metal's GPU runs them
- Make compute encoders of raw dispatch types as Metal makes them
- Answer a patch draw's nil buffers as Metal's getters do
- Measure Metal's handler thread cap: the runtime's refusal is where Metal hangs
- Regenerate docs/REFUSALS.md over the second stack

Content: the tree of `development` at e6e5d4b99a, unchanged.
2026-10-26 13:19:06 +02:00
Anees Iqbal 027451fc5f Revoke a queue at its second caused GPU error, as Metal does
The steps this packet landed as, in order:
- Draw private types in a pulled list form where the indexed list differs from Metal

Content: the tree of `development` at d3fc3a5794, unchanged.
2026-10-26 13:19:06 +02:00
Anees Iqbal b26640bac9 Reach every live sampler state by its ID through device-wide sampler tables
The steps this packet landed as, in order:
- Let a host step make the images, render passes, framebuffers and neutrals it needs
- Order a command after a barrier the CPU set once its encoder ended

Content: the tree of `development` at 6584b0e93d, unchanged.
2026-10-26 13:19:06 +02:00
Anees Iqbal 7f50ad492e Run a predicated loop's copies again until the loop ends
Content: the tree of `development` at 61cb931693, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal 537b9caf0c Close host_ab's calls workload, and fit two lane files to the stack
The steps this packet landed as, in order:
- Bump the semantics, artifact format and runtime versions for the stacked review round
- Pin the runtime sources of the stacked review round
- Bless the golden hash tables over the stacked review round

Content: the tree of `development` at 06fe802723, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal a653c11b49 Match Metal's detach timing: per submission, until the handlers ran
Content: the tree of `development` at 281583adb4, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal 123a9919fc List argument samplers at each batch's submission, and retire resource-id-takeover
The steps this packet landed as, in order:
- Refuse the private option bit where Metal ends the process, and take it where Metal ignores it
- Drop the GPU's writes to no-copy memory of the private option bit on macOS
- Let a host step ask the driver for a heap set's layout support
- Run a command that leaves a live sampler state out, announced, instead of failing it
- Record what a read-only view of no-copy pages costs

Content: the tree of `development` at abc094a6c3, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal ee21fca2f4 Write Metal's bytes in texture fills and two-plane buffer blits
The steps this packet landed as, in order:
- Hold RGB10A2Unorm_sRGB textures with Metal's conversions
- Name the runtime's gap, not a missing feature, for fetch on interlock devices
- Take clippy's forms in the RGB10A2Unorm_sRGB tests
- Fill multisample textures' samples as Metal's private fills write them
- Check fill units only for the formats the crate holds textures of
- Hold a two-plane texture's bytes between rows, which Metal's buffer blits read back
- Fill texture buffers as Metal does: bytes of the buffer, the pattern streamed
- Drop the multisample fill from apple_only's refusals, which fills it
- Meet the rows of a two-plane buffer blit into the texture in Metal's order
- Announce narrow two-plane row meetings across groups of 32 rows as one of Metal's

Content: the tree of `development` at 9d3447dec9, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal 9516e41497 Say what an indirect command holds of the pipeline state set on it
The steps this packet landed as, in order:
- Time indirect commands' CPU setters and getters in host_ab
- Read and write one field of an indirect command's record
- Set and read an indirect command's fields one at a time
- Call an indirect execution's check where it may see something, and run the CPU's later writes
- Load vkGetDescriptorSetLayoutSupport inside the exit guard's sections
- Hand out indirect command buffer IDs to 2^31 - 1 and place every one's records, as an M3 Max does
- Refuse an indirect command buffer reservation Metal hangs at as such
- Place an indirect command buffer's records at any length, found only at their start
- Leave a resource ID pool made after a reservation of 0 alone, as Metal does
- Ignore a late reservation call before looking at what it holds, as Metal does
- Expect the merged-draw tests' pipeline makings' notices on every device
- Keep an indirect compute command's threadgroup lengths where Metal keeps them
- Take the pieces of the ICB identifier range Metal's encoders take
- Answer a GPU-written command's state identifier as the state its ID named then
- Run a GPU-written record's released state as Metal does, from the buffer's kept programs
- State and test the bound on the programs a GPU-writable buffer keeps
- Record the earlier-window record of a re-held ID as a known gap

Content: the tree of `development` at 7d31ebb207, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal c83dcdd384 Give the predication step ops that drop, hold and resume a range, and check a unit's end
The steps this packet landed as, in order:
- Answer command predication as Metal does on an M3 Max under macOS 27.0.1
- Probe Metal's command predication from the validation crate's Metal platform
- Wait for the predication probe's command buffers through the bounded wait
- Name the record a predication block left open came from in its command buffer's failure
- Refuse a run's first indirect dispatch of another dispatch type at Metal level 26.7
- Read an encodeEndDoWhile's word only where it closes a live DoWhile
- Run command predication on devices without buffer device addresses
- Nest predicated loops to any depth, their copies bounded by what they lay down
- Read a predication word past its buffer as Metal reads it
- Halt a predication unit where a loop runs past its copies
- Name the lane's fixed loop case type, which clippy found too complex

Content: the tree of `development` at ef8b74ec1b, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal 9adc8a867a Draw Metal's private primitive types 5 to 8 as the lists Metal draws
The steps this packet landed as, in order:
- Test the private primitive types' draws against Metal's lists on the device
- Check the private draws through the weights' geometry stage too
- Use is_multiple_of and as_chunks in the private lists
- Fail a draw of primitive type 9 as Metal's GPU does
- Give the private-types fixture its golden printout and inventory rows
- Discard what a hang's queue schedules during it, and time the hang as measured
- Regenerate REFUSALS for the type-9 runtime changes
- Read Metal's quad primitive ID under private quads and quad strips
- Read a type-9 hang's Scheduled at Metal's time, not at its held last batch
- Schedule a hang's queue's command buffers from the hang's Scheduled on
- Stop a hang's thread waiting on a failed command buffer; keep storage-form commits on their last batch
- Hold a hang's joined command buffers behind a closure, so Rustdoc ends

Content: the tree of `development` at 5441a97bda, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal 787d92fdc2 Answer a heap texture's allocatedSize from the place that holds it
The steps this packet landed as, in order:
- Answer a kept heap texture requirement before asking the device's limits
- Answer whether a command buffer or submission uses given objects, cloning nothing
- List devices' registry IDs without making devices, and open one by its ID
- Give a made pipeline state's reflection from its compile, after its creation
- Enable optional device extensions where each device can, and say which it enabled
- Let a caller vouch for its host pages' write permission, skipping the kernel's answer
- Import read-only host pages from the caller's dma-buf source, and say whether a device takes shared pointers
- Hold a texture of Apple's private usage 0x8 alone to what Metal does with it
- Measure RADV 26.2.4 on the RX 7900 XTX: its pointer imports follow their address
- Free a no-copy buffer's dma-buf imports before its keep-alive goes
- Measure a file's pages mapped under a live RADV pointer import, a known gap
- Let what waits for a dma-buf import's free go as its fields drop

Content: the tree of `development` at 0a38130573, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal 27ad7597c1 Measure dispatches after one useResources in host_ab's encode workload
The steps this packet landed as, in order:
- Take the compute dispatch memo while the encoder's residency is unchanged
- Start a shared event listener's thread at its first notification
- Add a command buffer's scheduled event signal (encodeSignalEventScheduled:value:)
- Count the scheduler's passes, and measure signals, bursts and moving offsets in host_ab
- Hash the pipeline memos with the runtime's key hasher
- Let a dispatch take what its pipeline state last planned for the same shape
- Drop two casts clippy flags in completion_here's scheduled signal check
- State host_ab's dispatches taken as settled and as planned before

Content: the tree of `development` at f9d39326a3, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal 7b8ebc5b3e Use AtomicU64::try_update, the name fetch_update now has
The steps this packet landed as, in order:
- Refuse buffer-texture copy layouts whose rows pass u64::MAX instead of wrapping
- Wait without a deadline for a timeout past the host's clock, and test copies at the buffer's edge
- Place a multisampled buffer copy's rows where plain Metal does, staging off-texel rows
- Say that Metal copies the multisampled layouts the runtime still refuses
- Count the rows a compressed-texture blit rewrites, and test a copy out off the texel

Content: the tree of `development` at e5ff75b136, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal 1d15b13eb7 Complete a queued commit its own work refused
The steps this packet landed as, in order:
- Pin the runtime sources with a refused queued commit's completion

Content: the tree of `development` at a62e8a365f, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal 6da0b55c4b Leave a commit's own work behind a render encoder's end in flight, on request
The steps this packet landed as, in order:
- Regenerate the refusal surface and pin the runtime sources with commits behind the lowering thread

Content: the tree of `development` at 770f8bce10, unchanged.
2026-10-26 13:19:05 +02:00
Anees Iqbal 1505f4f5b3 Lower a render encoder's end on the device's lowering thread, on request
The steps this packet landed as, in order:
- Regenerate the refusal surface and pin the runtime sources with the end on the lowering thread

Content: the tree of `development` at bf576119ea, unchanged.
2026-10-26 13:19:04 +02:00
Anees Iqbal 19ccb91916 Log a render encoder's calls and lower them after they return, on request
The steps this packet landed as, in order:
- Regenerate the refusal surface and pin the runtime sources with the logged render encoder

Content: the tree of `development` at f3cfaa3feb, unchanged.
2026-10-26 13:19:04 +02:00
Anees Iqbal b94953dfa9 Resolve GPU-alone work's resident set at the first submission, not by recording it again
Content: the tree of `development` at 3f5472f696, unchanged.
2026-10-26 13:19:04 +02:00
Anees Iqbal d218c939a4 Encode again at a rebind an encoder whose only host-page use is its end copy back, and its GPU-alone work
Content: the tree of `development` at 3c7d40aea2, unchanged.
2026-10-26 13:19:04 +02:00
Anees Iqbal 8c96577b40 Record GPU-alone work again at a rebind before the first submission
Content: the tree of `development` at adea9e457c, unchanged.
2026-10-26 13:19:04 +02:00
Anees Iqbal 3d9304798d Add host_ab's icb workload: a kernel writes compute commands that a second encoder executes
The steps this packet landed as, in order:
- Run GPU-written compute executions on the GPU alone by indirect dispatches where the device has no generated commands
- Run a concurrent encoder's GPU-alone execution with no barrier between its commands

Content: the tree of `development` at 343b1abcb4, unchanged.
2026-10-26 13:19:04 +02:00
Anees Iqbal 644e055652 Keep a GPU pool's blocks while in use, and release a command buffer's own objects after its handlers
The steps this packet landed as, in order:
- Count the most GPU pool blocks leased at once
- Share one GPU pool block per queue among its command buffers
- Keep an arena's fitted list on the pools a completing command buffer takes out

Content: the tree of `development` at 0a94bc93a0, unchanged.
2026-10-26 13:19:03 +02:00
Anees Iqbal 4d9b17a359 Run a batch's first work in its work's VkSubmitInfo, not one of its own
The steps this packet landed as, in order:
- Count render encoders' render pass instances by where they began, and their splits by cause
- Set the runtime version and pin the runtime sources at the merged tree
- Bless the golden output hashes at the merged tree
- Bless the authored compile census at the merged tree
- Regenerate the refusal surface at the merged tree

Content: the tree of `development` at effa414f26, unchanged.
2026-10-26 13:19:03 +02:00
Anees Iqbal 3926ac1204 host_ab: a compositing workload of the consumer's frame shape; count the VkSubmitInfos submitted
Content: the tree of `development` at 89ca6673eb, unchanged.
2026-10-26 13:19:03 +02:00
Anees Iqbal e320a1f475 Drop design-record, work-package and evidence codes from comments, and retire vk12-bare from the corpus
Comments, fixture notes and docs lose their design-record numbers, work-package codes and evidence
codes; lines that earlier commits of this series added carry their cleaned text there, so this
commit holds the cleanup of lines that predate the series, the retired vk12-bare profile's corpus
rows (a rationale and two observation rows), and docs/FAST-PATHS.md's measurements stated as they
stand. Thirteen hash-keyed files keep their citations, because their bytes are case or record
identities: eight case-keyed .ll fixtures and five parity sources.
Verified: the CPU suites (4997 of 4997 and 1328 of 1328), clippy, rustdoc and doctests.

Folds in:
- Drop evidence codes, design-record numbers and work-package codes from comments and fixture notes
- Drop the retired vk12-bare profile from the corpus
- Say the fast-path ledger's measurements as they stand, without commits, rounds or host incidents
- Keep the case-keyed .ll fixtures byte for byte
- Keep the parity lanes' fingerprinted sources byte for byte
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 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 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 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 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 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 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 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 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 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 e5d1616030 Take a commit left to the scheduler in before its next check, and bound a commit's passes
The scheduler review's work packet: the inbox's and the work loop's fixes, and race tests that catch
a lost wake.

Take a commit left to the scheduler thread in before its next check, and bound a commit's passes:
Four defects in the commit inbox (scheduler/inbox.rs) and the scheduler thread's loop, which
broke the inbox's bound on a commit's wait and Metal's prompt commit:

- A commit left to the scheduler thread during the round that took an earlier one in waited for
  the thread's next check (the program's code) or host step: the thread looked at the inbox once
  before each piece of work, not again after that round. The thread's way through its work is now
  `scheduler/left.rs`'s `work_through`, which makes rounds for as long as the inbox holds commits
  before each piece, generic so that it is tested without a device.
- A committing thread passed again for as long as other threads' commits or wakes kept arriving
  during its passes, so one commit() was unbounded. Its look again now makes at most one pass
  (`inbox::AGAIN`); what is left to that pass with no other passer counted is answered as
  unattended, and `Scheduler::commit` wakes the scheduler thread for it (the wake's code moves into
  `Inbox::wake`, which `Scheduler::wake` and the tests' model share).
- Checks always ran before host steps, and rounds between pieces add checks, so a step (and its
  queue) could wait behind checks found after it. Work now runs in the order rounds found it, a
  round's checks before its steps.
- A pass cleared the nudge with a plain store, so the memory model gave no happens-before from a
  waker's change to the pass that took its nudge in. It is now a swap, which synchronizes with the
  waker's store it reads.

Docs made true again: the inbox's and the scheduler's wait bounds, SubmissionCheck's and
add_submission_handler's "a commit meanwhile still submits", the stall in texture/storage_form.rs
(also after a commit left to another thread's pass), and WorkCounts::queue_submissions (the first
work rides in the batch's call). RUNTIME_VERSION 1188; the runtime-sources pin follows in its own
commit.

Verified on msi-laptop (Linux, Rust 1.98.1), before the rebase onto fleet/round: clippy -p metal2vulkan-runtime --all-targets
--all-features clean; rustdoc of the crate clean; nextest tests::inbox, tests::left and
tests::scheduler 24 of 24. Each new deterministic test fails without its fix: with `if` for
`while` the left commit runs after the first check ([TakenIn(1), Ran(Check, 1), TakenIn(2)...]);
with checks always first a later round's check runs before an earlier round's steps; with the
committer unbounded it makes 5 passes for 4 commits left to it, against 2. A paced stress (4
threads, 6 commits a ms in all, 80 us passes, release) made up to 4 passes in one commit() on the
base (0.1-12% of commits over 2), and at most 2 with this change.

Make the inbox's race tests catch a lost wake, and print the paths they took:
The racing-commits test stopped its model scheduler thread right after the committers ended, and
the stop's own notify would make the thread pass for a commit whose wake was lost, so the test
could not see one. It now waits (up to its 30 s bound) for the thread to have passed every commit
before it stops it, as the wakers' test does for every raise, through a shared `soon`. Both tests
print how often the races took the paths they cover (commits left to another thread and left
unattended; wakes left to a pass under way), as evidence that those paths ran.

Test-only: the runtime sources the pin covers are unchanged.

Verified on msi-laptop: tests::inbox and tests::left pass (see the landing note for counts).

Versions: RUNTIME_VERSION 1196 -> 1197. RUNTIME_VERSION moves: when a commit's work is taken in and
how many passes it makes change. crates/metal2vulkan-validation/runtime-sources.sha256 holds
581e5e5522ddfb5c61d4b949e7b7b01e210925bff898241bcd517ef6fdee40f2, the hash of this tree's runtime
inputs (runtime-pin.py, which reproduces build.rs's). Version numbers quoted above are the values
the work's branch built with. Each part's Verified lines name the tree it ran at.
2026-10-14 20:17:36 +03:00
Anees Iqbal 07abdd4bd9 Fix the encoder review's findings: inherited thread hints, kept barrier lists, draw shapes
The encoder review's work packet: the handler threads' utilization floor no longer reaches the
threads they start, a draw state's used-resources shape is made once, a kept barrier list out of use
gives way to a new one, and a render state's helper threads start with the runtime's own.

Keep the handler threads' utilization floor out of the threads they start, and drop the dead QoS raise:
What: on Linux, exit_guard::run_at_user_interactive (the scheduler, the completion thread, each
VkQueue's waiter, the handler pool) now reads its own attributes with sched_getattr(2) and calls
sched_setattr(2) with the policy it read, without SCHED_FLAG_KEEP_POLICY, and with
SCHED_FLAG_RESET_ON_FORK | SCHED_FLAG_KEEP_PARAMS | SCHED_FLAG_UTIL_CLAMP_MIN, sched_util_min 1024.
The struct is exit_guard::SchedAttr, mutable across the call (a kernel whose struct is shorter writes
its size back before E2BIG), with SAFETY comments that say so. On macOS, raise_quality_of_service is
deleted, with its calls in exit_guard::spawn and spawn_scoped. Docs: spawn, spawn_user_interactive,
the Linux comment (the reset's effect on real-time policy and negative nice, the setting a handler
cannot clear, and the host-wide uclamp accounting the first call turns on until reboot), and the
public Handler, add_scheduled_handler and add_completed_handler (the handler threads'
user-interactive class on macOS, the floor on Linux, and that neither carries into a thread a
handler starts).

Why:
- With KEEP_POLICY the kernel keeps the thread's reset-on-fork setting and ignores RESET_ON_FORK
  (__sched_setscheduler: policy < 0), so uclamp_fork gave every thread a boosted thread starts the
  1024 floor for its life: the pipeline reaper a pipeline state's last release starts on a handler
  thread (Program::drop -> PieceHolds::close -> Reaper::start), the notices thread, pool and
  compile threads a program's call in a handler starts, a program's own thread made in a handler.
  The policy is passed back as read, so SCHED_OTHER, SCHED_BATCH and SCHED_IDLE (a session
  ananicy-cpp moved to SCHED_IDLE) stay as found; KEEP_PARAMS keeps nice, priority and slice.
- raise_quality_of_service never acted. A thread made by pthread_create with no QoS class in its
  attributes starts at QOS_CLASS_DEFAULT (<sys/qos.h> line 83), std::thread sets only the stack size
  (pthread_attr_init + pthread_attr_setstacksize), and every runtime thread runs it first thing on
  such a thread, so its utility-or-background test never held. Its doc said a new thread takes its
  creator's class, which is false. Under a process-wide clamp a new thread still reads DEFAULT and a
  request for DEFAULT changes neither its class nor its priority, so it could not help there either.
  Probe on this Mac (M3 Max, macOS 27.0.1 26A434, cc and rustc 1.98.1), a C program creating
  threads with pthread_attr_init + setstacksize from creators at background, utility, default,
  user-initiated and user-interactive, each new thread reading pthread_get_qos_class_np and
  thread_info's pth_curpri/pth_priority/pth_maxpriority, then calling
  pthread_set_qos_class_self_np(DEFAULT) and reading again:
    plain:                     every new thread 0x15 (DEFAULT), pri 31/31/63, unchanged after
    taskpolicy -c utility:     every new thread 0x15, pri 20/20/20, unchanged after
    taskpolicy -c background:  every new thread 0x15, pri 4/4/4, unchanged after
    taskpolicy -c maintenance: every new thread 0x15, pri 4/4/4, unchanged after
    taskpolicy -b:             every new thread 0x15, pri 4/4/4, unchanged after
    taskpolicy -t 5 -l 5:      every new thread 0x15, pri 31/31/63, unchanged after
    taskpolicy -b -t 5 -l 5:   every new thread 0x15, pri 4/4/4, unchanged after
  and a Rust probe (std::thread::Builder::spawn from creators at each class, reading
  qos_class_self): 0x15 from every creator, plain, under taskpolicy -c background and under
  taskpolicy -b. The core of the C probe:
    static void *child(void *start) {
        qos_class_t c, after; int r;
        pthread_get_qos_class_np(pthread_self(), &c, &r);
        int before = pri();  /* thread_info(THREAD_EXTENDED_INFO) pth_curpri, pth_priority, pth_maxpriority */
        int set = pthread_set_qos_class_self_np(QOS_CLASS_DEFAULT, 0);
        pthread_get_qos_class_np(pthread_self(), &after, &r);
        printf("creator %#x: new thread %#x pri %d; set DEFAULT rc %d -> %#x pri %d\n", ...);
    }
    for each start class: pthread_set_qos_class_self_np(start, 0); pthread_attr_init(&a);
    pthread_attr_setstacksize(&a, 1 << 20); pthread_create(&t, &a, child, ...); pthread_join(t, 0);
- The handler threads' class and floor differ from a plain thread's, which the public items did
  not say (AGENTS.md: name what differs from Metal).

Tests:
- tests::exit_guard::the_threads_that_take_command_buffers_to_their_handlers_run_with_the_
  utilization_floor (new, Linux): from creator threads at SCHED_OTHER, SCHED_BATCH and SCHED_IDLE
  (each it may enter; SCHED_IDLE required), the scheduler, completion, both waiters and two
  handler-pool threads read their own sched_getattr: floor 1024, reset-on-fork set, the creator's
  policy and nice; a thread each starts through exit_guard::spawn reads floor 0, no reset, the same
  policy and nice. On a kernel that refuses the floor it expects none and that the kernel refuses
  one the test asks for itself.
- tests::exit_guard::a_runtime_thread_starts_at_the_default_quality_of_service_whoever_started_it
  (macOS, rewritten from a_runtime_thread_runs_at_no_lower_quality_of_service_than_the_default): a
  plain and a runtime thread from a creator at each class both read DEFAULT. The user-interactive
  test now expects the reaper at DEFAULT.

RUNTIME_VERSION stays: no run's results change. The runtime-sources pin moves in this branch's last
commit (on fleet/base this tree hashed to 3ef35b8d...).

Verified on homelab-um780 (Ryzen 7 7840HS, Linux 7.0.0-38-generic, CONFIG_UCLAMP_TASK=y, Rust
1.98.1, release, RUSTFLAGS='-Dwarnings --cfg m2v_cpu_icd'): cargo nextest run -p
metal2vulkan-runtime -E 'test(/exit_guard::/)': 30 of 30 passed; the new Linux test entered all
three policies (nice 5) and read floor 1024 on the six threads, 0 on their children. With the old
flags (KEEP_POLICY, no RESET_ON_FORK) restored it fails: a boosted thread reads reset false. The validation pin test passed with
3ef35b8d... on fleet/base. The macOS tests are not run here (routed to the Mac).

Make a draw state's used-resources shape once when finding its bind shape among the kept ones:
What: BindState::position_of_shape(shapes) answers where among `shapes` the state's shape is (the
first of which has_shape answers true), making the shape of the resources the state lists at most
once for all of them, and only where a shape's every other field matches; has_shape compares the
used resources last, after every field it compares in place. GraphicsState::kept_shape finds a
draw's shape among its state's latest settles through it. docs/API.md names it beside has_shape.
The crate's test allocator (constant_blob_footprint.rs) also counts allocations
(allocations_during).

Why: kept_shape called has_shape once per kept settle (up to four), under the settles' lock, and
each call made the used-resources map again where the state lists used resources (useResource:,
argument-buffer programs): up to four maps a draw where one does.

Test: tests::bind_shape_of::a_state_s_shape_is_found_among_many_with_its_used_resources_made_once:
a state listing 16 used resources against four shapes equal in every other field, its own last:
position_of_shape allocates as much as one has_shape, and has_shape one by one four times that; a
state listing none, or of another field, makes nothing.

Let a kept barrier list out of use give way to a new one:
What: once a VkQueue keeps LISTS (8) lists of barrier command buffers, a new list replaces the one
taken least lately among those no batch took in the last STALE (256) values of the queue's timeline
and whose command buffers all completed; that list's command buffers become spares, which later
recordings take before allocating. The kept pool is made with RESET_COMMAND_BUFFER, so a spare's
begin resets it. Lists all in use in turn replace none, as before. The choice is
QueueKept::take (Take::Kept, Take::Record, Take::Past), apart from the Vulkan calls in
KeptBarriers::take.

Why: the first 8 distinct lists a queue met kept their places for the device's life, so where a
program's first batches (uploads, first moves) filled them, every later per-frame list was recorded
by its batch, a command buffer begun per batch, for good: the work 4600bc606d set out to remove.
The staleness window keeps lists in use in turn from replacing each other at every use (with more
than 8 of them, the first 8 stay kept, as before).

Tests (tests::kept_barriers, no device: handles the test makes): a list met twice in one batch takes
two command buffers, reused once that batch completed; a failed submission's command buffer waits
for the value the next batch signals in its place; past KEPT pending buffers or LISTS lists in use a
batch records its own; a list out of use gives way to a new one, recorded into its command buffers,
never a list in use or one with a buffer pending; more than LISTS lists in use in turn replace none.
a_list_out_of_use_gives_way_to_a_new_one fails without the change (the new list gets Own, for good).

RUNTIME_VERSION moves: a run submits kept command buffers where it recorded its own.

Test a rebound slot's retain, and keep only the measured bounds in the frame-cost lane:
What: runtime_lane::draw_work::a_slot_rebound_to_a_texture_let_go_after_its_draw_holds_it_until_
completion binds two fragment textures, rebinds slot 0 mid-encoder to a fresh texture the program
drops after its draw, and draws again with nothing changed: ArgumentTable::retain's per-slot check
retains the table at each draw that changed the slot (6 after the first draw), not at one that
changed nothing, and every column is its own draw's texture's under the validation layer.
frame_costs.rs: the doc comments of DRAW_ALLOCATIONS, OPEN_ALLOCATIONS, PASS_END_ALLOCATIONS,
COMMIT_ALLOCATIONS and SUBMIT_ALLOCATIONS keep the measured values and their venues and drop what
each measured before earlier changes.

Why: retain's per-slot address check had no test of a rebind among unchanged slots; and AGENTS.md
keeps history out of code comments (it belongs in the commits that moved the numbers).

No behaviour change.

Start a render state's reflection and log-hash threads as the runtime starts its own:
What: pipeline/render.rs starts the thread that works out a render state's reflection beside its
creation, and the creation log's SPIR-V hashing thread, through exit_guard::spawn_scoped instead of
std::thread::Builder::spawn_scoped.

Why: exit_guard::spawn says every thread the runtime starts is started through it, so the guard
knows it as the runtime's (may_call, in_program_call, the debug check that a runtime thread reaches
the device only inside a section); these two were not. Neither calls the device or the program's
code: the reflection is the translator's, and the hash reads the variant's SPIR-V.

No run's results change.

Say plainly why kept barrier lists in use in turn replace none:
What: the module doc of command_buffer/kept_barriers.rs: where more than LISTS lists are in use in
turn, the first kept stay kept, since replacing one at each use would record every list at each of
its uses.

Why: the sentence it replaces read as if the rest were recorded like a replaced list. Comment only.

Versions: RUNTIME_VERSION 1195 -> 1196. RUNTIME_VERSION moves: kept barrier lists and thread
start-up change what a run does. crates/metal2vulkan-validation/runtime-sources.sha256 holds
e9ed22eb2280cb6f1a7ea8811e3f4b2c2a32bcc5aca217dc670864b84f357848, the hash of this tree's runtime
inputs (runtime-pin.py, which reproduces build.rs's). Version numbers quoted above are the values
the work's branch built with. Each part's Verified lines name the tree it ran at.
2026-10-14 20:17:35 +03:00
Anees Iqbal f99d6b9895 Run the threads that take command buffers to their handlers at user-interactive on macOS
What: on macOS the scheduler thread, the completion thread, each VkQueue's waiter and every
thread of the handler pool (its first and the ones it starts later) request the user-interactive
quality of service as they start, before any work: exit_guard::spawn_user_interactive starts them
as exit_guard::spawn does, then calls pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0)
(<pthread/qos.h>). The compile threads keep their user-initiated raise and every other thread of
the runtime keeps the existing raise to at least the default class. No change elsewhere than
macOS.

Why: Metal runs every command buffer's scheduled and completed handlers at user-interactive,
whatever the class of the committing thread (probe on an M3 Max, macOS 27.0.1: commits from
dispatch queues at user-interactive, user-initiated, default, utility and background; every
handler ran at user-interactive). These threads ran at the default class, where a new pthread
starts (<sys/qos.h>, and seen on this Mac from creators at every class). No CPU affinity, and no
option or environment variable turns it off; the comment at the call says so.

Test: tests::exit_guard::the_threads_that_take_command_buffers_to_their_handlers_run_at_the_
user_interactive_class starts the scheduler, the completion thread with two waiters and the
handler pool from threads at each class, background to user-interactive, and reads each thread's
class from inside it (qos_class_self, through a test-only start hook; the pool's items read their
own). It also checks the reaper runs as exit_guard::spawn starts a thread, below user-interactive.

The runtime-sources pin moves (recomputed over this tree); RUNTIME_VERSION stays, since no
run's results change.

Verified on this Mac (M3 Max, macOS 27.0.1, Rust 1.98.1): cargo nextest run -p
metal2vulkan-runtime --all-features, 869 of 869 passed, the new test among them, and the existing
compile-thread and pipeline-pool class tests unchanged and passing; the new test fails with the
old class (the scheduler read 0x15, default, against 0x21, user-interactive); cargo check
--workspace --all-targets --all-features, plain and with RUSTFLAGS='--cfg m2v_gpu', clean. No MoltenVK lane or latency run (skipped at the user's request).
2026-10-14 12:34:30 +03:00
Anees Iqbal bd21b102f5 Cut a draw's and a pass open's allocations
Compare a draw's graphics key in place, keep a drawing state's routing for the pass colors it last
met, write descriptors from the stack and allocate the set in place, keep a draw's small lists on
the stack, hold what a draw retains by reference in one entry per encoder, find a draw's bind shape
among its state's settles, fill push bytes in place, bound coverage without allocating, gather named
keys only once a draw reaches the resident set, compare viewport compensations as they come, list
argument samplers again only where the device's changed, and keep each pass shape's compatible
render pass on the device (up to 64 shapes). The frame-cost lane bounds a draw at 27 allocations and
a pass open at 14.

Gain: allocations per draw from 67.5 to 24.5 and per pass open from 18 to 13 on RADV, ANV and
lavapipe. Frame CPU on ANV (Iris Xe), clean rounds: 5.66 -> 5.02 ms.

Verified on the original branch: the runtime lanes, 1313 of 1313 on RADV, ANV and lavapipe. This
squashed commit (with the wake fix under it) was not re-tested on its own.
2026-10-14 12:15:47 +03:00
Anees Iqbal 35fb5fd962 Cut a commit's CPU on the committing and the scheduler threads
Plan each batch's hazards without per-resource allocations or a sweep of the hazard state, plan a
batch of one encoder against that state itself, list only what a commit reaches unnamed among the
live buffers, and keep the scheduler order's emptied lines and head list between passes. The
frame-cost lane measures a checked frame's commits on both threads and bounds their allocations.

Gain: commit p50 about 40% lower; 19 -> 5 allocations a commit on the committing thread and 46.9 ->
16 on the other threads, which also cuts the allocator contention from cross-thread frees.

Verified on the original branch and again on this tree: fmt, clippy in every configuration, Rustdoc,
and the runtime lanes, 1311 of 1311 on RADV, ANV and lavapipe.
2026-10-14 12:15:37 +03:00
Anees Iqbal 4600bc606d Begin two command buffers per render pass instead of four
Keep a batch's barrier command buffers and submit them again rather than beginning new ones, cut a
pass end's allocations and work where nothing needs them, count the command buffers the runtime
begins, and count a frame's instructions per step in frames of their own, outside the timed ones.

Gain: two command buffers begun per pass instead of four (ANV memsets each one twice), and a pass
end's allocations from 52 to 36.

Verified on the original branch: the runtime lanes on RADV, ANV and lavapipe. This squashed commit
was not re-tested on its own.
2026-10-14 12:15:32 +03:00
Anees Iqbal 8963e1871b Submit a commit's work without waiting for the scheduler's lock
A commit no longer blocks on the scheduler's lock while another thread's pass holds it across its
vkQueueSubmit calls: it leaves its batches in a commit inbox that the pass under way takes in, in
commit order. A batch's first work rides in the batch's own vkQueueSubmit, a batch with nothing to
end submits no command buffer, and the runtime counts its queue submissions and live memory blocks
per commit.

Gain: on an Intel Iris Xe host (ANV on i915), the consumer's guest A/B measured a Finder window drag
at 22.1 -> 34.4 frames/s and Safari at 39.1 -> 42.7 frames/s.

Verified on the original branch: the runtime lanes on ANV and lavapipe. This squashed commit was not
re-tested on its own.
2026-10-14 12:15:22 +03:00
Anees Iqbal 11715e2a3f Import no-copy memory a driver refuses from the caller's dma-bufs
RADV imports host pointers through amdgpu userptr with ANONONLY, so it
refuses MAP_SHARED memfd pages (QEMU's memory-backend-memfd guest RAM and
views of it): every no-copy buffer, heap and rebind over them was refused,
and a macOS guest could not boot on AMD. NVIDIA imports the same pages.

What:
- The five no-copy entry points (new_buffer_with_bytes_no_copy, both
  new_heap_with_bytes_no_copy calls, Buffer and Heap rebind_bytes_no_copy)
  take a HostMemory; HostMemory::with_dma_buf adds a retained DmaBufSource.
- Where the pointer import is refused, and only there, on any device that
  lists VK_KHR_external_memory_fd and VK_EXT_external_memory_dma_buf, the
  runtime asks the source for dma-bufs of the window's pages (chunks cut at
  the device's sparse granule, sized by the caller within udmabuf's default
  limits) and binds one buffer over them: plain for one chunk, sparse for
  several (vkQueueBindSparse signalling queue 0's timeline; later work waits
  on it, no host wait). Every path that imported before is unchanged.
- Textures over such pages get a dedicated DRM_FORMAT_MOD_LINEAR image import
  of their own pages where the driver takes the plane offset and row pitch
  (multiples of 256 on RADV), with 64-bit modifier features; elsewhere, or on
  a source error, the existing shadow path.
- The extensions are enabled outside the compile profile: no device's enable
  set, fingerprint or ARTIFACT_FORMAT_VERSION changes. The translator crate is
  unchanged.
- Imports free inside exit-guard sections; the source is never called with a
  runtime lock held. WorkCounts gains dma_buf_imports, dma_buf_sparse_buffers,
  dma_buf_images and dma_buf_image_fallbacks.

Verified:
- Product suites 4553/4553, validation suite 1289/1289, clippy in every
  configuration, rustdoc -D warnings, scripts/api-docs.
- runtime_lane::dma_buf_imports and rebinds on RADV Mesa 26.2.4 (validation
  layer clean), the RTX 3090 and lavapipe (pointer imported, source never
  called), and dma_buf_imports on RADV Mesa 26.0.8.
- reims-vgpu on the Radeon 780M (RADV 26.0.8, udmabuf at its defaults): a
  macOS 26 guest cold-boots to the desktop and runs Safari; 5,119 dma-buf
  requests, none refused.
- 64 MiB on RADV 26.2.4, release: pointer import 187 us; one chunk 665 us;
  16 chunks 16.9 ms, about half of it the refused pointer attempt. The old
  host-fence bind waited 1.26 s behind queue-0 work on RADV 26.0.8.
2026-10-12 11:33:41 +03:00
Anees Iqbal 13b279df1b Squash 11203 commits of translator, runtime, and validation work
Rolls up everything since 43c46ac8 into a single commit. Its tree is
identical to the tree of private master at
b3c77f2d2b20a432be10591a2129547c10b1c24b.

- A Cargo workspace of five crates under crates/: metal2vulkan (the
  translator and the metal2vulkan command), metal2vulkan-runtime (the
  Metal API on Vulkan), metal2vulkan-air (the AIR front end),
  metal2vulkan-validation and metal2vulkan-devtools.
- Dual license: GPL-2.0-or-later OR LGPL-3.0-or-later.
- docs/: API, architecture, fast paths, how-to, Metal coverage,
  refusals, runtime porting and validation guides.

Private-Commit: b3c77f2d2b20a432be10591a2129547c10b1c24b
2026-10-11 20:09:13 +03:00