Commit Graph
1457 Commits
Author SHA1 Message Date
Anees Iqbal 737ccbf81a metal: the resource ID word, its spec and test vectors
Under the identity binding domains a guest computes a texture's or sampler's gpuResourceID itself,
with no round trip: the index the consumer grants in the low 32 bits and a word in the high 32 bits
that is a pure function of the Metal descriptor. The guest's port needs the word specified and a
file of vectors both sides check.

- metal::resource_word::TextureWord::of(pixel_format, swizzle): bits 0-11 Metal's border texels
  after the swizzle (the existing border_texels rule), bit 12 the out-of-bounds alpha of a format
  without alpha, bits 16-31 the MTLPixelFormat raw value, so a texture's word is never 0. None for
  the placeholders and the formats the translator holds no texture of or only copies.
- The sampler word is the existing SamplerWord, unchanged.
- docs/RESOURCE-ID.md: the ID's layout, the index classes (0 nil; storage-capable textures 1 to
  4,095, valid in both arrays; other textures 4,096 to 65,535; samplers 1 to 3,999), both words'
  bits and the level rule, and the vectors file. README's documentation table lists it.
- crates/metal2vulkan/tests/resource_words.tsv: 392 vectors (every pixel format with a word under
  the default swizzle, each channel of seven formats from each other source, every sampler field
  through its values, the level clamps around the points the nearest level turns at, and one
  descriptor with every field changed). tests/resource_words.rs recomputes every line through the
  public API and holds the file equal to what the generator writes; an ignored test blesses it.
- api_surface lists the new module; api_signatures regenerated.

Verified:
- msi job 40810 at the same tree: clippy -p metal2vulkan --all-targets --all-features -D warnings,
  rustdoc -D warnings, nextest 18 of 18 (resource_words, the TextureWord unit test, api_surface,
  api_signatures).
- msi job 40811 at the same tree: clippy under --cfg m2v_gpu and --cfg m2v_cpu_icd.
- msi job 40809: the bless test wrote the vectors; the combined sampler line (0x58f6ab53) and the
  A8Unorm and R8Unorm texture lines checked by hand against the bit tables.
2026-11-17 07:01:32 -08:00
Anees Iqbal 4406486e8c docs: the matrix's harness suite and time records 2026-11-17 06:19:58 -08:00
Anees Iqbal b4b22c7b2c matrix: the per-commit matrix runner and the user-space instruction counter (WIP) 2026-11-17 06:19:57 -08:00
Anees Iqbal 84fc9a95fc validation: replay streams name the guest RAM copies; a present reads nothing
The recorder writes the host's copies between the guest's RAM and a buffer as blit-encoder
records: m2v.copyFromGuestRam ([runs, buffer, offset, data]), m2v.copyFromGuestRamAt ([placed runs,
buffer, data]) and m2v.copyToGuestRam ([buffer, placed runs]), a run being [start, end] host
addresses of which only the length counts. docs/REPLAY-STREAM.md names them, with the data the
next recording carries. The player relocates the data of every upload (these two and
m2v.copyBytes:toBuffer:offset:) by one rule, where its buffer answered a gpuAddress, and counts its
bytes as written; the old runtime's backend copies them through a staging buffer, piece by piece,
and copies m2v.copyToGuestRam into host memory nothing reads.

m2v.present is now recorded wherever the device's display shows a guest present, a nil texture
where the stream never made it, so frames are counted once: the player closes the frame and
reads nothing (a readback per frame would add a copy Metal does not make).

Tests: a unit test plays the three copy-ins into a block and an addressless buffer (relocated,
counted apart 4 past 8, untouched) and refuses data of another length than its runs; a device
test lays a buffer out with a fill, both guest RAM copies, a fill copy and a copy back, and reads
it back as expected.
2026-11-17 06:14:55 -08:00
Anees Iqbal 964ae2c241 validation: replay streams v2, their player and the old runtime's backend
What: docs/REPLAY-STREAM.md specifies the binary replay stream (version 2): segments of records
(names, blobs by SHA-256 of the exact bytes, calls), tagged values, the address and resource-ID
model, CPU writes, surfaces before the platform cutover, commits, events and frames. The new
`replay` module of the validation crate holds its reader and writer, the address map, the player
(relocation of 8-byte-aligned address words in live recorded ranges, counting rewritten words and
the 4-mod-8 values it leaves; exact resource IDs; waits only for command buffers that can
complete, so one held on an event never stops another queue; counters per waited group, per frame
and in total, readbacks excluded; SHA-256 checks), and a backend over the old runtime's public API
(compute and blit encoders, blocks as placement heaps, textures at recorded IDs, events). A
selector it does not play is a typed refusal naming it.

`command-replay` now plays and dumps v2 streams; the v1 JSON manifest runner is deleted (nothing
in the tree or the lanes used it).

Tests: unit tests write their own streams (round trip, segments and a cut tail, refused kinds and
versions, the blob directory and its hash check, nested ranges, relocation counts, event-held
command buffers, frames, releases and host splits). Device tests (`runtime_lane::replay_streams`,
under m2v_gpu or m2v_cpu_icd) play written streams on the old runtime: a device pointer written
at a recorded block address is relocated and the kernel's output is the case's Metal output, on
two devices alike; a command buffer held on a CPU-set shared event does not stop another queue's;
textures are made at recorded resource IDs 77 and 5 and read back as written.
2026-11-17 06:14:54 -08:00
Anees Iqbal ec40b7de6d Interface: what a function reads and writes beyond its bound slots
Each stage interface, and a pipeline's together, states whether its
function may read or write a resource through anything but its bound
slots: a pointer or texture it loads from memory or makes from an
integer (an argument buffer's resources, an address stored in a buffer,
a resource ID), an indirect command buffer, ray tracing, or a call it
cannot see into. Decided from the specialized entry's memory plan: an
access whose pointer or texture handle may have a dynamic or call root.
With each slot's access, these are the two static facts the new
runtime's compute encoder needs to place a barrier only on a hazard.

SEMANTICS_VERSION 2144 (interface facts), ARTIFACT_FORMAT_VERSION 526
(two fields in StageInterface and PipelineInterface).
2026-11-17 06:14:08 -08:00
Anees Iqbal 374e29a988 metal2vulkan-rt: the floor's shader features, queue family, timestamps and memory types
The floor now also requires what the translator's shaders and the runtime's
core need of every device:

- shaderInt16, shaderInt8, storageBuffer16BitAccess (Vulkan 1.1 features,
  now read and enabled through Features::vulkan11), storageBuffer8BitAccess,
  scalarBlockLayout, vulkanMemoryModel and vulkanMemoryModelDeviceScope. The
  translator emits 8- and 16-bit access only in storage and physical storage
  buffers in practice (uniform views are u32 or uvec4, push fields are 32- or
  64-bit), so the uniform and push-constant 8/16-bit features stay out; it
  does use device scope.
- timestampComputeAndGraphics, and timestampValidBits of at least 36 on the
  first queue family with graphics and compute, which Capabilities names
  (queue_family). A device with no such family is Missing::QueueFamily.
- a host-visible, host-coherent, host-cached memory type (Shared storage)
  and a device-local, host-visible, host-coherent one (the parameter ring),
  each usable by a buffer of BUFFER_USAGE: every Vulkan 1.3 buffer usage plus
  device addresses. Vulkan answers buffer memory types only for a created
  device, so check() finds a type with each set of flags and carries the
  memory properties, and memory_types(device, &capabilities) chooses the
  first usable type of each with vkGetDeviceBufferMemoryRequirements.
  Missing::MemoryType names the flags.

Each shortfall is named in BelowFloor, with a unit case; the README's Floor
section states every item and tests::floor holds it to the code. The device
test now also creates each device with the floor's features and extensions
and chooses its memory types on it.

CI's lavapipe step (ci.yml and scripts/linux-gate-ci) runs the rt crate's
device tests too. refusal_surface.py reads metal2vulkan-rt and writes the
floor's Missing as section 10 of docs/REFUSALS.md; signatures.py pins
metal2vulkan-rt's public surface in api_signatures.tsv.

Verified: see the lane report (compile job, device legs on every lab GPU,
lavapipe and the Windows UHD 630).
2026-11-17 05:33:25 -08:00
Anees Iqbal 017ff31e2f wip harness crate 2026-11-17 05:22:15 -08:00
Anees Iqbal 28b6b0b9df metal2vulkan-rt: the new runtime's crate, and AGENTS.md's rules for one path on every device
What: a new, unpublished workspace crate, crates/metal2vulkan-rt, that will replace
metal2vulkan-runtime and take its name at the cutover. It has no public API yet. Its first test,
tests::one_path, reads the crate's product sources (line comments removed) and fails on:
- a vendor, device or driver identity name (vendor_id, deviceID, DriverId, driver_name ...);
- a GPU vendor's ID as a hex literal (0x1002, 0x10de, 0x8086 ...);
- an environment read (env::var, option_env!);
- a struct or enum named as a policy.
Two more tests prove the scan finds each form and passes prose and unrelated numbers.

AGENTS.md takes the owner's new rules, in priority order:
1. correct for documented Metal, with the device's arithmetic and static notes per operation;
2. one path for every device;
3. native-like speed;
4. small.
It also takes:
- the workaround ladder, the never-list and the thresholds;
- the matrix rules: every check fans out one leg per GPU at once, and the replay matrix runs on
  development after each merge with deterministic metrics and leak gauges;
- the freeze: the old runtime, DevicePolicy switches, driver-fact tables, device checks and
  docs/FAST-PATHS.md get regression fixes only until the cutover deletes them, and nothing new
  of those kinds is added;
- the scope rule: below the floor is a typed refusal, and a Metal feature no replay stream uses is
  a typed refusal until a stream needs it.
The crate table, the doc table, CI's crate lists and the gate commands in AGENTS.md,
CONTRIBUTING.md and docs/VALIDATION.md name the new crate.

Why: the owner's plan replaces the runtime with one that has no per-device code paths. These are
the rules every lane of that work follows from its first commit.

Verified: cargo fmt. Build, clippy and the crate's tests run on development after this lands.
2026-11-17 03:09:06 -08:00
Anees Iqbal 96e1041dbf RUNTIME 2538: submission checks: an answer that load could have made stands only for now
What: a merge or import tax answer now stands as far as it earned
(`Stands`). A merge `Holds` clear of the load and repeated, an import tax
`Holds` past its margin and repeated, and an `Unchecked` of a refused call
or a device with no pointer import are recorded. A `Fails` clear of the
load whose every try ran quiet stands for the device's life and is never
recorded. Every other answer stands for now: the checks' thread keeps its
command buffers and fence and checks it again 1, 2, 4 ... 64 s after the
first answers, then each minute, until none stands for now. A check again
replaces the verdict (tries that all split keep it), so a device whose
first merge answer was a loaded `Fails` groups once a check again answers
`Holds`. A record's `Fails` is a hint and no answer: a device that reads
one checks that check again at its making. Before each round and each
submission of a phase the checks stand by, at most 20 ms, until the
device's work is quiet (`DeviceShared::work_quiet_for`, shared with the
checks' thread through `WorkShare`).

The stop rule's thresholds (`Load::ran_quiet`): every stand-by found the
device's work quiet, no round or submission took past QUIET_ROUND_MOST
(2 ms, from its first call to its fence's reset), and all of them no more
than QUIET_TRY_MOST (30 ms). A merge `Fails` must also be clear
(MERGE_FAILS_CLEAR, 0.75 of the calls apart) and repeated
(MERGE_REPEATS); an import tax `Fails` must agree in its halves with a
held import adding at most half its bound (TAX_FAILS_CLEAR).

Why: on the Radeon 780M beside other jobs (m3-max-39740, load average
18-24 on 16 threads), two of four devices answered merge `Fails` at 0.72
and 0.745, both forms lifted by about the same 58-80 us, short of the
record but held for the device's life, so those processes grouped no
batch at all. At 0.75 and up with its repeats, the same load would have
written a `Fails` record that every later device of that release read
without checking. Threads of the process's own spinning or touching fresh
pages (m3-max-39786, 2x the host's threads) lifted every call alike and
left all eight devices at `Holds` (0.23-0.64), so the device test injects
the observed shape instead (`lift_next_merge_tries`: 70 us on the first
call of every round, its stand-bys not quiet).

Costs: a driver that does not merge or whose imports cost nothing pays
that check at every device's making, as before any record, and once more
at least where no try of its first answer ran quiet. An answer for now
costs a check again at each step of the schedule. The import tax is
included: a loaded tax `Fails` placed the device's long buffers in fresh
pages for its life on a driver whose imports do cost (39740's
b202c-bench run: 148.6 against 121.5 us, short of its margin).

CHECK_VERSION 9 (a record may hold no answer of a check, and a `Fails` in
one is no answer). Tests: unit tests of what each answer earns, the
schedule, the quiet bounds and the record; device tests that a recorded
`Fails` is checked again and that a lifted merge answer is checked again
and comes to the answer of a device beside it, with no `Fails` recorded.
in_place_check takes its answers through `answer_next_device`, since a
record can no longer hold a `Fails` as an answer. Forced verdicts
(`SubmitChecks::force`) stand for the device's life.

With it: the drag bench reports the submission checks' answers before and after its measurements
(test only); a lifted try's count goes down by AtomicU32::try_update (fetch_update's new name).

Verified (launchreg lane, tip 942672e8cb = these three commits on development 01415e33d6):
m3-max-39884 (msi): clippy -D warnings plain, m2v_cpu_icd and m2v_gpu 0; lavapipe submit_check,
in_place_check, teardown_threads, relay_facts, fresh_pages, padding_unobserved, host_ram_dma_buf,
dma_buf_parked_images, exported_textures, icb_records_policy, pointer_residency, fast_paths,
queue_quiet and view_check 114/114; view_check_device's stand-by test 3/3. The control (the fix
without the re-check of loaded and recorded answers) fails the new device tests as meant: lavapipe
(m3-max-39818) 2 of 2, RX 550 (39863) 2 of 2, Radeon 780M (39885) the recorded-Fails test; the fix
passes 26/26 on the RX 550 and the 780M. On the 780M (39907, the fix on an earlier base) a device
made under host load answered merge Pending (one try split), then "Holds, recorded (14.4 us in one
call of 4 against 39.4 us apart)" after its re-checks, and grouped; every later device answered
Holds in 3 tries.
2026-11-17 02:01:04 -08:00
Anees Iqbal 94e3f50b3e RUNTIME 2524: name and count each reader's snapshot image
What: a reader's snapshot (render/snapshot.rs, Texture::snapshot_texels) is a storage image of
the read texture's level-0 extent beside the texture's own image, which no log line named and no
count counted as an image. Each snapshot a draw takes is now counted
(WorkCounts::reading_snapshots_taken; reading_snapshots_recycled for those whose image was the
recycler's parked one, which placed no memory) and named in the shadow log
(METAL2VULKAN_LOG_SHADOWS): the draw's call, the texture it binds (format, size, levels, usage,
object ID, the texture it is a view of), the snapshot's format and extent, and whether its image
is the recycler's or one placed for it. Image records whether the recycler handed its VkImage
back (Device::recycled_image now says so).

Why: a consumer's Iris walk (RUNTIME 2485) showed a second Private image of each image cache's
size placed about 1 ms after the cache and returned with it, 109 of them, named by nothing: the
snapshot of a draw that samples the cache's view at its own pixels while its own pass renders the
view and writes that color. RUNTIME 2508 already releases it with its command buffers; it stayed
unnamed and uncounted.

Test: tests::snapshot_goes turns the shadow log on and checks one line per snapshot taken, the
recycler's named so, each naming the view, its texture and the snapshot's extent; the second
pass takes 1 snapshot, the recycler's. On a device without the path: none taken or named, and
the reader's copy is the usage shadow the log names for the attached read.

Verified (twinplace lane, tip 2e160c176e on fe3f09f569): m3-max-39527 (msi): clippy -D warnings
plain, m2v_gpu and m2v_cpu_icd 0 for metal2vulkan-runtime and metal2vulkan, rustdoc 0, lavapipe
snapshot_goes, snapshot_reader*, snapshot_area, leading_snapshots, swapped_out_book 10/10
(the copy route: snapshots taken 0); m3-max-39554: api_signatures, api_surface, env_registry
19/19; PHOENIX (RADV) m3-max-39555: the same 10/10, snapshots taken 3, recycled 2, lines 3.
New WorkCounts fields reading_snapshots_taken and reading_snapshots_recycled; no new
Degradation kind; no route change.
2026-11-16 23:52:28 -08:00
Anees Iqbal 7dcde89ddb RUNTIME 2522: a head whose line signals what another queue's head awaits takes no turn
Under the default Fair queue turns, a later command buffer of a queue sharing a
VkQueue is held for its turn while its queue's earlier one is in flight. Where
that later one signals a value another queue's held head waits for, and the
earlier one waits on the GPU for a signal the program gives only once that
waiter is scheduled (a caller's reserved signal, Event::reserve_vk_signal), the
program waited for the watchdog, where Metal schedules them all at once.

Each look now first gathers the values the line heads wait for that no
submitted signal or host set reaches (EventShared::landing), and, only where
there are any, marks each turn-taking line's head by whether a batch of its
line signals such a value for another line (one read per command buffer).
Such a head takes no turn (scheduler/mod.rs mark_awaited_signals; Held
signals_awaited); once the signal went, its line takes turns again. The
awaited values live in State and are emptied after each look, so a look
allocates nothing. queue_turns.rs gains the "Awaited signals" rule and the
FAST-PATHS queue-turns row says it.

The lane test runtime_lane::events::a_signal_another_queue_waits_for_takes_no_turn_behind_a_gpu_wait
(queue B's first command buffer waits on the GPU for a reserved gate, its second signals W=1,
queue A's waiter waits for W=1; the gate opens once A's waiter left Committed) comes with it.

Verified (evwait lane, tip b77e692259 on fe3f09f569): m3-max-39516 (msi): clippy -D warnings
plain, --cfg m2v_gpu and --cfg m2v_cpu_icd 0, rustdoc -D warnings 0, runtime unit tests
queue_turns|unshared_hold|fast_paths|scheduler|order 222/222. The lane test's before/after
on the XTX (m3-max-39536) and PHOENIX follows on development; unverified there until then.
No new Degradation kind, WorkCounts field or public signature.
2026-11-16 23:42:39 -08:00
Anees Iqbal d0714ec9a6 RUNTIME 2518: queue turns hold only a command buffer's first batch; its later batches follow
What: under QueueTurnPolicy::Fair, CommandBufferShared::held_for_turn now holds only a
command buffer's first batch (index 0). Once that one went, each later batch of it (a
command buffer splits at an event wait after its work or at a signal before more) goes as
it is ready, as Metal schedules a command buffer whole. queue_turns.rs gets a "Whole
command buffers" bullet and loses the claim that the turns add no wait that can close a
cycle; the FAST-PATHS queue turns row says it.

Why: a REGRESSION of RUNTIME 2490 (Fair, the default). A queue with no run seen keeps one
batch in flight, so a command buffer whose first batch waits on the GPU for a signal not
yet given (the caller's reserved signal, Event::reserve_vk_signal, or another VkQueue's)
had its later batch held for the turn until that first batch completed: it read
Scheduled only then, and another queue's command buffer waiting for its later signal was
held for EventValue meanwhile. A program that gives the signal once that waiter is
scheduled (Metal schedules both at once) waited for the runtime's 20.2 s watchdog, which
failed the signaller (GpuHang / victim) and recovered the device: the XTX lane's
runtime_lane::submission_checks reds. Every device whose command queues share a VkQueue
(RADV, ANV, lavapipe) takes Fair.

Verified before the fix (carried --lib gpucfg archives, alone, --test-threads 1):
development 68c456e5ba on the RX 7900 XTX (m3-max-39361) and the 780M PHOENIX
(m3-max-39362): a_submission_detached_while_a_gpu_signal_is_in_flight_fails,
a_wait_the_host_meets_is_checked_without_waiting_for_the_gpu and
an_event_wait_a_gpu_signal_in_flight_meets_is_checked_at_once FAIL (signaller Error after
the watchdog); the same tree with QueueTurnPolicy::CommitOrder (a probe, not landed):
4/4 pass in 0.1 s each on both. RUNTIME 2493 and 2503 fail alike on the XTX.

Verified after (evwait lane, tip c435183fba): clippy -D warnings on runtime + validation,
all targets, all features (m3-max-39391, msi), queue_turns + unshared_hold + fast_paths
unit tests 61/61; PHOENIX 780M (m3-max-39414): runtime_lane::submission_checks 9/9 as a
module in parallel, the three reds included (1.4-2.1 s each), and the runtime's
queue_share_device, queue_turns, scheduler_held_wakes, submission_turns and unshared_hold
tests 56/56. Clippy under the GPU cfgs, rustdoc and the XTX run follow on development.
No new Degradation kind, WorkCounts field or public signature.
2026-11-16 23:05:56 -08:00
Anees Iqbal 4114585b2a SEMANTICS 2143 / RUNTIME 2517: a selection on an own-pixel read keeps its snapshot slot
A fragment function that reads its own pixel of a colour attachment and branches on the value
was refused its snapshot read (SnapshotRefusal::Branch), so each such draw split its render pass
and copied the texture. On the consumer's desktop walks that was 614 draws/s on the XTX and the
Radeon 780M (510 render-pass splits/s, 20.8 M texels/s of split copies) and 107 draws/s on the
Iris Xe. In a pipeline dump of the 780M walk, 30 of the 33 readers refused for Branch branch
through selections whose arms hold no derivative, implicit-level sample, group op, kill or loop;
their values leave the arms through Function variables, not phis.

The rule (spirv/requirements/snapshot.rs, new snapshot/arms.rs): a branch or switch on a fetched
value keeps the slot when it is a selection whose arms leave only through its merge (no break,
continue, return, OpKill, OpTerminateInvocation or unreachable end), hold no tangled instruction
(Inst::is_tangled: a derivative, an implicit-level sample or LOD query, a subgroup or quad op),
hold no loop and no non-constant integer divisor or dynamic index, and call no function that
holds any of these. The merge's phis and the Function, Private and Output variables the arms (or
their callees) store to take the condition's reach, so a merged value that reaches a derivative
still refuses the slot (Derivative). A helper invocation may then take either arm: its stores to
Function, Private and Output memory have no effect beyond it ("Helper Invocations"), and nothing
in the arms observes its neighbours. The loop form stays Branch. demote_guard goes: the rule
covers it (demote arms are clean arms).

The facts a module states change (snapshot_textures, snapshot_refusals): SEMANTICS bump. A new
owned fixture, engine/snapshot_select.metal (scripts/regen-air-fixtures). No new Degradation
kind, WorkCounts field or public signature. Docs: SnapshotRefusal::Branch, docs/API.md (Snapshot
reads).

Tests: snapshot::tests (kept: empty arm, demote arms, Private store, callee and pointer forms;
refused for Branch: an arm with a derivative, a call to one, a kill, a loop, a non-constant
divisor, the loop exit; refused for Derivative: an arm's store or a merge phi reaching a
derivative); compile::tests::a_selection_on_the_texel_keeps_the_slot_where_a_helper_may_take_
either_arm (ss_read_selecting states no refusal on the 780M and lavapipe profiles;
ss_read_selecting_dfdx and wlk_read_branch state Branch); runtime_lane::snapshot_reads 12/12 on
lavapipe with two new lanes.

Verified (snapbranch lane): clippy -D warnings on the three crates (m3-max-39324), touched tests
6/6, lavapipe snapshot_reads 12/12 (m3-max-39334). The fixture's inventory, air_input printout
and golden hashes re-bless on development; clippy under the GPU cfgs, rustdoc, the release
translation timings and the PHOENIX lane run follow there.
2026-11-16 22:47:15 -08:00
Anees Iqbal 594c792b66 RUNTIME 2506: An upload's trailing barrier names its batch's own uses of the buffer
A batch's first work of Managed uploads alone ended with a barrier
TRANSFER/TRANSFER_WRITE -> ALL_COMMANDS/MEMORY_READ|MEMORY_WRITE. On a
device that orders its batches by their ends, where the first work
already takes no leading barrier (first_move::Earlier::Ended), its
second scope is now the union of the stages and access types the
batch's encoders' uses of those buffers name (first_move::Later::Batch,
from the parts' tracker summaries). Every later batch on the VkQueue is
ordered by the batch's end, Barrier::to_all, whose first scope includes
all earlier commands at ALL_COMMANDS/MEMORY_WRITE (the uploads among
them) and whose second includes every later command; another VkQueue's
command buffers wait for the batch's signal, whose first access scope
includes all memory access performed by the device. The barrier keeps
ALL_COMMANDS under the exact batch order, and wherever the batch's use
is unknown: a command may reach memory no use names, a heap's set is
bound, the work may write through its residency, an upload names no
key, or the batch's uses name none of a buffer.

Probe (64 B inline, GPU p50; probe-only branches, never landed): the
global barrier narrowed to COMPUTE_SHADER/SHADER_READ|SHADER_WRITE took
the RTX 2080 from 23.85 to 18.25 us (none 12.4) and the RTX 3090 from
32.25 to 25.05 us (none 21.8); a buffer-range barrier measured the same;
on the RX 7900 XTX the trailing barrier costs nothing (9.7 us either
way).

New counter WorkCounts::managed_upload_barriers_narrowed; device tests:
the WAR test counts it, a later batch reads the upload at a stage the
upload's batch never used, and the barrier's scope names both stages of
a batch whose kernel and blit both use the buffer (a test-only record of
the scopes).

The second commit (263b155a4a) prints vk flags as raw words; Later derives no Debug.

Verified: m3-max-38590 (m2v_gpu and release archives, clippy --cfg m2v_gpu) and m3-max-38591
(clippy plain and --cfg m2v_cpu_icd, rustdoc -D warnings) clean; device tests managed_inline,
host_ram_managed and managed_copy_device 49/49 on the RX 7900 XTX (m3-max-38597) and the RTX
2080 (m3-max-38600): the WAR test counts the barrier narrowed (0 under the exact order and in
its negative control), the later-batch test reads the upload at TRANSFER, and the scope test
finds COMPUTE_SHADER|TRANSFER and SHADER_READ|TRANSFER_READ. The base-vs-tip benches on the
2080 (m3-max-38610) and 3090 (m3-max-38612) follow the merge.
2026-11-16 18:33:58 -08:00
Anees Iqbal 3e39f3b9b1 RUNTIME 2502: Uploads alone after a batch's end take no barrier from the commands before
A batch whose first work is only Managed uploads (copies or inline
vkCmdUpdateBuffers into device copies) recorded, in its first-work
command buffer, an execution barrier ALL->ALL before its GPU start and a
lead barrier ALL_COMMANDS/MEMORY_WRITE -> TRANSFER before the uploads.
On a device that orders its batches by their ends (batch_order::by_ends:
RADV, NVIDIA, ANV) both are redundant: every earlier command on the
batch's VkQueue is a batch's, followed in submission order by its end
Barrier::to_all (ALL_COMMANDS/MEMORY_WRITE -> ALL_COMMANDS/
MEMORY_READ|MEMORY_WRITE), whose first synchronization scope "includes
all commands that occur earlier in submission order" and second "all
commands that occur later in submission order" (vkCmdPipelineBarrier),
the uploads among them. Earlier reads of the device copy run before them
(WAR needs only an execution dependency), earlier writes are available
and visible to their writes (WAW), and the start timestamp at the top of
the pipe is held there as a first encoder's prefix start already is. The
one other kind of submission on a batch VkQueue, an internal one
(device/submit.rs), ends with no such barrier: the batch skips both only
where no internal submission the host has not seen complete was made,
read while it holds its place in the first work's order, which an
internal submission takes before it is made. Another VkQueue's command
buffers stay ordered by the batch's semaphore waits. Under the exact
batch order (to_host ends) both barriers stay; the trailing barrier stays
everywhere.

New counter WorkCounts::managed_uploads_unbarriered. New device tests in
tests::managed_inline: an upload behind a batch whose kernel still spins
on the device copy's word lands after its reads (default order, counted
unbarriered on a by_ends device; exact order, kept), and an ignored
negative control forcing it unbarriered under the exact order. The bench
prints the counter.

The write-after-read test's buffers take their first work before its steps
(e54dbd08b3) and its doc says where it can fail (5cbadadeef).

Verified: clippy in three configurations and rustdoc passed
(m3-max-38492, m3-max-38530); the managed_inline device tests on the XTX
47/47 (m3-max-38511); the write-after-read legs on the 2080 passed
(m3-max-38527). Measured (release, inlinemanaged bench, 64 B inline):
the XTX's GPU gap over no upload fell from +5.6 us to +3.5 us
(m3-max-38521; 2.1-2.9 us across sizes); the 3090 showed no measurable
change (m3-max-38522). The 2080 rerun follows the merge.
2026-11-16 18:06:39 -08:00
Anees Iqbal 5bd1c466c8 RUNTIME 2500: A texture's copies with a guest RAM take one region per run of rows on an import
What: BlitCommandEncoder::copy_texture_from_host_ram / copy_texture_to_host_ram made one VkBufferImageCopy per row piece (bufferRowLength 0), and laid_over never joined runs that continue one another in host memory, so a surface given as one run per page was cut at every page end. Now host-contiguous runs merge within a row (as the buffer forms already do), and joined_rows makes pieces that share an import, a first texel and a texel count, in rows one after another with each row's import offset one pitch past the row before, into ONE region: bufferRowLength = pitch / texel bytes, imageExtent.height = its rows. Rows join only within a round, so a copy out whose pieces name a host byte twice keeps its order. A pitch over 2^31-1 bytes joins nothing (VUID-VkBufferImageCopy-bufferRowLength-09108). Rows that cross a chunk boundary keep their pieces.

Why: the consumer measured first fills of ~16 MiB surfaces from guest RAM on the Radeon 780M at 0.137 ms/MiB into images against 0.038 ms/MiB through copy_from_host_ram into a buffer (3.6x; +1.9 ms x 349 presents in one scene), and copies out over a walk with ~1000 downloads at Iris 75 -> 415 ms, 780M 56 -> 198 ms.

Measured (release, median of 10, a 2560x1600 BGRA8 surface given as 4000 page runs in 2 MiB blocks; regions per copy 4800 -> 20): 780M (m3-max-38432) fill 2.330 -> 0.510 ms, copy out 2.737 -> 0.494 ms, beside the buffer gather 0.488 and scatter 0.49 ms; XTX (m3-max-38429) fill 3.097 -> 2.452 ms, copy out 2.496 -> 2.484 ms (PCIe-bound), buffer gather 2.291 ms.

Tests: rows_over_host_bytes_in_a_row_are_one_region_on_their_import_both_ways (exactly 4 regions each way for 200 rows across a chunk end; bytes exact at a padded pitch, a tight pitch and a sub-rectangle; at the parent it makes at least one region per row); the scattered-pages test's count from a model of the rule; the bench host_ram_texture_bench (ignored by default). Docs: HOWTO, the runtime README, WorkCounts::host_ram_copy_regions.

Verified (msi, at ef7383646f): m3-max-38440 clippy -p metal2vulkan-runtime --all-targets --all-features 0, host_ram_texture_rows 2/2; m3-max-38441 lavapipe host_ram 129/129. clippy --cfg m2v_gpu / m2v_cpu_icd, rustdoc and the Iris bench (m3-max-38434) run after the merge.
2026-11-16 17:33:59 -08:00
Anees Iqbal db341427bf RUNTIME 2499: Queue turns: a held head waits for the completion that lets it go, and its bound's wake is no slice
pinreds' lavapipe counts (m3-max-38335) under Fair: submission_turns' committing-pass check had
0 completion wakes, 1 sleep slice and 1 slice rescue; grouped_submissions 4-5 completion wakes
for 6-7 turn holds and 1-2 rescues. Read, not a missed completion wake:

- A sleep the scheduler's thread ended at a held head's bound (await_room's wake_by: the time
  the oldest batch's run brings its queue's work under the budget, the turns' designed wake) was
  counted as a sleep slice and its pass as a slice rescue, though WorkCounts calls a slice the
  thread's longest wait with nothing having woken it. A bound shorter than the slice now ends
  the sleep as no slice does (short, as the idle's length before a driver's stall), on the
  condition variable and on the GPU.
- A turn-held head was gated on the oldest batch in flight, so every completion before the one
  that lets it go woke the thread to hold it again. Flight::own_ahead now gates it on the batch
  whose completion lets it go, or makes the batch of its queue whose run does so the oldest
  (turn_through), so the timer can be set then; a queue of unknown run on its first batch.
  Flight::turn adds the time another queue's last batch is 50 ms old where 2 ms holds the head
  and 16 ms would not, which the oldest's completion caught before.

Tests: queue_turns::a_held_batch_waits_for_the_completion_that_lets_it_go (the gate is the
fifth's predecessor, not each completion); the two turn unit tests' holds now carry the gate and
the quiet timer; queue_share_device's turns test asserts 0 slice rescues, at most a completion
wake per burst command buffer, and each submitted within 20 ms of the GPU end before it.

Verified (msi, at d4074ffeaa): m3-max-38421 runtime clippy --all-targets --all-features 0, unshared_hold|queue_turns 25/25, rustdoc 0, fast_paths 36/36; m3-max-38422 clippy --cfg m2v_gpu 0; m3-max-38423 lavapipe clippy --cfg m2v_cpu_icd 0, unshared_hold|queue_turns|submission_turns|scheduler_held_wakes|queue_share_device 64/64 (the turns test under Fair: 14 looks held, 0 slice rescues, 7 completion wakes for 12 command buffers, each submitted by the previous one's end). Open: validation grouped_submissions 14/15 in m3-max-38424 (a_shared_event_wait_for_a_kept_group_s_signal_ends_at_the_next_completion_turn, "Y completed before X"); its A/B against the parent (m3-max-38439, 38442) runs after the merge.
2026-11-16 17:30:51 -08:00
Anees Iqbal a55586f456 FAST-PATHS: the queue turns row's PHOENIX numbers at the landed shares fix
m3-max-38270: RADV on um790's Radeon 780M (PHOENIX), queue_share built at 037f1959bf
(m3-max-38259), frames, 5 s per run, load 1-3. Three 30 ms command buffers in flight beside a
draw every 16 ms: CommitOrder p50 71.1 ms, max 89.4 ms; Fair p50 17.6 ms, max 56.7 ms, every one
of the 313 draws run. Eight 4 ms in flight: CommitOrder p50 23.8, max 36.8; Fair p50 4.0, max
17.7, the GPU idle 1.68% against 0.08%.
2026-11-16 16:57:27 -08:00
Anees Iqbal a1ac85d9cd Queue turns: the burst probe's measurements replace the 200 ms oracle claim
cross_queue_burst_turns ran every case (m3-max-38188, 38240 on the M3 Max; 38189, 38241 on the
MacBook Pro's UHD 630 and Radeon Pro 5300M). The M3 runs a second queue's small command buffer
among a first queue's burst of 64 and beside its one 244 ms command buffer; the 5300M runs a blit
or render one among the burst but a compute one after the burst and after the long one; the 630
runs it after them in every case. The probe header records each case; the FAST-PATHS queue_turns
row, its known gap, queue_turns.rs and QueueTurnPolicy's docs said Metal ran it beside a 200 ms
one on the 630 and the 5300M, which the probe's compute one-long case contradicts, and now say
what was measured.
2026-11-16 16:57:27 -08:00
Anees Iqbal a9f42dd2f9 RUNTIME 2496: Scheduler: a committing thread leaves a VkQueue's batches to the scheduler's thread where its submit calls are slow
What: each VkQueue keeps the time of its last 15 batch vkQueueSubmit calls, whichever thread made
them, timed under the queue's lock in submit_logged (device/submit_calls.rs), and publishes their
floor, the least of them. Where that floor is 100 us or more, a committing thread's pass
(commit_and_submit) leaves the VkQueue's batches to the scheduler's thread, which it wakes at once
through the existing left_over wake, counted as LeftAtCommit::SlowCalls
(WorkCounts::scheduler_at_commit_left_slow_calls, new). Below it the committing thread submits as
since RUNTIME 2461. A thread about to wait for a command buffer still submits for itself whatever
the cost. No batch is reported as left for a host step with none due.

Why: a REGRESSION of RUNTIME 2461, which let a committing thread submit a batch that holds segments
with no host step due. On a host of unified memory every guest batch names host imports, and RADV
lists every import in each kernel submission, so on the Radeon 780M each such call took about 245 us
(p50; 394 p90), now on the guest's committing thread: the consumer measured the walk per render
encoder 84.0 -> 130.9 us and the commit call per part 19 -> 256 us, with 2461's one plain() line
undone matching the parent on every row. The cost is the driver's and the kernel's, so the decision
reads the measured call time, not a driver, GPU or memory kind. The floor rather than the median:
in m3-max-38258 a fresh lavapipe device's first calls held the median of 15 past 100 us for 14 of
200 commits while its calls then took 5.3 us at the median; load and a driver's rare long calls
lengthen calls and never shorten them, as the submission checks' floors already assume
(submit_check.rs), and the import tax this rule is for is paid by every call. Of the guest's
~290 us per inline part, ours before the call is ~43 us (~15%, the consumer's trace).

Tests: commit_and_submit::a_queue_whose_calls_are_slow_leaves_its_batches_to_the_scheduler_s_thread
(each batch call made 150 us slower through a cfg(test) hook, Device::slow_submit_calls: 0 of 40
batches at commit, 40 left for slow calls, floor 207.8 us; without the rule every batch goes at
commit); a_command_buffer_naming_host_pages_is_submitted_at_its_commit warms 15 rounds and asserts
the floor below the bound and nothing left for slow calls (200/200 at commit, floor 2.6-3.1 us).
The guest-shaped bench's SubmitCost leg puts its 250 us stand-in inside the timed call, with two
legs of the other forms (SubmitCostAtCommit, HostPagesHandedOff); on lavapipe release
(m3-max-38261) the hand-off cut the commit call 65.5 -> 8.2 us with commit -> GPU start p50 4089
against 4086 us, and a forced hand-off of the 0.4 us host-pages calls showed no start latency
(2598 against 2606 us).

Docs: scheduler module docs and plain_ready, unshared_hold.rs, commit_and_submit's doc, the runtime
README, RUNTIME-PORTING.md, FAST-PATHS.md's unshared-hold paragraph; api_signatures blessed.

Verified (msi, at f0a34f5d9b): m3-max-38277 clippy 0, lavapipe scheduler/queue/turns suites 101/102
and validation joined_completions|grouped_submissions 19/20 (the two failures fail at the base
b874899768 too, m3-max-38299: grouped_submissions::completions_wake_the_scheduler_only_once_a_head_
may_go 3/3 at both; submission_turns::a_committing_pass_ends_at_its_own_submission_handlers_grouped
1/3 at base alone); m3-max-38302 clippy --cfg m2v_gpu 0, --cfg m2v_cpu_icd 0, rustdoc 0. The 780M
before/after (m3-max-38281) and the Iris run after the merge.
2026-11-16 16:53:53 -08:00
Anees Iqbal f2367d8956 SEMANTICS 2142 / RUNTIME 2495: View facts from the device's own check: the runtime's view check, measured workarounds in the description
What: the two constant-window view cost facts no longer come from a GPU identity.
- metal2vulkan: DeviceDescription::measured (a set of DriverWorkaround, serde default) is a
  profile input: the profile takes those workarounds beside its identity's, so the fingerprint and
  every cache key follow it. The identity rows of UniformBufferPerLaneReadsSerialize (RTX 3090,
  RTX 2080, RTX 5080 Laptop) and ExternalUniformReadsSkipACache (ANV on the Iris Xe RPL-P) are
  gone, and NVIDIA_RTX_2080 with them (nothing else used it).
- The texel form now applies only to a slot with an indexed read (SlotPlan::indexed_read, from
  Provenance::indexed_constant_reads, marked on a profile with the texel fact): a slot read at
  constant offsets alone keeps its uniform buffer, whose ranges ANV pushes into registers (Mesa's
  brw_nir_analyze_ubo_ranges; read, not measured), as reims's Iris Geekbench pair 2 suggested.
  With both facts, view_kind gives a per-lane slot storage, an indexed-uniform slot the texel view,
  a constant-offset slot the uniform buffer: no conflict.
- bind::view_check_module (CheckView x CheckReads): the check's kernels, built and verified like
  any crate module (push-constant window mask, uvec4 reads, uniform / per-lane / fields).
- metal2vulkan-runtime: view_check.rs, a device check on its own thread, started as the device is
  made, once per driver + release + runtime, its medians kept in the shader cache's directory:
  8 kernels x 1 KiB / 4 KiB windows in device memory, and UBO / texel uniform reads over imported
  host pages; 7 interleaved rounds after a warm-up, medians of timestamps x timestampPeriod. Facts:
  per-lane where storage/UBO per-lane < 0.3 at both windows (NVIDIA 0.011-0.107, RADV 0.96-1.00);
  texel where texel/UBO uniform over imported pages < 0.7 at both (Iris 0.40-0.49). Unchecked
  (no fact) without timestamps or on any refusal. Device::settle_view_check, view_costs
  (ViewCosts, ViewVerdict), view_check_report.
- Timing: creation never waits. Device::compile_device returns the description's compile device
  until the check answers with a fact, then the one with the facts measured (made before the
  answer is published, held in the line's Invariant); a recorded answer applies from the first
  pipeline. pipeline::Sources reads the compile device once per creation or variant, so one
  compile and its link never straddle the answer. The runtime's own tests fix the facts
  (DeviceOptions::view_facts, cfg(test), default none) unless a test runs the check; it replaces
  compile_as.

Tests: device::tests::profile view_facts_come_from_the_measured_set_alone (no committed profile
nor the 3090/2080 IDs carries either fact by identity; each measured set its own fingerprint);
engine_lane_reads (the fact from the measured set on NVIDIA's and RADV's captures; NVIDIA
identities without it keep UniformWords; both facts compose: Storage / UniformTexel /
UniformWords); engine_access (the texel form for an indexed read, a constant offset keeps the
uniform buffer, nothing measured keeps it); bind::view_check validity on every committed profile;
runtime view_check::tests (facts on both sides of each bound, the measured GPUs' ratios, the record
round trip, the measured compile device and its fingerprint); view_check_device (lavapipe: settles
Measured with its medians, the compile device carries exactly its facts, a later device reads the
record); uniform_texels on indexed inline kernels under fixed facts.

Docs: API.md (DeviceDescription::measured, the texel form's indexed-read rule), runtime README
(the check, its cost, its verdicts, when translation takes them), FAST-PATHS known gap, api
signatures blessed, api_surface entries, REFUSALS regenerated (unchanged).

Verified so far: msi job m3-max-38239 at 5d493d44f7: clippy -p metal2vulkan -p
metal2vulkan-runtime --all-targets --all-features -D warnings CLIPPY=0.

With it (folded): View check: the inline kernels' module metadata llvm-as takes; the windows' descriptor alignment checked

The engine_access and uniform_texels inline kernels named llvm.module.flags and air.version with
the version tuples of air.version and air.language_version, which llvm-as rejects (msi job
m3-max-38254: engine_access's texel test panicked in assemble_text). The view check refuses a
window or out buffer whose VkBuffer offset lies off 256 bytes, the most any descriptor offset
alignment Vulkan bounds may ask, rather than write such a descriptor.

Verified: m3-max-38239 (msi) at 5d493d44f7: clippy -p metal2vulkan -p metal2vulkan-runtime --all-targets --all-features 0. m3-max-38262 at f941e38fab: clippy --cfg m2v_cpu_icd (runtime) 0; lavapipe 21/21 (uniform_texels, uniform_bind_offsets, view_check_device, view_check unit tests); lavapipe verdict Measured, no facts (per-lane storage/UBO 1.17-1.44, texel/UBO over imported pages 1.99-2.30, fields texel/UBO 1.99-2.09; the check took 267-487 ms; a second device read the record). m3-max-38254 at 46e4aaab03: translator 146/147 (engine_access's inline IR, fixed in the second commit). clippy --cfg m2v_gpu, rustdoc, the translator rerun and the device verdicts (2080, 780M, XTX, 3090, Iris) run after the merge.
2026-11-16 16:42:53 -08:00
Anees Iqbal c62128b564 RUNTIME 2493: Queue turns: a run several batches were seen complete in shares in proportion to their expected runs
What: unshared_hold's flight split a completion's run equally among the other queues' batches seen
complete in it. It now shares the run in proportion to each batch's expected run at its submission
(unshared_hold::Shares): a light batch seen complete with a long one keeps a light run, the long one
its own. Batches of queues with no run seen take the run beyond the others' expected runs, an equal
part each, at least 1 ns; when every batch is of unknown length they share it equally, as before.
Equal expected runs split as before, so the unshared hold's tests keep their numbers.

Why: a REGRESSION of RUNTIME 2490's Fair default. Under QueueTurnPolicy::Fair a compositor's plain
queue takes such a share: its light draw, seen complete together with the application's 30 ms
command buffer it waited behind, got half the run, about 15 ms, as its queue's expected run. With
2 ms of its own work allowed in flight, one draw in flight then held the next until that draw
completed, behind the application's next batch: one draw per application batch. On RADV PHOENIX
(m3-max-38213, frames, a draw every 16 ms beside three 30 ms command buffers in flight) the
compositor fell 2 s behind (p50 1192 ms, max 2062 ms, against CommitOrder's 77.8 and 106.3 ms).
2 ms stays the budget: 4 ms was worse for the compositor in both shapes measured.

FAST-PATHS: the queue turns row says how a grouped run is shared, and that the Macs disagree on
bursts (cross_queue_burst_turns: the M3 Max ran a second queue's small command buffer ahead of 56 to
62 of a first queue's 64; the UHD 630 after 60 to 63 of them; m3-max-38188, m3-max-38189).

Tests: queue_turns::a_light_batch_seen_complete_with_another_queue_s_long_one_keeps_its_light_run
fails under the equal split (the compositor's next draw is held);
a_batch_of_unknown_length_takes_the_run_beyond_the_others_expected_ones.

Verified (msi, at 7f6f9c4c6b): m3-max-38234 runtime clippy --all-targets --all-features 0,
unshared_hold|queue_turns 24/24, fast_paths 36/36, rustdoc 0; m3-max-38235 clippy --cfg m2v_gpu 0.
Lavapipe clippy and the queue_share_device / scheduler_held_wakes device tests (m3-max-38236) and the
PHOENIX rerun of both shapes run after the merge.
2026-11-16 16:33:21 -08:00
Anees Iqbal c091862da8 Fair queue turns: the FAST-PATHS row's measured lavapipe numbers; the queue_share example's --fixture
The lavapipe test of both QueueTurnPolicy values (job m3-max-38162, msi, load 7.32): twelve
command buffers of one queue committed at once, each about 37 ms there, and a small one of
another queue committed after the first was scheduled. Fair: the small one's GPU run started
37.5 ms after its commit, between the burst's first and second (14 looks held, 5 let go under
the idle budget). CommitOrder: 454.8 ms after, behind all twelve (0 held).

Verified: m3-max-38177 (msi) at c46daf583b: clippy -p metal2vulkan-runtime --all-targets --all-features -D
warnings 0 (compiles the example); nextest -p metal2vulkan --all-features fast_paths 36/36. The numbers:
m3-max-38162 (msi lavapipe, load 7.32): under Fair the small command buffer's GPU run started 37.5 ms after
its commit, between the burst's 1st and 2nd (14 looks held, 5 let go idle); under CommitOrder 454.8 ms,
behind all 12 (0 held).
2026-11-16 16:08:15 -08:00
Anees Iqbal 2911334351 RUNTIME 2491: A discrete host's small Managed ranges go to the GPU inline in the command stream
WIP: the mechanism, the counter, tests and bench; the bound and docs follow.

Measured bound (managed::INLINE_BYTES = 16 KiB; release managed_inline_bench, 200 one-dispatch command
buffers, p50 GPU us, copy against inline): RX 7900 XTX (m3-max-38126) 64 B 11.7-11.8 vs 10.2-10.3, 4 KiB
12.2-12.3 vs 11.0, 16 KiB 13.8-13.9 vs 11.0-11.1, 64 KiB 20.8-20.9 vs 11.2; RTX 2080 (m3-max-38161) 64 B
36.4-37.0 vs 31.1-31.6, 4 KiB 38.5-39.1 vs 31.7-32.3, 16 KiB 44.7-45.4 vs 39.4-39.9, 64 KiB 69.5-70.0 vs
70.5-71.0 (inline loses). Unaligned ranges keep the copy: widening them would put the host copy's bytes
over GPU writes beside the range. New WorkCounts::managed_ranges_inlined. RUNTIME_VERSION 2491.

Verified: msi m3-max-38118 at 7094cdbcd3: clippy -p metal2vulkan-runtime --all-targets --all-features -D
warnings plain 0 and --cfg m2v_gpu 0; 5f78fe489a compiled in m3-max-38132. managed_inline (bytes at 4 B,
B, B+4, 65540, unaligned ranges, a range named twice, GPU-filled neighbours kept, bound 0 the negative
control with 0 inlined) plus the Managed, host-RAM and copy suites: 61/61 on the XTX (m3-max-38126) and
61/61 on the 2080 (m3-max-38161). Lavapipe has unified memory, so it never takes this path. The 3090
bench and --cfg m2v_cpu_icd clippy and rustdoc follow.
2026-11-16 16:02:43 -08:00
Anees Iqbal 8f1e4157d8 RUNTIME 2490: Command queues sharing a VkQueue take fair turns: a queue's own work in flight there is bounded
What: a new DevicePolicy field, queue_turns. Under QueueTurnPolicy::Fair (the
default), on a VkQueue that two or more command queues hold, a batch of a queue
not made unshared goes only while less than 2 ms of its own queue's expected GPU
work is in flight there (16 ms while no other command queue took a batch there
within 50 ms); else the scheduler holds it in its place (HeldFor::QueueTurn) and
a later commit of another queue that shares nothing with it goes first.
QueueTurnPolicy::CommitOrder keeps the old behaviour: every ready batch at once,
in commit order. exact_answers() keeps Fair.

Why: on a device with one graphics VkQueue (RADV, ANV, lavapipe, Intel's Windows
driver) every ready batch went to the VkQueue at commit, so a command buffer a
second queue committed after one queue's burst (a long command buffer cut into
parts, a backlog of frames) waited for the whole burst. The unshared hold
protected only queues made unshared, and released the other queues' held
batches in commit order, so a later plain queue still waited behind the whole
burst, only paced. Metal ran a second queue's small command buffer beside a
first queue's 200 ms one (the consumer's oracles, UHD 630 and 5300M).

How: the VkQueue's flight (unshared_hold.rs) now counts each plain queue's
batches in flight and the latest two submitting queues; Flight::own_ahead
prices each of a queue's batches at its expected run now (a longer run prices
the rest of a burst at once), credits the running oldest only where it is the
queue's own, and holds a queue with no run seen to one batch. Under Fair every
batch enters the flight. The scheduler's look holds a head for its turn beside
the unshared hold (same gate and timer wake, await_room); a committing or
waiting thread's pass leaves such a head to the scheduler's thread
(LeftAtCommit::Turn). New counters: heads_held_for_queue_turns,
heads_let_go_turn_idle, scheduler_at_commit_left_turns. Unshared queues are
never held for a turn. FAST-PATHS gets the row; its known gap now says what
remains (a submitted batch runs to its end).

Tests: tests::queue_turns (the flight's turn math: two budgets, a later queue
not held by another's burst, repricing against the unshared bound, no run seen,
the oldest's credit, published completions); the existing unshared_hold unit
tests on the new flight API; queue_share_device::
a_later_queue_s_command_buffer_takes_its_turn_ahead_of_another_queue_s_burst on
a device under both values (Fair: the small one before the burst's fourth, heads
held; CommitOrder, the negative control: after the twelfth, none held);
fast_paths' ledger choice, keys-no-profile and exact_answers tests. API
signatures blessed; REFUSALS.md unchanged.

Also: the queue_share example's --turns fair|commit-order; the conformance probe
cross_queue_burst_turns.m (not yet run); the queue-sharing and unshared-hold device tests pin
CommitOrder so they keep testing their own mechanism. Public: QueueTurnPolicy::{Fair, CommitOrder},
DevicePolicy::queue_turns, WorkCounts::heads_held_for_queue_turns / heads_let_go_turn_idle /
scheduler_at_commit_left_turns. Default Fair per the owner's 11-03 decision (isolation outranks peak
rate); CommitOrder is today's behaviour. RUNTIME_VERSION 2490.

Verified: m3-max-38127 (msi, 37143cedda): clippy -p metal2vulkan -p metal2vulkan-runtime 0; fast_paths,
api_surface, api_signatures 51/51; queue_turns, unshared_hold, queue_share unit tests 32/32. At
079c3b7635: m3-max-38140 workspace clippy 0, rustdoc 0; m3-max-38142 --cfg m2v_gpu clippy 0;
m3-max-38141 (lavapipe) --cfg m2v_cpu_icd clippy 0, queue_share_device + queue_turns + unshared_hold +
scheduler_held_wakes 47/47: a_later_queue_s_command_buffer_takes_its_turn_ahead_of_another_queue_s_burst
passes under both values (Fair: the small CB starts before the burst's 4th, held > 0; CommitOrder, the
negative control: after the 12th ends, held 0). The 780M numbers for the row follow.
2026-11-16 16:01:06 -08:00
Anees Iqbal f19c613fe1 RUNTIME 2489: A compute or render encoder's core is made in the box it lives in: one 3 KB copy per encoder fewer
EncoderCore (2984 bytes, -Zprint-type-sizes on msi) was built by value in
EncoderCore::open, copied out of it in the returned Result, and copied again
into its box (EncoderCore::boxed / boxed_in) by the compute and render opens:
two 3 KB memcpys per encoder. A pinned LBR profile of a guest-shaped compute
stream (dispatch_chain --host 400 --only encoders --dispatches 5 --groups 64
--states 3 --binds tex-moved, msi lavapipe) put libc copies under
EncoderCore::open (~110 ns) and open_compute (~98 ns) per guest dispatch, one
encoder each.

EncoderCore::open_placed takes a place closure that puts the core where it
lies, the box for compute (parked room or the device's spares) and render
(spares), so the core moves once. open keeps the by-value form for the blit
encoder (HeldCore). Nothing else changes: the same fields, the same order
under the same lock, the same boxes.

Test: tests::compute_parked::a_compute_encoder_core_lies_in_the_box_its_command_buffer_parked (three
encoders of one command buffer find their core at one address; it pins where the core lies, not the
copy count). RUNTIME_VERSION 2489.

Verified: msi m3-max-38102: clippy -p metal2vulkan-runtime --all-targets --all-features -D warnings 0;
lavapipe debug (cfg m2v_cpu_icd) compute, dispatch, encoder, tracker and render suites 190/190. Pinned
interleaved A/B (msi lavapipe, release, taskset -c 0-7, 5 base/tip pairs, guest shape dispatch_chain
--host 400 --only encoders --dispatches 5 --groups 64 --states 3 --binds tex-moved, --runs 30): the open
call 640 -> 574 ns per guest dispatch (-66 ns); thread_cpu per dispatch within run-to-run noise (6137
vs 6240, range 5615-6681). Profile at the base (m3-max-38071, LBR): open copied the 2984-byte core out in
its Result (~110 ns) and open_compute again into its box (~98 ns).
2026-11-16 15:48:59 -08:00
Anees Iqbal ac7dffa3fd RUNTIME 2488: A spliced shadow's staged heads and tails go back as row copies too, one dispatch each where faster
A spliced copy back out of a staging buffer copied its rows' edges into
the arena region (each row's head before its first line boundary and its
tail after its last, which the host step then copies into the pages) as
one vkCmdCopyBuffer region per edge: 2N regions per copy back. On ANV,
which splices every such copy back, and on the RTX 5080 Laptop
(DriverFact::RowCopiesDispatchFaster), the driver records each region as
an operation of its own. That is the cost row_copies.rs removes.

shadow_splice::staged now puts a cut's heads (in `edges`) and its tails
(in `tails`) in separate lists. Each takes the region in the same order as
before (a row's head, then its tail), so the region's layout, the pieces
and the host step are unchanged. For rows of one shape the heads are
equal-sized and equally spaced in both buffers, and so are the tails.
SplicePlan::place makes each list a RowCopies from the staging buffer into
the region (the arena's chunks carry storage usage), beside the whole
lines' RowCopies into the truth. record_spliced records all three; the
encoder takes their stages and uses (ShadowCopy::spliced_stages and
spliced_uses: a texture buffer's shadow is read by every dispatched copy)
and retains every set.

Tests:
- tests::shadow_splice::a_staged_cut_of_equal_rows_is_three_copies_of_rows_of_one_shape_each
  checks that the cut of the validation test's shape, at three phases,
  gives whole lines, heads and tails of one dispatchable shape each.
- The staged cut's byte test also reads the tails.
- runtime_lane::row_copies::a_spliced_shadow_s_lines_heads_and_tails_go_back_as_one_dispatch_each
  (renamed from ..._whole_lines_go_back_as_one_dispatch) asserts 3 row
  copies of 96 regions, 3 dispatched where the fact holds. Before this
  change it was 1 copy of 32.
- The unforced test expects 3 copies where its copy back was spliced,
  else 1.

The three row copies live in Splice.rows (clippy's large_enum_variant refused a 600-byte variant of
SpliceCopies::Staged; nothing boxed). RUNTIME_VERSION 2488 (2487 is the early pin branch's).

Verified: msi m3-max-38042 at 777d9a3412, lavapipe, --cfg m2v_cpu_icd: clippy -p runtime -p validation
--all-targets --all-features -D warnings 0; validation 43/43 (a_spliced_shadow_s_lines_heads_and_tails_
go_back_as_one_dispatch_each: spliced 1, row copies 3, regions 96, 3 dispatched where the fact holds;
the same scenario measured 1 copy at 869519d69f, m3-max-38028); runtime shadow, splice and row-copy
tests 118/118 (a_staged_cut_of_equal_rows_is_three_copies_of_rows_of_one_shape_each: each copy meets
RowsDispatch::new's conditions, so ANV and the 5080 dispatch them: expected, not run). Plain and
--cfg m2v_gpu clippy and rustdoc in m3-max-38043.
2026-11-16 15:23:37 -08:00
Anees Iqbal 566f2da4f9 RUNTIME 2486: A spliced shadow's staged whole lines go back as row copies, one dispatch where faster
RUNTIME 2431 splices a shadow's copy back into host pages where the
device's check of those pages failed or has not answered. Its staged form
(a copy back out of a staging buffer: a 2D texture whose texels start off
their alignment, or a texture buffer) recorded its rows' whole lines as one
vkCmdCopyBuffer region a row, bypassing row_copies.rs, which every other
copy back out of a staging buffer goes through. So on ANV and the RTX 5080
Laptop (DriverFact::RowCopiesDispatchFaster), and the Iris Xe splices
every such copy back, the rows went as N regions again instead of one
dispatch, and WorkCounts::row_copies counted none.
runtime_lane::row_copies::a_shadow_s_staged_rows_go_back_as_one_dispatch
caught it on lavapipe: its device has no record of the check's verdicts,
so the copy back is spliced, and the row copies since were (0, 0) where
(0, 1) was wanted.

SplicePlan::place now makes a staged splice's whole lines a RowCopies from
the staging buffer into the truth (counted, one dispatch where the device
runs it faster); record_spliced records it; the encoder's splice records it
with the copy's stages and uses as that dispatch's (ShadowCopy::spliced_uses:
a texture buffer's shadow read by both the dispatch and the edges' copy),
retains its set, and notes the host step's write as before.

The validation test is split: its clear over the pages is a helper; the
original test keeps its contract, and
a_spliced_shadow_s_whole_lines_go_back_as_one_dispatch runs it on a device
whose check fails (DeviceOptions::fail_in_place_check), asserting the copy
back spliced and its whole lines one row copy, dispatched where faster.

Cause: shadow_splice.rs `splices` splices a copy back into host pages while the in-place check is
failed or pending (RUNTIME 2431, 9ea0a9c1f6); the staged splice recorded its whole lines as
vkCmdCopyBuffer, one region a row (shadow.rs record_spliced), never through RowCopies: N regions
where one dispatch was planned, on every device that splices (the Iris Xe always). RUNTIME_VERSION 2486.

Verified: msi job m3-max-38028, lavapipe, --cfg m2v_cpu_icd: validation 43/43 (runtime_lane::row_copies
all four, a_shadow_s_staged_rows_go_back_as_one_dispatch failing 3/3 before at 51280732aa
(m3-max-37994) and passing now; the new a_spliced_shadow_s_whole_lines_go_back_as_one_dispatch:
shadow_copies_back_spliced == 1, row copies (0, 1)); runtime shadow and splice tests 113/113; clippy
-p runtime -p validation --all-targets --all-features -D warnings 0. Plain and --cfg m2v_gpu clippy
and rustdoc in m3-max-38030.
2026-11-16 15:09:49 -08:00
Anees Iqbal 45ebbdaa5e RUNTIME 2484: Copies between a texture's region and a surface's runs of guest RAM
A consumer that keeps an IOSurface's GPU copy as one optimal texture, on a host whose surface
path copies by runs of guest RAM (copies_guest_ram: no view of the pages is made), needs the
texture forms of the run copies, or its fill, upload and download go back through a view per
block or a staging buffer.

What: BlitCommandEncoder::copy_texture_from_host_ram(ram, runs, offset, bytes_per_row, size,
texture, slice, level, origin) and copy_texture_to_host_ram(texture, slice, level, origin, size,
ram, runs, offset, bytes_per_row), runtime extensions (Metal has none). `runs` is the surface's
bytes in order (the shape the consumer's run copies pass today); offset and bytes_per_row are
Metal's copyFromBuffer layout over those bytes. Each row's texels within a run and a chunk are
one vkCmdCopyBufferToImage / vkCmdCopyImageToBuffer region straight on the chunk's import
(bufferRowLength and bufferImageHeight 0; bufferOffset a multiple of the texel,
VUID-vkCmdCopyImageToBuffer-srcImage-07975; the subresource bounds 07971/07972), with no staging
buffer. A first-touch or CPU-only chunk goes through the existing StagedGather / StagedScatter,
which now take a buffer or an image target. Hazard tracking, dirty-page reports, imports held to
completion and the bytes outside the texels are as the buffer forms keep them. Refused as the
buffer forms are, and with Invalid / Problem::HostRam for the texture's own cases (its doc
extended); no new RuntimeGap, Degradation kind or WorkCounts field: the direct form shows in
host_ram_copy_regions with no staged copy. replay.rs logs the call (HostRamTextureCopy);
blit_texture.rs and blit_plan.rs helpers are shared (pub(super)). Runtime README and HOWTO
document it; the signature table blessed (+2 methods); REFUSALS regenerated. RUNTIME_VERSION 2484.

Verified: msi job m3-max-37991 (lavapipe, --cfg m2v_cpu_icd): clippy -p metal2vulkan-runtime
--all-targets --all-features -D warnings 0; nextest host_ram_texture_device + host_ram_copy_device
39 passed. m3-max-37997: "HOST-RAM-TEXTURE llvmpipe: fill regions 250, dispatches 0, staged 0" (a
300x200 BGRA8 Private texture, rows at 1280 bytes from byte 48, one row across a chunk end); the
staged test saw exactly one staged gather and one staged scatter. Plain and --cfg m2v_gpu clippy,
rustdoc and the 780M and Iris runs follow on development.
2026-11-16 14:53:52 -08:00
Anees Iqbal 3619e37540 RUNTIME 2482: Texture::view_placement answers what a view would be, by the decision its making takes
The consumer will make an IOSurface plane's device cache one optimal Private texture, every
texture over the plane a view of it, and needs to know before it makes a view whether the
runtime would make it a Vulkan view of the image or a view shadow (which it sends to its own
fallback instead).

What: `Texture::view_placement(pixel_format)` answers `ViewPlacement` (`Image`,
`ImageThroughSwizzle`, `Shadow(ViewShadowReason)`, `OverBytes`), or the error
`new_texture_view` would refuse the view with. The decision is factored, not copied:
`Texture::checked_view` holds the checks `view_as` ran inline (Metal's rules, rotation, X32,
buffer slices, decoded twins), `Texture::view_hold` decides the storage (shared, through a
swizzle, the viewed image, a shadow and why, storage over the bytes), and
`Device::view_shadow_plan` / `shadow_plan` hold the shadow's refusals `image_shadow` checked
while making. `view_as` and the query call the same three. `image_plan::views_missed` replaces
`takes_views_of` and names why an image takes no view (another compatibility class, or not in
its list); `Device::view_apart` replaces `image_takes_view` and puts the device's missing
reinterpretation first; the `shadowed-texture-view` notice's reason now follows that reason
(it chose by the texture's PixelFormatView usage before).

Tests: `view_placement_device` (runtime, device cfgs) sweeps 10 texture formats x 5 usages x
24 view formats, checks the query moves no count and matches the view made (by
`view_shadows`, `views_through_swizzle` and the handed-out image), and names the consumer's
cases. `plane_device_cache` (validation lane): a 300x200 BGRA8Unorm Private texture round-trips
between no-copy buffers at offset 48 and pitch 1232 with every other byte kept; a clear through
its sRGB view then a copy through its own-format view in the next encoder, tracked and
untracked with a fence, read the clear with no hazard under synchronization validation, and the
unordered control is reported as a read after write.

Documented in the runtime README; the signature table blessed (10 rows); REFUSALS regenerated.
RUNTIME_VERSION 2482.

Verified: msi job m3-max-37961 at c2f0c96d3c: clippy -p metal2vulkan-runtime -p
metal2vulkan-validation --all-targets --all-features --cfg m2v_cpu_icd -D warnings 0; the lavapipe
tests, plain and --cfg m2v_gpu clippy and rustdoc follow on development. The hazard tracker keys a
view's uses on its image (texture.rs view_as shares the Arc<Image>; bound_use/image_use key on
image.identity.key), so the order across views needed no fix.
2026-11-16 14:48:17 -08:00
Anees Iqbal d8b39b12d1 SEMANTICS 2141 / RUNTIME 2481: Read short constant windows through uniform texel buffers on the Iris Xe
What: on a device whose profile takes the new cost fact
DriverWorkaround::ExternalUniformReadsSkipACache (ANV on the Iris Xe of
RPL-P alone), a buffer slot's uniform view whose window the translation
bounded to at most TEXEL_WINDOW_BYTES (4 KiB) is declared as a uniform texel
buffer (UniformConstant image, Dim Buffer, Sampled 1, u32 texels) and read with
OpImageFetch; the plan's form is DescriptorView::UniformTexel, its descriptor
UNIFORM_TEXEL_BUFFER, its use class Sampled, its range the uniform view's own
under minTexelBufferOffsetAlignment and maxTexelBufferElements. Every other
uniform view stays a uniform buffer exactly as before. The runtime makes an
R32G32B32A32_UINT view of the planned range for each write, with no cache,
holds it until the command buffer completed (State::retain_own, which also
keeps an indirect chunk that made one from being kept), and binds whole a draw
rebound or carried at such a slot. The zero buffer takes the uniform texel
usage, and upload regions align to the texel offset alignment too.
ARTIFACT_FORMAT_VERSION 525 (DescriptorView gains a variant); SEMANTICS_VERSION 2141, RUNTIME_VERSION 2481.

WorkCounts: uniform_texels_bound; uniform_buffers_bound_to_16k (a bound
buffer's uniform view written as a uniform buffer, window at most 16 KiB: on
the Iris the 4-16 KiB ones); uniform_buffers_bound_past_16k (longer, or not
bounded).

Why: ANV gives external memory MOCS 61 on Gen12.0, which loses the HDC L1
that uniform buffer reads go through; the sampler path keeps its cache. On the
Iris, a UBO over imported memory ran 2.0-2.5x (and 5.2-5.5x for a divergent
index) the time of device memory, a uniform texel buffer 0.98-1.04x (jobs
m3-max-37703, 37729). The window sweep (37753, 37780) set B: at 1 and 4 KiB
texel-set was no slower than ubo-set on device memory in every pattern; at
16 KiB one row was 3.1% slower; from 32 KiB per-lane patterns 2.8-4.2x.

B = 4 KiB covers the consumer's binds only where the kernel's window (its
struct size or accessed hull) is at most 4 KiB. The counting walk counted
buffer sizes, not windows, so the new counter will tell.

The cost of a view per write: vkCreateBufferView+vkDestroyBufferView 0.082 us
on the Iris (mean of 4000), vkUpdateDescriptorSets 0.007 us against a uniform
buffer's 0.024. A set 0 naming a fresh view is found again by no later
command, so such commands lose set-0 reuse.

Tests: engine_access (the texel form's module, its interpretation at
residuals 0, 4, 16 and 256, the window bound, the slot's plan), the profile
fact's carriers, and a lavapipe test whose compile device takes the Iris's
identity (cfg(test) DeviceOptions::compile_as): offsets 0, 4, 16, 256, 260,
set*Bytes data, bytes written before encoding, after it and by a blit, and a
4100-byte window kept as a uniform buffer, with the counts as evidence.

Also: the fixture uniform_texel_windows's AIR companions (job m3-max-37901); a texel form's
loop-invariant fetches move out of their loops as a uniform block's loads do (spirv::hoist, with
its test); the texel form documented (ARCHITECTURE, FAST-PATHS, view docs, runtime README); the
API signatures blessed.

Verified: msi job m3-max-37946 at 00121399e7: fmt check 0, clippy (plain, --cfg m2v_gpu,
--cfg m2v_cpu_icd; --all-targets --all-features -D warnings) 0, rustdoc -D warnings 0. Touched
suites running in the same job. Golden table and engine fixture inventory re-bless on development.
2026-11-16 14:46:29 -08:00
Anees Iqbal 8bcaf69f1d RUNTIME 2475: Compute dispatches instantiate over the commands their bind state kept
What: BindingPlan::instantiate_dispatch_into writes a dispatch's commands over a kept
DispatchCommands, every field set as instantiate_dispatch sets it, the vectors keeping their
storage: each region's specialization (spec_key_into, region_specialization_into) and push
write's bytes, the argument table's bytes, the ranges, extents, holes and uses.
instantiate_dispatch is that method over no commands. The regions a dispatch plans take no list
of each axis's pieces (`Pieces`, numbers alone). In the runtime, compute::Instantiated keeps its
commands as storage when a value they may read moves, and a direct dispatch that instantiates
writes over them where nothing else holds them (the memo entry they were taken into is replaced
first: a dispatch that instantiates settled anew); builds with debug assertions instantiate
afresh and compare. WorkCounts::dispatches_instantiated_in_place counts them.

Why: a guest's compute encoders bind their buffers at moving offsets, one dispatch an encoder,
so their kept commands never serve again (reims's Iris walk: 96.6% of dispatches instantiated
anew). Profile (msi lavapipe, dispatch_chain --host 400 --only encoders --dispatches 5 --groups
64 --states 3 --binds tex-moved, calling thread): instantiate_dispatch 5.6% of its CPU, about
600 ns a dispatch, of it translator instantiate 3.4%, regions 1.6%, region_specialization 1.1%;
about fifteen allocations each instantiation. The commands read the buffer bindings that move,
so no memo of them is exact for this shape: the cut is the work of making them.

Verified: tests::bind::dispatch's
instantiating_over_kept_commands_gives_a_fresh_instantiation (more regions, fewer, none, another
state, the key's storage kept); compute_instantiated's
encoders_of_moving_offsets_instantiate_over_the_kept_commands (five encoders of one command
buffer: 5 instantiated, 4 in place, each writing at its own offset), on lavapipe.

Checks at the lane tip d52118ce95 (msi): clippy -D warnings --all-targets --all-features for metal2vulkan and the runtime, plain (m3-max-37686), m2v_cpu_icd (37688) and m2v_gpu (37689), all 0; rustdoc -D warnings 0 (37689); the translator bind::dispatch, plan::compute and graphics tests 42/42 (37686); the runtime compute, dispatch and encoder tests on lavapipe in a debug build, so every in-place instantiation was compared with a fresh one, 244/244 (37688). gem10 lavapipe m3-max-37685: dispatches_instantiated_in_place 0.80 a dispatch on the tex-moved row, every instantiation; that run's timing was unusable (rows the change does not touch moved more than the cut); one interleaved timing run follows.

With: dispatch_chain: an encoder's dispatch binds as its command buffer's dispatch index says (aac8651f23): at development the encoders shape never moved offsets or swapped textures.
2026-11-16 13:03:25 -08:00
Anees Iqbal 3a3d31c374 RUNTIME 2470: Rebinds: a rebind before the submission of an encoder no rebind encodes again is refused
A rebind between a command buffer's commit and the submission of its last
event group, of a buffer an encoder of it named that keeps no log (a compute
encoder its unit of command predication reaches past, a loop's laying, a
render encoder opened while no buffer over host pages existed), failed that
submission EncodedUseRebound: the commit let go of its holds, and nothing
encodes the encoder again. The consumer's answer table ends the VM on that
kind. Now the rebind is refused instead (EncodedUses), and the command buffer
runs over the pages it was encoded over.

- State::keep_replays also answers whether an encoder that keeps no log
  (not one its commit fails, which runs nothing) named a buffer over host
  pages, by its own commands or by work it left for later not recorded on
  the GPU alone (State::unlogged_names_a_pin).
- Where so, the commit keeps the command buffer's holds
  (State::held_to_submission) instead of letting them go:
  Holds::hold_to_submission moves each from Entry::pending to a new
  Entry::unsubmitted under one lock of `buffers`, so no rebind falls
  between. They go as the last event group's first batch is submitted
  (State::first_submission, State::later_group), or at completion; a
  rebind after that keeps the old pages for the submitted work, as before.
- replace and the rebind's first check refuse while `unsubmitted > 0`,
  counted as their own reason: WorkCounts::rebinds_refused_unsubmitted.
- Cost: nothing new for a command buffer whose encoders a rebind encodes
  again (one pass over its ended encoders' flags at the commit, inside
  keep_replays). A host-step command buffer keeps holding to completion
  (steps_hold), unchanged.

Deadlock audit, by lock:

- Commit: hold_to_submission takes `buffers` under the command buffer's
  `state` lock: state -> buffers, the order encode_moved's Submitting and
  the commit's own clear of its holds already take.
- Submission: the holds go under the scheduler's lock and `state`, after
  the `Submitting` guard (`buffers`) was dropped; each Holds' drop takes
  `buffers` alone: scheduler -> state -> buffers, the order the
  submission's judging already takes. Never under `buffers` itself.
- Completion: moved out of `state` and dropped after its lock, with the
  submitted holds.
- Nothing waits on them: a rebind finds `unsubmitted` and is refused; no
  wait is added anywhere, so no cycle can form.

Tests (lavapipe): rebind_races gains a control (the predicated family
committed behind an unsignaled shared-event wait, rebound before the
signal: refused, completes over the old page, refused-unsubmitted 1), and
the threaded run asserts no command buffer fails EncodedUseRebound. Tests
that asserted the old outcome of such a rebind now assert the refusal and
a completion over the old pages: pending_rebind, rebind_loop_check's
rebind before the laying's submission, tile_rebind_making_wait's
unlogged tile pass, and validation's rebind_reach test of a unit's
encoder that laid its first step. The validation lane no longer has a test
that announces encoded-use-rebound (degrade_notices says so).

Docs: rebind.rs module docs (ordering rule, a predicated loop's laying),
Buffer::rebind_bytes_no_copy, RebindProblem::EncodedUses, the
encoded-use-rebound catalogue entry and its declaration, runtime README;
api_signatures blessed.

Follow-ups in the same landing: Rebinds: a state's reset takes held_to_submission fresh too; Rebinds: clippy (append, take) in the hold-to-submission moves.

Checks (lane rebindsafe2): clippy plain (runtime, validation) 0 at 5bfab2beaa in m3-max-37364; lavapipe runtime tests 356/356 at a0fc57f283 (m3-max-37354: rebind, detach, host_page, host_step, indirect, predication, pending, holds, encoder_fold, deferred_calls), the new control refused with refused-unsubmitted 1 and the threaded run asserting 0 EncodedUseRebound. Validation lavapipe (m3-max-37365), rustdoc and the cfg clippy runs follow on development.
2026-11-16 11:23:09 -08:00
Anees Iqbal 5acd27cd0d RUNTIME 2468: Rebinds: a call of an encoder the runtime cannot encode again never races a rebind
After RUNTIME 2465 a rebind racing an encoder call on another thread is
detected and the encoder encoded again; one the runtime cannot encode again
(a compute encoder its predication unit reaches past, one that left a
GPU-written indirect dispatch to its host step, a render encoder that keeps
no log) failed EncodedUseRebound at submission instead, which a consumer's
answer table treats as fatal.

The protocol: those encoders' calls are gated, so no publish overlaps one.

- Rebinds gains `calls` (gated calls under way). A gated call begins
  (`Holds::begin_call` -> `CallGate::enter`): calls += 1, then reads `open`;
  where a publish is open it backs off and waits for it to close
  (`wait_published`), before it reads anything of a buffer over host pages.
- A rebind's publish now opens before its replace (`Rebinds::quiet_calls`):
  open += 1, then reads `calls`; where a call is under way it waits for the
  calls to end (`drain`/`drained`), up to CALLS_DRAIN (2 ms), and is refused
  past it (EncodedUses, Unreplaced::Calls), never failing the encoder later.
  The four accesses are SeqCst (a store-buffering handshake: of a rebind and
  a call that meet, at least one reads the other's rise), so each gated call
  reads the buffer wholly before the publish (holding it, which refuses a
  rebind until its commit) or wholly after its close. Chosen over the
  registry lock: the call side costs two atomics and takes no lock.
- Which encoders: every compute encoder, and a render encoder that opened
  with no log. A compute encoder can become unreplayable mid-encoding (the
  call that records predication, a loop's record, an unbalanced record that
  leaves work out, a later encoder of its unit that lays a loop, a dispatch
  left to its host step), after earlier calls ran: a gate that started at
  that transition would leave those earlier calls racing. So the gate covers
  a compute encoder from its open. Blit encoders always log, and render
  encoders with a log, stay re-encodable and pay nothing new. A device with
  no buffer over host pages pays one Relaxed load per gated call (`any`).
- Nesting: a thread-local depth, so a call an encoder's call makes of its own
  public calls (a blit's unlogged calls, a loop's copies) never waits.
- WorkCounts: rebinds_refused_calls_in_flight (the retry rate),
  encoder_calls_held_by_rebind, and encoders_raced_unreplayable (raced
  encoders committed with no log: each fails EncodedUseRebound; zero now).

Deadlock audit, extending 2465's, by lock:

- `drain`: taken by a rebind waiting for the calls (no other runtime lock
  held: rebind_host_pages holds no lock across replace) and by a gated
  call's end, which holds none of the runtime's at its end. Nothing is
  taken under it.
- `buffers`: `unopen` takes it alone to lower `open` and notify `closed`
  (so a waiter between its check and its wait cannot miss it); a gated
  call's back-off waits on `closed` under it, holding at most its render
  deferral's `lowerer` lock (lowerer -> buffers is the order holds already
  take). No publish step takes `lowerer`; the rebind's `lower_all` runs
  before the publish opens.
- The rebind's wait for calls is bounded (2 ms), so a gated call under way
  that waits on a thread held at a gated begin (a render end waiting for
  its lowering) ends in a refusal, not a deadlock. A gated call waits only
  as it begins, never under way, and the publish waits for nothing an
  encoder holds (2465's audit), so every begin's wait ends when the open
  publishes close.

Docs: the Safety text of Buffer::rebind_bytes_no_copy and
Heap::rebind_bytes_no_copy, the rebind.rs **Other threads** bullet and
RebindProblem::EncodedUses state the new outcome: refused, never failed
later, for the gated kinds. api_signatures.tsv gains the three fields.

Tests (src/tests/rebind_races.rs): a pause-point control (a predicated
dispatch, Unlogged::Predicated, held at its hold while the main thread
rebinds: the rebind refused, the command buffer completes over the old
page, refused-for-calls 1); the threaded run gains a predicated family and a
host-step family (an indirect stage-in region, Unlogged::Segments), and
asserts encoders_raced_unreplayable == 0.

Follow-up in the same landing (cc0b4592a3): Rebinds: the refusal reason carries no pages (clippy: field never read).
Unreplaced::Held and Unreplaced::Calls no longer give the new pages back:
replace drops them once the registry's lock went (unopen drops the guard
first), as the caller's map_err dropped them before. Also the docs of the
encoded-use-rebound notice (degradation.rs, docs/API.md) and the runtime
README say which encoders still fail it after a race (a blit or logged
render encoder whose commit failed it, or whose encoding again a call that
answers otherwise refused) and that gated calls never race.

Verified: m3-max-37298 (msi) clippy at ec3cbb49c7 failed on exactly these
two fields; the next job checks this commit.

Checks (lane rebindsafe2): clippy plain (runtime, all targets, all features) 0 at cc0b4592a3 in m3-max-37302; lavapipe rebind/detach/host-page/host-step/indirect/predication/pending/holds suites with the gated control and the six-family threaded run in m3-max-37299 (ec3cbb49c7, same library code), the gate-off negative control, clippy GPU/CPU-ICD cfgs and rustdoc follow on development.
2026-11-16 10:59:33 -08:00
Anees Iqbal 2bafb6537a SEMANTICS 2138: Fragment simdgroup lane: run it on Cluster32 tiers, refuse it only below 32 lanes
What: a fragment function that reads [[thread_index_in_simdgroup]] on a profile
without DriverDeviation::MetalFragmentSimdgroups was refused Unsupported{SimdWidth}
on every tier but Direct. It is now refused only on Tier::PartialFragment (fragment
subgroups narrower than 32). On Tier::Cluster32 (a 64- or 128-lane fragment stage,
e.g. RADV on Polaris, wave64 only) the lane is the subgroup lane's low five bits.

Why: the guest is told an Apple GPU's width, 32 (threadExecutionWidth 32,
[[threads_per_simdgroup]] the constant 32), and its shaders are built for 32-lane
simdgroups. On Cluster32 each aligned 32 lanes of the device's subgroup is one
simdgroup. The function's simdgroup operations already ran there, and the emitter
already gave the lane as L & 31 (group::Lane::metal), the same cluster the shuffles
and ballot words use. So the device lacked nothing; the refusal was ours. The lane
is the device's grouping, which Metal allows, and records the existing
PrecisionNote::FragmentSimdgroupGrouping as before.

Tests: engine_simd's fragment-lane test also runs on wave64() (the committed RDNA3
description narrowed to 64 lanes) and requires every lane form to compile there on
Cluster32 with the note, the low-bits mask and L3. Without the fix it is refused and
the test panics. Device test fragment_simdgroup_lanes_are_metal_s accepts the
SimdWidth refusal only where the fragment stage's sizes are all below 32, so on a
wave64-only device it fails without the fix; it also prints the stage's sizes.

Docs: the note's text in docs/API.md and PrecisionNote, the doc comments in
lower::simd. SEMANTICS_VERSION 2137 -> 2138. REFUSALS.md regenerated, unchanged.

Checks (lane simd64): msi m3-max-37237 clippy plain 0, tests 88/88 (engine_simd, public_fixtures_engine, fast_paths, device::tests::subgroup); m3-max-37255 clippy GPU and CPU-ICD cfgs 0, rustdoc 0. The RX 550 run (m3-max-37259) follows on development.
2026-11-16 10:47:52 -08:00
Anees Iqbal 35ac917d6f RUNTIME 2466: GPU start: written before the batch's first work, and at the top of the pipe on every driver
What: a timed command buffer's first batch with first work (new resources'
first moves and zero fills, Managed copies in, staged copies) writes its start
timestamp in that work's command buffer, after an execution barrier from every
command before and before the work; and every start is written at the top of
the pipe, where batches ordered by their ends wrote it at the bottom.

Why: GPUStartTime must say when the GPU began the command buffer's work. In a
traced Geekbench-like compute pass on an RX 7900 XTX (RADV, Mesa 26.2.6), the
gfx ring's drm_sched jobs placed on the trace's clock (the job trace drifts
39.8 ppm against it, fitted per pass) showed command buffers whose start lay
in the last tenth of their own job: spans of 1 us on jobs of 4.5 to 36.5 ms.
Two causes. (a) The first work is inserted ahead of the start, and the start,
at the bottom of the pipe under by-ends ordering, waited for it: managed copies
in of the guest's did_modify_range ranges were 0.25 to 6.98 GB per workload.
(b) With no first work too (prefixed starts, 237 first-work batches of 7486),
about 1700 command buffers read their bottom-of-pipe start late; a Radeon 780M
showed the same. That GPU time counted as "submitted, GPU not started" in the
consumer's split: 4.06 s of its 5.90 s on the XTX.

Ordering (every driver path): the first work's start follows an execution
barrier ALL_COMMANDS -> ALL_COMMANDS, whose "first synchronization scope
includes all commands that occur earlier in submission order" and "second
synchronization scope includes all commands that occur later in submission
order" (vkCmdPipelineBarrier), the timestamp write among them. A start at the
top of the pipe where batches are ordered by their ends is held by the earlier
batch's end barrier, Barrier::to_all (src ALL_COMMANDS, dst ALL_COMMANDS and
HOST), by the same clause. Where batches are not ordered by their ends the
starts were at the top already and are unchanged; a start after a barrier
planned before the first encoder stays at the bottom, after that barrier.

Whether Metal's span holds a Managed copy in on a Mac with a discrete GPU is
not measured (the 5300M oracle can say).

Verified: compile and device runs pending (tests/start_stamp.rs).

Also folded: the test of a command buffer's GPU start against its own long work and its batch's
first work (e86e9d356e).
2026-11-16 10:17:56 -08:00
Anees Iqbal 372cf95641 RUNTIME 2465: Rebinds: an encoder call that races a rebind on another thread is encoded again
rebind_bytes_no_copy (Buffer and Heap) may now run while other threads encode and
commit command buffers that use the buffer or heap. Before, the Safety contract
excluded that; this lifts it.

The windows found:

- W1: an encoder call reads a buffer's pages before it holds the buffer. A
  dispatch builds its bind state, a draw its tables, and a blit reads the
  VkBuffer for a copy run that records in a later call. A rebind can land
  between that read and the hold. The hold then pins the new pages while the
  commands name the old ones.
- W2: what lies over the bytes (aliasing images and their views, texel views,
  the heap sets' elements) is made over the new pages only after `replace` has
  let go of the registry's lock. A hold in that gap pins the new pages over
  half-made state.
- W3: the render lowering thread does the same reads, later.
- W4: an encoding again (`replay.rs`) can run under a concurrent rebind of
  another thread. This one is a live defect under today's contract: a commit's
  rate-map or split re-encode, and one rebind's turn racing another buffer's
  rebind.
- W5: a texture made over the bytes during the call stays excluded.

The change: detect, then encode again. Nothing waits on the encode path.

- Each rebind's publish runs from `Rebinds::replace` to a new
  `Rebinds::published`. `published` is the close, after `renew_over`. It is
  tracked by a per-device count of closed publishes (`published`), a count of
  open ones (`open`), and `Entry::publishing` / `Entry::published`.
- Every encoder call loads that count as it begins (`Holds::begin_call`: one
  Acquire load of an AtomicU64). The sites: compute and blit `logged`,
  `end_encoding`, the five predication calls, render `Lowering::logged`, the
  deferral's `at_call_unit`, the replay dispatcher and `open_render`, which
  reads the count before it reads the attachments.
- A hold or pin finds the call raced when the entry's publish is open, or
  closed after the call began. A raced Taken counts as rebound
  (`Submitting::rebound`), so the commit encodes its encoders again before the
  first submission (`State::raced_again`), as for a rate-map reset.
- `reencode` loops: when an encoding again itself raced, it waits until no
  publish is open (`Rebinds::wait_published`, a condvar on `buffers`) and
  encodes again.
- The close marks again the command buffers committed while the publish was
  open, so their raced encoders are encoded again over finished state.
- An encoder the runtime cannot encode again whose call raced fails
  EncodedUseRebound at its submission. These are the existing list: a compute
  encoder its predication unit reaches past, one that left a GPU-written
  indirect dispatch to its host step, a blit or render encoder opened while no
  buffer over host pages existed, one whose commit fails it, and one with a
  call that answers otherwise. A rebind that no encode overlaps changes
  nothing for them.
- New WorkCounts::encoders_raced_rebind counts the encoders marked stale this
  way.
- `blit_at` holds the buffer before it reads its VkBuffer, because a copy run
  records in a later call.
- `replace` refuses a second rebind of a key whose publish is open
  (EncodedUses).

What the publish window covers:

- Inside it: `live_buffers.rebound`, the alias leave/hold/place, the image
  swaps and parking, the texel views, `forget_stale` and `renew_over`.
- Moved after the close: dropping the read twins (`drop(twins)`), dropping
  the old pages (`drop(old)`, which reaches vkDestroyBuffer/vkFreeMemory and
  the deallocator), `release_held_back`, `heap_sets::retire` and the
  encodings again.
- What a later pin judges against: the old pages' twins and the stand-ins.
- Not covered: the import of the new pages and the images made again over
  them before `replace`. These are the rebind's own and are invisible to
  other threads until `replace`.

Deadlock audit, by lock:

- `rebinds.buffers`:
  - `hold` and `pin` take `buffers`, then the cell's `pages` (`lying`), and
    hold nothing across them.
  - `replace` takes `buffers` -> `waiting` (`mark_waiting`) and `buffers` ->
    `pages` (`cell.replace`).
  - `published` takes `buffers` -> `waiting`. `mark_reencode` is an atomic.
  - No thread holds `waiting` or `pages` and then takes `buffers`.
  - The existing `state` -> `buffers` order (`encode_moved`'s `submitting`)
    is unchanged. Neither publish step takes a command buffer's state lock.
- `wait_published`: its callers hold only the command buffer's `reencoding`
  turn. These are the commit (after its state and slot locks are gone) and a
  rebind's or commit's `reencode`. No publish step takes a `reencoding` lock
  or waits for one. A publish waits for nothing: these take no lock an
  encoder holds across a hold:
  - `live_buffers.inner`;
  - `aliases`;
  - the image swap and view locks (`Image::swap_in`);
  - HostPages `parked`;
  - `rebinds.stale`;
  - the texel views;
  - `heap_sets`: `passing_hold` and `heaps`, whose writes are deferred while
    `heaps.holds > 0`, with no wait.
  So every wait ends as soon as the open publishes close.
- The test pause points (`rebind::pause`, cfg test) stop at the hold, with
  no runtime lock held, and in the publish after `replace` has let go of
  `buffers`.

Docs:

- The Safety text of Buffer::rebind_bytes_no_copy and
  Heap::rebind_bytes_no_copy states the new contract and outcomes. Still
  excluded: another rebind or a detach of the same buffer or heap, a texture
  made over its bytes, and a resource placed in the heap, during the call.
- The rebind.rs module docs gain an **Other threads** bullet.
- Also updated: the EncodedUseRebound declaration and its docs/API.md
  catalogue entry (the cost text is unchanged), the `renew_over` doc and the
  runtime README.
- api_signatures.tsv gains the new field.

Tests (src/tests/rebind_races.rs, device tests):

- A pause-point control at the hold: a dispatch that read the bound buffer
  before its hold, with a second buffer keeping the old import. Expected: the
  new page's output and one raced encoder.
- A pause-point control in the publish: a dispatch reading a texture over the
  buffer.
- A threaded run: four families (a dispatch of a texture over K, a draw with
  K as a vertex buffer, a blit copy from K, and a dispatch bound a call
  before) against a rebinding thread. Each output must be wholly one page of
  those K lay in meanwhile, or EncodedUseRebound.

Hot path: one Acquire load per encoder call (begin_call) plus one compare
under the lock the hold already takes. Per-call numbers follow in the bench
commit or report.

Also folded: the threaded run reports the pages its outputs read and each wrong output's reason
(060e8219f0); and a publish's close counts as a move (buffer::host_cells_settled), so a binding read
during the publish (a texel view for one) is not kept under the post-replace count and reused
by a later encoder that did not race; debug checks (check_reading, compute check_whole,
KeptSpaces::of) hold off where a call may have raced (rebind::call_may_have_raced, debug only)
(0c7a7a5c98).

Verified (lavapipe, msi): m3-max-37154 at 0c7a7a5c98: clippy plain and --cfg m2v_cpu_icd 0;
rebind*, pending_rebind, degradation*, argument_table, live_bind 41 passed; the hold and publish
controls raced 1 and completed; the threaded run (4 threads x 25 command buffers: a dispatch over
a texture over the buffer, a draw with it as vertex buffer 1, a blit from it, a dispatch bound a
call before) read every output wholly from one page, 0 EncodedUseRebound, 63 rebinds made, 1,537
refused (EncodedUses), 5 encoders raced, 11 encoded again. Negative control m3-max-37156 with
Entry::raced forced false: the hold control fails (the dispatch read the pages the buffer left).
2026-11-16 10:16:14 -08:00
Anees Iqbal 49b25c189c RUNTIME 2464: Parked dma-buf images released at the next pass where held imports tax submissions; each whole guest RAM import said with its time
A parked image (an in-place image over a no-copy buffer's dma-buf pages, kept for the next
texture over the same pages) is one more imported memory on every kernel submission's list on
RADV and ANV on i915. On the Radeon 780M that costs about 0.46 us a submission (m3-max-36970:
167 against 6 listed memories, 86.8 against 13.7 us a submission), 0.53 ms a second at the 1,150
submissions a second of a guest's desktop. Held 2 s (released by the first pass at least 2 s after
the park, passes every 0.5 s), an untaken park cost 1.06 to 1.32 ms of vkQueueSubmit time, while a
take saves its texture's making: on the 780M 0.13 ms (7.9 MiB) to 2.6 ms (84 MiB) over 2 MiB
pages, 0.73 to 24.3 ms over 4 KiB pages (texture_shadow_bench, m3-max-37048, medians). In a
guest's desktop walk on the 780M, 443 of 2,098 parks were taken; at 2 s the parks cost about 2.0
to 2.5 s of submit time, which pays only where a take saves 4.5 ms or more on average.

Where Device::pointer_imports_tax_submissions holds, the residency thread now releases a parked
image at its first pass after the park (held 0 to 0.5 s, 0.25 s on average); elsewhere, where a
held import costs no submission, the 2 s window stays. The cap of 64 parked images stays.

Expected, not measured: takes come soon after their park (a guest wrapping the same surface again
a frame or two later), so most still hit; an untaken park then costs about 0.13 ms instead of
1.2 ms, and a desktop walk at the cap holds about 10 parked images instead of 64. The proof is a
guest's desktop walk on the 780M before and after: dma_buf_images_taken against
dma_buf_images_missed, dma_buf_images_parked_released, and batch_submit_nanos per submission.

Tests: dma_buf_parked_images now forces the import tax: with Fails, a pass right after the park
keeps the image; with Holds, the next pass releases it (fails without the change: the 2 s window
keeps it). texture_shadow_bench's in-place arm parks its image in a warm-up within its own cycle,
outside its times and counts, so its texture still takes one: the other arms between two of its
cycles run longer than a pass.

Documented in host_residency.rs, dma_buf/parked.rs and docs/HOWTO.md. No new Degradation kind; not
an accuracy choice, so no FAST-PATHS row.

Also folded:

Guest RAM: say each whole import, with its time; bench it at 2, 4 and 8 GiB and across a recovery

A device that imports a resident guest RAM whole as its use begins now says so once on its
message sink (id name metal2vulkan-host-ram, Info): the bytes and chunks imported, those left to
the copies, the imports' time and the first listing's (the submission of no work it waits for).
A consumer then sees the one-time wait at setup in its log, and at each recovery of the device,
whose carry makes the use again on the new device before it serves, so the new device imports the
RAM whole in turn on the recovering thread.

Tests (host_ram_whole.rs): the resident RAM says the line once, naming its bytes and its one
chunk; the RAM with a hole says nothing; a recovery imports the resident RAM whole again before
recover_for_test returns, and says so again. The ignored whole_ram_bench runs 2, 4 and 8 GiB RAMs,
each on a device of its own, each with a hole and then resident, the resident one recovered,
printing the device's lines.

Documented in host_ram.rs (the module docs and use_host_ram) and docs/HOWTO.md.

Guest RAM recovery test: read the chunks of the generation that serves

a_recovery_imports_a_resident_ram_whole_again_before_the_new_device_serves read the RAMs through
the root handle, whose own generation the recovery lost, so it found none and passed without
asserting (m3-max-37099: "the new device does not import the RAM whole ([])", while the same run
counted one chunk imported ahead in the recovery and heard the second line). It reads them through
Device::current now, the generation that serves.

The docs give the 780M's measured whole-import times at 2, 4 and 8 GiB (m3-max-37099): the
imports 0.05, 0.08 and 0.1 s, the first listing 0.43, 0.63 and 0.51 s.

And: whole_ram_bench times the first commit after the chunks' imports apart (dbc707372d); one
doc line rewrapped (0d19c052f8).

Verified: at ae6ae7876a clippy x3 (m3-max-37116 CLIPPY_GPU=0; m3-max-37117 CLIPPY=0, CLIPPY_CPU=0,
DOC=0, 20 host_ram unit tests, lavapipe host_ram_whole/dma_buf_parked_images/host_residency 13
passed: the parked check kept with the tax forced Fails, released with Holds). PHOENIX
(m3-max-37099, at c894bbdb13): whole import 2/4/8 GiB: imports 56/77/102 ms, first listing
441/633/511 ms, use_host_ram 532/759/690 ms; recoveries 507/768/716 ms; the lazy first commit
today 429/639/510 ms.
2026-11-16 10:03:48 -08:00
Anees Iqbal df87983bb7 RUNTIME 2463: Render draws: the restarted list and the error and notice makers out of line, cold
What: draw_resident's restarted-list arm (the index rewrite and gather requests, 205 source lines)
is its own #[cold] #[inline(never)] method, restarted_list; Device::degrade, degrade_copied_pages,
degrade_host_step, degrade_where and tell, and error.rs's vulkan, invalid, nil and internal are
#[cold]. Same commands, barriers and answers; only where the code lies changes (draw_resident 130.7
-> 127.4 KB of machine code). Also folded: draw_costs gains a guest shape of a few render encoders
with set_bytes and each thread's CPU a draw (17126bfe04), the encoding thread's own CPU apart from
unnamed threads (afa24f4074), and --calls counting each call's cycles and cache misses (7249f6930b).

Why: on a Zen 4 host a one-draw render pass ran at IPC 0.79 against 1.7 inside a long pass, the
same on RADV and lavapipe (gem10, m3-max-36911/36975). The misses are instruction fetches: per pass
about 8.3k L2 instruction misses against 1.2k data, over 806 distinct 4 KiB code pages (more than
the L2 iTLB's 512), no function above 7.5% of them (m3-max-37017, -37041). This change is
measured neutral (m3-max-37061, lavapipe, release: pass1 instructions 112,257 -> 112,123, L2
misses 10,590 -> 10,577; cycles within the node's noise) and kept as correct and neutral; the
lever left is the layout of the path's code across pages, a build setting of the program.

Verified: see the landing's check jobs.
2026-11-16 09:43:35 -08:00
Anees Iqbal 0da1b0a342 RUNTIME 2462: Guest RAM: a resident, kept RAM takes chunks past 512 MiB, all imported as its use begins
On a device whose every held import costs each kernel submission (RADV, ANV on i915), a listed
guest RAM's chunks stopped at LONGEST_LISTED_CHUNK (512 MiB), our own constant: an 8 GiB guest
listed up to 16 chunk imports in every submission (the consumer's Iris Xe desktop: 15 live, about
4.7 ms/s at 0.35 us each and 1114 submissions/s). The cap bounds memory alone: a chunk's import
pins every page of it, and udmabuf allocates the pages of the guest's memfd that the guest never
touched. A RAM the VMM preallocated has every page allocated already, so there the cap bounds
nothing.

ram_plan now asks listed_chunks_of: where the cap would cut a range into more chunks than the
source's and the device's limits do, the chunks are kept (releases_idle_chunks false), and every
page of the RAM is resident as the use begins (every_page_resident: mincore over the ranges, a
chunk at a time, stopping at the first page missing), the chunks run to those limits (4032 MiB on
RADV and on ANV, whose maxStorageBufferRange is 4 GiB less one byte: an 8 GiB RAM in 3 chunks) and
the plan is whole. A whole plan's chunks are all imported on the calling thread before
Device::use_host_ram returns (Device::import_whole, counted as chunks imported ahead), then one
internal submission of no work is made and waited for: the first kernel submission that lists a
chunk just imported waits while the kernel writes its page tables, and every other submission of
the device waits with it (the VM's page-table lock), so that wait falls in the use's start, before
the guest's work, never inside a later submission. Vulkan used: the chunk import as before
(vkAllocateMemory with VkImportMemoryFdInfoKHR) and vkQueueSubmit with a fence, waited for. A RAM
with a hole, or one too long to keep, keeps the cap and its lazy imports as before.

listed_chunk_bytes now gives the limits' length alone; the cap moved into listed_chunks_of. The
module docs, use_host_ram's, Plan's, the imported-ahead count's, HOWTO section 6 and the
FAST-PATHS "Idle dma-buf imports are released" row say so.

Tests: listed_chunks_are_as_long_as_every_limit_takes_in_whole_64_mib (the limits' length);
a_resident_kept_ram_takes_chunks_past_the_cap_imported_whole (the rule, residency asked only where
the cap cuts the RAM; fails without the change, which answered the cap); and
a_ram_is_resident_once_every_page_of_its_file_is (mincore, a memfd with a hole then written). The
device tests tests::host_ram_whole (a 640 MiB resident RAM: one chunk imported as the use began;
one with a hole: 512 + 128 MiB, none imported) and the ignored whole_ram_bench (a consumer's
8 GiB RAM in 16 chunks of 512 MiB each imported against 3 imported whole: the use's time and a
submission's vkQueueSubmit time).

Also folded: the probe tests::listed_memories with the test-only census Memory::blocks_by_kind
(7120ba7212), and the unit tests' clippy fix (9efafb7742).

Verified: clippy x3 at 9efafb7742 (m3-max-37010 CLIPPY_GPU=0, m3-max-37011 CLIPPY=0 + 20 host_ram
unit tests, m3-max-37012 CLIPPY_CPU=0); rustdoc m3-max-36994 DOC=0; lavapipe host_ram 120 passed
(m3-max-36995). PHOENIX (m3-max-37009): a touched 640 MiB memfd took one 640 MiB chunk imported
ahead (use 126.2 ms); with a one-page hole [512, 128] MiB, none ahead. 8 GiB bench: 16 chunks
listed -> 3, vkQueueSubmit 11.6 us a submission resident against 971.7 us averaged over 300 with
the lazy chunks (first-listing stall included); use_host_ram 459.7 ms (89.0 ms imports).
2026-11-16 09:32:09 -08:00
Anees Iqbal ba311896eb SEMANTICS 2137: Iris: a loop-uniform read-only slot stays a storage view (undo SEMANTICS 2136)
What: reverts a552a55d1f. The Iris Xe RPL-P profile no longer declares
DriverWorkaround::UniformAddressStorageReadsSlow, and a kernel's read-only slot read in a loop at
a per-instance uniform offset is read through its storage view again, as on every other device.
Deleted with it: SlotPlan::uniform_loop_reads, the lowering's uniform-view arm, its plan and
engine tests, the profile test's entry, API.md's paragraph and the variant's signature row.
SEMANTICS moves forward to 2137 (not back to 2135): artifacts made under 2136 carry the uniform
views and must not be reused.

Why: the first guest walk with 2136 in (reims's Iris walk at 0b674f2c1e, m3-max-36915) ran every
kernel whose SPIR-V 2136 changed 3 to 10% slower than six walks without it: per encoder, at the
same maximum clock (act 1482-1496 MHz), one workload's two 15- and 33-tap weight-loop
convolutions took 5.84-5.89 ms against 5.47-5.63 ms in every other walk (1,805 encoders each),
and two kernels of another workload 4.05 against 3.70-3.78 ms and 10.75 against 10.42-10.61 ms;
about +0.5 s of GPU time against the walk before it. Kernels 2136 did not change ran as before
in the same windows. The probe behind 2136 (m3-max-36137, 36775: 0.80-0.91 of the storage form)
measured a synthetic shape; the guest's kernels answer the other way. One walk, so expected,
not verified: the next walk at a tip with this commit is the check (those encoders back at
about 5.5-5.6 ms).

Verified: cargo fmt; refusal surface regenerated (unchanged); api signatures --check. Build,
clippy and tests in the jobs named at landing.
2026-11-16 09:11:00 -08:00
Anees Iqbal 3de483d86f RUNTIME 2459: Joined completions: a command buffer marked to join the next groups under Exact
CommandBuffer::set_completion_joins_next marks a command buffer, before its
commit, as one whose completion may be seen with the next one's. Under
CompletionPolicy::Exact, on a device whose merge check holds and whose
queues are not relayed, a marked command buffer's batches wait in the
scheduler's group as every batch does under Grouped. The first batch of the
VkQueue behind them that is not marked goes last in that group, which then
goes at once (GroupEnd::Closed, WorkCounts::group_ends_closed), so it is
seen complete at its own end and never held back. Its submission check runs
with the marked ones' (check_heads), so they are found ready together. No
group is kept past its pass under Exact (Alone::Unkept,
WorkCounts::batches_held_alone_unkept): a kept group can reach the GPU after
the work ahead of it ended, which would delay the unmarked one behind it.
Everywhere else (Grouped, no merge, relayed queues, the encoder trail,
batches that never group) the mark changes nothing.

Why: on the Iris Xe, ANV on i915 lists every VkDeviceMemory in each
execbuffer, about 170-190 us of driver time a vkQueueSubmit at the
consumer's import count, and the consumer cuts each guest command buffer
into about 12 parts committed under Exact, one kernel submission each.
In its walk the GPU sat idle about 1.5 ms per waited guest buffer between
parts already committed, behind a backlog of those calls. The consumer will
mark every part but the last of a cut whose completion nothing observes.

Grouped-completion's notice, docs/API.md's catalogue, FAST-PATHS row 38, the
runtime README, CompletionPolicy::Exact's doc, api_signatures and REFUSALS
say so. Tests: runtime_lane::joined_completions (marked parts group and a
group is closed by the last; checked parts too; a no-op where the device's
own check finds no merge; unmarked parts go alone; an unmarked command
buffer is seen complete while the long one behind it still runs, the marked
one before it complete by then), on lavapipe with the merge assumed.

Joined completions: the cost table's length, and the order test's first work done before

The conformance cost table's SHARED list holds 36 rows with
batches_held_alone_unkept. In the order test the marked command buffer took
the new buffers' first work, which no batch in a group takes, so it went
alone and nothing grouped: the buffers' first work now runs before it.

Verified: clippy and lavapipe lane job m3-max-36769 showed the failure
(grouped 0 with grouping true); the rerun is the next job.

Verified at 8e6c37c263: m3-max-36784 (msi) clippy --workspace --all-targets --all-features 0; m3-max-36785 (msi, lavapipe, --cfg m2v_cpu_icd) joined_completions + grouped_submissions + alone_batches 21/21 (marked parts under Exact with the merge: 7 command buffers in 2 submissions; unmarked: 7 submissions, 0 grouped; lavapipe's own merge check, not Holds: 0 grouped; an unmarked buffer is seen complete at its own end). The Iris merge check answers Holds (m3-max-36725: 9.6 us in one call of 4 against 26.4 us apart). Release-mode lavapipe, clippy --cfg m2v_gpu and m2v_cpu_icd and rustdoc run after the merge.
2026-11-16 08:18:12 -08:00
Anees Iqbal a552a55d1f SEMANTICS 2136: Iris: a kernel's loop-uniform read-only slot is a uniform view
What: a new cost fact, DriverWorkaround::UniformAddressStorageReadsSlow, derived for ANV on
the Iris Xe RPL-P alone. On a profile that takes it, with robust descriptors:
- the memory plan finds a kernel's read-only slots read in a loop at a per-instance uniform
  offset (SlotPlan::uniform_loop_reads); the loop forest and the per-instance uniformity run
  only there (memory::plan::marks_uniform_loop_reads), nowhere else;
- lowering (lower::access::loop_uniform_views) reads such a slot through a uniform view in
  place of its storage view when the slot is also one unwritten_slots admits: an argument
  the AIR declares unaliased (air-buffer-no-alias) that no store, atomic, volatile or coherent
  access reaches, so no write of the dispatch lands on it and the view reads the bytes the
  storage view would. No aliasing fact, no bind-time check, no runtime change;
- the view is sized as Profile F's fallback sizes its views (fallback_view): its window's
  range, or maxUniformBufferRange where the window does not bound it. Then the slot states
  RuntimeFact::UniformViewRange as Viewed and no BufferRangeLimit, so a plan whose shape binds
  a buffer whose length class does not fit asks for the existing storage_view_slots variant,
  whose compile keeps the slot a storage view and states it Kept (a fixed point). That variant
  is made only for such a shape.
Every other profile and stage is unchanged.

Why: Iris job m3-max-36137 measured a convolution's weights, read in its tap loop at the loop
counter, at 316.3 us per tap through the storage view and 249.0 us per tap through a uniform
view of the same bytes (4896.8 and 4042.4 us a dispatch at 15 taps, 10589.8 and 8523.5 at 33).
The uniform view is the one form A's walk and that arm measured fast; ftreg's twin removal
(8933378831) left this slot a storage view, since its window is unbounded.

Docs: the workaround's doc, RuntimeFact::UniformViewRange, finish_slots and loop_uniform_views,
the memory plan's slot docs, docs/API.md section 5. api_signatures.tsv adds the variant;
docs/REFUSALS.md regenerated with no change.

Tests (each fails without the change):
- tests::engine_loop_uniform_views::
  - a_loop_uniform_slot_is_a_uniform_view_where_the_profile_takes_the_workaround: on
    intel-irisxe-rplp-anv the weights are UniformWords, set 0 writes UNIFORM_BUFFER there,
    the range fact is Viewed and no BufferRangeLimit; on intel-uhd770-rpls-anv (same driver and
    capabilities, no workaround) a storage view and STORAGE_BUFFER;
  - a_loop_uniform_view_needs_an_unaliased_argument_nothing_writes: without
    air-buffer-no-alias, or written by the kernel, the weights stay a storage view;
  - a_large_buffer_at_a_loop_uniform_view_asks_for_its_storage_variant: a 2 GiB binding asks
    for storage_view_slots {weights}, whose compile is a storage view stated Kept, the same key
    for the same shape;
  - a_loop_uniform_view_reads_the_bytes_the_storage_view_does: on the CPU interpreter the base
    module and the storage variant write the same output, the convolution's own.
- memory::plan::tests::uniform_reads: planned on the Iris profile; on moltenvk-m3 the tap
  loop's weights are not marked.

The Iris A/B (horizontal and vertical at the guest's shapes, B's output bytes equal to A's)
runs before landing; no landing before it shows the gain.

With it, the two facts it uses (folded from a3088b6722 and 42dfede633):

Memory plan: read-only slots read in a loop at a per-instance uniform offset

lower::simd::uniform gains a per-instance mode (Uniformity::per_instance): values
among the threads of a workgroup that execute one dynamic instance of an
instruction. A header phi is divergent only through a divergent incoming value,
so a counter with a uniform start and step stays uniform inside a loop whose
exit is divergent. Two rules replace the phi's divergent incoming block: a phi at
a join of a divergent branch (labels from the branch's successors, up to its
immediate post-dominator) is divergent, and a value defined in a loop holding a
divergent branch and used outside it is divergent.

The memory plan adds MemoryPlan::read_only (access READ, no atomic, declared
air.read, a buffer parameter's own slot, no dynamic buffer root) and
SlotPlan::uniform_loop_reads: a read-only slot loaded in a loop at an offset that
is not one constant through a per-instance uniform pointer. The loop forest and
the analysis run only where such a load exists.

Step 1 of the uniform-view work for same-address reads on ANV; nothing reads the
fact yet, so this stays on its branch until the view choice is wired.

Uniformity per instance: bound a walk's stack by the body's edges

Cfg::edge_count is test-only; count the body's successor edges instead.
Verified by the next check job.

Verified on the Iris Xe (m3-max-36775, ANV Mesa 26.2.6), A = development 19f8fb7588, B = this change, guest-shaped separable convolution kernels bound as the guest binds them, settled GPU medians per dispatch of 20 x 5: horizontal 15 taps 4908 -> 4037 us (0.823), 33 taps 10601 -> 8522 (0.804); vertical 15 taps 4409 -> 3993 (0.906), 33 taps 9561 -> 8437 (0.882). Output digests equal A and B for every shape; the weights slot is StorageBuffer in A and Uniform in B; B made one module (no storage variant). m3-max-36746 tests 155/155, clippy 0, three negative controls fail; m3-max-36765 clippy --cfg m2v_gpu and m2v_cpu_icd 0, rustdoc 0. Release translation of the library's 10 kernels: slowest 7.7 ms median (8.9 max), peak RSS 16.4 MiB. Golden tables and the compile census are re-blessed on development.
2026-11-16 08:16:28 -08:00
Anees Iqbal 8933378831 SEMANTICS 2135 / RUNTIME 2458: No storage twins: a kernel's constant buffer on the Iris reads its uniform view alone
What: the Iris Xe RPL-P profile (DriverWorkaround::PushReadsLengthenThreadPayload) declares no
storage twin. A kernel's constant slot keeps its plain uniform view, read at its residual as on
every device without ConstantOffsetUniformReadsPreloaded; its set-0 layout binds the uniform view
alone. Deleted with it, everything only the twin used:
- translator: DescriptorView::UniformWithStorageTwin, BufferForm::storage_twin,
  ResourceKind::StorageTwin, BindingSource::StorageTwin, AccessPlan/Declared twins and the
  census's twin count, storage_twins, views::declare_twin/twin_symbol, emit's TwinMem, the twin's
  NonWritable statement (unwritten_buffer keeps its unaliased-argument use), PlannedBuffer::twin,
  the second DescriptorRange, buffer_uses back to buffer_use, range_at_bind_offset's unbound twin
  arm, planned_range's twin exclusion, rebinds_into's twin arm, the interpreter's twin binding,
  the codec's variants, and BindingPlan::read_only_buffer (its only reason was the twin);
- runtime: uniform_residual_form_of and reads_other_words (keyed_regions takes no flat_grid),
  the neutral zero buffer's STORAGE_BUFFER usage and plan-based read-only check (back to the
  descriptor type alone, binding::read_only_buffer);
- validation: out_of_bounds's twin arms;
- docs: API.md section 5's twin bullet, the workaround's profile doc, residual.rs, views.rs,
  ModuleBuilder::unwritten_buffer, non_writable.rs, neutral.rs, neutral_zeros_shared's docs;
  api_signatures.tsv drops the five items.
Kept: storage views' RangeAtBindOffset at offset 0 on that profile and its creation of both forms
(RUNTIME 2410), set-0 counting tests, the dispatch_chain example's arms.

Why: the twins are the confirmed cause of the Iris regression. Walk A (the tip with no twins) took
137.4 s of GPU time against 145.8 to 150.2 s for three walks with twins; Face Tracking 13.50 s
against 18.1 to 21.1, Super Resolution 25.78 against 28.2 to 28.4, Background Blur 4.93 against
5.7 to 6.4; Horizon Detection gives up about 1.3 s (17.78 against 16.2 to 16.8). No structural
rule separates where a twin pays (ftreg's report to main).

SEMANTICS and RUNTIME are bumped at landing; golden tables and the compile census are re-blessed
on development.

Test: engine_access::a_kernel_constant_slot_binds_its_uniform_view_alone. On
intel-irisxe-rplp-anv, with and without uniformBufferStandardLayout,
buffer_end_byte_load_constant's slot 0 is UniformWords/UniformVec4, its RangeAtBindOffset key is
read, and set 0 links exactly slot 0 at (0,0) and slot 1 at (0,1). A plan of nothing bound writes
those two alone in set 0 (UNIFORM_BUFFER, STORAGE_BUFFER), and only them on four other profiles.
At development the slot is UniformWithStorageTwin and set 0 holds a third binding, so it fails.

ARTIFACT_FORMAT_VERSION 524: the codec drops the twin variants.

Verified: m3-max-36704 (msi) at 2b88dec3f1 clippy --all-targets --all-features 0; m3-max-36706 clippy --cfg m2v_gpu 0. Rustdoc, the translator suites, clippy --cfg m2v_cpu_icd with the lavapipe runtime tests, and the negative control (the new test at development fails) run after the merge; golden tables and the compile census are re-blessed on development.
2026-11-16 07:51:36 -08:00
Anees Iqbal e10f3529c2 FAST-PATHS: the Iris Xe reads imported host memory at about 2.2 times device memory's GPU time
A known gap, the device's: under ANV (Mesa 26.2.6, i915) a compute kernel's reads of
constants over imported host pages cost per read, by host pointer or udmabuf dma-buf alike.

Measured on the Iris Xe (reads_k probe, one pass, rings of 64): 256 threadgroups with 1,024
uint4 reads per thread took 325 us per dispatch from device memory against 714-740 us from
a pointer import or a dma-buf import (jobs m3-max-36557, m3-max-36652). 4 KiB and 64 KiB
rings cost the same, uniform and storage views cost the same, and no recorded command count
differed between placements. The dma-buf route ran (dma_buf_imports 4, no pointer imports).
The only lever would copy guest constants into device memory, which zero copy excludes.
2026-11-16 07:33:05 -08:00
Anees Iqbal 83b3b67f30 RUNTIME 2457: Predicated loops: a rebind while a loop without work apart runs again is taken
A predicated loop's check (Deferred::Loop) answered false in
Deferred::resolved_at_its_calls, so the commit's steps_hold kept the pages of
every buffer over host pages its command buffer used until it completed, and a
rebind of one meanwhile was refused Invalid(Rebind(EncodedUses)) for as long as
the loop ran on, which Metal does without bound.

The check's host step reads only its unit's halt word, in the command buffer's
upload arena. Each run again submits the laying's VkCommandBuffers again as they
were encoded (Piece::Raw), the predicate word's VkBuffer or address and the
body's sets taken at encoding, over the pages the laying's event group took at
its first submission, which Submitting::submit keeps in State::retained until
the command buffer completes; the batch the check holds keeps it from completing
before the loop ends. Only the work the laying left apart is recorded again at
each run: a host step's resolves the buffers its encoder named then, and work on
the GPU alone records over the buffers as they lie then.

So a loop's check is now resolved at its calls where its laying left no work
apart (LoopCheck::leaves_work_apart). A rebind after the laying's submission is
taken and every run again keeps the old pages, as Metal's loop reads the pages
its submission found. A rebind before that submission is taken too, and the
laying's encoders, which keep no log to be encoded again from, fail their
submission EncodedUseRebound (announced), as every other compute encoder that
predication reaches past does. A laying that left work apart keeps holding as
before. The docs say so: deferred.rs, rerun.rs, rebind.rs (the module doc,
RebindProblem::EncodedUses, Buffer::rebind_bytes_no_copy), the commit's
steps_hold comment, the runtime README, and FAST-PATHS's two known gaps (the
refusal now names a loop whose laying left work apart; the rebind between
submissions names a loop's laying rebound before its submission).
docs/REFUSALS.md does not move.

The test is tests/rebind_loop_check.rs: a no-copy buffer holds a DoWhile's word
and its body's input. A rebind while the loop runs again is taken, the loop runs
again after it, ends on the old page's word alone, and its body wrote the old
page's input; a rebind before the laying's submission fails the command buffer
EncodedUseRebound, announced, its output unwritten.

Verified: m3-max-36621 (msi, lavapipe, --cfg m2v_cpu_icd) at 30a7bfaa4e: rebind_loop_check 2/2 (running: rebind Ok, loop ends on the old page's word, old input; before submission: rebind Ok, EncodedUseRebound announced); rebind_*|pending_rebind|host_step_*|rerun_*|predicat* 29/29; control (development's Loop arm) fails both with Err(Invalid(Rebind(EncodedUses))); m3-max-36628 clippy --all-targets --all-features 0. clippy --cfg m2v_gpu / m2v_cpu_icd, rustdoc and the validation lanes run after the merge.
2026-11-16 07:24:16 -08:00
Anees Iqbal 9dc0a6a6ef Docs: name no workload of a consumer's benchmark
docs/FAST-PATHS.md's unshared-isolation row and a spares test's doc named two workloads of a
guest compute benchmark; they now say 'one workload' and 'a guest's compute workload'. The
repository names no consumer app, benchmark or workload. No behaviour change.

Verified: git grep for the benchmark's and its workloads' names finds none after the change.
2026-11-16 05:58:45 -08:00
Anees Iqbal e63ecb9405 RUNTIME 2453: Host pages: a buffer inside a no-copy buffer's own dma-buf import dedicated to nothing is bound in it
What: Device::bind_in_import now binds a no-copy buffer whose pages a live
import of dma-bufs holds all of inside that import, as it does inside an
import of the pointer, where the import is one VkDeviceMemory dedicated to
nothing (a no-copy buffer's own dma-buf of one chunk, a piece of a shared
file's import, a guest RAM chunk's). The new VkBuffer is made for the import's
handle type (VkExternalMemoryBufferCreateInfo DMA_BUF, from bound_memory), its
alignment and memory type checked as before, and the holding import is kept
imported for good (HostImport::pages(ReadApart::Inside), as for a pointer
import). Still refused: an import the driver took only dedicated to its buffer
(DmaBufPages::dedicated_to_buffer, NVIDIA 615's retry) and several chunks bound
to a sparse buffer (no memory); those pages stay a copy, or an import of their
own beside dma-bufs. Before, every dma-buf import but a guest RAM chunk's
refused, so such a buffer was a copy (copied_over_live_imports) whenever it
came with no dma-buf source, or a second import beside it.

The Vulkan rules: VUID-vkBindBufferMemory-memory-02985 (a buffer bound to
imported memory names the import's handle type in
VkExternalMemoryBufferCreateInfo::handleTypes, which host_buffer does from
bound_memory's External(DMA_BUF)); VUID-vkBindBufferMemory-memory-01508 binds
only the dedicated buffer where VkMemoryDedicatedAllocateInfo::buffer was not
VK_NULL_HANDLE, which holds only for the dedicated retry, still refused;
VUID-vkBindBufferMemory-None-10739 (offset a multiple of the alignment) and
-memory-01035 (memory type) as checked before.

Why: on the Iris, with a platform mapping a view of guest pages through one
dma-buf, a guest heap's region takes a 2 MiB no-copy buffer imported through
that dma-buf, and the 256 KiB buffers placed in the heap's pages, handed over by
their pointer alone, became copies of the pages over the live import: 582 copy
ins compared a second, each the copy's whole 64 pages (155 MB/s), 10.7 MB/s
copied in, commit_nanos 43.7 -> 120.5 ms/s. With the views mapped from their
files the same buffers were bound inside the pointer import
(buffers_bound_in_import), with no copy. dma_buf_buffer_imports_dedicated was
0 there: every such import was dedicated to nothing.

Docs: bind_in_import's doc no longer says a buffer's own dma-bufs' memory is
that buffer's alone; dma_buf.rs's module docs, import_from_source's and
chunks_buffer's `sole` contract and DmaBufPages::dedicated_to_buffer say a
buffer over part of the pages binds inside an import dedicated to nothing and
in none dedicated to its buffer; FAST-PATHS's NVIDIA dma-buf gap says the same.

Test: tests/dma_buf_beside.rs's
without_pointer_imports_a_buffer_inside_a_live_dma_buf_import_is_bound_in_it,
on a device made without VK_EXT_external_memory_host: a first no-copy buffer
over 4 pages of a memfd with a dma-buf source, then inside it a second with no
source and a third with one, each bound inside ([0, 0, 0, 0, 1] of copied over
live, beside, inside live, pointer imports, bound inside) where the first's
import is dedicated to nothing (else a copy, and beside or a copy); the GPU
reads the CPU's bytes through each, a CPU write before the commit reaches a
copy through the second, a fill through one and a copy through the other in one
encoder are ordered either way, and after the first's release the second's
fill reaches the file's pages and reads through the third.

Verified: m3-max-36423 at e377c24dce, clippy -D warnings (runtime and translator, all targets and features) 0 and rustdoc -D warnings 0. Lavapipe tests, the negative control, the cfg clippy and PHOENIX run after the merge.
2026-11-16 05:56:00 -08:00
Anees Iqbal aa272cd706 Rebind: record the refusal while a dispatch's host step is left as a known gap
A compute encoder can leave a dispatch to its host step (Deferred::Dispatch,
indirect_dispatch.rs): an indirect dispatch off the GPU's own path, or any
dispatch while an indirect stage-in region is set. The host step reads the
arguments once the work before it completed, and resolves the buffers its
encoder named as it records. Deferred::resolved_at_its_calls is false for it,
so the commit keeps the pages of every buffer over host pages the command
buffer used until it completes. A rebind of one meanwhile is refused with
Invalid(Rebind(EncodedUses)), where Metal's replace before the submission
reaches the new pages.

Encoding the encoder again (the reverted 947c110e49) would not reach this
path: the rebind is refused before any encoding again. So the behaviour stays,
and is now recorded:
- rebind.rs's module doc lists the dispatch among the commands that keep a
  committed command buffer counting as uncommitted until it completes, with
  the refusal;
- the doc comments of RebindProblem::EncodedUses and of Buffer's and Heap's
  rebind_bytes_no_copy name the committed case;
- Deferred::resolved_at_its_calls names its false arm (an execution, a
  dispatch left to its host step, a loop's check);
- the runtime README's rebind sentence names the committed case;
- docs/FAST-PATHS.md has a known-gaps entry.
HOWTO does not state the rebind's refusal, so it is unchanged.

The test is host_step_reads.rs's
a_rebind_while_an_indirect_dispatch_s_host_step_is_left_is_refused_until_completion.
On a device without device addresses (shaderInt64 withheld), it dispatches
[4, 1, 1] threadgroups from a no-copy page behind a shared-event gate, and
rebinds the page before the signal over one holding [2, 1, 1]. It asserts:
- the rebind is refused with Invalid(Rebind(EncodedUses));
- the command buffer completed with no error;
- the host step ran;
- the dispatch ran the encoded page's 256 threads;
- a rebind is taken once the command buffer completed.

Degradation kinds added or removed: none.
2026-11-16 05:52:20 -08:00