Author SHA1 Message Date
Anees Iqbal 46e001b5f2 Re-pin the runtime sources at the landing tip 2026-11-16 23:21:42 -08:00
Anees Iqbal 7cd74a306e RUNTIME 2520: the pin bundle with the queue-turns fix
The queue-turns fix (only a command buffer's first batch takes a turn; development's RUNTIME
2518) on the pin bundle 5fc0508f0b, under a runtime version of its own so no cache keyed to
2514 serves it.
2026-11-16 23:21:41 -08:00
Anees Iqbal 1404f9af90 Queue turns: only a command buffer's first batch takes a turn; 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 at_plan's devices on QueueTurnPolicy::CommitOrder
(probe 45561e17b7, not landed): 4/4 pass in 0.1 s each on both. RUNTIME 2493 (c62128b564)
and 2503 (946abfc913) fail alike on the XTX. The fix's runs follow in the tip report.
2026-11-16 23:17:30 -08:00
Anees Iqbal 5fc0508f0b Re-pin the runtime sources at the landing tip 2026-11-16 21:24:58 -08:00
Anees Iqbal 96b703c4f2 RUNTIME 2514: the pin bundle without RUNTIME 2474, 2475 and 2477-2480
A pin branch, not development. The consumer's Iris runs of a GPU benchmark's photo filter
workload find a slow mode in one compute state (per pass ~1.7-2.1 s against ~0.9, p90 8.7-9.7
against <= 2.8 ms an encoder, mostly warm passes) with RUNTIME 2474-2480: 5 of 12 passes,
against 0 of 8 at 24a0613783. RUNTIME 2476 is cleared: without it, 2-3 of 4 passes are still slow.
The slow mode lies in 2474, 2475 or 2477-2480. Two Iris arms (2477 reverted, 2479 reverted) are
queued. Until they report, this bundle carries everything else on development and reverts those
six. The innocent ones come back in the pin after.

Reverted: c195086369 (2480), 5a0d21cdc5 (2479), 4de6a8dd92 (2478), 86d7480c92 (2477),
8bcaf69f1d (2475), d4a111c357 (2474). Hand resolutions:
- compute.rs: RUNTIME 2489 makes a compute encoder's core in its box (EncoderCore::open_placed)
  over 2479's open. Kept 2489's form; the encoder takes its log from the device's spares again,
  as before 2479.
- bind/dispatch/tests.rs: the two tests 2478 added (and 0f29d6a6e3 changed after) go with it.
Every other hunk reverted as git made it.

Verified: see the pin's check jobs (clippy x3, rustdoc, the suites).
2026-11-16 21:24:58 -08:00
Anees Iqbal 92c6588f6e draw_costs: a moved shape, the restated draws with one material a pass
Every draw of a pass but its first changes only its scissor rectangle, its two buffer offsets
and its indices: the rebound draw with no texture, sampler or pipeline state change, measured
alone.

Verified: built and run in a release job (lavapipe).
2026-11-16 21:13:02 -08:00
Anees Iqbal a486e5a2c8 draw_costs: a restated shape, the scene's draws each under a scissor rectangle of its own
The scene shape's draws are their pipeline state's kept draw rebound with moved offsets and
their own indices; with a scissor rectangle set before each, every one is restated too, the
draw a guest's frame repeats about a thousand times a present. The shape lets that draw's CPU
be measured and profiled alone.

Verified: built and run in a release job (lavapipe).
2026-11-16 21:13:02 -08:00
Anees Iqbal cd0afde315 nextest: the GPU-start test of a command buffer's long work runs alone
tests::start_stamp::a_command_buffer_s_gpu_start_comes_before_its_own_long_work holds the
time from a command buffer's kernel end to its GPU start under half its life. Other test
processes' work on the same GPU runs before it, so that bound is the GPU queue's: in the
RTX 5080 Laptop GPU's whole runtime suite (round leg m3-max-39010) the start came 14.5 ms
after the kernel end, of a 25.8 ms life, while the 64 dispatches' GPU span of 11.2 ms still
held the work (the GPU start was stamped before it, as the test means to show). It now runs
alone, as the other GPU-time-bound tests do.

Test configuration only. Verified: the filter's form matches the queue_share_device override
beside it; the 5080 leg of the next round runs it alone.
2026-11-16 21:11:27 -08:00
Anees Iqbal d02ba47d3d Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 21:07:43 -08:00
Anees Iqbal ae4a69ff7b RUNTIME 2512: submit_calls: a queue's floor sets the shortest of its last 15 calls aside
A queue's call floor was the least of its last 15 calls of commands, so one short call among
slow ones kept the floor under the 100 us bound, and a committing thread kept making the slow
calls itself. On a guest's window drag on the Radeon 780M, a `VkQueue` shared by several guest
queues had one queue's smaller batches come in under the bound about once in each 15 calls,
never two in a row; the drag's parts still made their ~170 us calls inside their commit 5-9%
of the time (the consumer's two walks) where the rest left.

The floor is now the least of the last 15 once the shortest one is set aside (SHORT_CALLS = 1,
select_nth_unstable). It still moves only with a cost all but one of the calls paid: a driver's
rare long call, or lavapipe's slow first calls of a fresh device, among short ones does not
trip it.

Tests: a device test whose calls of commands are slow but one in each 15 (a test hook,
Device::fast_submit_call_every) leaves them to the scheduler's thread; a no-device unit test of
the ring's floor (one short among slow -> slow at every ring position; two short -> not; a short
call ages out after 15; one long among short -> not). The host-pages test holds the slow-call
rule off: it is about host steps, and on a loaded host the rule rightly left its calls.

Verified (drag99 lane): clippy plain/gpu/cpu_icd 0, rustdoc 0, lavapipe commit_and_submit + ring
test 12/12 (m3-max-39031); the new device test fails before on PHOENIX (floor 22.8 us) and passes
after (lavapipe 39031/39004/38966, PHOENIX x3 in 39019). PHOENIX bench (m3-max-38985), 140
imports, every call +100 us but one in 15: batches at commit 46.2% -> 0%, 1476 -> 31 us a frame
on the committing thread; the driver's own 66-86 us calls stay inline both ways.
2026-11-16 21:06:54 -08:00
Anees Iqbal f84f575107 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 20:27:58 -08:00
Anees Iqbal 5d5a34200f submit_calls, unsubmitted: no app or workload names in the docs
The measured steps are a video step and a 3D step in a consumer's macOS guest, and the drag's
thread the compositor's committing thread: comments only.

Verified: cargo fmt; plain clippy of the runtime in the lane's job.
2026-11-16 20:26:17 -08:00
Anees Iqbal 36d11f5b0c Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 20:25:33 -08:00
Anees Iqbal 7849c2f864 RUNTIME 2511: submit: a command buffer that needs no GPU work leaves the program's fills waiting on every device
What: the no-submission path (State::needs_no_gpu) now lets fills of the program's memory wait
past it on a device without a fill queue too (FirstMoves::none_waiting_but with the program's keys,
no has_fill_queue condition): such a command buffer completes in its queue's order with no
vkQueueSubmit, and the next batch takes the fill before its commands.

Why: a new Private buffer's zeros are the device's first work for its next submission
(buffer.rs clear_first), and only the GPU reads them. Without a fill queue every batch takes every
fill (FillTake::Owned) and an internal submission takes every one, so leaving them past a
command buffer with no commands changes nothing any command or the host sees. Before, an empty
command buffer after a new buffer carried its zeros in a submission of its own: a consumer's
macOS guest on the Iris Xe (ANV, no fill queue) made a buffer and committed a lone empty command
buffer 60 times a second in one 3D step; per second the empty ones taken with no call plus
new_buffer_zero_fills matched them (10+58, 18+58, 15+59, 30+45, 32+42, 6+60, 6+60, 7+57 of 60, 60,
60, 60, 60, 60, 60, 56), and those submitted at commit took 375-709 us.

Test: unsubmitted::an_empty_command_buffer_leaves_a_new_buffer_s_zeros_waiting: "unsubmitted 1,
queue submissions 0, zero fills 0; the copy after it: zero fills 1", and the copy reads zeros.

Verified: m3-max-38889 (msi): runtime clippy (all targets, all features), plain and --cfg
m2v_cpu_icd, clean; on lavapipe unsubmitted, first_move, fill_waits and commit_and_submit 44/44;
with the fill-queue condition put back in the same job the new test fails ("unsubmitted 0, queue
submissions 1, zero fills 1"). --cfg m2v_gpu clippy, rustdoc and the Iris count follow the merge.
2026-11-16 20:24:50 -08:00
Anees Iqbal de2a4b5c68 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 20:09:53 -08:00
Anees Iqbal 0e7230fd98 RUNTIME 2509: submit_calls: a call of no command buffer stays out of the queue's call floor
What: DeviceShared::submit_logged takes the number of VkCommandBuffers its call submits, and only
a successful batch call that submits one or more is timed into the VkQueue's ring of its last 15
calls (device/submit_calls.rs), whose floor decides whether a committing thread leaves its batches
to the scheduler's thread. The device tests' slow-call stand-in (Device::slow_submit_calls) slows
calls of commands alone, as a driver's are that submits no commands for a call of none.

Why: a batch with no work, no wait and no timestamp holds no command buffer (submit.rs), and its
call is short where calls of commands list every import (RADV, ANV). One such call among each 15
held the floor at its own length. reims's traced macOS guest on the 780M (window drag, ~140
dma-buf imports): 8.8% of the parts had no GPU time, every one the last part of a guest buffer
split into several; the inline ones took 15-40 us for the whole commit (all 413 short inline
commits were such parts), the rest 173 us at p25, so left_slow_calls fired for ~30 of ~800
commits a second and the committing threads made 85-88% of the calls. With them left out, the
least of each 15 calls of commands the window server's thread made was 143 us at p10. The Iris
(ANV) Safari video step: a third of the parts empty, left_slow ~0/s at 306-374 us a call.

Also: drag_submit_bench (ignored, release, m2v_gpu, Linux, udmabuf): frames of 13 parts, the
last empty, over 140 then 280 imports of 2 MiB dma-bufs (6e29a6cfda); the test's and the bench's
empty command buffers signal an event, since one that signals nothing makes no vkQueueSubmit
(cdbf3980b3); is_multiple_of in the new test (7f260ca8e4).

Verified: m3-max-38842 (msi, lavapipe): runtime clippy (all targets, all features) clean;
commit_and_submit 10/10 with the two existing tests; the new
a_queue_whose_calls_of_commands_are_slow_leaves_them_among_empty_ones: batches at commit 0 of 48,
left for slow calls 48, floor 197.3 us; with the ring line put back in the same job it fails
("the queue's call floor is 1916 ns among empty command buffers' calls"). m3-max-38854: clippy
--cfg m2v_gpu clean. The Radeon 780M before/after, --cfg m2v_cpu_icd clippy and rustdoc follow
the merge.
2026-11-16 20:09:11 -08:00
Anees Iqbal 56474d56d7 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 20:04:07 -08:00
Anees Iqbal bd7daa89ce RUNTIME 2508: Snapshots: held by the command buffers that take them, the texture weakly
What: a reader's snapshot (the full-size storage image a draw takes where it reads a texture its
own pass renders through a view, render/snapshot.rs) was kept with the texture for the texture's
life: an image of the texture's level-0 extent beside every texture a draw ever read so. The
texture now holds it weakly, and each command buffer whose draws take it holds it until it is
released (CommandBuffer::hold_used_texture, once, beside the textures it made). One snapshot
still serves every command buffer in flight; when the last holder goes, its image parks in the
device's recycler, which evicts it within 1 s (bounds 32 images / 128 MiB; images_parked,
images_recycled, images_evicted). The snapshot is the runtime's own image and stays out of the
texture's allocated size, as before.

Why: a consumer's Iris walk with image caches showed a second Private image of each cache's size
placed 1-10 ms after the cache and freed only with it (~1.4 GiB at peak, unannounced). On
lavapipe and the Radeon 780M the plain cache sequence makes no image; a draw that reads the
texture or its view while its own pass renders the view makes one. This commit releases the
snapshot form; the usage-shadow form for attached reads is unchanged, pending the Iris's answer
to which form the guest takes.

The branch's earlier step keyed snapshots by command buffer (the texture then named the command
buffer type, whose auto-trait check overflowed in examples/draw_costs.rs, and two snapshots lived
where one did); this replaces it.

New test tests::snapshot_goes: the first pass's snapshot parks by its command buffer's release
with the texture and view alive; the second pass takes that image back (recycled 1, none made);
the last parks and is evicted within the recycler's time.

Verified: m3-max-38839 (msi): plain clippy and --cfg m2v_gpu clippy clean, lavapipe 38/38;
m3-max-38825 (same product code at da4a2f4b87): --cfg m2v_cpu_icd clippy and rustdoc clean;
the Radeon 780M (m3-max-38840) 38/38, with snapshot_goes's line "first {snapshotted 1, taken 1,
recycled 1}, parked by its release 1; second {snapshotted 1, taken 1, recycled 1}, parked by its
release 1, evicted since 1". Not run: snapshot_goes against the old code.
2026-11-16 20:03:26 -08:00
Anees Iqbal 46e7cc96a2 host_ram_whole: a device whose limits take chunks within the 512 MiB cap is not run
The lavapipe leg 4/4 (um790, m3-max-38632) failed
a_recovery_imports_a_resident_ram_whole_again_before_the_new_device_serves: the resident 640 MiB
RAM was cut into chunks of [128, 128, 128, 128, 128] MiB and none was imported as its use began.
That is the plan's contract: listed_chunks_of (host_ram.rs) imports a resident, kept RAM whole
only where the cap would cut it into more chunks than the source's and the device's limits do,
and there a device limit (llvmpipe's maxStorageBufferRange) takes 128 MiB chunks, within the cap,
so nothing past the cap exists to import. udmabuf's limit was at least 640 MiB, or the test would
have said so and not run. So the failure is deterministic on lavapipe wherever /dev/udmabuf opens
with that limit, not load; the resident and hole tests assume the same chunks past the cap.

listed_device now computes the chunk the device's limits take (listed_chunk_bytes, as the plan
does, with udmabuf's limit as the source's) and, where it is no longer than
LONGEST_LISTED_CHUNK, says so and does not run, beside its other environment checks.

Test only; the product is unchanged.
2026-11-16 18:56:53 -08:00
Anees Iqbal f8d29324d5 start_stamp: the first work's span is held against the same fill's GPU time, not the life it adds
The Iris runtime leg (ANV, m3-max-38516) failed
a_command_buffer_s_gpu_span_holds_its_batch_s_first_work: with a new 256 MiB Private buffer the
fill's life grew by 65.3 ms, of which 54.1 ms lay from the kernel end to the GPU start and
11.37 ms in the GPU span (0.004 ms without the buffer). The span held the first work: 11.37 ms is
the zero fill's one vkCmdFillBuffer of 256 MiB. The 54 ms lay before the GPU's first timestamp,
after the start of the driver's submission call (the kernel end, command_buffer/group.rs's call
time), where the runtime does nothing: no GPU span holds it, nor would Metal's. The test's claim
(the span holds half the life the first work adds) counted it.

The test now runs the same fill again after the batch (one vkCmdFillBuffer of the buffer's
256 MiB, its first work done, which it asserts) and holds the batch's span to at least half of
that fill's span: GPU time against GPU time. A start written after the first work would leave a
span of about 0.004 ms against a bound of about 5.7 ms there, so the test still fails on that.
Each line also prints the submission call's own time where the process set
METAL2VULKAN_QUEUE_TIMES (CommandBuffer::submit_returned_time), so a run can show where the
time before the GPU start goes.

Test only; the product is unchanged.
2026-11-16 18:56:53 -08:00
Anees Iqbal ea452fed1d Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 18:47:22 -08:00
Anees Iqbal 9136d850d3 RUNTIME 2507: Parked images: destroy each in an exit-guard section, and before their pages' memory goes
What: dma_buf/parked.rs's release enters a section of the exit guard around each parked image's
vkDestroyImage (its shared.vk() included), leaving the image to the process's end while it exits,
as DmaBufPages's drop leaves the import. FixedPages releases its parked images inside its own
section and before its memory is freed or recycled (and before the free on a lost generation),
as the parked.rs docs say. The exported parking test now has the residency thread's own pass
release the parked images (import tax forced Holds), not the test thread's sweep.

Why: on the 780M, tests::exported_textures::an_nv12_picture_s_planes_over_exported_memory_go_in_place_naming_its_handle_type
ended in SIGABRT in parallel runs (m3-max-38587, and run 2 of 3 in m3-max-38611):
"metal2vulkan: the runtime's thread metal2vulkan-residency reached the device outside an
exit-guard section". The residency thread's pass (release_idle_parked) calls parked::release,
whose shared.vk() was read outside any section; a test build ends the process there
(exit_guard::check). Since exported images park (RUNTIME 2505), RADV's residency releases them
at its next pass, so the path runs on the thread in most tests over exported memory; the
host-page parked images took the same path before.

Verified: the 780M (m3-max-38630): the parallel 7-test set (exported_textures and
dma_buf_parked_images) 3 times, 7/7 each, no abort (before: 2 of 4 parallel runs aborted,
m3-max-38587 and m3-max-38611). msi: clippy --cfg m2v_gpu and the archive (m3-max-38621);
plain and --cfg m2v_cpu_icd clippy, lavapipe 20/20 (m3-max-38622).
2026-11-16 18:46:37 -08:00
Anees Iqbal 67fd26b824 linear_attachments: no settle before many passes over host pages: the lane's devices run no check
What: many_passes_over no longer settles the device's in-place check before a target over host
pages, nor prints its verdicts; the expected form still follows the verdicts (merges_on_host).

Why: the lane's devices take the exact answers (HostPageTexturePolicy::Shadow, in_place_textures.rs
in_place), under which no check runs, settle_in_place_checks answers false at once and every verdict
stays pending: the settle's assertion failed both legs in 0.1 s on the XTX (m3-max-38616 at
00142dfb2c). So the cause the commit before named was not a check still running when the passes
began but none at all: under these policies every shadow over host pages merges on the host
(shadow_splice::splices takes a pending verdict) and joins no run of passes, on every device, and
the passes keep for themselves, as merges_on_host reads from the pending verdicts.

Verified: the tip's XTX run, in the lane report.
2026-11-16 18:45:01 -08:00
Anees Iqbal 2b0aefb293 linear_attachments: many passes over host pages keep for themselves where the merges go on the host
What: many_passes_over settles the device's in-place check before a target over host pages, and
expects the shadow's passes to keep twice as one run only where its merges stay the GPU's; where
the settled check of host pages (Pointer) failed or did not answer a copy's or a shader write's
texels in lines beside other bytes (shadow_splice::splices), each pass keeps every texel for
itself. Where those passed but another class failed its copies and passed its reads, either form
is accepted, as the report states no memory flags (in_place::copies_verdict). A copied buffer's
merges stay the GPU's. The verdicts read are printed.

Why: since RUNTIME 2432 (518d6d8443) such a texture joins no run of passes (render.rs, the join's
!merges_on_host), as pass_runs.rs and shadow_splice.rs say; the runtime crate's copy of this test
(tests/merge_scratch.rs) took that branch and settles the check first in RUNTIME 2433. This copy,
with a fresh shader cache and no settle, ran its passes while the XTX's check was pending or
failed: m3-max-38545 (ea202ab28f) kept 706 times every texel (54220800 and 50832000) against the
two of one run. Unsettled, a check that answers midway could also split the passes between the
two forms.

Verified: the fix tip's XTX run, in the lane report.
2026-11-16 18:45:01 -08:00
Anees Iqbal adfe6b7207 gpu_times: the one-after-another fills start after an untimed fill that takes the buffer's first work
What: command_buffers_one_after_another_are_each_timed_on_their_own commits one untimed fill of
its new private buffer, and waits for it, before the counted window, so the eight timed fills
carry no first work.

Why: since RUNTIME 2466 (35ac917d6f) a timed command buffer whose first batch carries first work
(here the new buffer's zeros) writes its start in that work's command buffer, before the work
(command_buffer/submit.rs, GPU times), not in its first encoder's prefix, so it is no prefixed
start. The XTX lane (m3-max-38545, ea202ab28f) counted (7, 0, 0) prefixed, kept and reused
against (8, 0, 0), command buffer 0's GPU span 12.0 us against 3.6 to 5.4 us for the others.
The product does what its docs say; the test's claim missed the first work. The start of a batch
with first work is start_stamp.rs's test.

Verified: the fix tip's XTX run, in the lane report.
2026-11-16 18:45:01 -08:00
Anees Iqbal 823bee778f Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 18:34:41 -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 0d47fb67db Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 18:26:28 -08:00
Anees Iqbal a196a8645d RUNTIME 2505: Exported dma-buf images park under their buffer's pages and the next texture takes them
What: a texture over a buffer of the runtime's memory exported as a dma-buf, or in a block of its
buffers allocated exportable as one (Holds::FdDmaBufs), where no image binds in that memory
itself, takes a DRM_FORMAT_MOD_LINEAR image bound to a dedicated import of the memory's own
dma-buf. That image now parks as its texture goes, under the buffer's pages (FixedPages), and the
next texture over the same buffer of the same plan at the same texels and pitches takes it: no
vkGetMemoryFdKHR, no import, no VkImage made. The parking machinery of dma_buf/parked.rs is
shared: ParkSpot and the residency note a ParkHolder (HostImport or FixedPages) instead of a
HostImport, so the same bound (PARKED_MOST), windows and release passes apply, and the same
refusals (a handed-out VkImage, the device's check's textures, a detached image). Parked images
go with the buffer's pages, before their memory is freed or recycled, and on a lost generation.
New WorkCounts: exported_dma_buf_images_parked, exported_dma_buf_images_taken,
exported_dma_buf_images_parked_released (api_signatures.tsv blessed). HostImport::device, used
only by the residency's parked ages, is gone: the device comes from the parked images.

Why: a consumer's 780M walk (RADV) made and freed two such textures each frame over its surface
caches: 120 dma_buf_import_calls a second at ~333 us each (~40 ms of CPU a second), with
exported_dma_buf_images +120/s and nothing parked or taken, as this route never parked.

The second commit (622807d05b) reuses Buffer::fixed_pages (now pub(super)) and coerces each
ParkSpot holder's Weak through a binding of its concrete type.

Verified (msi): runtime clippy, all targets and features, plain and under --cfg m2v_cpu_icd
(m3-max-38572) and --cfg m2v_gpu (m3-max-38573) clean; rustdoc and the signatures check clean
(m3-max-38576); on lavapipe (m3-max-38572) exported_textures, dma_buf_parked_images,
dma_buf_shared_files and dma_buf_pieces 20/20, the host-page parking through the new holder
included. The new test a_texture_over_a_dma_buf_block_takes_the_image_the_last_one_parked is
not reached on lavapipe (its images bind in the memory itself); its 780M run and the release
bench exported_park_bench follow the merge (m3-max-38587).
2026-11-16 18:25:45 -08:00
Anees Iqbal 17fb0bbd93 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 18:20:19 -08:00
Anees Iqbal fdf6165ed3 RUNTIME 2504: A staged texture copy with the guest RAM joins no rows past a 2^31 - 1 byte pitch
What: copy_texture_from_host_ram / copy_texture_to_host_ram staged through the CPU (first touch,
a chunk that takes no import) recorded the GPU's copy between the arena and the texture as one
region at the surface's pitch, bufferRowLength = pitch / texel bytes, for any region of more than
one row. A pitch past 2^31 - 1 bytes (and up to texel x (2^32 - 1)) so recorded a
vkCmdCopyBufferToImage / vkCmdCopyImageToBuffer region breaking
VUID-vkCmdCopyBufferToImage-bufferRowLength-09108 and
VUID-vkCmdCopyImageToBuffer-bufferRowLength-09108 (bufferRowLength times the texel block size at
most 2^31 - 1); a wider pitch was refused (Problem::HostRam) where the texels overflowed a u32.
The copy straight on the imports already joined no rows past that pitch.

How: one rule, `joining_pitch` (more than one row, a pitch of at most 2^31 - 1 bytes), now used by
both paths; the staged path builds its regions with `staged_regions`: the one region of all the
rows where they join, else one region per row at the row's byte of the arena's region
(bufferRowLength 0, one row high). The same bytes either way; the arena's region is unchanged
(the whole span, which a device that cannot make a buffer that long refuses at the host step,
failing the command buffer, as before).

Verified: m3-max-38558 (msi): runtime clippy (all targets, all features) and rustdoc
clean; tests::host_ram_texture_rows 3/3 with the new
a_staged_copy_s_rows_past_a_pitch_of_2_31_minus_1_bytes_are_a_region_each, which fails with the
pre-fix rule restored in the same job (1 region, not 3). m3-max-38559 (lavapipe): runtime clippy
under --cfg m2v_cpu_icd clean; tests::host_ram* 94/94.
2026-11-16 18:19:37 -08:00
Anees Iqbal ed00d17107 Tests: a host-pages commit test counts slow-call leaves on a loaded host instead of failing
a_command_buffer_naming_host_pages_is_submitted_at_its_commit asserted that no commit was left
for slow calls. On a loaded host lavapipe's vkQueueSubmit calls can stay past the bound for a
stretch of the queue's last calls, so RUNTIME 2496's rule rightly leaves those commits to the
scheduler's thread: the pin round's lavapipe leg (m3-max-38535, um790 under load) left 5 of 200
plain-leg commits so, with 195 at commit and the final call floor 2.3 us. The test's claims stay:
no commit left for a host step, no host step recorded, the host pages' encoders keep their logs,
and at least half the batches go at commit. The slow-call leave is counted and printed;
a_queue_whose_calls_are_slow_leaves_its_batches_to_the_scheduler_s_thread proves that path.
2026-11-16 18:15:28 -08:00
Anees Iqbal 3b22403ead type_nine: the view check runs beside the scenarios again, its answer and stand-bys printed after them
With the check standing by for the device's work (RUNTIME 2501), the type 9 hang scenarios no
longer wait for its answer before they begin (ac9cad48bf): the check runs from the device's making
on a fresh scratch cache, beside the scenarios, as it does beside a program's first work. Once
they ended the test waits for its answer and prints it with WorkCounts::device_checks (its
stand-bys). For the NVIDIA run that shows the other queue's Scheduled latency with the check
beside it.
2026-11-16 18:14:00 -08:00
Anees Iqbal b225fabc0b Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 18:08:55 -08:00
Anees Iqbal 946abfc913 RUNTIME 2503: A command buffer that waited for another queue's completes after it behind handler-free items too
What: a command buffer's transition to Completed that waited on the GPU for another queue's
command buffer X now waits for X's transition to reach its completed handlers wherever nothing
before X's transition in X's queue's context may block: no item there, nor what a thread runs
there, runs a scheduled or completed handler of the program's or waits for a submission handler
(Run::may_block; completion-seen handlers never block). Before, it waited only where X's
transition was first in its context or already running, so behind an earlier command buffer's
handler-free transition still queued, or run by a thread the host kept off the CPU, it went on
and the program's completed handler of the waiter could read X short of Completed. Behind an item
that may block it still goes on, as Metal's does
(a_blocked_handler_of_the_signaller_s_queue_holds_back_the_signaller_and_not_the_waiter).

How: each item posted to a context takes a place (a counter over all lines); a line keeps the
places of its items that may block and whether what a thread runs of it may. Follow keeps its
transition's place (an AtomicU64 store where it kept an AtomicBool) in place of the command
buffer's address, so Lines::leads is one look at the line's first item and first place that may
block: no walk of the line (the old lead check walked it where a thread ran the line), no new
lock. Cost: a u64 per queued item, a u64 per queued item that may block, a deque push and pop for
those. Item::finishes, which only the walk used, is gone.

The validation test a_shared_event_wait_for_a_kept_group_s_signal_ends_at_the_next_completion_turn
now checks what the program can rely on: X reads Completed in Y's completed handler, and Y's GPU
work began after X's ended where the device's own timestamps place both. It no longer compares
the two completed handlers' start instants, which Metal does not order either (an M3 Max under
macOS 27.0.1 started the waiter's first in up to 6% of rounds with a plain event, 0.1% with a
shared one).

The contexts tests name items by their places, so Ends carries no name (353257e382).

Verified on lavapipe (msi, m3-max-38523): clippy (cpu_icd, runtime and
validation, all targets and features) clean; runtime tests 63/63
(tests::contexts with the new an_item_leads_its_line_behind_what_may_not_block,
the three completion_order follow tests, unshared_hold, queue_turns,
submission_turns, scheduler_held_wakes); validation grouped_submissions 16/16.
A scratch diagnostic of the same shape, 5 rounds under each of Fair and
CommitOrder: X read Completed in Y's handler in 10 of 10 (before the fix,
m3-max-38464: X still Scheduled in 2 of 10). m3-max-38524: workspace clippy
(all targets, all features), clippy with --cfg m2v_gpu, workspace rustdoc
with -D warnings: all clean.
2026-11-16 18:08:11 -08:00
Anees Iqbal 99778b04c0 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 18:07:22 -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 510b105309 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 17:53:00 -08:00
Anees Iqbal 1e902d7475 RUNTIME 2501: View check: stand by for the device's work before each kernel's making and each timed dispatch
What: the view check (RUNTIME 2495/2498) ran from the device's making beside the program's first
work. Before each of its eight kernels' making and each of its timed dispatches it now stands by
until the device's work is quiet (DeviceShared::work_quiet_for): no batch committed waits for
its submission (Scheduler::holds_none), none submitted is in flight on any VkQueue, and no use of
a VkQueue has been under way for step_aside::QUIET (20 ms) before a making, which cannot stop
once begun, or queue_quiet::SETTLE (1 ms) before a dispatch, or since the check's own last
dispatch where that was the last use. It stands by for no one while a call waits for its answer
(settle_view_check), and stops as the device's holds stop. Each kernel's making is a step of its
own, inside its own exit-guard section, after the allocation step-aside the rounds already took.
QueueQuiet::unused_for reads how long no queue use has been under way. Counted:
WorkCounts::device_checks.view_check_stand_bys and view_check_stand_by_nanos. The module docs
also correct one claim: the check's dispatches are internal submissions counted as the device's.

Why: on the RTX 5080 Laptop GPU beside the runtime lane (b5080 m3-max-38412), on a fresh cache,
the check's kernels' making (compute_pipeline_create_nanos +833 ms, an 18.5 ms vkQueueSubmit)
overlapped the type_nine hang test's first scenario, whose other queue's command buffer read
Scheduled 103.2 ms after its commit, and its rounds' internal submissions landed in later
scenarios' counted passes. Each dispatch is an internal submission (device/submit.rs,
submit_internal_taking): it holds the device's internal lock from before its recording through
its vkQueueSubmit on the device's first VkQueue and the wait for its fence, so it waits behind
the work submitted there before it and holds every other internal submission meanwhile; a
kernel's making holds the driver for its compile. The other checks step aside only for the
device's allocations and frees (step_aside.rs) and make no pipelines.

With it (folded): its quiet counted from no earlier than its start, so its first kernel waits for the program's first work (a device that had used no VkQueue read as quiet for ever, so the first kernel's making began at the device's making); the runtime README says when the check stands by and that a device whose work never pauses that long gets its answer once it does (or from the record next start).

Residual, unmeasured: a compile already begun when guest work arrives still runs to its end; 20 ms of full quiet first makes that unlikely, not impossible.

Tests: tests::view_check_device::the_check_stands_by_while_the_device_s_work_goes_on (lavapipe: while a queue keeps a command buffer committed or in flight for 900 ms, from 300 ms on the check makes no kernel and submits no dispatch and its answer stays pending; once the work stops it answers, having stood by for at least 600 ms).

Verified (msi, at 85ca74cc15): m3-max-38482 clippy -p metal2vulkan -p metal2vulkan-runtime --all-targets --all-features 0, rustdoc -D warnings 0, api_signatures/api_surface 15/15; m3-max-38481 clippy --cfg m2v_gpu 0; m3-max-38480 clippy --cfg m2v_cpu_icd 0, lavapipe view_check|submit_check|queue_switch|in_place_check|tiling_check|tiling_cost|step_aside|queue_quiet 59/59. An NVIDIA run follows the merge.
2026-11-16 17:52:15 -08:00
Anees Iqbal 40810b6d31 Fixtures: remove uniform_texel_windows, which no test reads since the view check's own kernels replaced it
What: the engine fixture uniform_texel_windows (.metal, its .ll and .air.ll) and its TOOLCHAIN line.
Why: since SEMANTICS 2142 the uniform_texels tests run on indexed inline kernels and the view check
builds its own kernels (bind::view_check_module); nothing references the fixture (git grep finds only
its own files and its TOOLCHAIN line). No dead fixtures.
Verified: in the check job named in the landing.
2026-11-16 17:40:20 -08:00
Anees Iqbal ac9cad48bf Tests: a pass's shared copy barriers and the type 9 hang scenarios begin once the view check answered
runtime_lane::pitched_surfaces::a_pass_s_copies_in_share_their_barriers and
runtime_lane::private_primitives::type_nine's hang scenarios each make a device over a fresh
scratch cache, which holds no record of the device's view check, so the check (RUNTIME 2495,
f2367d8956) runs from the device's making on a thread of its own. Beside the runtime lane on the
RTX 5080 Laptop GPU it ran into what the tests count and time:

- The barrier count is the device's: in the last counted pass the view check's internal
  submissions (one dispatch between two timestamps each, a barrier before) added 2 and 15
  barriers (1 against 3 and 16, internal_submissions +3 and +14), the pass's own staying 1.
- The hang test's first scenario overlapped the check's making of its pipelines
  (compute_pipeline_create_nanos +833 ms, an 18.5 ms vkQueueSubmit, steps_aside 2 -> 8): the
  other queue's command buffer read Scheduled 103.2 ms after its commit, past the hang, with no
  cross-queue hold counted (heads_held_for_earlier_commits, batches_held_for_another_queue,
  heads_held_for_unshared_commits and heads_held_for_queue_turns 0 in every scenario).

Both now wait for the view check's answer (Device::settle_view_check) right after making the
device. Found with counter prints of every moved WorkCounts field (b5080 m3-max-38412, two runs
beside the runtime_lane::p* tests).
2026-11-16 17:35:01 -08:00
Anees Iqbal ae4628a59b Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 17:34:45 -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 a0e0da9b47 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 17:31:32 -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 1a7170d57c Runtime README: the view check's verdicts on six devices and its cold cost
What: the view check bullet gains the verdicts it measured at the RUNTIME 2498 rule, and a cold
run's wall and GPU time. RTX 3090 and RTX 2080 take UniformBufferPerLaneReadsSerialize alone,
the Iris Xe of RPL-P takes ExternalUniformReadsSkipACache alone, and the Radeon 780M, the RX 7900
XTX and lavapipe take neither. Cold wall 28 to 136 ms on the GPUs (268 ms on lavapipe), GPU time
7.9 to 43.2 ms. Also rewraps the bullet's one overlong line. No product change.

Why: the brief asks the README to carry the check's cost and verdicts; it carried the memory
alone.

Verified: every number is from the jobs' "view check on" lines at e20054b908's archive (Iris
m3-max-38378, 3090 m3-max-38379, 2080 m3-max-38380, 780M m3-max-38382, XTX m3-max-38389,
lavapipe m3-max-38359); GPU time is the sum of the 24 medians times 8 rounds. cargo fmt.
2026-11-16 17:18:45 -08:00
Anees Iqbal b9f584ffc1 Tests: grouped completion wakes and a committing pass's end take no queue turns
Two tests failed on lavapipe since RUNTIME 2490 (8f1e4157d8, fair queue turns). Both still
passed at 44505b3807, and both fail at b874899768 and 20844a0232:
- runtime_lane::grouped_submissions::completions_wake_the_scheduler_only_once_a_head_may_go
  failed 3/3 with "5 wakings by completions" (wakes <= 1).
- tests::submission_turns::a_committing_pass_ends_at_its_own_submission_handlers_grouped failed
  with (Some(3), 1) vs (Some(3), 0): one scheduler slice rescue.

Cause (a diagnostic run printing the turn counters, lavapipe, msi job m3-max-38335, 3 runs):
- lavapipe has one graphics VkQueue, so each test's two command queues share it, and under the
  default `QueueTurnPolicy::Fair` the scheduler holds a queue's batch for its turn while its own
  work is in flight there.
- grouped_submissions: 6-7 heads held for queue turns (`heads_held_for_queue_turns`), 3-5 let go
  idle, 1-2 slice rescues; 4-5 completion wakes. Those wakes are the turns letting the fills'
  queue go on, not the checked head's.
- submission_turns: 2 heads held for queue turns, 0 completion wakes, 1 slice rescue. The later
  batches the committing pass left were held for their turns, not sent at its wake.

Neither test is about the turns: one checks when completions wake the scheduler for a head
waiting on a GPU signal, the other the wake a committing pass gives for the batches it leaves.
So both now make their device with `QueueTurnPolicy::CommitOrder`, as queue_share_device's tests
do for the sharing they measure; `tests::queue_turns` tests the turns themselves.

The slice rescue under Fair (a turn-held head let go by the sleep slice, no wake having come) is
reported to the turns' owner, not hidden here.

Verified: lavapipe runs of this commit (named in the tip report).
2026-11-16 17:12:04 -08:00
Anees Iqbal b2e4d9811f Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 17:11:34 -08:00
Anees Iqbal 12f70f8cca RUNTIME 2498: View check: the texel fact judged on the reads it moves over imported pages, its bounds from the Iris records
What: the view check's imported-page arms gain the per-lane reads (uniform buffer and uniform
texel buffer, both windows: 24 arms, CHECK_VERSION 2). ExternalUniformReadsSkipACache is judged
on the reads the fact moves to the texel view (lower::access::view_kind): the uniform reads, and
the per-lane reads where the per-lane fact does not hold (where it does, those keep their storage
view). It holds where, over imported pages at both windows, the texel buffer took less than the
uniform buffer's time in every such read (TEXEL_NO_SLOWER 1.0) and less than 0.7 of it in at
least one (TEXEL_FASTER). ViewCosts' `texel` gives way to `texel_fastest` and `texel_slowest`;
the report names both.

Why: on the Iris Xe (job m3-max-38288) the check gave no texel fact, so the Iris lost the texel
route its identity row gave it. The old rule asked the uniform walk to be below 0.7 at both
windows, a bound set from the records' one-word rows, while the arm walks the window. The
check measured what the records measure for a walk: texel/uniform over imported pages 0.48
(1 KiB) and 0.755 (4 KiB), the uniform buffer over imported pages 2.05 and 1.22 times its own
over device memory, the texel buffer 1.006 and 1.022. The records (job m3-max-37780, worked
out from each pattern's ratios to the uniform buffer over device memory) put a workgroup's walk
at 0.23 to 0.32 (1 KiB) and 0.83 to 0.86 (4 KiB), each invocation's walk at 0.026 to 0.058 and
0.16 to 0.17, each its own word at 0.081 to 0.084 and 0.19 to 0.23, every invocation one word
at 0.41 to 0.49 and 0.49 to 0.55. A uniform walk of 4 KiB is not where the cache loss shows,
and no bound on it alone separates the Iris (0.83 to 0.86 in the records) from RADV on the
Radeon 780M, whose uniform buffer keeps its cache over imported pages (0.93 and 0.97, job
m3-max-38330). So the rule now asks that no moved read is slower (1.0, above every Iris record
row) and one is clearly faster (0.7, between the Iris rows and the 780M's tie).

Verified (msi, at e20054b908): m3-max-38360 clippy -p metal2vulkan -p metal2vulkan-runtime --all-targets --all-features 0, rustdoc -D warnings 0, api_signatures/api_surface 15/15; m3-max-38359 clippy --cfg m2v_cpu_icd 0, lavapipe view_check|uniform_texels 11/11 (facts {}: per-lane imported texel/UBO 0.859, uniform texel 1.84 slower); m3-max-38358 clippy --cfg m2v_gpu 0. The Iris, 3090 and 2080 verdicts run after the merge.
2026-11-16 17:10:52 -08:00
Anees Iqbal 20844a0232 View check test: the committed profile found at run time, as a carried test archive needs
an_answer_with_facts_makes_the_measured_compile_device read lavapipe's committed profile through
env!("CARGO_MANIFEST_DIR"), the building machine's path, so a test archive carried to another node
(the RX 7900 XTX run, um790 job m3-max-38286) panicked reading it. It reads it through
metal2vulkan_devtools::validation_dir(), as the runtime's other profile-reading tests do.
2026-11-16 16:58:42 -08:00
Anees Iqbal 462cde3f6c Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 16:58:08 -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 17ded58844 pitched_surfaces: warm up twice, so the kept stamped barrier buffer is made before the counted passes
`a_pass_s_copies_in_share_their_barriers` failed on the RTX 5080 Laptop GPU on every run at
24a0613783 and later: "a pass reading 1 shadowed texture recorded 2 pipeline barriers, one
reading 4 recorded 1". That is 3/3 at a124d8c24d and 3/3 at 24a0613783 (b5080 entry
pinreds-lane-163117). It passed there at 44505b3807.

Cause (a diagnostic run printing each pass's work-count moves, b5080 entry
pinreds-diag6-164726): the test counts the barriers recorded from the encoder's end through the
wait, i.e. at commit and submission.
- The pass of 1 recorded one more: its commit began one more command buffer
  (`command_buffers_begun_kept_barriers` +1) and recorded a kept stamped barrier buffer
  (`stamped_buffers_kept` 0 -> 1).
- The pass of 4 after it took that buffer again (`stamped_buffers_reused` 0 -> 1) and recorded one
  barrier.
- Since RUNTIME 2466 (35ac917d6f), a batch with first work writes its start stamp in that work's
  command buffer. The warm-up pass has first work (`new_buffer_zero_fills` +1), so it kept a plain
  barrier buffer (`barrier_buffers_kept`). The stamped one, which every later command buffer with
  no first work takes, was first recorded in the first counted pass.
So the steady state is the same for both passes (one barrier each); the second barrier was a
one-time recording that the single warm-up no longer covers. This is not a change in how copies
in share their barriers.

Now two passes of the shape run before the counted ones. The second records the kept stamped
buffer, and the counted passes of 1 and of 4 both take it again.

Verified: the 5080 run of this commit (named in the tip report).
2026-11-16 16:56:29 -08:00
Anees Iqbal 6ddfbe912b Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 16:54:34 -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 04bcc2d89d submission_turns: two batches of one group read one submission's return, which orders neither
`a_pass_s_submission_handlers_run_while_it_goes_on_grouped` (RUNTIME 2437) failed on the RX 7900
XTX (RADV) in the 596d917dfe round (m3-max-38205) at submission_turns.rs:351: "the later command
buffer was submitted before the earlier one (Grouped)". Its line said "their submissions
returned 0.4 and 0.4 ms after the held one's", and its stderr held the group notice: "2 batches
of command buffers on one queue: the scheduler found them ready together".

RADV has one graphics queue, so both command queues share one VkQueue. Under Grouped, the pass
after the held one took `earlier` and `later` in together and grouped them into one kernel
submission. `submit_returned_time` is the instant the submission carrying a command buffer's last
batch returned, so both command buffers read the same instant. The strict `<` read that tie as
the later one going first. Inside one vkQueueSubmit the batches run in the order the pass took
them, which is commit order. So this is a tie the test misread, not a product order bug.

The check now passes on a strictly earlier return, or on an equal one where the pass grouped
batches (`WorkCounts::batches_grouped` rose across the two commits). Two separate submissions
still have to return in commit order.

Verified: the build and the test on the XTX (named in the tip report).
2026-11-16 16:50:38 -08:00
Anees Iqbal 2763ef98cc Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 16:43:38 -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 037f1959bf Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 16:34:09 -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 e22ca6d46a Runtime lane: alone_batches and joined_completions' two-queue test take their queue plan
Both tests failed on the RTX 5080 Laptop GPU's validation leg (596d917dfe round) at
layer_claim.rs:293 with the runtime's `metal2vulkan-queue-limits-reached`: "the program's
command queue 2 on a round robin of 1 VkQueue(s), took VkQueue 0, which another took, where the
plan's 14 give it one of its own".

The lane makes its devices under `LANE_QUEUE_LIMITS` (one round-robin VkQueue). Its documented
rule (runtime_lane.rs, `LANE_QUEUE_LIMITS`) is that this notice fails the run, and that a test
whose work places a second command queue, or an unshared one, makes its device with its plan
through its own adjust (`at_plan`). Neither test did:
- `alone_batches::a_batch_that_goes_alone_is_counted_once_by_why` (3a0e4b35a2, 25c7f896f9) uses
  `first`, `queue` and an unshared queue.
- `joined_completions::an_unmarked_command_buffer_is_seen_complete_at_its_own_end` (c9bad0206e)
  uses `queue` and `aside`.
Only a device whose families have queues to spare (NVIDIA's 16) is affected, because elsewhere
the limits leave the plan as it is. Neither test had run on NVIDIA before this round.

The fix is the existing rule, one rule for both: each test's adjust calls `at_plan`. Our notice
stays a failure in the lane, as the lane's queue-limit contract says.

Verified: the 5080 run of this commit (named in the tip report).
2026-11-16 16:31:42 -08:00
Anees Iqbal 6ec5288fa1 Conformance probes: what nocopy_alias_one_encoder and cross_queue_burst_turns measured
nocopy_alias_one_encoder (m3-max-38211 on the M3 Max, m3-max-38212 on the MacBook Pro's UHD 630
and Radeon Pro 5300M, 20 rounds a case): a fill through one no-copy buffer and a copy through
another over the same pages, in one blit encoder, are ordered on the 630 only; the M3 and the
5300M let the copy read part of the fill. Through one buffer, all three order them.

cross_queue_burst_turns (m3-max-38188 on the M3, m3-max-38189 on the MacBook Pro): the M3 runs a
second queue's small command buffer among the first queue's 64-command-buffer burst; the 630
runs the burst first. Both jobs ended at their timeouts in same-queue: B was made on A's queue
while A's 64 command buffers were uncommitted, at the queue's default limit of 64, so
commandBuffer waited for a free one forever. A's queue now allows BURST + 2; same-queue,
one-long and the 5300M are recorded as not measured yet.
2026-11-16 16:29:21 -08:00
Anees Iqbal b181c53a64 Conformance probe nocopy_alias_one_encoder: does Metal order a fill and a copy through two aliasing no-copy buffers inside one blit encoder
In one blit command encoder of one command buffer, fillBuffer: writes a value through no-copy
buffer 1, then copyFromBuffer: reads no-copy buffer 2 over the same page-aligned pages into a
third Shared buffer; committed, waited for, and the copy's words compared with the fill's value,
20 rounds with a value each. The control copies through buffer 1 itself and must see the fill.
The runtime orders the two as one resource's (host_aliases.rs); this measures whether Metal does,
for a decision on the order the runtime keeps there.

Conformance-only: an Objective-C probe with its build command in its header, not built by cargo.
Not yet run; its header records the measurements once it is.
2026-11-16 16:29:21 -08:00
Anees Iqbal 195585c7d4 dma_buf_beside: cite Metal's measured answer for two aliasing no-copy buffers in one encoder
The previous commit (9a7e59b1dd) runs `inside`'s fill-then-copy checks in one encoder only
where the second buffer is bound inside the first's import, and in two command buffers where it
is a copy. Metal's answer is now measured, and the comment cites it.

The conformance probe `probes/nocopy_alias_one_encoder.m` (landing with the fairqueue branch)
fills through one no-copy buffer, then copies through a second no-copy buffer over the same
pages, in one blit encoder, 20 rounds each:
- Apple M3 Max, macOS 27.0.1 (m3-max-38211): part of the fill in 20/20.
- Radeon Pro 5300M, macOS 26.7.1 (m3-max-38212): part of the fill in 20/20, mostly the old bytes.
- UHD Graphics 630, macOS 26.7.1: the whole fill in 20/20.
The one-buffer control saw the whole fill in 20/20 on all three. The Macs disagree, so ordering
across two aliasing no-copy buffers in one encoder is outside Metal's contract. The test asserts
it only where the runtime binds the second buffer inside the first's import (the in-place path
the test is named for), never where the second is a copy (HostBacking::Copied, the
copied-host-pages notice), as on the RTX 5080 Laptop GPU's 615.71.09.

Comment only; verified by the build and clippy of this commit (named in the tip report).
2026-11-16 16:23:37 -08:00
Anees Iqbal 9a7e59b1dd dma_buf_beside: a copy over a live import is checked at its commit and completion
`inside` (RUNTIME 2453) checked unconditionally that a fill through the first buffer and a copy
through the second, of the bytes they share, see each other in ONE blit encoder. Where the
driver takes the first buffer's dma-buf import only dedicated to its buffer, as the RTX 5080
Laptop GPU's 615.71.09 does, the second buffer is a copy (HostBacking::Copied, the
copied-host-pages notice). A copy agrees with the pages only at its commit and its completion
(copied.rs, "Coherence"), and Metal orders no two no-copy buffers over one allocation
(host_aliases.rs, "Not joined"). So the test failed at dma_buf_beside.rs:449 on the 5080, both
at 596d917dfe and at 24a0613783 (b5080 entry pinreds-parent-161559). The sibling test over_part
already ran its in-one-encoder checks only where both buffers lie in imports.

Now both orders run in one encoder where the second buffer lies in an import, as before. Where
it is a copy they run in two command buffers, which checks what the copy does promise: the
first's fill is copied in at the next commit, and the second's fill is merged back into the pages
at completion.

Verified: the 5080 run of this commit (named in the tip report).
2026-11-16 16:18:34 -08:00
Anees Iqbal 8e9c144ccb unread_attribute: compare the drawn codes within one code of Metal's
The test compared the 8-bit codes exactly. The RTX 5080 Laptop GPU (615.71.09) drew `shade`
as [64, 127, 191, 255], where the M3 Max stores [64, 128, 191, 255]. `shade`'s green is 0.5,
which scales to 127.5, a tie. Vulkan 1.4, 3.10.2 lets the float-to-unorm conversion return
either of the two codes nearest f x (2^b - 1) and only asks it to round to nearest. The fragment
module records `PrecisionNote::DeviceColorConversion`, whose documentation names this exact case:
NVIDIA's 615.71.09 stores 0.5 as 0x7f where Metal stores 0x80. Under owner rule 1 the device's
conversion stands, so a test that expects Metal's bits there is wrong.

Each channel is now compared within one code of Metal's answer, for both the gated-off and the
gated-on draws. The test still proves what it is for: `shade` (64, 128, 191, 255) and `color`
(191, 64, 64, 191) lie 127 codes apart in red, so a gated-off state that read the attribute
still fails.

Verified: the 5080 run of this commit (named in the tip report).
2026-11-16 16:18:34 -08:00
Anees Iqbal 9090e8a58f Exit guard: list spares.rs among the modules that keep the device's functions
RUNTIME 2455 gave the begin-ahead thread `BeginTargets` (spares.rs), which keeps an
`Arc<Functions>` so the thread can begin a spare pool's primaries without holding the device.
`only_the_listed_modules_keep_the_device_s_functions` failed on every venue since
("copies of the device's functions outside the listed modules: spares.rs: ...functions:
Arc<Functions>..."; seen on the RTX 5080 leg of the 596d917dfe round).

The copy cannot be called after the device's teardown: each begin runs inside a section of the
exit guard, and the teardown stops and joins the thread (`BeginAhead::stop`) before it releases
the spares and before vkDestroyDevice (device/mod.rs). So spares.rs joins KEEPERS with that
reason.

Verified: the test passes in the msi job that compiled this commit (named in the tip report).
2026-11-16 16:18:34 -08:00
Anees Iqbal b874899768 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 16:11:52 -08:00
Anees Iqbal 74223b54a4 RUNTIME 2492: A batch's first work that only uploads Managed copies takes narrower barriers
A batch whose first work is a Managed buffer's uploads alone (copies or inline writes of
did_modify_range ranges into its device copy) recorded the barriers every first work takes: from
ALL_COMMANDS to ALL_COMMANDS (MEMORY_WRITE -> MEMORY_READ|MEMORY_WRITE) before, and from TRANSFER
to ALL_COMMANDS|HOST with HOST_READ after. Uploads are transfers and carry no acquire, so the lead
barrier keeps its first scope (every command before, every write before) and narrows its second
to TRANSFER (TRANSFER_READ|TRANSFER_WRITE; the spec: the second access scope only includes
accesses of the stages in the destination stage mask). The device copies they write are never
read by the host (contents maps the host copy), so the trailing barrier drops HOST and
HOST_READ: no domain operation to the host (the spec: HOST_READ/HOST_WRITE in the destination
access mask perform that domain operation). Every other first work keeps its barriers.

Also: the INLINE_BYTES doc carries its XTX and 2080 numbers (a9df804b7f, which missed RUNTIME 2491's
landing). RUNTIME_VERSION 2492.

Verified: msi m3-max-38180 at dc5ffee24e: fmt 0; clippy -p metal2vulkan-runtime --all-targets
--all-features -D warnings plain 0, --cfg m2v_gpu 0, --cfg m2v_cpu_icd 0; rustdoc -D warnings 0. The managed
suites and the bench (development against this, inline against none at 64 B) on the XTX and the 2080
follow.
2026-11-16 16:11:09 -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 a686dac601 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 16:03:25 -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 72a4836b41 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 16:01:49 -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 fe23f92141 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 15:49:42 -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 5e3f60d851 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 15:24:18 -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 e3959de823 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 15:10:30 -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 3318645457 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 15:00:43 -08:00
Anees Iqbal 5d96974eca RUNTIME 2485: The tiling-cost check's bounds from its device verdicts: linear costly at twice the optimal frame
The check's first measurements put the linear frame at about 5.25 times the optimal one on the
Iris Xe of RPL-P under ANV (three runs: 4.685 against 0.890 ms, 2.109 against 0.402, 2.343
against 0.448; the first at a lower clock) and at 1.09 times on lavapipe (3.199 against 2.938
ms). The ratio bound moves from 1.5 to 2, about the middle of the two by ratio, so load on
either side moves no verdict; the excess bound stays at 500 us, below the Iris Xe's least
excess (1.7 ms) and above lavapipe's (0.26 ms). The record keeps the medians and the verdict is
worked out again as it is read, so no CHECK_VERSION bump. The measured medians, the check's
wall time (78.2 to 99.3 ms on the Iris Xe, 158.1 ms on lavapipe) and its GPU time go in the
module doc and the runtime README.

Measured: m3-max-37988 (Iris Xe, main's dispatch of 32787023ca), m3-max-37965 (lavapipe).
The 780M, XTX and 2080 runs sat behind the timing queue's exclusive jobs and were cancelled
(780M, XTX) or are still queued (2080, m3-max-37989): not measured.

MEASURED (2048x1536 BGRA8Unorm, medians of 8 rounds): Iris Xe RPL-P, ANV (m3-max-37988, three runs):
linear 4.685 / 2.109 / 2.343 ms against optimal 0.890 / 0.402 / 0.448 ms (5.23-5.26x), download
0.53-1.18 ms, upload 0.21-0.25 ms, the check 78-99 ms; lavapipe (m3-max-37965) 3.199 against 2.938 ms
(1.09x). COSTLY_RATIO 1.5 -> 2.0, COSTLY_EXCESS 500 us kept. RUNTIME_VERSION 2485.

Verified: m3-max-38017 at 384075907e: clippy -p metal2vulkan-runtime --all-targets --all-features
-D warnings 0; tiling_check unit tests 3/3 (the rule on both sides of each bound); rustdoc -D
warnings 0. The 780M, XTX and 2080 verdicts follow.
2026-11-16 15:00:02 -08:00
Anees Iqbal c66df8ee5a Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 14:54:36 -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 1104b02971 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 14:51:41 -08:00
Anees Iqbal d80fe0475f RUNTIME 2483: The device's tiling-cost check: linear images in place against optimal ones, once per driver
A consumer that keeps a GPU copy of host pages (as an x86 Mac's GPU keeps one of each
IOSurface) needs to know whether a texture in place over those pages costs the GPU more than
the copy saves. No Vulkan query answers that: a format's linear and optimal features say what
each tiling holds, not what it costs. So the device measures it, once per driver, release and
runtime, on a thread of its own, when asked.

Device::settle_tiling_cost_check(timeout) starts the check and waits for it;
Device::tiling_cost answers TilingCost (a TilingVerdict and four medians) and
Device::tiling_cost_check_report says it in words. The check draws, over 2048x1536 BGRA8Unorm
images, a full-target fetching pass and a zeroing pass into the runtime's own linear textures
in place over host pages and into Private (optimal) textures, and times the copies between the
optimal image and the pages both ways: 8 rounds after a warm-up, medians from timestamps.
LinearCostly where the linear frame passes the optimal one by more than 500 us and 1.5 times.
Unchecked, never fatal, on any refusal. The medians are kept as a record in the shader cache's
content directory, as the queue-switch and submission checks keep theirs.

The fetch stage is a new module of the translator's check draws (CheckDrawModules::fetch).
The check's thread is marked as a device check's, so its textures over host pages take the
image in place whatever the in-place check's verdicts; it holds its device through the holds
registry (Holder::TilingCheck) and steps aside as the in-place check does.

The check's note of mismatched image formats prints their raw values (vk::Format has no Debug in
the runtime's ash build); its textures over its pages take the default placement (only the
Private ones are placed outside). The signature table is blessed for TilingCost, TilingVerdict and
the three Device methods; the runtime README lists them. The bounds are provisional until the
device verdicts are in. RUNTIME_VERSION 2483.

Verified: m3-max-37966 at 32787023ca (msi): clippy metal2vulkan + runtime --all-targets
--all-features -D warnings 0, runtime with no default features 0, translator tests 16/16, rustdoc
-D warnings 0. m3-max-37965 (lavapipe): tiling_check tests 4/4, clippy --cfg m2v_cpu_icd 0, the
device report LinearCheap (linear 3.199 ms, optimal 2.938 ms, 1.09x; download 1.448 ms, upload
1.435 ms; ran 158.1 ms), a second device reading the same medians from the record. m3-max-37962 at
3be7050e7b: clippy --cfg m2v_gpu 0; m3-max-37959: tiling_check and holds tests 77/77.
2026-11-16 14:50:58 -08:00
Anees Iqbal 85987cda9d Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 14:49:02 -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 ae2fcadd20 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 14:47:16 -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 626c8c5767 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 14:28:25 -08:00
Anees Iqbal 94f09727a9 SEMANTICS 2140: Per-lane constant reads keep their storage view where a uniform buffer serializes them
On NVIDIA's driver a uniform-buffer read whose address differs between the lanes that run it
together takes many times as long as the same read of a storage buffer. A bare Vulkan sweep
(256 workgroups of 64 invocations, 64 and 1024 uvec4 reads of a 1 to 32 KiB device-local
window, the uniform block declared at the window's size, median of 15) measured the storage
buffer at 0.011 to 0.16 of the uniform buffer's time on the RTX 3090 (Ampere, 620.70.06, job
m3-max-37848), 0.026 to 0.18 on the RTX 2080 (Turing, 620.70.06, m3-max-37839) and 0.012 to
0.12 on the RTX 5080 Laptop GPU (Blackwell, 615.71.09, m3-max-37858) for per-lane words and
per-lane walks. A uniform texel buffer took 0.37 to 3.1 times the storage buffer's time there.
With every lane reading one word the storage buffer took 0.96 to 1.68 times the uniform
buffer's, so uniform reads keep the uniform buffer.

- DriverWorkaround::UniformBufferPerLaneReadsSerialize, a cost fact keyed on the three GPUs
  measured (driver_facts rows; NVIDIA_RTX_2080 added). RADV is not listed: AMD has no such fact.
- lower::simd::uniform: Uniformity::among_active_lanes, a data-only mode of the analysis (no
  control divergence, no post-dominator tree; a load divergent only through its pointer). The
  workgroup analysis makes every loop counter after an early return divergent; this mode keeps it
  uniform. What it misses (a phi joining uniform values after a divergent branch, a value read
  after a loop left per lane) errs toward the uniform view, today's choice.
- memory::provenance records the pointer of each indexed read of a constant buffer root;
  memory::plan marks SlotPlan::lane_read on a profile with the fact, for a slot a uniform view
  could read, running the analysis once and only where such a slot has an indexed read.
- lower::access::view_kind keeps a lane-read slot's storage view. The choice is the slot's: its
  uniform reads pay 0.96 to 1.68 times and lose spirv::hoist (documented there). Every stage takes
  the rule; compute was measured, the graphics stages are expected, not measured.
- No FAST-PATHS row: every view reads the same bytes. No Degradation kind. No runtime change.
  SEMANTICS_VERSION 2139 -> 2140.

Tests: uniform's active-lanes unit tests (an early return's loop counter, per-lane data alone);
engine_lane_reads (per-lane table -> Storage, guarded uniform loop and constant offset ->
UniformWords on the 5080, 3090 and 2080 identities; RADV keeps UniformWords for all three, the
negative control); device profile keying test. api_signatures blessed (one variant added).

Verified: msi job m3-max-37911: clippy -p metal2vulkan --all-targets --all-features CLIPPY=0;
nextest -p metal2vulkan --all-features over uniform::tests, engine_lane_reads, device::tests::profile,
engine_access, memory::plan, memory::provenance: 135 passed. Release translation time and peak, the
other clippy configurations, rustdoc and a 2080 runtime A/B follow on development.
2026-11-16 14:27:38 -08:00
Anees Iqbal 51280732aa Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 14:10:02 -08:00
Anees Iqbal c195086369 RUNTIME 2480: A dispatch's regions are counted once and walked by count, and its row checks read the pieces
What: Pieces holds the number of chunks its count takes, computed where the axis is cut, so
Regions::len and Regions::iter divide nothing; planning and instantiating a dispatch asked for
each axis's count over its chunk size again at every len() and every walk of the axis.

Why: the regions are numbers since f5b102f317, and an instantiation reads their count and
walks them several times (the product's bound, the emptiness check, the commands' length, the
unit-axes and row checks, the regions' own walk), each time three divisions.

Verified: the bind::dispatch tests in the next msi job.

What: Regions::iter is an iterator of its own (RegionsIter), which counts each axis's piece
from x slowest to z fastest and takes each piece by its number (Pieces::piece), where it was
three nested flat_maps over chained ranges. The unit-axes and row checks (unit_axes,
multi_row) read the widest local size of each axis's pieces (Regions::widest) rather than
walking every region: each piece of an axis is some region's wherever there is a region, so
the answers are the walk's.

Why: msi profile of both binaries in one job (m3-max-37856, taskset -c 0-7, the guest shape):
at the tip of the regions-as-numbers change, unit_axes alone took 122 calling-thread samples
(about 67 ns a dispatch, 1.8% of the dispatch call) and the flat_map walk in instantiate 32
more, where base walked a Vec; the instantiation subtree measured 12.75% of the dispatch call
against base's 12.25%.

Verified (lane instleft): clippy plain 0 and the translator bind::dispatch, bind::plan and bind::graphics tests plus tests::bind 80/80 at 080d04c44a (m3-max-37875). Profile of both binaries in one job (m3-max-37874, msi, taskset -c 0-7, the guest shape), base 542c74ed91 against 080d04c44a: the instantiation subtree 12.87% -> 11.13% of the dispatch call (about 42-52 ns a guest dispatch at a 2.4-3.0 us call; RUNTIME 2478 alone measured about neutral, its translator half costing what its runtime half saved). Clippy m2v_gpu and m2v_cpu_icd and rustdoc ran at f5b102f317 (m3-max-37851, all 0); these commits touch bind/dispatch.rs only, which has no cfg-gated code; they follow on development.
2026-11-16 14:09:20 -08:00
Anees Iqbal 6bbfc310d3 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 14:04:36 -08:00
Anees Iqbal 5a0d21cdc5 RUNTIME 2479: A reused command buffer state keeps its predication and fold-order room and its compute logs
A command buffer's state, reset at its release for the next command buffer
(spare_states.rs), started its command predication's lists (opened, alone,
each unit's opened_fresh) and each group's FoldOrder (its map and a Vec of
priors per resource) empty, so every 5-encoder command buffer allocated them
again over memory another thread freed. And every compute encoder took its log
from the device's SpareLogs mutex, which the queue's handler thread takes as
releases give logs back.

- Predication::reset clears its lists in place. opened_fresh moves from Unit to
  Predication: one unit is open at a time, and it is cleared as the unit ends.
- State.order_room holds the group order the way stash_room holds the stash:
  Fold::begun takes it, close_fold gives it back cleared (FoldOrder::clear keeps
  the map's room and moves each resource's emptied list into its boxes, which
  join reuses). The order's second-encoder build is a join into that room;
  FoldOrder::after is gone (tests build it with none + join).
- The release clears compute logs outside the state lock and keeps up to
  STATE_LOGS (32) in the state (State::keep_compute_logs). The rest go to the
  device spares in one give_all. A compute encoder's open takes its log under
  the state lock it already holds (State::kept_compute_log), and uses the device
  spares only when the state has none left.
- Bounds: Room counts the new lists (entries, for record_lists_grown) and the
  kept logs' bytes, so the existing caps hold. A state with more than 8 MiB is
  not kept, and kept states hold at most 16 MiB in total.
- Predication::enter no longer moves unit.carried out with mem::take. It
  drains it instead.

Same commands, barriers, predication and fold answers. New tests:
tests::spare_states::a_reused_command_buffer_of_five_compute_encoders_grows_no_list_and_takes_no_spare_log
(device) and tests::tracker::a_cleared_fold_order_answers_as_a_fresh_one_in_the_room_it_kept
(host).

With: Predication::enter rebuilds its unit around the bodies it hands on (take_if; no mem::take, no empty value left in a borrowed owner); the cleared fold-order test measures the room the clear kept.

Checks at the lane tip b107e56a6c (msi): clippy -p metal2vulkan-runtime --all-targets --all-features -D warnings under m2v_cpu_icd 0 (m3-max-37853); at ed6a832c98 the lavapipe spare_states, tracker, fold, rebind, compute, spares and encoder suites 250/251 (m3-max-37842; the one failure, the host test's baseline, is fixed in b107e56a6c). The suites and two negative controls at the tip, and the timing (encopen's estimate ~85 + ~48 ns a guest dispatch), follow on development.
2026-11-16 14:03:54 -08:00
Anees Iqbal 0f29d6a6e3 Instantiation's allocation test runs dispatches of as many regions or fewer
What: instantiating_over_kept_commands_allocates_nothing instantiates the ragged grid twice and
then the whole one over the kept commands, each of as many regions as the commands hold or
fewer. Its first form ran the ragged grid after the whole one, whose four regions take three
regions' keys and push writes anew over commands of one: 12 allocations (m3-max-37844), which
the method's contract allows.

Verified: in the next msi job.
2026-11-16 14:02:18 -08:00
Anees Iqbal a040b06857 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 14:02:10 -08:00
Anees Iqbal 4de6a8dd92 RUNTIME 2478: Compute instantiation over kept commands allocates nothing and searches no constant
What: a dispatch's regions are planned as numbers (dispatch::Regions: each axis's Pieces and
one MultiRegion), so planning makes no Vec<Region> and a ragged grid's fit check no list of its
local sizes; instantiate writes each region straight from them. A region's key takes the
template's fixed constants by walking them in the layout's order, which is the order the
planner lists them in, and searches them only where the next one is another key's. In the
runtime, Variant::keyed_regions zeroes a key's uniform-view RangeAtBindOffset constants in the
key's own bytes (render/residual.rs residual_in_place), over the constant IDs the variant lists
once as it is made (uniform_residual_ids), where it cloned each key into its residual form and
dropped the kept one.

Why: profile at 542c74ed91 (msi lavapipe, release with frame pointers, taskset -c 0-7,
dispatch_chain --host 400 --only encoders --dispatches 5 --groups 64 --states 3 --binds
tex-moved, job m3-max-37811, calibrated to the dispatch call's 2392 ns): instantiation took
320 ns a guest dispatch, of it keyed_regions 52 (the residual form's scan and the key's clone
and free), spec_key_into 45 (13 of it the linear search of the fixed constants), regions 34
(14 of it the Vec<Region>), bind_buffers 46.

The commands are the same by construction: the regions come in the order the product gave
them, each constant's value is the one the search finds (the planner's fixed values are a
function of the key alone), and the in-place zeroing is the residual form's, or the key as it
was where that form is the key itself. Builds with debug assertions still instantiate afresh
and compare at every in-place write.

Tests: bind::dispatch's instantiating_over_kept_commands_allocates_nothing (allocations_during,
now pub(crate): zero over commands of as many regions or more, which the Vec<Region> broke) and
a_regions_key_takes_its_fixed_constants_in_any_order; the runtime's general_form
a_key_takes_its_residual_form_in_its_own_bytes (the residual form's key, in the storage kept).

Checks at the lane tip f5b102f317 (msi): clippy -D warnings --all-targets --all-features for metal2vulkan and the runtime 0 (m3-max-37844). The translator bind tests (37844), the runtime compute, dispatch, encoder and general_form tests on lavapipe in a debug build (37845), the pinned interleaved release A/B (37843), clippy m2v_gpu and m2v_cpu_icd and rustdoc (37851) follow on development. Translation output is unchanged (no SEMANTICS bump).
2026-11-16 14:01:26 -08:00
Anees Iqbal 542c74ed91 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 13:30:18 -08:00
Anees Iqbal 86d7480c92 RUNTIME 2477: A part of one command is summarized from its uses, building no map
An ordered encoder's part whose one command waits uncompared (`first`) now
keeps that command's tracked uses where they wait, rather than noting them in
the part's tracked map: at the encoder's end its summary is made from them
(the tracked uses that touch something, a stable sort by key, the uses of one
key and range joined into the first), the very list the map read by key would
give. A command of at most ENTRIES_PER_KEY uses can merge no key's ranges, so
that is the only rule it has to repeat. Anything else that adds to the part,
orders after it or splits it (a second command, take_in_first, note_kept,
split) puts the waiting uses in the map first, through the same noting. The
readers of the map before the end (written, accessed, touched_in, uses_key,
written_ranges, tracked_in) read the waiting uses beside it, giving the map's
answers.

Why: a guest's compute encoders hold one dispatch each. The profile of the
guest shape (dispatch_chain --host 400 --only encoders --dispatches 5
--groups 64 --states 3 --binds tex-moved, msi lavapipe, release, pinned) had
the part's map at ~60 ns of the dispatch call (hashing each use, the map's
allocation) and finish_parts' walk of it at ~104 ns of end_encoding, both
for a list the dispatch already had.

The encoder's order (inside, first) is untouched, so every barrier inside an
encoder is the same; the summary is the identical list, so the fold's join,
the batch tracker's barriers and waits and the residency see the same input.
Builds with debug assertions also make the map's summary at the end and assert
it equal.

Tests: tests::tracker::a_part_of_one_command_is_summarized_as_its_map_would_be
(the summary against an unordered encoder's map: a key at two ranges, one
range twice, an untracked use, a use that touches nothing; no command noted in
a map, and both of a part of two),
a_part_of_one_command_answers_its_readers_as_its_map_would, and on a device
tests::compute_lone_parts (a command buffer of 5 one-dispatch encoders notes
no command in a part's map, of 5 two-dispatch encoders 10), counted by the
test-only tracker::part_notes. Timings and suite results are in the lane's
report.
Checks at the lane tip 3495163515 (msi): clippy -p metal2vulkan-runtime --all-targets --all-features -D warnings 0 (m3-max-37756); on lavapipe in a debug build, so the map-equality assertion ran in every ordered one-command encoder, tests::tracker (81) plus compute_lone_parts and compute_parked: 91/91 (m3-max-37756). The pinned interleaved timing (m3-max-37764), clippy m2v_gpu and m2v_cpu_icd, rustdoc and the lavapipe suites follow on development; the expected cut is ~150 ns a guest dispatch (the map note ~60 ns in the dispatch call, finish_parts' walk ~104 ns in end_encoding).
2026-11-16 13:29:31 -08:00
Anees Iqbal b9eadef0c9 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 13:18:59 -08:00
Anees Iqbal cb033efbcf RUNTIME 2476: A bind state sets aside 15 pipeline states, so a carry holds 16 kept draws
SET_ASIDE goes from 7 to 15. It bounds both the render bind state's
set-aside array (LiveBind) and the compute one's (LiveDispatch), and it
bounds a carry to SET_ASIDE + 1 kept draws. In guest walks, WindowServer's
desktop steps turn over 25-60 pipeline states a frame. Launchpad's command
buffers draw through a median of 12 states each (p90 46). Passes of more
than 8 states are 1.2-2.0% of passes but 13-22% of draws in Finder and
Launchpad. At 8, a pass of state k after 8 or more others finds no kept
draw carried and takes every step.

Docs that named 7/8 now name 15/16: live_bind.rs, render/carried.rs,
render/draw_again.rs, compute/live.rs. Tests that named the bound:
carried_draws' passes-of-states test now runs 16 states and expects 15
carried aside; compute_set_aside's doc says sixteen states and 32 KiB.
draw_costs gets 20 plain states, so `--states 16` runs and the default
pass1/pass17 shape still carries no kept draw. With 15 set aside, all
of the old 12 would carry. No FAST-PATHS row names this bound.

Verified (release build, msi lavapipe, encoding thread pinned to the
P-cores; jobs m3-max-37724 and m3-max-37730, base and after built in one
workspace). Instruction counts are the thread's user-space instructions.
draw_costs pass1/pass17, figures per pass (pass1 less the draw that
pass17 gives), base -> after:
  states 2:  instructions 75978 -> 76208 (+0.3%), cycles -2.2%
  states 4:  instructions 76278 -> 76478 (+0.3%), cycles -1.0%
  states 12: instructions 90656 -> 77339 (-14.7%), cycles -17.4%
  states 16: instructions 89686 -> 77547 (-13.5%), cycles -17.1%
pass1's draws_rebound_carried at states 12 went 568 -> 9204 of 9216, and
at states 16 0 -> 9200. Counts at states 2 and 4 are equal in both builds.
dispatch_chain's guest compute shape (5 encoders of 1 dispatch per command
buffer, 3 states, --binds tex), 3 interleaved pairs: instructions per
dispatch went 45787 -> 45738 (median, -0.1%), thread CPU 5221 -> 5111 ns.

Memory bound. size_of went up, render LiveBind 20808 -> 41224 bytes and
compute LiveDispatch 4688 -> 8784. Each is boxed, so encoders move a
pointer. Holders, each capped by the runtime:
- render: 4 device spares (SPARE_LIVE_BINDS); at most one per uncompleted
  command buffer (its open render encoder's, or the carry it holds for
  its next render encoder; an opening takes the carry); at most 16 per
  queue held past commits (queue::CARRIES).
- compute: 4 device spares (SPARE_LIVE_DISPATCHES); at most one per
  uncompleted command buffer (its open compute encoder's, or the one
  parked in it).
A queue holds at most its max command buffer count of uncompleted
command buffers (64 for newCommandQueue). Per queue at that default the
inline worst case is:
  render (64 + 16) x 20808 = 1.59 MiB -> 80 x 41224 = 3.15 MiB
  compute 64 x 4688 = 293 KiB -> 64 x 8784 = 549 KiB
and per device, on top of that, the spares: render 81 -> 161 KiB,
compute 18 -> 34 KiB. Beyond size_of, each slot also has its boxed
BindState and the lists that use grows; those were not measured.
compute_set_aside caps a compute slot plus its BindState at 2 KiB.
Unbounded by the runtime, as in Metal: how many queues a program makes
and each queue's max command buffer count.

Checks at the lane tip d074d4ea47 (msi): clippy -p metal2vulkan-runtime --all-targets --all-features -D warnings plain and m2v_cpu_icd 0 (m3-max-37735), m2v_gpu 0 and rustdoc 0 (m3-max-37736); lavapipe carried_draws, compute_set_aside and draw_again 48/48 (m3-max-37735). The state counts per pass and command buffer are the consumer's Iris walks (passstates, m3-max-37560/37561).
2026-11-16 13:18:07 -08:00
Anees Iqbal da80ece1d1 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 13:04:14 -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 ff32d9a89e Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 12:51:00 -08:00
Anees Iqbal d4a111c357 RUNTIME 2474: Compute dispatches clone no device handle: shadow planning returns early, record borrows
What: a compute dispatch no longer takes a handle of its own of the device.
- EncoderCore::plan_shadows returns no copies at once for a command that uses
  no shadowed texture in an encoder that used none (ShadowSync::is_empty, where
  Shadows::before changes nothing and plans nothing); where it plans, it reaches
  the device through the command buffer's handle, borrowed apart from the
  shadows and leases the merges take.
- EncoderCore::shadow_copies returns at once for no copies (nothing recorded,
  barriered or spliced).
- compute::record reaches the device through the command buffer's handle at
  each use (core.device()) instead of cloning it; the pushed set-zero count is
  added after command_reaching_pushed rather than inside its closure.

Why: every Device clone and drop is two SeqCst read-modify-writes, on the
Arc<DeviceShared> strong count and on Holds::program, lines every thread of
the device writes. The three clones were ~80 of the ~111 such RMWs per
command buffer of 5 compute encoders x 1 dispatch (msi, locked-instruction
samples), and two threads encoding at once each pay the other's writes. A
probe of exactly these three borrows (msi P-cores, lavapipe, exclusive):
thread CPU per dispatch spawned alone 3598 -> 3538 ns, two threads on one
queue ~4290 -> 4238, on two queues ~4288 -> 4135.

How verified (lane walkshare): msi P-cores, lavapipe, release, exclusive, thread CPU per dispatch (5 dispatches a command buffer), mean of 2 runs, before m3-max-37602 (5126f153ca) and after m3-max-37631 (c55c8666d9): alone on the calling thread 3341 -> 3226 ns (-3.4%), alone spawned 3621 -> 3466 (-4.3%), two threads on one queue 4306 -> 4039 (-6.2%), on two queues 4250 -> 4046 (-4.8%); per command buffer two walks on one queue 21.5 -> 20.2 us. The lavapipe compute, dispatch, encoder and shadow suites 143/143 (m3-max-37603). Clippy plain 0 (m3-max-37644) and m2v_cpu_icd 0 (m3-max-37646) at 06b683f292; m2v_gpu clippy and rustdoc follow on development (m3-max-37645).

With: dispatch_chain --queue-each (each encoding thread a queue of its own) and --spawned (one encoding thread started each run, as several run), measurement flags only; shadow planning passes the borrowed device on as it is (clippy needless_borrow).

shadow_copies keeps its own device handle on its work path (copies to make, rare), where what it takes from the device lives across calls on the encoder.
2026-11-16 12:50:13 -08:00
Anees Iqbal 24a0613783 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 12:40:18 -08:00
Anees Iqbal ebfc82f564 RUNTIME 2473: A dispatch left to its host step holds what its tables bind from its call
A rebind racing a compute encoder whose dispatch is left to its host step
failed the command buffer EncodedUseRebound (the threaded run's host-step
family, intermittently; the consumer's answer table ends the VM on that
kind). The cause: ComputeCommandEncoder::defer_dispatch cloned the encoder's
ArgumentTable into the ArgumentDispatch and never retained it, so the encoder
held none of the buffers the table binds (only the arguments or stage-in
region buffer that copy_arguments copies). At the commit, steps_hold keeps the
command buffer's holds until it completes, which is what the rebind.rs docs
promise ("counts as uncommitted until it completed: a rebind meanwhile is
refused"), but the bound buffer was not among them. The host step's own core
held the buffer only while it recorded (Holds::new at the step's start; the
segment core's Holds drop at end_segment). So a rebind could:
- overlap the step's recording: its hold then found the publish closed past
  its start, Taken::raced, and the segment's submission failed;
- or land between end_segment and the segment's batch submission: failing_at
  found the pin moved.
Both fail as ReboundAt::Segment(HostStep). 2468's gate covers only the
encoder's own calls, and 2470's hold to submission is the else-branch of
steps_hold, so neither reached it.

The fix: defer_dispatch retains the encoder's table into its core
(ArgumentTable::retain), as a recorded dispatch's record() does. That keeps
the bound keys and holds each buffer over host pages among them, and
steps_hold keeps those holds until completion. So a rebind from the
dispatch's call on is refused (EncodedUses, Unreplaced::Held), never failing
the command buffer later.

- Both defer forms take it. dispatch_resident's Direct form (an indirect
  stage-in region set) and dispatch_indirect_resident's Indirect form both
  reach defer_dispatch, whose first statement is the retain.
- The hold is taken inside the dispatch's call, which is gated
  (ComputeCommandEncoder::logged -> begin_call -> CallGate, every compute
  encoder from its open). No rebind's publish overlaps it, so it never finds
  a race.
- Cost: nothing for an encoder that leaves no dispatch to its host step. For
  one that does, one retain per deferred dispatch, as a recorded dispatch
  pays.

Deadlock audit, by lock: ArgumentTable::retain takes the table's `retained`
lock, then retain_into -> touch_keys -> Holds::hold takes rebinds.buffers. That
is table.retained -> buffers, the order record() already takes at every
recorded dispatch (compute.rs, tables.table.retain(core)). The predication
state lock taken just after for the host gate is a temporary, released
before. Nothing waits on the new hold: a rebind finds `pending` and is
refused, so no cycle can form.

Side effect, closer to Metal: the bound resources join the encoder's used
keys from the dispatch's call (used_resources, ended_encoders,
CommandBuffer::used_resources for detach_backing). Before, they were listed
only once the host step recorded. Metal knows a dispatch's resources at the
call. A detached buffer bound to such a dispatch now pins Detached at the
encoder, as a recorded dispatch's binding does.

Control: the previous commit's
a_rebind_while_a_host_step_records_a_dispatch_of_the_buffer_is_refused.

With: Rebinds: a control of a rebind while a host step records a dispatch of the buffer (1b5b6553a6, test only).

Checks at the lane tip 2fed4f8f75: clippy -p metal2vulkan-runtime --all-targets --all-features 0 and the m2v_cpu_icd test build in m3-max-37590 (msi); the control and the rebind, host_step, indirect, predication and pending suites on lavapipe, the threaded test 20 times, the negative control, clippy m2v_gpu/m2v_cpu_icd and rustdoc follow on development.
2026-11-16 12:39:30 -08:00
Anees Iqbal 7092110549 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 12:24:53 -08:00
Anees Iqbal 7055ff84c5 RUNTIME 2472: Compute encoders move as one pointer, and a core ends in its box
ComputeCommandEncoder held its whole state (888 bytes) by value, so its
open's return, each move by a caller (a consumer that boxes it copies it
into the box), and end_encoding's self each copied it whole. Its state now
lies in a box of its own (Body), and the encoder is that one pointer, as the
render encoder already boxes its lowering.

A core's end read the whole core out of its box onto the stack
(EncoderCore::unboxed_apart in end_encoding) and passed it by value to
end_with_replay, which took it apart again. end_with_replay now takes the
boxed core, takes it apart where it ends, and hands its emptied box on:
with a compute encoder's bind state to the command buffer's park
(compute::Parking, then Parked), else back to the device's spares.

The same Vulkan commands; no API change.

Verified: tests::encoder_moves asserts the encoder is one pointer (it was
888 bytes against the old bound of 1 KiB).

With: Compute encoders: fields through the body box everywhere; end_with_replay over a boxed or held core; end_with_replay: take the held core through one plain reference until it is taken apart.

Why: a compute encoder was 888 bytes moved by value through open, the caller's Box::new and end, and its core was read out of its box whole at its end (reims decodecost: large-value memcpy 4.0% of the decoder thread). Now a move copies 8 bytes and the core is taken apart inside its box.

Measured (lane encbox, msi lavapipe, dispatch_chain --dispatches 5 --groups 64 --only encoders, release, base/tip alternated twice, m3-max-37522): encode per encoder 4613 -> 4465 ns (-0.15 us), end 1102 -> 1013 ns; thread CPU 6645 -> 6488 ns. Below the 0.3 us bar for a perf claim; kept as a built, structural, measured-positive change.

Checks: clippy plain, m2v_cpu_icd, m2v_gpu (-p metal2vulkan-runtime, all targets, all features) 0 in m3-max-37545; tests::encoder_moves asserts the encoder is one pointer; the lavapipe compute/encoder/render/blit suites (m3-max-37547) and rustdoc follow on development.
2026-11-16 12:24:12 -08:00
Anees Iqbal db7a122086 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 11:30:20 -08:00
Anees Iqbal ea9feeb12f RUNTIME 2471: A variant refusal is kept in the device's memo: asked once a device, said once in the log
What: the device's memo of compiled pipelines now keeps the compile layer's Unsupported
refusal of a function under that function's FunctionCompileKey, the key its compiled
function is kept under. Sources::function answers a later ask of the same key from it,
translating nothing. A dispatch's variant answered this way gets no pipeline creation log
line (Variant::compile asks Sources::refusal_kept), so the log says each such refusal once
a device. Only Unsupported is kept, which the translator holds permanent for its input on
the device's profile (Error::is_permanent_for). A deadline, a cancellation, a failed
allocation or any other error is never kept. The entry sits in the memo's one LRU under
its byte and entry bounds, weighed at what it holds, and a recovery's carry_from takes it
with the rest.

Why: each compute state already remembers its own flat, folded, replay and
partial-threadgroups refusals (Program's *_refused flags). But a state made again of the
same function starts with clear flags, and the memo kept successes only. So every new
state's first indirect or ragged dispatch asked the compile layer for the refused variant
again: one declined line and one refused translation per state. A guest that makes many
states of one kernel logged the line thousands of times. Which form a dispatch runs, and
what it answers, are unchanged: the state still records the refusal and takes the same
other form.

Test: tests::declined_once (lavapipe or GPU cfgs). A child process with the log on makes
4 states of one threadgroup-barrier kernel, 4 indirect threadgroup dispatches each, and
checks every dispatch's words. The parent asserts 1 refused translation (a test-only
counter in sources.rs) and 1 declined line.

Checks (lane declineonce): lavapipe tests::declined_once in m3-max-37374: 4 states of one kernel, 4 indirect dispatches each, every word checked: 1 translation refused, 1 declined line (the control without the memo follows); clippy -p metal2vulkan-runtime all targets all features 0 plain (m3-max-37377), m2v_cpu_icd (37374), m2v_gpu (37379). Compute pipeline suites (m3-max-37387) and rustdoc follow on development.
2026-11-16 11:29:32 -08:00
Anees Iqbal 74e0d61851 rebind_reach: made_once is unused since the unit test asserts the refusal
m3-max-37369 (msi): clippy under --cfg m2v_cpu_icd and --cfg m2v_gpu at
5bfab2beaa failed on the unused import; rustdoc -D warnings passed.
2026-11-16 11:28:04 -08:00
Anees Iqbal 6904306929 Re-bless at SEMANTICS 2139: golden hashes, the new fixture's rows and printout, the census
m3-max-37348 (M3, at 4806a79c68): golden_hashes.tsv (function_constant_interface's
fc_fragment_input_to_output moves with its gated-off output's value now undef, plus the new
fca_vertex_unread_attribute fixture's rows), public_fixture_expectations_engine.tsv (the new
fixture) and tests/air_input/fca_vertex_unread_attribute.txt. m3-max-37349: authored-compile.tsv,
10 artifacts and the product stamp.
2026-11-16 11:24:21 -08:00
Anees Iqbal cda5fd8f02 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 11:23:50 -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 4806a79c68 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 11:17:17 -08:00
Anees Iqbal c8484ddf0f SEMANTICS 2139: An attribute read only into a gated-off output is not read
What: canon's unobserved_code kept every value-only instruction that a surviving
one reads. The returned struct's insertvalue chain stays because the return reads
it, so an insert into the field of an output a function constant gates off (or of a
field a later insert sets again) kept its inserted value alive, and with it the
value's whole computation and the parameter it read. Such an insert now inserts
`undef` in place of a value the observation does not observe (unread_inserts), and
kept_reads follows only its aggregate, so the computation and the parameter's read
go. lower::users::params_used, and with it pipeline::compile::declared_attributes,
then leave out a vertex attribute that reaches only a gated-off varying, and the
vertex projection no longer refuses a descriptor without it.

Why: a render pipeline was refused InvalidDescriptor(VertexAttribute { attribute: 1 }).
Its vertex function reads attribute 1 through one phi into a varying whose
air.function_constant predicate is false in the pipeline's constants. Metal reports
that attribute inactive and makes the pipeline from a descriptor without it. A live
attribute the descriptor lacks stays refused, as Metal refuses it.

Oracle (m3-max-37322, Apple M3 Max, macOS 27.0.1, validation layer off and on), the
new owned fixture fca_vertex_unread_attribute: constant false: attribute 1 active 0,
a descriptor of attribute 0 alone makes the pipeline, texel (64, 128, 191, 255);
constant true: attribute 1 active 1, that descriptor is refused ("Vertex attribute
color(1) is missing from the vertex descriptor"), both attributes draw
(191, 64, 64, 191).

Tests: tests::engine_unread_attribute (six committed profiles: gated off links
with attribute 0 alone and every stage passes L3; gated on refuses
VertexAttribute{1} without it and links with both); the runtime device test
tests::unread_attribute (the same three states, drawn, pixels compared with
Metal's). The lane's job reports and its negative control are in the tip report.

With 9a15486547: Owned fixture: an ungated vertex attribute that reaches only a gated-off varying.

Checks (lane deadattr): clippy plain (-p metal2vulkan-air -p metal2vulkan -p metal2vulkan-runtime, all targets, all features) 0 in m3-max-37340. Oracle m3-max-37322 (M3 Max, macOS 27.0.1, validation off and on): constant off, attribute 1 inactive and a descriptor of attribute 0 alone makes the pipeline; constant on, that descriptor is refused ("Vertex attribute color(1) is missing"). The air and translator suites, the negative control and the lavapipe draw (m3-max-37341) follow on development; golden and census re-bless on development.
2026-11-16 11:16:28 -08:00
Anees Iqbal e2922ae77c rebind_races: the two RUNTIME 2465 controls race blits, as compute calls are gated now
With compute calls gated, the hold control's dispatch refuses the rebind
(its call is under way) and the publish control's dispatch waits for the
held publish to close, which the test itself holds: both hung in
m3-max-37299 (lavapipe, msi), the hold one because the expect panicked
inside the scope before letting the paused thread go. They now run blits,
which log every call and are encoded again after a race: a copy from the
buffer held at its hold, and a copy from the texture over the buffer during
the held publish. The hold control lets the paused thread go before it
checks the rebind's answer, so a failure fails instead of hanging.

Verified: m3-max-37299 at ec3cbb49c7, 313 of 315 filtered lavapipe tests
passed (rebind, detach, host pages, host step, indirect, predication,
pending, holds), the new gated control and the six-family threaded run
among them; the two hung are these. The next job runs them.

Why now: on development since RUNTIME 2468 both controls hang (m3-max-37299: the hold control's dispatch refused the rebind and its expect panicked inside the thread scope while the paused thread waited; the publish control's dispatch waited for a publish the test itself held).

Verified (lane rebindsafe2): m3-max-37319 (msi lavapipe) all 4 rebind_races tests pass, the gated control refused EncodedUses, the six-family threaded run 0 wrong outputs; m3-max-37318 clippy m2v_cpu_icd and m2v_gpu cfgs 0. Test code only: no RUNTIME bump.
2026-11-16 11:06:41 -08:00
Anees Iqbal 4db18374c0 Re-bless the authored compile census at SEMANTICS 2138
The census (m3-max-37276, at 2bafb6537a) changed only its product stamp; the golden hash table,
engine inventory and air_input printouts (m3-max-37275) are unchanged.
2026-11-16 11:03:59 -08:00
Anees Iqbal f10ecb62cf Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 11:01:59 -08:00
Anees Iqbal 08e584e114 RUNTIME 2469: Scheduler: undo the burst linger (cut 2 of RUNTIME 2467); passing holds stay
What: removes the scheduler thread's stay-awake through a burst of commit_and_submit calls
(Burst, BURST_WINDOW, Inbox::pass_each's linger, the wake within a burst), its docs in
CommandBuffer::commit_and_submit, the runtime README and the scheduler and inbox module docs,
and its tests (tests::inbox's lingering-pass test, tests::commit_and_submit's back-to-back burst
test, and tests::scheduler_wakes' sleep of BURST_WINDOW between isolated commits). The
scheduler, the inbox and those tests are again as they were before RUNTIME 2467. Kept from
2467: the passing holds' signal only where a making waits (resource_ids.rs) and dispatch_chain's
latency, busy and idle lines.

Why: the hand-off misses its condition, that commit -> submission inside a burst gets no worse
at p99. Commit-call time per command buffer fell (RADV PHOENIX 34.4 -> 14.7 us, msi lavapipe
9.1-10.0 -> 4.3-6.3 us). But commit -> kernel start inside a burst rose at p99: msi lavapipe
11-12 -> 20-28 us (steady state 7.6-8.2 -> 9.9-14.3 us); RADV PHOENIX under
CompletionPolicy::Grouped 34 us -> 1.06 ms and commit -> GPU start 181 us -> 1.25 ms, where the
thread's passes kept burst batches in groups that the committer's would have sent alone; and
with two committing threads on an oversubscribed host (gem10, load 22 on 16 threads) 96 us ->
1.45 ms, where a lingering thread that is preempted while counted holds every commit left to
it.

Verified: the lane's potluck job (build, clippy, the touched lavapipe tests), named in its report.

Why undone: RUNTIME 2467 cut the commit call 34.4 -> 14.7 us per command buffer on RADV PHOENIX, but raised commit-to-GPU-start p99 there from 181 us to 1.25 ms (the scheduler thread's own passes held burst batches in groups under Grouped), and two-thread p99 under host oversubscription from 96 us to 1.45 ms (a lingering thread preempted while counted holds every commit left to it). Cut 1 (passing holds) and the bench stay.

Verified (lane walkcpu): m3-max-37306 (msi): build 0, clippy plain 0, lavapipe touched suites 71/71 (commit_and_submit, scheduler_wakes, inbox, left, resource_ids, passing_holds, waiter_submits, submission_turns). The seven files are identical to 6386a12a6b.
2026-11-16 11:01:17 -08:00
Anees Iqbal 3271b20cf8 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 11:00:20 -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 80d1e277d0 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 10:53:35 -08:00
Anees Iqbal e016e264c6 host_residency: the excess release loop lints clean where parked images are not built
Excess has its Parked variant on unix alone (RUNTIME 2464). Off unix the
release loop's let group = match excess { Excess::Group(group) => group }
is a single infallible arm, which clippy's infallible_destructuring_match
refuses under -D warnings: the runtime crate's clippy failed on Windows
(host_residency.rs:1200, job m3-max-37264 on the UHD 630 node, native
gnullvm, --cfg m2v_gpu --all-targets --all-features), as CI's clippy for the
Windows targets does.

A parked image is now released by a cfg(unix) if-let before the group is
taken, and Excess::group gives the group (None for a parked image), so the
loop is the same code on every target and unchanged in behaviour on unix.

Verified: Windows clippy in the job named in the lane's report.

Checks (lane d32s8): Windows clippy (runtime, all targets, all features, GPU cfg, x86_64-pc-windows-gnullvm) 0 in m3-max-37272 (it failed at development in m3-max-37264); msi m3-max-37281: Linux clippy plain 0, lavapipe host_residency and dma_buf_parked_images 10/10. Unix behaviour unchanged, so no RUNTIME bump.
2026-11-16 10:52:42 -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 a8b791bd12 completion_latency: the completion sync file calls compile on unix alone
CommandBuffer::add_completion_sync_file and export_completion_sync_file live
in command_buffer/sync_file.rs, which is cfg(unix). The guest-shaped leg's
commit closure (RUNTIME 2430) called them on every target, so the runtime's
lib test did not compile on Windows (error E0599 at completion_latency.rs:1670
and :1674, job m3-max-37226 on the UHD 630 node, development 6386a12a6b).
The calls are now cfg(unix); elsewhere the leg commits without a sync file,
as a device without one already did (add_completion_sync_file's Err).

Verified: compiled in the Windows lib-test build named in the lane's report.
2026-11-16 10:46:08 -08:00
Anees Iqbal ac2de74dee Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 10:45:56 -08:00
Anees Iqbal b01ec7ceeb RUNTIME 2467: Scheduler: awake through a burst of commit_and_submit calls; passing holds signal only where a making waits
What:
- Scheduler (scheduler/mod.rs, inbox.rs): a commit_and_submit within BURST_WINDOW (100 us) of the
  one before wakes the scheduler's thread after its own pass; the thread then stays counted as the
  inbox's passer while the last commit_and_submit came within the window, spinning on the inbox,
  so later commits of the burst post and return, left to it, and its next pass takes them in
  commit order. submit_before_waiting, a waker's poke for what is not in the inbox, and a stop end
  the burst. An idle device's thread spins not at all; a burst costs that thread's CPU for its
  length and one window more.
- Passing holds (resource_ids.rs): the last hold to end signals only where a making waits.
- dispatch_chain bench: back-to-back command buffers, encoding threads on one queue,
  commit-to-start latency, CPU per second busy and idle.
- Docs: commit_and_submit and the runtime README describe the burst.

Why: a guest's decode walk commits small command buffers (5 compute encoders of 1 dispatch) 35 to
76 us apart on its critical path, and each commit_and_submit made the scheduler's pass inline on
the committing thread (Inbox::pass_on inside the commit). Left to an awake scheduler thread, the
commit call returns early.

Verified (lane walkcpu):
- msi lavapipe (m3-max-37234), commit call per command buffer of 5 encoders x 1 dispatch:
  64 back to back 9.2 -> 4.5 us; two threads on one queue 11.5-12.6 -> 5.1 us, commit-to-submit
  p99 61 -> 42 us. About 95% of a burst's commits went to the awake thread. Scheduler thread CPU
  idle 0.0 ms/s before and after; in a burst 34 us per command buffer.
- Isolated commits (2 ms apart) still pass inline: passes_at_commit 1 per command buffer.
- Open: commit-to-submit inside a burst, p50 4.5 -> 5.6 us, p99 15-23 -> 29-37 us; the lane is
  splitting the burst's head from the rest to find the cause.
- clippy (plain at b8a81d328d, m3-max-37217; GPU and CPU-ICD cfgs at 675023517e, m3-max-37223),
  rustdoc (37223): 0.
- New tests: inbox linger unit test; device test of 48 back-to-back commits on 1 then 2 threads
  (handlers keep per-queue commit order, at least a quarter left to the awake thread); passing
  holds unit test (1000 holds, no making: 0 signals; 2000 raced rounds: every making goes on).
2026-11-16 10:44:41 -08:00
Anees Iqbal 11e7a30c94 Start stamp test: the batch's first work is checked by its span alone, not by a copy-in counter
What: a_command_buffer_s_gpu_span_holds_its_batch_s_first_work no longer asserts
WorkCounts::managed_bytes_copied_in >= FIRST on a device without unified memory. The leg
prints whether it made the Managed buffer's copy in instead, and the module doc names managed.rs
(the runtime's own Managed buffers) rather than managed_copy.rs (Managed no-copy buffers).

Why: that counter counts only copies into Managed buffers over the caller's pages
(Buffer::copy_in_from counts where caller_copy() is some); the test makes a Managed buffer of
the runtime's own, whose copy in nothing counts, so the assertion failed on every device with
two copies before the check the test exists for. On the RX 7900 XTX (RADV), m3-max-37158 ran the
leg before and after RUNTIME 2466: 0 bytes counted both times, failing at the counter, while its
times showed the fix: before, span 0.001 ms of 41.292 ms added (kernel end to GPU start 41.688
ms); after, span 41.023 ms of 40.884 ms added (kernel end to GPU start 0.127 ms). The span check
that remains fails before the fix and passes after it on those numbers.

Verified: the numbers above from m3-max-37158; the changed test's run follows on development.
2026-11-16 10:39:59 -08:00
Anees Iqbal 6386a12a6b Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 10:18:59 -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 4933e7cba9 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 10:17:02 -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 d3389d7cbb Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 10:04:35 -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 3f9cf43310 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 09:54:16 -08:00
Anees Iqbal 2921fb24da draw_costs: one thread run's answer is a named type
Clippy's type_complexity refused thread_run's return type and its callers' Vec of them (job
m3-max-37074, all three configurations). A ThreadRun alias names the tuple.

Verified: in the landing's check job.
2026-11-16 09:50:55 -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 be905fd899 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 09:33:15 -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 8167cc60de commit_and_submit: the order test drains its queue every 50th commit, as the checked one does
What: submission_handlers_keep_commit_order_across_commit_and_commit_and_submit now makes
every 50th commit a commit_and_submit that first waits for the commit before it to complete,
as checked_command_buffers_keep_commit_order_across_commit_and_commit_and_submit does.

Why: the test asserts some submission handlers ran on a committing thread. Each commit()
wakes the scheduler's thread, whose pass is often still under way at the other thread's next
commit_and_submit, which then makes no pass; and on a driver whose batches group, a committing
thread submits only where its VkQueue runs at most one earlier submission not seen complete,
which the two threads' backlog may never leave it. On the Radeon 780M (RADV) inside the touched
suites' run it failed: 0 of 1000 handlers on a committing thread, 1 pass at commit, 0 batches
(m3-max-36934, debug, 76 tests in parallel). Run alone in release it passed 10 of 10 with
12-17 of 1000 on a committing thread, with RUNTIME 2461's fix and without it alike
(m3-max-36983): the margin, not that fix. After a drain the scheduler's thread is idle and the
VkQueue runs nothing, so the commit_and_submit makes its pass and submits alone.

Verified: in the jobs named in the lane's report.
2026-11-16 09:28:07 -08:00
Anees Iqbal 2ccc3e9c38 Re-bless the golden hashes and the authored compile census at 9ae7edf748
What: SEMANTICS 2137 (ba311896eb, the undo of 2136) changes the SPIR-V of the rows 2136 changed
back: golden_hashes.tsv 6 rows (bless job m3-max-36987, inventory=0 golden=0) and
authored-compile.tsv 26 rows (census job m3-max-36988, census-exit=0), the same row counts the
re-bless after 2136 moved (0b674f2c1e).

Verified: both jobs on the M3 at 9ae7edf748, exit 0.
2026-11-16 09:24:12 -08:00
Anees Iqbal 9ae7edf748 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 09:18:48 -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 4f081c3490 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 09:07:16 -08:00
Anees Iqbal e6900ca020 Iris constant twin doc: state the per-encoder evidence, not one walk's totals
What: DriverWorkaround::PushReadsLengthenThreadPayload's doc (device/profile.rs) said a
storage twin of a kernel's uniform view took 145.8 to 150.2 s of GPU time over a walk of guest
compute workloads that took 137.4 s without it. It now gives the mean GPU time an encoder from
the runtime's encoder times in two walks without the twin against four with it. Comment only;
no code, version or answer changes.

Why: the 137.4 s total came from one walk (m3-max-35702, scratch 68e39640e9). The second walk
without twins, m3-max-36778 at c3d5b3e05e (8933378831 landed), took 146.0 s, inside the
twin walks' range. Its excess over the first sits in workload openings where the Iris
governor requested 300 to 1,200 MHz at 55 to 85% busy. Two walks of one sha (C0 and C02)
differ there as much. The totals do not separate the twin from the clock. Per encoder the
twin's effect is the same in both walks without it. 8933378831's message cites the totals
and one workload's 4.93 s as evidence. The message stays as it is, and this commit corrects
the record: that workload's difference was the first walk's opening, and the second walk
without twins took 6.42 s there. The twin's removal holds on the per-encoder figures below.

Evidence (mean ms an encoder; without twin: m3-max-35702, m3-max-36778; with: m3-max-35628
at bd3c1a8c37, walk T at 45d2a94af9, m3-max-36202 and walk C02 at 8d57656475; Mesa 26.2.6,
Iris Xe RPL-P; every window listed these rows, so the counts are whole):
- one workload's two heaviest convolution encoders, 200 each: 22.4 / 23.0 against 41.9,
  46.0, 28.1, 41.2; and 17.8 / 18.9 against 32.3, 32.8, 35.5, 32.5
- another workload's convolution encoder, 3,920: 6.27 / 6.30 against 6.79, 6.79, 6.77, 6.78
- a third workload's eight heaviest encoders, 439 to 480 each: six faster with the twin, e.g.
  3.67 / 3.74 against 2.86, 2.87, 2.84, 2.85, and 6.71 / 6.77 against 5.76, 5.75, 5.77, 5.77;
  one slower (4.82 / 4.92 against 5.56 to 5.63); one mixed
Read from each walk's qemu.log encoder-times lines (the walks' files on this Mac, read in
place).

Verified: cargo fmt --all only (comment change).
2026-11-16 09:06:19 -08:00
Anees Iqbal 24ccfe58db Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 08:49:42 -08:00
Anees Iqbal d6152c3247 RUNTIME 2461: Scheduler: a pass at commit asks whether a batch's host step is due, not whether it holds segments
What: scheduler::plain(), which decides what the pass of a committing thread
(commit_and_submit) and of a thread about to block may submit, left every batch that holds
segments to the scheduler's thread as a host step (LeftAtCommit::HostStep). It now asks the
command buffer whether a step is due (needs_host_step), as the thread's own look does
(holds_back, check_heads, gate_heads, place_of).

Why: BatchSync::segments is a gate alone: since a730cf1e96 it is also true for every batch one
of whose encoders kept its log for a rebind, which an encoder does whenever a command of it names
a no-copy buffer over host pages (replay.rs). A guest on a host of unified memory keeps all its
memory in place as such buffers, so on the Radeon 780M every one of the consumer's batches was
left to the scheduler's thread: its passes at commit ran (about 7.5k a window) and submitted
none, where on the RX 7900 XTX, whose guest resources lie in VRAM, they submitted about 4k a
window. An unshared head so left made the committing pass leave every other queue's batch on
its VkQueue too (first_for_the_thread). The thread's own pass submitted those batches with no
step, after a wake and a pass. A head whose step was recorded now goes from such a pass too.

How they meet the joined completions (RUNTIME 2459): the segments test comes first in plain(),
the group test after it. A batch of a command buffer marked to join the next, naming host
pages, now reaches that group test as any marked batch does: a committing thread sends it alone
where its VkQueue runs at most one earlier submission (goes_alone_at_commit) and leaves it to the
scheduler's thread to hold in the group otherwise; a waiting thread leaves it. No pass of a
thread other than the scheduler's runs while the group holds a batch, so none closes a group.

Docs: plain_ready's first condition; first_for_the_thread and unshared_hold.rs (Passes of other
threads) no longer name a recorded host step among what such a pass leaves.

Tests: commit_and_submit::a_command_buffer_naming_host_pages_is_submitted_at_its_commit, now in
a plain leg (a Private buffer) and a host-pages leg, 200 rounds each, printing the share at
commit and commit -> submission returned p50/p99; at the parent it failed on lavapipe with 40 of
40 left for a host step (m3-max-36852). queue_share_device's committing-pass test is renamed
a_committing_thread_s_pass_sends_an_unshared_head_with_its_step_recorded_first: under Exact the
committing pass now submits both command buffers, the unshared head first.

Verified: in the jobs named in the lane's report.

With it, the check and the bench legs (folded):

commit_and_submit: a command buffer naming host pages is submitted at its commit

What: a device test that fills a no-copy buffer over host pages with commit_and_submit, 40 rounds
on an idle device, and asserts every encoder kept its log for a rebind (replay_logs_kept, so each
batch holds segments), no host step was recorded, no pass at commit left a batch for a host step
(scheduler_at_commit_left_host_steps) and at least half the batches went at commit.

Why: scheduler::plain() leaves any batch that holds segments to the scheduler's thread as a host
step, though segments are a gate alone and an encoder that names a buffer over host pages holds
them with no step due. A guest's command buffers on a host of unified memory all name its memory
so, and the 780M's passes at commit submitted none of them.

Verified: run in the job named in the lane's report; it fails at this commit, before the fix.

completion_latency: a guest-shaped leg naming host pages, and why passes at commit left their command buffers

What: guest_shaped_completion_latency gains a HostPages leg: as Plain, each command buffer's blit
also fills 64 KiB of a no-copy buffer over host pages of its queue's own, as a guest's command
buffers name its memory over the guest's pages on a host of unified memory. Every leg now prints
a second line: the passes and batches at commit a frame, why those passes left their command
buffers to the scheduler's thread (WorkCounts::scheduler_at_commit_left_*), the host steps
recorded, the batches waiting threads submitted, the device's unified memory, its VkQueues, the
VkQueue each queue is on and which of them hold other queues' work back for the unshared
compositor.

Why: on the 780M a consumer's guest commits every command buffer with commit_and_submit, its
passes at commit run, and they submit nothing, where on the RX 7900 XTX they submit about 4k
batches a window. This leg puts the 780M guest's memory shape beside the plain one on the same
device, so one run on each GPU shows which condition leaves the batches.

Verified: built and run in the jobs named in the lane's report (a measurement, ignored by
default).

completion_latency: the guest-shaped bench times each commit call to its submission's return

What: each leg's at-commit line now opens with the time from each command buffer's
commit_and_submit call to the return of the driver's submission of its batch (p50, p99, max,
whichever thread submitted it), and counts the encoders' logs kept for a rebind a frame.

Why: the fix for batches over host pages left at commit is judged by that time on the 780M,
before and after, beside the share of batches submitted at commit.

Verified: in the build and bench jobs named in the lane's report.

Verified: m3-max-36888 (msi) at 3fbf10d3e1: clippy -p metal2vulkan-runtime --all-targets --all-features 0; lavapipe scheduler|commit_and_submit|queue_share_device|joined_completions|grouped_submissions 84/84. At the parent (m3-max-36852) 40 commit_and_submit fills of a no-copy buffer gave 0 batches at commit, all left for a host step with none recorded; at the fix 200/200 at commit (commit to submission returned p50 97.9 us, p99 104.1). The PHOENIX before/after, clippy --cfg m2v_gpu and m2v_cpu_icd and rustdoc run after the merge.
2026-11-16 08:48:53 -08:00
Anees Iqbal 3bc091f20a Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 08:41:11 -08:00
Anees Iqbal c9bad0206e Joined completions: the order test off its own queue; a private doc link to a test-only constant
Fix forward of RUNTIME 2459 (3de483d86f), and of the runtime private-doc pass red since RUNTIME 2437/2441.

Joined completions lane: the order test's first work on a queue of its own

an_unmarked_command_buffer_is_seen_complete_at_its_own_end failed once in
a release lavapipe run (debug runs passed): grouped 0 and 3 kernel
submissions where the device groups, so M went alone and U closed no
group. The first command buffer, which does the buffers' first work, filled
the 64 MiB buffer on the test's own queue. A queue's expected run is raised
at once by a longer command buffer (command_buffer/group.rs, "Bounded by its
expected run"), and a batch whose queue's expected run is past GROUP_RUN
(16 ms) goes alone (batches_alone_run_long). On a loaded host lavapipe's
64 MiB fill can take longer than that. The first work now runs on a second
command queue of the same device, so the test queue's expected run is the
warm-up's short fills'.

The lane's report also counts batches_alone_run_long, so a run that goes
alone for its expected run says so.

Verified: the release lavapipe run follows on this commit.

contexts: device_limit's doc names TEST_LIMIT without a link

TEST_LIMIT exists only in device test builds, so the private-items
Rustdoc pass (CI's "Private intra-doc links", ceiling 0 for the runtime)
found an unresolved link at contexts/mod.rs:102:
`cargo doc -p metal2vulkan-runtime --all-features --no-deps
--document-private-items` under RUSTDOCFLAGS=-Dwarnings exited 101 in msi job
m3-max-36795. The doc now names it as code.

Joined completions lane: the order test requires M not alone for its queue's expected run

The run-past-bound count the lane's report gained was read only by Debug,
which dead-code analysis ignores: clippy under --cfg m2v_gpu and
--cfg m2v_cpu_icd failed on 'field `long` is never read' (msi job
m3-max-36836; plain clippy, runtime-alone clippy, Rustdoc and the private-doc
pass of all six crates passed there). The order test now asserts it is 0
where the device groups: a batch alone for its queue's expected run is the
precondition the test's first work moved to a queue of its own, and the
assertion names it if it fails again.

Verified: m3-max-36867 at 9dd95c628d clippy plain, --cfg m2v_gpu, --cfg m2v_cpu_icd 0, joined_completions on lavapipe 5/5; m3-max-36836 at fa3b876cb5 rustdoc 0 and the private-doc pass 0 for all six crates; m3-max-36835 (release, lavapipe) joined_completions 5/5 with the counters moving (marked: 7 batches in 2 submissions; unmarked: 7 submissions; order test grouped 1, long 0).
2026-11-16 08:40:23 -08:00
Anees Iqbal 5dcb87e2e2 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 08:38:37 -08:00
Anees Iqbal 8bed9e05e4 RUNTIME 2460: A completed command buffer lets go of its kept footprints and its parts' sparse updates
Footprints: a completed command buffer lets go of its batches' kept footprints

A batch's kept footprint (CommandBufferShared::footprints) holds a probe of
each of its segments (SegmentProbe), and each probe holds a clone of the
segment's work (Deferred) and of a Rerecord step input. The command buffer
moves every segment's work into what it retained at its batch's submission
(State::place) or at its completion (State::unplaced) and lets go of that as it
completes, but the kept footprints stayed until the CommandBuffer was dropped.
So a program that keeps a completed command buffer, as Metal programs keep a
completed MTLCommandBuffer to read its status, error and GPU times, kept the
work of every segment whose batch's footprint the scheduler had kept: a staged
scatter's (its staging region of the arena and the RAM's use), a splice's
(its arena regions and its merges' scratch), an execution's, a render pass's
and a loop's check's among them. Nothing asks for a footprint once the command
buffer completed: the scheduler asks only of the batches it holds.

The release lets go of them now (Footprints::let_go), after its completed
handlers and before what it retained, each popped under the leaf lock and
dropped without it, as retained is.

Verified: the device test
tests::host_ram_copy_device::a_kept_completed_command_buffer_holds_nothing_of_its_staged_scatter
failed without this on lavapipe (msi job m3-max-36825: alive after its
completion 2, kept footprints' probes 1, after its drop 0; a staging of 163840
bytes). It now also asserts no kept probe after the completion; the run with
this change is reported with the tip.

Sparse updates: a completed command buffer lets go of its resource state encoders' updates

A resource state encoder's part keeps its updates (SparseUpdate: the textures
a mapping or a move names, and an indirect update's buffer) after its batch's
submission bound them: that submission clones them for the bind, and the
part held them until the CommandBuffer was dropped, so a program that keeps a
completed command buffer kept those textures and that buffer, where Metal lets
go of what a command buffer used as it completes. Nothing reads a part's
updates after its batch's submission (the steps, the footprint, the fold and
storage-form checks and an encoding again all come before it).

The release takes them out of the parts under the state's lock and drops them
without it, after the completed handlers, beside the kept footprints.

Verified: see the tip report (the device test
tests::kept_sparse_updates::a_kept_completed_command_buffer_holds_no_texture_its_mapping_update_names
run at the commit before this one and at this one).

Runtime tests: a kept completed command buffer's staged scatter, measured

A device test of the case: a program keeps a completed command buffer (as a
Metal program keeps a completed MTLCommandBuffer to read its status, error and
GPU times) whose blit encoder staged a scatter into a guest RAM through the CPU
(host_ram/copy.rs's StagedScatter: its staging region of the arena, as long as
the copy's bytes, and the RAM's use). It holds a weak reference to each
segment's work, taken before the commit (CommandBuffer::segment_works, a device
test's view, through Deferred::weak), and asserts none is alive once the
command buffer completed, while the program still holds it; it prints how many
are, how many segments the batches' kept footprints probe
(CommandBuffer::kept_footprint_probes), and how many are alive once it is
dropped.

Verified: not yet run; this commit is the measurement.

Runtime tests: name the work's type in Deferred::weak's downgrade

Verified: the measurement job m3-max-36816 failed to compile without it (E0308).

Runtime tests: a kept completed command buffer's mapping update, measured

A device test of a resource state encoder's update: a mapping of every tile of
a sparse texture the program let go of once it encoded the mapping, its
command buffer kept after it completed. It asserts the texture's handles'
retain is gone once the command buffer completed, while the program still
holds it, and prints the retain's and the texture object's holds after the
completion and after the drop.

Verified: not run at this commit alone; the job that runs it here and with the
fix after it is reported with that fix.

Verified: m3-max-36850 (msi, lavapipe) at 006565aff9: clippy --cfg m2v_cpu_icd 0; the scatter test (alive after completion 0, kept probes 0) and the sparse test ((0, 0) after completion) pass; footprint families 177/177; the sparse control at 02b1234c4d fails ((1, 1) after completion); the scatter control m3-max-36825 fails (alive 2, probes 1). Clippy plain and --cfg m2v_gpu and rustdoc run after the merge.
2026-11-16 08:37:37 -08:00
Anees Iqbal 0b674f2c1e Re-bless the golden hashes and the authored compile census at 884da5680a
SEMANTICS 2136 (a552a55d1f) views a kernel's loop-uniform read-only slot as a uniform view on
the Iris profile: golden_hashes.tsv 6 rows, authored-compile.tsv 26 rows. The engine inventory
and the air_input printouts did not change.

Verified: bless m3-max-36806 (inventory 0, golden 0, printouts 0) and census m3-max-36807
(census-exit 0) on the M3 at 884da5680a.
2026-11-16 08:25:27 -08:00
Anees Iqbal 884da5680a Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 08:18:59 -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 03e5c2fd24 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 08:17:16 -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 47dd49ebe4 dispatch_chain: describe the textured form as a guest's compute encoders, naming no benchmark
A comment wording only.
2026-11-16 08:01:46 -08:00
Anees Iqbal c3d5b3e05e Re-bless the golden hashes and the authored compile census at 19f8fb7588
SEMANTICS 2135 (8933378831) removed the Iris storage twins, so the Iris profile's cells
moved: golden_hashes.tsv 347 rows, authored-compile.tsv 991 rows. The engine inventory and
the air_input printouts did not change.

Verified: bless m3-max-36720 (inventory 0, golden 0, printouts 0) and census m3-max-36721
(census-exit 0) on the M3 at 19f8fb7588.
2026-11-16 07:57:19 -08:00
Anees Iqbal 19f8fb7588 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 07:52:25 -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 aa95a93e00 Predicated loops: the loop rebind test asks the announcements with contains
Clippy's manual_contains (-D warnings, --cfg m2v_gpu, job m3-max-36629) refused
the iter().any() over the heard degradations in
tests/rebind_loop_check.rs; it reads them with Vec::contains instead.

Fix forward of RUNTIME 2457 (83b3b67f30, test only).
2026-11-16 07:25:54 -08:00
Anees Iqbal be50ccef9c Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 07:25:00 -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 bdba2e7858 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 07:10:35 -08:00
Anees Iqbal 74b2b04859 RUNTIME 2456: Bind inside a releasable import before keeping it for good
bind_in_import took the outer import with `pages(ReadApart::Inside)` before
any of its checks: that call keeps a releasable import imported for good.
Every refusal after it (a dedicated dma-buf, the window outside the
placement, the alignment, the memory types, a failed vkBindBufferMemory)
then returned None, the buffer became a copy, and the outer import stayed
held for good with nothing bound in it: never released while idle again.

Now the checks and the bind read the import through the blit's
non-pinning hold (`blit_pages`, imported again where released, which the
release sweep skips while it is held), and `expose(ReadApart::Inside)`
runs only once vkBindBufferMemory succeeded. A released import the device
cannot import again is now a refused bind (a copy) rather than a lost
device, since no work reads the stand-in there.

The test `a_bind_refused_inside_a_pointer_import_leaves_it_releasable`
refuses a bind inside a live pointer import through a test hook
(`refuse_binds_in_imports`, compiled only into the Linux device tests) and
checks the outer import is not counted as read apart inside, not kept for
good, and released; then binds a second buffer inside it and checks it is
kept for good. At development's bind_in_import the first check fails: the
import is held for good and never released.

Verified: m3-max-36585 (msi, lavapipe) at 940903c12e: pointer_residency|one_import|host_import_counts|dma_buf_beside|lone_fetch|host_residency 46/46; the new test alone passes (released after the refused bind, kept for good after the bind); clippy --all-targets --all-features -D warnings 0. The control at development's bind_in_import, clippy --cfg m2v_gpu and m2v_cpu_icd and rustdoc run after the merge.
2026-11-16 07:09:50 -08:00
Anees Iqbal 83f6c5ed10 The what and why of RUNTIME 2455 (9afd9699e1), whose folded message lost them
RUNTIME 2455 folded two commits whose messages did not reach it. They follow verbatim. No change to any file.

--- 9f9a9a2019 Begin ahead: a settled pool's primaries begun on a device thread, one an encoder

A command buffer that gives its first pool back settled posts the pool to
a new device thread (begin_ahead.rs) once its completed handlers ran, and
the completing thread begins none itself. The thread begins as many of the
pool's primaries as encoders of that command buffer opened their own in it,
one at least and spares::AHEAD = 8 at most (a dealt frame's chunks opened
5.6 encoders' own on average on ANV), one at a time: the pool out of the
spares under their lock only while one begins, kept again between begins,
so a taker never waits for a begin and one between two begins takes the
pool with those begun so far. Every encoder that opens its own primary
takes one begun while the pool holds any; before, only a command buffer's
first encoder did, and only where no thread waited for the command buffer
that gave the pool back.

Why off the completion path too: each begin was 8 to 20 us on ANV
(spares.rs), spent by the completing handler thread while the queue's
context was held, for every settled command buffer no thread waited for.
The completion now only posts (one lock, one push, one wake). The cost is
a race: a command buffer that takes the pool before the thread made its
begins finds fewer. Counted: WorkCounts::encoder_primaries_begun_ahead_missed,
the encoders among as many as the pool's begin ahead owed that found none
(the pool taken first, or out of the spares as the thread came to it);
each began its own as before. A pool is due its begins from the give-back
until the thread made them (CommandPool::due), and owes as many as the
pool's last command buffer opened (CommandPool::owed) to its next taker.

The thread: one a device, started by the first post, at the user-interactive
class as the handler threads that began these before; at most 64 pools
wait, one posted twice waits once; holds the spares' pools, the device's
functions, loader word and counts (spares::BeginTargets), never the device;
each begin in a section of the exit guard; stopped and joined by the
teardown after the handler contexts stop, before the spares are released.
The command buffer allocation the begin may make goes through the same
helper as the device's (device::allocate_command_buffers), counted alike.
CommandPool::begun is a Vec; take_begun is open_encoder, which also counts
the encoder for the pool's next begin ahead. The gate's waiter count
(Gate::awaited) had no user left and is deleted, with its test.

Tests:
- tests::begin_ahead::each_render_encoder_after_a_settled_command_buffer_
  opens_from_a_primary_begun_ahead: a command buffer of 5 render encoders
  on a new pool, then the next takes that pool, the only spare: each of its
  5 render encoders opens from a primary begun ahead
  (encoder_primaries_begun_ahead 5), none missed, same pixels.
- tests::begin_ahead::a_waiter_returns_before_the_begins_and_a_taker_before_
  them_counts_its_encoders_missed: the thread held (test hook) at its
  begins, the command buffer's wait returns with no primary begun; the next
  command buffer takes the pool first and counts 5 missed; released, the
  third opens all 5 from primaries begun ahead.
- spares unit tests for several begun primaries, the AHEAD cap, the misses,
  and a pool that may begin no more being due no more.
- Tests that read the spares or the begin counts after a wait settle the
  thread first (BeginAhead::settle, test only); draw_again's begun-alike
  test holds the thread from the start rather than waiting for a run that
  begins its own, and its begun-meanwhile test holds it until the event's
  command buffer took a pool, so that pool is due a begin; the bound test
  holds it so the begins are its own.

Verified so far (scratch commits of the same tree, msi lavapipe): the touched
suites begin_ahead|spares|draw_again 64/64 and clippy --cfg m2v_cpu_icd 0
(m3-max-36530); the tip's own runs follow.

--- 5774363889 Spares test: a pool past a command buffer's first holds its primaries begun ahead beside POOL_HOLDS

A spare that holds primaries begun ahead and serves a command buffer past
its first pool keeps them begun (only a command buffer's first pool's
encoders take them), and the command buffer grows its made primaries to
POOL_HOLDS beside them: lavapipe (msi, m3-max-36541) saw a spare of 35, 32
primaries, a secondary and two begun ahead, past the fewest test's bound of
POOL_HOLDS + 2. The bound is POOL_HOLDS + AHEAD + 1 now, and the spares
module docs say where the begun ones sit.

Verified: the rest of that job's 243 touched tests passed; this test's
run follows.
2026-11-16 06:54:07 -08:00
Anees Iqbal bdd4710e92 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 06:53:45 -08:00
Anees Iqbal 9afd9699e1 RUNTIME 2455: Spares: primaries are begun ahead on a device thread, one for each encoder the pool last served, eight at most
Verified: m3-max-36547 at 5774363889, lavapipe begin_ahead|spares|draw_again|pending_audit 72/72, clippy (host, m2v_cpu_icd) 0; m3-max-36546 clippy --cfg m2v_gpu 0; m3-max-36541 at 9f9a9a2019 rustdoc 0; negative control m3-max-36540 (AHEAD = 1) fails both new tests (taken 1 against 5; missed 1 against 5). PHOENIX (m3-max-36549) runs after the merge.
2026-11-16 06:53:04 -08:00
Anees Iqbal 566dc02f9d Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 06:19:14 -08:00
Anees Iqbal 32285d7988 RUNTIME 2454: Carries: a queue holds sixteen, a frame's dozen side by side each open warm
A program that encodes each frame as about a dozen command buffers side by
side (measured: 11 to 12 a frame) opens each of the next frame's against the
carries of this frame's commits. A queue held four (queue::CARRIES), so
over a third of them opened with no carry (measured: 333 a second of 883
command-buffer parts), and each one's first draws took every step. Sixteen
hold a frame's with room.

Memory held per queue at sixteen, measured on lavapipe (msi, job
m3-max-36477, a throwaway test that dropped the carries a queue held and
counted the heap bytes freed with a counting allocator): 33,952 bytes a
carry whose encoders drew once, 34,384 a carry of 100-draw encoders, the
same in each of four rounds; 16 carries 543,232 to 550,144 bytes (about
0.53 MiB) a queue, against about 0.13 MiB at four. size_of: Carried 920,
LiveBind 21,072, BindState 632. A carry's live bind goes back to the
device's live binds as it is let go. Scope: the test's one-state draws;
a program's carries with more slots bound hold larger tables (unmeasured).

Test: tests::carried_draws::a_dozen_command_buffers_encoded_side_by_side_
each_open_from_a_carry_their_queue_holds, two groups of twelve: each of the
second group opens from a carry (kept_draws_carried_across 12), none let go
at a commit, only the first group's draws take every step, the pixels those
of the same passes on queues of their own. side_by_side_frame takes the
group size; the existing callers pass 2.

Verified: lavapipe (msi) carried_draws 16/16 at the scratch commit with the
same tree plus the measurement (m3-max-36477); the negative control and the
tip's own runs follow.

Verified: m3-max-36493 at 3c8f52ce23, lavapipe carried_draws|spares|draw_again 76/76, clippy (host, m2v_cpu_icd) 0, rustdoc 0; m3-max-36494 clippy --cfg m2v_gpu 0; negative control m3-max-36492 (CARRIES = 4) fails the new test (across 4 against 12). PHOENIX runs after the merge.
2026-11-16 06:18:31 -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 5ecdb6a1ac Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 05:56:42 -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 3ce1d01744 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 05:55:16 -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
Anees Iqbal 286d25bded Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 05:44:55 -08:00
Anees Iqbal 439b3b7280 RUNTIME 2452: Sparse scrubs: a rebind encodes the encoder of a scrub again
A blit or a render pass that writes a sparse texture leaves a scrub of the
unmapped tiles it wrote, recorded at its batch's submission
(Deferred::SparseScrub). Deferred::resolved_at_its_calls answered false for
it, so the commit's steps_hold kept the pages of every buffer over host pages
the command buffer used until completion, and a rebind of one before the first
submission was refused with Invalid(Rebind(EncodedUses)). Had it not been,
the encoder kept no log (Unlogged::Segments), and the submission would have
failed EncodedUseRebound.

The scrub zeroes tiles of its texture alone, as its batch mapped them, and
reads no buffer. So it is now resolved at its calls, and left again by an
encoding again: the blit or pass encoded again leaves its own scrub over the
same texture, and the first's goes unrun (finish_replay prepares it;
splice_replay retains the first's). Unlogged::Segments now names only a
GPU-written indirect dispatch's host step. The docs of records_again,
finish_replay and splice_replay name the scrub.

The test is tests/rebind_sparse_scrub.rs. The texture's left tiles are mapped,
then a blit writes the whole texture and fills a no-copy buffer behind a
shared-event gate. The buffer is rebound before the signal, and the test
asserts:
- the command buffer completed with no error;
- one encoder was encoded again;
- the fill reached the new pages and not the old;
- the mapped tiles hold the blit's texels.
The control (this commit's deferred.rs reverted) fails at the rebind with
Invalid(Rebind(EncodedUses)).

Degradation kinds added or removed: none.

Verified: m3-max-36396 at 8f4ce875f5 (same tree), clippy -D warnings of the runtime (all targets and features) 0 and rustdoc -D warnings 0. The cfg clippy, the control, the rebind tests, the suites on lavapipe and the sparse conformance replay run after the merge.
2026-11-16 05:44:09 -08:00
Anees Iqbal 56c04b2f41 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 05:36:09 -08:00
Anees Iqbal f27f432487 RUNTIME 2451: Shadows: a gated copy in copies from the truth's buffer as its call found it
RUNTIME 2450's test,
dirty_pages_device::a_rebind_before_the_first_submission_encodes_a_gated_copy_in_s_encoder_again,
failed on lavapipe at RUNTIME 2450 and at the tree before it alike
(m3-max-36334): rebind_bytes_no_copy answered
Invalid(Rebind(EncodedUses)), not EncodedUseRebound. A shadow's copy in
left to its batch's submission (Deferred::GatedCopyIn) read the truth's
VkBuffer as its record ran there (ShadowBuffer::Rebound), so it was work
whose step resolves what it records then
(Deferred::resolved_at_its_calls false): its commit held the pages of
every buffer over host pages the command buffer used until it completed
(steps_hold), and a rebind of one meanwhile was refused at the call, as
for a command buffer not yet committed, where Metal's replace is not.
The rebind never reached the encoding again, so RUNTIME 2450's
predicate (Deferred::left_again_by_an_encoding_again for GatedCopyIn)
was inert on that path; the test's control at development's files fails
on the same refusal.

Now a GatedCopyIn captures, at its encoder's call, the VkBuffer of a
truth a rebind may move (GatedCopyIn::from: bytes of a buffer over host
pages, the only such truth a gated copy in reads, a log's; a standing
one's truth only the runtime's commands write), and its record at the
submission copies from it (ShadowCopy::record_gated and record_moves
take it beside the gate; every other caller passes none and reads the
buffer as it is). Its recording then reads nothing of a buffer resolved
later, and Deferred::resolved_at_its_calls answers true for it: the
command buffer lets those pages go at the commit (held weakly until its
first submission), a rebind before that submission is not refused but
encodes the encoder again, whose own gated copy in captures the new
buffer and takes the first's place (RUNTIME 2450), and a rebind after it
leaves the old pages to the command buffer until it completes. A first
gated copy in whose encoder a rebind could not encode again is let go of
with its encoder's failing segments (State::fail_part, before
record_scrubs), so no captured buffer is recorded after its pages went.

Docs: shadow.rs (GatedCopyIn, record_gated), deferred.rs
(resolved_at_its_calls), and attached_read_faces' busy lane, which said
a rebind there is refused.

Verified: cargo fmt only; the job reported with this tip runs RUNTIME
2450's test (which this fix-forward makes pass) and its control.

Degradation kinds added or removed: none.

Verified: m3-max-36366 at fc0e1aee30 (same tree), clippy -D warnings (runtime; m2v_gpu; m2v_cpu_icd runtime+validation) 0 and rustdoc -D warnings 0. The control, RUNTIME 2450s test, the rebind tests and the touched suites on lavapipe run after the merge.
2026-11-16 05:35:25 -08:00
Anees Iqbal 2687d19eb6 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 05:24:00 -08:00
Anees Iqbal 5410cd5cf4 RUNTIME 2450: Shadows: a rebind encodes the encoder of a gated copy in again
An encoder that left a shadow's copy in to its batch's submission
(Deferred::GatedCopyIn: over host pages a consumer logs, the regions its
log decides; or a command buffer's first copy in of a shadow that may
stand across command buffers) kept no log (Unlogged::Segments): no
Segment::records_again test held for it. A rebind, before the command
buffer's first submission, of a buffer over host pages that encoder used
then failed the command buffer with EncodedUseRebound, where Metal
resolves the use at the submission. Keeping the log alone would not do:
the encoding again redoes the copy in for itself (a gate of the log
taken again, a standing decided at the submission, ended_encoders_wrote
answering false while replaying) and leaves a GatedCopyIn of its own, or
records the copy in in place, but finish_replay asked every other
segment to record on the GPU alone, which a gated copy in does not, and
refused the encoding again.

Now Deferred::left_again_by_an_encoding_again answers for GatedCopyIn
too: the encoder keeps its log, its place takes the encoding again
(splice_fits), finish_replay prepares the encoding again's segment as the
commit prepares one (no recording, StepInputs::None), and the batch's
submission records it (submit.rs's record_scrubs, which takes every
unrecorded such segment). The first's goes unrun, retained. A gated copy
in made by the encoding again holds a gate of the log made after the
commit's decisions (DirtyShadows::committed), whose decision is none, so
it copies every region (CopyInGate::regions): a superset of the rows the
log reports changed, read at the submission, after every CPU write before
the commit; the shadow's hold was advanced to the commit's stamp by the
first gate's decision, and its image then holds at least that. Its cost,
one whole copy in, falls only on a rebind of such an encoder. A standing
gate is decided at the submission (stands), as the first's would be. GPU
parts are unchanged: a gated copy in starts none.

Unlogged::Segments now names a GPU-written indirect dispatch's host step
and a scrub. Docs: deferred.rs, rebound_use.rs, encoder.rs, reencode.rs,
shadow.rs (GatedCopyIn).

Test: dirty_pages_device's
a_rebind_before_the_first_submission_encodes_a_gated_copy_in_s_encoder_again:
a kernel inverts a shadowed RGBA8 texture over a logged no-copy buffer
into a plain texture, behind a shared event only the host signals; the
buffer is detached and rebound over other pages, logged by the same log,
before the signal. Asserts the command buffer completes with no error,
the rebind encoded the encoder once, one gated copy in ran (the encoding
again's) and copied every row (dirty_copies_in_gated +1,
dirty_copies_in_whole +1), and the kernel read the new pages' texels. At
development's files it is expected to fail on the error
(EncodedUseRebound).

Degradation kinds added or removed: none.

Verified: m3-max-36334 at a7b5d28822 (same tree), clippy -D warnings of the runtime (all targets and features) 0. Rustdoc, the cfg clippy, both controls, the rebind tests and the touched suites run after the merge.
2026-11-16 05:23:18 -08:00
Anees Iqbal 3858812d69 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 05:14:52 -08:00
Anees Iqbal dcac15a5c6 RUNTIME 2449: Host RAM: a rebind encodes the encoder of a gather staged past the imports again
An encoder that left a gather from a guest RAM staged through the CPU
kept no log (Unlogged::Segments) where an encoding again could not copy
the gather through the imports in its place: over a chunk that takes no
import while it runs (Staging::cpu_only: a chunk the device refuses, or
one an object's own import of its pages holds back), or in a part of its
own after the GPU completed the work before it (Staging::after_the_gpu:
a copy into those chunks was recorded, or a buffer over host pages lies
over the bytes), which a copy through the imports would not start. A
rebind, before the command buffer's first submission, of a buffer over
host pages that encoder used then failed the command buffer with
EncodedUseRebound, where Metal runs it over the new pages.

Now such a gather is staged again as its first encoding staged it, as
RUNTIME 2448 does for a staged scatter: HostRamCall::staged_again answers
the first encoding's Staging for a gather that is not
Staging::through_imports (StagedGather::encoded_again_through_imports),
and Deferred::left_again_by_an_encoding_again answers for such a
GatherStage, so the encoder keeps its log, its place takes the encoding
again, and finish_replay leaves the step for its host step. Every other
staged gather is copied through the imports by an encoding again, as
before (Deferred::recorded_by_an_encoding_again).

Unlogged::Segments now names a GPU-written indirect dispatch's host
step, a scrub, and a shadow's copy in left to its batch's submission
(shadow::GatedCopyIn, which no Segment::records_again test holds
either; the doc did not name it). Docs: host_ram/copy.rs (First touch,
the gather; Staging; StagedGather), deferred.rs, encoder.rs,
reencode.rs, rebound_use.rs, and docs/HOWTO.md's two sentences on a
gather's rebind.

Test: host_ram_copy_device's
a_rebind_before_the_first_submission_encodes_a_gather_staged_after_the_gpu_again,
on the shape of a_first_gather_over_chunks_a_scatter_wrote_waits_for_no_import
(each chunk import held in flight 300 ms by making_pause): one encoder
scatters into scattered pages, gathers them back (staged after the GPU,
the scatter having written the chunks) and fills a no-copy buffer,
behind a shared event; the buffer is detached and rebound before the
signal. Asserts the command buffer completes with no error, the first
encoding staged both copies, the rebind encoded the encoder once and
staged both again, the fill is in the new pages alone, the RAM's runs
hold the scatter's bytes, and the gather's buffer holds them too. At
RUNTIME 2448's files it is expected to fail on the error
(EncodedUseRebound): the gather's step keeps the encoder from keeping
its log.

Degradation kinds added or removed: none.

Verified: m3-max-36303 at 75b7873bc2 (same tree), clippy -D warnings of the runtime (all targets and features) 0 and rustdoc -D warnings 0. The cfg clippy, the lavapipe control at the old files, the staged rebind tests and the touched suites run after the merge.
2026-11-16 05:14:10 -08:00
Anees Iqbal eb57e734d7 submission_turns: the hand-off checks wait for no completion until every command buffer was submitted
a_pass_s_submission_handlers_run_while_it_goes_on_grouped failed once on lavapipe at 7399e1ebfc
(job m3-max-36231, msi under three builds' load): the earlier command buffer's submission
handler started 200.3 ms after the pause after the later one's submission ended. That is one
whole extra pause: the later command buffer was submitted first and the earlier one after it,
its handler handed off only after its own submission's pause.

The checks release the scheduler's thread and then wait for each command buffer's completion
at once. A thread about to block passes for itself where no pass is under way
(Scheduler::submit_before_waiting), and its pass submits only command buffers with no
submission handler, each behind no earlier commit it overlaps: one that came between the
scheduler thread's passes took both commits in, submitted the later one (no handler, another
queue, another target) and left the earlier one, whose handler it may not run, to the thread's
next pass. Nothing of the runtime's early wake is on this path: these checks commit with
`commit`, and only `commit_and_submit`'s pass wakes the thread early.

Both FirstWork checks now poll, without a wait for completion, until the scheduler's thread
submitted every command buffer (CommandBuffer::submit_returned_time), then wait. The hand-off
check also asserts the submission order (earlier before later) and prints both submissions'
returns after the held one's, so a failure names which order it saw.

Verified: to be run on lavapipe (submission_turns) and in the next PHOENIX suite.
2026-11-16 05:12:07 -08:00
Anees Iqbal 6300970312 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 05:07:33 -08:00
Anees Iqbal ce22739364 RUNTIME 2448: Host RAM: a rebind encodes a staged scatter's encoder again, staging it again
An encoder that left a scatter into a guest RAM staged through the CPU
(Deferred::ScatterStage and ScatterDrain, host_ram/copy.rs) kept no log
(Unlogged::Segments): no Segment::records_again test held for those
steps. A rebind, before the command buffer's first submission, of a
buffer over host pages that encoder used then failed the command buffer
with EncodedUseRebound, where Metal resolves the use at the submission
and runs it over the new pages. Keeping the log alone would not do: an
encoding again took no chunk (takes() is empty there, and so is the
kept plan's) and copied the scatter through the imports, which starts
no part, while the staged scatter's CPU copy goes in a part of its own;
splice_fits refuses an encoding again with fewer parts. And a scatter
staged because a chunk takes no import while it runs (CopyTake::CpuOnly)
cannot go through the imports at all.

Now the call records how its first encoding staged it
(HostRamCall::staged, set where the staging is decided), and an encoding
again stages a scatter so marked again (HostRamCall::staged_again): no
kept plan, no imports, record_staged_scatter from where the buffer lies
then, its two steps and its part as the first's. It is the first
encoding's own decision made again. Deferred::left_again_by_an_encoding_again
answers for ScatterStage and ScatterDrain too, so such an encoder keeps
its log (Segment::records_again), its place takes the encoding again
(reencode.rs's splice_fits), and finish_replay leaves the two steps for
their host steps as the commit left the first's. The first encoding's
steps are retained unrun, as a replaced splice's are; the stage takes its
arena region only at its step, so the unrun one takes none. Every other
copy in an encoding again goes through the imports as before.

Unlogged::Segments now names a GPU-written indirect dispatch's host
step, a staged gather over a chunk that takes no import or in a part of
its own, and a scrub. Docs: host_ram/copy.rs (First touch, the scatter;
takes), deferred.rs, encoder.rs, reencode.rs, rebound_use.rs, and
docs/HOWTO.md's sentence that such a rebind failed EncodedUseRebound.

Test: host_ram_copy_device's
a_rebind_before_the_first_submission_encodes_a_staged_scatter_s_encoder_again,
on the shape of the staged gather's: a blit encoder scatters into
scattered pages (a page named twice) and fills a no-copy buffer, behind
a shared event; the buffer is detached and rebound before the signal.
Asserts the command buffer completes with no error, the first encoding
staged the scatter, the rebind encoded the encoder once and staged the
scatter again, the fill is in the new pages alone, the RAM's runs hold
the scatter's bytes (the later's for the page named twice), and the page
beside them is unchanged. At development's files it fails on the error
(EncodedUseRebound).

Degradation kinds added or removed: none (EncodedUseRebound stays, for
fewer encoders).

Verified: m3-max-36269 at ebf9c7563f, clippy -D warnings of the runtime (all targets and features) 0. Rustdoc, the cfg clippy, the lavapipe control at the old files, the new test and the touched suites run after the merge.
2026-11-16 05:06:43 -08:00
Anees Iqbal 56d06bc71d Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 04:58:41 -08:00
Anees Iqbal 865e824a97 RUNTIME 2447: Carried draws: a queue holds the carries of its latest four commits; draws_none_kept_uncarried
What: a command queue's place held one carry (render/carried.rs), the
kept draws of its latest command buffer's last render encoder, and each
commit that carried replaced it, letting the one before go untaken. It
now holds up to four (queue::CARRIES), the latest first; a render
encoder that holds no carry of its own takes the latest that fits its
pass (carried_fits, checked at the opening as before), and one that does
not fit stays held for another. With four held, the commit that hands a
fifth lets the one held longest go (kept_draws_carry_dropped_commit). A
new count, WorkCounts::draws_none_kept_uncarried, splits draws_none_kept:
those of encoders that opened from no carry.

Why: a consumer deals each of its compositor's command buffers (about 63
render encoders) into about 11 command buffers of one queue, encoded side
by side and committed in order. Each one's first render encoder opens
before the ones just before it commit, so the one carry its queue held
reached at most the first opener after a commit, and the next commit
replaced it (374/s let go untaken, 378/s taken, in a profiled 26.7.2
walk on the Iris). The others opened cold: draws_none_kept ran at 4.6 to
5.0 per such command buffer on three 26.7.2 walks, each about 128 us of
host CPU against about 14 us rebound, 27% of the walking threads'
samples. A carry names the program's objects by key and handle alone
(index buffers, vertex buffers and bind state values as ResourceKey and
raw handles, pipeline states and interfaces weakly); what it holds
strongly is the runtime's own (settles' variants and plans, VkPipelines,
draw settings), so a queue holding four keeps no program buffer or
texture alive.

Test: tests::carried_draws::
command_buffers_encoded_side_by_side_each_open_from_a_carry_their_queue_holds
(two command buffers encoded, then committed; two more encoded: both
open from a carry, none let go at a commit, only the first two draws
counted uncarried, pixels as on queues of their own) and
a_carry_held_beside_another_keeps_no_released_buffer_alive (a host
page's no-copy index buffer the first one draws, released once the
first two committed, is freed, its deallocator run, while its carry sits
held beside the second's; the fourth pass then opens from it and draws
another buffer's indices).

Verified: m3-max-36241 at bdafc3ba84, clippy -D warnings (runtime and translator, all targets and features) 0 and rustdoc -D warnings 0. Lavapipe touched suites (36242), the CARRIES = 1 negative control (36243) and clippy under m2v_gpu/m2v_cpu_icd run after the merge.
2026-11-16 04:57:55 -08:00
Anees Iqbal e76cb0e374 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 04:53:31 -08:00
Anees Iqbal d3a79a68db Early wake: a committing pass's own submission handlers wait for no later submission, which may go first
With the early wake (RUNTIME 2445) the scheduler's thread is woken before the committing
thread runs its own command buffer's submission handlers, so it may submit a later batch before
they start. The docs still said they run before any later batch's submission, and the check
asserted it: its own handler noted one kernel submission at its start.

That held in the check only while the scheduler's thread was held until the handler began. With
the thread asleep and free (d4142474fd), job m3-max-36199 on lavapipe: the Exact variant failed
it, the handler noting 2 submissions at its start (the scheduler's thread had already submitted
second's first), with all three later batches submitted by its end (Some(3), no slice rescue).

The handlers wait for none of those submissions, which is what the early end buys; when a later
batch's submission comes relative to them is not ordered. The check now asserts that the
handler ran inside the call; the early end is asserted by the pass's counts (one batch at
commit, one early end), the wake by the three submissions by the handler's end, and the
handler order as before. The runtime README, the scheduler's module docs, commit_and_submit's
docs and WorkCounts::scheduler_passes_at_commit_ended_early now say so.

Verified: to be run on lavapipe and PHOENIX, with the no-wake control.
2026-11-16 04:52:49 -08:00
Anees Iqbal c2c28b0565 submission_turns: the committing pass's check stages the scheduler's thread asleep
The check of a committing pass that ended at its own submission handlers held the scheduler's
thread after a pass (waiter_submits::Held). Its control without the wake (c9bda0351d) still
passed, 14/14 on lavapipe (job 36157): the pass's mark (state.dirty) alone sends a thread that
is held, not asleep, on to the left batches as soon as it is let go.

The check now waits until the scheduler's thread sleeps with nothing to do
(Scheduler::asleep), then holds every commit_and_submit before its pass
(trace::Point::AtCommitPass) as its commit is posted with no wake (trace::posted_count), four
in all, and lets only the first go on (trace::let_through), whose pass takes all four in. With
no wake the sleeping thread never sees the mark while that handler runs, so the three later
command buffers are submitted by its end only at the wake (Some(3), with no slice rescue).

The assertion on that runs before the wait for completion, so a missing wake fails there, with
the counts, and not at the completion's timeout.

Verified: to be run on lavapipe, with a control that removes the wake.
2026-11-16 04:52:49 -08:00
Anees Iqbal 43d2fa26ff Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 04:33:10 -08:00
Anees Iqbal 8562b28fe4 RUNTIME 2446: Shadows: a split merge on the host copies no piece; its kernel skips their columns
A merge on the host past shadow_merge::HOST_WHOLE_BYTES split: its host
step stored the pieces of each row in lines beside the texels, and its
kernel the rest. To keep the kernel off those lines, the GPU copied the
pieces' kept bytes into an arena region and their changed bytes over
them in the kept part: two vkCmdCopyBuffer calls of one region per
piece. On the Iris Xe (ANV) that work cost about 7 to 9 us a region,
growing with the rows, not the bytes: about 0.6 ms for 34 rows
(m3-max-35898) and about 15 ms for 1024 (m3-max-36118: a BGRA8 1023x1024
render target over host pages drew in 17.57 ms a command buffer as a
shadow against 1.26 ms in place, its host step 0.28 ms of it).

Now the kernel takes a column window (bind::ShadowMergeModule: two more
push words, PUSH_BYTES 24; shape_within, shape the whole row): a word
outside the columns is neither read nor written in either store form,
and counts as unchanged in its block. A split merge pushes the words
between each row's pieces where every row's pieces lie at the same
places in it (shadow_merge::columns: whole words, the same head and tail
each row; rows whose pitch is no multiple of the line differ, and those
merges go on the host whole). It records the changed copy and its
dispatches alone, with no save, no mask, two fewer barriers and no arena
region; the host step reads each piece's kept and changed bytes in the
scratch's two parts, which nothing writes after the changed copy.
Removed: HostMerge::saved, ShadowMerge::saves, ShadowCopy::merge_saves,
the merge's region in EncoderCore::merge_on_host, MergeDrain::_region,
and the split's copy uses of the kept part. The bound stays 1 MiB; its
doc comment states the measured costs. Linear merges push the whole row.

Tests:
- bind::shadow_merge's
  a_region_merged_within_columns_leaves_the_words_outside_them: 70 rows
  of 6 words, columns 1 to 4, every word changed; words outside the
  columns keep the current buffer's, in both store forms, and a window
  of every column equals shape.
- shadow_runs' merges_on_the_host_go_whole_up_to_the_bound_and_split_past_it
  also asserts shadow_merge_words_examined: every word of the whole
  merge's rows; for the split, the words between each row's pieces
  alone (height * (row bytes - line) / 4).
- shadow_write_lines' cost test gains a 4K shape: 3839 RGBA16Float texels
  a row, 2160 rows 30720 bytes apart.

The merge module is under no golden table (golden_hashes covers the
fixtures' translations). api_signatures: PUSH_BYTES, shape, and the new
shape_within. Degradation kinds added: none.

Landing note: msi m3-max-36189 at 4b09425f2d (same tree): clippy metal2vulkan + runtime, all targets and features, CLIPPY=0. The API tables, the module tests, rustdoc, clippy m2v_gpu / m2v_cpu_icd, the lavapipe control (development's whole-row kernel fails the split test's words-examined count) and the touched suites, PHOENIX and the Iris re-time follow on development.
2026-11-16 04:32:27 -08:00
Anees Iqbal 6df2d88550 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 04:11:09 -08:00
Anees Iqbal 7fa39e82e5 RUNTIME 2445: Scheduler: a committing pass that ended at its own handlers wakes the scheduler's thread before running them
What: where a commit_and_submit pass ends right after its own command buffer's last batch with
batches left, it marks the state for the thread's pass (State::dirty) under the lock. Right after
the lock is free, before the completion turn it owes and before its handlers, the committing
thread wakes the scheduler's thread (wake_thread, Woken::Host). That pass reports no left_over,
so the end of submit_at_commit does not wake the thread again; passed_over() is still checked.
The thread passes while the committing thread runs its handlers; the batches it submits take
later Turns tickets, so their handlers still run after the committing command buffer's.

Why: in PHOENIX m3-max-36098 (the guest-shaped SubmissionHandlers leg after RUNTIME 2442), the
time from an early end to the next kernel submission made by the scheduler's thread was
p50 27 / p90 278 / p99 986 / max 1273 us (212 samples). The left batches waited for the
committing thread's handlers and the wake after them. The usual wake (wake_for, inbox.nudge)
skips the wake while the committing thread is still counted as the passer, and pass_once_then
never looks again. The scheduler's thread is never gated by a counted passer: it waits only for
the lock.

Tests: submission_turns' a_committing_pass_ends_at_its_own_submission_handlers_{exact,grouped}
now let the scheduler's thread go once the committing command buffer's handler has started. That
handler waits, up to two seconds, for the three later command buffers' submissions
(CommandBuffer::submit_returned_time), and all three are made before it ends (none without the
wake). The handler-order assertion stays. The test's messages lose the runs of spaces an edit
left in them.

The check also requires no sleep-slice rescue (WorkCounts::scheduler_slice_rescues moves by 0): the first control with the wake removed (ctl/complat2f 86baad51c4, lavapipe m3-max-36134) passed the timed check, because a 100 ms WAIT_SLICE let the left batches go within the handler's two-second bound.

Verified: msi m3-max-36132 at 46c7eedd4a (product code as landed): build, runtime clippy plain and --cfg m2v_gpu, unit, sigs EXIT=0. The tightened check at the tip and its control (m3-max-36157), the suites, clippy x3, rustdoc and the PHOENIX legs (m3-max-36158) follow on development.

Degradation kinds added: none.
2026-11-16 04:10:27 -08:00
Anees Iqbal 81280c01f4 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 03:57:29 -08:00
Anees Iqbal c602b94223 RUNTIME 2444: Host pages: remove the lend of free padding to the copies; such render targets are shadows
What: a texture that renders over host pages whose rows end inside a line, with
free padding, whose renders failed, no longer takes its image in place when the
class's copies failed too. Removed: in_place::lent_to_copies and lends, the lend
branch in in_place() (it now asks each access's own verdict and nothing else),
unlent_words and the shadowed-texture notice words it added,
degrade_line_write_back and line_write_back_reason, the storage form move's lend
count and notice, Degradation::LineWriteBack ("line-write-back") with its
docs/API.md catalogue entry, the device test lent_dma_buf_targets, and the
validation lane's LINE_WRITE_BACK list. copies_verdict stays: through
InPlaceChecks::decided it now decides only whether a shadow's copies back and
merges into such pages are spliced (shadow_splice::splices). FAST-PATHS's
host-pages row and the Iris known gap are edited in place.

Why: the lend loses CPU writes Metal keeps. Both Macs kept render padding over
buffer rows (m3-max-35486 and 35487: clear-and-store and draw changed 0 bytes;
only the UHD 630's kernel changed any), and the lend's render passes write the
rows' last lines back whole on the Iris. Its stated reason was that the shadow
lost the same bytes. That no longer holds: the shadow splices its copies back
and merges on the host on such devices, and on the Iris (m3-max-35898) its
clears and draws put back 0 bytes against the copy control's 5,941 in 300
rounds. Under the user's contract rule a form that loses writes Metal keeps is
deleted, not kept behind a switch.

Guest cost, bounded by counts: the guest's Iris Forward+ boot (reims run 35408
at 44505b3807) lent nothing (line-write-back 0); its 57 shadows are IOSurface
planes.

Tests: the in_place unit tests now assert a render target over free padding is
a shadow by its renders' verdict whatever the copies say, and that a copy back
splices by the crossed copies' verdict; the decision's model in
the_decision_takes_a_texture_whose_class_passed_each_of_its_accesses asks each
access's own verdict, the first that did not pass naming the shadow. The validation lane's render-target test
asserts in place exactly where renders passed.

Degradation kinds removed: LineWriteBack. Added: none.

Landing note: lavapipe m3-max-36064 at 5b9af90e0a: CLIPPY=0, API=0 (15/15), RUSTDOC_RT=0, CLIPPY_GPU=0, CLIPPY_CPU=0; holds 2/2; suites 641/641; validation 33/33 (IN-PLACE-FREE: both render targets shadows, 0 padding bytes changed). PHOENIX m3-max-36117 and the Iris page-short timing (in place against the shadow per import, m3-max-36118) follow on development.
2026-11-16 03:56:47 -08:00
Anees Iqbal 4a9fc2ac19 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 03:52:21 -08:00
Anees Iqbal 61b3749144 RUNTIME 2443: WorkCounts::dma_buf_sparse_binds; DmaBufRequest and HOWTO state what several chunks cost
What: a new WorkCounts field, dma_buf_sparse_binds, counts each
VkSparseMemoryBind the dma-buf chunks bind a sparse buffer with (one a
chunk, counted in dma_buf.rs's chunks_buffer once the binding is made).
DmaBufRequest's rustdoc and docs/HOWTO.md now say what an answer of
several chunks costs: each chunk is one sparse bind, which RADV makes a
GPU virtual-address operation of its own, updating the GPU's page tables
as the buffer is bound and again as it is released, where one chunk binds
a plain buffer in its import with no such update. The advice: answer a
request whose pages lie in several runs with one dma-buf of those runs
where the source can (udmabuf's UDMABUF_CREATE_LIST, up to list_limit),
and with several chunks only where one dma-buf cannot hold them. The
host_ab example lists the count.

Why: a consumer's guest compute walk on the RX 7900 XTX (RADV, Mesa
26.2.6) rose 0.4 s in its heaviest workload once its source answered
guest buffers with many pieces of its RAM's region files: 81 sparse
buffers over about 5,000 pieces in one second of setup, followed by
15,732 of amdgpu's page-table range jobs (377 ms of kernel SDMA jobs in
that second, against about 45 ms before), and 4,930 more as 240 buffers
were destroyed with one memory freed. Across the workloads the page-table
jobs tracked the pieces at about 3.5 a piece; the guest's own GPU job
time fell. No count said how many binds a sparse buffer took, and the
docs gave sources no cost for splitting.

Test: tests::dma_buf_shared_files's two-piece buffer now asserts two
sparse binds for its one sparse buffer (none where the device binds one
piece) and prints the count.

Verified: in the job that reports this tip (clippy of the runtime, the
dma_buf_shared_files tests on lavapipe). api_signatures blessed (one
field). No new Degradation kind.

Verified: msi m3-max-36087 at 9c5829c1ac: clippy -p metal2vulkan-runtime --all-targets --all-features CLIPPY=0; lavapipe (m2v_cpu_icd) tests::dma_buf_shared_files 10/10 ("two pieces of one file: ... sparse buffers 1, sparse binds 2", asserted). Clippy m2v_gpu / m2v_cpu_icd and rustdoc follow on development.

Degradation kinds added: none.
2026-11-16 03:51:38 -08:00
Anees Iqbal 2c6a66c3a0 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 03:41:48 -08:00
Anees Iqbal 3348b469c2 RUNTIME 2442: Scheduler: a committing pass ends right after its own command buffer's last batch where that one has submission handlers
What: where a commit_and_submit pass submits its own command buffer's last batch and that command
buffer has submission handlers, the pass ends there. It takes no check, and leaves whatever else
is ready to the scheduler's thread, which the committing thread wakes as before (left_over ->
Woken::Host). The committing thread then runs its own handlers once the lock is free, before any
later batch's submission. New WorkCounts::scheduler_passes_at_commit_ended_early counts the
passes that so ended with batches left. A test-only hold point, trace::Point::AtCommitPass, comes
before a committing thread's pass.

Why: PHOENIX m3-max-35993 (the guest-shaped submit-cost leg, a trace of Turns waits by the
holder of the ticket waited behind) found one kind of wait. A segment that a committing pass
handed off waited behind that pass's own ticket: 0.12 a frame, p50 3449 us, max 4586 us. The
handler runs only after the pass's later submissions, which are costly in that leg. Every
segment after it in the one hand-off context waited too: submission return to own handler
p99 3410 us on the handler threads. The scheduler's handed segments never waited in Turns, and
committing threads never waited behind handed segments.

Tests: submission_turns' a_committing_pass_ends_at_its_own_submission_handlers_{exact,grouped}.
The scheduler's thread is held after a pass. A commit_and_submit is held before its pass while
three ready command buffers are committed after it: one on another queue, one behind it on its
own, one behind the first on the other. Its handler runs inside its call with one kernel
submission made (without this change, after all four). The pass submitted one batch and counted
one early end. The handlers run in submission order, each queue's in commit order.

Verified: msi m3-max-36060 at 0c131eff3a: build, runtime clippy plain and --cfg m2v_gpu, unit, sigs EXIT=0 (api_signatures: WorkCounts::scheduler_passes_at_commit_ended_early). Control m3-max-36061 (early return removed, lavapipe): both checks FAIL under Exact and Grouped ("submitted 4 batches, ended early 0; handlers ... [ours 4, ...]"); the other 12 submission_turns tests pass. Lavapipe suites, clippy x3, rustdoc and the PHOENIX submit-cost leg (36069) follow on development.

Degradation kinds added: none.
2026-11-16 03:41:06 -08:00
Anees Iqbal 7cc30e485e Tests: a no-copy buffer's import goes at the completion past a merge on the host
RUNTIME 2440 removed the program's buffer from the host step's drains
(SpliceDrain, MergeDrain), whose segment the command buffer keeps until
it goes. The test that showed the hold,
a_no_copy_buffer_a_committed_dispatch_writes_a_texture_over_keeps_its_import_until_completion,
no longer reaches a merge on the host since RUNTIME 2438/2439: its rows
fill whole lines, so no line holds a byte beside its texels, and the
merge goes by its kernel alone.

The new leg TextureMergedOnHost keeps the path: the same dispatch into a
texture over the no-copy buffer, its rows a texel short of their pitch
(511 RGBA8 texels in 2048 bytes), on a device whose every texture over
host pages is a shadow (HostPageTexturePolicy::Shadow, under which the
check gives no answer), so both releases (at the commit, and once
scheduled) take the merge on the host. Each asserts that a host step ran
(WorkCounts::shadow_host_steps grew) and that the deallocator runs once
the command buffer completed, the CommandBuffer still held. Where the
device's lines hold no more than a texel, the leg prints and returns.

texture_write and over_buffer take the width. The texture write legs'
check goes row by row: each row's texels hold the dispatch's, and the
bytes past them to the pitch still hold the pages' fill (the merge keeps
them); for the 512-texel rows of TextureWrite that is every word, as
before.

Test only; no product change.

Verified (lavapipe, m2v_cpu_icd, msi m3-max-36042):
- CONTROL_LVP=100 with 7713853865's shadow.rs, shadow_merge.rs and
  shadow_splice.rs (the drains holding `_buffer`): "host steps 1", then
  "the deallocator never ran" at the Committed release.
- HOLD_LVP=0 at RUNTIME 2440: the new test (host steps 1 at each
  release) and TextureWrite, 2 of 2.
- HOLDS_LVP=0: every *holds* test, 134 of 134.
- clippy of metal2vulkan-runtime under m2v_cpu_icd and m2v_gpu: clean.
2026-11-16 03:29:54 -08:00
Anees Iqbal 7dc5edc687 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 03:29:42 -08:00
Anees Iqbal c2aedcd64c Diagnostics: encoder times count draws again; the pass log watches states by label hash
METAL2VULKAN_ENCODER_TIMES counted a render encoder's draws only where a draw
took every step: a draw drawn again as before (render/draw_again.rs) or rebound
(render/draw_again/rebound.rs) bumped the encoder's draw calls but not its
timed work, so a row named a fraction of its draws (a measured guest run: rows
of about 2300 draws/s against about 36k indexed Vulkan draws/s). Both paths now
count as the program's draws, as every step's do.

METAL2VULKAN_LOG_PASSES watched only textures by format and size, and its
256-line bound was spent before the pass of interest ran: in that run every
2768x1570 pass before the measured step printed (256 lines distinct even with
object IDs left out, 171 by attachments and states alone), so the pass the
encoder times ranked first never printed. A `state:HASH` entry now watches a
render pipeline state by the label hash the encoder times name their rows by
(encoder_trail::label_hash), so a run can name exactly the pass it needs; each
state in a line carries its hash, so a line maps encoder-time rows to states.
The hashes are worked out only where the log watches a state or prints a line.
The bound and the once-per-pass rule are as before.

Both are default-off diagnostics and change no work while off.

Tests: tests::encoder_times::an_encoder_s_draws_again_count_among_its_draws
(draws again as before and rebound, each counted, in a line of all its draws;
fails without the fix: the line names only the draws that took every step);
tests::pass_log state-entry parsing, refusals and matching.
2026-11-16 03:29:01 -08:00
Anees Iqbal 325eb61cde Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 03:21:44 -08:00
Anees Iqbal f3390be7f0 RUNTIME 2441: Scheduler: a committing thread's pass keeps only its own command buffer's submission handlers; gated completions post with one look
What: commit_and_submit's own pass (and the pass the lowering thread makes for one left for a
render encoder's end) keeps inline only its own command buffer's submission handlers, which run
on the committing thread inside the call, in their turn, as before. Every other command buffer's
handlers whose last batch the pass submits go to the device's handler threads right after that
submission, as one segment with its Turns ticket; the committing command buffer's ticket is taken
as its batch goes, so submission order holds. Both of submit_plain_ready's places that take
handlers (a submitted last batch and one held in the group) go through keep_or_hand_off.

A transition to Completed or Error whose transition to Scheduled is still owed is posted behind a
gate only where its submission handlers have not run (gate_for_handlers); otherwise plainly. The
gated post pushes the item behind the gate and opens the poster's closing under one lock with one
look for a thread (Contexts::post_gated), where post_behind and open made one each. FAST-PATHS
records the hand-off's own cost (19.1 wakes a frame).

Why: on PHOENIX, in the guest-shaped submit-cost leg after the scheduler-pass hand-off
(RUNTIME 2437), a submission's return to its own handler was p50 991 / p99 5231 us where a
committing thread ran it (978 handlers), against p99 380 on handler threads: a committing pass's
handlers waited for the rest of that pass's submissions. The gated post's second look for a thread
cost 4.4 wakes a frame.

Tests (submission_turns): a_committing_pass_keeps_only_its_own_submission_handlers_{exact,grouped}
(fails at control C2 m3-max-35888, the hand-off reverted: the earlier command buffer's handler ran
on the test thread); a_gated_completion_is_posted_with_one_look_for_a_thread_{exact,grouped} (fails
at control D m3-max-35877, post_behind + open: [(true,2)] against [(true,1)]). The check takes the
device's queue plan.

Verified: msi m3-max-36014 at bd810397db: build, runtime clippy plain and --cfg m2v_gpu, unit
44/44, sigs, lavapipe suites 126/126 (encoder_holds TextureWrite passes). Workspace clippy x3,
rustdoc and lvpval 30/30 at the pre-rebase tip 2d09ed2392 (m3-max-35927). PHOENIX m3-max-35923
(suites at df21628b0f): handler-thread wakes per frame 50.2 -> 48.37 (post_behind + open 8.9 ->
post_gated 6.72); seen to seen-handler p50 11, p99 3658 us.

Degradation kinds added: none.
2026-11-16 03:21:03 -08:00
Anees Iqbal 8d57656475 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 03:11:33 -08:00
Anees Iqbal f93cb22b94 RUNTIME 2440: Shadows: a host step's drains hold none of the program's objects
A shadow's copy back spliced (RUNTIME 2431) and its merge on the host
(RUNTIME 2432) leave their CPU parts, SpliceDrain and MergeDrain, to a
host step in a Deferred::ShadowSplice segment. Each drain held the
truth's Buffer (`_buffer`), and the segment lies in the command buffer's
recorded parts, which its completion does not let go of: only
State::reset clears them, as the CommandBuffer goes. So a no-copy
buffer whose texture's write-back went through a host step kept its
import past the completion for as long as the program kept the command
buffer, where Metal lets go of what the commands used, and runs the
deallocator, at the completion.
tests::encoder_holds::a_no_copy_buffer_a_committed_dispatch_writes_a_texture_over_keeps_its_import_until_completion
failed on development ("the deallocator never ran"): it makes its
texture while the device's check is pending, which splices
(shadow_splice::splices), so the dispatch's write-back merges on the
host.

The rule the drains now rest on: the host step runs before its command
buffer completes, and until then the command buffer holds what its
encoders' commands named (`retained`, retained.rs), the texture among
them, which holds the buffer whose pages the step writes. The runtime
makes no command buffer with unretained references, so that hold is
always there. The drains drop `_buffer` (SplicePlan its buffer, and
ShadowMerge::drain its parameter); what they still hold is the
runtime's own: the merge with its scratch, and the arena's region. The
SAFETY comments and the ShadowSplices doc say what holds the pages.

Degradation kinds added: none.

Verified: see the jobs named in the landing report (the failing test at
the fix and at its parent on lavapipe, at the fix on PHOENIX, the shadow
and hold suites, clippy in three configurations, rustdoc).

Verified: msi m3-max-36002 at 4606d9e40c (same tree): CLIPPY=0, CLIPPY_GPU=0, RUSTDOC=0. Lavapipe control + fix (m3-max-36003) and PHOENIX follow on development.
2026-11-16 03:10:51 -08:00
Anees Iqbal 7713853865 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 02:58:20 -08:00
Anees Iqbal 528379dad5 RUNTIME 2439: Merge on the host whole up to 1 MiB of rows; count host steps
On the Iris Xe (RPL-P, ANV) the split merge's own GPU work (two buffer
copies of the pieces beside the texels, three barriers and the kernel's
dispatch) cost about 0.6 ms a command buffer for the guest's 34x34
RGBA16Float target (m3-max-35898: draw minus clear 0.69 ms, against
0.10 ms when the merge went on the host whole), while the host step's
word loop costs about 0.30 ns a byte (4.97 ms for a 1920x1080 target's
16.6 MB, half its texels changed). So the split pays only past about
2 MB of rows.

A merge on the host whose cut rows hold at most HOST_WHOLE_BYTES (1 MiB,
half the break-even) now goes on the host whole again; larger ones
split. A merge none of whose rows' lines holds a byte beside its texels
still goes by its kernel alone, as on any device. The whole merge is
also the exact form for the unmeasured case (a CPU write to a texel the
commands left in a line whose other bytes they changed), so the known
gap now applies only where the kernel stores: past the bound, and where
no row's line holds a byte beside the texels. Both forms keep the
measured padding contract, so there is no switch and no FAST-PATHS row.

WorkCounts::shadow_host_steps counts the host steps that ran for
encoders' copies back spliced and merges on the host: against
command_buffers_submitted, the GPU-to-CPU round trips a command buffer
pays, for a walk to read before any deferral of them.

Tests:
- shadow_runs::merges_on_the_host_go_whole_up_to_the_bound_and_split_past_it:
  over pages 16 bytes into a page, a 512x512 BGRA8Unorm target (1 MiB
  of rows) compares every byte of its rows on the host, and a 512x513
  one each row's first and last lines alone; each one host step.
- shadow_write_lines: the contract test's draw merges now compare every
  byte of their rows; the cost test alternates its verdict arms round by
  round, so clock drift and order weigh on both alike (the 1080p gap
  35898 showed, equal in Clear and Draw, with the same work recorded in
  both arms by every count); a new test prints, for a render target
  whose rows end a texel short of a 4096-byte page (1023x256 and
  1023x1024 BGRA8Unorm), under the device's own check and default
  policy, over pages imported by pointer and as dma-bufs: every host-page
  class's renders and copies verdicts for those row ends and its memory
  flags, the form the texture takes with its notices, and the median per
  command buffer of a clear-and-store and of a draw.

Degradation kinds added: none.

Verified: msi m3-max-35933 at f763e15338 (same tree): CLIPPY=0, CLIPPY_GPU=0, API=0 (15/15), release archive built. PHOENIX, lavapipe and the Iris run follow on development.
2026-11-16 02:57:29 -08:00
Anees Iqbal 84b8fe0645 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 02:29:59 -08:00
Anees Iqbal 438fdd4eee RUNTIME 2438: Merge on the host only the lines beside a texture's texels
A shadow's merge in place into host pages, on a device whose stores
write back the lines they end in (the Iris Xe under ANV) or whose check
has not answered, went on the host whole: the host step compared and
stored every byte of the merge's rows. On the Iris that cost 12.7 ms a
merge for a 1920x1080 RGBA16Float draw (17.7 ms a command buffer
against 3.7 ms by the GPU kernel), and the guest's scene has about 73
such shadows.

The merge now splits as the splice of a copy back does:

- Its kernel stores the changed words of each row's bytes in the lines
  that hold the texture's texels alone (ShadowMergeStores::Words, never
  whole blocks).
- The host step merges only each row's bytes in the lines that also
  hold a byte of no row of the texture's: the bytes between the rows and
  around them (shadow_splice::beside_texels; at most a row's first and
  last line).
- Before the kernel the GPU copies those pieces' kept bytes into a
  region of the command buffer's arena, then their changed bytes over
  them in the kept part, so the kernel finds them unchanged and stores
  none of them; the host step compares the region's bytes with the
  changed part's.
- The host step compares 4-byte words and stores a changed word with one
  AtomicU32 store (the changed word where all four bytes differ, else
  the word as it holds it with those bytes changed, as the kernel's
  Words form does); bytes outside whole words go one by one.
- A merge none of whose rows' lines holds such a byte (rows that start
  and end on lines, as the 1920x1080 plane's 15360-byte rows do) goes by
  its kernel alone, with its fetch view and kept image where it has
  them. A merge not cut to its texels' rows stays on the host whole.

The measured contract is the padding: row_padding_writes found the M3
Max, the 5300M and the UHD 630 keeping CPU writes to the bytes between
and around a texture's rows under clears, stores and draws, and over
IOSurfaces under kernels. No probe measured a CPU write to a texel the
commands left inside a line whose other bytes they changed, while the
command buffer runs; the kernel now stores into such lines, so that
write may be put back on the Iris. FAST-PATHS's known gaps record it,
beside the measured contract.

WorkCounts::shadow_merge_bytes_on_host counts the bytes the host steps
compared. Buffer::own_pages_flags gives a buffer's memory type flags,
which the cost test prints for a buffer made as the host scratch is,
beside the host loop's time over plain heap memory and over that
memory (1920x1080, half the texels' red and blue changed).

Tests:
- tests::shadow_splice (pure): the pieces equal the rows' bytes in
  lines beside the texels, found byte by byte, over 9 shapes and 6 page
  phases (wrapping among them); the host loop stores the differing bytes
  alone at every alignment.
- tests::shadow_write_lines: each draw merge's host step compares 16
  bytes a row (the row's last texels, in its padding's line); the cost
  test's 1920x1080 draw no longer merges on the host.
- tests::shadow_runs: the rebind test of host merges puts its pages 16
  bytes into a page, so every row's first and last lines hold bytes
  beside its texels, and asserts the bytes compared (a line a row).

Degradation kinds added: none.

Also (65db6f5b40): the old device-local query, left with no callers, is gone; the probe prints
the scratch's memory flags by name.

Verified (fplend): msi m3-max-35872 at a5289d8132 (same tree as 65db6f5b40): clippy 0, clippy
--cfg m2v_gpu 0, api_signatures + api_surface 15/15, debug and release archives built; 35850:
tests::shadow_splice 5/5 (host pieces against a byte-by-byte answer over 9 shapes x 6 page
offsets; the CPU word loop at every alignment). PHOENIX, lavapipe, rustdoc and the Iris run follow.
2026-11-16 02:29:15 -08:00
Anees Iqbal 86fd05fb88 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 02:02:29 -08:00
Anees Iqbal 2feb4e70f1 RUNTIME 2437: Scheduler: hand a pass's submission handlers to the device's handler threads as it goes on
What: the scheduler thread's passes no longer run the submission handlers of the command
buffers they submit (or hold in a group, or make Scheduled behind a host step) at the end of
the pass. Each time the pass is about to look for its next batch, it hands the handlers taken
so far, as one segment with its Turns ticket, to the device's handler pool (one context of the
"metal2vulkan-handlers" threads, made at the first hand-off), and goes on submitting. The
segment runs there in its turn, so submission order holds across passes and with
commit_and_submit's own pass, which still runs its handlers inside the call on the committing
thread. A pass that settled a switch of storage forms keeps the handlers it took from then on
and runs them itself after the switch ended, as before, since the switch must end before those
command buffers are Scheduled.

The blocking wait in run_scheduled (a Finished that found Scheduled owed waited on a pool
thread for the submission handlers) is gone: such a Finished is posted behind a context gate
(finish_after_handlers), its place kept, holding no thread, and the thread that ran the
handlers opens the gate; the Finished then runs the owed Scheduled first. So no handler thread
waits for a submission handler, and the pool's cap cannot be exhausted by such waits.

A held group is cut short for another queue's submission handlers (Alone::Handlers) only where
the pass keeps them (a settled switch): handed-off handlers hold back no pass.

Why: in the guest-shaped submit-cost leg on PHOENIX, a command buffer's submission handlers
started 1683/5299/5776 us (p50/p99/max) after its own vkQueueSubmit returned, behind the rest
of the pass; 4561 of 5280 command buffers were seen complete before their own submission
handler ran, and seen -> seen handler was 1.4 ms p50 / 5 ms p99 against Metal's 0.28 ms p99.

Tests: submission_turns gains a_pass_s_submission_handlers_run_while_it_goes_on_{exact,grouped}
(a handler of an earlier submission starts before the pass's later submission returns plus the
pause) and completions_before_their_submission_handlers_hold_no_handler_thread_{exact,grouped}
(6 queues with owed Scheduled on a pool of 2 threads, all complete within a bound; test hook
contexts::TEST_LIMIT). waiter_submits::Held now holds the scheduler thread with a test hook
after the pass that handed off its command buffer's handler (trace::hold_after_hand_off,
Point::HandedOff), since a submission handler no longer runs there. Tests and lanes that held
the scheduler thread in a submission handler hold it in a submission check instead
(unsubmitted, host_memory's deallocator lane); queue_order's take-up probe notes from the
check, which still runs on the scheduler thread; commit_and_submit's held-check test asserts
the orders that hold (A's handler before B's, B's check before B's handler) instead of one
interleaving; the submission_handlers lane expects the handler threads; grouped_submissions'
cross-queue handler lane counts X and Y's one submission once all completed.

Docs: add_submission_handler names the threads (inside commit_and_submit: the committing
thread; otherwise the device's handler threads), README, RUNTIME-PORTING, FAST-PATHS (the
grouped-completion row's handler rule, the commit cost entry), scheduler, inbox, group,
submit, contexts.

Also: the completion_latency guest-shaped leg times each submission handler from its own
submission's return; the unsubmitted check and the deallocator lane hold the scheduler thread
where an empty opener runs no submission check.

Verified (complat): msi m3-max-35809 at 0e0c55e4e8: build, clippy -D warnings (runtime, plain and
--cfg m2v_gpu), unit 44/44, signatures, lavapipe suites 122/122, all 0; gem10 35797 at 4aa9c2ac29:
workspace clippy x3 and rustdoc 0. Negative controls (msi 35811, lavapipe): with the blocking wait
back, completions_before_their_submission_handlers_hold_no_handler_thread fails under Exact and
Grouped (5 of 6 never completed with 2 handler threads); with no hand-off,
a_pass_s_submission_handlers_run_while_it_goes_on fails under both. PHOENIX suites and the
submit-cost leg before/after follow.
2026-11-16 02:01:45 -08:00
Anees Iqbal a7908e6554 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 01:40:11 -08:00
Anees Iqbal be720853a5 Name no consumer benchmark in comments, tests or docs
Eight comments and docs (dispatch_chain, compute_instantiated, spares_compute, unshared_hold and
its tests, FAST-PATHS) named the guest compute benchmark a workload came from, and two named a
consumer's job labels. AGENTS.md keeps consumer apps and benchmarks out of the tree; the shapes
and numbers stay, described by what they are (a guest compute benchmark's super-resolution
workload, its fluid simulation).

Verified: git grep finds no such name; cargo fmt. Comments and docs only.
2026-11-16 01:39:25 -08:00
Anees Iqbal dff52cb6f1 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 01:34:57 -08:00
Anees Iqbal 2824464479 Storage twin docs: NonWritable states read-only memory, nothing more
What: views::declare_twin, DriverWorkaround::PushReadsLengthenThreadPayload and docs/API.md
section 5 no longer say that the twin's NonWritable decoration lets ANV fold or merge its loads, or
that the twin without it read more than the uniform view. They keep the fact: the twin binds the
uniform view's own range of a constant buffer, which the dispatch only reads, so its views are
decorated NonWritable. The decoration and its test stay.

Why: a585a74686 gave that as the cause of the Iris regression between pins 825997e49c and
44505b3807. The evidence since says it is not:
- Iris A/B m3-max-35592 (ANV, Mesa 26.2.6, 5 rounds): dispatch_chain --binds params ran
  358.8 us a dispatch with and without the decoration.
- Iris walk m3-max-35628 at bd3c1a8c37 (the decoration in): the two regressed workloads did
  not move (19.72 -> 20.01 s and 28.53 -> 28.36 s GPU).
- ANV's own stats (INTEL_DEBUG=cs, m3-max-35722) for a kernel of ours that reads its constant
  blocks through helpers and a private struct: twin at key 1 without the decoration and with it
  compile alike (SIMD16, 722 instructions, 79 sends, no spills).
The regression's cause is under investigation separately: a scratch build without storage twins
(68e39640e9, walk m3-max-35702) brought the workload back, so the twins are involved, not their
decoration.

No behaviour change: doc comments and docs only, no version bump. The runtime-sources pin
re-pins at landing (views.rs and profile.rs are hashed).
2026-11-16 01:34:11 -08:00
Anees Iqbal 72760fb849 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 01:32:56 -08:00
Anees Iqbal d8898b007e RUNTIME 2436: Shadows: an encoding again leaves a splice's CPU part for its host step
What: EncoderCore::finish_replay now prepares a ShadowSplice segment the encoding
again left (Deferred::left_again_by_an_encoding_again) as the commit prepared the
first one, leaving it for its host step with the commit's inputs and bound,
instead of asking to record it on the GPU alone.

Why: with the previous change the rebind encoded such an encoder again, but
finish_replay asked every segment that keeps no pipelines to record on the GPU
alone, and a host step's work refused the encoding again ("an encoder encoded
again whose work no longer runs on the GPU alone"). PHOENIX job m3-max-35779 at
3231f11017 showed it: tests::shadow_runs::passes_merged_on_the_host_are_encoded_again_at_a_rebind
failed with EncodedUseRebound, "encoders encoded again 0, refused 4". Lavapipe job
m3-max-35784 at the same tree failed the same test; CLIPPY_CPU=0, RUSTDOC=0, and
268 of 269 passed there.

Verified: cargo fmt only so far; the jobs reported with this tip run the tests.

Degradation kinds added: none.

Verified (fplend): msi m3-max-35787 at 060ecbcd45: clippy 0, clippy --cfg m2v_gpu 0, debug archive 0.
RUNTIME 2435's tree left passes_merged_on_the_host_are_encoded_again_at_a_rebind failing on PHOENIX
35779 (340/341) and lavapipe 35784 (268/269); the touched suites at this tip follow.
2026-11-16 01:32:12 -08:00
Anees Iqbal 5dce2bfae3 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 01:28:22 -08:00
Anees Iqbal 918a5e59fb RUNTIME 2435: Shadows: a rebind encodes an encoder with a host merge or splice again
What: an encoder that left a splice's or a merge on the host's CPU part
(Deferred::ShadowSplice) now keeps its log, and a rebind's encoding again replaces
that segment with the one it leaves itself over the new pages
(Deferred::left_again_by_an_encoding_again, in Segment::records_again and
reencode.rs's splice_fits). The first segment is retained unrun, as a replaced
pending dispatch's is. A rebind keeps the bytes' offset in their page, so the
copies back cut alike and the encoding again's parts match the first's.

This covers ShadowSplice only, not a staged scatter (Deferred::ScatterStage and
ScatterDrain, host_ram/copy.rs). An encoder that left a staged scatter still keeps
no log (Unlogged::Segments), so a rebind of its buffer fails the command buffer
with EncodedUseRebound as before. Whether a scatter's encoding again over the new
pages leaves segments of the same parts was not checked: its staging depends on
the chunks and imports the new pages lie in.

Why: after RUNTIME 2433 the rebind was no longer refused, but such an encoder kept
no log (Unlogged::Segments), so its command buffer failed EncodedUseRebound.
PHOENIX job m3-max-35745 at 343f4489d3 (RUNTIME 2433's tree) failed
tests::shadow_runs::passes_merged_on_the_host_are_encoded_again_at_a_rebind
("Error Some(EncodedUseRebound); encoders encoded again 0"), and so did lavapipe
job m3-max-35749. The other five tests that failed at RUNTIME 2432 passed there,
and so did 340 of 341 PHOENIX suite tests and 268 of 269 lavapipe ones.

Verified: cargo fmt only so far; the jobs reported with this tip run the tests.

Degradation kinds added: none.

Verified (fplend): msi m3-max-35769 at 4ac4c366b5 (same tree): clippy 0, clippy --cfg m2v_gpu 0, debug
archive 0. lavapipe 35749 at RUNTIME 2433's tree: 268/269, the one failure the rebind test this
fixes. PHOENIX shadow_runs / merge_scratch and the suites follow.
2026-11-16 01:27:38 -08:00
Anees Iqbal c70ba66b60 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 01:26:50 -08:00
Anees Iqbal 1c0833c2dd RUNTIME 2434: A settle of the device's maps looks only at the objects released since the last
Every compute or render state creation whose variant is not live
(VariantObjects::kept_or_create) settled the device's content-keyed maps:
the linked pipelines, the four graphics pipeline library parts, the shader
modules, the pipeline layouts and the sampler sets. Each settle walked
every entry with Arc::get_mut (a compare-exchange on each entry's weak
count) under the map's lock, so a creation cost O(objects the device
holds), a run of creations O(N^2), and creating threads queued behind each
other's walks. A guest benchmark's 7,981 compute makes spent 19.4% of their
on-CPU time in settle_device_maps and 6 + 3 ms asleep on those locks; the
new COMPUTE-CREATE-SCALING bench shows the slope (XTX, 4 threads: p50 10.7
us at 64 modules, 80.3 us at 4,160).

Now holders take a Share<T> from the map instead of a bare Arc<T>: the
object counts its shares, and the drop that leaves it with none queues its
insertion number on the map's release queue (a leaf mutex, each number
once until a settle takes it). ContentKeyed::settle drains only that queue
and destroys each queued object that still has no share, read under the
queue's lock and the map's (a lookup, the only way to take a share anew,
holds the map's lock; a later last drop queues the object again). The
objects destroyed, their order (insertion) and the calls that destroy them
are today's: the walk found exactly the objects whose shares had all gone.
No switch, no deferral, every map bound as before. The render libraries'
maps (Libraries::settle, the links and the four parts) are ContentKeyed
maps too, so a compute creation no longer walks them either.

Holders changed from Arc to Share: StageObject.module, VariantObjects and
KeptObjects samplers and layout, SharedLayout's sampler set, Link's parts
and layout, Linked. A layout's empty sampler set is Share::unmapped.

Tests (content_keyed, no device):
- a_settle_looks_only_at_what_was_released: 10,000 held, one released, the
  settle looks at 1 object (0 with none released); the old walk looked at
  10,000 each time.
- a_share_taken_again_before_the_settle_keeps_the_object, and the same on
  another thread: a share taken between the last drop and the settle keeps
  the object; released and taken again, it is queued once.
- settles_racing_shares_destroy_nothing_held: 4 threads take and drop
  shares while another settles; nothing destroyed while held, each object
  destroyed once.
- a_share_dropped_after_its_map_leaves_nothing: a share that outlives the
  map's teardown drain goes without panicking and frees its object and the
  queue.

Also: the COMPUTE-CREATE-SCALING and COMPUTE-CREATE-KEYS benches (ignored) and their profile
targets; the content-keyed map tests start their threads through exit_guard::spawn.

Verified (pipesettle): lavapipe gem10 m3-max-35753 (debug, m2v_cpu_icd) 142/142 (pipeline::*,
kept_variants, sampler_sets, linked_pipelines_shared, render_stage_digests, kept_across_calls,
core_image_libraries, exit_guard); msi 35734 clippy -D warnings 0 and 67 pipeline:: tests; gpucfg
build 35754. XTX release bench 35765 (not exclusive, same neighbour both runs), p50 us per creation
at 64 / 1088 / 4160 modules: T=1 5.9/9.3/21.8 -> 5.4/5.2/5.2; T=4 7.6/23.4/76.2 -> 6.8/7.0/6.6.
PHOENIX suites (35772) and clippy x3 + rustdoc at the tip follow.
2026-11-16 01:26:02 -08:00
Anees Iqbal ecf4c80873 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 01:17:57 -08:00
Anees Iqbal 07afa63605 RUNTIME 2433: Shadows: let a rebind encode a host merge or splice again; run tests on lines kept
What: Deferred::ShadowSplice is now resolved at its calls, as a staged copy's
drain is. Its CPU part writes the pages the truth's buffer lay in at the encoder's
call, so a rebind before the command buffer's submission encodes that encoder
again (its CPU part over the new pages), and one after it keeps the old pages until
the command buffer completes (rebind.rs). Before this, a command buffer holding a
spliced copy back (RUNTIME 2431) or a merge on the host (RUNTIME 2432) refused
every rebind of its buffers (RebindProblem::EncodedUses) until it completed; this
fixes both.

The run tests (tests::shadow_runs) run on a shadow-policy device given the check's
answer that copies and shader writes keep their lines (blit_holds::lines_kept),
since runs open only where merges stay on the GPU. A new test,
passes_merged_on_the_host_are_encoded_again_at_a_rebind, runs the rebound sequence
with every pass merged on the host: the rebind is not refused, each pass merges on
the host once, and the texels match the private texture's. merge_scratch's
one_scratch expects a keep per pass where the target merges on the host, and still
checks that the device's memory grows by less than an eighth of a scratch a pass.

Why: PHOENIX job m3-max-35711 at RUNTIME 2432's change failed five tests:
- tests::shadow_runs::{rebound_passes_leave_their_runs, a_pass_alone_merges_in_place,
  scissored_runs_keep_again_once_and_merge_in_blocks,
  runs_over_host_pages_keep_and_merge_once};
- tests::merge_scratch::many_passes_over_host_pages_take_one_scratch.
Under the shadow policy the check never answers, so every merge over host pages
went on the host and opened no run, and the rebind was refused.

Verified: cargo fmt only so far; the jobs reported with this tip run the tests.

Degradation kinds added: none.

Verified (fplend): msi m3-max-35737 at 343f4489d3: clippy (runtime, all targets/features, -D warnings) 0,
clippy --cfg m2v_gpu 0 (compiles shadow_runs, merge_scratch, blit_holds), debug archive 0. The
PHOENIX run of the five tests RUNTIME 2432 broke, the new rebind test and the suites follows.
2026-11-16 01:17:14 -08:00
Anees Iqbal 37d9f80130 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 01:05:49 -08:00
Anees Iqbal 518d6d8443 RUNTIME 2432: Shadows: merge on the host over host pages on devices that write lines back
What: a shadow's merge in place into a no-copy buffer's host pages, on a device whose
check of those pages failed, or has not answered, the copies or the shader writes of
texels whose rows end inside a line (the same rule as the copy back's splice), now goes
on the host. Its keep and the copy of the texels the commands left go into two parts of
a Shared scratch (ScratchKind::ShadowHost; the fetch view is not used, so the changed
texels are always copied). The encoder records only that copy, and a host step of a
batch of its own (Deferred::ShadowSplice, now carrying HostWrite::Splice or ::Merge)
compares the parts eight bytes at a time and stores each byte that differs into the
pages with atomic byte stores. Such a texture joins no run of passes (render.rs), so
each pass merges as its encoder ends. Devices where both checks passed keep the
kernel merge.

Why: the Iris probe (m3-max-35510) showed the merge kernel's stores losing CPU writes
to padding bytes in the line that holds each row's last texels, as the copy back did.
A CPU store changes only the bytes it stores, so the bytes the commands left, and
every byte the CPU writes meanwhile, stay. Metal keeps those bytes
(conformance probe row_padding_writes.m).

Where the merge stays on the GPU (FAST-PATHS known gaps): merges recorded between a
pass's instances, before a tile dispatch, into a held command buffer, at a segment's
end, merges through a copy, and the runtime's own Shared memory.

New WorkCounts fields: shadow_merges_on_host, shadow_merge_host_nanos.

Tests: shadow_write_lines now asserts the Draw rounds (keep + merge) put back no byte
and go on the host under unanswered verdicts, and follow the measured verdicts in the
second test. A new test, costs_of_a_write_back_spliced_or_not, prints the median
command-buffer time of a copy back and a merge for 34x34 and 1920x1080 RGBA16Float,
with verdicts unanswered and passed.

Degradation kinds added: none.

Verified (fplend): msi m3-max-35675 at bdb1e2cbae clippy (runtime, all targets/features, -D warnings) 0,
touched unit tests 3/3, api_signatures + fast_paths 34/34; msi 35689 clippy --cfg m2v_gpu 0.
PHOENIX suites (35711), lavapipe, rustdoc and the Iris cost run follow.
2026-11-16 01:05:03 -08:00
Anees Iqbal 8ff90fd10c completion_latency: the guest-shaped leg takes the device's own queue plan
What: guest_shaped_completion_latency makes its device with queue_limits: None.

Why: the runtime tests' default queue limits (TEST_QUEUE_LIMITS, a round robin of two VkQueues)
refuse a third program queue, so the leg panicked at its third queue on PHOENIX (job
m3-max-35637), before and after alike. A guest's queues take the device's plan.

Verified: the next PHOENIX job runs it.
2026-11-16 00:48:21 -08:00
Anees Iqbal 4538751968 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 00:47:47 -08:00
Anees Iqbal 9ea0a9c1f6 RUNTIME 2431: Shadows: splice a copy back into host pages on devices that write lines back
What: a shadow's copy back (Step::Back) of a 2D texture's image, or of a texture
buffer's staging buffer, into a no-copy buffer's host pages is spliced where the
device's check of those pages (DmaBuf or Pointer) failed, or has not answered, the
copies or shader writes of texels whose rows end inside a line (Access::Copies or
Access::Writes of RowEnds::InLines, Failed or Pending). The GPU copies only the
columns that fill whole lines of memory (nonCoherentAtomSize): one region a slice
where its rows are a multiple of a line apart, else one a row. Each row's head and
tail columns go by the GPU into a line-aligned region of the command buffer's arena,
and a host step of a batch of its own (Deferred::ShadowSplice, after the work before
it completed) copies them into the pages a byte at a time, as the CPU's stores go.
The encoder notes the truth's writes after the step. A copy whose texels fill whole
lines alone copies back as before; a device where both verdicts passed copies back
as before. New count WorkCounts::shadow_copies_back_spliced.

Why: on the Iris Xe (ANV) a copy of texels into a buffer's rows writes back the
64-byte line holding each row's last texels whole, putting back older values over
the CPU's writes beside them. The lane's probe (m3-max-35510) lost 3,539 to 14,319
bytes a kind in 300 command buffers through a shadow's copy back and merge, where
Metal keeps every such byte (row_padding_writes.m). This breaks Metal's contract on
the guest's bytes; the merge is the next change.

Where the copy stays (docs/FAST-PATHS.md, known gaps): a copy back between a render
pass's instances or before its tile dispatch, into a held pass's command buffer, at
a segment's end recorded at a commit or a host step, of rotated, two-plane, tiled or
heap depth/stencil textures, and into the runtime's own memory.

Tests: tests::shadow_splice (the cut run as GPU and CPU over a map of host bytes:
every texel once, no GPU byte in a shared line, every shape of texel, width, pitch
and phase); tests::shadow_write_lines (the probe made a device test: the guest's
34x34 RGBA16Float target over dma-buf pages, buffer and plane forms, a clear's copies
back put back no byte the CPU wrote beside them and are spliced; and a copy back
spliced exactly as the device's measured verdicts say).

Degradation kinds added: none.

Verified (fplend): msi m3-max-35614 clippy 0, tests 0, signatures 0; 35623 clippy m2v_gpu 0;
lavapipe 35625 clippy m2v_cpu_icd 0, 216 passed, rustdoc 0; PHOENIX 35632 (um790) in-place +
shadow suites 287/287, shadow_write_lines 2/2: under the measured verdicts (Copies and Writes
Passed) 0 spliced; under HostPageTexturePolicy::Shadow (no check, verdicts Pending) every copy
back splices (+300 in 300 rounds, 0 bytes put back). The Iris run follows.
2026-11-16 00:46:56 -08:00
Anees Iqbal 45d2a94af9 runtime README: name the scheduler_at_commit_left_* counts beside the other at-commit counts
What: the commit_and_submit paragraph lists the at-commit work counts; it now names the
scheduler_at_commit_left_* counts too: why the call made no pass, or made one that left its
command buffer to the scheduler thread, by reason.

Why: the counts are public (WorkCounts) and consumer-facing; tip 1 added them without naming them
in the README.

Verified: documentation only.
2026-11-16 00:44:34 -08:00
Anees Iqbal 574223a971 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 00:39:59 -08:00
Anees Iqbal 82db0086aa RUNTIME 2430: Scheduled waits outside its queue's context until its submission handlers ran
What: CommandBufferShared::schedule() now marks the command buffer's transition to Scheduled as
owed (State::scheduled_owed). Where that transition waits for submission handlers
(state.submitting), schedule() no longer posts it at once; it is held back (scheduled_deferred).
The thread that runs the submission handlers (run_submission_handlers) then runs it where it is
plain and its context is idle (run_alone, no handler-thread wake), or posts it. A command buffer
whose work completes before its submission handlers ran has its Finished transition posted, never
run on the waiter, and that transition runs the owed Scheduled step first (run_scheduled,
claimed once under the state lock), waiting there for its own handlers. A Scheduled item that
finds the step already run does nothing.

Why: the Scheduled transition used to be posted into the queue's serial context as the batch
went, and slept there (run_scheduled, while state.submitting) until the submission handlers ran.
Every later item of that context waited behind it, so the completion of the queue's previous
command buffer, seen on time, was posted late by as long as the next command buffer's handlers
took to run. reims's exacttail trace (780M, RADV, Exact, ca6259f7d1) found nearly every late
completion posted into a line that was running the next buffer's Scheduled transition, begun
60-290 us before the GPU end. With the previous commit the handlers run at the end of their own
pass, but the parked transition still held the line for the rest of that pass. Now a command
buffer's completion never waits for a later command buffer's submission handlers. It waits for its
own only where its GPU work ended before they ran.

Metal's orders kept: submission handlers before Scheduled; each command buffer Scheduled (its
scheduled handlers run) before it completes; each queue's Scheduled transitions in submission
order (the handlers' Turns tickets order the posts); completed handlers in commit order (the
waiter's turn order is unchanged). A command buffer that fails before it is scheduled owes no
Scheduled step and runs none.

Check: tests::submission_turns::a_completion_waits_for_no_later_submission_handler_{exact,grouped}.
A queue's waiter is held before it publishes a first command buffer's completion
(Point::Publish) while the queue's next command buffer is submitted. That command buffer's
submission handler then waits up to 10 s for the first one's completed handler. Before this change
the second's Scheduled transition, parked in the queue's context, held the first one's completion
behind it, so the wait timed out. Now the completed handler runs while the submission handler waits.

Also: tests::completion_latency::guest_shaped_completion_latency, an ignored measurement of a
guest's frames under CompletionPolicy::Exact (GPU end -> wait returned -> seen -> handlers, p50/p99/max,
three legs: plain, with submission handlers, and with a 250 us pause after each vkQueueSubmit),
and a test-only trace::seen_of.

Verified (complat): msi m3-max-35620 at de5ae45083: build, clippy -p metal2vulkan-runtime
--all-targets --all-features -D warnings (plain and --cfg m2v_gpu), unit 44/44, api-signatures
--check, all 0; lavapipe release 116/116 (scheduler, inbox, completion, submission_turns,
commit_and_submit, waiter_submits, held_step_order, ...) including both checks under Exact and
Grouped. Negative control m3-max-35597 (tip 1 + check 2 without the deferral): check 2 times out
at 10 s under both policies. PHOENIX suites and the PHOENIX latency bench follow.
2026-11-16 00:39:16 -08:00
Anees Iqbal d70b808ee8 Re-bless the golden hashes, the engine fixture tables and the authored compile census at 39dc658503
SEMANTICS 2133 (OpenCL 1D images through a variant) and 2134 (a uniform view's storage twin
decorated NonWritable, the Iris profile) changed translation output, and RUNTIME 2428 added the
owned fixture fan_clip_distances. Tables re-blessed on development, as CONTRIBUTING.md says.

Verified: m3-max-35616 at 39dc658503 (bless_engine_inventory 0, bless_golden_hashes 0,
bless_engine_goldens 0: golden_hashes.tsv, public_fixture_expectations_engine.tsv and the new
air_input printout); m3-max-35617 (corpus-triage --audit authored-compile --bless, exit 0;
authored-compile.tsv 991 rows rewritten).
2026-11-16 00:36:10 -08:00
Anees Iqbal 39dc658503 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 00:28:08 -08:00
Anees Iqbal 1cfa70ee32 RUNTIME 2429: Scheduler: run each pass's submission handlers right after that pass, not at the round's end
What: the scheduler thread's round made a pass, then kept passing while commits kept arriving
(Inbox::look_again), and only after the last of those passes ran the after-work: storage-form
settles, the owed completion turn, the submission handlers in their Turns tickets, and the holds.
Now Inbox::pass_each runs each pass's after-work once that pass let go of the lock and counted
out, before the look that may pass again (round() -> let_go per pass). Inbox::pass,
which only the tests called, is gone; they go through pass_each by a test-only trait.

Why: a command buffer's transition to Scheduled waits for its submission handlers
(run_scheduled, while state.submitting), and its queue's context line waits behind that
transition, so the completion of the queue's earlier command buffer was posted that much late.
reims's exacttail trace (780M, RADV, Exact, ca6259f7d1) saw the scheduler on CPU for 1.2-6.3 ms
of back-to-back passes (240-267 us per submit info), up to 22 ms on a first open, with the
handlers waiting for all of it. The scheduler and Inbox docs already said the handlers run right
after their pass; the code did not.

Also: commit_and_submit's own pass now counts why it left its command buffer to the scheduler
thread (WorkCounts::scheduler_at_commit_left_*). Two of the counts are for when it made no pass:
the commit was already taken in, or a pass was under way. The rest are for a pass that ran and
submitted nothing, by why its command buffer's first batch stayed in the order: gone, behind its
own queue, behind another queue, an event wait, checks, a host step, a binary wait, an unshared
hold, or other. reims's counts show the 780M making ~7.5k at-commit passes a window that submit
almost nothing. Which condition leaves those batches is open; these counts are meant to answer it
in the next walk. The predicates plain/plain_ready now answer why (LeftAtCommit) instead of a
bool.

Checks: tests::submission_turns holds the scheduler's pass in a submission (Point::FirstWork)
while another queue commits. The first command buffer's submission handler must run before the
later commit's submission is called (its kernel_end_time). Under the old round, the handler ran
after it. The test runs under CompletionPolicy::Exact and ::Grouped. tests::inbox has a unit test
of pass_each's order (pass, after, pass, after) that also shows the thread is uncounted during
its after-work.

The second caller of Scheduler::submit_at_commit (a commit_and_submit whose last render
encoder's end the lowering thread lowered) names its command buffer too.

Verified (complat): msi m3-max-35593 build 0, clippy -p metal2vulkan-runtime --all-targets
--all-features -D warnings 0, unit nextest (inbox|scheduler|left::|work_counts|completion)
44/44, api-signatures --check 0. The device check and its negative control run on lavapipe
(35596/35597) after landing.
2026-11-16 00:27:19 -08:00
Anees Iqbal e528dfbe2f Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 00:24:31 -08:00
Anees Iqbal bd3c1a8c37 RUNTIME 2428: A refused fan-out variant's region-by-region pipeline is begun at commit
Where the translator refuses a draw's fan-out variant for the device's
limits (pipeline::link::fan_out: a vertex function's clip distances past
what the device carries beside the fan-out's four, a geometry stage of
barycentric weights, a layer or a viewport), the host step's draw settles
again asking for none and draws region by region. An execution's settle
at commit only dropped the error, so it began no pipeline for such a
draw, and a FanOut host step made the regions variant's VkPipeline itself
on the first frame of the state.

One function now decides the refusal for both (render.rs fan_out_refused).
settle_draw_of settles again without the fan-out outside the encoder's
fan-out, as the step does, so the regions variant's pipeline is begun
with the key the step's draw looks up (its multi-draw viewports included,
region_batch); under the encoder's fan-out it settles nothing for the
draw, which that fan-out does not take.

Test: rate_mapped_fan_out::a_refused_fan_out_variant_s_first_frame_makes_no_pipeline. The owned
fixture fan_clip_distances holds fan_clip_triangle, a vertex function of six clip distances
placing each vertex where tob_triangle does: with the fan-out's four it needs ten, past a
device's eight, so the translator refuses its fan-out variants. The workload's plain commands
take it (Workload::placed_by), and under FanOut the test checks, on a fresh device's first
executed frame, that only the command across w = 0 is probed, flagged and drawn through the
region-copy variant, that the host step makes no VkPipeline itself
(WorkCounts::host_step_pipelines_made), and that the pixels are the encoder's.

Fixture: engine/fan_clip_distances.metal (our own MSL; .ll and .air.ll from
scripts/regen-air-fixtures on the M3, job m3-max-35588, SDK 27.2).

Verified (rmkey): lavapipe m3-max-35590 with the fix: 0 made at the step, counts [1,1,0,1],
pixels equal, 17/17 rate_mapped_* tests, clippy (m2v_cpu_icd) 0. Without it (control commit,
the settle's retry disabled; gem10 m3-max-35591): 1 made at the step. The fixture's
expectation and golden rows re-bless on development.
2026-11-16 00:23:39 -08:00
Anees Iqbal 2284a63c0d Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-16 00:21:24 -08:00
Anees Iqbal a585a74686 SEMANTICS 2134 / RUNTIME 2427: A uniform view's storage twin is decorated NonWritable
What: memory::views::declare_twin states the twin's binding unwritten
(ModuleBuilder::unwritten_buffer). The serializer then decorates the twin's variables NonWritable,
its word view and its uvec4 view, where its own walk finds no store reaching them. No store goes
through a twin: TwinMem's write, write_bits, write_unit and write_vec all refuse.

Why: on the Iris profile (DriverWorkaround::PushReadsLengthenThreadPayload, ANV, Mesa 26.2.6)
RUNTIME 2413 reads a kernel's constant slot through its storage twin where the slot's
RangeAtBindOffset holds. The twin was not decorated NonWritable, because serialize::non_writable
only takes the bindings the lowering states unwritten. ANV runs nir_opt_access
(anv_shader_compile.c), which marks a storage buffer's loads reorderable only where the variable
is NonWritable or the shader writes no buffer. A kernel that writes its output therefore kept
every twin load apart, wherever it stood: no CSE, no hoisting, no merging. The uniform view's
loads, a uniform buffer's, are always reorderable, and the driver folded them.

Metal's compiler leaves a constant buffer's repeated loads for its own backend to fold. One guest
depthwise convolution kernel loads its params.srcSize (<4 x i32>) four times in every iteration
of its tap loop and its dstSize about ten times, and every inlined sample reads its ndArrayParams
again. Read through the twin, each of those loads ran per thread. A benchmark's Iris walk rose
from 754 to 1120 us a dispatch on that workload between pins 825997e49c and 44505b3807, and
825997e49c rebuilt matched the old walk (771). dispatch_chain's bump_wide reads its constant
word once, so the 2413 A/B could not show this. --binds params now can.

Aliasing (why NonWritable states nothing the uniform view did not):
- storage_twins gives a twin only to a slot whose form is a uniform view by its own window. That
  is view_kind's uniform view: a Metal constant address-space slot that no store or atomic of the
  function reaches, with a Bounded window, never the per-stage storage-buffer fallback.
- bind::instantiate::bind_buffers writes the twin's descriptor with the uniform binding's own
  buffer and DescriptorRange, pushed once for both.
- So the twin's bytes are exactly the uniform view's, under the same rule that chose a uniform
  view before the twin existed (the base form, 825997e49c).
- A uniform buffer is read-only to the module, and nothing orders it with a write through another
  descriptor of the same dispatch. Metal's constant address space is read-only for the dispatch.
  A guest that binds one MTLBuffer range as both a constant and a written device slot got no
  ordering from the uniform view either; the decoration claims no more than that.
- The runtime binds a twin nowhere the uniform view is not bound. A slot bound to nothing binds
  both from the device's zero buffer (RUNTIME 2420), which no command writes.

Docs: views.rs (the module docs and declare_twin), ModuleBuilder::unwritten_buffer,
serialize/non_writable.rs, the workaround's profile doc, docs/API.md section 5.

Test: engine_access's
a_kernel_uniform_view_reads_its_storage_twin_at_its_bind_offset asserts that every variable bound
at the twin's binding is decorated NonWritable. It fails without the change, where no twin
variable is.

SEMANTICS_VERSION 2134: translation output changes on the Iris profile alone (the twin's
decoration). The golden hashes and the authored compile census re-bless on development. New
Degradation kinds: none.

Also: dispatch_chain gains --binds params and params-off (bench only), a kernel that reads its
constant block again in a loop: params reads it through the twin at its bind offset
(RangeAtBindOffset 1), params-off through the uniform view at its residual (the base form).

Verified (ftreg, msi m3-max-35578 at 00a41f052f): clippy -p metal2vulkan -p metal2vulkan-runtime
--all-targets --all-features -D warnings 0; twin/NonWritable tests 44/44; negative control
(views.rs before the change) fails engine_access's twin test with [(12, false)]. Release A/B
arms built (35573/35574/35576); the Iris A/B follows. RUNTIME 2427: the translation changed.
2026-11-16 00:20:20 -08:00
Anees Iqbal be19769dcd rate-mapped tests: a boxed host step's first frame makes no pipeline; the first frame's multi-draw batch
a_host_step_s_first_boxed_frame_makes_no_pipeline draws the boxed-draws
workload's executed frame first on a fresh FanOut device and checks that
its host step boxes the four patches and makes no VkPipeline itself
(WorkCounts::host_step_pipelines_made). The fan-out test's first-frame
line now prints the regions a multi-draw takes, the evidence that the
regions variant drew several regions a command (region_batch).
2026-11-16 00:13:48 -08:00
Anees Iqbal 0953deca29 rate_mapped_fan_out: a host step's first frame makes no pipeline under either policy
A device's first frame of the commands' states, with no encoder draw
before it, counts the VkPipelines its host step makes itself
(WorkCounts::host_step_pipelines_made) under FanOut (the eight's pattern
and the parted probe's commands) and under Exact. The earlier tests drew
the encoder's frame first, whose draws may make the step's keys ahead,
so they could not see a settle at commit that keys a pipeline otherwise
than the step.
2026-11-16 00:13:48 -08:00
Anees Iqbal 2da9cfbbdc Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by hand after land-pkt.sh's

fast-forward step failed once (the lane removed its tree during the landing).
2026-11-16 00:12:19 -08:00
Anees Iqbal c1de99a1b3 Docs: a remap under a live pointer import is unspecified, not taken anew
63bbaa086d removed the submission checks' follows check, which remapped
pages under a live host-pointer import, outside VK_EXT_external_memory_host's
contract, and rewrote the FAST-PATHS gap, HOWTO and host_range_remapped
docs: what a no-copy buffer reads after a remap under it is unspecified.
Four follow-era sentences remained:
- DeviceShared::submit_checks still named a check of whether pointer
  imports follow their address (only Merge and ImportTax remain);
- HostAliases::remapped and host_range_remapped_now said a driver's
  pointer import takes the remapped pages anew at its next submission;
- WorkCounts::host_remaps_over_imports (public) said ANV's userptr on
  i915 takes its pages anew, all of them, at its next submission.
Each now says what is counted and that what such an import reads is
unspecified (docs/FAST-PATHS.md, known gaps). Comments and doc text only.

Verified: comments only; grep for 'follow', 'taken anew' and 'takes
anew' in the runtime's sources and docs finds no other.
2026-11-16 00:09:12 -08:00
Anees Iqbal 8b70cf1ca7 FAST-PATHS: what listing a render target's sibling formats costs its compression
The view bullet now states the measured cost of cdcd787fb8's listing of
a render target's channel-order sibling formats (BGRA8Unorm and
BGRA8Unorm_sRGB of an RGBA8Unorm texture) in its image's format list,
which lets a pass render into such a view of the image in place.

Measured with tests::reordered_list_compression (ignored probe, carried
archive of d6366dcf65 built in m3-max-35552 on msi), the runtime's own
plan of a 2048x2048 Private ShaderRead|RenderTarget texture, its
VkImageCompressionPropertiesEXT::imageCompressionFlags, Mesa 26.2.6:
- Radeon 780M (PHOENIX, m3-max-35557) and RX 7900 XTX (NAVI31,
  m3-max-35558): DEFAULT as planned, without the sibling's formats and
  not mutable, for RGBA8Unorm and BGRA8Unorm.
- RX 550 (POLARIS12, m3-max-35556): DISABLED in all three forms,
  the not-mutable control included: the driver compresses no render
  target image of the runtime's usage there, so the list costs nothing.
- lavapipe (m3-max-35553): no VK_EXT_image_compression_control.
ANV and NVIDIA not measured.
2026-11-16 00:09:12 -08:00
Anees Iqbal d6366dcf65 Probe: name imageCompressionFlags, which ash prints no Debug of
Verified: m3-max-35546 (msi) failed E0277 on the Debug print; this names
the four values instead.
2026-11-16 00:05:01 -08:00
Anees Iqbal 0bcdfad466 Probe: what a render target's sibling formats cost the driver's compression
An ignored measurement (tests::reordered_list_compression): the runtime's
own plan of a 2048x2048 Private RGBA8Unorm and BGRA8Unorm render target
(ShaderRead | RenderTarget, no PixelFormatView) made on a second VkDevice
of the runtime's physical device with VK_EXT_image_compression_control,
as planned (the channel-order sibling's formats listed, cdcd787fb8),
without the sibling's formats, and not mutable at all (the control), each
image's VkImageCompressionPropertiesEXT::imageCompressionFlags printed as
REORDERED-DCC lines.

Why: cdcd787fb8 lists the sibling's formats in every such render target's
image so a pass renders into a BGRA8 view of an RGBA8 texture in place;
its compression cost was expected from Mesa's sources (RADV before GFX11
keeps no DCC for a list of differing channel orders), not measured.

Verified: not yet built.
2026-11-16 00:03:04 -08:00
Anees Iqbal 1448ca32d6 scheduler_held_wakes: read the counts once the scheduler sleeps again
The pass that sends a batch counts a slice's rescue only after its
submission returned (scheduler/mod.rs, `pass`), so the batch's command
buffer can complete, and the test's poll see it, before that count is
made. On gem10's PHOENIX under load (round 44505b3807) the held-wake
test read 0 rescues while its steps showed the slice's pass send the
kept group and then "a slice's rescue" 350 us after the kept fill's
completion was published: the test, not the product, was wrong.

Each of the file's three reads of the counts after the work now waits
for the scheduler's thread to sleep again (scheduler_wakes' `asleep`,
now pub(super)), when no pass is under way and its counts are made.
The two tests that assert no rescue came read too early in the same
way and could pass with a rescue uncounted. event_wake_bench and
submit_long_bench print the same delta and take the same wait.

Verified: see the lane's lavapipe control (a 20 ms delay before the
count: the old test fails, this one passes) and the PHOENIX run.
2026-11-15 23:41:02 -08:00
Anees Iqbal 25c7f896f9 alone_batches: the check's device takes CompletionPolicy::Grouped
The lane's devices take DevicePolicy::exact_answers(), CompletionPolicy::Exact
among them, so the check's validated device grouped nothing and counted no
reason; the PHOENIX rerun (m3-max-35449) showed the step's batch submitted at
commit with none counted. The check now sets the default Grouped, as the
grouped_submissions checks do. No runtime change: the steady_presents legs,
on a device of the default policy, accounted for every batch.
2026-11-15 23:34:18 -08:00
Anees Iqbal 3a0e4b35a2 alone_batches: fill each buffer once before the steps, and report each step's batches
On PHOENIX (job m3-max-35424) the check's first step, a fresh queue's first
command buffer filling a buffer never used before, counted no reason where
unknown run was expected. Each buffer is now filled once on a queue of its own
before the steps, so no step takes a buffer's first work, and each step prints
the batches it made (submitted or held, grouped, at commit), the command
buffers taken with no submission and the kernel submissions, so a step that
counts nothing says where its batch went.
2026-11-15 23:34:18 -08:00
Anees Iqbal 6483bb9973 OpenCL 1D lines: the mechanism table and two Entry literals name the new items
device::tests::mechanism lists every RuntimeFact by index and its expected mechanism:
OpenClLineTexture is 103, a Variant. The uniform and memory-plan tests build air::Entry field
by field and name open_cl_1d_images (job m3-max-35395 stopped at E0063/E0004 there).
2026-11-15 23:16:24 -08:00
Anees Iqbal 7eeb634944 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 23:16:07 -08:00
Anees Iqbal b034129644 RUNTIME 2426: Grouped: count each batch that went alone by why, and unshared queues' batches
Under CompletionPolicy::Grouped a batch refused a place in a group while no group
was held went alone and was counted nowhere: group_ends_* count only groups that
held a batch. So the consumer's steady Launchpad walks (batches_grouped 0,
group_ends_drained 1 a window) could not say why nothing grouped.

Each batch on a VkQueue whose batches group that goes in a kernel submission of
its own now counts once, by the first reason in group::Alone's order
(WorkCounts::batches_alone_* and batches_held_alone_*): an unshared queue's
batch, a binary wait or signal (a completion sync file), a sparse update, pieced
work, a fence, an unknown or too long expected run, first work or a wrapped image
with no group held, a committing thread's submission; or, held in a group that
went holding it alone, what sent that group (at most one earlier submission in
flight, an unshared queue's hold on the VkQueue, a head waiting for the GPU,
another queue's handlers, a waiter, kept with none joining, a batch that could
not join, or other). Group::keeps answers why it does not keep. And
batches_of_unshared_queues counts unshared queues' batches on every device, so a
walk under either policy gives their share.

The validation lane's alone_batches checks one batch per reason it can make
deterministic (unknown run, at commit, one pending, a completion sync file, an
unshared queue, beside an unshared queue) on a device that groups, and none
counted elsewhere; steady_presents (ignored, a measurement) runs a steady
present shape with an unshared compositor queue and prints the spread.
Conformance classes the counts that follow what the host had seen complete as
not the case's own. API signatures blessed.

Also 4d71df7f28 (a type alias for clippy) and 5e04b74b48: FAST-PATHS: grouped submissions' measured lateness, the unshared exclusions and the alone counts

Row 38 edited in place, docs only. It now states:
- the measured cost of the fast form in the consumer's guest walks on RADV at
  ca6259f7d1 (lateness of command buffers seen complete after a later one's
  end, p99 18.4 ms against Exact's 2.1 ms on the 780M, 5.1 against 2.4 ms on
  the XTX), against the Metal oracles' p99 of at most 0.28 ms;
- that the bounds are on expected runs, so a later batch running longer than
  its queue's recent ones makes earlier members late by its actual run, which
  no bound set ahead can cap;
- that CompletionPolicy::Exact adds none of this lateness;
- that an unshared queue's batches join no group on a VkQueue held back for it
  and no group is kept there, which on a device of one graphics VkQueue (RADV,
  ANV, lavapipe) keeps no group of any queue: read from group.rs (Group::keeps,
  CommandBufferShared::groups) and create.rs's queue plan;
- the new per-reason counts (batches_alone_* and batches_of_unshared_queues).
The fast form's bounds are unchanged (owner's call, AGENTS.md rule 1).

Verified in the lane: m3-max-35367 at 71158a8ea4 plain clippy (runtime, validation, conformance,
metal2vulkan) 0, api_signatures 3/3, conformance 119/119, runtime group tests 12/12;
m3-max-35394 at 5e04b74b48 lavapipe clippy m2v_cpu_icd 0, alone_batches + grouped_submissions
16/16. Still running when landed: clippy m2v_gpu, plain clippy + fast_paths + rustdoc at the tip,
one PHOENIX run of the counts (path-ran evidence). Bounds unchanged.

New Degradation kinds: none.
2026-11-15 23:15:15 -08:00
Anees Iqbal 4cbe5d66e1 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 23:14:29 -08:00
Anees Iqbal 59fc85ea83 SEMANTICS 2133 / RUNTIME 2425: OpenCL mode: a 1D image bound to a real 1D texture reads it, through a variant
An OpenCL-mode kernel declares each image1d_t / image1d_array_t slot as the 2D texture of
height 1 Apple's OpenCL binds (canon::opencl::entry, canon::opencl_1d). A real 1D or 1D array
texture is a VK_IMAGE_TYPE_1D image, which takes only 1D views (Table 18,
VUID-VkImageViewCreateInfo-subResourceRange-01021), and a 1D view cannot sit in the slot's
Dim 2D descriptor (VUID-vkCmdDispatch-viewType-07752). So the binder wrote the declared 2D
type's neutral (PlanDiagnostic::IncompatibleBinding) and every read answered zero, outside
both measured answers (Radeon Pro 5300M: the 1D values; UHD 630: layer 0 of the array).

Now a per-slot variant keyed by the bound texture's type:
- air: Entry::open_cl_1d_images records the texture indices of an OpenCL-mode kernel's 1D
  images; SpecRequest::open_cl_lines names those a 1D texture is bound for, whose parameter
  keeps its texture1d type (opencl::entry) and whose operations stay 1D (opencl_1d::expand
  skips a call whose texture operand is that parameter).
- The kernel states RuntimeFact::OpenClLineTexture { slot } (Mechanism::Variant) per 1D image,
  in the base and the variant alike; nothing else states it.
- The compute plan puts such a slot in VariantKey::open_cl_lines where the shape binds a
  Type1D (Type1DArray) texture at a 1D (array) image read by the kernel
  (bind::plan::slots::open_cl_line_variant). VariantKey::lowering_inputs carries it to
  LoweringInputs::open_cl_lines, the specialized-entry cache key and SpecRequest. The variant's
  interface states the slot Type1D / Type1DArray, so its plan binds the 1D view and states the
  same key. The answer is the 5300M's.

With the set empty (Apple's 2D bindings) canon, the SPIR-V and the VariantKey are as before;
the base artifact gains only the OpenClLineTexture facts. The reflection still states the 2D
types. No runtime source changes.

Tests: canon::tests::opencl::opencl_1d_images_bound_to_1d_textures_keep_their_1d_operations,
engine_opencl_mode::an_opencl_mode_kernel_reads_real_1d_textures_through_its_variant and
a_plain_2d_texture_slot_given_a_1d_texture_binds_the_neutral; the runtime's
opencl_mode_1d_images_read_real_1d_textures (the repro).

SEMANTICS_VERSION 2133. api_signatures blessed (5 records); REFUSALS unchanged; docs/API.md's
OpenCL images paragraph.

Also e1aba1ad67 (the repro test), 9f3b309b65 and 8f2677c0ae (compile fixes: an Idx import; every SpecRequest literal names open_cl_lines).

Verified in the lane at 8f2677c0ae: lavapipe (m3-max-35393) OpenCL-mode runtime tests 19/19, the
new opencl_mode_1d_images_read_real_1d_textures among them (it failed at e1aba1ad67, m3-max-35348:
[0,0,0,0] for [10,11,12,13]); the 2D height-1 read and write tests pass at both. air OpenCL tests
9/9 (m3-max-35386). Still running when landed: the translator's engine_opencl_mode and api tests,
clippy x3, rustdoc, executor parity (runtime_lane::executions, runtime_run), the probe comparing
the guest 2D path's SPIR-V, facts and plan at base and tip, the PHOENIX run.

RUNTIME 2425 because the runtime's variant choice moves (bind::plan::slots); no runtime source
changed. New Degradation kinds: none.
2026-11-15 23:13:43 -08:00
Anees Iqbal 84a75db279 HASHED_BESIDE: the measured thread start and the overlapped make
A scoped thread's start and join measured 22 to 33 us at the median on
the Ryzen 7 7840HS (PIPELINE-MAKE-THREAD, job m3-max-35318), and the
14.6 MB metallib's make 8.1 to 9.3 ms with the overlap against 14.9 to
15.5 ms without it, under a load average of 8.9 on 16 threads.
2026-11-15 22:40:28 -08:00
Anees Iqbal 60e11c3c9d library_hash_records: a kernel of one entry point, as a metallib function's module is
The metallib's container check takes a function's module to declare
exactly one entry point; the examples fixture declares five, and the
state's creation was refused (ContainerMismatch). The engine fixture
store_const is one kernel.
2026-11-15 22:39:04 -08:00
Anees Iqbal cc6efc676f Library: a metallib of 1 MiB or more is hashed beside its parse
Library::from_metallib and Library::parse made a metallib in two full
passes over its bytes, one after the other: the parse checks each
function's HASH against the SHA-256 of its bitcode, then the library
takes the SHA-256 of the whole file as its content hash. On the walk's
CPU (Ryzen 7 7840HS) a make costs 0.92 ms per MB (14.6 MB in 13.5 ms),
about half of it each pass, and a guest waits for its library's make:
the walk's largest library took 121 ms at each workload pass's start.

From 1 MiB on, a metallib that is no universal file has its whole-file
SHA-256 computed on one std::thread::scope thread while the parse runs
its checks, so the two passes overlap. The content hash, the library
and the error a refused library answers are the inline path's: the
parse is the same call, its error comes back first and unchanged, and
a hash thread that cannot start or panics leaves the hash to the
inline computation after the parse. Below 1 MiB, and for a universal
file (whose content is the AIR slice only the parse finds), the path
is exactly the old one. The threshold's source is in HASHED_BESIDE's
doc: about 0.45 ms per MB spared against a thread's start and join.

Checks: tests::library_hash_beside (translator) counts the parses that
hashed beside (a test-only per-thread count, which stays at 0 without
the change) and compares a 2 MB metallib's library, field for field
and whole, with the inline path's over the same bytes (the same
metallib as a universal file's AIR slice), and a refused one's error
with the inline refusal's; tests::library_hash_records (runtime, a
device test) compares the two libraries and a state's pipeline record
from each, byte for byte.
2026-11-15 22:39:04 -08:00
Anees Iqbal 5570004b70 Bench: a library's making per MB, and a scoped thread's start and join
PIPELINE-MAKE-LIBRARY prints each size's median make per MB, and
PIPELINE-MAKE-THREAD what starting and joining a scoped thread costs the
calling thread: the two figures a large library's content hash computed
beside its parse is weighed by. The profiler target goes: perf is not
permitted inside the cluster's jobs, so nothing ran it.
2026-11-15 22:39:04 -08:00
Anees Iqbal 8cd4ddd838 Bench: report the cold round after its release; time a record's making piece by piece
PIPELINE-MAKE-RECORD times what a pipeline record costs a creation where
the device has a hook: the descriptor's clone, its encoding, its reading
back and the comparison with the descriptor (medians of 256).
2026-11-15 22:39:04 -08:00
Anees Iqbal a2699fc45b Bench: a warm compute pipeline state's and a library's making, step by step
PIPELINE-MAKE times what a guest's pipeline compile makes on the calling
thread: the function with its constant values, the compute state, the
six properties a reply reads, and the release, for states that take back
a released variant's objects (kept) and states made while their twin
lives (live), with a pipeline record hook that only counts and without
one. PIPELINE-MAKE-LIBRARY times new_library_with_data of metallibs of
1, 256 and 2048 functions and the lookup of the last function by name.
pipeline_make_profile is a profiler target over the same makings.

The compute creation bench's kernels and helpers are shared with it.
Ignored tests; run in release under m2v_gpu or m2v_cpu_icd.
2026-11-15 22:39:04 -08:00
Anees Iqbal 3a26d3cb90 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 22:37:16 -08:00
Anees Iqbal 662460fe5e RUNTIME 2424: Storage twins take 0 where their kernel reads any other word the binder writes for it
What: the runtime's uniform_residual_form sets every twin's RangeAtBindOffset to 0, as it does
beside a residual read, also where the twin's stage reads under the key another word the binder
writes for it (residual::reads_other_words, from the interface's PushPlacements): a field placed in
its push range or its ArgumentTable, but a slot's SlotBindOffset residual where the key sets its
RangeAtBindOffset, and the DispatchRegion words where the key leaves the stage's MultiRegion 0 on a
variant that does not run a flat grid (a flat grid's one region reads them whatever MultiRegion
says). A root table's or execution status's address, a replay's region record, a slot's guest
base, a texture's levels and every other placed field count wherever placed. keyed_regions passes
the variant's flat_grid; the render callers pass false (render stages have no twins).

Why: RUNTIME 2419 kept a twin's key wherever no other RangeAtBindOffset of the key was 0, so a
kernel with a twinned constant view that also reads a root table's address (a pointer through an
argument buffer, dispatch_chain --binds ptr), or a multi-region region (dispatchThreads' edge
regions and group-count splits, tile and partial-threadgroup plans), or a flat grid's region kept
reading the twin at its bind offset while its thread payload stays long: the 2419 mechanism (ANV,
Mesa 26.2.6, Iris Xe RPL-P: moved arm 154.0 us through the twin against 143.1 us through the
uniform view, job m3-max-34864), whose cost is the stage's push reads (job m3-max-34063).
dispatch_chain --binds 4 reads thread_position_in_grid but dispatches threadgroups with
MultiRegion 0, so its measured twin gain (102.1 against 142.8 us) is kept.

Runtime only: no translation output, plan or artifact moves (the executor and the execution
record's plan check compare plans and artifacts, which the runtime's region keys are not), and no
creation key. Only dispatch keys of a kernel with a twin and such a word move, on the Iris profile
alone.

Docs: residual.rs's module docs and functions, keyed_regions, the workaround's profile doc and
docs/API.md section 5.

Tests: general_form's a_twin_takes_0_where_its_stage_reads_another_word (the twin zeroed where its
kernel reads another word, kept where it reads none, another stage's word ignored) and
a_stage_reads_its_region_under_multi_region_and_every_other_word_it_places (reads_other_words'
cases: MultiRegion 0 and 1, a flat grid, a residual held or not, an unkeyed residual, a root
table's address, another stage's field).

Verified in the lane (m3-max-35286, msi, at def6a68f94; each step's own exit code): clippy
-p metal2vulkan-runtime --all-targets --all-features -D warnings 0; tests::general_form 6/6;
lavapipe runtime_lane::executions + candidate::engine::runtime_run 34/34 (executor parity).
Still running when landed: clippy m2v_gpu and m2v_cpu_icd, rustdoc, the Iris A/B (a twinned
constant view beside a root table address / multi-region region, --binds 4 as control).

New Degradation kinds: none.
2026-11-15 22:36:33 -08:00
Anees Iqbal 51db809d47 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 22:23:54 -08:00
Anees Iqbal 3cd05059be RUNTIME 2423: Compute encoders set aside one bind state per pipeline state lately dispatched, as render encoders do
A compute encoder kept one bind state, its last dispatch's: a dispatch of
another pipeline state than the one before read its table whole, found its
shape again and instantiated its commands again, though its own state's
previous dispatch had planned and instantiated the same. A guest's compute
workloads switch kernel at every dispatch, about one dispatch a compute
encoder (walk counts: 356,723 dispatches, 369,091 instantiations, 226 as
before, planned as before 90%).

LiveDispatch now sets aside the states of up to live_bind::SET_ASIDE (7)
pipeline states dispatched before its last dispatch's, each with its shape,
listing count, ReadFrom, DispatchMemo and Instantiated, under the pipeline
state that left it (held weakly); a dispatch starts from its own state's.
They travel as the state does: parked in the command buffer for its next
compute encoder, given to the device's spares at the commit, every memo let
go there and its sampler states unlisted where the state's are.
live_bind::start_from is the rule both encoders' select share (render's
select now calls it; same choices).

Exact as a draw's: whichever state a dispatch starts from, every field is
brought in place from the encoder's table at that dispatch; kept commands
only while no value kind their plan reads moved since that state's last
dispatch; a memo entry only where every input it compares holds.

WorkCounts: dispatches_from_set_aside, and its split set_aside_commands_kept
/ set_aside_commands_instantiated. Test: tests/compute_set_aside.rs (three
states in turn, an encoder each, within and across command buffers; a
moving output instantiates again; changing setBytes keeps its commands with
the right words; the entry's bytes bounded).

Also 260b91e6b8: dispatch_chain: --states K, dispatch n of a command buffer of the host's time sets state n % K

A program whose dispatches each run a kernel of their own sets another
compute pipeline state for each: --states K makes K states of the
kernel, one creation each from the same function, and dispatch n of a
command buffer sets state n % K (with --host). The HOST line names K.
Bench only; compiled in the dispcall lane's first build job.

Verified in the lane at 1d48a48e1a: msi m3-max-35257 clippy -p metal2vulkan-runtime --all-targets
--all-features -D warnings 0; lavapipe (m2v_cpu_icd, debug) compute, carried, draw_again, live_bind and
compute_set_aside 97/97 (three states in turn, one encoder a dispatch: CB1 instantiated 3, from
set-aside 9, kept 9; CB2 instantiated 0, from set-aside 12, kept 12; words checked; offsets moving
instantiate again 9; setBytes changes keep commands with the new words); api_signatures re-blessed
(+3 WorkCounts fields); release dispatch_chain build m3-max-35261. Still running when landed: the
negative control, PHOENIX compute suites, the PHOENIX bench before/after, clippy m2v_gpu and
m2v_cpu_icd, rustdoc.

New Degradation kinds: none.
2026-11-15 22:23:11 -08:00
Anees Iqbal afc21e4ab9 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 22:22:18 -08:00
Anees Iqbal e01547bb97 In-place check: say why a store failure carries across memory types where a copies' failure does not
What: two doc sentences. carried_store_failures (in_place_check.rs) says it carries a store
failure whatever memory the classes' check pages lay in, and copies_verdict (in_place.rs) says the
store carry crosses memory of any flags, unlike its own same-flags rule (RUNTIME 2417).

Why: the two carries point opposite ways. A carried copies' failure lends a render target's
padding and lies it in place, so it needs evidence measured through memory of the same flags. A
carried store failure makes a class's textures shadows, which keep every byte, and the class
whose own rounds see the line write-back least is the one whose pages the CPU maps uncached,
which the memory's flags need not say: ANV maps its exported memory uncached whatever the type,
and the Iris's dma-buf class passed storage writes inside lines in one fresh check of three for
that reason (aadc115900). Applying 2417's rule there could only turn a carried failure back into
a pass. Decided with the orchestrator: no behaviour change, no CHECK_VERSION bump.

Verified: rustdoc -D warnings of the runtime crate (the job named in the lane's report).
2026-11-15 22:19:12 -08:00
Anees Iqbal 4f35dfd6f9 The authored compile census re-blessed at 44505b3807 (executor v183)
What: corpus/authored-compile.tsv re-blessed at the pin candidate 44505b3807 (m3-max-35212): 2369
cases over 21 profiles, 49749 cells, failed 0, differences 0, regressions 0; 2016 rows take the
artifact digests of ENGINE_EXECUTOR_ABI vulkan-engine-v183 (the executor classes buffer lengths
under the device's range limits, 6e6762cf37..175706d3f2).

Why: the census currency check reads the executor version the table was blessed at (v182 until now).

Verified: census wall 214 s, slowest compile 3.3 s, peak worker RSS 234 MB; golden bless
m3-max-35211 at the same sha changed no byte.
2026-11-15 22:17:39 -08:00
Anees Iqbal 62c3708211 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 22:17:13 -08:00
Anees Iqbal 68731202fe RUNTIME 2422: The buffer recycler parks a command buffer's upload chunks whole: 1024 buffers, at most 64 of them holding their own allocation
What: the recycler's buffer bounds keep 64 MiB and a second, and now admit 1024 buffers, the bytes
bound over the upload arena's largest chunk (upload::CHUNK_BYTES), where they admitted 64. Of the
parked buffers, at most 64 may hold an allocation of their own (Placement::holds_allocation: a
dedicated block, an import of their own pages), the earliest parked of those going first past it
(one no take handed out first); the images' bounds are unchanged (32, any of them alone).

Why: a kernel's unbound written device slot takes a fresh 64 KiB region a dispatch (by design: it
may be stored through), past half the arena's chunk, so one dedicated 64 KiB VkBuffer a dispatch.
Its command buffer's chunks parked as it completed, but the count bound of 64 destroyed all but
64, and the next command buffer of 256 such dispatches made 192 new VkBuffers (the Iris probe
m3-max-35104: 34.5-41 us encoded a dispatch against 19-21 us with the slot bound or read-only,
192 VkBuffers made a round). The bytes (16 MiB) were well inside the bytes bound. Every parked
buffer that holds its own VkDeviceMemory counts against maxMemoryAllocationCount, so those stay
at today's 64: the larger count admits only buffers of shared blocks, which add no allocation.

Tests: tests::recycle_bounds (CPU, the recycler's book): 256 chunks park whole and the next 256
takes find them all, 1024 park and the 1025th evicts the earliest; 64 own-allocation buffers park
beside 100 of shared blocks, two more evict the two earliest own ones and no shared one.
tests::neutral_zeros_shared::steady_dispatches_with_a_written_slot_unbound_make_no_vk_buffer
(device): command buffers of 256 dispatches with the written slot unbound make 0 VkBuffers once
the first's chunks parked, and recycle at least 256; it prints the host time per dispatch against
every slot bound.

Verified in the lane (m3-max-35234, msi, at ee16b6d58d; each step's own exit code): clippy -p
metal2vulkan-runtime --all-targets --all-features -D warnings 0; tests::recycle_bounds 2/2;
lavapipe (m2v_cpu_icd) neutral_zeros_shared 6/6 (steady test: first command buffer 256 made, the
3 steady ones 0 made and 256 recycled each); lavapipe recycle, recycle_bounds, upload_chunk_zeros,
idle_sweep, posted_frees, fresh_pages, churn_counts, clip_bursts, managed_copy_device,
exported_textures, submit_check_device, storage_form_recycle 73/73. Still running when landed:
the Iris timing run, clippy m2v_gpu and m2v_cpu_icd, rustdoc.

New Degradation kinds: none.
2026-11-15 22:16:25 -08:00
Anees Iqbal 44505b3807 dma_buf_in_import: back to 64x32; the 5080's 615.71.09 imports a 72 KiB buffer's dma-buf dedicated too
The 5080 run of the landed fix (b5080 batch m3-max-35075, entry nvinimport-inimport-212418,
615.71.09) passed both tests (TESTS_5080=0), but the main test took the elsewhere branch: "the
buffer's pages in one import dedicated to nothing false (imports dedicated to the buffer 1); the
texture in place false: in the import 0, dma-buf images 0, their imports live 0, source calls 1".
The driver imported the 72 KiB buffer's dma-buf dedicated to the buffer as it did the 24 KiB one,
so the 64x128 size, chosen so that 615.71.09 would take the import dedicated to nothing, bought
nothing there; the module docs said it did.

The texture is 64x32 again, and the docs state what the 5080 measured: a buffer's dma-buf of one
page, or of 72 KiB, imported dedicated to the buffer alone there, though the class's check
passed over the device's own exported memory. The premise gate and the stand-in test stay.

Verified: build, clippy and the two tests on lavapipe in the job that builds this commit.
2026-11-15 21:44:39 -08:00
Anees Iqbal 175706d3f2 The executor classes buffer lengths under the device's range limits, as the runtime does
What: views_told_apart takes the device's BufferRanges and sets every stage table's
buffer_ranges to them, so the executor's bind states state the length class the runtime's
states of the same binds state (RUNTIME 2412 rounds a buffer's class under
BufferRanges::of(limits); the executor kept the defaults, which tell every class apart). The
compute, render and mesh builders (bind_state, compute_shape, graphics::bind_state,
render_shape, mesh_shape) take the ranges; the executor passes its device profile's limits
(case_compiles from the worker device, platform run/execute from the opened device), the
runtime-lane tests their compile device's, and the unit tests the defaults. ENGINE_EXECUTOR_ABI
goes to vulkan-engine-v183: every executed artifact whose plan binds a buffer changes digest.

Why: a BindingPlan states its bound length class (BoundKind::Buffer), so the runtime path's plan
digest differed from the executor's and from the authored compile census's on every device:
candidate::engine::runtime_run's parity (run.census.artifact == on_context.census.artifact)
and runtime_lane::executions' plan digest check failed on lavapipe and the Iris. With both on
the device's ranges the executions test is back to its single digest equality, and the earlier
split of compute_state for its decision-only comparison is folded back.

The authored compile census owes a re-bless after this landing (executor ABI and digests
change); it is re-blessed once, at the next pin sha.

Verification: a lavapipe (cpuicd) job runs the three runtime_run tests, executions, and the
touched engine, graphics, public_cases, argument_buffer_members, worker::compile and
runtime_lane suites, plus a negative control (views_told_apart on default ranges) that must
fail the runtime_run parity; results go to main with the job id.
2026-11-15 21:43:46 -08:00
Anees Iqbal 5328cb1149 executions: the shapes the plan check compares outlive their plans 2026-11-15 21:43:46 -08:00
Anees Iqbal 6e6762cf37 The execution record's plan check classes the executor's lengths under the device's ranges
runtime_lane::executions::the_execution_record_names_each_dispatchs_compiled_pipeline compared the
runtime's plan of its recorded bind shape with the executor's plan of the case, digest for digest.
Since RUNTIME 2412 the runtime's tables carry the device's BufferRanges, so its shape rounds each
buffer's length class up, while the executor's bind state keeps the default ranges (exact
classes), as 2412 meant, to leave executor digests and the compile census unchanged. A plan states
the class it bound (BoundKind::Buffer's length_class, for its instantiation's kind check), so the
two digests differ while every decision is the same (round 5974320352's Iris lane: runtime
[167, 4, ..] against the executor's [199, 127, ..], which was the runtime's before 2412).

The test now plans the executor's case state with each table's buffer_ranges set to the device's
(BufferRanges::of), as the runtime classes lengths, and requires that digest to be the runtime's;
and requires the executor's own plan to make the runtime plan's decisions: its variant,
specialization and descriptor writes. engine::compute_state is compute_shape's state before its
shape, so the test builds it as the executor does. Test only; the executor's shapes, plans and
artifact digests are unchanged.
2026-11-15 21:43:46 -08:00
Anees Iqbal 5e7f470da3 alias_split_device: the one-pass case compares texels only where the texture's image is linear
On RADV PHOENIX (job m3-max-35102) the one-pass case's heap texture is an optimal image, and
252 of its 256 texels read other than the buffer's bytes under them: an optimal image's texels
lie in its own layout over the memory, which Vulkan does not define, nor Metal for a heap's
aliasing resources. The case now asserts the texels only over a linear image (the buffer form
on every device, the heap form where its image is linear) and prints the rest.

Verified: the same run's buffer form read every texel right; lavapipe (m3-max-35085), whose heap
image is not linear either, matched only by its layout.
2026-11-15 21:35:43 -08:00
Anees Iqbal d822ca6ad6 grouped_submissions: behind_running_work's device takes its queue plan
The 5080 lane's red in round 5974320352 (m3-max-34982):
runtime_lane::grouped_submissions::a_command_buffer_committed_behind_running_work_is_scheduled_while_its_group_is_held
failed on the runtime's notice metal2vulkan-queue-limits-reached: "the program's command queue 2 on
a round robin of 1 VkQueue(s), took VkQueue 0, which another took, where the plan's 14 give it one
of its own: the device's queue limits (DeviceOptions::queue_limits) changed that". Those are the
lane's own limits (LANE_QUEUE_LIMITS, round_robin 1), not the driver's: RUNTIME 2405 gave
behind_running_work a second command queue (A's calibration on a queue of its own) and not its
device the plan. LANE_QUEUE_LIMITS's contract is that a test whose work places a second command
queue makes its device at the plan (at_plan), and the harness fails on the notice by design; every
other two-queue helper in the file already does. Only a family of several queues shows it (NVIDIA's
16); on the Iris, lavapipe and RADV the round robin's family has one queue and the limits change
nothing. All three callers (the plain and the consumer-carried held-behind tests, and
the_exact_completion_keeps_no_group_behind_running_work) take the fix.

The adjust calls at_plan(options), with a doc line saying why.

Verified: build and clippy in the job that builds this commit; the three tests on an NVIDIA family
of several queues (the 2080) through main.
2026-11-15 21:34:51 -08:00
Anees Iqbal 365bbd6ed0 in_place_textures: the check's report counts eight classes, DmaBufInImport among them
The Iris lane's red in round 5974320352 (m3-max-34993):
runtime_lane::in_place_textures::a_failed_check_keeps_the_shadow_and_no_record found 128 verdicts where
VERDICTS said 112. VERDICTS was seven classes x eight accesses x two row ends; RUNTIME 2409 added a
class, DmaBufInImport, and the report gives every class on every device, so it is 8 x 8 x 2 = 128.
The report in that log lists DmaBufInImport's verdicts, each Failed as the test forces.

VERDICTS is 128 and its doc names the eight classes. The runtime's PagesClass::ALL is
crate-private, so the lane keeps the count.

Verified: the lavapipe run of the test, in the job that builds this commit.
2026-11-15 21:34:51 -08:00
Anees Iqbal 1db9ad2f97 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 21:34:34 -08:00
Anees Iqbal 92a77c7025 RUNTIME 2421: Continued passes on a device that splits at aliases, where no buffer write meets their images
What: on a device whose driver has DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer
(NVIDIA's 620.70.06 on the RTX 3090), an inline pass's last instance may now stay open, and
the next render encoder may continue it, as on every other device. Before it continues,
EncoderCore::continue_pass checks the group's byte writes (FoldOrder::byte_writes, the
leader's summary or the group's order) against every image the continuing pass uses:
its draws' images (AliasWrites' images noted apart), its attachments, and the uses of the
copies and steps before its later instances (render/inline_splits.rs, waiting_uses), all
of which record into the tail after what the group wrote there. Where one meets, the pass
begins its own instance in its own VkCommandBuffer, the measured form, counted in
WorkCounts::command_buffers_split_at_aliases. Where none meets, it continues and takes
the group's writes as its own (AliasWrites::continues), so what it records into the tail
after its pass is checked as a joining encoder's is.

Why: continuation cut the glass-panel frame's GPU time 11-26% on the 780M and Iris but was
off on the 3090. The open instance itself never holds a buffer write: its draws touch only
attachments, and anything else that records into the tail ends it first. The tail before
it can hold one, though (the leader's earlier inline instances and what records between
them), so the check is what the fact needs.

Also: render_fold's Lane::continuing (622368ab37) goes, since its lanes continue on every
device now. A test-only DeviceShared::aliases_split_forced lets lavapipe take the 3090's path.
New tests: tests::alias_split's continues unit test; tests::alias_split_device's count case,
a copy out of a texture after a continuation, a later instance of one pass reading an
earlier one's buffer write, and a texture over another buffer of the same host pages
(the last two are byte cases for two possible gaps on the 3090).

Also e818e7b442: Continued passes: a pass's uses of bytes count in the alias check, as an aliasing texture's are.
What: AliasWrites notes the bytes of buffers that the commands noted apart use (bytes_apart).
AliasWrites::continues now refuses a continuation where those bytes, or a Bytes use among
the pass's other uses, meet the group's byte writes, besides its images.

Why: a texture whose linear image aliases a buffer's bytes (Storage::Alias) names them as
the buffer's bytes (Texture::image_use), not as an image range. The lavapipe run with the
split forced (m3-max-35002) showed a pass sampling such a texture over bytes the leader had
just written continuing anyway: (1, 1, 1, 2, 0) where (2, 1, 0, 3, 1) was expected. A
continuation is refused rather than guessed at: a draw that reads, through a buffer, bytes
the group wrote also begins its own instance on such a device.

Tests: the count case now reads the written bytes through a texture over a buffer and

And dae7c2cad8: alias_split_device: the counted and copy-after cases read a texture over a buffer alone.

Verified in the lane (m3-max-35085, msi, at dae7c2cad8): clippy -p metal2vulkan-runtime --all-targets
--all-features -D warnings exit 0; lavapipe (m2v_cpu_icd) alias_split and render_fold 36/36; the
count test forced: written read (2,1,0,3,1), quiet read (1,1,1,2,0), unforced (1,1,1,2,0), texels
right. Still running when landed: the 3090 correctness job (alias_split, render_fold; F1-F3 byte
cases), PHOENIX render suites, clippy m2v_gpu and m2v_cpu_icd, rustdoc, the 3090 glass A/B.

New Degradation kinds: none.
2026-11-15 21:33:46 -08:00
Anees Iqbal feb99ed5db dispatch_chain: --heap's heap is tracked, so its encoders are ordered as Metal orders them
--heap placed the words and zeros in a no-copy Placement heap made with
ResourceOptions::shared(), whose hazard tracking mode is Default: a heap's
Default resolves to Untracked (heap.rs, as Metal resolves it), and so did
every buffer placed in it. Metal leaves untracked resources unordered
between encoders (the program orders them with fences), so the shapes of
several encoders over the words (encoders, blits, loads) raced: the
tracker leaves untracked uses out of an encoder's summary and the host
alias uses of the RAM's key carry the same tracked: false, so no barrier
went between the encoders, and on RADV they overlapped. xtxhost's
'encoders: word 0 is 243, not 900' (PHOENIX; 157 of 900 with --binds tex,
1210 of 7200 on the XTX) is about one increment a command buffer of six
dispatches, a race's signature; one serial encoder and one dispatch a
command buffer passed, as Metal orders those even for untracked memory.
Lavapipe and MoltenVK ran the shapes serially, which hid it.

The heap is now Tracked: Metal tracks a tracked heap's resources as one,
so the encoders over its words are ordered as the plain shapes' tracked
words are, and --heap differs from them only by the heap over host pages
(still a copy beside the RAM's import, copied-host-pages). No runtime
change.

Verified in the heaplost proof job: the bench at the previous commit
(untracked heap) and at this one, --heap --only encoders and --binds tex,
on PHOENIX and lavapipe, with the command barriers each counted.
2026-11-15 21:31:49 -08:00
Anees Iqbal b4f27d3df9 dispatch_chain: a shape's lines print before its word check
A failed word check returned before the shape's CHAIN/HOST lines and counts,
so a run that lost words showed no counts (barriers, folds, copies) to read
the loss by. Each shape now prints its lines, then checks the words; a failed
check still fails the run with the same message.

Bench only; no runtime change. Built and run in the heaplost proof job.
2026-11-15 21:31:49 -08:00
Anees Iqbal 10b4b054d4 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 21:24:01 -08:00
Anees Iqbal cceefacfa7 RUNTIME 2420: A storage twin's neutral shares the device's zero buffer: the plan says which buffer writes are read-only
What: a new public BindingPlan::read_only_buffer(&DescriptorWrite): true for a uniform buffer and
for a uniform view's storage twin (DescriptorView::UniformWithStorageTwin, PlannedBuffer::twin),
which no function stores through. The runtime asks it where it used to read the descriptor type
alone (binding::descriptor's neutral arm, make_neutrals, binds_own_zeros), and makes the device's
zero buffer a storage buffer too, so a twin bound to nothing binds it.

Why: on the Iris Xe RPL-P profile (DriverWorkaround::PushReadsLengthenThreadPayload) RUNTIME 2413
gave a kernel's constant slot a storage twin. Left unbound, the plan writes the twin from the
ZeroBuffer neutral at a STORAGE_BUFFER binding, which the runtime took for a writable binding: every
dispatch took a fresh 64 KiB upload region, a dedicated VkBuffer allocated and zeroed, held until its
command buffer completed. Round 5974320352's Iris leg:
neutral_zeros_shared::dispatches_share_the_devices_one_zero_buffer, 8 dispatches made 8 VkBuffers
and 16 made 16.

Translation output and plans are unchanged (no SEMANTICS bump); the API addition is blessed in
api_signatures.tsv, and docs/API.md section 5 says it.

Test: engine_access::an_unbound_constant_slot_s_storage_twin_is_a_read_only_write plans
buffer_end_byte_load_constant with nothing bound on intel-irisxe-rplp-anv (the twin's STORAGE_BUFFER
write read-only, the written slot's not) and, as the negative control, on four other profiles (no
twin; read-only exactly at uniform buffers). The device check is the neutral test itself on the
Iris, which fails at the base.

Also, test premises on the Iris profile (round 5974320352's iris:runtime reds):
- a20c0a26d8: the compute creation test counts the forms its profile makes (1 + keyed storage views
  since RUNTIME 2410) and holds the pool only where completion is bounded (under Exact the second
  form runs on the pool).
- 88b8d31a32: set 0 at offsets counts the pipeline binds (draws past offset 0 take the residual form)
  and the push after each where the driver forgets pushed descriptors after a pipeline bind.

Verified in the lane (msi): m3-max-35051 clippy -D warnings -p metal2vulkan -p metal2vulkan-runtime
--all-targets --all-features exit 0, translator tests 71/71 (api_signatures 3/3); m3-max-35053
lavapipe (cpuicd) deferred_calls, neutral_zeros_shared, set_zero_at_offsets, uniform_bind_offsets
43/43. Still to run: clippy gpucfg and cpuicd, rustdoc, ONE Iris run of the three tests.

New Degradation kinds: none.
2026-11-15 21:23:17 -08:00
Anees Iqbal 6434a3d134 dma_buf_in_import: the in-import premise reads the buffer's import too; a test of an import dedicated to its buffer
The RTX 5080's red in round 5974320352: tests::dma_buf_in_import::a_texture_over_a_dma_buf_buffer_s_pages_binds_in_its_import
asserted the texture in place because the DmaBufInImport check passed its reads, yet the texture took no
image. The product was right; the test's premise was short.

The route binds the image in the buffer's import only where the buffer's pages lie in one import
dedicated to nothing (HostPages::in_one_dma_buf_import). NVIDIA's 615.71.09 refuses small dma-bufs
dedicated to nothing (it refuses a page's and takes 64 KiB: dma_buf.rs's ram_takes_dma_bufs), so the
test's 24 KiB udmabuf was imported dedicated to the buffer, which binds no image
(VUID-vkBindImageMemory-memory-10926). The check passed because its buffer is 40 MiB of the device's
own exported memory, imported dedicated to nothing: its verdict says what such an image does once
bound, not whether a given buffer's import holds one. The fallback, an image over a dma-buf of the
texture's own pages, was refused too: NVIDIA lays an explicit plane 512 bytes into a page out at
offset 0 (the 3090's PLANE-OFFSET probe), so the image binds at an offset of an undedicated import
of its own ~20 KiB dma-buf, which 615.71.09 refuses as small. The texture read its texels through
its shadow form.

The change, in the test alone:
- The in-import assertions run where the class's verdict passed and the buffer's pages lie in one
  import dedicated to nothing, the making's own question; elsewhere it asserts no image in the
  import and prints whether the import was dedicated to the buffer.
- The texture is 64x128 (64 KiB of rows), so the buffer's dma-buf (72 KiB) and the control's own
  image dma-buf (68 KiB) are of a size 615.71.09 imports dedicated to nothing: the route and its
  control run on the 5080 rather than skip.
- A second test, the same body with Memory::undedicated_import_refusal (the stand-in for 615.71.09's
  refusal that no_pointer_import uses) set before the buffer: its import is dedicated to it
  (dma_buf_buffer_imports_dedicated + 1, no one import dedicated to nothing) and no image binds in
  it. Under the old premise it fails where the class passed (lavapipe, Iris, the 5080) as the 5080 did.
- The in-place assertion names the counts it saw.

No product change, no new Degradation kind or WorkCounts field.
2026-11-15 21:11:55 -08:00
Anees Iqbal ca6259f7d1 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 20:40:36 -08:00
Anees Iqbal da08882991 RUNTIME 2419: Storage twins keep their key only where no other view reads its residual
On ANV (Mesa 26.2.6, Iris Xe RPL-P) a kernel's uniform view with a storage twin read the twin at
its bind offset wherever its own key held, also beside a storage view bound past offset 0, which
keeps reading its pushed residual word. There the thread payload stays long, and the twin's
per-lane storage read cost more than the uniform view's block read at its residual:
dispatch_chain --binds moved ran in 153.96 us a dispatch against base's 143.14 (job
m3-max-34864, 7 interleaved rounds, medians; ref's branch-free storage module 154.01), while
--binds 4, fixed and tex gained 28 to 38 %.

The runtime's uniform_residual_form now sets every twin's RangeAtBindOffset to 0 too where
another RangeAtBindOffset constant of the key is 0 (uniform_residual_form_of): a storage view
bound past offset 0, a twin at an offset no alignment divides, or a uniform view of no twin. The
kernel then reads its uniform views at their residuals, as base does. Where every view holds its
key, nothing changes.

Runtime only: no translation output moves, and no creation key (a creation's prediction binds
nothing, so its storage views and twins all hold). Only dispatch keys of a kernel with a twin and
a view off its bind offset move, on the Iris profile alone.

Docs: residual.rs, keyed_regions, the workaround's profile doc and docs/API.md section 5.

Test: general_form's a_twin_keeps_its_key_only_where_no_other_view_reads_its_residual (fails
with the cut sabotaged, the negative control in the check job).

Verified in the lane at 6d68983cc6: release build of the runtime and its dispatch_chain (m3-max-34932,
BUILD=0). Still running when landed: clippy plain, m2v_gpu and m2v_cpu_icd, rustdoc, the touched
runtime tests and the negative control (34931, 34933), the runtime suite on lavapipe, and ONE Iris
A/B of the arms and native code (base bcd50aba9f / opt2 680fc8997e / cut 6d68983cc6).

New Degradation kinds: none. Fixes the opt2 (SEMANTICS 2132 / RUNTIME 2413) regression of the moved arm.
2026-11-15 20:39:53 -08:00
Anees Iqbal 0cdd3d5399 heap_placed_reads: count the reads through copies, which a draw rebound counts too
What: the lane's Read counts WorkCounts::attachment_reads_through_copies, which every path a
draw takes counts, in place of attached_read_slots, which only a draw that takes every step
counts. Read's doc and the module doc say why: the read of the texture over the attachment's
bytes is a draw of the first read's state, whose kept draw the queue carries into its encoder
(render/carried.rs), so it is rebound (render/draw_again/rebound.rs), except in builds with debug
assertions, where the first carried draw rebound takes every step to check the rebind.

Why: the PHOENIX release failures (m3-max-32457, m3-max-34675: copied_slots 0, announced 1). The
probe f730cfe9c1 (not landed) printed each read's path counts on gem10's Radeon 780M
(m3-max-34911, load 11-15, 3 runs per build): built for release, the over read is a carried
rebound (draws_rebound_carried 1, draws_rebound 1, attached_read_slots 0, through copies 1,
announced 1) in 3 of 3 runs, so the old counter fails there; built with debug assertions, it
takes every step (attached_read_slots 1, draw_shapes_carried 1) and the debug check logged one
rebound checked (KEPT-IDENTITY-CHECKS, m3-max-34877). The draw reads the texture's copy on both
paths. Verified: the new counter reads 1 on both builds' over read.
2026-11-15 20:38:16 -08:00
Anees Iqbal 28510ece64 dma-buf release lane: the rebind step runs again where the busy work ended before it
What: the third part of dma_buf_pages_go_on_a_handler_thread_as_a_command_buffer_completes (busy
work, a copy out of the buffer's old pages, the rebind away from them) runs under
busy_premise::until_premise_held, as device_copies' and first_use's busy steps do. A try whose
busy work ended before the rebind writes its DMA-REBIND step times as a LANE-BUSY-MISS line and
runs again with new pages and new busy work, at most three tries. Every try checks the bytes the
copy read and the busy work's end. Only a try whose premise held checks that the old pages stayed
while the copy was in flight and went on a runtime thread: where the copy completed before the
rebind, the rebind frees them on the test's thread. A call that waits for the busy work misses
every try, and the test then fails with each try's times. busy_premise's doc names the step and
its measured times.

Why: round 4334fadfdc's PHOENIX leg failed it ('the busy work ended before the rebind') inside a
513-test suite, the test taking 3.43 s where it takes about 0.7 s alone. The step times show no
wait on the busy work at that tip or at today's: at 4334fadfdc (m3-max-34877, gem10's Radeon
780M, load 19-21, 3 runs) the busy work committed in 6-54 ms, the copy's commit 0.3-5.8 ms later,
scheduled() 0.2-2.8 ms after it and the rebind 0.4-1.3 ms after that, the end mark 0 at every
step; at 44708b4c3e and 95f8d61a48 (m3-max-34783, m3-max-34807, um790's 780M, 6 runs) the rebind
returned 5-8 ms after the busy work's commit, 45 ms once under load. So the host outlasted the
busy window: the premise, not the runtime.
2026-11-15 20:38:15 -08:00
Anees Iqbal de5612781e Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 20:36:13 -08:00
Anees Iqbal c053f814b1 RUNTIME 2418: The in-import dma-buf class takes the dma-buf class's copies verdicts
The check's DmaBufInImport class makes its pages exactly as DmaBuf's
(dma_buf_pages, plus the gate that its buffer lies in one import dedicated
to nothing), and a copies round puts no image over the pages: its copies
rounds repeat DmaBuf's over pages made alike. At its copies turn it now
takes DmaBuf's copies verdicts for both row ends, and runs no rounds of its
own, where DmaBuf's were measured this run or known before (passed or
failed) and both classes' noted memory flags are known and equal, the
same-memory-type rule of RUNTIME 2417's crossing; otherwise its own rounds
run as before. The note names the source verdicts and the flags
("DmaBufInImport copies: DmaBuf's verdicts, Failed and Passed for rows on
lines, its pages made as DmaBuf's in memory of property flags 0x..: no
rounds of its own"). A shared failure is a proof for pages made alike; a
shared pass is one draw of the rounds' race fewer, which errs to the shadow.
CHECK_VERSION 22: a record of 21 may hold the in-import class's own copies.

Tests: tests::in_place's unit test of shared_copies (shared where measured
and memory alike; the control: coherent against cached either way, either
memory unknown, a row end unchecked or pending, every other class: none);
tests::in_place_check's device count (the shared note once and no rounds of
its own where the rule holds, the dma-buf class's verdicts taken; printed
with both classes' memory and the check's wall time).

Also 00ba762437 (test only): the lent targets' test prints every host class's memory on a device made
with VK_EXT_external_memory_host too (LENT-TARGETS-POINTER lines).

Verified in the lane (m3-max-34930, msi, at 937274ec72): runtime clippy --all-targets --all-features
-D warnings plain, m2v_cpu_icd and m2v_gpu exit 0; touched tests 39/39; gpucfg archive built.
On the Iris Xe (RPL-P, m3-max-34910 at 00ba762437): lent_dma_buf_targets passed; Pointer, Fresh,
DmaBuf and DmaBufInImport check pages all lie in memory of flags 0xf. Still to run: the PHOENIX
check wall time base against tip, and the Iris count test with the in-place suite.

New Degradation kinds: none. CHECK_VERSION 21 -> 22: every device runs one fresh in-place check.
2026-11-15 20:35:31 -08:00
Anees Iqbal 5974320352 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 20:16:24 -08:00
Anees Iqbal b63bfbfac7 RUNTIME 2417: A render target's lend takes copies' failures through memory of one type
On the Iris Xe walk, a game engine's renderer made 73 RGBA16Float render
targets with free rows' padding over a no-copy buffer's dma-buf pages, and
each was a shadow: their renders failed for rows that end inside a line,
and the dma-buf classes' copies' verdict they lend that padding by
(`in_place::lent_to_copies`) was not failed in the recorded check, while
fresh checks fail it. A class's rounds catch a copy's line write-back only
as often as the CPU's writes race it, so the verdict hangs on a race.

The lend's copies verdict (`in_place::copies_verdict`, through
`InPlaceChecks::decided` at every decision site) now takes another host
class's copies failure, its reads passed, where the class's own kept every
byte or was unchecked, but only where the check's pages of both lay in
memory of a type of the same VkMemoryPropertyFlags as the driver reports
them: a write-back measured through memory of other flags says nothing of
this memory. Each class's memory flags are noted by the check and kept in
its record (CHECK_VERSION 21, eight words more). A shadow that renders with
free padding over host pages names the copies verdict it took in its
shadowed-texture notice. The line-write-back reason and docs (FAST-PATHS
host-pages row and the Iris known gap, API.md section 1 and the catalogue,
the kind's rustdoc) say so.

Tests: the unit test of the rule on the exact shape (same memory in place,
coherent against cached apart in both directions a shadow, unknown memory,
reads not passed, own-memory classes, own failed or pending kept, the
record's memory words); and a device test over a no-copy dma-buf buffer
(tests::lent_dma_buf_targets) whose control notes the pointer class in
memory of other flags and keeps the shadow.

Also 6e1f7b369d: the lend's memory flags are compared and printed as raw bits (ash's
MemoryPropertyFlags has no Debug impl here; clippy's chunks_exact_to_as_chunks).

Verified in the lane (m3-max-34875, msi, at 6e1f7b369d): runtime clippy --all-targets --all-features
-D warnings plain and --cfg m2v_cpu_icd exit 0; tests::in_place, tests::degradation*,
tests::texture_placement 38/38. Still to run: the device test on the Iris, PHOENIX and lavapipe
in-place suites, a sabotaged-build negative control, clippy m2v_gpu, rustdoc.

New Degradation kinds: none. CHECK_VERSION 20 -> 21: every device runs one fresh in-place check.
2026-11-15 20:15:41 -08:00
Anees Iqbal 384ba5ee67 Re-bless the authored compile census after the Iris at-bind and storage-twin work
The authored compile census's expectations at b9cf2070a4, every profile (m3-max-34868, release):
cases 2369, profiles 21, cells 49749, compiled 48670, refused 1079, failed 0, regressions 0,
differences 84, moved artifacts 4303. Rows moved: intel-irisxe-rplp-anv 1897 and its robustness-off
leg 1947 (the RPL-P-only push payload workaround, an unbound storage view taking offset 0's key, and
the kernel storage twins: SEMANTICS 2131/2132); one case's artifact on gate-lavapipe (+x86_64),
amd-780m-radv and nvidia-rtx5080-laptop, each with its robustness-off leg (6 rows). No outcome moved
between compiled and refused.

Wall 132.5 s; slowest compile 817 ms (intel-irisxe-rplp-anv+robustness-off); slowest case 22.4 s
over all its profiles; peak worker RSS 229.5 MB (500 MiB ceiling); peak case-worker RSS 393.4 MB.
2026-11-15 20:13:25 -08:00
Anees Iqbal 24c3923929 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 20:11:08 -08:00
Anees Iqbal 45296d9b50 RUNTIME 2416: DmaBufRequest names the alignment of a one-chunk answer apart
A no-copy buffer's, heap's or rebind's request longer than the device's
sparse granule asked every chunk at a multiple of the granule (64 KiB on
RADV of Mesa 26.2.4), one chunk included. That rule was ours: one chunk
is bound to a plain buffer, which vkBindBufferMemory takes at any
multiple of the buffer's memory alignment (VUID-vkBindBufferMemory-
None-10739). The granule binds only an answer of several chunks, as a
sparse buffer is bound at multiples of its alignment in both the buffer
and the memory (VUID-VkSparseMemoryBind-resourceOffset-09491). So a
consumer whose guest buffers lie in a 64 MiB region's dma-buf at page
offsets off 64 KiB (15 of 16 such starts) answered them with dma-bufs of
their own, each one more import on every RADV kernel submission's list.

Expected effect on the consumer (reims's diagnosis of 1910 refused asks
on the 780M, m3-max-34841): only the 212 asks that are one run of pages
inside one region (30 of them 2 MiB heaps) were refused for this rule
alone; about 33 of their objects are live at a time, about 7% of the
~450 imports on each submission's list, and the walk's dma-buf imports
fall about 4092 -> 3900. The other 1698 asks are scattered 4 KiB guest
pages (runs per ask p50 6, 1317 crossing region ends): no piece of a
region holds them (a plain buffer is one range of one memory) and no
split does (the 64 KiB granule needs 64 KiB-aligned runs), so they stay
dma-bufs of their own.

DmaBufRequest gains one_chunk_alignment (the host page, or the plain
dma-buf buffer's memory alignment where larger; it divides alignment
and equals it where the granule is the length); a lone chunk is checked
against it, several against alignment, as before. Answers valid before
stay valid. The rustdoc and HOWTO say how a source picks between them.

How it is verified: tests::dma_buf_shared_files::one_piece_off_the_
granule_binds_a_plain_buffer_at_its_offset (the previous commit's,
refused Invalid without this one) and two_pieces_off_the_granule_are_
refused (its control, refused before and after) on a device whose
granule is coarser than the page (PHOENIX, RADV); tests::one_piece_bench,
a release bench of submission cost with 128 buffers over one region
answered by each rule. The evidence is in the lane's report.

Also: 51768bf6ab (tests: one piece off a device's sparse granule is taken; two such pieces stay refused),
and an ignored release bench, tests::one_piece_bench.

Verified in the lane (m3-max-34863, msi, same tree as 832c48ad2c): api_signatures 3/3; lavapipe
-E 'test(/dma_buf/) | test(/host_memory::a_source/)' 76/76 (lavapipe's granule is a page, so the two new
tests print "shows nothing" there); clippy m2v_cpu_icd --all-targets -D warnings. Still running when
landed: PHOENIX (64 KiB granule) base refusal, tip suite and bench; clippy plain and m2v_gpu.

API: adds the field DmaBufRequest::one_chunk_alignment (additive; a source that checks alignment alone
still answers validly).
2026-11-15 20:10:21 -08:00
Anees Iqbal b9cf2070a4 Re-bless the golden hashes for the Iris's kernel storage twins
SEMANTICS 2132 (765997d91f) declares a storage twin beside each kernel uniform view on the Iris RPL-P profile. The re-bless on the M3 (m3-max-34860 at fc6562aa97: bless_engine_inventory, bless_golden_hashes, bless_engine_goldens all 0) moves 347 rows, every one in the intel-irisxe-rplp-anv column alone; no other profile's cell, no key added or gone.
2026-11-15 20:05:26 -08:00
Anees Iqbal fc6562aa97 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 20:01:43 -08:00
Anees Iqbal 47a0a82849 RUNTIME 2415: Pass ends make and compare their open instance's key with no allocation
What: a render pass's end, which works out whether its last instance may stay open for the next
render encoder (encoder_fold.rs's Continued passes), allocates nothing for it:
- a framebuffer holds its attachments' views in place (render_target::AttachmentViews, at most
  each color and its resolve, the depth/stencil attachment and its resolve), not in a Vec copied
  from the list it was made with, and render_target::PassKey holds them so too;
- the key goes by value (EncoderCore::continuable, OpenPass, State::open_pass), not in an Arc;
- InstanceShadows::touches_alone holds each of its draws' uses against the attachments' keys as
  they stand where no use takes another (HostAliases::takes_none), with no list of either; where
  the device's host aliases are live, as before.

Why: round 4334fadfdc's PHOENIX and Iris lanes failed
frame_costs::a_frame_s_draws_and_pass_ends_allocate_within_their_bounds at 20.19 allocations a
pass end, past its bound of 19. RUNTIME 2404 (09a3f0505b) added the key at each pass end: the
attachments' uses listed, the draws' uses collected, the framebuffer's views copied into the key,
the key boxed in an Arc, each per pass.

Verified: in the lane (counts follow).

Also: be328d1804 (the dma-buf lane prints the rebind step's times; test only).

Why: fix forward for RUNTIME 2404 (09a3f0505b): every pass end allocated an Arc'd PassKey whose views
were a Vec, and touches_attachments_alone collected the attachment uses into Vecs, so
runtime_lane::frame_costs::a_frame_s_draws_and_pass_ends_allocate_within_their_bounds failed (20.19 and
20.91 allocations a pass end against a bound of 19; round 4334fadfdc PHOENIX and XTX, m3-max-34783).

Verified in the lane: PHOENIX (m3-max-34783/34807): base b650408113 16.15 / 6.24 allocations a pass end /
a draw; 44708b4c3e 20.91 / 6.37, red 3 of 3; the same product diff on it 16.15 / 6.24, the four frame
tests 3 of 3. lavapipe (m3-max-34811): render_fold 25/25 at base and tip, and the 21 distinct
RENDER-FOLD lines (every continuation and wrong-texel count) identical between bcd50aba9f and the tip.
Still running when landed: clippy x3 and rustdoc (m3-max-34799).
2026-11-15 20:00:58 -08:00
Anees Iqbal b91cca6da5 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 19:59:43 -08:00
Anees Iqbal 97da82174b RUNTIME 2414: WorkCounts times the device's dma-buf imports and pieces' joins
The consumer asked for the time its dma-buf import calls take: each
vkGetMemoryFdPropertiesKHR and vkAllocateMemory of a dma-buf import, and
each piece's join of a live shared import.

Three new WorkCounts fields:
- dma_buf_import_calls: imports of dma-bufs of host pages tried, made or
  failed, wherever made (buffers', heaps', rebinds' chunks, shared files'
  imports at a first piece, ahead by a handle or again after the
  residency released them, guest RAM chunks and run lists, images).
- dma_buf_import_nanos: their nanoseconds, on the threads that made them.
- dma_buf_join_nanos: the nanoseconds of the joins dma_buf_pieces_joined
  counts (a map look and a hold, no driver call).

Every import goes through one timed helper (Device::import_timed) that
queries the dma-buf's types and imports it; the four call sites (a
chunk of its own, a shared file, the two image imports) use it.

Verified: the shared-file tests assert one timed import and a positive
join time for four buffers over one file, and four timed imports with
no join time for four dma-bufs of their own.

Why: the consumer's ask (reims dmabufapi): their A/Bs could not report the time the dma-buf import
calls take from WorkCounts.

Verified in the lane (m3-max-34812, msi): clippy -D warnings -p metal2vulkan-runtime --all-targets
--all-features; api_signatures 3/3; lavapipe -E 'test(/dma_buf/)' 73/73: four buffers over one shared
file count import calls 1 with nanos > 0 and 3 joins with join nanos > 0; the control (four dma-bufs of
their own) counts import calls 4 and join nanos 0. Still running when landed: clippy m2v_gpu and
m2v_cpu_icd, the PHOENIX dma-buf suite.

API: adds the fields WorkCounts::dma_buf_import_calls, dma_buf_import_nanos and dma_buf_join_nanos (additive).
2026-11-15 19:58:43 -08:00
Anees Iqbal a7f125fa0c The storage twin's slot test binds its shapes under BufferRanges
RUNTIME 2412 gave BoundBuffer::shape the stage table's BufferRanges; the twin
test landed beside it called the one-argument form. The default ranges tell
every length class apart, as the test's other shapes take them.

Verified: cargo fmt; clippy and the bind tests run as a potluck job.

Fix forward for 765997d91f: the merge of SEMANTICS 2132 with RUNTIME 2412 left one opt2 test calling BoundBuffer::shape(alignment) where 2412 takes (alignment, BufferRanges); the metal2vulkan tests did not compile. Test-only. Checked in m3-max-34828 (clippy on the three crates + the bind::, engine_access, engine_device_replay and interp tests), running when landed.
2026-11-15 19:51:53 -08:00
Anees Iqbal b587d494ca Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 19:49:06 -08:00
Anees Iqbal 765997d91f SEMANTICS 2132 / RUNTIME 2413: Kernel constant buffers on the Iris: a uniform view and its storage twin
What: on a profile that takes DriverWorkaround::PushReadsLengthenThreadPayload (ANV on the Iris Xe of
RPL-P), a kernel's uniform view (a read-only constant buffer whose window fits maxUniformBufferRange)
also binds its range as a storage buffer, its storage twin (DescriptorView::UniformWithStorageTwin,
ResourceKind::StorageTwin, BindingSource::StorageTwin). Each load selects, on the slot's
RangeAtBindOffset key, the twin read at the bind offset alone (key 1: a bind at an offset the class
divides, inline bytes, or unbound) or the uniform view at its residual (key 0). Specialization folds
the selection. The binder writes the twin from the slot's own source with a second descriptor range
starting at the bind offset. A twin's kind sorts last, so link numbers put a stage's twins after its
other bindings (docs/API.md section 5). Render stages and every other profile are unchanged: no twin
is declared and translation output is the same.

Why: on the Iris (m3-max-34275, dispatch_chain, us a dispatch) reading a kernel's constant buffer
through a storage view at its bind offset measured binds 4 142.7 -> 102.1, fixed 143.2 -> 101.3, tex
119.6 -> 74.4; at a non-zero residual the storage view lost (moved 143.1 -> 154.0), so the uniform view
keeps the residual case. Creation makes the key and its general form together (RUNTIME 2410), so no
first-use making.

Also: the cache codec lists the new variants; the interpreter binds a twin with no buffer of its own
to its slot's buffer; the device-replay tests name the twin's symbol. Docs: API.md section 5, the
workaround, the DEFECTS row, residual.rs, views.rs.

Verified in the lane: m3-max-34780 (at 7a862493b8) clippy -D warnings, metal2vulkan, runtime and
validation, all targets and features; the metal2vulkan suite 3626 passed, 11 failed: golden_hashes
(re-blessed on development) and 10 fixed at fca91cb055. m3-max-34804 (at fca91cb055) clippy 0. Still
running when landed: nextest over the three crates (34804), the authored compile census on the Iris
profile base against tip (M3), the Iris device tests and dispatch_chain A/B (every arm against base,
the branch-free reference for the folding check).

API: adds DescriptorView::UniformWithStorageTwin, ResourceKind::StorageTwin, BindingSource::StorageTwin
and BufferForm::storage_twin (additive to the enums: a consumer matching them exhaustively must add the
arm; a consumer binding set 0 itself fills the twin as docs/API.md section 5 says).
2026-11-15 19:48:21 -08:00
Anees Iqbal bcd50aba9f C3 venues: the Iris venue allows the RPL-P alone, which its translation key names
Iris venue: allow the RPL-P alone; the RPL-S derives another translation key

Since SEMANTICS 2128 DriverWorkaround::PushReadsLengthenThreadPayload is keyed on the Iris Xe of
RPL-P (8086:a7a0) alone, where it was measured. The UHD Graphics 770 of RPL-S, which the
intel-irisxe-rplp-anv venue also allowed, has a capture that differs from the RPL-P's only in
maxMemoryAllocationSize, but its derived profile does not take the workaround, so its translation
key differs. Venues::check_profiles refuses that, and every test that loads the committed venue
list failed, among them candidate::engine::guards::tests::no_venue_runs_a_guarded_target_under_
robustness_1_alone, the c3 venue tests and the two-device profile test.

The RPL-S leaves the venue: translation tells the two apart, and no cluster host has an RPL-S to
record a venue of its own. Its capture stays committed (other tests read it as a device profile).

- c3-venues.json: the Iris venue's devices are the RPL-P alone.
- c3::tests: the venue allows the RPL-P alone; pushing the RPL-S with its own capture is refused
  as a device that derives another key and needs a venue of its own; the RPL-P's capture under
  the RPL-S's identity is refused as another device's.
- candidate::platform::profiles::tests::the_intel_venue_allows_the_rplp_alone_and_stops_the_rpls
  (was one_intel_venue_allows_both_devices_and_stops_any_other): the captures still differ only
  in maxMemoryAllocationSize, the workaround is the RPL-P's and not the RPL-S's, the keys differ,
  and the venue runs the RPL-P and stops the RPL-S on its name, device ID and driver build.
- c3/venues.rs docs and the regen script's comment say so.

Verified: cargo fmt; built and tested in the next potluck job.

Iris venue tests: the RPL-S also stops on its key and allocation size; six venue devices

The venue no longer allows the RPL-S (51c031e187), so its check against the
RPL-P's venue reports, past its four identity differences, its own
translation key and its host's maxMemoryAllocationSize; and the venues allow
six devices, not seven. Both tests now say so.

Verified: cargo fmt; clippy and the c3/candidate tests run as a potluck job.

Iris venue tests: the venues that present the requirements documents no longer list the RPL-S

The RPL-S is no venue device since 51c031e187, so the presented-on lists of
lunarg-desktop-baseline-2023 and roadmap-2022 drop it.

Verified: cargo fmt; clippy and the c3/candidate tests run as a potluck job.

Fix for development's red since SEMANTICS 2128 (d3b1dbdbe0): DriverWorkaround::PushReadsLengthenThreadPayload is keyed on the RPL-P (8086:a7a0) alone, so the RPL-S capture's derived profile takes another translation key, and every test that loads the committed venues failed (c3::tests x6, guards::no_venue_runs_a_guarded_target_under_robustness_1_alone, profiles::tests x2, integration authored_compile_census and private_corpus_root). Verified (m3-max-34762, msi, at b5d745e599): validation clippy --all-targets --all-features 0; c3:: + candidate:: tests 270/270.
2026-11-15 19:37:36 -08:00
Anees Iqbal 2dae45566e Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 19:30:15 -08:00
Anees Iqbal a853d9a944 BufferRanges's docs link no private item; the field check names buffer_ranges
The length-class cut (725d2913d7) added StageTable::buffer_ranges and linked BufferRanges's docs
to the private free function length_class. On development's tip 44708b4c3e:

- rustdoc -D warnings refused the two links ("public documentation for `BufferRanges` links to
  private item `length_class`"); the docs now say "length class" and "its exact class" in words.
- tests::argument_table::the_check_compares_every_field failed on lavapipe: StageTable's Debug
  now prints buffer_ranges, which check_reading already compares (kept.buffer_ranges against the
  device's views.ranges). The test's list names it, and its doc says how it is compared.

Verified: the runtime suite on lavapipe at 44708b4c3e ran 1450 of 1451 passing in partition 1,
the one failure this test; the doc job's two errors are the two links. The rerun at this commit
follows.

Fix forward for RUNTIME 2412 (725d2913d7): rustdoc -D warnings (m3-max-34733, DOC=101: BufferRanges's docs linked a private fn) and tests::argument_table::the_check_compares_every_field on lavapipe (m3-max-34744, 1450/1451: StageTable's Debug now prints buffer_ranges). Docs and a test list only. Re-run (rustdoc, argument_table + grid_classes on lavapipe) m3-max-34760 running when landed.
2026-11-15 19:29:32 -08:00
Anees Iqbal d172da9e5c The compile worker fixture reads its last argument from the back
clippy::double_ended_iterator_last in the cpu_icd lib test build (msi job m3-max-34662,
CLIPPY_CPUICD=101): std::env::args().next_back() in place of .last().

Fix forward for 52a784770c: clippy::double_ended_iterator_last under --cfg m2v_cpu_icd (CLIPPY_CPUICD=101 in m3-max-34662). Verified (m3-max-34725, msi): clippy -p metal2vulkan-validation -p metal2vulkan-devtools --all-targets --all-features -D warnings, cpu_icd 0 and plain 0. Plain validation + devtools suites (m3-max-34721): 1398 passed, 11 failed, all the known C3 venue RPL-S key failure on development since SEMANTICS 2128 (fix in flight); the scan's negative control (m3-max-34745) lists the 88 sites at the base.
2026-11-15 19:27:41 -08:00
Anees Iqbal 44708b4c3e Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 19:20:54 -08:00
Anees Iqbal 725d2913d7 RUNTIME 2412: Bind shapes tell buffer length classes apart only as far as the device's range limits do
What: a new public bind::BufferRanges (a device's maxUniformBufferRange and
maxStorageBufferRange, BufferRanges::of(limits)), carried on each StageTable (buffer_ranges,
serde default), which the runtime sets on every table it reads (argument_table's AtBindViews,
beside the view base alignment: stage_table_reading, refresh_reading and the in-part
refreshes, AtBindViews::holds, and the debug check of a kept table). A buffer's shape states its
length class rounded up to the greatest class that fits the same limits
(BufferRanges::length_class); a class past both stays its own. BoundBuffer::shape and same_shape
take the ranges; BoundKind::of_bound and instantiate::bound_buffer class the bound length under
the table's ranges, so the instantiation's kind check takes a binding exactly where its class is
the plan's. The default (both 0) tells every class apart, as before.

Why: a guest compositor's serial compute encoder of ~1,140 fix-up dispatches over buffers of
many sizes made a new bind shape at 46% of its dispatches and planned again at 69% (the
consumer's XTX walks). A plan reads a length class only through class_fits against those two
limits (storage_view_variant and large_view_candidates against maxUniformBufferRange,
psb_variant and range_variant against maxStorageBufferRange); otherwise it only stores the class
for the kind check. On an RX 7900 XTX both limits are 4294967295, so every buffer below 4 GiB
takes the same plan decisions, and the dispatch_chain bench's 44 length-class shapes were one
plan. The bench there (job m3-max-34605, interleaved) matched the walk's split exactly (made
46%, found 18%, kept 36%) at 7.1-7.6 us a dispatch, against 4.1-4.4 us for the same stream of
one shape.

Exact: under the device's own limits, every class_fits answer of the rounded class is the exact
class's, so every plan decision, variant key and specialization is the same; under any other
limits the rounded class still bounds the padded length from above (padded < 2^class), so no
plan reads a range past a limit (it may take only a longer buffer's form).

Digests, cache keys and stored records: none carries the class. BindShape keys only in-memory
memos (Variant::plans, a state's kept Planned entries, the dispatch memo, the render draw
shapes); artifact digests and region keys are functions of the variant key and specializations,
which this leaves equal; validation and executor states keep the default ranges, so their shapes
and plans are unchanged; no pipeline record or warm record holds a shape. The serde form of
StageTable gains a defaulted field. So no SEMANTICS bump, in my reading.

Tests: bind::plan::slots length_classes_are_told_apart_as_far_as_a_plan_reads_them (4 GiB
limits, 64 KiB/128 MiB both ways round, 16 KiB, and none: every length's class answers both
limits' class_fits as the exact class does, bounds its padded length, is exact under none, and
bound_buffer takes a binding for another length's kind exactly where the classes are one, only
where the exact classes answer both limits alike); bind_shape_of's has_shape states and
same_shape pairs over range limits; runtime grid_classes
lengths_the_device_tells_apart_nowhere_plan_once (outputs of four length classes under 16 KiB,
one shape, 23 of 24 dispatches planned as before; 20 without this), and
shapes_and_classes_in_turn_each_plan_once re-made from the constant's binding (inline bytes, a
buffer, a buffer with a per-bind stride), since its three length classes are now one shape.
API: signatures blessed, api_surface, docs/API.md.

Also: 674c995a42 (dispatch_chain --zero-classes and --stay: a guest's fix-up dispatches over buffers of
many sizes), ad406afa87 (clippy in the new test).

Verified in the lane (m3-max-34674, gem10, at ad406afa87): clippy -D warnings -p metal2vulkan
-p metal2vulkan-runtime --all-targets --all-features; translator tests 21/21 (the new
length_classes test, bind_shape_of, the slots tests). Still running when landed: the XTX bench before
and after (release, interleaved), the lavapipe bench, the runtime suite under m2v_cpu_icd on lavapipe,
the negative control (AtBindViews ranges set back to the default fails the new runtime test), clippy
gpucfg and cpuicd, rustdoc.

API: adds bind::BufferRanges and StageTable::buffer_ranges (serde default); additive.
2026-11-15 19:20:06 -08:00
Anees Iqbal a842f346cb Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 19:18:52 -08:00
Anees Iqbal 581d870e51 RUNTIME 2411: A continued pass's end takes no barrier after its group's earlier encoders
A continued pass's end takes no barrier after its group's earlier encoders

A render encoder that continued the instance its group's tail held open
noted its whole pass's uses at its end against the group's order, which
still held the earlier encoders' copies (a split's shadow or attachment
copies) and so asked for a barrier; recording it ended the instance the
encoder left open, so in a run of readers only every other encoder
continued (render_passes_continued 53 of 106 boundaries in the glass
walk's branch form on the 780M). The barrier orders nothing: a group
whose tail holds an open instance holds its leader and the encoders that
continued it alone, each of whose last instance touched nothing but its
attachments, so every other access of theirs came before a split's
barrier from everything before that instance began; the continuing
pass's first instance is ordered after their attachment accesses by
rasterization order and after the rest by that barrier, and its later
instances follow its own split's barrier. Its uses still join the
group's summary, so an encoder that joins later orders itself after
them.

Tests: three readers in a row (a draw, a barrier over the render
targets, a sampling draw that splits) each continue the one before, each
band holding what its sampling draw read of its first draw; a compute
encoder after two continued render encoders reads what they drew,
inverted.

render_fold: continuation lanes expect no continuation where the device splits at aliases

On NVIDIA's 620.70.06 on the RTX 3090 (ImageUsesMissBufferWritesInOne-
CommandBuffer) no pass leaves its instance open or continues another, by
the Continued passes rule, so each render encoder begins its own; the
round at 4334fadfdc failed a_dispatch_between_render_encoders_ends_the_
continued_instance there with (6, 0, 6), its texels right. The lanes
that expect a continuation now expect each encoder's own instance on
such a device (Lane::continuing), printed; the rebind lane expects the
last encoder alone encoded again, each encoder a group's alone.

Why: v2 (RUNTIME 2408) continued only every other multi-instance encoder on the glass frame
(branch private: render_passes_continued 53 of 106 boundaries): an encoder that continued noted its
pass's uses at its end, and the group's order asked for a barrier after the earlier members, which
ended the open instance. Also round 4334fadfdc's 3090 red
(render_fold::a_dispatch_between_render_encoders_ends_the_continued_instance (6,0,6)) was the tests'
premise: the 3090's driver fact ImageUsesMissBufferWritesInOneCommandBuffer keeps every pass from
continuing, by design.

Verified in the lane (m3-max-34636, lavapipe, at 622368ab37): the 12 continuation cases (readers in a
row: (1, 2, 4), each band's texels right; compute after a continued group: its own barrier counted,
texels right); hand control with the old ordering (after_fold = true): only the readers case fails at
continued 1; full runtime suite 2869/2870 (the one failure,
dma_buf_standing_refusal, is development's own at b4e6511871 and fixed by 47e6b45475). Compiled under
m2v_gpu (m3-max-34637). Still running when landed: clippy x3, the 3090 render_fold suite, the 780M and
Iris glass A/Bs.
2026-11-15 19:18:08 -08:00
Anees Iqbal 52a784770c Validation tests find their inputs and their compile worker under any archive selection
Validation reads the checkout where the test runner names it, everywhere

A lib-only archive of the validation crate, built on msi and run from another root with
--workspace-remap and the build tree's sources moved away (lavapipe, job m3-max-34590), failed
runtime_lane::tests::a_kernel_runs_the_functions_its_descriptor_links (NotFound at tests.rs:697:
crate::engine::profiles_dir() is env!("CARGO_MANIFEST_DIR")/profiles) and
candidate::engine::graphics::tests::public_render_cases_plan_or_refuse_typed ("0 public render
cases planned": a baked corpus root). Both pass when the build tree is present. The scan
39bff0de2a added covered only runtime_lane/, not the library code the lanes call, nor the rest of
the crate a carried archive holds.

Every env!("CARGO_MANIFEST_DIR") read left in the validation crate moves onto
metal2vulkan-devtools' resolvers, mechanically: the crate's own files onto validation_dir(), the
public fixtures onto fixtures_dir()/engine_dir(), the workspace and crates/ onto workspace_dir().
That is 73 sites in src/ (library ones included: engine::profiles_dir, source::corpus_root,
cutover::list_path, library_module's linked fixtures, mesh_cases, corpus-harvest's default
corpus) and 15 in tests/. The runtime pin's include_str! takes a path relative to its file. A
binary run outside cargo names no manifest directory, so workspace_dir() falls back to the checkout
the dev-tools crate was built in: the same directory as before.

The devtools scan (tests::the_carried_tests_read_the_checkout_where_the_runner_names_it) now
covers all of crates/metal2vulkan-validation/src and tests beside the runtime's src; at the base
it lists the 88 sites.

Test harness and validation tooling only; no product file.

The lib's device tests compile through their own test binary

A lib-only archive of the validation crate (cargo nextest archive -p metal2vulkan-validation --lib,
lavapipe, job m3-max-34590) failed 20 runtime-lane tests whether or not it ran beside its build tree:
the 16 kernels_with_textures_and_samplers_match_metal shards, the two argument-buffer censuses,
sparse_cases_match_metal and public_render_cases_match_metal. All panicked at candidate/tests.rs:63:
compile_worker() looked for the corpus-pipeline binary above the test binary, and Cargo builds a
package's binaries only for a selection that holds an integration test, so a --lib build or archive
never has one.

compile_worker() now names this test binary (CompileWorker::lib_tests), which already installs the
counting allocator (alloc::tests) and already served the compile path's limit probes. A
CompileWorker carries the arguments and variables before the worker argument: none for a binary;
for the lib test binary, `--exact worker::compile::tests::compile_worker_fixture --nocapture
--quiet --` and M2V_TEST_COMPILE_WORKER, so the worker argument run_json's caller appends is a
filter after `--`. The fixture serves a compile, or the probe the variable names, through
worker::serve_process as a binary does, on an 8 MiB thread (a binary serves on its main thread;
the harness runs a test on a 2 MiB one), and exits. It refuses any worker argument but the compile
worker's. run_json decodes the last non-blank line of the worker's stdout as its report, so the
harness's "running 1 test" line before it is not read.

The worker keeps every limit of the boundary: its parent is the same compile() path, so it has
its own process group, the 20-s deadline, the process-group RSS kill, the 500-MiB allocator budget
and scratch removal. The limit probes now go through CompileWorker::lib_tests and compile(),
the exact path the device tests use: deadline (timeout), resident memory (oom), budget
(worker_exit) and the uncounted refusal. New tests:
worker::compile::tests::the_lib_tests_worker_returns_the_pipeline_the_public_api_compiles (the same
comparison tests/integration/compile_worker.rs makes through the real corpus-pipeline,
corpus-vulkan and corpus-moltenvk, which stays) and
worker::tests::a_worker_s_report_is_the_last_line_of_its_stdout.

Test harness only; no product file.

mesh_cases borrows its label for the fixture path; run_json's doc rewrapped

The unbake rewrite moved the row's label into the path join (E0382 in the cpu_icd lib test build,
msi job m3-max-34650); it joins a borrow. Compile fix and doc wrap only.

Why: a lib-only nextest archive of the validation crate (as lanes build) failed 22 tests when run off
its build tree, 20 when run on it (m3-max-34590, lavapipe): the compile worker binary is built only
for selections that include an integration test, and 88 env!("CARGO_MANIFEST_DIR") reads lay
outside the tree the 39bff0de2a scan checks.

Verified (m3-max-34662, msi, at 97feb0e0dc): the lib-only cpu_icd archive, run on lavapipe remapped to
another root with the build tree's sources moved away: 426/426 (the commitwait set, every touched lib
test module and worker::), including the 22 that failed at the base; the four limit probes through
CompileWorker::lib_tests (timeout 20.06 s, RSS kill, allocator budget, uncounted refusal); the new
lib-tests worker equality test. Still running when landed: clippy x3 for validation and devtools, the
plain suites (the corpus-pipeline integration comparison), the widened scan's negative control, rustdoc.
2026-11-15 19:16:35 -08:00
Anees Iqbal 47e6b45475 In-place images in the buffer's import: a free check, a route-(b) test held to its route, and a first-use bench
tests::dma_buf_standing_refusal measures the source's asking, which only an image in a
dma-buf import of its own does: it fails the in-import class's verdicts first, as the other
route-(b) tests do. lavapipe (m3-max-34595) took the in-import route there, so the test saw no
request and failed.

tests::dma_buf_in_import now also checks that the import an image binds in, kept imported for
good, is freed once the textures and the buffer go (host_imports_live and
dma_buf_memories_live back to their values before the buffer), and gains an ignored release
bench (in_import_first_use_bench): new_texture and a one-texel blit's first use, in the import
against in an import of its own, 1920x1080 and 4096x5376, medians of 3.

Test-only follow-up to RUNTIME 2409 (8d617591f8).
- tests::dma_buf_standing_refusal fails the new class's verdicts first (own_dma_buf_images), as the
  other route-(b) tests do: on lavapipe the route (a) image took the texture, and the test counts
  source requests only route (b) makes (it failed at :138 in m3-max-34595).
- tests/dma_buf_in_import.rs drops its textures, buffer and command buffers at the end and polls until
  host_imports_live and dma_buf_memories_live return to their values from before the buffer: the
  import goes with its last holder.
- An ignored release bench, in_import_first_use_bench (IN-IMPORT-AB lines), route (a) against route (b).

Verified (m3-max-34616, msi, m2v_cpu_icd): the in_place, dma_buf, texture_placement, copied_device,
host_pages_placement, host_residency, shadow_causes_device and rebind filter, 232/232. The count test
on llvmpipe: in the import 1, dma-buf images 0, imports live 0, source calls 0; its negative control: 0,
1, -, 1; the free check passed.
2026-11-15 19:11:37 -08:00
Anees Iqbal b4e6511871 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 19:03:32 -08:00
Anees Iqbal 66de1cabbc SEMANTICS 2131 / RUNTIME 2410: At-bind storage views: creation makes the offset-0 key and its general form
On a profile that takes DriverWorkaround::PushReadsLengthenThreadPayload (ANV on the Iris Xe of
RPL-P) a storage view bound at offset 0 reads at its bind offset alone (RangeAtBindOffset 1). Every
plan made before a bind (a render state's creation prediction, a compute state's predicted region,
a warm pass's replay of a recorded dispatch) bound nothing, and an unbound storage view took 0, so
the creation made the general form and the commonest command, every storage view at offset 0,
made a second pipeline at its first use; the warm records named the other form.

- bind::plan::slots::range_at_bind_offset: a storage view bound to nothing takes what a bind at
  offset 0 takes; a uniform view keeps 0. Elsewhere no storage view declares the key.
- Render creation (pipeline/predicted.rs): the predicted key keeps its storage views' constants
  (uniform_residual_form) and the creation makes that key and, where it differs, its general form,
  together (RenderVariant::make_at_creation: pooled and waited for within one bound under Bounded,
  joined under Exact). The pool-ahead making of the key is deleted; the creation log names the
  general form's line.
- Compute creation (pipeline/dispatch_making.rs): the predicted region and its residual form,
  made together the same way. A warm pass's dispatch replay makes each region's residual form too
  (pipeline/dispatch_record.rs).
- The executor tells offset 0 apart at every slot (views_told_apart), so its plan of a case on the
  row is the runtime's (runtime_lane::executions).
- Tests: per-row expectations where offset 0 is its own shape or the creation makes two
  (made_at_creation, pipeline_records' Makings, grid_classes, dispatch_work, warm, the kernel
  creation counts in uniform_bind_offsets); the draw-again general-form test now binds
  colored_vertex's positions at 16 and colors at 0, a key neither creation form matches; a new
  device test, storage_views_at_offset_0_make_nothing_at_their_first_use, counts that a draw and a
  dispatch of storage views at offset 0 make, pool and take nothing but the creation's pipeline;
  an ignored timing test, storage_creation_times, times such a state's creation cold, from the
  memo and from the directory.
- Docs: DriverWorkaround::PushReadsLengthenThreadPayload, the DEFECTS row, residual.rs,
  predicted.rs, dispatch_making.rs, dispatch_record.rs, the warm pass, docs/API.md.

Also: c1d0b47a10 (WorkCounts docs name both creation forms; the first-use test types its positions),
6377eafa09 (storage_creation_times prints each round).

Why: fix forward for RUNTIME 2398-2400. Round cc1d619c7a's Iris legs failed about 16 tests on the
pipeline the creation made not being the one first use takes (made_at_creation, pipeline_records,
warm, restart, ycbcr_textures, executions, grid_classes, dispatch_work).

Verified in the lane: m3-max-34579 (at 2e6fbef8f2) clippy -D warnings, metal2vulkan, runtime and
validation, all targets and features; bind::plan::slots tests 14/14. m3-max-34603 (at 6377eafa09)
clippy --cfg m2v_gpu of runtime and validation; validation candidate::engine + worker::compile 103/105:
the runtime-sources pin (re-pinned at landing) and
candidate::engine::guards::tests::no_venue_runs_a_guarded_target_under_robustness_1_alone
(guards/tests.rs:125, under investigation: present on development or not). Still running when landed: the
Iris suites (made_at_creation, pipeline_records, restart, ycbcr_textures, executions, dispatch_work,
grid_classes, warm, uniform_bind_offsets, draw_again) and the creation-time A/B, cold and warm.
2026-11-15 19:02:47 -08:00
Anees Iqbal 57c08ab04f Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 18:56:41 -08:00
Anees Iqbal 8d617591f8 RUNTIME 2409: In-place textures over dma-buf pages: the image bound in the buffer's own import
A texture in place over a no-copy buffer's dma-buf pages no longer always asks the pages'
source for a new dma-buf and a dedicated import of its own. Where the pages lie in one import
dedicated to nothing (no sparse buffer over several imports, no import the driver made
dedicated to the buffer), its DRM_FORMAT_MOD_LINEAR image whose plane lies at offset 0 at the
texels' pitches is bound in that import at the texels' offset, beside the buffer
(vkBindImageMemory's memoryOffset): no udmabuf, no import, no new GPU mapping. Every fact is
asked of the driver: the image requires no dedicated allocation (VUID-vkBindImageMemory-
image-01445), the format query takes dma-bufs for it outside one (not DEDICATED_ONLY), its
alignment divides the offset (-None-10735), its size fits the pages' placement (-None-10737)
and its memory types take the import's. An import dedicated to the buffer binds no image
(-memory-10926): DmaBufPages now notes that.

A new check class, PagesClass::DmaBufInImport (CHECK_VERSION 20), measures that image; the
check's textures of each dma-buf class take that class's image alone (a thread-local of the
class the check runs). texture/route.rs takes the new class where its verdicts take the
texture, else DmaBuf's; a shadow waits on DmaBuf's verdict while both pend. Where the making
refuses the image in the import, it falls back to today's image where DmaBuf's verdicts take
it. A pending move re-routes the same way. Binding in the import reads it apart: it is kept
imported for good, as an image in a pointer import's is. A rebind remakes such an image in the
new pages' import by the same order. RADV requires a dedicated allocation of every such image,
so its check leaves the new class unchecked and it never takes the route.

New WorkCounts field: dma_buf_images_in_import. No new Degradation kind.

The route-(b) device tests (parked images, plane offset, import cycles, a texture's residency)
fail the new class's verdicts first, so they keep measuring today's image on any device. A new
device test (tests/dma_buf_in_import.rs) counts the route and its negative control.

Also: 4c3cbe2f1d and 37d2a750ce (the probe, dma_buf_linear_bind: a linear and a modifier image for
dma-bufs bound in the pages' existing import, the dedicated answers, a re-import arm), 5a40c2ef7b
(docs: API.md, HOWTO.md, FAST-PATHS.md, host_residency.rs module docs).

Why: the owner asked how to remove the per-texture dma-buf. Probe answers (Mesa 26.2.6): RADV on
the Radeon 780M refuses LINEAR images for dma-bufs (NOT_SUPPORTED x15) and requires a dedicated
allocation of every DRM_FORMAT_MOD_LINEAR image (m3-max-34443), so there it never fires. ANV on the
Iris Xe takes both images outside a dedicated allocation, bound in the existing import byte-exact;
first use of an 84 MiB texture 1.37 -> 0.21 ms (m3-max-34453).

Verified in the lane (m3-max-34571, gem10, at 5d5dee7901): clippy -D warnings -p metal2vulkan-runtime
--all-targets --all-features, plain and m2v_cpu_icd. Still running when landed: the lavapipe
in-place and dma-buf suites with the new count test (m3-max-34593), clippy m2v_gpu, PHOENIX, and the
Iris count test with its negative control.

API: adds the field WorkCounts::dma_buf_images_in_import (additive; api_signatures blessed in the lane).
2026-11-15 18:55:56 -08:00
Anees Iqbal 15d4b7f640 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 18:54:58 -08:00
Anees Iqbal aa9c211eac RUNTIME 2408: Render encoders continue the last of several inline instances, and across barriers between draws
A render encoder's pass now leaves its last render pass instance open
for the next render encoder where every instance recorded inline and
nothing records after the last, not only where it had one instance; the
earlier instances end and store in its command buffer as before. The
key of a kept instance after a split is its render pass's shape, its
framebuffer (its own or the first instance's) and the render area it
began over, the layout's extent; PassKey now carries the render area,
so an instance that began over a smaller area than its framebuffer's is
continued only by one of the same area. An instance whose colors are in
the feedback loop layout stays closed.

A memory barrier between draws no longer keeps an instance from
continuing, or from being continued: it records inside the continued
instance as inside its own, against the subpass's dependency on itself
(VUID-vkCmdPipelineBarrier-None-07889). Compatible render passes are
otherwise identical, so they hold the same dependencies, and every
render pass of a shape depends on itself (render_target's Between
draws), by region and view by view as the barrier is (07891, 07893).

Tests: a barrier between the next encoder's draws continues the
instance; the second of a barrier-split pass's two inline instances
stays open for the next encoder. The render_fold lane's target drops
its queue before the clear's, under the tests' two-queue limit, and the
slice lane expects two instances begun, as the counter counts begins.

Also: e3c23a73fc and b2dab0dd2f (render_fold tests: the continuation cases count pipeline barriers;
what ends or forbids a continued instance: a sampled read of the first encoder's attachment, a
DontCare store, a blit or compute encoder between, another array slice, a 4-sample resolve, a
rebind).

Verified in the lane (m3-max-34559, tip 8711dc6b14, lavapipe): the ten continuation cases 10/10;
the full runtime suite 2864 passed, 0 failed; three negative controls by hand (continuation off:
the 6 continuing cases fail on counts with the same texels; the barrier limit restored: the barrier
and last-instance cases fail; the one-instance limit restored: the last-instance case fails).
780M A/B (m3-max-34567, release, base 190f64ca18): glass frame over pages 8.48 -> 7.87 ms (-7%),
private 5.49 -> 4.92 ms (-10%), snapshot private -24%, branch -16%, plain -76/-77% (v1); render pass
instances per glass encoder 1.68 -> 1.19. Still running when landed: the Iris A/B (m3-max-34570) and
clippy x3 (m3-max-34572).
2026-11-15 18:54:17 -08:00
Anees Iqbal 8a8af67803 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 18:49:41 -08:00
Anees Iqbal 873c255ded RUNTIME 2407: Grouping bound: a queue's expected run follows its command buffers' own GPU times
What: the group bound (GROUP_RUN, 16 ms) reads a per-command-queue estimate of its own
(QueueGen::group_run), with the same rule as before: raised at once by a longer run, halved
toward a shorter one. It is fed at each command buffer's completion in place_gpu_times:
- from its GPU duration by its timestamps, the value the long-queue mark already reads;
- where the device answers GPU times from the host, from those placed host times.
Device::flies goes back to the Flight for a VkQueue an unshared queue holds only, so the unshared
hold's Expected and its feed are as they were before 37b1ca8563.

Why: 37b1ca8563 fed the bound from the host's view of each batch's run as its VkQueue's oldest.
That view holds other VkDevices' work on the GPU and the host's latency. Under nextest's parallel
suite on the Radeon 780M (m3-max-34541, at bf0ca5902a), the warm fills' commit-to-completion
times read 0.6 to 825 ms. Queues read past 16 ms, grouping stopped, and five grouping tests
failed. The hazard the bound guards is our own kernel job's length. A command buffer's two
timestamps bracket its own work, and other clients' work does not lengthen them.

Docs: group.rs and the grouping FAST-PATHS row say where the estimate comes from. With
gpu_times_from_host it follows host times, which hold other clients' work too, so under contention
there a queue's batches may stop grouping.

Test: scheduler_held_wakes::a_late_completion_of_short_gpu_work_leaves_its_queue_grouping. A warmed
queue's fill has its completion held unpublished 40 ms (Point::Publish) while its GPU work is
short by its timestamps, then the queue's next group must be kept. Under the host-view estimate
that run reads 40 ms and no batch of the queue would join a group.

Fix forward for RUNTIME 2405 (5021e3b4ac): its regression showed on the 780M as five grouped tests
failing under the parallel suite (m3-max-34541).

Verified in the lane (m3-max-34562, tip c90332ba5e): clippy -D warnings m2v_cpu_icd, runtime and
validation, all targets and features. Still running when landed: the lavapipe set (dropped_work and
the new test), clippy plain and m2v_gpu, rustdoc, and the 75-test 780M rerun under the parallel suite.
Expected, not yet shown: the new test fails against 5021e3b4ac's estimate.
2026-11-15 18:48:54 -08:00
Anees Iqbal 2a13f503ce FAST-PATHS: the grouping row measures its run bound on the Radeon 780M
frame_costs_over_imports, release with --cfg m2v_gpu, before (dcd5b6fc96) and after (37b1ca8563)
on the same node (job m3-max-34529): grouped vkQueueSubmit calls a frame barely move, and no
group went for a batch's expected run.
2026-11-15 18:41:06 -08:00
Anees Iqbal 4334fadfdc Re-bless the engine tables for the 16x16x16 simdgroup matrix fixture
SEMANTICS 2130 (aa5511f61e) added the owned fixture engine/simd_matrix16 (12 kernels). The re-bless on the M3 (m3-max-34524 at 085e1a5e25: bless_engine_inventory, bless_golden_hashes, bless_engine_goldens all 0) adds its 24 rows (.ll and .air.ll x 12) to golden_hashes.tsv and public_fixture_expectations_engine.tsv, and its air_input printout. No existing row moved.
2026-11-15 18:36:47 -08:00
Anees Iqbal a84a88e75a Grouping tests: warm each grouping queue with six fills, and print each warm fill's time
grouped_submissions' warm() prints its fills' times from commit to completion (GROUPED-WARM)

The line bac49a5b1b's message names; it shows how long a grouping queue's first fills ran, which
the queue's expected run takes (unshared_hold::Expected).

Grouping tests warm each grouping queue with six fills in turn

What: the grouped lane's warm(), scheduler_held_wakes' warm() and submit_check_device's paths
test now run six fills in turn on each queue that should group, where they ran one. The lane's
warm() prints each fill's time from commit to completion (GROUPED-WARM).

Why: a queue's expected run takes a first run at once and halves toward later shorter ones, and a
batch groups only within 16 ms of it (GROUP_RUN). On lavapipe, with the merge assumed, two tests
failed at 37b1ca8563 (m3-max-34508), each with one warm fill:
- a_held_group_goes_before_another_queue_s_submission_handler_runs: X was not kept, and no batch
  of the first queue was held at all;
- scheduler_held_wakes::a_held_batch_whose_wake_never_came_goes_at_the_next_slice: the third
  command buffer's group was not kept.
The explanation (a slow first fill on llvmpipe) is inferred, not yet shown; the GROUPED-WARM line
is there to show it. Five halvings bring a first run of up to about 500 ms under the bound.

Fix forward for RUNTIME 2405 (5021e3b4ac): on lavapipe two grouping tests (grouped_submissions::a_held_group_goes_before_another_queue_s_submission_handler_runs, scheduler_held_wakes::a_held_batch_whose_wake_never_came_goes_at_the_next_slice) failed in m3-max-34508 at 37b1ca8563 (73/75): one warm fill there can run past GROUP_RUN, and a queue's expected run takes its first run and only halves toward shorter ones. Test-only. Re-test m3-max-34526 running when landed.
2026-11-15 18:35:27 -08:00
Anees Iqbal 085e1a5e25 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 18:32:48 -08:00
Anees Iqbal aa5511f61e SEMANTICS 2130 / RUNTIME 2406: 16x16x16 simdgroup matrix products: refused as their own feature, Metal's rule below Apple10
What: `air.simdgroup_matrix_16x16x16_[widening_]multiply_accumulate` is now refused in every stage
as `Unsupported{SimdgroupMatrix16x16x16, NotImplemented}` (a new `Feature`), ahead of the 8x8
lowering's kernel-only check. The runtime's `compile_error` answers it as Metal does:
`Needs::MetalGpuFamily(1010)` on a device that does not claim Apple10, `NotImplemented` on one
that does (as `IndirectRenderState`). The owned fixture engine/simd_matrix16 shrinks to one form
per class (float, half, widening signed int8), each with the four transpose-flag pairs, 12
kernels; the probe carries the M3's answer in its header.

Why: Metal itself refuses these products below Apple10. The M3 Max (macOS 27.0.1) refused every
pipeline of the fixture at creation, AGXMetalG15X_M1 code 3, "simdgroup_matrix<T,16,16x16>
operations are supported by GPUFamily10 and later" (job m3-max-34410). No device the runtime
presents claims Apple10: the family lists the "SIMD-scoped matrix multiply operations" row (from
Apple7), refused NotImplemented(SimdgroupMatrix) on every device, and the lod-bias row, a gap. So
the refusal is Metal's own answer, not a device gap: no FAST-PATHS known gap.

Tests: engine_simd_matrix::products_of_16x16x16_are_refused_as_their_own_feature (every
committed profile, the fixture's 12 kernels); runtime_lane::simd_matrix16 (the device's compute
pipeline creation answers MetalGpuFamily of Apple10). REFUSALS.md regenerated, api_signatures
blessed, reach mark added. The engine fixture expectation table and golden hashes take the
fixture's rows on development.

Also: f639b74288 adds the owned fixture (MSL we wrote, compiled by scripts/regen-air-fixtures) and
its Metal probe; 5dbfa3d3d5 imports AirLibrary in the runtime-lane test.

Verified in the lane: m3-max-34499 (msi, at 38d4694b12) clippy -D warnings for metal2vulkan, runtime
and validation (all targets and features) and 45/45 tests, incl. the new engine_simd_matrix test (12
kernels on every committed profile), the error tests, refusal_surface, api_signatures, api_surface;
m3-max-34514 (gem10, at 5dbfa3d3d5) clippy m2v_cpu_icd and runtime_lane::simd_matrix16 on lavapipe
(Needs::MetalGpuFamily(1010) for all 12). Clippy m2v_gpu (34516) still running when landed.

API: adds Feature::SimdgroupMatrix16x16x16 (additive; api_signatures blessed in the lane).
2026-11-15 18:32:00 -08:00
Anees Iqbal dc9d9a4ba9 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 18:30:39 -08:00
Anees Iqbal 5021e3b4ac RUNTIME 2405: Grouped submissions: a group's summed expected GPU run stays within 16 ms
What: a batch joins a held group only where its queue's expected run is known and keeps the
group's expected runs, summed, within GROUP_RUN (16 ms). Otherwise the group goes first
(GroupEnd::Long, WorkCounts::group_ends_long), and the batch leads the next group where its own
run is known and within the bound, else goes alone. The expected run is unshared_hold::Expected,
which was fed only on a VkQueue an unshared queue holds. It is now fed on every VkQueue whose
batches group: Device::flies enters each batch there in the Flight. The hold's decisions still
read the Flight only where other queues' batches are held back.

Why: the driver runs a group as one kernel job, and Linux's amdgpu ends a job past its 2 s default
timeout with no error the device reports. On a Radeon 780M a single 3.2 s command buffer was ended
and the one behind it dropped. Four batches that each finish alone could cross the timeout
merged. With the bound, merging adds at most 16 ms of the others' expected work to any job. 16 ms
is the owner's line for an intolerable wait, and it also caps how late grouping makes a member's
completion seen (the FAST-PATHS row said about 20 ms behind a 20 ms batch). A queue none of whose
batches was seen complete has no expected run, so its batches go ungrouped until one completes.

Tests:
- tests::group_run: the admission rule (unknown, alone, a full group of quarters, 12 + 5 ms,
  overflow).
- runtime_lane::grouped_submissions::a_queue_s_batches_group_within_their_run: on a grouping
  device with one VkQueue, behind running work on another queue, a fresh queue's batches group
  none, a warmed one's group, and none after a 40 ms command buffer of its own.
- The grouped lane scenarios, and submit_check_device's paths test, warm each grouping queue with
  one completed fill first. The behind-running-work tests measure the fills' rate on a queue of
  its own, so the B queue's expected run stays its first fill's.
- Every place that sums the group ends counts the new end, and frame_costs prints it.

Docs: group.rs and unshared_hold.rs module docs, the grouping FAST-PATHS row (its bound and its
cost line), and WorkCounts::group_ends_long.

Verified in the lane (m3-max-34508, tip 37b1ca8563): clippy -D warnings with m2v_cpu_icd, runtime and
validation, all targets and features. Still running when landed: lavapipe tests (group_run, the
grouped lane, unshared_hold, submit_check_device, kernel_end_device, commit_and_submit,
queue_share_device, frame_costs), clippy plain and m2v_gpu, rustdoc, and the 780M before/after.
Expected, unverified: conformance cost records' grouping counts (not the cases' own, never gated)
may drop in cases that commit on fresh queues.

API: adds the field WorkCounts::group_ends_long (additive; api_signatures blessed at landing).
2026-11-15 18:29:57 -08:00
Anees Iqbal 7ed19b94bb Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 18:26:23 -08:00
Anees Iqbal 0ac105376c Parked images: a device-test hook for the parked cap; the shadow bench in 2 MiB pages with an unparked arm
What: Device::park_dma_buf_images_at_most (crate device tests only) sets how many images the
device parks, as keep_resident_host_imports sets the residency's most. 0 parks none: an
in-place image then goes with its import, as before parking. The default stays PARKED_MOST, so
behaviour is unchanged. dma_buf_parked_images checks that path: with the cap at 0, a used and
dropped texture parks nothing, and its image's import is freed.

texture_shadow_bench: each RAM is written through a 2 MiB-aligned shared mapping of the whole
memfd, advised MADV_HUGEPAGE as QEMU advises guest RAM, or MADV_NOHUGEPAGE for a labelled 4 KiB
arm. Every buffer arm runs over both, and the bench prints shmem_enabled and each RAM's
ShmemPmdMapped as evidence of the pages it got. A third arm, unparked, runs the in-place cycle
with the cap at 0 as the same binary's "before".

Why: the 4 KiB-page bench overstated the kernel's per-page import cost about 10x against guest
RAM, and the parked change needs a same-binary before and after.

Verified in the lane (msi job m3-max-34459, tip b4576231cf): clippy -D warnings plain, m2v_cpu_icd and
m2v_gpu and rustdoc of the runtime, all targets and features; lavapipe tests::dma_buf_parked_images
passed (made 5, parked 6, taken 2, missed 5, released 4; the source asked 5 times for 7 textures).
Negative control (m3-max-34461, take_parked answering None): the test failed at "the image taken
after its move rests in GENERAL, no move noted". The PHOENIX bench runs after landing.
2026-11-15 18:25:41 -08:00
Anees Iqbal 45e7a1edeb Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 18:24:21 -08:00
Anees Iqbal 09a3f0505b RUNTIME 2404: Runtime: render encoders over one target continue one render pass instance
What: a render encoder whose pass recorded its one instance inline, touched nothing but its
attachments, and records nothing after that instance leaves it open in its group's tail. The
next render encoder whose first instance renders the same subresources through a compatible
render pass and loads every attachment keeps its draws, and at its first split or its end records
them into that instance with no end, barrier or begin between, joining the group; else it closes
the group and begins its own. Rasterization order inside one subpass orders the later draws'
attachment accesses after the earlier ones', as Metal's load after store does. Counted:
WorkCounts::render_passes_continued.

Why: a glass-panel frame of 107 render encoders over one target spends its GPU time in
per-encoder boundaries: on the Iris Xe about 50 us per boundary (23 pass + 15 barrier + 12
command buffer), on the 3090 a frame of one encoder costs 0.59 ms against 1.39 ms with
plain encoders (about 7.5 us per boundary). Folding and carrying across fences did not move the
glass mix; continuing the pass removes the boundary itself.

Also: walk_costs / walk_glass_frame (runtime lane, ignored by default) measure a glass frame of
107 encoders by recipe and the forms that take a plain encoder's GPU cost apart.

Verified in the lane (m3-max-34473, tip 7ab5efb5f0): the runtime lib test build, and on lavapipe the
render_fold, draw_again, inline_splits, inline_continues, snapshot, attached_read and
leading_snapshots suites, 69/69. Expected, not yet run: the 780M and Iris A/B, a negative
control, clippy x3 and the full runtime suite; the lane runs them after landing.

API: adds the field WorkCounts::render_passes_continued (additive).
2026-11-15 18:22:08 -08:00
Anees Iqbal b650408113 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 18:18:40 -08:00
Anees Iqbal 1acb205fb0 RUNTIME 2403: Runtime: a command buffer whose timestamps read unavailable after its queue passed it fails as Metal's victim
What: in complete_seen, a command buffer that would complete with no error, but whose own
timestamps read unavailable (Stamped::Read(None)) once its queue's timeline passed its last batch,
now fails with GpuRecoveryVictim. Its GPU times read 0, the new WorkCounts::unrun_command_buffers
counts it, and nothing counts against its queue. Its host-page logs hear of it as of a failed
command buffer.

Why: Linux's amdgpu ends a job past its timeout (2 s by default) with no error RADV reports. On a
Radeon 780M (Mesa 26.2.6, Linux 7.3.3) a 3.2 s fill was ended, and the command buffer queued
behind it on the same queue never ran, yet both completed with no error. Read-only from Mesa
26.2.6:
- radv_device_check_status checks only OpAbortKHR;
- syncobj waits pass no fence error;
- VK_KHR_device_fault reports only GPUVM faults and shader aborts (radv_device.c:2145).
The timestamps are the documented signal. A signal's first scope holds "all commands that occur
earlier in submission order" (Semaphore Signaling), and "a query is made available by the
operation of ... vkCmdWriteTimestamp" (Queries). So a query read unavailable after the signal was
never written. The completion turn already reads both queries with availability: the check adds
no Vulkan call, one comparison.

Docs: gpu_time.rs, the GpuRecoveryVictim and WorkCounts docs, the runtime README's lost-device
section, and two FAST-PATHS known gaps:
- work a driver drops is found only where the command buffer writes timestamps (not with host
  GPU times, MoltenVK on Apple's GPUs, a family of no timestamp bits, no free slot, or an
  adopted device);
- amdgpu's 2 s default job timeout fails a single command buffer that Metal's longer watchdog
  runs.

Test: tests/dropped_work.rs injects the unavailable read (completion::trace::unstamp_of), with no
GPU hang. A command buffer whose stamps read as written completes and counts 0. The injected one
fails as GpuRecoveryVictim with GPU times 0 and counts 1. The queue's next command buffer
completes and its fill lands.

Verified in the lane (m3-max-34463): clippy plain, m2v_cpu_icd and m2v_gpu and rustdoc of the runtime; lavapipe
35/35 incl. tests::dropped_work (injected unavailable stamps fail the command buffer as GpuRecoveryVictim; the
queue's next command buffer completes), gpu_time, device_recovery, completion and stall.

API: adds the field WorkCounts::unrun_command_buffers (additive; api_signatures blessed at landing).
2026-11-15 18:17:58 -08:00
Anees Iqbal dcd5b6fc96 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 18:10:43 -08:00
Anees Iqbal 3442c96054 RUNTIME 2402: Park an in-place dma-buf image with its import for the next texture over the same pages
A texture in place over a no-copy buffer's dma-buf pages made a new
DRM_FORMAT_MOD_LINEAR image and a dedicated import of a new udmabuf of its
pages each time, so the kernel pinned and mapped every page again and the
first submission waited for the page tables: on the Radeon 780M an 84 MiB
texture took 1.4 ms to make and its first command buffer 7.1 ms against
2.2 ms over the device's own memory, every frame for a guest that remakes
its texture over the same pages.

As such an image goes (its texture and every command buffer that used it
gone) it now parks, VkImage and import, under the HostImport of its pages,
keyed by its plan, its texels' address among the pages, pitches and memory
type (dma_buf/parked.rs). The next texture in place over the same pages
tries each plan in its usual order and takes a parked image of that plan at
its texels before asking the source. An image whose first move ran rests in
GENERAL on our queue family (spec 12.10, 7.7.6: ownership stays with the
acquiring family; 7.9: host writes are visible to later submissions), so
the taken one notes no move; one never moved notes the same acquire a new
image notes. Not parked: images whose VkImage was handed out, the in-place
check's, rebind or detach replacements, past 64 per device.

Parked images are released by the residency thread after IDLE (2 s), count
as one listed import each against RESIDENT_MOST (released in park order
among the releasable imports' groups), go on host_range_remapped over their
buffer's bytes, and go with the HostImport before its deallocators.

WorkCounts: dma_buf_images_parked, dma_buf_images_taken,
dma_buf_images_missed, dma_buf_images_parked_released (api_signatures
blessed). New device test tests/dma_buf_parked_images.rs.

Verified in the lane (m3-max-34434): clippy -D warnings of the runtime, all targets and features; on lavapipe
(m2v_cpu_icd) tests::dma_buf_parked_images (6 textures over one buffer: 4 images made, 6 parked, 2 taken with
no source call and the CPU's later bytes, equal to a fresh image's; released on host_range_remapped and with the
buffer), dma_buf_plane_offset and host_residency's releasable-import test. The PHOENIX bench follows.
2026-11-15 18:09:55 -08:00
Anees Iqbal 825997e49c Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 18:08:51 -08:00
Anees Iqbal a9ebe9154b RUNTIME 2401: Draws again keep only a key's own pipeline, never its general form's
A draw whose key's own VkPipeline is still being made draws with its general form's
(begin_graphics_pipeline returns Made with own false), and render.rs kept such a draw to draw
again: its draws again then recorded through the general form after the key's own was made. In
builds with debug assertions a draw again also takes every step, which found the own pipeline
made, and draw_again's check panicked ("a draw again kept another draw: its [\"made\"] differ").
Since RUNTIME 2398 the Iris Xe's profile keys a storage view bound at offset 0
(RangeAtBindOffset), so every first draw of a state with such a slot differs from the creation's
general form there: the consumer's Iris leg (m3-max-34406) panicked in 7 of 2256 graphics tests,
by timing. Release builds drew correct pixels (the general form reads at the residual, which the
binder writes for every form) and only missed the own pipeline while the draw stayed kept.

The draw's lookup now carries whether its pipeline is the key's own (a shape memo hit is: the
memo keeps only a key's own), and a draw is kept only where its pipeline is made and its own;
else it keeps nothing and counts under draws_unkept_making, as the draw-again tests' docs
already said ("a draw recorded against a making, or of a residual form, keeps nothing").

Test: uniform_bind_offsets' a_draw_through_its_general_form_keeps_nothing draws cof_device (a
vertex device buffer at offset 0) four times in one encoder, the first with the pool held: on the
workaround's profile the first takes the general form and keeps nothing, the second takes every
step through its own, the third (checked) and fourth draw it again; elsewhere the first is kept.
Without the fix its first draw again panics there.

Regression of RUNTIME 2398 on the Iris Xe: the consumer's Iris leg (their m3-max-34406) panicked in 7 of 2256
tests at draw_again.rs "a draw again kept another draw: its made differ"; their 780M leg passed. Release
drew correct pixels (the general form reads at the residual). Verified in the lane: clippy 0 (m3-max-34437);
the lavapipe suites and the Iris run with a negative control follow from the lane.
2026-11-15 18:08:08 -08:00
Anees Iqbal af372e849c Lane busy work: one GPU job stays under the kernel's timeout; host copies past the window ask again
What: the runs behind running work (behind_running_work, behind_another_queue_s_handler,
behind_a_kept_signal) calibrate A's fills by the GPU's time of the calibration command buffer
(first_use::gpu_took) instead of its commit-to-completion wall time, and cap every stretched A
(and behind_a_kept_signal's long B) at A_MOST, 1 s of GPU time at the measured rate. A stretch
past the cap repeats at the cap. Each run writes a GROUPED-A line with A's fills, the time they
take at the calibration's rate and A's GPU time.

Why: round e8d0bfc33c's PHOENIX lane leg 2/4 (gem10, m3-max-34259) failed
a_held_group_goes_before_another_queue_s_submission_handler_runs with "buffer 0: bytes off its
fill: left 4096": all four command buffers completed with no error, yet B's whole fill was never
run. A ended before Y's handler in runs 1 to 3, so the loop doubled A to 8 times its calibrated
fills, one kernel job. At 17:18:48 the node's kernel logged "ring gfx_0.0.0 timeout ... Ring
gfx_0.0.0 reset succeeded", naming a metal2vulkan_validation process. amdgpu's default job
timeout on that kernel is 2 s (Linux 7.3.3-cachyos, modinfo: "lockup_timeout ... default:
2000"; no override on the command line). The reset ended A and dropped B, which A's context had
emitted behind it; RADV 26.2.6 reported neither (radv_device_check_status checks only
OpAbortKHR, and the kernel did not refuse the context's later submissions: X and Y ran).
Measured on a Radeon 780M (um790, same kernel, m3-max-34394): one 128 MiB fill takes 2.09 ms of
GPU time; A of 192 fills took 0.39 to 0.45 s, of 384 fills 0.80 s, so 8 x 192 fills is about
3.2 s, past the timeout. The wall-time calibration also stopped at 4 fills (12 or 24 returned,
28 to 50 ms of GPU work) in 3 of 10 quiet runs, where the others took 192: the first
calibration command buffer carries first-use costs, so a short A ends early and the loop doubles.
Windows' default TDR is 2 s too, so the cap is half of it.

Not a regression of c218071502..e8d0bfc33c: both shas passed every run of m3-max-34394 (3 quiet,
1 at stretch 2 and 3 beside 8 busy CPU threads and lane partition 2/4, each), with no stretch
past 2 and no ring timeout.

Test: a_stretched_command_buffer_stays_within_its_job_bound (no GPU) asserts that every stretch
the loops reach keeps one command buffer within A_MOST at the leg's measured rate (192 fills at
2.09 ms), where 8 x 192 fills would take about 3.2 s, and that a calibration already past the
bound is cut to it. It fails without the cap.

first_use: a host copy whose busy window the host outlasted is asked again

What: shared_textures_copy_on_the_host_while_the_gpu_is_busy runs each storage mode's calls
through busy_premise's until_premise_held, as device_copies' did_modify_range steps do. Each try
makes a new texture and new busy work, checks its bytes and the copies' counts on every try, and
where the busy work's end mark turned before the calls (or, for copies on the host or the staging
queue, before they returned) writes a LANE-BUSY-MISS line with the time to the busy work's
scheduling, each call's time and the busy work's GPU times, and tries again, at most 3 times. A
copy that waits for the busy work misses every try and fails with each try's times, as before.

Why: round e8d0bfc33c's PHOENIX lane leg 2/4 (gem10, m3-max-34259) failed it with "Ok(Shared) on
AMD Radeon 780M: a host copy waited for the busy work (get_bytes 139.749us, replace_region
666.597us)": the end mark read 0 right before the calls and ENDED after a get_bytes of 140 us.
The calls did not wait for about 2 s of busy work; the test's thread was held past the busy
window between the check and the call, in a leg at its 3 GiB memory limit (peak 3.0 of 3 GiB)
while a virtual machine booted on the node. The test passed at both e8d0bfc33c and c218071502 in
every run of m3-max-34394 (Radeon 780M on um790: 3 quiet runs, 1 more and 3 beside 8 busy CPU
threads and lane partition 2/4, each), its calls taking 20 to 222 us; the miss did not recur.

docs/VALIDATION.md and busy_premise.rs name the test beside device_copies.

Verified in the lane: lavapipe 10/10 (m3-max-34415, GROUPED-A stretch 1: 48 fills, 447 ms of GPU, cap 1 s) and
clippy under m2v_cpu_icd 0; the m2v_gpu archive built (34416). Not a regression of c218071502..e8d0bfc33c:
both shas pass quiet and loaded on PHOENIX (m3-max-34394), and the red leg's ring timeout followed the
stretch to 8x (~3.2 s in one job, past amdgpu's 2000 ms lockup_timeout). PHOENIX run follows.
2026-11-15 18:03:50 -08:00
Anees Iqbal 28aaeb2721 heap_trimmed's docs: the wide chain's free heap on the Radeon 780M, measured alone
70409f0ea2 gave RADV's free heap for the 20,000-step, 600-live chain as
an extrapolation from the 40,000 and 80,000 rows (about 1.4 times the
trim floor). Measured, the kernel made alone in a process of its own on
the Radeon 780M (RADV, Mesa 26.2.6; probe archive of scratch 648efdb10f,
job m3-max-34324): 345,583,872 bytes free after its first making, 1.6 s,
a trim after each of its two makings. The docs now say that: 346 MB,
1.3 times the floor.

Verified: cargo fmt; comment only. The lint job follows.

Verified: clippy plain, m2v_gpu and m2v_cpu_icd and rustdoc of the runtime crate passed (m3-max-34352).
2026-11-15 17:43:44 -08:00
Anees Iqbal cc1d619c7a heap_trimmed takes ANV's stage-bound refusal of the long chain; the wide chain is 20,000 steps
On the Iris Xe (ANV) the test panicked at its first kernel: the long chain
(320,000 steps, 64 live) weighs 320,038, past COMPILED_STAGE_WEIGHT
(99,109), and the device refuses it honestly (Unsupported { StageSize,
DriverDefect(CompilerMemoryGrowsWithStageSize) }, rounds ef313200e2 and
c218071502, leg iris:gputime). The shapes NVIDIA's compile frees past the
trim floor are all past that bound (the module's table: 303 MB at
240,000 steps, 189 MB at 80,000 with 600 live), so no long chain serves
both.

The test now goes by the device's answer: state() returns None only for
that exact refusal, whose symbol names an entry weight past its bound;
every other error fails the test. trims > 0 and the resident bound stay
asserted on every device, so some in-bound kernel must trim on ANV.

A probe (scratch 648efdb10f, never landed; Iris job m3-max-34234), each
shape made once in a process of its own, free heap from mallinfo2 after
the making: 20,000 steps at 600 live freed 794 MB in 145.7 s (peak 3.0
GiB); 40,000 and 80,000 at 600 live did not finish their first making in
240 s; 96,000 at 64 freed 289 MB in 160.9 s at a 7.2 GiB peak. So the
wide chain takes 20,000 steps: three times past the floor on ANV, and on
RADV, at about 18.6 KB a step at 600 live (739 MB at 40,000, 1,506 MB at
80,000 on the 780M), about 1.4 times; NVIDIA's trim comes from the long
chain, and the shorter wide chain halves its time there. The test line
now prints the free heap after each kernel's first making and each
kernel's time, so every device's run shows its premise.

Verified: cargo fmt. The build, clippy and the runs on the Iris Xe, a
PHOENIX and an NVIDIA GPU follow.

Verified: the test passed on the Iris Xe (m3-max-34319: the long chain refused past the stage bound,
the wide chain 4 trims, 372 s), the Radeon 780M (m3-max-34316, and the wide chain alone trims 1.29x
the floor, m3-max-34324) and the RTX 5080 (b5080 entry trimiris-heaptrim-173211); clippy under
m2v_gpu 0 (m3-max-34306).
2026-11-15 17:40:26 -08:00
Anees Iqbal 45af992f33 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 17:39:13 -08:00
Anees Iqbal 0427b71281 RUNTIME 2400: Uniform views keep their residual form where storage views read at their bind offsets
On the profile that takes DriverWorkaround::PushReadsLengthenThreadPayload (ANV, Mesa 26.2.6,
Iris Xe RPL-P) the runtime read every view at its bind offset, a uniform view's included. A
uniform view read so compiles there to a constant-cache block read (send.hdc_ro
oword_block_read:owords4, job m3-max-34232) in place of the untyped read the residual form takes,
which cost about 18 us a dispatch more than the push word it saved. Now the device reads its
uniform views at their residuals, as on every device without
DriverFact::ConstantOffsetUniformReadsPreloaded, and the plan keeps the storage views' key:
reads_views_at_bind is the fact's alone again, and the plans and dispatch regions take
uniform_residual_form (each uniform view's RangeAtBindOffset at 0, a storage view's as the plan
gives it), which is residual_form wherever no storage view declares the key. Runtime only: no
translation output moves.

Measured on the Iris (job m3-max-34275, dispatch_chain, 4480 groups of 256, 200 dispatches a
command buffer, 7 interleaved rounds, medians in us a dispatch; every run checked its words):

  arm                   base f4082938de   landed d3b1dbdbe0   this change
  binds 1, serial            120.15             55.90             55.84
  binds 1, raw-barrier        55.74             55.75             55.75
  binds 4                    142.71            161.78            142.77
  fixed                      143.19            161.77            143.17
  moved                      143.10            165.23            143.04
  tex                        119.63            128.29            119.40

The storage-only kernel stays at raw speed, and every other arm is within 0.25 us of base.

Tests: general_form's a_plans_key_zeroes_its_uniform_views_and_keeps_its_storage_views (the
uniform-only residual form keeps a storage view's constant, the residual form zeroes both);
pipeline's every_committed_driver_reads_its_uniform_views_at_their_residuals again; and
uniform_bind_offsets' two kernel creation tests now key the kernel's own pipeline where its
output, a storage view bound at offset 0, declares the key (keys_its_own), on the workaround's
profile as on a device with the fact. Docs: residual.rs, the workaround's doc, the bind state's
uniform_views_at_residual, and docs/API.md.

Also: the test suites follow the Iris Xe's new workaround (its profile fingerprint differs from the
UHD 770 RPL-S by it; the stage-bound test's reference profile). Verified in the lane: clippy for
metal2vulkan and the runtime, all targets and features (m3-max-34321); the Iris run of
uniform_bind_offsets and inline_continues follows from the lane.
2026-11-15 17:38:32 -08:00
Anees Iqbal a50148491b Runtime lane: heap storage reads by the formats' bits without the feature
What: runtime_lane/heap_storage_reads.rs makes the cfg's device without
shaderStorageImageReadWithoutFormat (withheld) and runs a kernel that
reads an argument buffer's read_write texture into a buffer and writes
(1, 0, 1, 1) back through the same handle, for the six float read-write
tier formats and BGRA8Unorm, RGB10A2Unorm, RG11B10Float. Each read is the
uploaded texel where the heap's view has STORAGE_READ_WITHOUT_FORMAT and
zero where it lacks it (asserted never for a tier format); each write
stores its bytes either way; the validation layer reports nothing.

Why: device evidence for the bits-alone route (lavapipe with the feature
withheld; the Iris Xe as it is, where the three non-tier views lack the
bit).

Verified: lavapipe with the feature withheld (m3-max-34302): 3/3 lane tests, the six tier formats read
their uploaded texels and every write stored, no layer report; clippy under m2v_cpu_icd 0. The Iris
run (m3-max-34313) follows from the lane.
2026-11-15 17:32:00 -08:00
Anees Iqbal bffeca8021 Re-bless the golden hashes and fixture expectations at SEMANTICS 2129
The heap storage-read change (4a06ce915d) moves 52 rows: the heap fixtures' modules on every profile
(48 cells each on most), and the a8r_buffers expectations, now translated on the profiles that read by
the formats' bits. Blessed on the M3 at a3c1f190cb (m3-max-34299: inventory, golden hashes and
printouts 0). Merged-tree clippy, plain and m2v_gpu, passed at a3c1f190cb (m3-max-34300).
2026-11-15 17:30:08 -08:00
Anees Iqbal a3c1f190cb Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 17:26:42 -08:00
Anees Iqbal 4a06ce915d SEMANTICS 2129, RUNTIME 2399: Heap storage reads by the formats' own read bits on a device without the feature
A compute pipeline that reads a read_write argument-buffer texture was refused
Unsupported{ArgumentBufferTextures, needs ShaderStorageImageReadWithoutFormat}
on a device without shaderStorageImageReadWithoutFormat (ANV on Gfx12.0, the
Iris Xe), so the guest's work waited on a nil pipeline. Vulkan 1.3 and
VK_KHR_format_feature_flags2 enable the SPIR-V capability
StorageImageReadWithoutFormat, and a read of a view without a format is then
valid wherever the view's format has STORAGE_READ_WITHOUT_FORMAT_BIT (spec
19.9.3, VUID-vkCmdDispatch-OpTypeImage-07028). The slot path already took
that route; the heap path checked the feature alone.

- declare_heap takes a storage (and storage texel buffer) read by the
  feature or by the formats' bits (DeviceProfile::storage_reads_by_format_bits),
  and on such a profile needs the read bit of the class's neutral, which a
  null handle reads.
- The binder keeps each storage view as before (writes unchanged). On such a
  profile, a member whose view's format lacks the read bit is held for its
  writes and flagged (new entry flag FLAG_STORAGE_UNREADABLE, bit 28: the
  texel-class field narrows to the 12 bits its indices use), and a storage
  read through its handle reads the null element, as a nil texture's read
  does. A member of one of Metal's read-write tier formats, whose read
  Metal's contract defines, is refused without the bit instead.
- handle_entry_flags takes the profile (the flag is the device's).

On the committed Iris profile every Metal read-write tier format has the
read bit; RGB10A2, BGR10A2, RG11B10Float, BGRA8 and the 16-bit packed
formats do not (Mesa's isl: no Gfx12.0 typed reads).

A read-write tier format whose view lacks the bit is not refused at the member (binding runs for
every shader-writable texture of the runtime's device-wide heap, so a refusal there dropped the
texture's writes on a profile such as roadmap-2022, job m3-max-34236): lower::texture::slot::
declare_heap refuses the function that reads a heap storage class where any tier format would be
held in that class through a view without the bit, naming each view's bit; the member is held for
its writes, flagged. Docs: API.md accepted difference, FAST-PATHS known gap and device-gap row,
REFUSALS.md.

Verified in the lane (m3-max-34272): clippy -D warnings for metal2vulkan, metal2vulkan-runtime and
metal2vulkan-validation, all targets and features; nextest over the heap, handle, storage, profile,
fast_paths, without_format, texel_class and tier tests plus api_signatures, refusal_surface and
api_surface: 317 passed. A synthetic Iris profile with RGBA16F's read bit cleared refuses the
reading kernel naming that format; the committed Iris compiles it. The lavapipe lane with the
feature withheld and the Iris run follow from the lane.
2026-11-15 17:26:02 -08:00
Anees Iqbal a79d16b428 Re-bless the golden hashes at SEMANTICS 2128
The ANV at-bind workaround (d3b1dbdbe0) re-keys the intel-irisxe-rplp-anv profile (fingerprint
6d95bb254f9f9d66 -> 2f820bef4bfb9669). Blessed on the M3 at 726532bd21 (m3-max-34227: inventory,
golden hashes and printouts 0); every changed cell (1939 rows) is in that profile's column, no other
profile's cell moved.
2026-11-15 17:11:33 -08:00
Anees Iqbal 726532bd21 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 17:08:25 -08:00
Anees Iqbal d3b1dbdbe0 SEMANTICS 2128, RUNTIME 2398: Buffer views read at their bind offset where a pushed word lengthens every thread's payload
On ANV (Mesa 26.2.6) on the Iris Xe RPL-P, a compute function that reads a client push word
gets a longer per-thread payload (the base workgroup id moves 17 registers further), and a
light kernel runs about 2.2 times as long: 120.2 us against 55.7 us a dispatch on the same
module with the push read removed (raw Vulkan chains, jobs m3-max-34063 and m3-max-34038).
The 780M (RADV) shows no such gap (m3-max-34031). The runtime's storage views read their
SlotBindOffset residual on every access, so every kernel paid it there.

A measured DriverWorkaround row, PushReadsLengthenThreadPayload, on that driver and GPU:

- the translator declares SpecKey::RangeAtBindOffset for storage views too on that profile
  (access plan's storage_at_bind; the pulled vertex fetch of a shared slot folds its residual
  under the same key), so a key at 1 reads no push word once the driver folds it;
- the binder sets a storage view's key only at bind offset 0, where the runtime tells offset 0
  apart at the slot (StageTable::zero_offset_views, class ZERO_OFFSET_CLASS), and only where
  instantiation's range starts there (starts_at_bind), so the bytes before a bind offset stay
  reachable through the range from the buffer's start at every other offset;
- the runtime keeps the zero-offset slots beside the uniform ones (AtBindViews), leaving out a
  slot once it is bound at another offset, and reads views at their bind offsets on that
  profile (reads_views_at_bind), the uniform views' existing form included.

Every other profile declares no new key and its modules are unchanged; its stage tables leave
zero_offset_views 0, so its shapes and plans are as before.

Also a FAST-PATHS known gap: on the Iris Xe, kernels over exportable or host-pointer-imported
memory run about 2.2x (125.53 and 122.95 us against 55.73, m3-max-33760), cause unobserved;
zero copy stays.

Tests: engine_access (a storage view's module at key 1 reads no SlotBindOffset, at key 0 it
does, answers on the interpreter; no key on the other profiles), the binder's offset-0 rule and
class, the committed profiles' form choice, and a runtime device test of a storage view at
offset 0 and past it.

Verified in the lane: touched tests in msi jobs 34174/34198 (engine_access, bind::, fast_paths,
api_signatures, the runtime pipeline and argument_table tests); lavapipe m2v_cpu_icd 21/21 (34190:
uniform_bind_offsets and the new storage test, answers at offset 0, past it and at 0 again); clippy
plain 0 (34198), m2v_cpu_icd and m2v_gpu 0 (34200); rustdoc 0 (34213). golden_hashes reads stale only
for intel-irisxe-rplp-anv (re-keyed: 1788 cells, fingerprint 6d95bb254f9f9d66 -> 2f820bef4bfb9669); no
cell under an unchanged key moved. The table is re-blessed on development.
2026-11-15 17:07:41 -08:00
Anees Iqbal 244fa02286 SEMANTICS 2127, RUNTIME 2397: Generic pointers move with whole-struct copies of thread memory
A generic pointer stored into a thread struct that a constant-length memcpy or memmove copies
to another alloca was refused as GenericPointer(Memory) when loaded from the copy: the generic
pass counted every copy into a cell as a write of other bytes over its slots. A struct holding
a generic table pointer, copied whole into each callee's argument object, hits this.

canon::generic::cells now has slot copies, mirroring the memory plan's: a copy of a constant
length between two allocas at constant offsets moves each source slot the copied bytes hold
whole to the destination slot at the same distance, along chains of copies, and the
destination slot takes the source slot's pointers in the plan's union-find (nullness flows
from source to destination). It is a slot copy only where neither cell has a generic access
at an unknown offset, no slot straddles either end of the copied bytes, every destination
slot inside them is a moved one and the source is not open; any other copy still writes its
bytes, and a copy from an open cell opens its destination as before.

Tests (canon::tests::generic_pointers): a struct holding a generic pointer, 7 and null copied
whole, and copied on again, is loaded as the device pointer stored with its queries answered;
a copy that splits a slot, and one into a struct read at an unknown offset, still refuse as
Memory.

Verified in the lane: a negative control with generic.rs, generic/cells.rs and generic/plan.rs at their
base refuses the whole-struct copy test while the splitting and unknown-offset test still passes
(m3-max-34173); clippy in all three configurations, rustdoc and the metal2vulkan-air suite 572/572
(34187, 34188). A release linked census of 265 system kernels (34178): 244 translate (was 234),
slowest 1.20 s, largest 198.8 MiB.
2026-11-15 17:02:04 -08:00
Anees Iqbal e8d0bfc33c heap_carried_reads: a heap shadow's decode expectations follow its twin
runtime_lane::heap_carried_reads::a_heap_s_carried_textures_read_as_outside_a_heap failed on the
Iris Xe (round c218071502, iris_lane_1_2): for ETC2RGB8 at Metal's heap answer, "two reads in one
command buffer, shadowed true: Counted { copies: 1, decodes: 0 }" and "a sample after
replaceRegion decoded nothing". ANV samples ETC2 itself, so that texture is a shadow of the heap's
bytes with no twin ("twin none" in its HEAPDECODE line). The test took every shadow to have one: it
asked decodes == copies of the reads and a decode after replaceRegion. Its counts are the
product's rule: read x2 copies 1 (one copy in, the second encoder carrying the image), sample 1,
blit+sample 1, replace+sample 1, as the same Iris's twinned 4:2:2 shadows copy (each plus one
decode). PHOENIX and lavapipe passed because RADV and lavapipe lack ETC2, so their ETC2 shadows
have twins.

Now the case reads whether its texture took a twin (carried-decoded-twin at its making, as its
HEAPDECODE line already did). The two reads in one command buffer must take exactly one copy in
for a shadow, decoded once with a twin and never without; before, a twinned shadow passed with
any number of copies. A Shared shadow's samples after replaceRegion must show a decode with a twin
and a copy in without one. An image in the heap's memory still decodes nothing. So a second copy
inside one command buffer fails both branches. The FORMATS and module docs say ANV samples ETC2.

Verified: the test passed on the Iris Xe (ANV, m3-max-34147: ETC2RGB8 shadows twin none, read x2 copies 1
decodes 0, replace+sample copies 1 decodes 0), PHOENIX (m3-max-34145) and lavapipe (m3-max-34118); clippy in
all three configurations and rustdoc passed (34118, 34146).
2026-11-15 16:55:52 -08:00
Anees Iqbal aaeb7fa475 SEMANTICS 2126, RUNTIME 2396: Static initializers evaluate integer vectors lane by lane
A static initializer's integer arithmetic, comparisons and casts of vectors were left
unevaluated (the folder's integer folds take scalars), so a module whose initializer builds a
vector global from its function constants refused at specialization: Unsupported
StaticInitializer. MPSCore's stitchable functions are such modules (their initializer stores
<4 x i32> and <4 x i8> globals built from two ushort constants by scalar bit tests inserted
into undef vectors and a zext of a <4 x i1>), so every kernel linking them, 257 of the census's
265 refused MPS rows once linked, refused there.

Folder::lanewise applies a scalar integer fold to each lane of constant vectors of the result's
lane count; the static-initializer interpreter takes it for integer binops, icmp and integer
casts. A vector with an undef or otherwise unknown lane is still not evaluated (the module is
refused as before). SCCP's folds are unchanged: only static initializers evaluate vectors.

Test: canon::tests::static_vectors builds that initializer's shape (lanes inserted into undef,
scalar compares into <4 x i1> then zext, trunc/lshr/and of a scalar, and splat/lshr/and/icmp/
zext/trunc on vectors throughout) and checks the kernel's stores fold to the lanes' values;
a vector with an undef lane still refuses.

Verified in the lane: canon::tests::static_vectors 2/2 and a negative control without the fold
(it refuses); metal2vulkan-air clippy clean and its suite 570 passed (m3-max-34114); a release
linked census of the 265 refused MPS rows with this commit (m3-max-34128): 234 translate and pass
spirv-val, slowest 0.39 s, largest 199 MiB.
2026-11-15 16:44:14 -08:00
Anees Iqbal 44904ec1fe Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 16:43:07 -08:00
Anees Iqbal 7049627f79 RUNTIME 2395: Managed no-copy buffers: the caller's promise of zero bytes is zeroed on the device, not copied in
What: `HostMemory::with_zero_from(offset)`, a runtime extension with no Metal counterpart. The
caller promises that a no-copy buffer's bytes from `offset` to its length read zero when it is
made (a buffer its program made with no bytes, or with fewer than its length). A `Managed` one on
a device without unified memory then makes its GPU copy's bytes from `offset` to the length as
zeros the device writes in its own memory (one word-aligned vkCmdFillBuffer registered before the
making's copies in, `Buffer::zero_device_copy_first`). Only the bytes before the offset, and the
rest of the last page past the length, are copied in from the pages, so no import is held for the
zeros. New counters: `WorkCounts::managed_device_copies_zeroed`, `managed_bytes_zeroed`. Nothing
else takes the promise: a buffer that lies in its pages, a copied host buffer's first read, heaps,
rebinds, recoveries (the pages' `made_of` parts keep no promise), `did_modify_range` and
`synchronize_resource` behave as before.

Why: on a discrete GPU behind a 4.8 GB/s link, a compute workload's 131 ms GPU job was the making
copy of six new `Managed` buffers (631 MB across the bus, 12 MB of it named by
`did_modify_range`), and a 72 ms kernel wait for the imports preceded it. A guest's buffer made
with no bytes holds zero pages, which the consumer knows and the runtime cannot.

How verified: tests::managed_copy_device's zero-promise legs (through an import and over pages no
import maps): no promise, and a promise at the length, copy the pages in whole (negative control);
a promise from byte 0 over zero pages copies in and stages nothing, counts one zeroed device copy
of the buffer's bytes, reads zero, and a later did_modify_range copies in as ever; a promise from
an offset inside a word over pages that hold other bytes copies in exactly the bytes before it and
reads zero from it, which only the device's fill can have written. A buffer in its pages reads
them under the promise. The device runs are in the lane's jobs (lavapipe, which has unified
memory, runs only the in-place leg; the XTX runs the two-copy legs).
2026-11-15 16:42:22 -08:00
Anees Iqbal 48c7296fcb device_copies: a did_modify_range step whose calls outlasted its busy work is asked again
runtime_lane::device_copies::exact_answers_take_a_did_modify_range_at_the_commit failed once on the
RX 7900 XTX (round c218071502, m3-max-33927): "the runtime's, step 4: the busy work ended first".
Each oracle step commits about 2 s of busy work (8 links of 250 ms at the kernel's measured rate)
and then makes its calls; the end mark reading 0 as they return is the step's premise, that the GPU
has not run its command buffer yet.

The cause is the host, not the runtime. Host times around each act (probe jobs) show no act waits
on the GPU at ef313200e2 or at c218071502: from the busy work's first commit to the mark check a
step took 13-47 ms alone on the XTX and 5-36 ms in its lane leg 2/2 (m3-max-34065), against links
that spun 240-268 ms each (their GPU times, about 30 samples). On the RX 550 (m3-max-34044, 3 runs
of each sha) per-act times swung with the node's load, the busy work's commit from 3 to 280 ms,
equally at both shas. c218071502 passes alone and in the lane; the failure was one step in one of
8 XTX rounds, in a leg whose node's 16 CPUs also ran the RTX 2080 runtime suite, the PHOENIX
replay and lavapipe 2/4. round.py now runs one round job per node, so rounds no longer pack suites
so; this guards the nodes we don't control.

The window cannot be stretched to fit a host: its length rests on a rate measured once, and Vulkan
does not promise that a running shader sees the host's release (on the XTX alone the first link
never saw it and spun its whole cap). So a step now asserts its premise and asks again, as
device_room's with_room does for a device: runtime_lane/busy_premise.rs's until_premise_held runs
a try, and where the busy work ended before the calls returned the try still checks the bytes it
read (one of the answers allowed whatever the timing), writes a LANE-BUSY-MISS line with each
act's host time, the calls' total and each busy command buffer's GPU time
(BusyWork::gpu_span), and runs the step again with fresh busy work, at most 3 tries. A step that
misses every try fails with each try's times, so a call that waits for the GPU's earlier work
still fails as before, and the next real miss shows which side moved.

Tests: busy_premise's a_held_premise_is_tried_once, a_missed_premise_is_tried_again and
a_premise_missed_on_every_try_fails (no GPU). docs/VALIDATION.md names the rule.

Verified: m3-max-34107 (msi) clippy -p metal2vulkan-validation --all-targets --all-features -D warnings under --cfg m2v_gpu, and on lavapipe 5/5 (busy_premise unit tests x3, device_copies exact_answers_take_a_did_modify_range_at_the_commit and a_did_modify_range_reaches_the_bytes_the_next_commit_finds). Running at landing: the XTX run (m3-max-34117).
2026-11-15 16:39:22 -08:00
Anees Iqbal f4082938de artifact tests: the translator's repro writer is a default-off diagnostic, not a runtime input
RUNTIME 2366 made the runtime's FALLBACK repro bundle (metal2vulkan-runtime/src/repro.rs) use
metal2vulkan::repro (ReproBundle, ReproDevice), so the runtime's inputs reached
metal2vulkan/src/repro.rs, which is neither a listed input nor a listed non-input:
candidate::engine::artifact::tests::the_runtime_sources_are_the_committed_ones failed in the
round at c218071502 (validation, m3-max-33994). The writer acts only where METAL2VULKAN_REPRO_DIR
names a directory and its bundle changes no run's answers, as env_vars.rs's diagnostics, so it is
listed with them as reached but not a runtime input; the runtime-sources pin is unchanged.
2026-11-15 16:04:43 -08:00
Anees Iqbal ddb4bcbfaa Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 16:02:32 -08:00
Anees Iqbal f143091069 RUNTIME 2394: an owned kernel is looked up under the lock and made outside it
Device::owned_kernel held the device's owned-kernels lock across a
kernel's whole making: its module's build and its VkPipeline's
creation, which on ANV can take hundreds of milliseconds to seconds.
So every lookup of a kernel made already waited for an unrelated
kernel's compile: an encoder's rows copy, ICB reset, shadow copies and
merges, YCbCr sample and index kernels on encoding and committing
threads, ycbcr_conversion and made_ycbcr_conversion at a texture's or
a pipeline's creation; and route_counts_kernel's try_lock answered None
while any making ran, so the frame's routed draws took the region-copy
route. The pool's begin_draw_replay_kernels makes three kernels in a
row and begin_route_counts_kernel one, each a trigger.

Now the lock covers only a lookup, a settle and a Y'CbCr conversion's
creation:
- A kernel made is answered at once.
- A kernel in flight (OwnedKernels::making, one InFlight per kernel) is
  waited for: its asker waits on that making's answer alone, holding no
  turn of the budget's (budget::without_turn lends a pool piece's), and
  takes the same kernel or a clone of the same error. No second compile.
- Otherwise the asker records an InFlight, lets the lock go, takes its turn
  (program_turn: what helper_turn took once the kernel was known
  unmade), builds, makes the sampler of a YCbCr or 4:2:2 sample kernel
  under a short lock (the order and the one conversion per sampler that
  the views and the samplers baking it share, as before), and makes the
  objects. Its settle, under one lock, counts the kernel
  (WorkCounts::owned_kernels_made, as before), keeps it, and removes the
  making from those in flight, then answers the waiters. A making whose
  thread unwinds is settled with an internal error by its guard, so no
  asker waits for ever. A failed making is not kept: a later asker makes
  it again, as before.
- route_counts_kernel locks (briefly) in place of try_lock: it answers
  Some once RouteCounts is made, whatever else is being made.

keep_nothing (device/carry.rs) is a LOST generation's recovery step: the
line serves past it, its objects were carried to the new generation,
none of its command buffers records, and no work is made on it again;
it destroys the generation's owned kernels (OwnedKernels::destroy sets
`destroyed`). The only other caller of destroy is DeviceShared's drop,
which no making can overlap (a making holds a &Device). Before, destroy
waited on the lock for a making in flight and then destroyed its kernel;
now a making settled after it destroys its kernel at once and answers
Error::DeviceLost, which is what that generation is. A live device never
has `destroyed` set, so no asker on a live device that got a kernel
before gets DeviceLost now.

The test hold: it stays a field of OwnedKernels (a kernel and a Held,
the same Held type device/holds.rs holds its holders with) rather than
a Holds slot. The holds of device/holds.rs are indexed by Holder, the
runtime's own holders of a device, and are passed in holds_go_on
between a holder's steps, before a making starts, where the lock is not
held. This hold must stop one kernel's making midway (between its
module's build and its objects), on whatever thread makes it, the pool's
or a program's, and be read under the same lock as the lookup, so it is
keyed by the kernel where the kernels live.

The test grows a same-kernel check: a second asker of the held kernel
is seen waiting on its making in flight (a test-only count), the hold
has one making at it, and once let go both askers take one pipeline,
one kernel made.

Verified: at the base f310ebe9ee the test failed on lavapipe (msi job
m3-max-33983: the lookup waited past 5 s, the routes' kernel answered
unmade). This commit's runs follow in the lane's report.

Test: tests/owned_kernel_lookups.rs holds one kernel's making midway and asserts that a made kernel's lookup on another thread returns at once with the same pipeline, that route_counts_kernel answers Some, that a second asker of the held kernel waits on its making, and that the release makes exactly one kernel.

Verified: lavapipe on msi (llvmpipe, LLVM 23.1.1): at the test alone (f310ebe9ee, m3-max-33983) owned_kernel_lookups fails ('a made kernel's lookup waited past 5s for another kernel's making'; the routes' kernel answered unmade); at 2a52418bfc (m3-max-33993) clippy -p metal2vulkan-runtime --cfg m2v_cpu_icd --all-targets --all-features -D warnings 0, and 71/71 tests (owned_kernel_lookups, owned_kernel_builds, owned_pushes, rate_mapped_route_kernel, driver_pipeline_compile, the 15 teardown_threads tests, ycbcr_device, ycbcr_in_place_loop, ycbcr_refresh, described_row_copies, shadow_merge_read, surface_two_planes, icb_carry_race, rate_mapped_*, mipmap_plan). Running at landing: plain and --cfg m2v_gpu clippy, rustdoc. Not run on hardware GPUs; the stall is shown with a deterministic hold, not timed on ANV.
2026-11-15 16:01:47 -08:00
Anees Iqbal 8fee9b86f8 partial_threadgroups: the heavy kernel keeps 8 values live, not 400
ANV's compile time grows with the values live at once. At 94f9436cd8 the heavy test failed on
the Iris Xe (ANV, Mesa 26.2.6; Iris job m3-max-33948): at 10,000 steps with 400 values live a
command buffer waited past the test's 60 s WAIT for its pipelines, and the test failed at that
wait after 224.8 s. With 8 live the same driver is fast at that size: in the same job the
large-kernel test, whose chain is 8,000 steps with 8 values live, made its states' variant and
plain pipelines and passed in 3.6 s in all, and 40,000 steps with 8 live took about 52 s
(m3-max-33783).

WINDOW is now 8. STEPS stays 10,000, which keeps the kernel large by the runtime's measure, and
the test still asserts that premise (`ComputePipelineState::whole_on_partial`: `COUNTED_WORDS`
SPIR-V words or more) for each state it makes. The 400 came with the test and no measurement
chose it. The test's name and docs still say what it checks: the variant's one VkPipeline
against the split's six, with their creation times printed.

Verified at 5a39d9a75f: m3-max-33966 (msi) clippy -D warnings for metal2vulkan-runtime (all targets, all features) plain, --cfg m2v_cpu_icd and --cfg m2v_gpu. Running at landing: the heavy test on the Iris.
2026-11-15 15:51:04 -08:00
Anees Iqbal 18b14cca39 line_beside: a write beside a plane over Private memory keeps its bytes under the plane's writes
On the Iris Xe (ANV), whose GPU writes back the whole 64-byte line its writes end in, a plane's
texture at 0x20 of a Private buffer is in place for RenderTarget and ShaderWrite while another GPU
command may write the bytes beside it in the plane's first and last lines. A device test
(tests::line_beside, under the GPU cfgs) puts two commands with no dependency between them in one
command buffer: a render pass's clear and store, or a kernel's writes, of an R8Unorm plane at
0x20 (a buffer laid by aligned_byte and a plain one; tight rows of 1920 and padded rows of 1000
at 1024; tracked and untracked), and a blit copy or kernel stores into bytes 0x0-0x1f and the
bytes after the plane's last texel to the end of its line; it reads the buffer back. A control
leaves the second command out and must count every one of its bytes lost.

docs/FAST-PATHS.md's Iris known gap now says the line write-back holds over the runtime's own
memory as over host pages (the check's Pooled, ExportedFd and ExportedDmaBuf classes fail renders
for rows that end inside a line, m3-max-33545), and that another GPU command's bytes in the line
are kept.

Verified: Iris m3-max-33919 (ANV, Mesa 26.2.6): 0 bytes lost in all 32 cases x 3 rounds, the
controls counting exactly the left-out bytes ([32, 64], [32, 32], [32, 24], [32, 56]), 0 wrong;
lavapipe m3-max-33912 the same; clippy -p metal2vulkan-runtime --all-targets --all-features
-D warnings under --cfg m2v_gpu (33920), --cfg m2v_cpu_icd (33921) and plain (33926). The doc
commit had cargo fmt only; tests::fast_paths runs on development.
2026-11-15 15:44:07 -08:00
Anees Iqbal 94f9436cd8 partial_threadgroups: the heavy kernel is 10,000 steps, asserted large by the runtime's measure
On ANV (Mesa 26.2.6, the Iris Xe of RPL-P) the heavy kernel's 40,000-step chain took the driver
about 52 s to make with 8 values live (Iris job m3-max-33783: the first ragged grid done at
53.76 s, one VkPipeline) and more than 120 s with the test's 400, and the test makes seven
pipelines of it, so it ran for minutes there. Its compiler took about 3.2 MB of stack for that
chain (3,216,936 bytes measured), about 80 bytes for each value; the runtime now makes every
driver compile on a stack with that room (RUNTIME 2392), so the chain's length no longer stands
in for the stack guard, which tests::small_stack_device and the relay's and the pool's unit
tests cover.

STEPS is now 10,000, and the test asserts the premise that keeps it heavy by the product's own
measure: each state it makes is large (`ComputePipelineState::whole_on_partial`, the module at
`compile_memory::COUNTED_WORDS` SPIR-V words or more), so a smaller chain cannot pass the test
vacuously. LARGE_STEPS (8,000, window 8) already meets that measure, so 10,000 holds it with room.

docs/FAST-PATHS.md records the driver's time and stack as a device gap, with what the runtime
does about the stack: the pool's threads start with 8 MiB, and a call asked for on a thread with
less than 4 MiB of stack left is made on a thread of the runtime's started with 8 MiB.

Verified: an msi job's clippy (plain, --cfg m2v_gpu, --cfg m2v_cpu_icd) and the ledger tests,
and an Iris job running tests::partial_threadgroups (the heavy test prints its ANV times) and
tests::small_stack_device from this commit's archive.

Verified at a96a3ef68d: m3-max-33936 (msi) clippy -D warnings for metal2vulkan-runtime (all targets, all features) plain, --cfg m2v_cpu_icd and --cfg m2v_gpu; metal2vulkan tests::fast_paths 34/34. Running at landing: the heavy test and small_stack_device on the Iris (m3-max-33948).
2026-11-15 15:38:35 -08:00
Anees Iqbal 911692b55d Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 15:32:11 -08:00
Anees Iqbal 2163335121 RUNTIME 2393: a dma-buf source is asked once per texture after its standing refusal
A texture over a no-copy buffer's pages imported as dma-bufs tries its image in place with each
of its plans (wider usages first, its own last) and asks the caller's source for each plan's
pages. On RADV PHOENIX (Mesa 26.2.6) an RGBA8Unorm ShaderRead texture tries four, so a source
that refuses pages past udmabuf's list_limit was asked four times for the same pages
(texture_shadow_bench, m3-max-33878: source calls 4.00, refused 4.00 a texture); a consumer's
trace logged 1,620 such refusals over 765 textures, 367 ms in all.

The runtime cannot infer that one refusal answers a wider range: a source may accept exactly a
range it keeps a dma-buf of, or a wider one split otherwise. So the source marks it: a new public
DmaBufStandingRefusal (a runtime extension), returned as its io::Error, stands for every range
that holds the refused one for the rest of that texture's making. bind_dma_buf_image reads it into
DmaBufRefusal::Source { stands }, and in_place_image refuses each later plan whose request holds
such a range with that refusal, its unbound image released, the source unasked. Plain errors
behave as before: each plan is asked.

Documented in DmaBufSource's and DmaBufStandingRefusal's rustdoc, docs/HOWTO.md's dma-buf section
and the runtime README; api_signatures blessed (the type, new, Display, Error). REFUSALS.md
regenerated, unchanged.

Test: tests/dma_buf_standing_refusal.rs, on a device that imports no host pointer: a source of
plain refusals is asked once per plan, a standing one once, and one that refuses plainly then
gives the pages makes the texture in place on the second ask.

With it, a test-only release bench (ignored, --cfg m2v_gpu, Linux with /dev/udmabuf), tests/texture_shadow_bench.rs: an RGBA8Unorm ShaderRead texture over a no-copy buffer of a sealed memfd's pages, in place over one dma-buf against a shadow over more runs than one udmabuf lists, used by one or two dispatches that read or sample every texel and dropped, at four sizes, with a blit and a Private sample as references, printing host, GPU and CPU time, submission counts and the WorkCounts of each part. Its source marks its list_limit refusal as standing.

Verified: compiled in m3-max-33918 (msi, release lib-test archive under --cfg m2v_gpu). Running at landing: lavapipe (dma_buf*, no_pointer_import, host_residency, texel_rows, texture_placement) in 33918, clippy x3 next, and a PHOENIX run of the new test and the bench (the 4 -> 1 asks on RADV expected, unverified). The bench's numbers (PHOENIX m3-max-33878 um790, 33898 gem10) came from 2fe80f0a64 and d06fa76b74.
2026-11-15 15:31:24 -08:00
Anees Iqbal c218071502 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 15:08:29 -08:00
Anees Iqbal 495aa80968 RUNTIME 2392: a driver's compile runs on a stack with room: the pool's threads and the compile relay start with 8 MiB
On the Iris Xe (ANV, Mesa 26.2.6) two runtime tests aborted with "has overflowed its stack":

- tests::partial_threadgroups::a_heavy_kernel_s_ragged_grids_pay_one_creation, on a pipeline pool
  thread (std's default 2 MiB stack). Under gdb (m3-max-33742) the thread held 25,972 frames and
  2,090,624 bytes when it overflowed, 25,922 of them one function of libvulkan_intel.so, 80 bytes
  each: ANV's compiler recurses about 80 bytes deep for each value of a chain of dependent
  values. The kernel's chain is 40,000 values long, so its vkCreateComputePipelines takes about
  3.2 MB. Our frames above the driver's entry point there are 13 KiB.
- tests::small_stack_device::a_device_is_made_used_and_released_on_a_thread_with_a_small_stack, on
  a 256 KiB thread. Device creation's priming (prime.rs) compiles its kernel through
  vkCreateComputePipelines on the caller's thread: 204 KiB of our frames in this debug build
  (assemble 108,864 bytes, create_on 52,560, Primer::objects 24,688) and then ANV's compile, 52 KiB
  of its frames (one of 49 KiB) when the stack ran out. vkCreateDevice itself took about 55 KiB,
  and the fill, commit and wait at most 74 KiB of the thread (painted stack probe, 33742).

Metal compiles in a service of its own, so no program's stack takes its compiles. Every driver
call that may compile already goes through device/compiles.rs's at_user_initiated
(vkCreateDevice, vkCreateGraphicsPipelines, vkCreateComputePipelines, priming's included):

- this_thread::stack_room reads the room left on the calling thread's stack, where its stack ends
  read once a thread: pthread_getattr_np + pthread_attr_getstack on Linux,
  pthread_get_stackaddr_np - pthread_get_stacksize_np on macOS, GetCurrentThreadStackLimits on
  Windows (gnullvm and msvc alike, windows-sys's Win32_System_Threading), none elsewhere.
- at_user_initiated runs the call on the asking thread only where it is at the user-initiated
  class (macOS) and its stack has COMPILE_ROOM (4 MiB) left; else on its relay thread, which now
  starts with COMPILE_STACK (8 MiB, glibc's default thread stack, which Mesa's own compile threads
  use) on every OS. A Linux or macOS main thread still compiles in place; a Rust thread's 2 MiB,
  a macOS secondary thread's 512 KiB and a Windows main thread's 1 MiB hand the call over, at one
  thread start and join per call. The relay is the one macOS's class already used, unchanged: it
  raises its class to user-initiated on macOS, makes the one call inside an exit-guard section
  with the asking thread's measured diagnostics, holds the driver's messages for the asking
  thread's sink, is joined before the call returns, resumes the call's panic on the asking
  thread, and where no thread starts or the process is exiting the asking thread makes the call.
- The pipeline pool's threads start with COMPILE_STACK, so their pieces' makings run on them.

The stacks are address space; the system commits their pages as they are touched.

Tests: device::compiles::tests::a_pipeline_asked_for_on_a_small_stack_is_made_on_a_stack_with_the_room
(a fake driver reports the room and thread its call ran on: asked on 256 KiB and 2 MiB threads
it runs on the relay with at least 4 MiB left, on an 8 MiB thread on the asking thread; without
the room check it runs on the 256 KiB thread and fails), and
pipeline::pool::tests::a_piece_runs_on_a_stack_with_the_room_a_compile_takes. The existing tests'
asking thread now has the compile stack, so their in-place assertions still hold.

The relay test expects by the room the asking thread has: glibc reuses a cached stack of up to four times the size asked, so a 2 MiB thread may hold the 8 MiB a previous relay thread left and rightly compile in place; the 256 KiB thread must relay and the COMPILE_STACK thread must not.

Verified at a4d5ec0cdf: m3-max-33801 (msi) clippy -D warnings for metal2vulkan-runtime (all targets, all features) plain, x86_64-pc-windows-gnullvm, x86_64-pc-windows-msvc, gpucfg and cpuicd; device::compiles + pipeline::pool unit tests 14/14; the negative control (room check removed) fails at the 256 KiB thread ('made on the asking thread true, 251975 bytes of room'); lavapipe small_stack_device and the two non-heavy partial_threadgroups tests 3/3. Iris (m3-max-33783, the same stack code plus inert probe hooks): small_stack_device passes; the heavy kernel's vkCreateComputePipelines ran on an 8 MiB pool thread at 3,216,936 bytes deep (13,449 ours) without overflowing. The heavy test still takes ANV about 52 s a pipeline at 40,000 steps; its step count follows in its own commit.
2026-11-15 15:07:38 -08:00
Anees Iqbal ad0a4907fc dispatch_work: the changed-only push test makes its pipeline first
Its first encoder's first dispatch recorded later, in a segment of its own, while the pipeline
was being made: the next dispatch pushed whole into the encoder's new VkCommandBuffer and the
segment kept the second encoder from folding (lavapipe, m3-max-33792: [2, 2, 2, 2, 2, 0], 0
folded). One dispatch completed first makes it. The ANV rule PushedSetZero follows is draws'
in render/bound.rs (Bound::pushed_set's forgotten flag).
Verified: m3-max-33819 (msi) clippy -p metal2vulkan-validation, lavapipe 14/14: writes per dispatch [2, 0, 2, 2, 2, 0] with 1 encoder folded pushing, [0, 0, 0, 0, 0, 0] with push withheld, outputs checked under the validation layer.
2026-11-15 15:05:58 -08:00
Anees Iqbal 7caf91a180 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 15:04:51 -08:00
Anees Iqbal 617ebd26d6 RUNTIME 2391: the rate map's route-counts kernel is made ahead on the pool, never on the encoding thread
The encoder's end built the route-counts kernel inline (owned_kernel): a VkPipeline made on the
encoding thread behind a program turn of the pipeline budget, which can wait behind the pool's
makings. On the PHOENIX (RADV, release, probe m3-max-33749) end_encoding took 0.83 to 0.90 ms with
the kernel built there, against 0.22 to 0.27 ms with it made before.

A pass's first draw the GPU routes now begins the kernel on the device's pool, once per device
(Device::begin_route_counts_kernel, holder RouteCountsKernel). The encoder takes it as it ends
only where it is made, without waiting (Device::route_counts_kernel, a try_lock). An instance
whose kernel is not made by then runs no steps: its draws' counts keep what the CPU wrote
(fan-out 0, region-copy MAX_SEGMENTS), so each draws its region-copy route, as a draw whose other
routes did not record does. rate_map_gpu_routed_draws now counts an instance's marked draws as its
steps are planned, so routed equals fanned plus copied whether or not the steps ran. The device
tests' hold array takes its length from the last holder (it had three places, so the kernel's
pool piece indexed past it under the GPU cfgs).

Test: rate_mapped_route_kernel holds the pool while a frame's routed draws begin the kernel and
asserts the encoder made no kernel, routed none, drew every draw by its region-copy route (2897
red, 16 region-copy draws), and that once the kernel is made the same draws are fanned out over
the same pixels ([16, 16, 0]).

Verified at 7ed2805004: m3-max-33791 clippy (runtime, all targets, all features), runtime unit
tests 79/79, lavapipe rate_map device tests 25/25 (depth_equal 0 red in every leg), and the
negative control (the kernel made inline again: the new test fails, 1 kernel made in the held
frame); m3-max-33818 clippy under m2v_cpu_icd and m2v_gpu. PHOENIX (m3-max-33813, release, two
runs): cold end_encoding 204 / 182 us (166 / 158 us with the kernel made before; 826-896 us
before this change), the kernel made on the pool in the cold frame (0.30 ms, off the encoding
thread), the second frame routing 64/64; cold through commit 6.0 / 5.8 ms against 5.8 / 5.2 ms
premade.
2026-11-15 15:04:06 -08:00
Anees Iqbal 738c2bb358 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 15:00:12 -08:00
Anees Iqbal c20a99ca94 RUNTIME 2390: compute dispatches push only the set-0 writes that changed and keep the bound pipeline
A compute dispatch pushed its whole set 0 and bound its pipeline at every dispatch, though draws
already push only what changed (render/bound.rs). On ANV a dispatch's push and the flush of the
dirty push set cost most of the ~5.7 us a dispatch its committing thread spends there beyond
lavapipe (the Iris sizing run, committer 8.5 us a dispatch of the textured shape).

Now an encoder keeps what its dispatches recorded at the compute bind point of its
VkCommandBuffer (binding::PushedSetZero): the pipeline bound last and set 0 as pushed with a
pipeline layout. A dispatch binds its pipeline only where another is bound and pushes only the
writes that differ from those set 0 holds, none where none does. It holds only while nothing
else recorded into that VkCommandBuffer since the encoder's last such dispatch (a count of the
encoder's recordings, bumped by every command, barrier, copy run and gather run that takes it);
another VkCommandBuffer, any other command (which forgets it explicitly), a flat dispatch's
preprocess, set 0 bound from a set and a dispatch of another layout forget it. Each encoder
begins it empty, so an encoder folded into the group's VkCommandBuffer (encoder_fold.rs) pushes
its first set 0 whole, and a dispatch recorded later into a segment of its own pushes whole.

Vulkan's rules it rests on: vkCmdPushDescriptorSet, "Push descriptors can be updated
incrementally and cause shaders to use the updated descriptors for subsequent bound pipeline
commands ... until the descriptor is overwritten, or else until the set is disturbed"; Pipeline
Layout Compatibility, binding a set N disturbs a lower set only where the layouts are not
compatible for it, and binding a pipeline disturbs none. Where the driver's pushed descriptors
go stale across a pipeline bind (RuntimeDriverDefect::PushedDescriptorsStaleAfterPipelineBinds,
ANV), the dispatch binds its pipeline before the push and pushes at least one write after each
bind (set 0's first where none changed), as a draw does; a later region that binds another
pipeline pushes one again.

WorkCounts::dispatch_set_zero_writes_pushed now counts the writes carried (none for a dispatch
whose set 0 is unchanged); dispatches_pushing_set_zero still counts each dispatch of a pushed
set 0.

Tests: tests::pushed_set_zero (carry, forgetting, the stale rule); the device test
runtime_lane::dispatch_work::dispatches_push_only_the_writes_that_changed: writes per dispatch
[2, 0, 2 | 2, 2, 0] over two encoders folded into one VkCommandBuffer (encoders_folded 1), the
second's first dispatch of the buffers the first's last pushed carrying 2, and every output's
words checked, under the validation layer, both ways.

Verified: clippy -p metal2vulkan-runtime -p metal2vulkan-validation --all-targets --all-features -D warnings in m3-max-33792 (msi). Running at landing: the lavapipe tests (33792) and the negative control at the base plus the test alone (33803); the Iris A/B follows.
2026-11-15 14:59:27 -08:00
Anees Iqbal c711ed7092 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 14:48:52 -08:00
Anees Iqbal c2206c14b0 RUNTIME 2389: Device::import_shared_dma_buf imports a shared dma-buf ahead and keeps it while a handle lives
A runtime extension (Metal has none). A guest's buffers over pieces of one shared file of guest RAM
were each imported as their own dma-buf import and freed with the buffer, so a compute loop that
made and dropped no-copy buffers paid an import and a free per command buffer, and on RADV each
import maps its pages at once (the next submission's CS waits for the page-table job).
Device::import_shared_dma_buf(file, options) (unix) imports the whole dma-buf on the caller's
thread, or joins the device's live import of it, and returns a SharedDmaBufImport; while a handle
lives, the file's entry in the device's map keeps the import, so buffers over its pieces join it
instead of importing again, and it is freed once its last buffer, heap and handle have gone (one
kept import per file a live handle names, per generation). The class comes from `options` as a
no-copy buffer's (Private, Memoryless and undefined options refused, Invalid StorageMode); the
import takes the type a no-copy buffer of that class would get first, so pieces join it.
Refusals use the existing kinds (Unsupported HostMemory, OutOfMemory). A device's recovery lets go
of the lost generation's kept holds and seeds the new one's map, whose first buffer imports the
file again; nothing is imported on the recovering thread. A device without a dma-buf importer
keeps nothing (Debug: imported false). The handle imports whether or not the device's buffers over
those pages take the dma-buf route: on a device that takes the pages' pointer it is one listed
dma-buf a submission for nothing. WorkCounts::dma_buf_shared_imports_kept gauges the kept imports;
the handle's import counts in dma_buf_imports. Docs: rustdoc, dma_buf.rs Shared files, HOWTO
dma-buf section, the runtime README extensions and unix-only lists. REFUSALS.md: the StorageMode
site moved to host_class, which the no-copy call and this one share.

Public surface: Device::import_shared_dma_buf, SharedDmaBufImport (Send + Sync, consumer_auto_traits)
and WorkCounts::dma_buf_shared_imports_kept, blessed in api_signatures.tsv.

Verified: m3-max-33745 at the lane tip 856a1fabae: clippy plain, m2v_gpu, m2v_cpu_icd 0; rustdoc 0;
lavapipe runtime suite 2836 passed. Device tests (lavapipe): three buffers made and dropped in turn
take imports 1 / joined 3 with the handle, imports 3 / joined 0 without; a handle keeps a live
buffer's import; recovery imports nothing and the next buffer's import stays kept; Private refused.
Churn bench, PHOENIX (RADV 780M, release, interleaved, 450 command buffers an arm, a8f297bf11, the
same code but the count): no handle 1 import + 1 free a command buffer, call median 820-907 us, GPU
start median 3026-3037 us; handle kept 0 imports, 0 frees, 1 join, call median 25-69 us, GPU start
median 104-145 us.
2026-11-15 14:48:09 -08:00
Anees Iqbal af37f92d91 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 14:46:37 -08:00
Anees Iqbal 9dc44438fa RUNTIME 2388: WorkCounts count the uses a compute dispatch's tracking walks
What: two default-on counts, one relaxed add each per compute dispatch that records (compute.rs,
before its command_reaching or command_later): the dispatches whose uses hazard tracking took, and
those uses (each resource range the command reads or writes, those reached through what the
encoder made resident among them). Uses over dispatches is what a dispatch's tracking walks
(command_reaching, track, order_as, touch_reaching). Listed in the host_ab example's counts; the
dispatch_work lane test asserts four tracked dispatches of at least two uses each.

Why: a guest compute benchmark's dispatches cost 7 to 38 us each on a Radeon 780M, most of it
inclusive under command_reaching, track, settle_live and order_as, which scale with the uses a
dispatch reaches; the repository's dispatch bench reaches 5 and costs about 1.2K instructions
there. No count said how many uses the costly dispatches reach (dispatch_used_resources_listed
counts listings of what an encoder made resident, not uses per dispatch).

Verified: m3-max-33750 (msi) at the lane tip b7ed24d9a8: clippy (runtime + validation, all targets, all
features) 0; lavapipe runtime_lane::dispatch_work passes (4 dispatches tracked 8 uses, push and bind devices).
clippy m2v_gpu / m2v_cpu_icd and rustdoc follow.

Public surface: WorkCounts (for the lanes) gains dispatches_tracked and dispatch_uses_tracked, blessed in
api_signatures.tsv; a struct literal of WorkCounts must name them, Default and readers are unaffected.
2026-11-15 14:45:43 -08:00
Anees Iqbal 79d9325e44 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 14:44:32 -08:00
Anees Iqbal aa5e196575 read_twin_device: wait for the in-place check wherever the policy keeps textures in place
On lavapipe (msi job m3-max-33699, the test binary at d7e7eca11f) three tests made their
textures while the device's in-place check was still pending ("pending 2" in the counts), so
the textures and their twins were shadows and "the texture's twin made, in place" read 0:
a_private_bit_buffer_s_texture_is_read_in_place_by_a_kernel,
a_private_bit_buffer_s_texture_is_sampled_in_place_by_a_draw and
a_texture_twin_bound_without_the_slots_proof_is_refused_and_would_reach_the_pages. The tests'
device waited for the check only where its memory types export (fd_buffer_types), which
lavapipe's do not, so whether the check answered before the first texture was a race the
loaded host lost.

device_with now settles the check wherever the policy takes textures over host pages in place
too (Device::settle_in_place_checks), as it did on exportable devices.
2026-11-15 14:43:52 -08:00
Anees Iqbal fd9a9373f4 read_twin_device: the shadow-log shape runs under RADV's plane rule, as its siblings
On the Iris Xe (ANV) the_shadow_log_names_a_twin_not_in_place_and_a_dispatch_s_first_read
reached neither line ("the shape reached neither line on this device", read_twin_device.rs:993):
ANV takes the 64x64 BGRA8Unorm texture at rows of 272 bytes as an explicit
DRM_FORMAT_MOD_LINEAR plane, so its read twin and the texture both lie in place (made: twins 1,
not in place 0, pitched 1). The product is right; the premise "no driver lays rows at 272" did
not hold.

The test forces RADV's rule for such a plane on its own device (`linear_pitch_rule_forced`,
256), as the sibling tests of the same shape (`refused_twin`, REFUSED's (0, 64, 64, 272)) do,
so neither lies in place on any device, and asserts both lines' preconditions exactly: one twin
not in place, the texture a shadow.

Verified: see the lane's report (Iris probe job and the msi build with lavapipe runs).
2026-11-15 14:43:51 -08:00
Anees Iqbal 0d6c6ce5d4 aligned_byte: the control asks the plane's image alignment, not the line-bound answer
On the Iris Xe (ANV) the plane R8Unorm 3840x2160 at byte 0x20 of a buffer made without the
aligned-byte option was in place ("off the alignment without the option", aligned_byte.rs:207).
The test asserted a shadow wherever
`Device::minimum_linear_texture_alignment_for_pixel_format` answers more than 32 bytes. That
answer is at least the device's line of memory (`nonCoherentAtomSize`): ANV answers its 64-byte
line, while its linear image of the plane binds 32 bytes into memory, and the runtime makes a
texture under the answer in place where the device's image takes its layout (as documented).
The product is right; the premise confused the line with the image's alignment.

The control now asserts the shadow where the memory alignment of the device's linear image of
the plane (`VkMemoryRequirements::alignment`) does not divide 0x20, read through
`Device::linear_texture_memory_alignment`, a test-only query that makes the same image
`linear_texture_bytes_per_row` makes (one code path, `own_linear_image`). The public API is
unchanged. The print names both alignments.

Verified: see the lane's report (Iris probe job and the msi build with lavapipe runs).
2026-11-15 14:43:51 -08:00
Anees Iqbal 735834e304 kept_padding: the device's own linear pitch is a texture's only where Metal takes it
On the Iris Xe (ANV, Mesa 26.2.6) four kept_padding tests failed. ANV lays the linear rows of the
tests' textures tight: an RGBA8Unorm image 101 texels wide at 404 bytes a row, a BGRA8Unorm one
65 texels wide at 260 (`Device::linear_texture_bytes_per_row`, the driver's
`vkGetImageSubresourceLayout` row pitch, as documented). Neither is a multiple of 16, which
Metal's `bytesPerRow` must be, so no texture lies at the device's own pitch there:
`Buffer::new_texture` refused 404 (`RowPitchAlignment { bytes_per_row: 404, alignment: 16 }`,
kept_padding.rs:336), and the blocks tests' premise "rows of the device's own pitch hold
padding" failed at 260 (kept_padding.rs:667). The product's answers are right; the premise held
only where the driver pads linear rows to a multiple of 16 (lavapipe, RADV, NVIDIA).

The own-pitch checks now run where that pitch is a multiple of 16 (as padding_unobserved.rs
already does); on ANV each of 416, 448 and 512 is checked as one of the other pitches (a shadow,
or in place with its first move kept). The two blocks tests of the texture at the device's own
pitch print that none lies there and return; the past-pitch test lays rows 256 bytes past that
pitch rounded up to 16 (unchanged where it is a multiple of 16: 528 on ANV).

Verified: see the lane's report (Iris probe job and the msi build with lavapipe runs).
2026-11-15 14:43:51 -08:00
Anees Iqbal 144cad9488 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 14:38:15 -08:00
Anees Iqbal 9c7013f60b RUNTIME 2387: host RAM copies: a dispatch writes its own imports alone into a partially bound import array
What: the pages copy's owned kernel makes its first storage-buffer binding, the array of
PagesCopyModule::imports(device) imports, VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT where the
array holds more than one and the device enables descriptorBindingPartiallyBound (the runtime
enables it wherever the device has it: device/enables.rs, Vulkan 1.2 features). Each dispatch of a
copy then writes (pushes, or writes into its set) only its own imports, then the buffer's window
and the table: OwnedKernel::first_written accepts a set that writes 1 to the array's length of the
array's elements where the binding is partially bound, every element elsewhere, and buffer_place
places the rest after them. Without the feature the elements past the dispatch's imports hold its
first import again, as before. The kernel's making text carries the flag.

Why: since RUNTIME 2322 every pages-copy dispatch wrote the whole array: on a device of 32 push
descriptors (ANV, RADV, NVIDIA, lavapipe: 30 imports) a dispatch over one import pushed 32
storage-buffer descriptors where 3 serve, through push_set's heap path (past 16 writes) and the
driver's vkCmdPushDescriptorSet, at every copy dispatch (358 to 813 a consumer's boot). No table
entry names an element past the dispatch's imports, so no invocation accesses one.

Vulkan: VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT "specifies that descriptors in this binding
that are not dynamically used need not contain valid descriptors at the time the descriptors are
consumed"; a push descriptor set layout takes it
(VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-flags-03003 forbids such a layout only
UPDATE_AFTER_BIND, UPDATE_UNUSED_WHILE_PENDING and VARIABLE_DESCRIPTOR_COUNT), and
descriptorBindingPartiallyBound must be enabled for it.

Test: host_ram_copy_device's a_dispatch_over_one_import_writes_its_own_descriptors_alone: rows of
4-byte texels in one chunk, one dispatch, the gathered bytes right, and the storage-buffer
descriptors the owned kernel's set or push wrote (a test-only thread-local count,
owned_kernel::buffers_written) 3 where the array is partially bound, the array's length and 2
elsewhere (32 before this change on lavapipe).

Verified: m3-max-33702 (msi) at the lane tip 238fde9d64: clippy (runtime + validation, all targets,
all features) 0, rustdoc 0; lavapipe host_ram_copy_device 32/32 (m3-max-33686, the same tree before
its rebase), "an array of 30 imports, partially bound true: 3 storage-buffer descriptors written";
PHOENIX (RADV, carried m2v_gpu archive of 238fde9d64) host_ram_copy_device 32/32, 3 written
(m3-max-33733); negative control (the whole array written again) fails the new test with 32
(m3-max-33700). clippy m2v_gpu / m2v_cpu_icd in 33722.
2026-11-15 14:37:33 -08:00
Anees Iqbal 0d87e8e26e Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 14:27:22 -08:00
Anees Iqbal a2a46d52fd RUNTIME 2386: WorkCounts count the descriptor writes compute dispatches push
What: a default-on count beside dispatches_pushing_set_zero, one relaxed add of the push's write
count per pushing dispatch (compute.rs), so writes over pushes is the descriptors a compute push
writes. Listed in the host_ab example's counts; the dispatch_work lane test asserts every push
carries the same writes, at least one, and that writes are counted exactly where pushes are.

Why: on the consumer's Iris Xe, binding::push_set's instructions over a guest compute benchmark's
timed pass rose 21-36% between two runtime pins with the same Mesa (26.2.6), almost all of it
under compute dispatches' pushes, inside the driver's vkCmdPushDescriptorSet. Whether each push
carries more descriptors, or more dispatches push, needs both counts; draws already count theirs
(set_zero_writes_pushed).

Verified: msi m3-max-33677 at the lane tip 9794e48d50: clippy (runtime, all targets, all features) 0;
lavapipe runtime_lane::dispatch_work::dispatches_push_their_set_zero_where_the_device_pushes passes both
ways (4 pushes carried 8 descriptor writes / 0 pushes carried 0). clippy m2v_gpu/m2v_cpu_icd and rustdoc follow.
2026-11-15 14:26:41 -08:00
Anees Iqbal 82ebc34ae1 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 14:21:39 -08:00
Anees Iqbal 4ee4deb737 RUNTIME 2385: a heap's 4:2:2 texture, a shadow of the heap's bytes, keeps a decoded twin
A heap's GBGR422 or BGRG422 texture lies as a shadow of the heap's bytes in Metal's rows (its answer
is Metal's measured rows: 512 @ 16 for 16x16, 8192 @ 16 for 64x64), and heap_texture_at excluded
4:2:2 textures from the decoded twin RUNTIME 2382 gave other carried formats' shadows, so every
kernel read and sample of one was refused, NotImplemented(Format) (56 refusals on PHOENIX and on
lavapipe, m3-max-33636 / 33625), where Metal reads it and the device can decode it.

heap_texture_at drops the 4:2:2 exclusion: the shadow keeps the twin with_decoded_twin chooses for
the device, through the device's conversion of the pairs where it converts them (rule 1), else
Metal's decode, one whole-image pass recorded after each copy in that moves its rows, its kernel made
at first use. A 4:2:2 heap texture cannot lie apart from the heap's bytes (held_to_metal sends rows to
Shadow or refuses with HeapTextureMemory; Unaliased is for one-plane and two-plane formats only), so
every 4:2:2 heap texture over device memory now keeps a twin; one over the caller's host pages, and a
detached heap's stand-in, stay twinless and refuse reads. Docs: chroma_pairs.rs contract,
decoded_twin.rs, degradation.rs CarriedDecodedTwin (doc and cost: "moves the blocks or rows"),
docs/API.md; first_use's lines say "decode passes set at the making N, their kernels made at first
use"; the HEAPDECODE line names a missing twin "none".

Verified: PHOENIX m3-max-33671 (carried archive of the lane tip 4976a40be3): 5/5 (heap_carried_reads
with GBGR422 and BGRG422 16/64 Private/Shared under both heap answer policies, new_resources_wait_for_
no_gpu_work, a_carried_heap_texture_reads_its_bytes_with_no_commit, four_two_two_heap_textures_take_
metal_s_size_and_layout, a_texture_held_for_copies_a_kernel_s_handles_reach_is_announced_once): every
4:2:2 case shadowed, a use 1 copy and 1 decode, a second encoder 0 and 0; kernel reads, samples,
samples after a blit and a Shared replaceRegion, blit out and getBytes equal the texture outside a
heap; route: Metal's decode (RADV and lavapipe convert no 4:2:2 pairs; the device-pair route in a
heap shadow ran on no device). lavapipe msi 33635: the same 5. Control (test commit alone): PHOENIX
33636 and lavapipe 33625 fail with the 56 refusals. Clippy plain, m2v_gpu, m2v_cpu_icd and rustdoc 0
(33635); runtime lib tests in 33672.
2026-11-15 14:20:58 -08:00
Anees Iqbal fc99097390 rate_mapped_pieces_encoder: the frame's device fans out
The lane's device options ask for exact answers, RateMapRegionPolicy::Exact among them, and the
encoder frame did not set the policy back, so its draws went region by region through each
region's own viewport: on the Iris Xe (job m3-max-33608) every frame printed 0 draws through the
region-copy variant and 0 routed on the GPU, base and tip alike. It now sets FanOut, as the
pieces frames set their policy. A lavapipe probe of the same pass over the same map under the
default policy took the region-copy variant and the GPU's routes in every case (job m3-max-33629).
2026-11-15 14:18:50 -08:00
Anees Iqbal 1e143ae315 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 14:13:49 -08:00
Anees Iqbal df0e7ec05e RUNTIME 2384: a fence update keeps its encoder group; the group orders after it by the narrowest barrier
A guest compute benchmark's encoders each update one fence and wait for one (reims, 780M,
c471372f87: fence updates = waits = encoders in every workload; 63 encoders a command buffer in one
workload), and an encoder that updated a fence ended its fold group, so every encoder began its own
VkCommandBuffer: 47.5 a submission, encoders_folded 54 of 117591. The driver's per-call work grows
with every VkCommandBuffer, and on the Iris Xe a VkCommandBuffer boundary costs 18.25 us of GPU time
against 0.64 us for the least barrier between dispatches (m3-max-33589).

A fence update no longer ends its group. A later member's commands order after the update by a
barrier recorded per command at the narrowest width that covers it: source, the updating encoders'
writes in the stages the update covers (SHADER_STORAGE_WRITE in shader stages, TRANSFER_WRITE in
transfer stages, attachment writes in a pass); destination, what the command can reach of memory
no use names, in its own stages (SHADER_STORAGE_READ | SHADER_SAMPLED_READ | SHADER_STORAGE_WRITE,
TRANSFER_READ | TRANSFER_WRITE), plus its untracked uses' own reads (indirect-argument or uniform
reads only where an untracked use reads them); tracked resources keep the tracker's rule. Between
two compute encoders that is the least barrier, SHADER_WRITE to SHADER_READ | SHADER_WRITE. The
barrier precedes the member's commands whether or not it waits, since a wait anywhere in an encoder
covers all its commands, which enter the shared VkCommandBuffer as they come; independent encoders
that update fences no one in the group waits on so run one after another (accepted: the guest's
encoders all wait). Across command buffers and queues nothing changes: Metal evaluates a fence at
submission, a wait only orders after updates committed before it ("commit the command buffers with
the producing passes before those with the consuming passes", MTLFence), a waiter on another VkQueue
waits for the updater's batch end, and a group never crosses a batch, so no cycle can form.
WorkCounts gains fold_fence_barriers and six folds_refused_* counts (the reason a join was refused:
kind, tail, batch, state, parts, ends; one relaxed add on a refused join, nothing on a join). Tests
that ended a group by a fence update now end it by a change of dispatch type or an event.

Verified: PHOENIX (RADV 780M, release, interleaved, 600 command buffers of 24 encoders, m3-max-33626):
fenced chain 47 -> 1 VkCommandBuffer a submission, mean call 56-79 -> 18-20 us, GPU start median
142-173 -> 101-105 us, GPU time median 146.7 -> 87.8 us (either wait order); independent fence-updating
encoders 74.7 -> 88.0 us GPU (serialised, as accepted); unfenced control unchanged (49.2 us).
fold_fence_barriers 13800 = 600 x 23; no folds_refused_* moved. Long-call bench, small listed:
539 -> 371 us mean call. Lane tip 8ae906a4fd: clippy plain, m2v_gpu, m2v_cpu_icd 0 (33633); lavapipe
runtime suite 2829 passed at 143a0013f8 and tracker unit tests 85 (33621; 8ae906a4fd deletes only the
dead Summary::has_updates); PHOENIX encoder_fold, render_fold, spares, fences 71 passed (33626).
Iris before/after: m3-max-33627, pending.

Public surface: WorkCounts (for the lanes) gains fold_fence_barriers and folds_refused_*, blessed in
api_signatures.tsv; a struct literal of WorkCounts must name them, Default and readers are unaffected.
2026-11-15 14:13:04 -08:00
Anees Iqbal 72f5acfec7 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 13:48:58 -08:00
Anees Iqbal 209f11b467 RUNTIME 2383: rate maps: the GPU routes a fanning pass's own draws (step 1)
- Rate maps: the GPU routes the encoder's own draws of a fanning pass
- rate-map GPU routes: the rebound recording takes no route; the routed-draw count through the device's counters
- rate_mapped_pieces_encoder: the small triangles' commands drawn as the encoder's own draws
- Rate maps: the GPU routes' docs, the depth test's flagged draw between fanned ones
- rate_mapped_pieces_encoder: the draws the GPU routed, fanned out and drew through the region-copy variant
- CountDraws: the indirect-count draw's recording is record_draw
- rate_mapped_depth_equal: the GPU routes the encoder's draws as the host step's probe decides them

In a rate-mapped pass that fans out (RateMapPolicy FanOut, the default), the encoder's own draws
were routed by the host step only for executions; the GPU now routes them: a counts kernel
(bind/fan_out/route_counts.rs, built through the translator's public API) reads each draw's lead
instance probe and writes indirect counts, so each draw either fans out per region or draws through
the region-copy variant, as the host step's probe decides for the same draws. Its kernel is made at
first use; a cold frame, whose variants are still being made, falls back to the region-copy route
alone. Exact (RateMapPolicy::Exact) routes nothing on the GPU. WorkCounts gains
rate_map_gpu_routed_draws, rate_map_gpu_fanned_draws and rate_map_gpu_copied_draws (for the lanes;
blessed in api_signatures.tsv). FAST-PATHS rate-map row updated. No new Degradation kind.

Verified: msi m3-max-33521 at the lane tip 4ee726aa13: clippy (translator, runtime, validation; all
targets, all features) 0; translator route_counts, fan_out, api_surface, api_signatures, fast_paths
62/62; runtime fan_out, every_command_the_runtime_records_is_routed, work_counts, upload,
owned_kernel 10/10; lavapipe rate_map device tests 24/24. rate_mapped_depth_equal (each pass two
ground halves with a w-crossing triangle between): 0 red pixels in every leg under Exact and FanOut;
the warm FanOut encoder frame routed 6/6 draws on the GPU (2 fanned, 4 region-copy), the same as the
host step decides for them executed. Pending: clippy m2v_gpu/m2v_cpu_icd, rustdoc, the Iris A/B.
2026-11-15 13:48:07 -08:00
Anees Iqbal f0e220ceab Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 13:47:02 -08:00
Anees Iqbal d62e1d2bd9 RUNTIME 2382: a heap's decoded-format texture on a shadow route keeps a decoded twin
Under DevicePolicy::exact_answers (HeapAnswerPolicy::Metal) a heap's PVRTC or ETC2 texture on RADV
PHOENIX misses Metal's answer (its BC1 carrier image takes 4096 B @ 4096, Metal answers 128 @ 128
or 2048 @ 128), so it lies in memory of its own as a shadow of the heap's bytes (MemoryShadow;
Shadow or Tiled where those serve). heap_texture_at gave a decoded twin only to the Direct,
HostTransfer, Linear and Hidden routes, so its sampled view fell to the carrier, which has no
sampled usage, and every kernel read and sample was refused, Unsupported(Format) (8 of 8 cases in
m3-max-33467), where Metal samples it and the device can decode it.

A heap's PVRTC, ETC2 or EAC texture on a shadow route (not over the caller's host pages, not
detached) now gets its decoded twin. ShadowCopy::record_gated records the shadow's decode
(ShadowCopies::decode) after a copy in that moved texels, and only then (record_moves answers
whether it moved any); the pass is set at making (Image::decode_after_copies_in) and its kernel is
made in ShadowCopies::prepare at first use, so no making compiles. WorkCounts::shadow_twin_decodes
counts the decodes. 4:2:2 heap shadows stay twinless; heaps over the caller's host pages stay the
documented copies-alone gap. Docs: decoded_twin.rs, pvrtc.rs, etc.rs, degradation.rs, docs/API.md,
docs/FAST-PATHS.md (heap shadows of decoded formats are no longer for copies alone). New device test
runtime_lane/heap_carried_reads.rs. Public surface: WorkCounts (for the lanes) gains
shadow_twin_decodes, blessed in api_signatures.tsv.

Verified: PHOENIX m3-max-33568 (carried binary of the lane tip d5bf9cac82): heap_carried_reads,
a_carried_heap_texture_reads_its_bytes_with_no_commit, pvrtc_texels_read_as_metal_s and
etc_texels_read_as_metal_s pass. Under HeapAnswerPolicy::Metal all 8 cases shadowed; a use takes 1
copy and 1 decode, a second encoder in the same command buffer 0 and 0; kernel reads, samples, blit
out and getBytes equal the texture outside a heap, and samples follow a blit and a replaceRegion.
Under HeapAnswerPolicy::Device: not shadowed, 0 copies, 0 decodes, equal. Without the fix
(33467 at the test commit) all 8 reads were refused. lavapipe (msi 33535): the 4 tests pass. Clippy
x3 running in 33569.
2026-11-15 13:46:15 -08:00
Anees Iqbal dc77ffbb55 in_place_textures: the lent render targets' print keeps its line continuations
The IN-PLACE-LENT line of render_targets_whose_copies_lose_their_padding_lie_in_place
printed runs of spaces where its string's line continuations had collapsed when
it was written (lavapipe job m3-max-33512 shows them). Print only; no
assertion changes.

Verified: compiled under --cfg m2v_gpu by the clippy job that follows.
2026-11-15 13:40:10 -08:00
Anees Iqbal fb33065288 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 13:33:05 -08:00
Anees Iqbal 5813fe6743 RUNTIME 2381: a render target whose copies lose its padding lies in place
On the Iris Xe (ANV), a render target over host pages whose rows end
inside a 64-byte line (nonCoherentAtomSize) failed the in-place check's
renders: the clear and store, and draws, write back the line holding a
row's last texels whole, so a CPU write to the padding in that line can
be lost. Such textures were shadowed (733 in reims's walk: RGB10A2
66x66@512 572, RGBA16F 55, R8 49, A8 49, BGRA8 3). But the shadow keeps
nothing more: its copy back writes the same lines, and on this device a
plain buffer copy, a copy of texels into a buffer's rows and a kernel's
stores all write back that line too (Iris probe, job m3-max-33417:
clear+store 15/15 rounds changed padding bytes, draw 15/15, product
shadow copy back 14/15, buffer copy 15/15, kernel stores 6/6; every
changed byte in the row's tail line, none past it; rows on lines 0).

The check gains an access, Copies: a blit copies a zero texture's texels
into the class's buffer's rows while the CPU writes beside them (every
shape but the 3840x2160 surface; no rounds over the runtime's own
memory). A texture that renders over host pages whose rows' padding is
free (not declared unobserved), whose renders failed for its row ends,
now takes the verdict of renders that let that padding change where the
class's Copies failed for those row ends too (pending while they are),
announced as Degradation::LineWriteBack (line-write-back, Precision).
Copies failures carry across classes as the other GPU writes do. The
check notes each class and access's rounds' time. CHECK_VERSION 19.

Docs: FAST-PATHS host-pages row and a known gap for the Iris line
write-back (nonCoherentAtomSize 64; buffer copies, texel copies, kernel
stores, passes); API.md section 1 and the catalogue entry; the in-place
lane's VERDICTS 98 -> 112 and a lane test with the kind's site.

Verified: msi m3-max-33510 at the lane tip 47b06c9f0d: clippy (runtime + translator, all features,
all targets) 0; runtime tests 29/29 (the decision, a_texture_that_renders_lends_its_free_padding_
where_the_copies_change_it_too, carry, degradation_catalogue, degradation_sites, texture_placement);
translator api_signatures, fast_paths, api_surface 34/34; --cfg m2v_gpu archive of runtime +
validation built (33511). Pending: negative control 33520, lavapipe 33512, the Iris proof.
2026-11-15 13:32:18 -08:00
Anees Iqbal ecd43305a5 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 13:19:12 -08:00
Anees Iqbal 369835f951 RUNTIME 2380: the submitting thread's CPU time is read only where queue times are noted
RUNTIME 2379's WorkCounts::batch_submit_cpu_nanos and submit_long_call_cpu_nanos read
CLOCK_THREAD_CPUTIME_ID twice on every submission call on every driver. That clock is a system
call on Linux, not a vDSO read: 459 ns a read against the host clock's 19 ns (thread_clock_bench,
Ryzen 7 7840HS, Linux 7.3, fastest of 3 rounds of 1M reads, m3-max-33486), so 0.9 us a call always
on, against a whole NVIDIA submission call of ~12 us. The thread's CPU time is now read only where
the device notes queue times (METAL2VULKAN_QUEUE_TIMES, the existing default-off diagnostic); the
CPU fields read 0 elsewhere and their docs say so with the measured cost. The wall-time fields,
the long-call counts included, stay on. The long-call bench turns queue times on and gains its
unfenced arms (one VkCommandBuffer against 47); thread_clock_bench measures the reads.

Verified: msi m3-max-33490 at the lane tip 57e916e1c6: clippy (all features, runtime + translator)
0, clippy --cfg m2v_gpu 0, lavapipe kernel_end_device + submit_stalls 16/16 (the queue-times device
test checks the CPU time stays unread when not asked and is counted once asked).
2026-11-15 13:18:30 -08:00
Anees Iqbal e37fbf2c50 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 13:06:48 -08:00
Anees Iqbal f938dfae91 RUNTIME 2379: WorkCounts count the submitting thread's CPU time across the driver's submission calls
A guest compute loop's vkQueueSubmit calls on the Radeon 780M averaged 601 us, 293 of them 1 ms or
more in 32 s, and nothing told a call that works from one that waits on a driver without the stall
fact. WorkCounts::batch_submit_cpu_nanos sums the thread's CPU time (CLOCK_THREAD_CPUTIME_ID; on
Windows GetThreadTimes, sampled at the clock's ticks) across every call batch_submit_nanos times;
submit_long_calls, submit_long_call_nanos and submit_long_call_cpu_nanos count the calls of 1 ms or
more. Benches (test-only): a guest compute loop's submissions term by term, chained encoders and a
host-set event's wake, growth per VkCommandBuffer with fenced chains, import and free churn apart,
and long calls split by the GPU's work and the listed dma-bufs, with and without a warm-up spin.

Finding (PHOENIX, release, m3-max-33442): the long calls work, they do not wait: thread CPU is
about wall time in every arm (360 listed, 3 in flight: mean 867 us, 861 us CPU). A 500 us spin
before the call cuts it 7-12%, so most of the doubling after a 3 ms GPU step is cold caches.

Verified: msi m3-max-33446 at the lane tip f67314bade: clippy (all features) 0, clippy --cfg
m2v_gpu 0, submit_stall tests 12/12. Windows clippy not run (thread_cpu, the existing
GetThreadTimes path, only made pub(super)).

Public surface: WorkCounts (for the lanes, not part of the API) gains four pub fields, blessed in
api_signatures.tsv; a struct literal of WorkCounts must name them, Default and readers are unaffected.
2026-11-15 13:06:05 -08:00
Anees Iqbal d64e988624 host_ram_copy_device: the recovery test copies into a buffer made after the recovery
a_recovery_starts_a_ram_s_plans_and_their_tables_anew copied into a Shared buffer made before
recover_for_test(). Where the device keeps Shared buffers in pooled memory (the RX 7900 XTX on
RADV, whose check finds that a held import taxes submissions), the recovery leaves such a buffer
with the lost generation, as device/carry.rs documents, so the first copy after it was refused
with NotImplemented(MadeBeforeRecovery) (round ef313200e2, XTX runtime leg). The test is about
the RAM use's plans and tables, which the recovery carries; the copies after it now go to a
buffer made after it.

Verified: see the landing check job.
2026-11-15 12:54:02 -08:00
Anees Iqbal 4515cc0250 first_use: a heap making's name passed by value (clippy needless_borrows_for_generic_args)
Job 33403: clippy under --cfg m2v_gpu and m2v_cpu_icd flagged the borrowed
format! passed to Calls::time, which takes impl Into<String>.
2026-11-15 12:52:11 -08:00
Anees Iqbal ae895a5729 first_use: the heap's carried makings are PVRTC and ETC2, which take a twin; ASTC is refused there
The commit before made the heap's carried texture an ASTC_4x4_LDR one. A
heap refuses that texture where the device lacks ASTC
(NotImplemented(DecodedHeapTexture), job 33372 on lavapipe). A heap's 4:2:2
texture is a shadow of the heap's bytes (AliasRoute::MemoryShadow), so it
takes no twin and stages no decode. The heap's carried kinds that take a
twin in its own memory, and stage its whole decode as they are made
(heap.rs, decode_whole), are ETC2/EAC and PVRTC. So the timed heap makings
are now a PVRTC_RGBA_4BPP texture and an ETC2_RGB8 one. Every device but
PowerVR's carries PVRTC. The test prints the whole decodes those makings
staged (WorkCounts::block_decode_passes), which shows the route was taken.
The no-commit get_bytes test uses a PVRTC texture in a Shared heap. Its
rows are unpitched, as Metal takes PVRTC's.

Verified: nothing yet; the msi job (clippy x3, rustdoc, lavapipe) and the
PHOENIX run (tip x3 plus the control) follow.
2026-11-15 12:52:11 -08:00
Anees Iqbal eaaacae33e first_use: the staged whole decode is an ASTC heap texture's, which PHOENIX and lavapipe carry
A GBGR422 texture in a heap took no staged decode on PHOENIX: the control
(runtime at 18c640a85d) built nothing at that making, so the check could not
fail there without the fix. An ASTC_4x4_LDR texture in a heap is carried
where the device lacks ASTC (PHOENIX, lavapipe), and its making stages its
twin's whole decode (heap.rs, decode_whole), so the timed making and the
no-commit get_bytes test now use one. The 4:2:2 texture of its own stays
among the makings.

Verified: nothing yet; the msi job and the PHOENIX run (tip x3 plus the
control) follow.
2026-11-15 12:52:10 -08:00
Anees Iqbal 3b7bcfa367 least_queue_plan: the least plan's making the driver refuses under load is asked again
On the RTX 2080 (job m3-max-33373, 34 queue tests at 16 threads)
a_device_refused_once_takes_its_least_plan_where_it_takes_fewer_queues
failed: the stand-in refused the plan's 18 VkQueues as the test asks,
and the driver itself then refused the least plan's 3
(ERROR_INITIALIZATION_FAILED), the other test processes' devices
holding its channels, so the test read a refusal of a least plan that
takes fewer.

plan_room's wait is now a generic with_room (device_with_room is built
on it, unchanged in what it does), and the test asks the stand-in's
refusal and the least plan's making again while the driver's own
answer to the least plan is a refusal (two attempts on a GPU whose least
plan takes fewer), with the same pauses and bound and a
PLAN-DEVICE-ROOM line each. The probe's making again, where the least
plan takes no fewer, goes through device_with_room.

Verified: cargo fmt; build, clippy and the tests in the lane's jobs.
2026-11-15 12:39:51 -08:00
Anees Iqbal 187127bd04 Runtime lane: a making made again leaves the loader's errors about its refused vkCreateDevice behind
The 2080 lane leg 1/2 at c1747ff89 (job m3-max-33322, 1,040 tests,
830 s) waited 35 times for room, 12.0 s of pauses in all, and every
device it waited for was then made with its plan. 16 of those tests
then failed on the loader's errors, which the wait had left in the lane's
message list: kernel_textures x10, layered_passes, made_at_creation x2,
math_routines, mesh_commands and ycbcr_in_place. The loader reports each
refused vkCreateDevice as two errors through the instance's messenger
("terminator_CreateDevice: Failed in ICD ... vkCreateDevice call",
"vkCreateDevice:  Failed to create device chain."), and those come from
the making the lane drops and makes again, not from the device the
test keeps.

Messages::failing_kept and Messages::drop_failing_since: the lane marks
the failing list before each making, and where it makes that one again
it drops what was kept since the mark. The kept making's messages, the
layer's included, stay. validated_device_with and made_lane_device both
do it.

Verified: cargo fmt; build, clippy and the 2080 lane leg in the lane's
jobs.
2026-11-15 12:32:12 -08:00
Anees Iqbal 111a086b82 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 12:29:42 -08:00
Anees Iqbal c471372f87 RUNTIME 2378: Decoded twins: no making builds a decode kernel; a decode pass's kernel is made at its first recording or before the submission's lock
What: a DecodePass keeps what its sets bind as it is made; its kernel (TwinDecode, or a
4:2:2 twin's ChromaSample) and its sets are a FirstUse (owned_kernel.rs), made:

- by its maker where it records the pass at once: a blit's decode, and the decode a blit's
  write makes for a second twin, as the blit is encoded; a replace_region's own submission,
  before the submission;
- for every pass staged for the device's next submission (a heap texture's whole decode, a
  host call's staged copy's) or queued for a second twin (its whole decode, a host write's),
  by Device::make_pending_decodes on the submitting thread before the submission takes its
  lock: commit_as before the scheduler's section, submit_internal_taking before the device's
  internal lock. The passes are listed under the first-move registry's and the queue's locks
  and made after those are free, so a making that stages one never waits behind a compile; an
  atomic note, set after each registration, makes the walk one swap where nothing is pending.

Inside the sections, a submission takes no pass whose kernel is not made: a staged copy whose
decode is unmade waits for a later submission with every staged copy after it (the copies keep
their order), and a queued second decode stays queued. Such a pass was staged after the
submission's walk began, so its texture was made after the commit began, and none of the
submission's commands reads it. Each DecodePass::record debug-asserts that its kernel was
made. PairsSampling makes the device's conversion alone (made_ycbcr_conversion) and names its
kernel (module()), which surface_pairs' first-use making and the decode passes make.
make_second_twin no longer builds the kernel at the view's making.

Why: Metal's making compiles nothing. A carried texture's making in a heap compiled TwinDecode
(or ChromaSample), a 4:2:2 texture's making compiled ChromaSample where the device converts
its pairs, and a view of an ASTC carrier in its other colour space compiled TwinDecode. The
submissions record staged and queued decodes inside the scheduler's section (submit_batch,
record_second_decodes) or the internal lock (submit_internal_taking), so the compile goes to
the submitting thread before those locks, where no other queue's submission waits for it.
Where the cost lands: the first commit or internal submission after a carried heap texture's
making, a second-twin view or a carrier's staged write, once per device per decode kind.
commit's doc says so. A making whose staged decode passes the staging bound makes an internal
submission at once, as before, whose walk then compiles in that making.

Test: first_use's per-call built-nothing check covers three more makings: a GBGR422 texture
(a ChromaSample build where the device converts pairs), one in a heap (its whole decode), and
an ASTC_4x4_LDR texture's sRGB view (a second twin where the device lacks ASTC); the next
commit (a blit out of each 4:2:2 texture) takes the decodes, and the line names what the uses
built. a_carried_heap_texture_reads_its_bytes_with_no_commit: a GBGR422 texture made in a
Shared heap builds no kernel, then replace_region and get_bytes with no commit between read
the bytes written, the internal submissions among them making the staged decode first.

Verified (m3-max-33342, msi, at a13cf74a78): clippy of the runtime and validation crates (all
targets, all features, -D warnings) 0; lavapipe 376/376 of the first_use, heap, two-plane, YCbCr,
ASTC, chroma pairs, ETC, PVRTC, compressed-decode, first_moves, twin and encoder_fold tests;
first_use: no making built a kernel, the uses built 4; the carried heap texture's making,
replace_region and get_bytes built 0 kernels each and the bytes matched. The PHOENIX runs and
the device-configuration clippy follow on development.
2026-11-15 12:29:01 -08:00
Anees Iqbal 64ce708f46 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 12:28:15 -08:00
Anees Iqbal c37ea84558 RUNTIME 2377: Fresh pages on Windows: the class predicate no longer gates on unix
`class_takes_fresh_pages` answered `host_visible && cfg!(unix)`, a gate from
when `OwnPages::map` returned None off unix. b8bb06bcac gave Windows a
VirtualAlloc `OwnPages::map` (and the page-buffer blocks already use it there
through `own_page_types`), but left the gate. So on Windows no buffer took
fresh pages, even on a device that imports host pointers and whose submission
check found no import tax. In particular, an indirect command buffer's records
lay in pooled memory even under `IndirectRecordsPolicy::Carried`, where a
recovery's carry moves them and resets every command, where Metal keeps them.

Now the predicate is the class alone. Where the system maps no pages, or the
device imports none, the buffer lies where it would have (`OwnPages::map`
answers None; no importer). On unix the expression is unchanged. The module doc
cites VirtualAlloc's MEM_COMMIT zero guarantee beside mmap's.

Verified at the base (ef313200e2) on an Intel UHD Graphics 630, Windows driver
101.2145, gnullvm, --cfg m2v_gpu, each test in its own process (m3-max-33325):
tests::icb_carry_race::a_recovery_keeps_the_commands_the_cpu_encoded failed
("render command 0 (Lost)": [None; 4] against [Some(64), Some(80), Some(96),
Some(112)]); a_write_held_across_a_recovery_lands_on_the_records_it_keeps hung
(the pooled carry waits for the write the test holds); tests::fresh_pages failed
3 of 6 (no fresh-page buffer made where the device's check says they pay). The

Also in this landing (tests only): icb_carry_race's a_write_held never holds a write across a
pooled carry (it skips visibly where the device imports no host pointer, and fails at once where
the records still pool); device_recovery's Scratch makes a directory of its own per call, so each
recovery test gets its own device in one process (under cargo test's threads they shared one and
recovered each other's); host_ram_device's logged RAM fixture compiles only where its bench does.

Verified: UHD 630 Windows (m3-max-33356, at 38455c7259): the 7 icb_carry_race tests each alone and
all 7 in one process pass (each recovery generation 1; the carried tests print Kept);
tests::fresh_pages 6/6. Base controls m3-max-33325 and 33334 (above; in one process the 5 pooled
failed 3/5 on one shared line at generations 1-5). Lavapipe, cargo test in one process (33354):
the recovery family, icb_carry_race, icb_records_policy, fresh_pages, stall and labels 56/56. At
9d78e00e30: clippy plain, m2v_cpu_icd and m2v_gpu 0 (33360), Rustdoc 0 (33364).
2026-11-15 12:27:34 -08:00
Anees Iqbal ec88d92702 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 12:26:34 -08:00
Anees Iqbal da6cc554bb SEMANTICS 2125, RUNTIME 2376: Rate maps: a region-copy recording draws one row, its region its first's segments plus DrawIndex
A recording through the region-copy variant drew a box of several rows, so its vertex function
found its region as `first + (DrawIndex / c)·nx + DrawIndex mod c`: it read the table's count of
columns, divided by it and by the box's columns, and only then read its region's terms.

Now each row of a box is its own recording (in parts of at most a multi-draw's draws), and
`PushField::RegionBox` holds the row's first region's segments `[x0, y0]`: the vertex function
draws the region of segments `(x0 + DrawIndex, y0)`, dividing nothing and reading no table word
before its region's own, the row's `y0` the same at every vertex. A row is recorded a region at
a time where a sample may lie on a pixel's left edge (`folds` answers that axis alone: a row's top
and bottom edges are its scissor's). The pixels and positions are the route's as before: the same
copy arithmetic of the same region, under the same viewport, its row's scissor holding the
regions' pixels. A whole-table draw is 34 recordings where it was 2
(rate_map_region_copy_recordings). The docs, the FAST-PATHS fan-out row and the boxes test say
rows; the docs drop the cost claim the Iris A/B disproved.

Kept though neutral on the Iris: the shorter vertex function (42 instructions, 428 estimated
cycles, 8 sends -> 37, 258, 7) did not move the per vertex-region cost, which lies in the fixed
function after it (four user clip distances tested on every copy; 2073 of 2074 rejected there).

Verified: m3-max-33295 (msi, at 72bd8baa20): clippy of the translator and runtime (all targets,
all features, -D warnings) plain, m2v_cpu_icd and m2v_gpu 0; translator 47/47 and runtime
fan_out 6/6 unit tests; lavapipe 24/24 rate-map device tests. m3-max-33355 (ef59a08250, docs):
clippy plain and Rustdoc 0. Iris (ms01) m3-max-33332: 24/24 rate-map device tests
(region_boxes direct [3 draws, 39 recordings] against indirect [3, 624], 0 texels differ;
depth_equal 0 red). Negative control m3-max-33327: the base's divided region restored, the SPIR-V
divisions assertion fails (4 vs 0). Iris A/B m3-max-33262 (warm, no INTEL_MEASURE): whole-table
commit frame 671.1 -> 670.9 ms, Exact 505.7 -> 498.7 ms; per sub-draw 1.068 us + 0.3626 ns x V
-> 0.926 us + 0.3697 ns x V.
2026-11-15 12:25:53 -08:00
Anees Iqbal b6081e2c7e Runtime tests: a device of the queue plan is made again while the driver lacks room for it
On the RTX 2080 (job m3-max-33317, 31 queue tests at 16 threads) the
driver refused 10 of the 12 queue_share_device tests' devices their
queue plan, and the runtime made them with its least plan's 3
VkQueues; the tests passed on one shared VkQueue, so what they claim
about the plan's queues went untested. The runtime's own device tests
had no wait like the lane's (ef66c46a5f): on NVIDIA each VkQueue is a
channel, the 2080 holds about 210 across processes (11 devices of the
plan's 18, job m3-max-19615), and the suite's 16 processes ask more.

src/tests/plan_room.rs's device_with_room makes such a device again,
the one made dropped first, while the driver refuses it for want of
resources (Error::DeviceRefused) or it took its least plan
(DeviceShared::least_plan), with pauses doubling from 0.25 s to 2 s up
to 120 s in all, each a PLAN-DEVICE-ROOM line naming the answer and the
wait. Any other error returns at once; past the bound a refusal is
returned and a device still of its least plan fails its test, so a test
of the plan's queues runs on them or not at all. No lock and no
cross-process coordination.

Every plan-device maker in the runtime's tests goes through it:
blit_holds, caller_queue_writes, commit_and_submit, completion,
completion_wakes, draw_again, hand_out_waits, queue_limits_device,
queue_share_device (5), reserved_queues, scheduler_held_wakes,
scheduler_wakes, store_out_device and video_interop. Left as they are:
the least plan's own tests (least_queue_plan, reserved_queues'
a_device_made_with_its_least_plan_reserves_what_its_plan_spares), which
stand the driver's refusal in with refuse_next_devices; many_devices, a
GPU hazard that fills the GPU on purpose; host_ram_first_fill_bench's
ignored release benchmarks.

Test: plan_room::a_plan_device_refused_once_is_made_again_of_the_plan_s_queues
refuses the first making with the stand-in and asserts the device
helped back is of the plan's round robin and presenting queues (from
queue_plan over its families), not its least plan; a plain making
answers the least plan (NVIDIA) or a refusal (lavapipe, RADV) there.
docs/VALIDATION.md says the runtime's tests wait too.

Verified: cargo fmt; build, clippy and the tests in the lane's jobs.
2026-11-15 12:22:02 -08:00
Anees Iqbal 18c640a85d Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 12:09:12 -08:00
Anees Iqbal 00e1304a7c RUNTIME 2375: Owned kernels: a resource's own moves are made at its first use, never as it is made
What: a shared FirstUse cell (owned_kernel.rs) keeps what a resource's sets of one of the
runtime's own kernels bind as the resource is made; the kernel (once per device, as
owned_kernel's rule says) and the sets are made by make() at the resource's first use, as an
encoder plans a command that uses it (ShadowCopies::prepare), before any of its copies is
recorded. Every record takes them through made(), which debug-asserts that a use made them and
records nothing where none did. Three resources take it:

- the tiled heap texture's moves (HeapTiledCopies), which held this form inline;
- a heap's two-plane extended-range texture's moves (HeapPlaneCopies, RGB10A8_2P_XR10 and its
  sRGB twin, in a heap or over a surface's planes), whose making compiled TwoPlaneTexels;
- a 4:4:4 two-plane YCbCr texture's write shadow's write-back (YCbCrWriteBack), and a render
  shadow's load (YCbCrLoad), whose making compiled YCbCrWrite (and YCbCrConvert's float form):
  a heap set's float storage element makes that shadow as the texture is placed, so the
  texture's making compiled it wherever such a set lived.

Why: Metal's resource creation never waits for anything and compiles no pipeline; on a RADV
APU a compile beside busy GPU work took 10-43 ms in a heap texture's making (the tiled form's
probe). The compile now moves to the first encode that needs the moves, once per device, on
the encoding thread, not on the making's.

Test: first_use's check that no making builds a kernel of the runtime's own
(WorkCounts::owned_kernels_made, per call) covers two more makings while the busy work runs:
an RGB10A8_2P_XR10 texture in a heap, and a YCBCR8_444_2P texture over a surface's plane made
after a kernel that writes through an argument buffer ran (so the device's heap set lives and
its float storage element takes the texture's write shadow), where the device holds textures in
argument buffers. Each is used after (a blit out; a write through its handle), and the line
names the kernels the uses built.

Left: a carried texture's decoded-twin kernels (a 4:2:2 texture's pairs on a device that
converts them, a heap texture's whole decode, a view's second twin) still build at making;
the next change. A multisample heap texture's sample-move trial builds pipelines to decide its
route; a separate follow-up.

Verified (m3-max-33274, msi, at ab77f697ba): clippy of the runtime and validation crates (all
targets, all features, -D warnings) 0; lavapipe 292/292 of first_use, heap*, two_plane*, ycbcr*,
extended_range_planes, shadow*, surface_two_planes and owned*; first_use: the makings built no
kernel, the uses built 3. The PHOENIX runs and clippy in the device configurations follow on
development.
2026-11-15 12:08:30 -08:00
Anees Iqbal 84888808bd Runtime lane: made_lane_device compiles only where its device tests do
validated_device_with no longer calls it, so the lib build outside the
device cfgs warned it unused (msi job m3-max-33276); its two callers are
device tests (degrade_notices, resource_ids).

Verified: cargo fmt; build and clippy in the next job.
2026-11-15 12:06:07 -08:00
Anees Iqbal ab4dacce5c least_queue_plan: read the plan's queues from the queue plan of the device's families
On the RTX 2080 (job m3-max-33087, 18 queue tests at 16 threads)
a_device_refused_once_takes_its_least_plan_where_it_takes_fewer_queues
failed "the least plan took no fewer": it read the plan's round robin and
presenting queues from a device the driver had made, and under that load
the driver refused that device its plan too, so it had taken the least
plan's 1 + 0 and the test compared the least plan with itself.

The plan's queues now come from queue_plan over the device's queue
families, as reserved_queues::spare reads them, so the branch the test
expects (least plan taken, or refused) is a property of the families, not
of the load. The probe that reads the families is made as a loaded GPU's
driver makes it, refused its plan once by the stand-in (so of its least
plan's 3 VkQueues on NVIDIA, made again where the least plan takes no
fewer), and dropped before the test's own device: the test now
reproduces 33087's condition on every run and holds 3 channels, not
18 + 3. The LEAST-QUEUE-PLAN line names what the probe took.

Verified: cargo fmt; the tests on the 2080 and lavapipe in the lane's
jobs.
2026-11-15 12:06:07 -08:00
Anees Iqbal 760f8d045b Runtime lane: a device the driver refused for want of room is made again once other processes may have let it go
The 2080 legs of round 9ce951f521 failed 33 of 2,054 lane tests at device
creation: 27 devices of the queue plan that the driver refused (the
runtime then took its least plan and announced least-queue-plan, which
the lane's creation check rejects) and 6 lane devices of 3 VkQueues it
refused outright (Error::DeviceRefused, ERROR_INITIALIZATION_FAILED or
ERROR_OUT_OF_HOST_MEMORY).

Cause, measured: NVIDIA's driver gives each VkQueue a channel with an
instance block of its own, and refuses a device where it cannot allocate
one (the kernel logs "Could not create Channel"). A device of the plan
takes 18 VkQueues on the RTX 2080 (14 round robin, 2 presenting, the
staging and fill queues; its copy family's 2 queues put the copy queue on
the fill queue's), a lane device 3. With nothing else running the 2080
(NVIDIA 620.70.06) holds about 210 channels across processes: 11 runtime
devices of the plan and 3 of the least plan, the 15th refused (job
m3-max-19615), and 66 bare devices of 3 with room for 18 (19562). The
legs run 16 test processes, 188 of the lane's 408 modules make devices of
the plan, and nextest runs a module's cases side by side: 16 x 18 = 288
VkQueues. Lane 2/2's indirect_executions shards, 64 tests at the plan in
a row, took 22 least plans. Nothing leaks: each lane test is its own
process, every helper drops its device in a scope, and a runtime device
makes one vkCreateDevice whose queues its threads never add to.

Neither answer is the test's: its device is the one it asked for, and
the GPU lacked room only while the lane's other processes held theirs
(the runtime's DeviceRefused docs: a device asked for again once fewer
are live may be made). So validated_device_with makes such a device
again, the one made dropped first, after a pause doubling from 0.25 s to
2 s, for at most 120 s in all (runtime_lane/device_room.rs), and
made_lane_device does the same for a refusal. Only Error::DeviceRefused
and a least-queue-plan announced as the device was made are asked
again; any other answer returns at once, and past the bound the last
answer is handed back, failing the test as before. Each pause writes a
LANE-DEVICE-ROOM line naming the answer, the pause and the time waited.
No lock and no cross-process coordination: the driver's answer is the
only signal. The runtime's least plan and refusal stay its own tests'
(tests::least_queue_plan, the driver's refusal stood in for).

Tests: runtime_lane::device_room's unit tests (no device): a short
answer is asked again with doubling pauses until one has room; an answer
with room returns with no pause; one that never has room stops at the
bound. docs/VALIDATION.md's few-channels paragraph says what the lane
does now; degrade_notices' LEAST_PLANS says why no lane test keeps it.

Verified: cargo fmt; build, clippy and the tests in the lane's jobs.
2026-11-15 12:06:06 -08:00
Anees Iqbal ef313200e2 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 11:46:35 -08:00
Anees Iqbal bb21c14865 compute/live: name SamplerState where the debug check takes it, so a release build imports nothing unused
check_whole, the only user of SamplerState in compute/live.rs, is cfg(debug_assertions), so a
release build under --cfg m2v_gpu warned 'unused import: SamplerState' (live.rs:94), an error
under -D warnings (seen by the gbgap and ratemap3b lanes' release builds). The signature names
the type by its path and the import goes.

Verified: see the landing check job.
2026-11-15 11:44:21 -08:00
Anees Iqbal db50e74588 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 11:42:38 -08:00
Anees Iqbal 7098431fe0 RUNTIME 2374: Dirty pages: a command's run of uses of one key is noted at once
DirtyCommit::note did all its work once a use. A host RAM copy over 128 chunks of a RAM with
a log names 2048 writes, and each chunk's key has a log of its own (RamOnDevice::chunk_key):
each write searched `host` for its log (one entry a chunk's log, about 128), took a Vec of its
own in `reported`, looked its key up in the imports and upgraded the log's Weak again, and put
its key in `used` again. On msi's lavapipe that was 179 us of a 290 us call (release probe,
m3-max-33184, the layer bench's logged case).

note now takes each run of consecutive uses of one key at once: the key goes into `used` once;
its logs are looked up and upgraded, and their places in `host` found, once, at the run's first
write; each kept write's reported logs are a range of one flat list (reported_hosts) that the
run's writes share, so no write takes a Vec of its own. Each write is still kept apart (the
seen check of the last 8, `written`, WRITES) and noted in its logs' ranges (HOST_RANGES, the
whole past it) as alone: written, host, what report_host_writes tells and when are as before.
wrote_host is split into host_place and wrote_at; wrote_unreported reads a write's logs through
its range.

Test: runs_of_one_key_note_exactly_as_their_uses_one_by_one notes 300 generated command
buffers (runs, keys named twice, reads, repeated writes, keys of no log and of two, logs past 64
ranges) and one past 4096 writes and keys, through note and through note_each (the uses one by
one, test-only), and asserts the same NotedWrites: each write with its logs, the keys used, the
overflows and each log's ranges.

The test's evidence bound asks for more than 30 logs written whole past 64 ranges (the rounds
give 43).

Verified: m3-max-33195 (msi, at 65498cb639): the runtime crate on lavapipe 2822/2823 (the one
failure the test's own bound, lowered in d99df37c6a), clippy plain, m2v_gpu and m2v_cpu_icd 0,
Rustdoc 0; m3-max-33205 (at d99df37c6a): 49/49 dirty and host_ram_copy tests, clippy cpu-icd 0.
Release A/B (m3-max-33196, msi lavapipe, 3 interleaved pairs, the same probe on both, us a call,
128 chunks of a logged RAM): note_dirty 200.4/204.1/196.6 -> 75.8/86.6/79.7, the call 324.1 ->
204.4 mean; unlogged unchanged; the log told 4096 runs a copy in every run.
2026-11-15 11:41:52 -08:00
Anees Iqbal 79adf9aef7 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 11:36:03 -08:00
Anees Iqbal cdb708d35f RUNTIME 2373: Heap textures: a tiled heap texture's making builds no kernel; its first use does
What: HeapTiledCopies (a heap texture held as a shadow in Metal's tiles,
AliasRoute::Tiled, and the surface depth textures that use it) no longer
builds the device's TiledTexels kernel or writes its two descriptor sets as
the texture is made. They live in a OnceLock and are made at the texture's
first use, in ShadowCopies::prepare(), which the encoder's plan_shadows calls
before it records any shadow copy. That is the path a converted YCbCr
texture's conversion already takes. dispatch() debug-asserts that the kernel
was made. So the compile moves to the first encode that needs any tiled
shadow, once per device, as owned_kernel.rs's rule says ("made once per
device, when a command first needs it"). That cost is now on the encoding
thread, not on resource creation.

Why: runtime_lane::first_use::new_resources_wait_for_no_gpu_work failed three
times on the Radeon 780M (RADV PHOENIX), always at "new_texture in a heap",
which returned 0.7-0.8 s later, about 65-70 ms after the busy work ended, with
no internal submission. A probe on um790's PHOENIX (9 runs, 3 of them beside
the lane's partition 4/4) showed that this making takes 10-43 ms every time,
while every other making takes about 1 ms. Backtrace samples taken 4 ms into
the call (3 runs) sit in vkCreateComputePipelines under HeapTiledCopies::new,
via Device::owned_kernel(TiledTexels). It is the only timed call that builds a
pipeline. Expected, not verified (the long wait did not reproduce in the probe
runs, nor beside a VRAM hog): the 0.7-0.8 s is that compile waiting in the
driver or kernel for the GPU's in-flight work, on an APU with a 2 GiB carve-out
shared by the lane's parallel processes. Metal's makings compile nothing.

Test: the first-use test records WorkCounts::owned_kernels_made around each
timed call and fails where a making built a kernel. Without this change that
check fails wherever the heap texture takes the tiled route (the 780M:
verified). The test also prints the tiled-heap-texture count and the kernels
the later uses built, as evidence the path ran. The heap texture's copy in and
copy out still read Metal's bytes.

Left alone (main records it): owned_kernel holds the device's owned_kernels
lock across every compile, so a lookup of a kernel already built waits behind
another kernel's compile.

Verified (m3-max-33194, msi, at 01fe19ba22): clippy of the runtime and validation crates (all
targets, all features, -D warnings) 0; lavapipe 132/132 of first_use|heap*|shadow*, including
first_use::new_resources_wait_for_no_gpu_work and every heap_tiled unit test. The PHOENIX runs
(the cause's device) and clippy in the device configurations follow on development.
2026-11-15 11:35:22 -08:00
Anees Iqbal 8bd796ce4f Bench: the layer's download over every chunk of a RAM whose writes a log keeps
A VMM keeps a log of its guest RAM's writes on a discrete GPU, so a download into that RAM
records each command's uses for the commit's report to the log (DirtyCommit::note): a cost the
layer bench's RAM, which had no log, never showed. host_ram_layer_encode_bench now runs its
two cases (the layer in one chunk and over every chunk), lets that RAM go (its keep-alive
dropped, so two RAMs' pages are never held at once), then runs the layer over every chunk of a
second fresh RAM with a log (HostRam::with_dirty_pages of LayerLog, which counts the runs it is
told), alone and beside a fill as the others, and prints the runs the log was told a copy: the
evidence the logged path ran.

The case's body is layer(), shared by the three. host_ram_device gains fresh_logged_ram_in, a
fresh RAM with a log, beside fresh_ram_in (fresh_host_ram_of makes the RAM for both).
2026-11-15 11:28:16 -08:00
Anees Iqbal 87e6846abd Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 11:27:52 -08:00
Anees Iqbal ccf9d5847a RUNTIME 2372: Encoders: a command's joined runs go into the part's tracked uses at once, as note leaves them
order_joined's Joins::of copied every use of a joined run's kept tail into a `noted` list grown
from empty, and took each run's hull twice by folding whole uses; note then walked those uses one
by one (a map entry, a find over the key's ranges, a clone, the room for 9 at the second), though
Joins already holds the run's key new to the part and named once by the command. At a host RAM
copy over 128 chunks (2049 uses, 128 runs of 16) that was about 25 us in Joins::of and 25 us in
note a copy on msi's lavapipe (release probe, m3-max-33112).

Joins now keeps, for each joined run, its key and the list note leaves of it from none (the hull
of its first 9 + 8m uses, then each after, in one Few with room for 9 past the first, as note
reserves), and `noted` holds only the uses no run joined. order_joined orders by `ordered` and
notes `noted` through order_as as before, then puts each joined key's list into the part at once
(note_kept), the map reserved for them. A run's hull is the first's range hulled with the last's
(their bytes past each other: the first's start to the last's end) with the reads and writes of
all folded, no use moved per step. A run with an empty range is not joined (joins), so note's
merge of equal ranges never meets a joined run, and empty ranges order as before.
order, inside_uses and admit are unchanged; the plain path takes none of this.

Test: runs_of_9_and_20_uses_join_exactly_and_one_with_an_empty_range_does_not (a 20-use run that
note collapses at its 9th and 17th, a 9-use run, a buffer use; after a command and as the first;
ordered and not) asserts equal barriers, summaries and the next encoder's cross-queue plan against
order, and that the run with an empty range is not joined. The 600-round
runs_of_one_key_joined_order_exactly_as_their_uses keeps asserting the same over random commands.

Verified: m3-max-33153 (msi, at 83e47c807a): the runtime crate on lavapipe 2823/2823, clippy
plain, m2v_gpu and m2v_cpu_icd 0, Rustdoc 0. Release A/B (m3-max-33160, msi lavapipe, 3
interleaved pairs, the same probe on both, us a call at 128 chunks): note 25.7/23.2/29.3 ->
4.0/4.3/4.5; Joins::of unchanged (about 27); the call 132.0 -> 115.1 mean; one chunk unchanged.
2026-11-15 11:27:11 -08:00
Anees Iqbal b255317a37 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 11:26:06 -08:00
Anees Iqbal 09aee83953 RUNTIME 2371: Compute: a state keeps 16 plans; a lookup compares the latest four in place and keys only the rest
A dispatch takes what its state planned for its bind state's shape and class of grids while the
state keeps it among its latest PLANNED. A stream of dispatches over buffers of several length
classes in grids of several classes cycles more pairs than 4: the bench's moved, heap, ragged
shape of three length classes cycles 6 through 4 entries, so a fifth of its dispatches planned
again (plan_now 4.0% of the encoding thread on msi lavapipe, m3-max-33099). In the consumer's
profile of its compositor's fix-index encoder on the XTX (hvP2, at 2cdfa840b5) plan_now,
BindState::shape and position_of_shape were 25.2% of dispatch_threads, 64% of its dispatches
planned and 47% made their shape anew.

PLANNED goes from 4 to 16. Each Planned carries its shape's key beside its used resources
(BindShape::key_beside_used). A lookup (position_of, used by planned_shape and planned_of)
compares the latest IN_PLACE = 4 entries in place, as the state compared its four before; only
where none is the state's shape does it work out the state's key (which folds every argument
sampler's) and compare whole only the remaining entries of that key. planned_for's fallback,
past the Arc match, compares whole only entries of the shape's key. PLANNED's doc states the
bound: about 290 bytes an entry, and at most PLANNED entries' variants and region pipelines kept
past the state's memos. The dispatch_chain bench's --classes takes up to 12.

Test: grid_classes::shapes_and_classes_in_turn_each_plan_once (six shape-class pairs in turn for
six rounds: each plans at its first dispatch alone, every later one takes its plan, every slice
Metal's words); at PLANNED=4 it fails (grid_classes.rs:346).

Verified at 9b5717e840 (m3-max-33158, msi): clippy plain, m2v_cpu_icd and m2v_gpu 0, Rustdoc 0,
106 lavapipe tests of the compute paths, the PLANNED=4 control failing. Profile (m3-max-33180,
msi lavapipe): 48 samplers, 3 classes: no key pass, plan_now gone; 12 classes (24 pairs): the
keyed path runs. XTX A/B (m3-max-33162, 5 interleaved rounds, load 23, median ns a dispatch,
dev 0ab6927fce / this): no samplers 3 classes 4448/4272; 48 samplers 3 classes 5180/5122, 12
classes 7708/6423; 200 samplers 3 classes 6408/6435 (flat); plain 3753/3554; no samplers 12
classes noisy (median 6151/6547, min 5839/5220, least encode+commit 6166/5543).
dispatches_planned_as_before 0.80 -> 1.00 at 3 classes; at 12 classes 0.61 reused where dev
planned every dispatch.
2026-11-15 11:25:26 -08:00
Anees Iqbal 0ab6927fce Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 11:02:00 -08:00
Anees Iqbal c76dec3f57 RUNTIME 2370: Host RAM copies: a copy's imports name their chunks in one flat list, and a made chunk's import is taken without a list of its own
copy_imports built, per chunk, a Vec in a BTreeMap of the import indices that hold the chunk's
bytes, and for_copy returned a one-element Vec for every made chunk: at 128 chunks two heap
allocations a chunk on every copy, the kept plan's reuse included, before the plan's serials
and maps were compared.

CopyImports::of_chunk (and KeptPlan's copy of it) is now one Vec of (chunk, import index) pairs
in the imports' order, sized for one import a chunk up front. copy_imports takes a made chunk's
import itself, after take_for_copies still moved the window past every chunk left, and
for_copy handles only chunks not made. The reuse compares the two lists as before (same
imports in the same order, each holding the same chunks). The full path sorts a copy of the
pairs by chunk (stable, so each chunk's imports keep their order) and looks a piece's chunk up
in it (imports_of), in place of a table of every chunk's slice.

Test: each_chunk_s_imports_are_found_by_chunk_in_the_order_they_were_given checks imports_of
against the old per-chunk map over 200 generated import lists. The device tests of both copy
paths cover the rest.

Verified: m3-max-33083 (msi, at 9b59c25348): the runtime crate on lavapipe 2821/2821, clippy
plain, m2v_gpu and m2v_cpu_icd 0, Rustdoc 0. Release split at 128 chunks (m3-max-33086, msi
lavapipe, before/after interleaved, the same phase probe on both, us a call): copy_imports
23.1/25.1 -> 4.9/5.1, the reuse's compare 6.7/6.9 -> 2.5/1.9, the imports' drop 4.6/4.0 ->
0.8/0.9; the layer's call 156.7 -> 133.9 mean; one chunk unchanged (one slot).
2026-11-15 11:01:19 -08:00
Anees Iqbal 1328c20270 parity: the corpus path comes from the validation directory at run time, not the build machine's
corpus() joined env!("CARGO_MANIFEST_DIR"), baked at build time, so a carried test archive run
on another node read no Metal records (parity::sequences::lane::sequences_0..7 'no Metal record'
off msi, regr98's 31742). It now joins metal2vulkan_devtools::validation_dir(), as the
runtime lane's corpus readers do.

Verified: see the landing check job.
2026-11-15 10:54:57 -08:00
Anees Iqbal 48ce52b1b9 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 10:54:00 -08:00
Anees Iqbal 421ee18512 RUNTIME 2369: Compute: a dispatch holds its pipeline state, variant objects and pipelines by address first
Each compute dispatch held its pipeline state, its variant's objects and each region's
VkPipeline by another reference (an Arc clone) that Retained::shared then dropped where the
encoder held the object lately, as it does for every dispatch of the objects of the one before
it: an atomic increment and decrement of each object's count, on lines other threads touch too.
In the consumer's profile of its GL fix-index encoder Retained::shared was 3.3% of
dispatch_threads, 2.8% its own.

Retained::shared_of holds an object by the caller's reference, cloning it only where the encoder
does not hold it lately, the same address test shared makes (EncoderCore::retain_shared_of,
ComputePipelineState::retain_in); compute's record holds its three kinds so, and keeps a
reference to the variant's objects rather than a clone of them. ComputePipelineState::held,
unused now, is gone.

Tested: tests::retained's new a_hold_by_reference_takes_another_only_where_none_is_held_lately
(holds and strong counts of shared_of alone and mixed with shared, and the push-out of the eight
looked among).

Verified at 1480a5352c (msi-laptop-w3657): m3-max-33061 clippy plain 0, lavapipe 332 tests of
retained|held|holds|compute|dispatch|grid_|pending passed; m3-max-33066 clippy m2v_cpu_icd 0,
m2v_gpu 0, Rustdoc 0. XTX A/B (m3-max-33058, radeon, 5 interleaved rounds, load 17-23, median
ns a dispatch, dev f452591afc vs the cut on it): 200 samplers 6074/6156, 48 samplers 4738/4641,
none 4398/4357, moved heap 3493/3470: no measurable change in the bench, where the counts stay
in one thread's cache; the in-situ gain is expected only, for the consumer's next profile.
2026-11-15 10:53:14 -08:00
Anees Iqbal 981d3f5f4b Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 10:44:16 -08:00
Anees Iqbal 2332ae096e RUNTIME 2368: Host RAM copies: a kept plan's table goes into a buffer of its own at its first reuse, which each reuse binds
Each copy by a kept plan uploaded the plan's table into its command buffer's arena: 8100
entries of 16 bytes for a layer, past the arena's 32 KiB so a chunk of its own (a new Shared
buffer) and a 130 KB copy, 22.5 us of a 74 us call at 1 chunk and of 191 at 128 (probe
m3-max-32988, steelbrain/dl2-probe4, not landed), for bytes the plan held and never changed.

KeptPlan keeps them in a buffer of its own (table_kept, a OnceLock), made at its first reuse
by KeptPlan::table_buffer: the arena's class (Shared, default cache, untracked, by
unzeroed_buffer_with, so the GPU reads it from the same memory), written once before any
command reads it and never again. record_dispatches takes the table as bytes to upload (the
full path, as before) or as that buffer (Table::Kept), which each command buffer that binds
it retains, so a plan the LRU or the RAM's end lets go of frees it once they complete. Two
encoders' first reuses at once keep the one set first. A plan never reused makes none. The
tables count in MOST_PLAN_BYTES already, so the device memory kept is at most that and each
buffer's rounding. A recovery carries the RAM's use to a new RamOnDevice on the next
generation (RamUseCell::carry), whose plans start anew, so no old generation's table is bound.
New counter WorkCounts::host_ram_copy_tables_kept; api_signatures.tsv blessed; the module
docs, KeptPlan's and HOWTO's say what memory the plans keep.

Tests (device): a_plan_keeps_its_table_in_a_buffer_from_its_first_reuse (planned, first reuse
keeps it +1, later reuses +0, bytes each time); a_kept_table_a_command_buffer_bound_outlives_
its_plan (command buffers held by a shared event bind it, eight other copies push the plan
out, the bytes after the signal); a_recovery_starts_a_ram_s_plans_and_their_tables_anew
(recover_for_test: the first reuse after keeps a table of its own).

Verified: m3-max-33015 (msi, at 612f09e48a): the runtime crate on lavapipe 2811/2811, clippy
cpu-icd, plain and gpu configurations clean, Rustdoc clean; the API tests 15/15 (m3-max-33048),
whose recovery test printed no skip line. Medians (m3-max-33017, msi, before/after interleaved,
us per call): one chunk, copy alone 60.6/59.6 -> 44.4/41.6, the copy after a fill 58.1/58.2 ->
44.3/41.6; 128 chunks about 10 us lower on average, within the runs' spread.
2026-11-15 10:43:31 -08:00
Anees Iqbal cb44fd0030 dispatch_work: a grid of the planned one's class takes its plan, and a ragged grid plans again
RUNTIME 2363 lets a dispatch of another grid of the class a plan was made for (pipeline::GridClass:
form, threadgroup size, whole, one row) take that plan where it names the very variant for the
grid. dispatches_take_what_their_state_planned_for_the_same_shape still expected the step
"the grid" (THREADS to 2*THREADS at the same threadgroup size: both whole, one row) to plan again,
and failed at dispatch_work.rs:516 on lavapipe (found by the synchaz lane, m3-max-33014/33033).

The step now expects the first grid's plan (planned 1, settled 0), and a new step dispatches a
ragged grid (1.5 threadgroups, another class) of the same shape, which must plan again. The later
steps move up two threadgroups to make room for its words; the doc says what the test checks now.

Verified: runtime_lane::dispatch_work on lavapipe and validation clippy (plain and m2v_cpu_icd)
in the potluck job that reports this tip.
2026-11-15 10:37:54 -08:00
Anees Iqbal 5ac7852e20 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 10:37:42 -08:00
Anees Iqbal 85a91d182c RUNTIME 2367: Queue plan: a device made with its least plan reserves what its plan reserves, no more
The 2080 round 9ce951f521-1115-0907 failed
reserved_queues::a_device_with_no_queue_to_spare_reports_the_reserved_queue_absent:
"11 asked, 11 reserved; no message", where queue_plan(families, u32::MAX)
spares 10 (NVIDIA's graphics family of 16 less the round robin's floor of
four and presenting's two). Asked for 11, the plan takes 4 + 2 + 10 plus the
staging and fill queues, 18 VkQueues; the driver refused that for want of
channels (um790's kernel log: "kchannelAllocMem_GM107: Could not create
Channel" 19 times at 10:01 and 13 at 10:02, while the 780 s run that ended
10:04:38 was at the test), and made_within_resources took least_queue_plan:
queue_plan_within(families, options.reserved_queues, {1, 0}), a round robin
of one and reserved min(15, 11) = 11. 11 is what only that path gives.

So a device short of resources gave the caller more reserved queues than the
same device given them, and skipped the reserved-queues-absent message,
though the least plan's notice and the runtime README say it keeps the
plan's reserved queues. least_queue_plan now reserves as many as the
device's own plan (within options.queue_limits) reserves; its round robin
of one always leaves room for them, so no fewer either.

Tests:
- queue_limits::the_least_plan_reserves_what_the_plan_reserves: every
  family shape, reservation (0 to u32::MAX), limit and cached flag; fails
  without the fix on NVIDIA's shape asked for 11 (11 against 10) and on a
  family of 24.
- reserved_queues::a_device_made_with_its_least_plan_reserves_what_its_plan_spares:
  the plan refused through refuse_next_devices(1), the device asked for
  spare + 1 takes its least plan (its notice heard, round robin 1) and
  reserves spare, reporting the rest absent; refused where the least plan
  takes no fewer (lavapipe, RADV).
- The test sink records each message's id name with its text, so the
  least plan's notice is matched by its code.

Docs: the degrade catalogue (docs/API.md), LeastQueuePlan's rustdoc and the
runtime README's "A driver short of resources" say the reserved count is the
plan's.

Also: queue_share_device's pinned test takes a stay the sharing rule
explains, as its siblings do (test only).

Verified (msi, m3-max-33039): clippy plain 0; lavapipe reserved_queues,
least_queue_plan, queue_limits and the pinned test 16/16. The 2080 run
follows on development.
2026-11-15 10:37:01 -08:00
Anees Iqbal 30331a477f kept_textured: the spun copies wait for the spin through a fence
Under METAL2VULKAN_LANE_VALIDATION=sync on lavapipe,
runtime_lane::kept_textured::a_kept_heap_draw_reads_what_an_earlier_command_buffer_wrote
failed on 1024 reports (512 copies, two cases): "vkCmdCopyBufferToImage(): READ_AFTER_WRITE
hazard detected. vkCmdCopyBufferToImage reads VkBuffer ..., which was previously written by
vkCmdDispatch", copy regions from offset 64, 64 bytes each.

spun_copies encodes the spin's dispatches, which store their count in the source buffer's
first word (bytes 0..4), and then copies the texels from bytes 64 on. Its premise ("so the
copies follow the spin") was Metal's whole-resource tracking of the buffer. The runtime orders
a tracked buffer by the bytes, as its README's "Hazards" says:

  The runtime orders a tracked buffer by the bytes a command reaches: those its translation
  proves a shader reads or writes, else from the bound offset to the buffer's end. Vulkan's
  synchronization validation takes a shader's buffer as accessed over its whole descriptor,
  which spans those bytes widened to 16-byte granules from the device's offset alignment, so
  it reports hazards between commands whose bytes are apart, as it does between untracked
  uses Metal leaves to the program; no order of either changes a result.

So on the runtime the copies did not follow the spin, and the test lost the delay it was built
on (the frame's kept draws waiting for an earlier command buffer's late writes). The layer
reported the copies' reads against the dispatch's whole descriptor.

The spin's encoder now updates a fence and the copies' blit encoder waits for it: an order
Metal keeps too (redundantly, beside its tracking), and one the runtime records as a barrier
from the spin's compute stages (fence.rs, the tracker). The copies follow the spin on both,
and the layer sees that barrier. Spin::encode takes the fence to update; Spin::new's timing
runs pass none.

Before: m3-max-32985 (msi, lavapipe, sync, at 3945a91289) failed the test with the reports
above. The proof run of this tip is in its landing report.
2026-11-15 10:22:18 -08:00
Anees Iqbal f67343b44e address_maps: the alpha-code rounds note their dispatches' apart writes
Under METAL2VULKAN_LANE_VALIDATION=sync on lavapipe,
runtime_lane::address_maps::every_alpha_code_of_a_texture_whose_alpha_reads_one_reads_one
failed on 65280 reports (255 pairs a round, 256 rounds) of one record-time hazard:
"vkCmdDispatch(): WRITE_AFTER_WRITE hazard detected. Shader stage VK_SHADER_STAGE_COMPUTE_BIT
writes to VkBuffer ..., which was previously written by another vkCmdDispatch command", binding
0 of rrp_sw_read_f.

Each round's 256 dispatches write o[0], a float4: 16 bytes each, CODE_STRIDE (256) bytes
apart, in one tracked buffer. The runtime binds the slot over the buffer and orders a tracked
buffer by the bytes the translation proves a shader writes (runtime README, "Hazards"). The
layer takes the whole descriptor as written. Writes that share no byte make no data race
(Vulkan's Memory Model appendix), so no order of them changes a byte, and the claim the test
stated (layer_reported_nothing_at_all) was wider than what the runtime promises.

Each round now notes its 256 writes (NotedWrites, one per round: the rounds write the same
bytes again, after the previous round's wait) and states
layer_reported_nothing_but_apart_writes, which lets a write after write between noted writes
pass only where no two of them share a byte.

Before: m3-max-32985 (msi, lavapipe, sync, at 3945a91289) failed the test with the reports
above. The proof run of this tip is in its landing report.
2026-11-15 10:22:18 -08:00
Anees Iqbal b815e51395 Hazard parser: read a transfer command's access as the layer words it at recording
Under METAL2VULKAN_LANE_VALIDATION=sync on lavapipe,
runtime_lane::memoryless_uses::memoryless_compute_and_blit_uses_fail_as_metal_s failed in
its "unused" case on one write after write the layer reported as the fill was recorded:

  vkCmdFillBuffer(): WRITE_AFTER_WRITE hazard detected. vkCmdFillBuffer writes to dstBuffer
  VkBuffer 0x700000000070, which was previously written by vkCmdDispatch.

The fill writes mark 3 (bytes 12..16) and store_const the mark at 8 (bytes 8..12). The test
notes both, so the report is of the apart form its claim already lets pass (8 of the run's 9
reports passed so). The lane's hazard parser (parity::sequences::hazards::parse) wanted
"VkBuffer " right after "writes to " and returned None for the parameter name ("dstBuffer")
that the layer puts before the memory in a transfer command's record-time wording. The runtime
now records the blit encoder after the compute encoder in one VkCommandBuffer, so the layer
reports the pair as recorded and no longer in the submission form the parser read.

parse() now skips one word between the verb and "VkBuffer "/"VkImage ". parity::sequences'
lane reads the layer's hazards through the same parser, so it gains the record-time transfer
wording too.

Tests: the_lane_reads_the_layers_hazards parses the exact record-time fill wording above and
a read of a "srcImage VkImage"; apart_writes' a_fill_and_a_dispatch_apart_pass_either_way_round
judges the record-time fill wording apart. Both fail without the parser change.

Before: m3-max-32985 (msi, lavapipe, sync, at 3945a91289) failed the test with the message
above. The proof run of this tip is in its landing report.
2026-11-15 10:22:18 -08:00
Anees Iqbal f452591afc Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 10:15:32 -08:00
Anees Iqbal ab139e4b6e RUNTIME 2366: Runtime FALLBACK repro bundle at a creation refusal (default-off diagnostic)
What: metal2vulkan-runtime writes the FALLBACK repro bundle the command line
writes for its own failures when it refuses a library or pipeline creation,
where METAL2VULKAN_REPRO_DIR names a directory (unset, nothing is written).

- The CLI's bundle writer moves into the library as the hidden crate-root
  module metal2vulkan::repro (feature serde), shared by the binary and the
  runtime. A bundle's directory is named by its content
  (metal2vulkan-repro-<16 hex>), written under a temporary name and renamed,
  so an identical failure is written once, across threads, processes and
  runs. The CLI's own bundles keep their files (input, profile.json, the
  descriptor files, repro.sh, repro-command.txt, failure.txt); only the
  directory's name changed, so a bundle written before still replays.
- The CLI takes --device FILE in place of --profile: the JSON of a
  DeviceDescription and DevicePolicy (ReproDevice), which builds the
  runtime's own compile device.
- The runtime hooks each creation where its refusal returns: a library of a
  metallib, a function's lookup, every compute and tile state
  (ComputePipelineState/TileState::create_adding: creations, added binary
  functions, archive adds) and every render state
  (GraphicsState::create_reflecting). It bundles Unsupported, NotImplemented
  and Compile refusals but a cancelled compile and a name the library lacks
  (Metal's own nil); never Invalid/Nil/MetalError. The bundle holds the
  library's bytes, device.json, the request as the CLI's options and
  descriptor files, and failure.txt with the call, the refusal and what the
  command does not replay. That list comes from a full destructuring of the
  compute, tile and render descriptors (and the stage functions): a new
  descriptor field fails to compile in repro.rs until it is replayed or
  listed.
- Bounded: at most 32 bundles and 256 MiB per process; past either nothing
  more is written and one line says so. Written on the refusing thread; the
  call returns the same refusal; a write failure is said once. Each bundle
  is named in one line through the device's message sink (id name
  metal2vulkan-repro). The runtime's metal2vulkan dependency gains serde.
- Not bundled: mesh states (no CLI mesh path), a dispatch's or draw's later
  variant, driver VkPipeline makings, Metal-source libraries.

Docs: env_vars registry, README CLI, docs/HOWTO.md section 4, the runtime
README's Errors section, the CLI help.

Tests: runtime CPU tests of the bounds (a tally with the seam's limits);
a lavapipe/GPU device test (ob3_stage_input with no stage-input descriptor:
one bundle with the expected parts and command, device.json rebuilding the
runtime's compile device by profile fingerprint and answering the same
refusal, none for a second identical refusal or a missing name, none
without a directory); CLI tests replaying library-written runtime bundles
(compute, and render with a vertex descriptor) through repro.sh to the same
FALLBACK, and --device compiling what --profile does.

Verified at ae56b195e9 (msi, m3-max-32986): metal2vulkan cli,
api_surface and api_signatures 25 passed; runtime repro tests 9 passed;
clippy -p metal2vulkan -p metal2vulkan-runtime all targets, all features
0. Lavapipe (m3-max-32978): repro_device writes one bundle that the
CLI replays to the same refusal; a second identical refusal writes
nothing.
2026-11-15 10:14:52 -08:00
Anees Iqbal 2cdfa840b5 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 10:13:55 -08:00
Anees Iqbal 1d2dbcbfc5 RUNTIME 2365: Compute: an encoder's dispatch takes the device's sampler states only where it needs them
Every compute encoder dispatch that settled (no memo entry held) listed
every live sampler state of the device (argument_samplers_at: a lock,
an Arc clone of each, and their drop), though its kept bind state
already listed them at the count of their slots' changes that held, and
a variant with no set-1 arrays binds none of them. In the consumer's
profile of its GL fix-index encoder that listing was 4.7% of
dispatch_threads, beside the states' drop.

A compute encoder's dispatch now takes them as a draw does
(sampler::ArgumentSamplers): only where the kept listing is not of
every live state at the count that holds (then compared state by state,
as before), where the variant has set-1 arrays (fitted and written to
the heap, as before), where a notice names a state of pixel coordinates,
or where a parked memo entry of such a variant goes on in the next
encoder (restamp). SettledDispatch::argument_samplers is None where
none were taken; a heap dispatch without them is an internal error,
not a silent empty listing. The memo's count of slot changes is the
taken states' where it took them, else the one the kept listing holds
at.

WorkCounts::argument_samplers_taken now counts compute dispatches'
takes too (its doc says so); no new field, no new Degradation kind.

Verified: not yet built; the next job builds and tests it.

Verified (msi, lavapipe, m3-max-32979 at 421c3c4d65): clippy plain 0;
compute, dispatch, grid, region widths, partial threadgroups, flat
simdgroups, sampler, argument and heap trimmed tests 163/163, including
compute_sampler_listing (argument_samplers_taken moves only after a state
is made or goes; every dispatch's words are Metal's).
2026-11-15 10:13:12 -08:00
Anees Iqbal 3945a91289 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 10:07:22 -08:00
Anees Iqbal 0ffe55a639 RUNTIME 2364: Encoders: a command's runs of one resource's bytes past what the order keeps are ordered as one use, exactly as their uses
A host RAM copy names each chunk it touches by up to 16 ranges (MOST_RANGES), 2049 uses for
a layer over 128 chunks, and the encoder's order paid for each: note 45 us, touch_reaching
27 us and wait_first 11 us of a 200 us call on msi, and the next command took the copy in
for another 150 us (inside_uses, merge's sort and finds, admit's finds). Probes m3-max-32845
and m3-max-32862, branch steelbrain/dl2-probe3 (not landed).

EncoderCore::track now orders a command by EncoderUses::order_joined. A run of more than
ENTRIES_PER_KEY consecutive tracked uses of one key's bytes, each past the one before, of a
key the command names nowhere else and the part holds no entry of (in its order, after the
part's first command is taken in, nor in its tracked uses), is compared, waited and taken
in as one use, its hull with the reads and writes of all: admit collapses the run's entries
into exactly that entry, and the comparison meets no entry of the key either way. The part
notes it as note leaves it from no entries: the hull of its first 9 + 8m uses, then each
after. So every barrier, the order and the encoder's summary are the same as order makes of
the uses; anything else goes through order unchanged. note_dirty, shadows.wrote, skips, the
twin check, owed.pay and the fold's order keep the command's own uses; inside_uses, admit and
note are unchanged. touch_reaching skips a use whose key and naming the use before it had
(its insert and name are idempotent; its per-position cache is kept for every use).

Tests: tracker, runs_of_one_key_joined_order_exactly_as_their_uses (600 generated encoders,
ordered and not, keys holding none to more than 8 entries before runs, runs off by an empty
range, a range not past the one before, an untracked use, a key named twice; per-command
barriers, summaries and the cross-queue plan of a following encoder equal; more than 300
commands joined); device, copies_over_a_long_scatter_s_pages_and_gaps_in_its_encoder_keep_
their_order and a_long_scatter_reports_each_run_to_the_ram_s_log_and_no_page_between_them.

Verified: m3-max-32906 (msi) clippy plain, m2v_gpu, m2v_cpu_icd 0,
rustdoc 0; m3-max-32926 the whole runtime crate on lavapipe 2806/2806;
runs_of_one_key_joined_order_exactly_as_their_uses: 600 generated
encoders, order and order_joined equal on every barrier, summary and the
next encoder's plan; sync_coverage 7/7 (m3-max-32907). Release medians
(m3-max-32909, msi loaded, interleaved), 128 chunks: the fill after the
copy 194.8/194.1 -> 27.9/26.5 us, the copy after a fill 459.0/442.1 ->
275.9/259.8 us.
2026-11-15 10:06:41 -08:00
Anees Iqbal 291635393a Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 10:05:37 -08:00
Anees Iqbal ac0229e5d7 RUNTIME 2363: Compute: a direct dispatch takes what another grid of its class planned
A compute pipeline state kept what its latest direct dispatches planned
(Planned: the variant, its plan and its regions' made VkPipelines) keyed
by the exact dispatch, so a guest's fix-up stream of dispatchThreads:
calls of a thread per element, one width after another, planned every
dispatch again: settle_direct, settle_flat and Variant::plan's LRU hash
and compare of the bind shape two or three times, a new Planned whose
regions' pipelines were looked up again, and plans of other shapes
pushed out of the four kept, so the shape was made again too. In the
consumer's profile of its GL fix-index encoder on an RX 7900 XTX that
was plan_now 17.8% of dispatch_threads, region lookups about 6%, and
BindState::shape 5.3% beside position_of_shape 2.3%.

A grid's class (pipeline::GridClass) is its dispatch form, its
threadgroup size, and whether it is a whole number of threadgroups and
one row in threadgroups of one row: what settle_direct chooses its
branch by (flat_direct and partial_direct now read those from the
class). Where every region a plan plans has the call's threadgroup size
(a flat variant's one region, a partial-threadgroups variant's
threadgroups, a whole grid's chunks), every variant key the branch makes
is a function of the plan and that local size, and the grid's size
reaches it only through the device's limits. So a Planned of the bound
form on a flat or partial-threadgroups variant, or of a whole grid,
serves the other grids of its class, after its plan names its very
variant for the new grid (BindingPlan::dispatch_variant, which checks
the grid against those limits each time); otherwise the dispatch plans
as any and meets the same refusal. A ragged grid's exact split keeps
the exact key. The call's own grid is what record instantiates; the
dispatch memo and the kept commands (Instantiated) keep their dispatch,
since their commands are the grid's.

New count: WorkCounts::dispatches_planned_across_grids, those of
dispatches_planned_as_before of another grid of the class.

Verified: not yet built; the next job builds and tests it.

Verified (msi, lavapipe, m3-max-32955 at ccfcc384b3): clippy plain 0;
api_signatures and api_surface 15/15; compute, dispatch, grid, region
widths, partial threadgroups and flat simdgroups 90/90; grid_classes reads
every dispatch back against Metal's answer and counts 20 cross-grid plans
a kernel; an over-limit grid of a planned class is refused as before.
Negative controls: reuse with the check skipped fails both tests.
2026-11-15 10:04:56 -08:00
Anees Iqbal 59932b32ba dma_buf_imports: is_multiple_of in the shared source's alignment check
Clippy (--cfg m2v_gpu and --cfg m2v_cpu_icd, -D warnings) refused the manual
modulo in Memfd::shared_source (clippy::manual_is_multiple_of), red in
m3-max-32936 for development b1c6b40570. Same check, its method form.

Verified: cargo fmt; clippy of metal2vulkan-validation in all three
configurations in the msi job that follows.
2026-11-15 09:59:10 -08:00
Anees Iqbal b1c6b40570 submit_per_import: held buffers as pieces of one shared dma-buf file
A third held-for-good kind: the n buffers' source answers each request with
a piece of one udmabuf of their whole memfd (DmaBufRequest::shared_files, as
a consumer's group of views is), so the device imports the file once and
binds each buffer at its piece (Memfd::shared_source). Against the own
dma-buf rows it shows whether a shared file costs RADV's submissions one
listed entry, whatever its pieces; the lines now print the pieces joined and
the shared files live, the evidence the join path ran.

Verified: cargo fmt; run on gem10's PHOENIX in the probe job that follows.
2026-11-15 09:49:50 -08:00
Anees Iqbal 1db2624115 submit_per_import: a phase of imports held for good
The dma-buf phases held at most 64 imports live (136 for 1000): their
buffers are read by blits alone, so the residency released those past the
most it keeps on a device whose held imports cost every submission. A
guest's imports are bound and stay (the HawkPoint Launchpad walk held 363
buffer dma-bufs and 163 image ones). Each kind now runs again with every
buffer's Metal address read (Buffer::gpu_address), which keeps each import
held for good, so a phase holds all n live and its line gives the per-entry
cost at the walk's counts.

Verified: cargo fmt; run on gem10's PHOENIX in the probe job that follows.
2026-11-15 09:36:16 -08:00
Anees Iqbal 5aad56bc82 submit_per_import: print each VkSubmitInfo's time in vkQueueSubmit
The SUBMIT-PER-IMPORT lines now carry the VkSubmitInfos a phase submitted and
WorkCounts::batch_submit_nanos over them: the driver's time per submission
beside the kernelStart-to-kernelEnd percentiles, so a phase's per-import cost
reads in the same unit as a walk's WorkCounts (perdraw8: the HawkPoint walk's
scheduler spent 390 us per VkSubmitInfo in RADV's vkQueueSubmit).

Verified: cargo fmt; built and run in the gem10 PHOENIX probe job.
2026-11-15 09:29:26 -08:00
Anees Iqbal e4daf97233 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 09:20:33 -08:00
Anees Iqbal 0b6f72ac29 RUNTIME 2362: Scheduler: a copy queue's command buffer keeps commit order behind a held batch
What: a head on a queue made for copies (Device::new_command_queue_for_copies) no longer
goes before an earlier-committed batch of another queue it conflicts with because that
batch gives way. The order's comparator (scheduler/mod.rs is_behind) treats a held batch
that gives way as one that keeps its place when the head's queue keeps commit order
(Standing::commit_order, from CommandBufferShared::keeps_commit_order: the queue's kind,
set by the copy queue's constructor). Such a head waits behind it in the scheduler when
tracker::ordered says the two conflict, whether the held batch waits for its pipelines'
making, a host step or its checks. Once the held batch is submitted, the tracker orders the
copy after it on the GPU: the copy engine's VkQueue waits for the other VkQueue's timeline,
or a barrier where they share one. There is no wait on the host. A copy that shares nothing
with the held batch still goes. Unchanged:
- plain queues keep the give-way exactly as before (order.rs, Held batches give way), so the
  Iris Xe compositor case is untouched;
- a held batch ON a copy queue stands to a later plain queue's commit as any held batch does
  (the rule is the head's);
- a batch held for an event value or a binary semaphore's signal the program has not given
  holds back no copy (Stops).

Why: the copy queue's documented promise is that a copy reading what another queue's
command buffer committed before it wrote waits for that command buffer on the GPU. A
command buffer of a blit and a new pipeline's first dispatch, held for the pipeline's
making, gave way to a copy committed right after it on the copy queue. The copy ran first
and read the bytes from before the blit: the consumer's copy queue on an RTX 2080, and a
plain second queue on MoltenVK, round 0 only, always the new pipeline's first dispatch. The
give-way rule (b46459080d) stays for plain queues, where real Macs disagree; the copy queue
is a runtime extension whose contract is ours.

Docs: order.rs (But not to a queue made for copies, No deadlock), the scheduler's Tracking
paragraph and is_behind, new_command_queue_for_copies (what holds exactly, the reverse
direction, and that on a device that answers None a plain queue used instead gives way, so a
caller orders such a copy with an event), the runtime README's copy-queue and pipeline-wait
passages, docs/API.md's pipeline-wait passage, pending_dispatch.rs,
WorkCounts::heads_held_for_earlier_commits, and the hold_sites module docs.

Verified: lavapipe before (the previous commit's copy-queue leg) and after, reported with
the tip.

Verified (lavapipe, the copy queue on the round robin VkQueue): at
87ab2111b0 (m3-max-32839) the copy-queue leg fails, reading the bytes
from before the blit; at 404352e262 (m3-max-32840) hold_sites,
dispatch_pending, pipeline_wait_order, held_step_order and copy_queue
16/16, clippy m2v_cpu_icd 0.
2026-11-15 09:19:49 -08:00
Anees Iqbal 177ff2240b Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 09:16:59 -08:00
Anees Iqbal f10e9d8c90 RUNTIME 2361: Host RAM copies: a repeated copy's call finds its kept plan as it merges the runs given, and makes no vector of them
On a repeated copy by a kept plan, a third of the encode was the call's own work on its
runs before the plan was even looked up: runs.to_vec, merged into a second vector, boxed,
in_words, then compared with the plan's at the recording (probe m3-max-32752, msi: 66.8 of
97.1 us at 1 chunk, 51.2 of 233.0 at 128 chunks).

The four calls (copy_from_host_ram, copy_to_host_ram, copy_runs_from_host_ram,
copy_runs_to_host_ram) now give HostRamCall::new their runs as given (Given: laid one after
another from an offset, or each at its own byte). It looks for a plan of the same direction,
form and buffer key (RamCopies::kept_for) and compares the given runs with the plan's while
it merges them (merges_to): each run checked as merged checks it, joined as merged joins
it, each joined run compared with the plan's next, a run laid past u64 refused as
one_after_another refuses it. Merged runs, checked and in_words are functions of the given
runs alone, and a plan exists only for checked runs copied by words, so a match is exact.
On a match the call shares the plan's runs (HostRamCall.runs and KeptPlan.runs are now
Arc<[Run]>) and names the plan (HostRamCall::kept); else it builds its runs as before, and
a plan kept of it shares them instead of cloning them.

The recording takes a named plan only while the RAM keeps that very plan
(RamCopies::keeps, by Arc identity): one the LRU bound or anything else let go of before
the copy records (an encoding again at a rebind, say) takes the copy to the full path
over the call's shared runs. A call that named none looks one up as before. Every dynamic
check of record_kept is unchanged.

Second, takes() no longer joins every chunk's ranges for copy_take: copy_take's signature
is unchanged in its types (device, importer, slot, ranges: &[Range<u64>]) but ranges are
now the chunk's ranges as touched_ranges gives them, and copy_take joins them
(copy::alone_ranges) itself, only past its made() check, where it reads them. Same
answers: the joined ranges were read only on that branch. (probe: 9.2 us a call at 1
chunk, whose ~4100 ranges were joined though the chunk was made; 40.3 at 128.)
chunk(), take(), took() and after_take are untouched.

Tests: unit, runs_merged_as_they_are_compared_match_the_kept_runs_exactly_as_merged_gives_them
(random runs of both forms with joins, empty and off-word runs, runs laid past u64,
against their merge, one run more, the last fewer, the merge of the runs less their last,
each run changed); device, the repeated-copy test gains runs at their own bytes, and
a_named_plan_the_ram_let_go_of_before_the_recording_is_not_taken (eight copies' plans
push the named one out, a rebind encodes the encoder again: no reuse, the bytes right).

Verified at 96e281ba59 (msi, m3-max-32802): host_ram tests on lavapipe
106/106, clippy plain, m2v_gpu and m2v_cpu_icd 0, rustdoc 0; the named
plan let go of before recording is not taken (negative control fails).
Release medians (m3-max-32803, lavapipe, interleaved, 200 of 200 copies
by a kept plan): layer in 1 chunk 99.1/94.0 -> 59.7/58.1 us, over 128
chunks 248.9/282.6 -> 176.9/197.0 us.
2026-11-15 09:16:17 -08:00
Anees Iqbal 9dd5e78f60 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 09:11:16 -08:00
Anees Iqbal 5ba7afd9d4 RUNTIME 2360: Shader cache: no default directory makes a memory-only device, never a failed one
With no caller directory and no home (USERPROFILE on Windows, HOME elsewhere),
default_directory answered Err and CacheSetup::of turned it, and any failure to
open the default path, into Error::ShaderCache, so every device creation and
adoption failed. Metal never fails device creation over its shader cache, and
the default is the runtime's choice, not the caller's (owner rule 2).

- The Windows default is %LOCALAPPDATA%\metal2vulkan (the local application
  data folder, read from the environment; no new dependency). XDG_CACHE_HOME and
  USERPROFILE are no longer read there.
- default_directory takes its environment as a closure (CacheSetup::of_in), so
  a test feeds its own without touching the process's.
- Where the caller names no directory and the default does not exist or cannot
  be made or written, the device keeps its cache in memory alone: the Store has
  no directory, every lookup is absent, every write is refused with no
  filesystem call, the scans do nothing, and writers ask has_directory first so
  nothing is encoded for it (a translated function still is: its encoded length
  weighs it in the memo). The device says so once as it is made, as the existing
  degrade notice ShaderCacheEntryNotWritten naming why; each entry it does not
  write counts in write_failures. The driver's pipeline cache data is not read
  back, and the device checks' verdicts are not encoded.
- A directory the caller names that cannot be used is still Error::ShaderCache.
- Device::shader_cache_directory answers Option<&Path>: None for such a device.

Docs: the shader_cache module docs, ShaderCacheOptions::directory,
write_failures, Error::ShaderCache, the degradation's declaration and its
docs/API.md entry, the runtime README (Windows default, error table), HOWTO,
create.rs's list of environment variables. api_signatures re-blessed;
docs/REFUSALS.md regenerated (a refusal's site function renamed).

Tests: tests::shader_cache's default-directory and no-directory-store unit
tests (plain gate), and the lavapipe/GPU device test
shader_cache_no_directory: a device made with an empty environment and no
caller directory is made, has no directory, makes four render states with two
functions translated once, writes nothing, and its notice is heard once.

Verified (msi): m3-max-32796 clippy plain 0, 67/67 shader_cache and
degradation tests, api_signatures 0, clippy x86_64-pc-windows-gnullvm 0;
m3-max-32797 (lavapipe) clippy m2v_cpu_icd 0, 61/61 shader_cache and
in_place_check, including the no-directory device test.
2026-11-15 09:10:25 -08:00
Anees Iqbal 9ce951f521 store_out_device: the stencil store test keeps three queues live, so it takes the queue plan
Its three faulting passes each take a queue of their own, and the earlier
queues stay live to the test's end, past the runtime tests' default limit
of two (lavapipe, job m3-max-32737: the device's panic names the limit).
plan_device, as the resolve tests use.
2026-11-15 08:57:17 -08:00
Anees Iqbal d3702a9758 Device tests: a Stencil8 attachment stores, resolves and faults as Metal's
A Stencil8 texture on a device without S8_UINT is held in a combined
depth/stencil image; these tests run the shapes the consumer's tests died
at on Intel's UHD 630 under Windows, and a plain draw into such a target.

- store_out_device: a Stencil8 texture at the start of a placement no-copy
  heap of bit 24 stored at Store (descriptor's and encoder's) faults its
  command buffer; at DontCare and a late CustomSampleDepthStore it
  completes. A 4-sample Stencil8 attachment resolving into it at
  MultisampleResolve (descriptor's and encoder's) and
  StoreAndMultisampleResolve faults; attached unresolved it completes. The
  pages keep their bytes. Each prints the format its image is held in.
- stencil_target: a Stencil8 target cleared to 0x5a, drawn into over its
  left half with a Replace of reference 0xa5, and stored reads 0xa5 and
  0x5a by halves through a copy; a later pass that loads and stores it
  keeps every byte, so the hidden depth aspect's DONT_CARE disturbs no
  stencil byte. Prints the image's format.

Verified: compiled and run in the jobs named in the lane's report (the
UHD 630 under Windows and lavapipe).
2026-11-15 08:57:17 -08:00
Anees Iqbal c119a60d91 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 08:47:00 -08:00
Anees Iqbal 4781b54e6e RUNTIME 2359: image_plan: a depth-only or stencil-only texture held combined is an attachment of its image
A Stencil8 texture on a device without S8_UINT (Intel's UHD 630 under its
Windows driver 101.2145, and the roadmap-2022, vk12-floor and
lunarg-desktop-baseline-2023 profiles) is held in D32_SFLOAT_S8_UINT or
D24_UNORM_S8_UINT (FormatEmulation::StencilInCombined), which the format
table admits for DepthStencilAttachment and documents as exact. plan_held
kept the attachment mapping only where its format was the direct one
(S8_UINT), so the image took no DEPTH_STENCIL_ATTACHMENT usage, RenderTarget
went unavailable, and the render pass refused the texture as needing
D32_SFLOAT_S8_UINT as a depth/stencil attachment, which the device has.
The consumer's store and resolve of a Stencil8 attachment died there.

The attachment filter now also admits the combined-aspect emulations
(DepthInCombined, StencilInCombined); the RenderTarget branch compares the
image's format with the attachment mapping's rather than the direct
format, and a memoryless plan takes the mapping's format. Colour formats
and direct depth/stencil formats plan as before (their attachment format
is the direct one). render_target.rs already renders such an attachment:
the hidden depth aspect is DONT_CARE both ways.

Test: tests/image_plan.rs
a_depth_or_stencil_format_held_combined_is_an_attachment_of_its_combined_image
feeds the planner the UHD 630's formats (no S8_UINT, no D16_UNORM_S8_UINT;
the combined formats render, sample and copy optimally, with no BLIT_DST
and no linear features) over the uhd770 profile: Stencil8 and Depth32Float
without D32_SFLOAT, 1 and 4 samples and memoryless, are D32_SFLOAT_S8_UINT
depth/stencil attachments with nothing unavailable.

Verified (m3-max-32701, msi): clippy plain 0; the runtime unit suite
1593 passed; with image_plan.rs restored to its parent, the new test
fails (Stencil8 planned D32_SFLOAT_S8_UINT with TRANSFER_SRC|TRANSFER_DST
only, RenderTarget unavailable).
2026-11-15 08:46:20 -08:00
Anees Iqbal 771dd124e8 tests: the replay modules' extended products are all 32-bit
the_replay_modules_test_overflow_by_a_products_high_word counted every
OpUMulExtended (8 in the flat dispatch, 11 in the preprocess). Since
the builder makes each 64-bit extended product from four 32-bit ones,
the five u64 products count four each: 23 and 26, every one 32-bit.
The test now counts them by width and wants no 64-bit form, so a
64-bit OpUMulExtended coming back into either module fails it.

Found red by the msi run of the metal2vulkan suite at 71ec267314
(job m3-max-32642: 3617 passed, this one failed with 26 where it
wanted 11 on the preprocess). Verified by the follow-up job named in
the report.
2026-11-15 08:44:50 -08:00
Anees Iqbal 29d0f9263e fresh_pages: a cleared long buffer's cleared bytes are its 16 KiB allocation
Step 2 (a1175662e7) gives a runtime buffer of 16 KiB or more Metal's allocation,
its length rounded up to 16 KiB, and the host clears all of it so that a texture
over the buffer reads zero past the length. Two fresh_pages expectations still
counted the length rounded to 16: the recycled buffer in
a_long_buffer_made_right_after_a_filled_one_reads_zero (red on lavapipe, partition
2: 33570816 cleared, 33558544 expected) and the cleared class in
a_long_new_buffer_reads_zero_with_nothing_written (the RADV leg, where no class
takes fresh pages). Both now expect the length rounded up to METAL_PAGE.

Test-only: the runtime-sources pin skips tests, so it is unchanged.
2026-11-15 08:42:56 -08:00
Anees Iqbal 1ba1330549 SPIR-V builder: a 64-bit extended product from four 32-bit ones
Every 64-bit OpUMulExtended and OpSMulExtended the builder would emit
is now built from four 32-bit OpUMulExtended of the operands' halves,
summed in 64-bit adds and shifts; signed, the high word subtracts
each operand where the other is negative. The struct result is the
same, so every caller (mul_hi, the flat indirect-dispatch derivation's
checked multiply, the replay preprocess) keeps its shape.

Why: Intel's Windows driver 101.2145 on the UHD Graphics 630 answers
garbage high words for both 64-bit forms, different from run to run,
while its 32-bit forms and its 64-bit UDiv and UMod are exact
(measured by the runtime's host_step_reads device test in job
m3-max-32600). The flat indirect-dispatch derivation's overflow check
read those garbage high words as overflow, zeroed the command and
reported ReplayFaults::GROUP_COUNT, so indirect dispatches and ICB
executions ran nothing on that device. The leaf is unconditional:
both forms are exact everywhere, and a per-driver key would leave
any missed construction site broken.

SEMANTICS_VERSION 2123 -> 2124: modules with a 64-bit mul_hi or a
flat dispatch derivation change their words.

Verified: the CPU interpreter test
sixty_four_bit_extended_products_are_exact_from_halves (both signs,
scalar and two-lane vectors, 121 operand pairs including 0, 1, -1,
i64::MIN, i64::MAX and u64::MAX, against i128/u128 products, and only
four 32-bit MulExtended in the module) is dispatched with this
commit; the device run on the mini follows.
2026-11-15 08:31:57 -08:00
Anees Iqbal 509a9c4c4e tests: a kernel's 64-bit multiply (low word) beside its mul_hi forms
The wide-math device test also stores `mul i64 x, y` for large
operands, to show whether the 64-bit OpIMul is exact on the device
whose 64-bit OpUMulExtended and OpSMulExtended high words are wrong.
Not yet run; the next mini run measures it.
2026-11-15 08:31:57 -08:00
Anees Iqbal 3500934fa6 tests: signed 64-bit and 32-bit mul_hi beside the unsigned 64-bit one
On the UHD 630 (m3-max-32592) the unsigned 64-bit mul_hi answers garbage high
words while 64-bit division and remainder are exact, and the flat dispatch
reports ReplayFaults::GROUP_COUNT. The fix's encoding depends on which widths
and signs the driver multiplies right; this measures them.

Verified: m3-max-32592 (UHD 630).
2026-11-15 08:31:57 -08:00
Anees Iqbal 9185644506 tests: a kernel's 64-bit mul_hi, division and remainder; the flat path's execution report
The device-pointer run passed on the UHD 630 (m3-max-32574): the translated
kernel's own loads and stores by device address work there. The flat path's
derivation (bind::replay flat_dispatch) computes in 64 bits through
OpUMulExtended, OpUDiv and OpUMod; this checks those in a translated kernel
and prints the flat dispatch's execution report (a GROUP_COUNT replay fault
would say the derivation found the grid too large).

Verified: not yet run.
2026-11-15 08:31:57 -08:00
Anees Iqbal d2a9880b4e tests: a translated kernel's load and store through a device pointer
On the UHD 630 (Windows, 101.2145) the indirect dispatch on the flat path, from
Shared, Private and unimported memory alike, and the GPU replay of copied
commands run nothing, while the host step with no device addresses
(shaderInt64 withheld) runs. This separates the translated kernel's own reads
and writes by device address (direct dispatches) from the indirect machinery.

Verified: m3-max-32562 (UHD 630) ran the earlier five: 4 failed, the host step passed.
2026-11-15 08:31:57 -08:00
Anees Iqbal 8e8af60ade tests: host_step_reads reports the WorkCounts fields it has
Verified: the Windows build of 91b38cc731 named own_pages as no WorkCounts field.
2026-11-15 08:31:57 -08:00
Anees Iqbal 4853b4ba5c tests: the GPU's reads of indirect arguments on each path, with and without pointer imports
The consumer's correction: their failing indirect dispatch takes the GPU (flat)
path, not the host step. The test now runs the dispatch from a Shared buffer the
CPU wrote on the default device and on one that imports no host pointer
(VK_EXT_external_memory_host withheld), from a Private buffer a blit filled, and
through the host step; each prints its page-buffer and import counts.

Verified: not yet run.
2026-11-15 08:31:57 -08:00
Anees Iqbal 6189c27fe9 tests: a host step's indirect dispatch and copied-command execution write their outputs
A device test of what a host step reads: an indirect dispatch on a device
without device addresses (shaderInt64 withheld) runs the arguments the CPU
wrote and those a blit copied before it; the same dispatch on the device as
made; and an execution of a dispatch a blit copied into the executed buffer.
Each prints the notices and the host steps recorded. Reproduces the consumer's
Windows report (UHD 630: host-step dispatches and executions run nothing).

Verified: not yet run (first build on the Windows mini).
2026-11-15 08:31:57 -08:00
Anees Iqbal fd921926d9 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 08:31:29 -08:00
Anees Iqbal 8ba1fd7d67 RUNTIME 2358: Host RAM copies: a repeated copy takes the plan kept of it, where its buffer, the device's figures and its imports are the plan's
A copy by dispatches spent most of its encode on work that depends only on its runs, its
buffer and the imports it reads through: cutting the runs into pieces, the chunks' ranges,
the pieces' places in the imports, the table and the dispatches. A consumer repeats the same
copy (a surface's same runs) every frame.

Such a copy's plan is now kept per RAM per device (RamCopies, which ChunkKeys becomes):
direction, runs' form, buffer key (object id, device generation, length), the runs, the
blit_at VkBuffer and byte, the device's figures (window, alignment, workgroups, array), the
span and total, the chunk ranges and joined ranges, the import serials in order with the
chunk-to-imports map, the table and the dispatches. The next copy with the same key (runs
compared element by element, no hash trusted) takes the table and dispatches where:
- blit_at gives the same VkBuffer and byte (a rebind or a new VkBuffer plans anew);
- the device's figures are the same;
- every chunk takes at once (copy_take Now for all; else the full path stages it);
- copy_imports gives the same imports, by serial number, in the same order, with the same
  map. RamChunk now carries a serial from a process-wide counter, never reused, so a chunk
  released, given back or imported again has a new one. Plans keep numbers, not Arcs.
Every step a copy takes each time still runs: blit_at, copy_wrote, the takes, copy_imports,
the upload, the binds, the uses and the counts. Where the plan does not hold, what it took
(blit, takes, imports) goes to the full path, which takes none twice: a chunk released
between the takes and the imports plans over the imports it got.

Bounds: 8 plans and 4 MiB per RAM per device, the one taken longest ago dropped first; a
plan over 4 MiB is not kept. Counter: WorkCounts::host_ram_copy_plans_reused.

stages() is split into takes() and Takes::staging() so both paths share the takes;
record_dispatches() is the dispatch tail both paths record through.

Tests: unit, the bounds; device (lavapipe): a repeated copy takes its plan and a run
changed, the other direction, another buffer offset, another buffer, a rebound no-copy
buffer each plan anew; a chunk let go of (idle, given back) makes the next copy plan anew
and the one after take the new plan; a new use of the RAM plans anew; a kept plan's copy
is ordered after a fill of its buffer and after a scatter into its pages in the same
command buffer.

The plan also holds the buffer's host pages weakly and compares them by
identity: lavapipe gave a rebound buffer's new VkBuffer the destroyed
one's handle value (m3-max-32579), so a handle match alone cannot see a
rebind. The plan names no VkBuffer; the binds take the live one on every
call. The pages copy's kernel is looked up only where a copy goes by
dispatches, as before. The layer bench says how many copies a kept plan
recorded.

Measured (release, msi lavapipe, m3-max-32581, before d0ef5e0145 and
after, one job, median us a call over 8100 single-page runs): layer in 1
chunk 373.9 -> 139.1, over 128 chunks 859.8 -> 323.4; at 0bae61504a
(m3-max-32615) 200 of 200 copies by a kept plan.

Verified at 0bae61504a (m3-max-32610): host_ram tests on lavapipe
103/103, clippy plain, m2v_gpu and m2v_cpu_icd 0, rustdoc 0. Negative
control (m3-max-32579): with the serial compare removed, the let-go test
fails (a reuse happened).
2026-11-15 08:30:44 -08:00
Anees Iqbal 18cc0cd056 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 08:29:48 -08:00
Anees Iqbal 135df83657 RUNTIME 2357: Textures over buffers: an image over a buffer's texels may take its whole placement; an unobserved buffer lies on the linear image alignment
Intel's driver for the UHD 630 on Windows (101.2145) rounds a small
linear image's VkMemoryRequirements size up to its 4096-byte alignment:
BGRA8 73x8 at a pitch of 320 has a 2560-byte subresource and a 4096-byte
image, 16x16 1024 -> 4096, RGBA16F 88x8 6144 -> 8192. The in-place check
(linear_plan::aliases) bounded the image's size by the buffer's VkBuffer
bytes from the texture's first, so a texture over a padding-unobserved
Private buffer of exactly its rows was a shadow, and a buffer placed on
256 bytes failed the image's 4096 start too.

The room an image over a buffer's texels may take is now the buffer's
own placement from its byte 0 (Buffer::memory_room: bytes no other
resource is placed in), in texture.rs's two aliasing checks and the
two-plane YCbCr check. A buffer whose maker declares its padding
unobserved is placed on the device's linear images' memory alignment
(Device::linear_image_alignment: one probe image's alignment, a 64x8
R8G8B8A8_UNORM linear image, kept for the device), its start and size
whole units of it; the recycler's BufferMaking keys on that alignment,
and a device recovery's carry places such a buffer so again. Where the
alignment is 256 or less (RADV, lavapipe, MoltenVK), every placement met
it already and nothing changes. Cost: at most alignment - 1 bytes more
for each such buffer on the UHD 630, plus the start's padding.

Still a shadow: an image the driver sizes past its alignment's rounding,
R8 4096x1 over 4096 bytes taking 16384 on the UHD 630 (FAST-PATHS known
gaps), and on that driver textures over buffers that do not declare
their padding unobserved where the image is larger than the placement or
starts off 4096.

Tests: padding_unobserved's a_texture_whose_rows_fill_an_unobserved_buffer_is_in_place
makes a 73x8 BGRA8Unorm texture at the device's own linear pitch over a
Private padding-unobserved buffer of its rows alone and asserts the
placement lies on the alignment, the texture is the image over the
buffer, and no shadow is counted.

Docs: BufferDescriptor::padding_unobserved, the runtime README entry,
FAST-PATHS known gaps.

Checks: on the UHD 630 (Windows, m3-max-32630, at the same diff before
its rebase), padding_unobserved's new test passed: 73x8 at a pitch of 320
over 2560 bytes, 4096 of room on 4096, an image over the buffer, 0
shadowed. At cb7660c625: clippy plain, m2v_gpu and rustdoc 0
(m3-max-32602); lavapipe touched set 153/153 and m2v_cpu_icd clippy 0
(m3-max-32603).
2026-11-15 08:28:49 -08:00
Anees Iqbal d0b5b196c9 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 08:26:57 -08:00
Anees Iqbal 2a64c23a05 RUNTIME 2356: host_ram: an object that waited for the thread's import of a chunk marks it taken after the thread
What: RamOnDevice::chunk cleared a chunk's `untaken` mark for an object's call
before it looked at the chunk's state. An object that found the device's thread
importing the chunk (Import::Making, By::Ahead) cleared it, then waited; the
thread, ending its import, set Made and then marked the chunk untaken under the
chunk's lock, after the object's clear. The object then took the chunk, which
stayed marked untaken. A give-back near the allocation limit skipped it while
the object's buffer held it, but freed it once that buffer went, setting `tried`,
so the thread never imported it ahead again and the next object over it
imported it itself.

How: the object clears the mark in the Import::Made arm, once it holds the
chunk, under the same lock the thread marks it under, so the clear comes after
the thread's mark whether the object found the chunk made or waited for it.

Test: at_the_margin takes when its first object takes the RAM's first chunk
(Opens::Made, as before, or Opens::InFlight: the thread's import held in flight
by making_pause, the object's call past taking_pause and still blocked on it).
a_chunk_an_object_waited_for_the_thread_s_import_of_is_not_given_back drops
that object, brings the device within the margin with an object past the
thread's chunks, and asserts AHEAD-1 chunks went back and 2 stay live (the first
chunk and the new object's); with the mark left set, AHEAD go back and 1 stays.
Verified on lavapipe: m3-max-32606 ran the 99 host_ram tests and clippy
(m2v_cpu_icd); m3-max-32614 ran clippy plain and with m2v_gpu. In the
same job, the host_ram.rs hunk reversed (negative control) fails the new
test: 4 chunks given back, 1 live.
2026-11-15 08:26:08 -08:00
Anees Iqbal f4c9902c63 FAST-PATHS: the cold Shared making's range on this tree is 95-97 ms
The previous commit gave 92-97 ms; m3-max-32595's two runs of this tree
made the cold round in 97.0 and 94.6 ms.
2026-11-15 08:15:57 -08:00
Anees Iqbal 9ee682344f FAST-PATHS: the 16 KiB allocation's measured cost
A 16385-byte buffer's VkBuffer requires 32768 bytes where 16400 did, on
RADV PHOENIX and lavapipe (m3-max-32595, m3-max-32558). On the Radeon
780M, release, exclusive, the base (d2ee5bca5b) and this tree run twice
each in one job (m3-max-32595): 1000 buffers of 16 KiB + 1 to 4 MiB
required 763.3 MB against 754.8 MB and took one more 64 MiB block in
their second round; making them took the same time within the runs'
spread, Shared ones cleared on the host and Private ones' first fills
alike.
2026-11-15 08:15:57 -08:00
Anees Iqbal ab779daf66 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 08:14:54 -08:00
Anees Iqbal a1175662e7 RUNTIME 2355: Textures over buffers: a buffer of 16 KiB or more holds Metal's allocation, a heap's buffer its heap
A texture over a buffer whose texels run past the length was always a
copy: a shadow image or a staged texture buffer whose bytes past the
length lay in a tail of its own. Metal's texels there are the
allocation's: a buffer of 16 KiB or more holds its length rounded up to
16 KiB (allocatedSize), zero when made, and a heap's buffer reaches its
heap's end, whose bytes are the heap's.

Now a buffer the device makes in the Metal address space with a length
of 16 KiB or more takes that allocation (buffer.rs's metal_allocation):
its VkBuffer and placement are its length rounded up to 16 KiB, which
its first fill clears with the rest (Buffer::clear_first: the host's
clear of a Shared or Managed buffer, the device's fill of a Private
one), with no command of its own. A texture keeps in place the bytes the
buffer's memory holds for it (Buffer::texel_reach: the allocation, a
heap's buffer's heap to its end, a no-copy buffer's length), so such a
texture is made as one inside the length is: an image over the buffer's
memory where the device makes one, a texture buffer viewed in place. The
shader-visible ranges, robustness, copy reach (a blit past the length is
still refused) and exported sizes stay at the length. Heap, no-copy,
wrapped and exportable buffers, and every buffer under 16 KiB, take
their length; past what the memory holds a texture keeps its tail, as
before. The runtime has no buffer allocatedSize; a heap's size and a heap
texture's allocated_size are unchanged.

The tails conformance cases now lie in place: their comments say so,
and the texture buffer case drops its staged-texture-buffer allowance,
which no device can fire there any more (its view starts at 16384).

Tests: buffer_tail_device's last-texel case lies as over a buffer that
holds it inside its length, with no tail; a new case over a 20000-byte
buffer (64x128 packed, ending at 32768) reads zero in the padding as
made, lies as inside the length, lands a kernel's writes past the length
in the buffer's memory, takes no copy where it is an image over the
buffer, and refuses a blit past the length; the heap case lies in the
heap, its kernel writes landing in the heap's other buffer; a new case
over a heap's second buffer keeps its texels past the heap's end in a
tail; the no-copy and 4096-byte cases keep their tails.

Docs: buffer_texture.rs's Tails, linear_plan.rs's Length, docs/API.md's
accepted difference and StagedTextureBuffer entry, and a FAST-PATHS
cost-of-matching-Metal entry for the padding.

Checks: the jobs that compiled and ran this commit are named in the
lane's report.

Evidence (lane jobs): m3-max-32551 (msi): clippy runtime+conformance -D warnings 0; 2632/2632 runtime+conformance; fast_paths +
api_surface 34/34. m3-max-32578 (lavapipe) at the tip: touched 56/56 (buffer_tail_device incl. the allocation, heap and
heap-end cases, texture_placement_device, linear_plan, buffer_texture, degradation_catalogue); runtime+validation partition
1/4 1572/1572. VkMemoryRequirements on lavapipe for a 16385-byte buffer: 32768 (alignment 64). The padding is cleared by the
buffer's existing first fill (no new command). allocatedSize: no buffer API; heap sizes unchanged. The PHOENIX run, the
release creation bench and lavapipe partitions 2-4 follow in the lane. Conformance: buffer-tails cases now in place; the M3
venue's cost records for buffer-tails-* re-bless on development.

Lane commits: d2ee5bca5b (bench), a8f3796f59, ee54952340 (heap cases in a placement heap).
2026-11-15 08:14:12 -08:00
Anees Iqbal b3113687a8 heap_textures: the untracked lane prints each heap's splits at aliases
The untracked lane (a kernel's write of an untracked heap's buffer, bound
or through the address its argument buffer holds with the buffer resident,
then a read of a texture over the same bytes in one encoder) asserted only
that the run as a whole split some command buffer at aliases where the
driver fact holds and a texture lay in place. On the RTX 3090 at
25119268da both forms split 1 command buffer over the Shared and the
Private heap, each texture in place, so the counts did not say which heap's
read split, nor that the resident write splits where the bound one does.

Each HEAPTEX untracked line now prints the command buffers split at aliases
while its heap ran (from before its texture was made to after its compute
command buffer completed). Test-only; nothing asserted changes.

Verified: cargo fmt. The lavapipe build and run follow.
2026-11-15 08:04:10 -08:00
Anees Iqbal d0ef5e0145 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 07:57:53 -08:00
Anees Iqbal 7ede7adacf RUNTIME 2354: Host RAM copies: a copy finds each run's chunk by arithmetic, marks its pages in one bitmap vector and keeps its ranges as they are where they need no joining
A copy's encode cost grew with the chunks its runs touch: a binary search over the
chunks for each run that left the last run's chunk, a bitmap allocated for each chunk
touched, its runs read into a vector and copied into another, and each chunk's ranges
cloned, sorted and merged again before joining, though touched_ranges already gives
them sorted and apart.

- ChunkSpans (host_ram.rs): the chunks' spans and each RAM range's first chunk; of()
  finds an address's chunk as the range's first plus the chunks before it, the span
  span_of finds. pieces() takes it and still tries the last piece's chunk first.
- touched_ranges keeps every touched chunk's bitmap in one vector, reads the pages
  back with MarkedRuns (lazily, runs across words as one) and builds each chunk's
  ranges once, with as much room as its pieces.
- joined takes a chunk's ranges as touched_ranges gives them and borrows them where
  there are no more than the bound; chunk_ranges sorts and merges before it.

Same ranges, same overlap answer, same uses as before (the touched_ranges
equivalence test is unchanged). New unit tests: a chunk found by arithmetic is the
span that holds the address; MarkedRuns reads the runs the bits one by one give.

Evidence (lane jobs, msi lavapipe): m3-max-32538 at the lane tip: clippy plain / m2v_gpu / m2v_cpu_icd -D warnings 0;
host_ram 98/98; rustdoc 0. m3-max-32486: a_chunk_found_by_arithmetic_is_the_span_that_holds_the_address and
marked_runs_are_the_runs_of_the_bits_one_by_one; the touched_ranges equivalence test unchanged. Release medians, one job
m3-max-32485, 8100 single-page runs: 1 chunk 309.6 -> 298.9 us, 128 chunks 811.7 -> 733.4 us.

Lane commit: b13c097e6d.
2026-11-15 07:57:10 -08:00
Anees Iqbal 584da21fad Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 07:55:56 -08:00
Anees Iqbal 487a1253f2 host_ram: RamSource::wakes compiles only with its one caller, the device tests
Plain clippy of the runtime's lib test failed on development (a4ea017d9e): the
accessor was cfg(test), but its only caller, tests/host_ram_copy_device.rs,
compiles only under m2v_gpu or m2v_cpu_icd, so it was dead code there. It now
takes the caller's cfg, as step_aside.rs's device-test hooks do.
RamOnDevice::wakes stays cfg(test): the host_ram unit tests call it.
2026-11-15 07:55:10 -08:00
Anees Iqbal 4ebd9d1ba1 held_step_order: then_some for the thread's CPU time (clippy, --cfg m2v_cpu_icd)
clippy -D warnings under --cfg m2v_cpu_icd (m3-max-32505, msi) refused 02a27ea50f's
(answer == 0).then(|| ...) as unnecessary_lazy_evaluations: the value is two field reads.

Verified: the clippy job follows.
2026-11-15 07:49:58 -08:00
Anees Iqbal 02a27ea50f held_step_order: the thread's CPU time from CLOCK_THREAD_CPUTIME_ID; the suite's stretch stated as measured
The printout's time on a CPU came from /proc/thread-self/schedstat's first field, which stands
as of the thread's last scheduler event and leaves out the slice it is running: at the 5 runs
alone on the Radeon 780M (m3-max-32473) it printed 1.99 ms on a CPU for a 1.19 ms call. It now
comes from clock_gettime(CLOCK_THREAD_CPUTIME_ID) on unix, which counts the running slice too;
the run-queue wait stays schedstat's second field (Linux), which accrues only while the thread
waits and is whole by the time it runs.

The COMMIT doc and the nextest override's comment said the suite stretched the commit's work 8
to 60 times its CPU time, a ratio of tick-granular rusage numbers. They now give the measured
times themselves: a release build's later calls 5.8 and 7.0 ms under the suite's load (4.7 and
7.3 ms on a CPU, by rusage) against 0.10 to 0.26 ms alone; the test build's 10.7 and 16.3 ms
(8.2 and 10.4 ms on a CPU) against 1.1 to 1.2 ms alone.

Test printout and comments only; every assertion is unchanged.
2026-11-15 07:45:02 -08:00
Anees Iqbal 4c98eee685 held_step_order: the Scheduled-behind-a-step test runs alone; its commit bound's split measured
tests::held_step_order::command_buffers_behind_a_waiting_step_read_scheduled failed on the Radeon
780M (PHOENIX) in the development rounds a88823f8f4 and cc68beb2af, inside the device suite's
runtime partition: the long command buffer's commit call, bounded by a frame's 16 ms in one of
its 3 runs at least (COMMIT), took 394.2 / 21.7 / 30.7 ms and 166.9 / 38.3 / 16.9 ms.

The split of that call (WorkCounts' commit phases, and the thread's /proc schedstat and rusage
over the call; gem10's 780M, RADV PHOENIX, Ryzen 7 7840HS) puts all of it in Recording, the
host-step pass's Deferred::prepare on the program's thread: no pipeline wait, no wait for the
scheduler's lock, no pass or submission time (each 0.00 ms), 0 to 1 voluntary switches in the
later calls. First call / later calls, in ms:
- test build, the GPU to itself (m3-max-32424, 2 x 3 runs): 27.1-29.8 / 1.12-1.23, nearly all
  of it on a CPU, at most 0.05 on a run queue;
- test build inside the runtime partition 2/2 (m3-max-32429, 1355 tests, load average 14 on 16
  threads): 367.6 (274 on a CPU, 85 on a run queue) / 10.7 and 16.3 (on a CPU 10.4 and 8.2, on a
  run queue 1.5 and 10.3);
- release build alone (m3-max-32453): 3.58-4.21 / 0.10-0.26;
- release build inside the partition (m3-max-32457): 39.1 (28.6 on a CPU, 6.6 on a run queue) /
  5.8 and 7.0 (on a CPU 4.7 and 7.3).
So the call is the same work, which the suite's 15 other GPU test processes stretch to 8 to 60
times its CPU time (the APU's CPU shares its power, caches and memory with the GPU they keep busy)
plus waits for a CPU. There is no wait for the product to remove. The bound is the fastest run's,
a later call: 1.2 ms in the test build alone, 13 times under it; 5.8 ms in a release build under
the suite's load; 10.7 to 38 ms in the test build under it.

The test now runs alone (.config/nextest.toml, threads-required = num-test-threads), as the
teardown test's 16 ms wait and the queue-sharing latency tests do. COMMIT stays 16 ms, by the
call's own clock, on the fastest of the runs; its doc and the override's comment carry the
split. Test and nextest configuration only; no product change.

Verified: the numbers above are those jobs' printouts. The 5 runs alone at this tip and the
negative control (20 ms slept in the commit's recording phase) follow in the lane's report.
2026-11-15 07:42:50 -08:00
Anees Iqbal 2b9ed6d610 held_step_order: print where the long commit call's time went
The long command buffer's commit call is asserted within a frame (COMMIT) in one of the runs at
least. Its failure printed the call's whole time alone, which cannot tell the call's own work
from a host whose other processes held the CPU. The printout now splits the call by its phases
(WorkCounts' commit times: lowering, recording, pipeline waits, the scheduler's lock, its pass,
submissions) and, where the host reports them (Linux's /proc/thread-self/schedstat), the
calling thread's time on a CPU and on a run queue over the call.

Test printout only; every assertion is unchanged.
2026-11-15 07:42:50 -08:00
Anees Iqbal c7f70699bf Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 07:36:26 -08:00
Anees Iqbal a4ea017d9e RUNTIME 2353: Host RAM copies: a copy moves the device thread's window past its chunks under one lock and wakes the thread once, not once a chunk
copy_imports' for_copy moved the import thread's window for each chunk a copy touches and woke
the parked thread each time it moved, which, the chunks coming in order each next to the last,
was every chunk: 127 futex wakes for a copy over 128 chunks, a few microseconds each on the
encoding thread (kernel time a user-space profile misses; the per-chunk part of a consumer's
download encode, ~7 us a chunk). The staged first-touch paths did the same with a take and an
ask a chunk, up to two wakes a chunk.

RamOnDevice::take_for_copies(slots, ask) applies a take of each chunk in turn to the window
under one lock, so the thread finds the window a take of each would leave, asks for those not
imported where ask (a staged copy), and wakes the thread once after them all, or not at all
where the window moved nowhere and nothing was asked. copy_imports calls it once before
for_copy, which takes nothing itself now; the staged gather and scatter call it with ask. An
object's take is unchanged.

Tests: host_ram::tests::a_copy_s_takes_move_the_window_as_each_take_would_and_wake_the_thread_once
(the same window as a take of each, one wake, none where nothing changes, asks in the same
wake), and host_ram_copy_device::a_copy_over_several_chunks_wakes_the_device_s_thread_once (a
staged scatter over three new chunks and the scatter through their imports after it each wake
the thread once; a test-only count of wakes). Timings: see the lane's report.

Evidence (lane jobs, msi lavapipe): m3-max-32403/32436: a_copy_over_several_chunks_wakes_the_device_s_thread_once (staged
copy 1 wake, copy through the imports 1 wake); negative control (one take a chunk) fails with 3 wakes; the window unit test
(the same final window as a take of each chunk; no wake when nothing moved); clippy cpuicd clean; host_ram 95/95.
Timing (m3-max-32404, one job): no measurable change (1 chunk 354 -> 359 us, 128 chunks 938 -> 972 us, within the jobs'
~15% spread): the per-chunk cost is not the wakes (a phase probe names the per-run passes). Kept as a correct, built,
neutral change.

Lane commits: 754e50319e, c3dbc7c309.
2026-11-15 07:35:36 -08:00
Anees Iqbal 2da278dab9 Conformance: recordings and the census's sources are read from the checkout the binary runs in
recordings_dir() (recording.rs) and the coverage census's read_source and runtime_src
(coverage.rs) joined env!("CARGO_MANIFEST_DIR"), the directory the binary was built in, so a
conformance binary carried to another machine read the build machine's paths: no recording, no
source. The replay lane had to symlink the build path on the GPU node to run a carried binary
(11-15). All three now go through metal2vulkan_devtools::workspace_dir(), which takes the
checkout the runner names (a remapped archive's or cargo's CARGO_MANIFEST_DIR at run time) where
it holds the validation fixtures, else the build checkout, as the validation and runtime test
trees have since 39bff0de2a. No other env!("CARGO_MANIFEST_DIR") is left in the conformance
crate's src/.

Verification: the next development round's conformance suite (1043 tests), the lavapipe replay
and the XTX/PHOENIX replays, which read every recording through recordings_dir.
2026-11-15 07:33:20 -08:00
Anees Iqbal d72b69000d Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 07:32:08 -08:00
Anees Iqbal 155f97fbfd RUNTIME 2352: Host RAM: an object moves the window to its chunk only once it holds it
RamOnDevice::chunk moved the device's thread's window to an object's chunk
(take + notify) before the object marked the chunk's import in flight. The
window's first slot is the chunk just taken, so the woken thread could find it
not imported and import it By::Ahead in the object's place: counted as imported
ahead and marked untaken, with the object waiting for that import at the
thread's pace (SCHED_BATCH on Linux, utility QoS on Apple). Off Linux the thread
does no fault-in before an import, so it reaches the claims lock at once; that
is the failure seen once on the Windows mini under nextest -j 4:
a_chunk_bound_buffer_and_a_copy_of_its_pages_order_by_their_host_bytes saw ahead
imports 3 where 2 were expected (chunks 0 and 2 by the thread, then 3 within
settled()'s 300 ms).

Now the window moves (RamOnDevice::took) once the object holds the chunk: found
made, marked in flight by it, or held back. The thread, woken by the move,
finds the chunk in flight or made and imports the ones past it.

Test: an_object_holds_its_chunk_before_the_window_moves_to_it holds the
object's call 300 ms before it holds the chunk (RamSource::taking_pause, a new
cfg(test) pause beside making_pause) and checks the object imported its chunk
and the thread one past it alone.

Evidence (lane jobs, msi): m3-max-32427: clippy -p metal2vulkan-runtime --all-targets --all-features -D warnings 0;
lavapipe 78/78 (host_ram_device, host_ram_copy_device, host_ram:: units) incl. the new
an_object_holds_its_chunk_before_the_window_moves_to_it and the original a_chunk_bound_buffer_and_a_copy_of_its_pages_...
Negative control m3-max-32428 (the take back at the top of chunk()): the focused test fails, "the object imported its
chunk, the thread not in its place: left 0, right 1". The Windows mini runs follow in the lane.

Lane commit: 10dfe36dce.
2026-11-15 07:31:27 -08:00
Anees Iqbal 891307e5ac known-gaps: RADV's linear alignments and the XR mipmap ties hold on PHOENIX too
The PHOENIX replay of 9c438c6b72 (the Radeon 780M, RADV PHOENIX; job
m3-max-32387) failed on 27 rows the ledger lists for "RADV NAVI31" alone, as
nothing replayed PHOENIX regularly:
- device-linear-texture-alignments, 16 formats: Metal 16 (0x10), ours 256
  (0x100) at case/<format>/Ok, the same 16 formats and the same answer as the
  NAVI31 rows. The cause is RADV's: the smallest power of two from 16 at which
  the driver lays a linear image at the asked pitch
  (texture/linear_alignment.rs asks it per image), 256 on both chips.
- blit-generated-mipmaps-bgr10xr levels 1-5 (803, 232, 58, 13, 3 words; largest
  differences 1048577, 1049601, 1049601, 1049601, 1025) and
  blit-generated-mipmaps-bgra10xr levels 1-6 (58, 78, 46, 18, 5 fields of
  largest difference 64; level 6 Metal 0x7d00, ours 0x7d40): the NAVI31 rows'
  counts and differences exactly, and llvmpipe's. The cause is the runtime's
  bilinear compute filter in the device's float at ties
  (device-filtered-mipmaps), whose IEEE f32 rule gives these counts on any
  venue that computes it so.

So the 27 rows' venue widens from "RADV NAVI31" to "RADV", and the alignment
rows' words name both chips' measurement. No row's words change cause; the
llvmpipe and Apple M3 Max rows are untouched.

Verification: the PHOENIX and XTX replays at this commit, in the job reports
that follow.
2026-11-15 07:25:55 -08:00
Anees Iqbal 4b06d19b5e conformance: blit-copy-indirect-command-buffer declares staged-indirect-records
On a device that places indirect command buffer records by their first use (no
unified memory, a staging queue), the copy case announces
staged-indirect-records, and the XTX replay read it as an undeclared notice
(development a88823f8f4, and still at 45e6784e91, which removed the staging of
records the GPU never wrote).

The remaining staged accesses are the host steps' reads of records the GPU
wrote. Each copy of at least one command is the first use of its destination,
which the case makes and touches nowhere before, so the blit's write places the
destination's records in device-local memory. The execution after it takes the
host step (the case already declares host-replayed-indirect-commands for it),
and that step reads the records the copy wrote while their command buffer holds
them, through the staging queue: the documented, announced degradation, which
cannot be avoided where the GPU wrote the bytes in device memory and the host
never maps it. On the Apple chips the recordings were taken on there is one
memory and the notice cannot fire, so it is the venue's memory model, as
shared-in-system-memory is.

Measured on the RX 7900 XTX (RADV NAVI31), the case replayed alone and
`conformance cost --show --runs 1` at 45e6784e91's runtime (cfcdb2978, job
m3-max-32363):
- copy: host_steps_recorded 3, icb_records_staged_accesses 3 (the legs
  range-one-at-0, range-one-at-2 and range-whole; indirect_record_bytes_gpu_copied
  13488 = 6 commands of 2248 bytes), indirect_record_runs_read 1 (the
  range-none leg's commit read, in place);
- reset: host_steps_recorded 3, no staged access (its buffer is the CPU's
  first, so its records lie in host memory).
So every staged access is a host step's read of GPU-written records, and none
reads records the GPU never wrote.

The declaration: replay::staged_records_notice, beside shared_memory_notice,
with the venue's-memory-model reasoning, and the copy case names it alone
(Call::places_its_records_on_the_gpu), with a comment citing the run. It
loosens the notices site alone; every value still compares exactly. On unified
memory (the M3 Max, PHOENIX, lavapipe) it cannot fire and counts as a
declaration nothing on that run justifies, as shared-in-system-memory does
there.

Verification: in the job reports that follow (the XTX and PHOENIX replays).
2026-11-15 07:17:01 -08:00
Anees Iqbal b1eaad49c7 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 07:16:31 -08:00
Anees Iqbal 0ca24685d7 RUNTIME 2351: Textures over buffers: Metal's allocation bound counts the last texel, a heap's size and a no-copy buffer's pages
A texture over a buffer whose texels run past the length was answered nil
where its rows' padding ended past the length rounded up to 16 KiB. The
M3 Max (macOS 27.0.1, the consumer's limits runs, every buffer kind and
length bisected) makes more:

- A 2D texture and a texture buffer count to their last texel, not the
  last row's padding: a 2D R32Uint 64x64 from 256, rows 512 apart, over
  20000 bytes is made with its last texel at 32768 (rows' end 33024); a
  texture buffer of 32768 R8Uint texels at a bytesPerRow of 36864 over
  20000 bytes is made. Arrays keep their rounded slices' end.
- A heap's buffer is bounded by the heap's size, counted from the
  buffer's start, whatever its length or place in the heap (4 MiB heap:
  made to 4194304, nil at 4194305).
- A no-copy buffer is bounded by its pages: its pointer's offset in its
  16 KiB page plus its length, rounded up to 16 KiB, from its start
  (16384 bytes starting 4096 short of a page's end: made to 32768).

BufferFacts now carries the buffer's allocation (own, a heap's size, a
no-copy buffer's page offset), filled from Buffer::heap, host_backing and
contents; BufferFacts::allocation_end gives the bound. Buffers under
16 KiB keep no bound (the M3 Max answers nil past 128 KiB there, the x86
Macs make every end measured), and an array whose last texel lies inside
the length is still made: no new refusal.

Such a texture stays a copy, as before at the old bounds: a 2D texture or
array is a shadow image whose copies in and back go through its tail
(texture/route.rs Route::Past -> TextureShadowReason::PastLength,
announced shadowed-texture), a texture buffer's functions view its tail
(into_texture_buffer, staged-texture-buffer). The texels past the length
live in the tail, zero when made; the caller's bytes past a no-copy buffer
and a heap's other bytes are never read or written.

Tests: tests::linear_plan::a_texture_ends_where_metal_s_allocation_of_its_buffer_does
(each kind's and form's M3 boundary, made at it and nil one past; the
made rows past the old bound fail before this change); device tests in
buffer_tail_device (a heap's buffer to its 64 KiB heap's size, a no-copy
buffer at page offset 12288 to 32768, a padded 2D texture to its last
texel): made, every path reads and writes right, the buffer's CPU write
inside the length is read through the texture, shadow copies counted,
no other memory touched, one row more Metal's nil. docs/API.md's
accepted difference, REFUSALS.md regenerated.

Evidence (lane jobs, msi): m3-max-32369: clippy -p metal2vulkan-runtime --all-targets --all-features -D warnings 0;
linear_plan|buffer_texture 34/34 incl. tests::linear_plan::a_texture_ends_where_metal_s_allocation_of_its_buffer_does (the
M3's boundaries per kind and form, made at E, nil at E+1). m3-max-32370 (lavapipe): 13/13 buffer_tail_device + allocation
tests incl. a heap's buffer to its heap's size, a no-copy buffer to its pages, a 2D texture whose last texel ends at the
allocation: every path (get_bytes, blit, kernel) reads as made, writes coherent with the buffer's bytes inside the length
(shadow copies counted: such textures are shadows / staged texture buffers through their tail), neighbours untouched, one
row more Nil(PastAllocation). Negative control and the PHOENIX run follow in the lane.

Lane commit: 263219d515.
2026-11-15 07:15:50 -08:00
Anees Iqbal 58cbb48fca commands_recorded: a run of copies between the same two buffers is one vkCmdCopyBuffer
Since 43bb61c60e (RUNTIME 2344) consecutive copy_from_buffer_to_buffer calls between the same
two buffers with their destinations rising record one vkCmdCopyBuffer of a region each
(copy_run.rs), counted WorkCounts::buffer_copies_merged. runtime_lane::commands_recorded::
each_command_recorded_counts_once_by_kind still expected one call a copy, so it failed on the
XTX and PHOENIX in development round cc68beb2af-1115-0626 (xtx:lane 1/2, phoenix:lane 3/4):
"the fills' and copies' calls recorded: left [5, 0, 1], right [5, 0, 2]". Its two copies are
such a run (filled -> copied, word 0 then word 1), so it now expects one vkCmdCopyBuffer and
buffer_copies_merged + 1, and prints the merged count. The bytes checks are unchanged.

Test-only. Verification: the next development round's lane partitions (XTX, PHOENIX, 5080).
2026-11-15 07:14:17 -08:00
Anees Iqbal 7f429c8edb Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 07:13:22 -08:00
Anees Iqbal f59fa9b0b4 RUNTIME 2350: Host RAM copies: a chunk's ranges, the overlap check and the table in one pass, with no map lookup or sort a run for whole pages
record_host_ram_copy spent most of its encode on per-run bookkeeping (a profile of 8100
single-page runs on lavapipe, release, frame pointers): chunk_ranges' BTreeMap entry a piece, a
Vec and a sort a chunk (46%), in_imports' BTreeMap lookup a piece (14%), the scatter's overlap
check sorting every host range (14%), plan's BTreeMap entry a table entry (10%), and pieces'
binary search over the chunks a run (9%).

- touched_ranges: pieces of whole pages from a page mark their pages in a bitmap of their chunk,
  read back in order; only the other pieces (rows inside pages) are sorted. It gives the ranges
  chunk_ranges gives, byte for byte (so every use and barrier is as before), and whether two
  pieces share a host byte, exactly: a page marked twice, another piece's bytes in a marked page,
  or two other pieces that overlap.
- in_imports looks a piece's imports up in a vector by chunk.
- plan buckets its entries by array of imports and window in a vector, in the same order.
- pieces looks for a run's chunk first where the piece before it lies.

Test: copy::tests::touched_ranges_are_the_chunks_ranges_and_their_overlap_in_one_pass (whole
pages, rows sharing a page, overlaps of each kind, and 2000 random mixes over four chunks, against
chunk_ranges and share_a_byte). Timings: see the lane's report.

Evidence (lane jobs, msi lavapipe): m3-max-32324: clippy cpuicd -D warnings 0; host_ram tests 93/93 incl.
copy::tests::touched_ranges_are_the_chunks_ranges_and_their_overlap_in_one_pass (byte-exact ranges and overlap flag vs
chunk_ranges + share_a_byte: whole pages, rows sharing a page, each overlap kind, 2000 random mixes over 4 chunks).
Release medians, one job m3-max-32339, parent's copy.rs vs this, 200 CBs of copy_runs_to_host_ram with 8100 single-page
runs, call CPU: 1 chunk 750.6 -> 351.1 us (92.7 -> 43.3 ns a run); 128 chunks 1523.7 -> 1097.6 us (188 -> 135 ns a run).
Uses and barriers unchanged by construction. 3090 run: m3-max-32374.

Lane commit: 6c02be1492.
2026-11-15 07:12:41 -08:00
Anees Iqbal ae2982cfdf Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 07:11:45 -08:00
Anees Iqbal f851c07e52 SEMANTICS 2123 / RUNTIME 2349: Texture buffers past maxTexelBufferElements bound through views of their parts
Metal makes texture buffers of up to 2^28 texels on every Mac; one texel
buffer view holds at most the device's maxTexelBufferElements (2^27 on ANV
and lavapipe, 2^26 on MoltenVK), and the binding of a wider one was refused
(BindError::TexelBufferTooLarge).

The consumer now states with a texture buffer's binding the views its texels
take (BoundTexture::Buffer::parts, bind::texel_buffer_parts: 1 within the
limit), which its shape carries. A slot whose function only reads, writes,
updates by an atomic or asks the width of the texture buffer, on a device that
indexes texel buffer arrays NonUniform, states RuntimeFact::TexelBufferParts;
where the shape binds more than one part there, the plan asks for the parts
variant (VariantKey::texel_buffer_parts). Under it the slot is an array of
the parts' texel buffers: texel i is texel i - k*P of part
k = min(i / P, parts - 1), P the device's limit rounded down to its texel
buffer offset alignment (bind::part_texels), and the width (parts - 1) * P
plus the last part's. texel_ranges writes one range per part at its array
element (DescriptorRange::element), and the runtime views each.

Each part is the device's own view in the format one view takes, so a read
converts its texel as the one view does: no precision note. A texture buffer
one view holds keeps one view, no variant and its key. The families row
TextureBufferWidth is exact where the parts reach 2^28.

Still refused (TexelBufferTooLarge): a slot read through a sampler or used beyond read/write/atomic/width; a device
without NonUniform indexing of that kind of texel buffer array; formats with several texels a block. Argument-buffer
texture buffers past the limit stay the heap neutral (unnamed-texture-unviewable). New: WorkCounts::texel_buffer_parts_bound,
RuntimeFact::TexelBufferParts (appended), bind::part_texels / texel_buffer_parts, BoundTexture::Buffer.parts,
TextureShape::Buffer.parts (serde default 1), VariantKey/LoweringInputs.texel_buffer_parts (hashed only when non-empty),
DescriptorRange.element. SEMANTICS_VERSION bumped: input once refused now translates.

Evidence (lane jobs, msi): m3-max-32343 at 628264de17: clippy --workspace --all-features --all-targets -D warnings 0;
41 metal2vulkan tests incl. golden_hashes_match_the_table (every fixture's SPIR-V unchanged on every profile: one part is
byte-identical), the binder test (an under-limit slot: no parts entry, empty variant, layout counts 1), the interpreter
parts test (robust and unrobust), api_surface / api_signatures / refusal_surface; families::states_follow_their_sources;
lavapipe texture_buffer_width_device (R32Uint limit+64 texels: both sides of the limit and the last texel read and written,
past the end reads 0 and writes dropped, texel_buffer_parts_bound +3) and buffer_tail_device. Without the fix the device
test fails at bind: TexelBufferTooLarge{elements 134217792, limit 134217728} (m3-max-32140). ANV (2^27) is down; the XTX
(2^29) never parts.

Lane commits: 9fbf7d3c14, 7f7f3ad95e, 9a745ffb3c, 740e9e43dd, 628264de17.
2026-11-15 07:10:59 -08:00
Anees Iqbal c9abbafd2f Queue-plan tests count the command queues' VkQueues, not the copy queue's
Since 43bb61c60e (RUNTIME 2344) a device with a copy engine (a transfer-only family of at
least 2 queues: NVIDIA) lists the copy queue's slot last in DeviceShared::queues. Two tests
counted every entry after the round robin as presenting queues, so on the RTX 5080 (development
round cc68beb2af-1115-0626, job 5080:runtime) they read the copy slot as one more:
- least_queue_plan::a_device_refused_once_takes_its_least_plan_where_it_takes_fewer_queues:
  (1, 1) where the least plan is (1, 0);
- queue_limits_device::a_default_test_device_fails_where_its_work_needs_the_plan: 3 VkQueues
  for command queues where the test limits allow 2.
On NVIDIA's 2-queue copy engine the copy slot shares the fill queue's VkQueue, so the device
asked for no more queues; only the count was wrong. Both now count round_robin() +
presenting() (DeviceShared::presenting already leaves the copy slot out). lavapipe, the XTX and
PHOENIX have no copy engine by default, which is why only the 5080 leg showed it.

Test-only. Verification: the next development round's 5080 runtime partition.
2026-11-15 07:04:48 -08:00
Anees Iqbal 281fc9b40b Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 06:59:16 -08:00
Anees Iqbal 45e6784e91 RUNTIME 2348: ICB records the GPU never wrote are read in place, not staged
On a device that places indirect command buffer records by first use (no
unified memory, a staging queue), a host access of records in device-local
memory was staged whenever a command buffer held them or the buffer was
Private: the records it read were copied down through the staging queue and
waited for, counted, and staged-indirect-records announced. That held even
where the GPU never wrote the records, though then the host's buffer holds
exactly what device-local memory does.

The XTX conformance replay of development a88823f8f4 failed on it:
blit-copy-indirect-command-buffer announced staged-indirect-records. Its
range-none leg copies no commands into a fresh destination (an empty copy
holds nothing and marks nothing written), then executes destination command 0.
The execution's hold placed the untouched records in device-local memory, and
the commit, which records the execution from the CPU's records because no GPU
route met the buffer, read them through host_access while its own command
buffer held them: staged. The cause dates from 5dd3668a4f (RUNTIME 2294,
placement by first use); the last green XTX replay (06fd49b221, 11-11)
predates it, and the case's recording did not change.

Now host_access serves an access that only reads (Reach::Reads) records the GPU
never wrote (State::written false) in place: not staged, not counted, nothing
announced. A write of such records is still staged, for its copy back alone:
it no longer copies the runs down first.

Why the two sides cannot differ while written is false:
- placement (place_on_device) fills the device-local storage with zeros and
  writes encode_header's header, which is what the host's storage holds as the
  buffer is made (write_header: CommandBuffer::initialize's header and reset
  records, flags cleared; the reset record is all zero,
  metal2vulkan's indirect_commands/tests/records.rs
  reset_clears_action_and_bindings_to_zero). A Shared buffer the CPU touches
  before any GPU use is placed on the host for good; a Private one is placed on
  the device at its first host access, before that access writes.
- every CPU write of the records goes through records_access with
  Reach::Writes or Reach::Overwrites (reset_command, batch, the CPU reset), and
  while the records lie in device-local memory that access is staged with
  back = true, whose drop copies the written runs (records and written flags)
  back into device-local memory: home.rs line 222,
  `copy_runs(self.icb.generation(), records, host, &self.runs, false)`.
- every GPU route that writes the records holds them with writes = true, which
  sets written (home.rs line 320, `state.written |= writes`): a blit's copy and
  reset, and a compute or render encoder's use_resource with WRITE.
The move path already relied on the same fact (a move of a buffer the GPU never
wrote copies no bytes).

The conformance case needs no declaration: the notice was the runtime staging
where it need not.

Also: the runtime-lane test private_indirect_records_follow_the_memory_model
expects two staged accesses (its two setters), its getter now reading in place;
the docs of home.rs, Degradation::StagedIndirectRecords (and its cost),
WorkCounts::icb_records_staged_accesses and docs/API.md's catalogue entry say
which accesses stage. No new Degradation kind, no new counter.

Verification: in the job reports that follow.

Evidence so far (lane jobs): msi m3-max-32246 at cfcdb29780: the conformance binary and the m2v_gpu archives built; the
lavapipe replay (conformance replay --cpu) matches known-gaps.tsv (LVP_REPLAY=0). gem10 m3-max-32248: clippy -D warnings
plain, m2v_gpu and m2v_cpu_icd on runtime + validation = 0. The XTX replay and the new device tests (with the control at
76a78ec60a) follow in the lane's um790 job.

Lane commits: 76a78ec60a (tests), cfcdb29780 (fix).
2026-11-15 06:58:33 -08:00
Anees Iqbal 374a9207a0 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 06:57:44 -08:00
Anees Iqbal 7aff494cc4 RUNTIME 2347: Command buffers take the state a released one left, reset by its release
CommandQueue::command_buffer allocated and filled a fresh 5.8 KB State for
every command buffer (86% of CommandBufferShared's 6.7 KB), on the thread
that makes it, and took a record storage from the device's pool apart. The
thread that frees a command buffer is never the thread that made it, so
the allocator could not recycle the block locally and every line of the
copy was a cold write. A profile of 200,000 command buffers made on
lavapipe (make_bench) put CommandBuffer::new at 62% of the make,
building and moving the state about 30% and record_storage.take 9%; the
consumer's Iris profile put the allocation, the copy and the record
storage take at about half of 5.1 us a command buffer.

Now CommandBufferShared::state is an Arc<Mutex<State>>. Its Drop resets
the state in place, reached through Arc::get_mut and Mutex::get_mut (only
the command buffer holds it, so no lock): State::reset destructures an
owned State::new() exhaustively, by value, and assigns each part, while
the four lists of records are cleared where they are, keeping their room.
The compiler holds the reset to every field. The Drop then hands an
Arc::clone of the state to the device's SpareStates (in DeviceShared,
freed with the generation), which keeps at most 64, none whose lists hold
past 8 MiB and 16 MiB over all. A command buffer being made pops one
whole, with the footprints revision it moves; it builds one only where
none is kept (WorkCounts::command_buffer_states_made, new). This replaces
SpareRecordStorage, and with it State::record_storage's three
mem::takes. Nothing is moved out of a borrowed owner.

The state's parts now drop at the release, inside the Drop, before the
command buffer's device, queue and root handles go (before, after them);
its slot still goes after.

Tests (tests/spare_states.rs, device tests): a command buffer made after
another's release takes that very state and builds none; a kept state of
a failed, labelled command buffer with a kept refusal carries none of it
to the next one, whose own fill runs; 80 released at once keep 64, and a
command buffer past 8 MiB of list room keeps none. make_bench prints the
states built.

Evidence (lane jobs, msi): m3-max-32266 at 6e4c8a8723: clippy -p metal2vulkan-runtime --all-targets --all-features
-D warnings 0; lavapipe 134/134 touched tests (spare_states, dropped_uncommitted, freed_memory, encoder_fold, render_fold,
command_buffer, completion, sync_file, teardown_threads, ...); negative control (SpareStates::give refuses every state):
all 4 spare_states tests fail. Release medians, one job m3-max-32278, base 5266f9fa59 vs tip, base/tip/base/tip:
command_buffer() p50 one encoder 955/927 -> 319/291 ns, empty 902/986 -> 405/359 ns; means 1027/993 -> 408/409,
1126/1215 -> 579/522; made-to-committed p50 one encoder 5448/5469 -> 5022/4965 ns; states built 0-2 of 20,000.
Not measured yet: the release side (the reset on the releasing thread), a GPU device A/B (XTX/PHOENIX next; Iris when
its node is back).

Lane commits: 5266f9fa59 (make_bench), e91d54e0fc, 6e4c8a8723 (cfg-gated assignments in blocks).
2026-11-15 06:56:54 -08:00
Anees Iqbal 61b3da253d Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 06:48:55 -08:00
Anees Iqbal b7053280de RUNTIME 2346: 4:2:2 textures over IOSurface planes: an image of their texels, decoded from the pairs in place
A GBGR422 or BGRG422 texture made over a buffer's bytes (Buffer::new_texture_with_iosurface_plane,
a CoreVideo 2vuy or yuvs plane, over a Shared buffer or a no-copy buffer's host pages) had no
decoded twin: twins are attached only to textures whose image is their own for good, so every
dispatch or draw that read or sampled it was refused, with a "needs R8G8B8A8_UNORM SampledImage"
line naming a format every device samples.

Such a texture is now an R8G8B8A8_UNORM image of its texels, the converted shadow a two-plane
YCbCr texture over planes already is (ShadowSource::Converted, its conversion now an enum of the
planes' and the pairs'): its copy in, before the first command of a command buffer that reads it
and after a command wrote the bytes, is one dispatch of the new bind::chroma_convert_module that
reads the pairs where they lie, at any byte of their VkBuffer, through one storage-buffer binding,
and writes Metal's texels (ChromaDecode, exact) through the image's R32_UINT view. Copies, blits
and CPU calls keep moving the plane's bytes. Where the device converts the pairs' format with
Metal's reconstruction (MoltenVK), the copy in is that conversion instead: the plane's rows copied
into the pairs' image, sampled through the conversion (chroma_sample_module) into a scratch,
copied into the image; announced decoded-texel-precision at the copy in's planning. The set binds
the buffer's VkBuffer, so the planning makes it again after a rebind gave the buffer another one,
and each command buffer holds the set it took. The placement query answers OtherShape. A plane
the window cannot take (past maxStorageBufferRange, a last word past the buffer, rows that share
bytes, texels past the buffer; with the device's conversion, a first byte or rows off 4 bytes)
keeps the carrier, its reads refused; FAST-PATHS records it as a known gap.

Per frame, per texture (w x h texels): before, no read ran at all; the texture was an R8G8_UNORM
carrier of the plane, 2 bytes a texel. Now no byte is copied: one dispatch reads the w*h*2 bytes
of pairs in place and writes w*h*4 bytes of texels (1920x1080: 4147200 read, 8294400 written).
Memory: one R8G8B8A8_UNORM image, w*h*4 bytes (1920x1080: 8294400), in the carrier's place; with
the device's conversion also the pairs' image (w*h*2) and the scratch (w*h*4), and per copy in a
w*h*2 copy in and a w*h*4 copy out. Announced carried-decoded-twin (an existing kind) with that
cost. No new Degradation kind, no new WorkCounts field.

A carrier's binding without a twin is now refused NotImplemented(Format) naming the texture's
format (pvrtc::holds_for_copies), not a need of the twin's view format.

Public surface: metal2vulkan::bind::{chroma_convert_module, ChromaConvertModule} added
(api_signatures.tsv blessed, api_surface table); docs/REFUSALS.md regenerated (one more
binding_view site of Format).

Tests: the in-place kernel against ChromaDecode's decode under the interpreter (both orders, first
bytes off a word, odd sizes, rows apart); a carrier's binding refusal (binding_view unit test);
a device test of both formats over a Shared buffer and over host pages reading Metal's measured
bar values (an Apple M3 Max, macOS 27.0.1) and Metal's decode of a random frame written on the
CPU before the next command buffer, OtherShape from the placement query, and the device's
conversion counted and announced where it converts. Verification jobs follow in the lane report.

Evidence (lane jobs): msi m3-max-32240 at 94f603bf35, --cfg m2v_cpu_icd on llvmpipe: 130/130 touched tests, clippy -D warnings 0;
the device test fails without the fix (placement not OtherShape, the read's dispatch refused). PHOENIX gem10 m3-max-32260
(archive m3-max-32241): all 4 cases (GBGR422/BGRG422 over a Shared buffer and over host pages) "Metal's texels, exact"
for the M3's measured bars and a random CPU-written frame; ycbcr_device, ycbcr_refresh, twin_reads 7/7. MoltenVK (device form)
run on the M3 follows.

Lane commits: 735234d5f4, d59f44baa6, 94f603bf35.
2026-11-15 06:48:09 -08:00
Anees Iqbal 675912b3ad Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 06:44:08 -08:00
Anees Iqbal ef64727c7a RUNTIME 2345: Host RAM: a first gather over bytes some use may write is staged in a part of its own, never through imports made or waited for on the encoding thread
stages() staged a gather over chunks the device's thread imports only where no use but a
copy's read may write its host bytes (RamOnDevice::written_over). That holds for the whole copy
as soon as one chunk it touches had a scatter recorded (copy_wrote, never cleared) or a buffer
over host pages lies over its bytes, so a first fill over a fresh RAM after any download into one
of its chunks took the imports' path: for_copy imported each chunk not imported yet on the
encoding thread (the ahead plan imports no range alone). A consumer's decoder waited 1.73 s
for 124 such imports on an RTX 3090 (each pins 64 MiB of fresh pages).

Such a gather is now staged as one over a chunk that takes no import is when written: in a part
of its own (Staging::after_the_gpu), its host step after the work before it in its command buffer
completed, on the steps' thread. Its encoder keeps no log (an encoding again through the imports
would start no part, so its parts would not be the first's). Docs: copy.rs, deferred.rs,
docs/HOWTO.md.

Tests: host_ram_copy_device::a_first_gather_over_chunks_a_scatter_wrote_waits_for_no_import (a
scatter then a gather in one encoder over two chunks not imported, the thread's imports held in
flight): the gather is staged, waits for no import, imports no range, reads the scatter's bytes;
two later fills of its pages (a later encoder, a later command buffer) land after its read.
Benches (ignored, release): host_ram_first_fill_spread_bench, host_ram_layer_encode_bench.

Evidence (lavapipe, msi): negative control m3-max-32190 (the test against the parent's copy.rs
fails: not staged, 600 ms waiting on two paused imports); with the fix all 92 host_ram tests pass
(32190); clippy cpuicd -D warnings clean and the extended test pass at the tip (32210). First-fill
bench after a 1-page download: before staged 0, 121 chunks imported on the encoding thread, call
1369 us (32174); after staged 1, 0 import waits, 0 chunks imported by the copy, call 328 us (32210).
The 3090 run follows.

Lane commits: e70fea0886, f50ee551c3, 9e74f43df1, ab6d8af756.
2026-11-15 06:43:15 -08:00
Anees Iqbal cc68beb2af host_ram_device: the window assertion names the chunk counts and the import tax
A Windows run (UHD 630) failed it with no more than the two ahead counts; the
message now carries what the device's thread did between them.

Verified: cargo fmt; the run follows on the Windows node.
2026-11-15 06:24:26 -08:00
Anees Iqbal 08ae84505e teardown_threads: the queue-switch check's test states its release at the RTX 2080's usual speed
The measured split behind the previous commit's bound (the teardown's wait for the stopped
check, less the release of its Vulkan objects), on the RTX 2080 (NVIDIA 620.70.06):

- Pin 99, run alone, its host making driver calls three to four times slower than usual
  (um790 job m3-max-31777): wait 33.1 / 23.3 / 19.8 ms, release 19.6 / 22.0 / 18.4 ms,
  difference 13.6 / 1.3 / 1.4 ms. The old bound failed all three.
- After the Thunderbolt replug and the reboot, the old test passed in the exclusive GPU-time leg
  (m3-max-32075, 18/18; it printed no split, as it passed).
- This branch's test, 5 runs on the same card (m3-max-32110): wait 6.5 / 1.7 / 4.7 / 5.1 /
  1.9 ms, release 4.5 / 1.6 / 2.7 / 3.5 / 1.7 ms, difference 2.0 / 0.13 / 2.0 / 1.7 / 0.13 ms.

So the release scales with the host's driver speed. Those destroy calls must precede
vkDestroyDevice (VUID-vkDestroyDevice-device-05137) on whichever thread makes them; they are not
the check's stop, which the 16 ms bound is for.

Controls in the same job, a diagnostic build of this branch (not for landing) that sleeps 20 ms
in the check: inside its timed release, the test passed with a wait of 26.8 ms (release 24.4 ms,
difference 2.4 ms), a wait the old bound would have failed; in its stop path (after its hold,
before it reads that the teardown began), the test failed: wait 24.5 ms, release 2.8 ms,
difference 21.7 ms. So the bound still catches a check that is slow to stop.

What changes: the test's doc adds the usual-speed numbers beside the slow host's.

Verified: cargo fmt; the numbers are from the jobs above.
2026-11-15 06:13:08 -08:00
Anees Iqbal a59f80573e teardown_threads: the queue-switch check's teardown wait is bounded less its objects' release, which is printed beside it
a_running_queue_switch_check_leaves_the_device_to_the_program_s_thread failed on the RTX 2080
(NVIDIA 620.70.06) at pin 99, run alone (um790 job m3-max-31777): the teardown waited 33.1, 23.3
and 19.8 ms for the stopped check against RELEASE (16 ms), of which the release of the check's
Vulkan objects took 19.6, 22.0 and 18.4 ms and the drop of its shares 3-5 us. The wait less the
release was 13.6, 1.3 and 1.4 ms. At that time that host made driver calls three to four times
slower than usual. The same test passes on the RTX 3090 (same driver), the RX 7900 XTX and the
Radeon 780M.

Why the bound changes (the measured split above): the wait (QueueSwitch::stop) covers the test
hook's release (a 1 ms poll), the check's wake and the end of its step (none here: it is held
between rounds), then Objects::release: eleven destroy calls (three timelines, three fences, the
timestamp pool, the scratch buffer and its memory, the command pool of 97 command buffers),
through the validation layer this test's device enables. Those calls must precede
vkDestroyDevice (VUID-vkDestroyDevice-device-05137) on whichever thread makes them: moving them
to the teardown's own releases after its wait for idle would leave the last drop just as long
(5.1 s, 632 ms and 589 ms in those runs). They are driver time, not the check's stop, which is
what the 16 ms bound is for: that the teardown waits for at most one step of the check, never
for its run. The bound now applies to the wait less the objects' release (timed by the check,
QueueSwitch::last_steps), and the test prints the wait, the release, the shares' drop and the
difference, as queue_order's bounds take the driver's vkQueueSubmit time out. No product change.

Verified: see the lane report (the RTX 2080 job).
2026-11-15 06:12:26 -08:00
Anees Iqbal 74e6846f93 runtime device tests: detach_lost's pages through the host helper
Verified: Windows clippy under --cfg m2v_cpu_icd at 4854552866 (job m3-max-32077)
listed this module's libc calls only; under m2v_gpu it passed.
2026-11-15 06:10:51 -08:00
Anees Iqbal 3c78564977 runtime device tests: the unix-only exportable-buffer parts' imports and constants gated
Verified: Windows clippy under --cfg m2v_gpu at eb6fb128a8 (job m3-max-32067) listed
these errors only; Linux clippy under m2v_gpu and m2v_cpu_icd passed there.
2026-11-15 06:10:51 -08:00
Anees Iqbal 38b301e1ed runtime device tests on Windows: host pages, protections and CPU times through one helper
tests/host_os.rs gives the device tests fresh private and shared pages (a memfd on
Linux, anonymous shared memory on the other unix hosts, a section view on Windows),
their release and protection, the page size and CPU times, so the host-memory and
host-RAM device tests build and run on Windows under --cfg m2v_gpu. copied_device's
read-only host is a section with a writable and a read-only view on Windows, and its
read-only-copy tests run there; a new test checks that no-copy buffers over private
and shared pages are imported in place where the device takes them. shared_pointers
runs on every host and expects Intel's Windows driver to import a section view. Tests
of unix-only items (exportable buffers, dma-buf hooks, memfd guest RAM) stay unix-only.

Verified: cargo fmt; Windows and Linux clippy follow as jobs.
2026-11-15 06:10:51 -08:00
Anees Iqbal 55ff518295 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 06:10:02 -08:00
Anees Iqbal 43bb61c60e RUNTIME 2344: Runtime: a command queue on the copy engine, and buffer copies merged into runs
Device::new_command_queue_for_copies() answers a CommandQueue whose command
buffers submit to the device's copy engine (the staging queue's family of
transfers alone), or None where the device has none to give (MoltenVK,
lavapipe, RADV by default, a copy engine of one queue, an adopted device).
Its VkQueue is the copy engine's third queue where it has one, else the fill
queue's, whose submissions then take that QueueSlot's lock: NVIDIA's copy
engine has two queues, staging's and fill's, and staging must wait for no work
in flight. The slot is the last of the device's VkQueues, after presenting's;
its family stays out of image sharing (buffers already share it as the staging
queue's family, so no ownership transfer is recorded).

Its command buffers take blit encoders alone, and of their commands buffer
copies, fills and fences: other encoders and blit commands are refused
(Invalid, Problem::CopyQueue(CopyQueueProblem::Encoder | Command)), as is a
caller's VkBuffer not concurrent with the copy family (Buffer). A copy batch
takes buffers' fills alone from first work. Barriers on its VkQueue name the
copy family's reads (Barrier::record_reading), not the primary family's, which
a family of transfers alone may not name beside ALL_COMMANDS
(VUID-vkCmdPipelineBarrier-dstAccessMask-02816).

A blit encoder's consecutive copy_from_buffer_to_buffer calls between the same
two VkBuffers that its order needs no barrier between are recorded as one
vkCmdCopyBuffer of many regions (copy_run.rs), on every queue; counted as
WorkCounts::buffer_copies_merged. Batches on the copy slot are counted as
WorkCounts::copy_queue_batches.

Verified: not yet built (first build job follows).

Also in this landing:
- Copy queue: docs, and the device test's None answer checked against the device
- Copy queue: keep the copy queue's place alive while the families are counted

Evidence: lavapipe 425/425 (m3-max-32049), clippy m2v_cpu_icd and m2v_gpu -D warnings (32049, 32053); XTX m3-max-32073: default RADV answers None; RADV_PERFTEST=transfer_queue: 1 batch on the copy engine, 63 of 64 row copies merged, sync file signalled, bytes right, refusals typed, validation layer silent.
The derived API table and docs/REFUSALS.md were re-derived on the merged tree (winport's #[cfg(unix)] gates landed beside copyq).
2026-11-15 06:09:09 -08:00
Anees Iqbal 4c8ca3e4b4 queue_order: the single taken-up test times the scheduler's thread from the holder's let-go, its wait for a core apart
a_checked_command_buffer_committed_during_a_submission_is_taken_up_promptly still noted the
VkQueue's release before it sent the release to its holder thread, so the holder's own wake (it
must get a core to unlock: measured up to 40.7 ms after the release under 16 busy loops on the
RX 7900 XTX, m3-max-31893) was charged to the scheduler's thread against the 40 ms bound, and
its measure ran to the left command buffer's kernel start, past the instant where the driver's
time was read, so a wait for a core after its check counted too.

What: the test now takes the timing d25f77ecb1 gave its sibling
checked_commits_during_submissions_are_taken_up_promptly, through the same helpers, which move
into one place: the holder (`Held`, which both rounds and the commit-order test now use) notes
the instant it lets go of the VkQueue as its closure's last step, with the scheduler's thread's
schedstat (`Freed`); the left command buffer's take-up is noted by its submission handler on the
thread that took it (`carried`, `Noted`), and the bound applies to the take-up less the longer of
the driver's vkQueueSubmit time and the thread's run-queue wait over that same span (`own_time`,
`Noted::since`). Its kernel start and submission are printed, not bounded, as the sibling prints
them. The test also begins once the device's submission checks answered
(Device::settle_submit_checks), as the sibling has since 88ed42fc2a, for its reason: a lane
device's checks run on its first VkQueue as it is made, holding that VkQueue's lock for calls
batch_submit_nanos does not count, and this test's one round is the earliest there is. Each run
prints a TAKEN-UP-ONE line with the split. `in_driver` and `noting` had no other user and go.

Verified: see the lane report (the RX 7900 XTX job: 5 runs alone, and the old and new binaries
under busy loops pinned with the test to the same cores).
2026-11-15 06:02:11 -08:00
Anees Iqbal c7d3c434fb Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 05:50:16 -08:00
Anees Iqbal 0bede1683a Windows: the dma-buf gauge accessor and the Source refusal's test pair on unix alone
Verified: Windows clippy at 3d6ba0eff5 (job m3-max-31991) listed these two errors only.
2026-11-15 05:49:35 -08:00
Anees Iqbal a3b38034d5 runtime README: Windows
What the runtime asks Win32 for on Windows (VirtualQuery and GetSystemInfo for host
pages, the performance counter and its calibration domain, GetThreadTimes, the C
runtime's atexit, the default shader cache directory), how section views are imported,
and the fd items absent there. docs/REFUSALS.md is unchanged (refusal_surface.py --check
passes): no refusal or RuntimeGap was added.

Verified against the code at this commit; no Degradation kind added.
2026-11-15 05:49:35 -08:00
Anees Iqbal de2921df91 Windows: unix-only counters and the dma-buf source refusal gated; residency's pointer form without a lazy closure
The counters of dma-bufs, sync files and fd budgets that only unix code calls, and
in_place's Refusal::Source (made only from a caller's dma-buf source), compile on unix
alone; leaves_rows names the two refusals that keep the rows instead of listing the rest.
Again::pointer returns early so that its Windows form has no closure for clippy to flag.

Verified: Windows clippy at cd6973f432 (job m3-max-31977) listed these errors only.
2026-11-15 05:49:35 -08:00
Anees Iqbal 6267d10c6f CI: clippy of the published crates and devtools for Windows, on Linux
x86_64-pc-windows-gnullvm (the primary Windows target) and x86_64-pc-windows-msvc, with
--all-targets --all-features and warnings denied. Clippy links nothing, so the Linux job
needs only the two targets' standard libraries. AGENTS.md's CI paragraph names the step.

Verified: the same clippy lines ran in potluck jobs on Linux (msi) for both targets.
2026-11-15 05:49:35 -08:00
Anees Iqbal 402135752b Windows: the remaining unix-only imports, the exportable event check and fd tests gated; docs say Windows asks too
dma_buf.rs's exit-guard and release imports, EventShared::carry's check of an exported
semaphore and the memory tests of dma-buf and fd placement compile on unix alone.
The docs of refuse_unwritable's callers now say Windows asks the system as Linux does.

Verified: Windows clippy (gnullvm, msvc) at a571e90d9d reported these errors only.
2026-11-15 05:49:35 -08:00
Anees Iqbal adb6f3c93c devtools: the tool runner's test module on unix hosts only
Its one test runs /bin/sh; on Windows the module held only an unused import.

Verified: Windows clippy (gnullvm and msvc, --all-targets) reported this as the
only error at 438f0c42cb (job m3-max-31946).
2026-11-15 05:49:35 -08:00
Anees Iqbal 3369c52a3c Windows: dead fd/dma-buf helpers unix-only; examples' pages and CPU times on Win32
The fd and dma-buf helpers, fields and test hooks that only unix code reaches are
compiled on unix alone, so the Windows build carries no dead code. The examples'
anonymous pages use VirtualAlloc/VirtualFree/VirtualProtect on Windows and their
thread and process CPU times GetThreadTimes/GetProcessTimes.

Verified: cargo fmt; the Windows and Linux clippy rounds follow as jobs.
2026-11-15 05:49:35 -08:00
Anees Iqbal a9dce911e7 Known gaps: drop the first commit's translation; held_step_order's numbers from a release build
9aadbdf281 rewrote the known gap from the test profile's numbers. A release build of the same
test on the same idle Radeon 780M (RADV PHOENIX, m3-max-31944, 2 processes x 3 runs) puts the first
commit of a host-step pass, which translates the variants its step draws with, at 4.5 and 5.4 ms,
and a later one at 0.11 to 0.19 ms; the unoptimized test build takes 23 to 25 ms and 1.0 to 1.3 ms
there. Nothing measured holds a guest's commit past a frame's 16 ms any more: the 406 and 10.5 ms
were the test build inside a suite that loaded the host's cores. So the known-gap row goes, and
CHANGELOG's known-failing line names only the teardown test. The test's COMMIT doc carries the
release and the test build's numbers.

Docs and a test comment only. Verified: the numbers are m3-max-31944's printouts.
2026-11-15 05:45:35 -08:00
Anees Iqbal a88823f8f4 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 05:39:49 -08:00
Anees Iqbal 88873b27e1 frame_costs: the debug draw bound's note states the kept checks' schedule and the new measurement
The draws of a build with debug assertions no longer build the whole bind shape at each draw
(kept_checks.rs, the commit before): runtime_lane::frame_costs measured 6.24 allocations a draw
on lavapipe (llvmpipe, LLVM 23.1.1) in m3-max-31921 on msi, against the 17.88 its note stated.
The bound (20) stays; the note says what the checks do now.
2026-11-15 05:39:05 -08:00
Anees Iqbal d4846e710b Debug builds check a draw's kept values at their first uses and at powers of two
Builds with debug assertions re-derived four kept values of a render draw at every draw and
compared them with the kept ones: its used resources (refresh_bind_state), its bind shape
(LiveBind::shape, kept and recent paths), its uses of what its encoder made resident
(binding::command_uses_into) and its heap part (render/heap_part.rs). Each is a walk of everything
the encoder made resident, so a recording of n draws over r resident resources walked them n
times in those builds alone.

That is what made runtime_lane::kept_textured time out on the RX 7900 XTX under the suite (pin 99:
two TimedOut at kept_textured.rs:155 after 60 s; pin 93b: all five, with a host step still
recording at exit). Its page is 512 draws over 2048 resident resources (1536 buffers, 512
textures). Measured on the XTX (RADV, Mesa 26.2.6), a host step of those 512 heap draws, alone:
- 2.9 to 3.5 s with the validation layer, 3.0 to 3.2 s without it (VK_LAYER_PATH at an empty
  directory, the device made with no layer): the layer's share is about nothing;
- 140 to 177 ms in the same unoptimized build without debug assertions
  (CARGO_PROFILE_DEV_DEBUG_ASSERTIONS=false), the five tests 1.3 to 2.1 s each against 10.7 to
  14.7 s: the debug-only checks were about 95% of the step;
- of 205 samples of the steps thread at 20 Hz (gdb): HeapPart::check 40%, LiveBind::shape's
  checks 27% (kept 19%, recent 7%), command_uses_into's whole uses 8%, refresh_bind_state's used
  resources 7%.
Beside a suite slice (load 10 to 16) the same steps took 5 to 11 s; with three suites on the
node's 16 threads one passed the test's 60 s wait.

Each of the four kept values now keeps a debug-only count of its uses since it was worked out
(kept_checks::KeptChecks) and is checked at its first 8 uses and then at each use whose count is a
power of two, so a recording walks the resident resources 8 + log2(n) times for each kept value. A
kept value that is wrong stays wrong until a change works it out again, so one that goes wrong
after its first uses is still caught within twice the uses it took (render/draw_again.rs already
checks every second draw again). A found bind shape is still checked at each find. Builds without
debug assertions are unchanged: they compiled none of these checks.

Test: tests::resident_uses::kept_values_are_checked_at_their_first_uses_and_at_powers_of_two
draws 40 draws over one residency and counts 11 kept resident-use checks and 11 kept heap-part
checks (uses 0 to 7, 8, 16 and 32); before this change both counted 39.
2026-11-15 05:39:05 -08:00
Anees Iqbal 9aadbdf281 held_step_order: time Scheduled from the commit's return; hold the commit call to a frame
command_buffers_behind_a_waiting_step_read_scheduled failed 3 of 3 on the Radeon 780M (PHOENIX)
inside the whole device suite (m3-max-31782): the long command buffer's commit returned 405.95,
23.66 and 10.50 ms after its call, and the test bounded the call plus the scheduler's pass to
`Scheduled` by 10 ms together. Scheduled itself came 19.6, 1.6 and 2.3 ms after the commit
returned: the ordering the test is for held.

What holds the call (probes m3-max-31832 and m3-max-31876, gem10's 780M idle, step marks in the
commit path): no pipeline wait (commit_pipeline_wait_nanos 0) and no lowering; Recording,
Deferred::prepare of the host-step pass. Its first commit translates the variants the step draws
with on the program's thread (DeferredPass::settle: the step's buffer forms and the fan-out's,
the route's replay variant; record_on_gpu's decision and, once a device, the notice's rules past
its cause): 24.1 / 23.7 ms cold, 49.8 in an earlier run. A later commit finds them made: 1.0 ms
(2.4 in the earlier run), about 30 lookups of 5 to 35 us, no single repeated item. The suite on
the host's cores stretched the same work about tenfold. The translation cannot move earlier
(whether the pass is a host step and its route are decided at the commit) nor off the program's
thread (the device keeps only what the program's calls make, in its order).

So the test's one bound mixed two properties. Now:
- `Scheduled` is timed from the long commit's return, still within 10 ms (the long work ends
  100 ms or more after it);
- the commit call is asserted apart, by its own clock (WorkCounts::commit_nanos), within a frame's
  16 ms in one of the runs at least (the later runs are warm), the test's own work_counts()
  snapshot outside the timed span.

docs/FAST-PATHS.md's known gap is rewritten to what is measured (the first commit of a host-step
pass translates its step's variants, why it stays there), and CHANGELOG's known-failing line with
it.

Verified: see the lane's report (PHOENIX 5/5, negative control with a sleep in the commit path).
2026-11-15 05:36:51 -08:00
Anees Iqbal ab9103b213 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 05:25:19 -08:00
Anees Iqbal 673d542c39 Windows: the section probe's security feature; tests on Windows forms
- CreateFileMappingW is behind windows-sys's Win32_Security feature (its
  SECURITY_ATTRIBUTES argument).
- Unused-on-Windows bindings gated (NoImage, pointer_refused).
- Tests: the fork test of degradation.rs is unix-only; the host RAM window
  tests take their untouched address space from one helper (mmap
  MAP_NORESERVE, or VirtualAlloc on Windows); a Windows test of the
  calibration's domain (the performance counter's); and a Windows test that
  the exit hook atexit holds runs at exit before the handlers registered
  before it and closes the guard (a child process of the test binary, as
  tests::warm runs one; its handler ends it with 42 where the guard closed).

Verified: a step of the Windows check iteration (gnullvm, msi job). The
Windows tests are compiled, not run: no Windows node runs them yet.
2026-11-15 05:24:38 -08:00
Anees Iqbal b8bb06bcac Windows: host pages, clocks, thread times and exit hook through Win32; pointer residency on every host
Windows forms of the runtime's host facilities, through windows-sys:
- the host page (GetSystemInfo), the process's page permissions
  (VirtualQuery: mapped_readable, mapped_writable, and refuse_unwritable, so
  pages the process cannot write are a copy whose GPU writes are dropped, as
  Metal drops them, counted in host_mappings_queried), and section views
  (MEM_MAPPED) as shared memory for a guest RAM's plan;
- the runtime's own pages (fresh pages, the submission checks' and the
  in-place check's pages: VirtualAlloc/VirtualFree), so those checks run;
- the shared-pointer probe over a view of a paging-file section
  (CreateFileMappingW SEC_COMMIT + MapViewOfFile), as a VMM's Windows guest
  RAM is made;
- the fault-free read of caller pages (ReadProcessMemory);
- a thread's CPU time (GetThreadTimes);
- the host clock on the performance counter, calibrated against
  VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR (gpu_time.rs: host_nanos,
  host_domain, Calibration::reading only);
- the exit guard's hook registered through the C runtime's atexit, one
  handler per kind, where the not(unix) arm registered nothing.

The idle release of pointer imports (host_residency) is structural, decided by
the device's submission checks, so its pointer form runs on every host; only
its dma-buf form is unix-only. A guest RAM's dma-buf sources are absent on
Windows (cfg(unix) builders; no source exists, so the RAM's dma-buf paths are
uninhabited there). Buffers report exported memory through memory_exported,
false where the system has no file descriptors to export.

Linux and macOS: the cfg(unix) residency gates removed are always true there;
in_place_check's host page now reads host_memory::host_page (sysconf), as its
own copy did.

Verified: a step of the Windows check iteration (gnullvm, msi job).
2026-11-15 05:24:38 -08:00
Anees Iqbal 4c6a29c409 Windows: dma-buf items unix-only; dirty pages, residency and rotation on every host
The runtime's first Windows check stopped at its module tree: dma_buf.rs
takes file descriptors (std::os::fd) unconditionally, while dirty_pages,
host_residency and texture/rotation were unix-only modules that every host's
code names.

- dma_buf.rs: every item that holds or makes a file descriptor (the
  sources, requests and chunks, the imports of dma-bufs and their pages,
  images bound to them, exported pages) is cfg(unix). The DRM-modifier image
  items that hold none (ModifierMemory, the explicit-plane and natural-layout
  checks, the format queries) stay on every host: their extension decides at
  run time.
- dirty_pages and texture/rotation hold no unix code: on every host.
- host_residency: the descriptor limit (RLIMIT_NOFILE), the dma-buf form of
  an import made again and its descriptor counts are unix-only; the pointer
  form and the sweeps stay on every host.
- devtools' scratch lock: the file identity on Windows is the volume serial
  number and file index (GetFileInformationByHandle) in place of dev/ino.

Verified: a step of the Windows check iteration (gnullvm, msi job).
2026-11-15 05:24:38 -08:00
Anees Iqbal c40358858a runtime: libc on unix hosts only, windows-sys on Windows
The runtime's host facilities (pages, clocks, threads, exit handlers) are
libc's on unix. Windows has none of libc's there, so libc becomes a
cfg(unix) dependency and the Windows forms come from windows-sys (MIT OR
Apache-2.0, a GPL-2.0-compatible option), a workspace dependency with the
features the runtime's Windows forms call.

Verified: dependency resolution in the Windows check job that follows.
2026-11-15 05:24:38 -08:00
Anees Iqbal d25f77ecb1 queue_order: the taken-up rounds time the scheduler's thread from the holder's let-go, its wait for a core apart
checked_commits_during_submissions_are_taken_up_promptly failed on the RX 7900 XTX under the full
suite with two other GPUs' suites on the same 16-thread host (pin 99 legs, um790 job m3-max-31769):
round 2 took its two left command buffers 23.6 ms and 55.5 ms after the release, the thread's
"own" time 18.1/46.0 ms against a 40 ms bound, while the thread had waited 25.8/46.8 ms of it on
the host's run queue (schedstat): ready to run, kept from a core by the host's load, not by its
own work.

What: each round's take-up is now timed from the instant the round's holder lets go of the
VkQueue (noted as the last step of its with_vk_queue closure, with the scheduler thread's
schedstat read there, where that thread waits for the VkQueue off the run queue), not from the
instant the test sent the release: the holder thread's own wake under load (it must get a core to
unlock) was charged to the scheduler's thread as blocked time. The bound (unchanged, 40 ms) now
applies to the take-up less the LONGER of the driver's vkQueueSubmit time and the thread's
run-queue wait: the two may overlap, so their sum is never taken out, and the measure is never
below the thread's own time. The take's schedstat is read before its instant and the let-go's
after, so a wait between the reads stays in our time. Each round now also prints the thread's
time on a core and its sleeps at each take, and the holder's latency from the release to its
let-go, so a failure still left says whether the thread ran, was blocked, or slept.

Why the model changed (the measured split): in 31769, round 2 is all run queue (its wait at
least its "own" time). The slowest round there, 19 (taken 102.5/135.4 ms, run queue 38.2/57.0,
driver 0.9/6.7), left 63-72 ms that is neither; that it was the holder's wake is INFERRED, not
measured: the old print had no holder latency, CPU time or sleeps. A diagnostic build of the old
test with those prints (branch steelbrain/qorder-diag, 1fa4226bdf, not for landing), 40 rounds a
run, 2 alone and 3 beside a runtime-lane partition (load average 6-16): on the RX 7900 XTX
(m3-max-31849) every round made 2 then 3 passes, 0 sleeps and 0 wakings between the release and
its takes, the thread on a core at most 1.65 ms, taken at most 2.0 ms alone and 10.4 ms loaded
(8.35 ms of it run queue); on the Radeon 780M PHOENIX (m3-max-31841) the same steps, taken at
most 22.1 ms loaded (22.6 ms run queue at most, thread on a core 9.4 ms). No lost wake and no
slow own work in what ran.

Verified: see the lane report (the XTX proof job: alone, and beside a runtime-lane partition on
6 pinned cores against the old binary).
2026-11-15 05:20:00 -08:00
Anees Iqbal fac976c772 Re-pin the runtime sources at the landing tip
The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-11-15 05:19:46 -08:00
Anees Iqbal 7ba0cd9fe6 RUNTIME 2343: GPU times placed by a calibration still beyond 20 us are announced and counted
A calibration pair is read again while the smallest deviation so far
states more than 20 us (`gpu_time::SETTLED`), four readings at most
(`least_deviation`). Where the least of four still stated more (93 and
125 us on the RX 7900 XTX under full parallel suites: a reading's
deviation holds the time its thread spent off the CPU), the runtime
placed the command buffer's GPU times by it, inside the command
buffer's life, with up to that error, and said nothing. Owner rule 2:
a near-equivalent is recorded and announced.

`GpuClock::span` now answers `Placement::Loose { deviation }` where the
pair places both times inside the life and its deviation exceeds
`SETTLED` (a pair outside the life is still set aside as before).
`Placement::read` gives the notice for every placement the first read
of a command buffer's GPU times announces, counting a loose one:
- new kind `Degradation::LooselyCalibratedGpuTimes`,
  `loosely-calibrated-gpu-times`, class Precision, announced once per
  device at the read (the site `uncalibrated-gpu-times` uses), its
  reason stating the deviation; not `uncalibrated-gpu-times`, whose
  cost says the times are placed by the completion, where these are
  the pair's, the duration exact;
- new `WorkCounts::loosely_calibrated_gpu_times`: command buffers
  whose times a read found placed so, counted at the read that
  announces, so the count is nonzero exactly where the kind was
  announced.

Tests: `tests::gpu_time::a_pair_still_beyond_the_settled_deviation_is_
announced_once_and_counted` feeds `least_deviation` a fake source of
four readings above 20 us (Loose, the kind with the deviation in its
reason, each read counted, announced once) and settled ones (Iris
Xe's 165 then 7.6 us; 20 us exactly: Calibrated, nothing), and a loose
pair outside the life (Disagreed, the uncalibrated kind, not counted).
The lane's `gpu_times` expects the kind exactly where counted, and holds
the count nonzero exactly where `calibration_deviation_most` exceeds
the slack (no disagreement); `read_kinds` adds it where counted
(mesh_draws), `disagreeable_kinds` allows it (first_use); a site const
`LOOSE_GPU_TIMES` takes it. The conformance cases that read GPU times
(`command-buffer-facts`, `empty-command-buffers`) allow its notice:
the host's load decides it, and every value still compares exactly.

docs/API.md's catalogue lists the kind; api_signatures.tsv blessed.
2026-11-15 05:18:59 -08:00
693 changed files with 84054 additions and 13026 deletions

No files matched your search

+22
View File
@@ -77,6 +77,15 @@ threads-required = 'num-test-threads'
filter = 'package(metal2vulkan-runtime) & test(/^tests::queue_share_device::(a_compositor_beside_a_long_queue_keeps_its_latency_once_that_queue_went_long|an_unshared_compositor_beside_a_long_queue_never_stalls)$/)'
threads-required = 'num-test-threads'
# The runtime's GPU-start test of a command buffer's own long work runs alone. It holds the time
# from the command buffer's kernel end to its GPU start under half its life, a bound the GPU's
# queue sets: other test processes' work on the same GPU runs first. In an RTX 5080 Laptop GPU's
# whole runtime suite the start came 14.5 ms after the kernel end, of a 25.8 ms life, where the
# 64 dispatches' GPU span of 11.2 ms still held the work.
[[profile.default.overrides]]
filter = 'package(metal2vulkan-runtime) & test(/^tests::start_stamp::a_command_buffer_s_gpu_start_comes_before_its_own_long_work$/)'
threads-required = 'num-test-threads'
# The runtime's teardown test of the queue-switch check runs alone. It holds the teardown's wait
# for the check (its stop at the next step, its release of its Vulkan objects and of its shares)
# under the 16 ms the owner allows a wait. On an RTX 5080 Laptop GPU (NVIDIA 615.71.09) that wait
@@ -86,6 +95,19 @@ threads-required = 'num-test-threads'
filter = 'package(metal2vulkan-runtime) & test(/^tests::teardown_threads::a_running_queue_switch_check_leaves_the_device_to_the_program_s_thread$/)'
threads-required = 'num-test-threads'
# The runtime's test of command buffers made `Scheduled` behind a waiting host step runs alone. It
# holds the long command buffer's commit call under the 16 ms the owner allows a wait in one of its
# runs at least, by the call's own clock. That call is recording on the program's thread alone (no
# pipeline wait, no wait for the scheduler's lock, no submission): on a Radeon 780M (RADV PHOENIX,
# Ryzen 7 7840HS) its later calls took 1.1 to 1.2 ms in the unoptimized test build with the GPU to
# itself, 0.10 to 0.26 ms in a release build. Beside the device suite's other processes (load
# average 14 on 16 threads) the same work took many times the CPU time and waited for a CPU too:
# 10.7 and 16.3 ms in the test build (8.2 and 10.4 ms of them on a CPU), and up to 38 ms in the
# rounds' runs; 5.8 and 7.0 ms in a release build (4.7 and 7.3 ms on a CPU).
[[profile.default.overrides]]
filter = 'package(metal2vulkan-runtime) & test(/^tests::held_step_order::command_buffers_behind_a_waiting_step_read_scheduled$/)'
threads-required = 'num-test-threads'
# The lane's index pool handler test runs alone. Each round holds a command buffer's completed
# handler to less than half a block's making after the command buffer completed: a handler that
# waited for the making ran as it ended. That bound is a thread's wake on the host's CPUs, which
+14
View File
@@ -121,6 +121,20 @@ jobs:
CARGO_TARGET_DIR: target/gpucfg
run: cargo clippy --workspace --all-targets --all-features -- -D warnings
# The published crates (and devtools, which their tests use) for Windows, checked from Linux:
# clippy links nothing, so neither target needs a Windows SDK or linker. gnullvm is the
# primary Windows target, msvc the second.
- name: Clippy for Windows (warnings denied, Linux)
if: runner.os == 'Linux'
run: |
set -euo pipefail
rustup target add x86_64-pc-windows-gnullvm x86_64-pc-windows-msvc
for target in x86_64-pc-windows-gnullvm x86_64-pc-windows-msvc; do
echo "::group::$target"
cargo clippy --target "$target" -p metal2vulkan-air -p metal2vulkan -p metal2vulkan-runtime -p metal2vulkan-devtools --all-targets --all-features -- -D warnings
echo "::endgroup::"
done
- name: Build public documentation (warnings denied)
env:
RUSTDOCFLAGS: -Dwarnings
+3 -2
View File
@@ -232,8 +232,9 @@ cargo test --workspace --all-features --doc
([docs/VALIDATION.md](docs/VALIDATION.md)).
- CI (`.github/workflows/ci.yml`) runs on `ubuntu-26.04` and `macos-26` (never `*-latest`): format,
clippy (all features, each feature alone, `--cfg m2v_gpu`), Rustdoc, the API reference check
(`scripts/api-docs`), packaging, the suites, doctests, and on Linux the device tests and public
case qualification on lavapipe.
(`scripts/api-docs`), packaging, the suites, doctests, and on Linux clippy of the published
crates and devtools for `x86_64-pc-windows-gnullvm` and `x86_64-pc-windows-msvc`, the device
tests and public case qualification on lavapipe.
When chasing a hang, read the whole nextest output; do not pipe it through `head` or `grep`.
+3 -3
View File
@@ -22,9 +22,9 @@ A full rewrite: nothing of 0.1.0's API or command line remains.
- **Validation tooling** (unpublished): authored cases run on Metal and on Vulkan and compared,
plus bounded audits over a private corpus.
- **License**: dual-licensed `GPL-2.0-or-later OR LGPL-3.0-or-later`; 0.1.0 was `LGPL-3.0-or-later`.
- **Known failing**: two latency tests fail on some GPUs: a commit can hold the program's thread
past 16 ms (a Radeon 780M), and a device's teardown can wait past 16 ms for its queue-switch
check (an RTX 2080). Both are open gaps in [docs/FAST-PATHS.md](docs/FAST-PATHS.md#known-gaps).
- **Known failing**: a latency test fails on some GPUs: a device's teardown can wait past 16 ms for
its queue-switch check (an RTX 2080), an open gap in
[docs/FAST-PATHS.md](docs/FAST-PATHS.md#known-gaps).
## 0.1.0
+2
View File
@@ -29,6 +29,8 @@ repository = "https://github.com/steelbrain/metal2vulkan"
# Never the loader at build time: a crate that opens it adds `loaded`.
ash = { version = "0.38", default-features = false }
libc = "0.2"
# The Windows forms of the host facilities (pages, clocks, threads); MIT OR Apache-2.0.
windows-sys = "0.61"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# SHA-256 on the CPU's own instructions where it has them (ARMv8's SHA2 extension, x86's SHA-NI),
+5 -2
View File
@@ -81,7 +81,8 @@ metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json
- `--profile` is required: the crate ships no device description. Any Khronos profiles JSON works;
[`crates/metal2vulkan-validation/profiles/`](crates/metal2vulkan-validation/profiles) has
examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK.
examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK. `--device FILE` takes its
place with the `device.json` a runtime repro bundle holds (a device description and policy).
- Without `--function` it compiles the library's only kernel or vertex function. A kernel with
`--color-format` compiles as a tile pipeline. A post-tessellation vertex function adds
`.tesc.spv` and `.tese.spv` modules on a device with `tessellationShader`; on one without, it is
@@ -97,7 +98,9 @@ metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json
`METAL2VULKAN_SPIRV_VAL`.
- Success prints a line with `PASS` and exits 0. Failure prints `metal2vulkan: FALLBACK (<why>)`,
writes nothing, and exits 2; a failure after the inputs are read also writes a repro bundle
under `$TMPDIR/metal2vulkan-repros` (or `METAL2VULKAN_REPRO_DIR`).
under `$TMPDIR/metal2vulkan-repros` (or `METAL2VULKAN_REPRO_DIR`), whose `repro.sh` replays it.
metal2vulkan-runtime writes the same bundle for a creation it refuses where
`METAL2VULKAN_REPRO_DIR` is set.
- `metal2vulkan --help` lists every option.
## Library
@@ -1,7 +1,7 @@
//! Devirtualization tests over IR built with the typed test builder: calls through visible-function
//! tables and through constant function addresses.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use super::*;
use crate::abi::{
@@ -130,6 +130,7 @@ fn request() -> SpecRequest {
SpecRequest {
call_stack_depth: 1,
open_cl_mode: false,
open_cl_lines: BTreeSet::new(),
entry: "k".into(),
constants: BTreeMap::new(),
}
@@ -4,7 +4,7 @@
//! the search order, a library's own calls binding to its own definitions, a variable shared by
//! every reference, the refusals of what is missing or not loaded.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use super::*;
use crate::abi::{
@@ -311,6 +311,7 @@ fn request() -> SpecRequest {
SpecRequest {
call_stack_depth: 1,
open_cl_mode: false,
open_cl_lines: BTreeSet::new(),
entry: "k".into(),
constants: BTreeMap::new(),
}
+40 -2
View File
@@ -14,8 +14,10 @@
//! operation whose result would be poison (division by zero, an oversized shift, an out-of-range
//! element), is left unfolded. A fold never guesses: `None` means "not a constant here".
//!
//! The static-initializer interpreter alone also evaluates the basic float operations where
//! every IEEE 754 evaluation agrees ([`Folder::static_float_binop`]): a static initializer is the
//! The static-initializer interpreter alone also evaluates the integer operations, comparisons
//! and casts over each lane of a constant vector ([`Folder::lanewise`]), and the basic float
//! operations where every IEEE 754 evaluation agrees ([`Folder::static_float_binop`]): a static
//! initializer is the
//! deferred form of an MSL constant expression, which the pipeline build evaluates once, before any
//! entry runs, not the device's per-invocation arithmetic.
@@ -965,6 +967,42 @@ impl Folder<'_> {
self.mk_int(to, r, m)
}
/// A scalar fold over each lane of a vector: `fold` of lane `i` of `a` and of `b` (each of
/// its own vector type, `zeroinitializer` expanded) typed as `ty`'s element, collected into a
/// constant of the vector type `ty`; for a scalar `ty`, `fold` of `a` and `b` themselves.
/// `None` when an operand's lanes are not known constants of `ty`'s lane count, or a lane
/// does not fold. A unary fold reads `a` and ignores `b`.
pub fn lanewise(
&mut self,
ty: TypeId,
a: ConstId,
b: ConstId,
m: &mut Meter,
fold: impl Fn(&mut Self, TypeId, ConstId, ConstId, &mut Meter) -> Result<Option<ConstId>, Error>,
) -> Result<Option<ConstId>, Error> {
let Some(&Type::Vector { elem, len }) = self.types.get(ty) else {
return fold(self, ty, a, b, m);
};
self.transient(m, |f, m| {
let (Some(xs), Some(ys)) = (f.members(a, m)?, f.members(b, m)?) else {
return Ok(None);
};
let n = usize::try_from(len).unwrap_or(usize::MAX);
if xs.len() != n || ys.len() != n {
return Ok(None);
}
let mut out = Vec::with_capacity(n);
for (x, y) in xs.into_iter().zip(ys) {
match fold(f, elem, x, y, m)? {
Some(c) => out.push(c),
None => return Ok(None),
}
}
f.mk(ty, Const::Aggregate(out.into_boxed_slice()), m)
.map(Some)
})
}
/// `extractelement vec, idx`.
pub fn extract_element(
&mut self,
+2 -1
View File
@@ -9,7 +9,8 @@
//! Generic pointers that must share a type share a space: a `getelementptr`, `bitcast`,
//! `addrspacecast` or `freeze` of a generic pointer and its operand, a `phi` or `select` and its
//! operands, the two sides of an `icmp`, the generic pointers stored into and loaded from one
//! slot of thread memory whose every access the translation sees ([`cells`]), and a generic
//! slot of thread memory whose every access the translation sees, and a slot and the slot a copy
//! of its bytes moves it to ([`cells`]), and a generic
//! pointer an aggregate or a vector value holds (a *leaf*) and what it comes from ([`leaves`]).
//! The links are the union-find of [`plan()`]. Each such group has one space where every pointer
//! entering it does:
@@ -23,9 +23,19 @@
//! address stored as a value into a slot not followed, cast to an integer or to another space,
//! passed to another call, merged by a `phi` or a `select`, or held in an aggregate), or where
//! bytes other than a generic pointer's may be read as one: two slots overlap, a write of
//! anything else (a store of another type, an atomic operation, a copy or a `memset`) overlaps a
//! slot or writes bytes the translation cannot place, or a generic access at an unknown offset
//! meets any such write.
//! anything else (a store of another type, an atomic operation, a copy other than a slot copy or
//! a `memset`) overlaps a slot or writes bytes the translation cannot place, or a generic access
//! at an unknown offset meets any such write.
//!
//! A *slot copy* is a `memcpy` or `memmove` of a translation-time constant length from one
//! `alloca` at a constant offset to another, as a struct holding a generic pointer is copied
//! whole. It moves each slot of the source that the copied bytes hold whole to the destination,
//! at the same distance from the copy's start: the destination slot takes the source slot's
//! pointers, and a chain of copies moves a slot along it (a destination that held none becomes a
//! cell). It is a slot copy only where neither cell has a generic access at an unknown offset, no
//! slot of either holds bytes on both sides of either end of the copied bytes, every slot of the
//! destination inside them is a moved one, and the source is not open; its other bytes are then
//! data copied onto data. Any other copy writes its bytes, as above.
//!
//! [`GenericPointer::Memory`]: crate::error::GenericPointer::Memory
@@ -65,6 +75,9 @@ pub(super) struct Cells {
pub slots: usize,
/// Slots in one group: an access at an unknown offset and each slot of its cell.
pub links: Vec<(u32, u32)>,
/// The slots slot copies move: each destination slot, which takes the pointers of the
/// source slot that follows it.
pub moves: Vec<(u32, u32)>,
}
impl Cells {
@@ -511,6 +524,38 @@ fn cells(
if generic.is_empty() {
return Ok(None);
}
for &(_, c, off) in &generic {
let cell = table
.get_mut(c as usize)
.ok_or_else(|| invariant("a cell out of range"))?;
match off {
Some(o) => {
m.reserve(&mut cell.slots, 1)?;
*held = held.saturating_add(std::mem::size_of::<u64>());
cell.slots.push(o);
}
None => cell.anywhere = true,
}
}
for cell in &mut table {
m.tick(1)?;
cell.slots.sort_unstable();
cell.slots.dedup();
}
// A generic pointer's bytes.
let width = u64::from(
cx.parts
.data_layout
.pointer(AddrSpace::Generic.raw())
.size_bits
.div_ceil(8),
);
let mut copies = slot_copies(cx, &at, m, held)?;
moved_slots(&copies, (&mut index, &mut table), width, m, held)?;
for c in &mut copies {
m.tick(1)?;
c.moves = moves(c, (&index, &table), width);
}
// The cell an address is in, and its offset there.
let cell_of = |v: Value| -> Option<(u32, Option<u64>)> {
let (a, off) = at(v)?;
@@ -523,8 +568,14 @@ fn cells(
})
};
let mut failed = None;
for inst in cx.body.insts.values() {
for (i, inst) in cx.body.insts.iter() {
m.tick(1)?;
if copies
.binary_search_by_key(&i, |c| c.call)
.is_ok_and(|k| copies.get(k).is_some_and(|c| c.moves))
{
continue;
}
uses(cx, layouts, (&inst.kind, inst.ty), &exempt, |u| {
let (v, write) = match u {
Use::Escape(v) => (v, None),
@@ -553,27 +604,33 @@ fn cells(
return Err(e);
}
}
for &(_, c, off) in &generic {
let cell = table
.get_mut(c as usize)
.ok_or_else(|| invariant("a cell out of range"))?;
match off {
Some(o) => {
m.reserve(&mut cell.slots, 1)?;
*held = held.saturating_add(std::mem::size_of::<u64>());
cell.slots.push(o);
for cell in &mut table {
m.tick(1)?;
cell.open |= !disciplined(cell, width);
}
// A copy from an open cell moves no slot: it writes bytes the translation cannot read as
// pointers, which may open its destination, and so on along a chain.
let mut changed = true;
while changed {
changed = false;
for c in &mut copies {
m.tick(1)?;
let (s, d) = (cell_at(&index, c.src.0), cell_at(&index, c.dst.0));
let src_open = s.and_then(|s| table.get(s)).is_some_and(|x| x.open);
if !(c.moves && src_open) {
continue;
}
c.moves = false;
changed = true;
if let Some(cell) = d.and_then(|d| table.get_mut(d)) {
m.reserve(&mut cell.writes, 1)?;
*held = held.saturating_add(std::mem::size_of::<Option<(u64, u64)>>());
cell.writes
.push(c.dst.1.checked_add(c.len).map(|hi| (c.dst.1, hi)));
cell.open |= !disciplined(cell, width);
}
None => cell.anywhere = true,
}
}
// A generic pointer's bytes.
let width = u64::from(
cx.parts
.data_layout
.pointer(AddrSpace::Generic.raw())
.size_bits
.div_ceil(8),
);
// Slot nodes: each cell's distinct offsets, then one for an access at an unknown offset.
let mut first: Vec<u32> = Vec::new();
m.reserve(&mut first, table.len())?;
@@ -582,9 +639,6 @@ fn cells(
let mut links = Vec::new();
for cell in &mut table {
m.tick(1)?;
cell.slots.sort_unstable();
cell.slots.dedup();
cell.open |= !disciplined(cell, width);
first.push(slots);
let count = u32::try_from(cell.slots.len() + usize::from(cell.anywhere))
.map_err(|_| invariant("slots past u32"))?;
@@ -624,13 +678,205 @@ fn cells(
};
reach.push((i, node));
}
// Each slot a copy moves, by node: the destination's takes the source's.
let node = |a: u32, o: u64| -> Option<u32> {
let c = cell_at(&index, a)?;
let k = table.get(c)?.slots.binary_search(&o).ok()?;
first.get(c)?.checked_add(u32::try_from(k).ok()?)
};
let mut moved = Vec::new();
for c in copies.iter().filter(|c| c.moves) {
let Some(src) = cell_at(&index, c.src.0).and_then(|s| table.get(s)) else {
continue;
};
for &o in &src.slots {
m.tick(1)?;
let Some(t) = c.image(o, width) else { continue };
let (to, from) = node(c.dst.0, t)
.zip(node(c.src.0, o))
.ok_or_else(|| invariant("a moved slot not found"))?;
m.reserve(&mut moved, 1)?;
*held = held.saturating_add(std::mem::size_of::<(u32, u32)>());
moved.push((to, from));
}
}
give_back(m, held, copies);
Ok(Some(Cells {
reach,
slots: slots as usize,
links,
moves: moved,
}))
}
/// A `memcpy` or `memmove` of a translation-time constant length from one `alloca` at a constant
/// offset to another: the call, the destination's `alloca` and offset, the source's, the length,
/// and whether it is a *slot copy*, which moves the source's slots to the destination, or writes
/// its bytes as any other copy does.
struct SlotCopy {
call: InstId,
dst: (u32, u64),
src: (u32, u64),
len: u64,
moves: bool,
}
impl SlotCopy {
/// Where the copy puts source slot `o`, where the copied bytes hold it whole.
fn image(&self, o: u64, width: u64) -> Option<u64> {
let (_, lo) = self.src;
let hi = lo.checked_add(self.len)?;
let end = o.checked_add(width)?;
if o < lo || end > hi {
return None;
}
self.dst.1.checked_add(o - lo)
}
}
/// The cell of `alloca` `a`, if it is one.
fn cell_at(index: &[u32], a: u32) -> Option<usize> {
let c = *index.get(a as usize)?;
(c != NONE).then_some(c as usize)
}
/// The `memcpy`s and `memmove`s of a translation-time constant length from one `alloca` at a
/// constant offset to another, in instruction order.
fn slot_copies(
cx: &Cx<'_>,
at: &dyn Fn(Value) -> Place,
m: &mut Meter,
held: &mut usize,
) -> Result<Vec<SlotCopy>, Error> {
let mut copies = Vec::new();
for (i, inst) in cx.body.insts.iter() {
m.tick(1)?;
let InstKind::Call(call) = &inst.kind else {
continue;
};
let (
Callee::Llvm {
op: LlvmIntrinsic::Memcpy { .. } | LlvmIntrinsic::Memmove { .. },
..
},
[dst, src, len, ..],
) = (&call.callee, &*call.args)
else {
continue;
};
let (Some((a, Some(d))), Some((b, Some(s))), Some(len)) =
(at(*dst), at(*src), int(cx.parts, *len))
else {
continue;
};
if a == b {
continue;
}
m.reserve(&mut copies, 1)?;
*held = held.saturating_add(std::mem::size_of::<SlotCopy>());
copies.push(SlotCopy {
call: i,
dst: (a, d),
src: (b, s),
len,
moves: false,
});
}
Ok(copies)
}
/// Give each copy's destination the slots of its source that the copied bytes hold whole, at
/// the same distance from the copy's start, until no copy adds one: a chain of copies moves a
/// slot along it. A destination that held no slot becomes a cell.
fn moved_slots(
copies: &[SlotCopy],
(index, table): (&mut [u32], &mut Vec<Cell>),
width: u64,
m: &mut Meter,
held: &mut usize,
) -> Result<(), Error> {
let mut changed = true;
while changed {
changed = false;
for c in copies {
m.tick(1)?;
let Some(src) = cell_at(index, c.src.0).and_then(|s| table.get(s)) else {
continue;
};
let mut moved: Vec<u64> = Vec::new();
for &o in &src.slots {
m.tick(1)?;
if let Some(t) = c.image(o, width) {
m.reserve(&mut moved, 1)?;
*held = held.saturating_add(std::mem::size_of::<u64>());
moved.push(t);
}
}
if moved.is_empty() {
continue;
}
let slot = index
.get_mut(c.dst.0 as usize)
.ok_or_else(|| invariant("an alloca out of range"))?;
if *slot == NONE {
*slot = u32::try_from(table.len()).map_err(|_| invariant("cells past u32"))?;
m.reserve(table, 1)?;
*held = held.saturating_add(std::mem::size_of::<Cell>());
table.push(Cell::default());
}
let dst = table
.get_mut(*slot as usize)
.ok_or_else(|| invariant("a cell out of range"))?;
for &t in &moved {
if let Err(k) = dst.slots.binary_search(&t) {
m.reserve(&mut dst.slots, 1)?;
*held = held.saturating_add(std::mem::size_of::<u64>());
dst.slots.insert(k, t);
changed = true;
}
}
give_back(m, held, moved);
}
}
Ok(())
}
/// Whether copy `c` is a slot copy: neither cell has a generic access at an unknown offset, no
/// slot of either holds bytes on both sides of either end of the copied bytes, and each slot of
/// the destination inside them is the image of a slot of the source, so every generic pointer the
/// destination's slots read there is one the source's slots held.
fn moves(c: &SlotCopy, (index, table): (&[u32], &[Cell]), width: u64) -> bool {
let cell = |a: u32| cell_at(index, a).and_then(|k| table.get(k));
let (Some(src), Some(dst)) = (cell(c.src.0), cell(c.dst.0)) else {
return false;
};
if src.anywhere || dst.anywhere {
return false;
}
if straddles(&src.slots, c.src.1, c.len, width) || straddles(&dst.slots, c.dst.1, c.len, width)
{
return false;
}
let (lo, hi) = (c.dst.1, c.dst.1.saturating_add(c.len));
let from = dst.slots.partition_point(|&t| t < lo);
dst.slots
.get(from..)
.unwrap_or_default()
.iter()
.take_while(|&&t| t < hi)
.all(|&t| src.slots.binary_search(&(t - lo + c.src.1)).is_ok())
}
/// Whether a slot of `slots` (sorted) holds bytes on both sides of either end of the `len` bytes
/// at `lo`.
fn straddles(slots: &[u64], lo: u64, len: u64, width: u64) -> bool {
let across = |x: u64| {
let k = slots.partition_point(|&s| s.saturating_add(width) <= x);
slots.get(k).is_some_and(|&s| s < x)
};
across(lo) || across(lo.saturating_add(len))
}
/// A use of an address other than a generic access, address arithmetic, a read or a comparison.
enum Use {
/// The address leaves the uses the translation sees.
@@ -4,7 +4,8 @@
//! The union-find's nodes are the instructions, then the slots of thread memory generic pointers
//! pass through ([`cells`]), then the leaves of the aggregate and vector values that hold them
//! ([`leaves`]). Nullness flows along the same links, from a value to what takes it: an operand to
//! the address it derives, a stored value to its slot and the slot to its loads, an inserted value
//! the address it derives, a stored value to its slot and the slot to its loads and to the slots
//! copies move it to, an inserted value
//! or an aggregate's leaf to the leaf that takes it.
//!
//! [`leaves`]: super::leaves
@@ -360,6 +361,11 @@ pub(super) fn plan(cx: &Cx<'_>, m: &mut Meter, held: &mut usize) -> Result<Optio
g.takes(a, b, m)?;
g.takes(b, a, m)?;
}
// A slot a copy moves to takes the slot it moves from.
for &(to, from) in cells.as_ref().map_or(&[][..], |c| &c.moves[..]) {
let (to, from) = (g.slot(to), g.slot(from));
g.takes(to, from, m)?;
}
// Each group's space: the join of what enters each of its members.
let mut group: Vec<Space> = filled(m, held, nodes, Space::Unseen)?;
for node in 0..nodes {
+130 -34
View File
@@ -9,9 +9,12 @@
//!
//! **Absent outputs**. An output gated off is not part of the specialized function: it leaves the
//! entry point's outputs, and the returned struct keeps its field, which no interface variable
//! receives. Each remaining output names its field. Two remaining color outputs at one color
//! attachment and one blend index are an invalid request (`RequestError::DuplicateColorOutput`):
//! Metal refuses such a specialization when it makes the function.
//! receives. The field is inserted `undef`, so what only computed its value goes
//! ([`unobserved_code`]): a parameter read only into it, such as a vertex attribute, is not read
//! (Metal reports such an attribute inactive). Each remaining output names its field. Two
//! remaining color outputs at one color attachment and one blend index are an invalid request
//! (`RequestError::DuplicateColorOutput`): Metal refuses such a specialization when it makes the
//! function.
//!
//! **Absent arguments**. The LLVM parameter of an argument gated off stays, and the body may still
//! read it (SCCP deletes the reads its own constants guard, not every dead one).
@@ -979,8 +982,14 @@ fn absent_values(
/// allocation, and a terminator are never [`value_only`] or deferred, so the observation starts
/// from them and they stay. A [`value_only`] instruction the observation observes is read by an
/// instruction that stays, or only by the address of a write it deletes; one it does not observe
/// stays only where an instruction that stays reads it (the part of a returned struct no output
/// stores). The body stays valid, and nothing any output, side effect, or branch sees changes.
/// stays only where an instruction that stays reads it: an `insertvalue` of the returned struct's
/// chain, which builds a field no output stores or a later insert sets again. Such an insert stays
/// and inserts `undef` in place of a value the observation does not observe ([`unread_inserts`]),
/// so what computed that value, a parameter's read included, goes with it: the specialized function
/// reads nothing for a field it does not output, as Metal's reads nothing for a gated-off output
/// (Metal reports a vertex attribute that reaches only such an output inactive, and makes the
/// pipeline from a vertex descriptor without it). The body stays valid, and nothing any output,
/// side effect, or branch sees changes.
///
/// Specialization leaves such code where it deletes uses: SCCP removes the uses its constants
/// guard, and an absent argument's unobserved reads take `undef`, so an absent texture table's
@@ -1009,7 +1018,7 @@ pub(super) fn unobserved_code(
let n = body.insts.len();
let gone_bytes = n * std::mem::size_of::<bool>();
m.charge(gone_bytes)?;
let gone = {
let marked = {
let mut private = Private::new(body, &parts.types, &parts.consts, params, &layouts, m)?;
let observed = observation(
body,
@@ -1018,7 +1027,7 @@ pub(super) fn unobserved_code(
&mut private,
m,
);
let gone = observed.and_then(|(o, bytes)| {
let marked = observed.and_then(|(o, bytes)| {
let mut gone = vec![false; n];
for (id, inst) in body.insts.iter() {
m.tick(1)?;
@@ -1027,26 +1036,18 @@ pub(super) fn unobserved_code(
*g = value_only(&inst.kind) || (!seen && private.deferred(id));
}
}
let unread = unread_inserts(body, params, &o, m);
m.release(bytes);
Ok(gone)
Ok((gone, unread?))
});
private.release(m);
gone
marked
};
m.release(parts.types.len() * std::mem::size_of::<Option<Layout>>());
let rebuilt = gone.and_then(|mut gone| {
if !kept_reads(body, &mut gone, m)? {
return Ok(None);
}
scoped(m, |m, held| {
let mut edit = BodyEdit::keep_all(body, m, held)?;
for (i, g) in gone.iter().enumerate() {
if *g {
edit.delete(InstId::new(u32::try_from(i).map_err(|_| invariant("ids"))?));
}
}
apply(body, &edit, &|c| c, m).map(Some)
})
let rebuilt = marked.and_then(|(gone, unread)| {
let r = without_unobserved(body, gone, &unread, &mut parts.consts, m);
m.release(unread.len() * std::mem::size_of::<(InstId, TypeId)>());
r
});
m.release(gone_bytes);
rebuilt?
@@ -1063,10 +1064,62 @@ pub(super) fn unobserved_code(
Ok(())
}
/// `body` without the instructions `gone` marks for deletion that no instruction that stays reads
/// ([`kept_reads`]), each insert of `unread` that stays inserting `undef` of its value's type in
/// place of its value; `None` where that deletes and rewrites nothing.
fn without_unobserved(
body: &Body,
mut gone: Vec<bool>,
unread: &[(InstId, TypeId)],
consts: &mut ConstTable,
m: &mut Meter,
) -> Result<Option<Body>, Error> {
let deletes = kept_reads(body, &mut gone, unread, m)?;
let mut undef = Vec::new();
for &(id, ty) in unread {
m.tick(1)?;
if gone.get(id.index()).copied().unwrap_or(true) {
continue;
}
let value = Const::Undef;
undef.push((id, consts.intern(Constant { ty, value }, m)?));
}
if !deletes && undef.is_empty() {
return Ok(None);
}
scoped(m, |m, held| {
let mut edit = BodyEdit::keep_all(body, m, held)?;
for (i, g) in gone.iter().enumerate() {
if *g {
edit.delete(InstId::new(u32::try_from(i).map_err(|_| invariant("ids"))?));
}
}
for (id, c) in undef {
if let Some(InstKind::InsertValue { agg, indices, .. }) =
body.insts.get(id).map(|x| &x.kind)
{
let kind = InstKind::InsertValue {
agg: *agg,
val: Value::Const(c),
indices: indices.clone(),
};
edit.rewrite.insert(id, kind);
}
}
apply(body, &edit, &|c| c, m).map(Some)
})
}
/// Keep, among the instructions `gone` marks for deletion, every one an instruction that stays
/// reads (transitively), so no surviving use names a deleted instruction. Whether any is still
/// marked.
fn kept_reads(body: &Body, gone: &mut [bool], m: &mut Meter) -> Result<bool, Error> {
/// reads (transitively), so no surviving use names a deleted instruction. An insert of `unread`
/// ([`unread_inserts`]) that stays reads only its aggregate: it inserts `undef` in place of its
/// value. Whether any is still marked.
fn kept_reads(
body: &Body,
gone: &mut [bool],
unread: &[(InstId, TypeId)],
m: &mut Meter,
) -> Result<bool, Error> {
let bytes = gone.len() * std::mem::size_of::<InstId>();
m.charge(bytes)?;
let mut work: Vec<InstId> = body
@@ -1074,26 +1127,69 @@ fn kept_reads(body: &Body, gone: &mut [bool], m: &mut Meter) -> Result<bool, Err
.ids()
.filter(|id| !gone.get(id.index()).copied().unwrap_or(false))
.collect();
let mut keep = |v: Value, work: &mut Vec<InstId>| {
if let Value::Inst(j) = v {
if let Some(g) = gone.get_mut(j.index()) {
if *g {
*g = false;
work.push(j);
}
}
}
};
while let Some(id) = work.pop() {
m.tick(1)?;
let Some(inst) = body.insts.get(id) else {
continue;
};
inst.kind.for_each_value(|v| {
if let Value::Inst(j) = v {
if let Some(g) = gone.get_mut(j.index()) {
if *g {
*g = false;
work.push(j);
}
}
match &inst.kind {
InstKind::InsertValue { agg, .. }
if unread.binary_search_by_key(&id, |(i, _)| *i).is_ok() =>
{
keep(*agg, &mut work);
}
});
kind => kind.for_each_value(|v| keep(v, &mut work)),
}
}
m.release(bytes);
Ok(gone.iter().any(|g| *g))
}
/// The `insertvalue` instructions of `body` whose inserted value the observation `o` does not
/// observe (an instruction it leaves unobserved, or a parameter of `params` it reads only
/// unobserved), each with that value's type, in instruction order: the inserts into a field of the
/// returned struct that no output stores or that a later insert sets again, whose own result only
/// the return's chain reads (an observed insert observes its value). The ledger bytes the list
/// holds are charged to `m`, for the caller to release.
fn unread_inserts(
body: &Body,
params: &[TypeId],
o: &Observation,
m: &mut Meter,
) -> Result<Vec<(InstId, TypeId)>, Error> {
let mut out = Vec::new();
for (id, inst) in body.insts.iter() {
m.tick(1)?;
let InstKind::InsertValue { val, .. } = &inst.kind else {
continue;
};
let ty = match *val {
Value::Inst(j) if !o.observed.get(j.index()).copied().unwrap_or(true) => {
body.insts.get(j).map(|x| x.ty)
}
Value::Arg(a) if o.reads.get(a.index()).copied().flatten() != Some(Read::Observed) => {
params.get(a.index()).copied()
}
_ => None,
};
if let Some(ty) = ty {
out.push((id, ty));
}
}
m.charge(out.len() * std::mem::size_of::<(InstId, TypeId)>())?;
Ok(out)
}
/// How the body reads a parameter.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Read {
@@ -1,7 +1,7 @@
//! Linking tests over IR built with the typed test builder: a kernel calls visible functions
//! through reference stubs, and linked modules define them.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use super::*;
use crate::abi::{
@@ -253,6 +253,7 @@ fn request() -> SpecRequest {
SpecRequest {
call_stack_depth: 1,
open_cl_mode: false,
open_cl_lines: BTreeSet::new(),
entry: "k".into(),
constants: BTreeMap::new(),
}
+17 -3
View File
@@ -199,6 +199,12 @@ pub struct SpecRequest {
/// sits 3 past its index, and OpenCL C's work-item functions read the dispatch's values
/// ([`opencl`]). Any other entry than a kernel specializes as without it.
pub open_cl_mode: bool,
/// With [`open_cl_mode`](Self::open_cl_mode), the texture indices of the kernel's 1D images
/// (`texture1d` and `texture1d_array` arguments) that a 1D texture is bound for, where Apple's
/// OpenCL binds a 2D texture of height 1: each keeps its 1D type and its 1D operations, which
/// read the 1D texture. Every other 1D image of the kernel is read as the 2D texture
/// ([`Entry::open_cl_1d_images`]).
pub open_cl_lines: BTreeSet<u32>,
}
/// The constexpr samplers of one linked function that a pipeline state numbers
@@ -290,6 +296,11 @@ pub struct Entry {
/// no measurement says whether it speculates them (an arm of an instruction, size or shape no
/// probe covers). Such a branch keeps the AIR's lanes; Metal's may be the block's.
pub unmeasured_speculation: bool,
/// In a kernel of OpenCL mode ([`SpecRequest::open_cl_mode`]), the texture indices of its 1D
/// images (`texture1d` and `texture1d_array` arguments): each is read as the 2D texture of
/// height 1 Apple's OpenCL binds for it, or as a 1D texture where
/// [`SpecRequest::open_cl_lines`] names it. Empty elsewhere.
pub open_cl_1d_images: BTreeSet<u32>,
}
/// An entry's explicit call stack: what its recursion through visible functions runs on. Its stacks
@@ -653,9 +664,10 @@ pub fn specialize_dynamic(
let body = block_read::expand(body, &mut parts, ep.func, m)?;
// OpenCL C's vector data loads and stores are their element accesses.
let body = vector_data::expand(body, &mut parts, ep.func, m)?;
// OpenCL mode: a 1D image's operations are the 2D texture's that Apple's OpenCL binds for it.
// OpenCL mode: a 1D image's operations are the 2D texture's that Apple's OpenCL binds for it,
// but those of an image a 1D texture is bound for.
let body = if req.open_cl_mode && matches!(ep.stage, Stage::Kernel { .. }) {
opencl_1d::expand(body, &mut parts, ep.func, m)?
opencl_1d::expand(body, &mut parts, (ep, &req.open_cl_lines), m)?
} else {
body
};
@@ -812,8 +824,9 @@ pub fn specialize_dynamic(
ep.params.extend(lanes.bindings());
}
// OpenCL mode's indices and hidden buffers.
let mut open_cl_1d_images = BTreeSet::new();
if let Some(first) = hidden {
ep = opencl::entry(ep, first)?;
(ep, open_cl_1d_images) = opencl::entry(ep, first, &req.open_cl_lines)?;
}
// The built-in parameters the global built-ins' reads became.
ep.params.extend(global_builtins);
@@ -908,6 +921,7 @@ pub fn specialize_dynamic(
lockstep: Lockstep::default(),
call_stack,
unmeasured_speculation,
open_cl_1d_images,
module,
})
}
+23 -6
View File
@@ -51,6 +51,8 @@
//! left, and lowering refuses it. [`entry`] then moves the entry's buffer-indexed arguments 3 on
//! and adds the three buffers' bindings.
use std::collections::BTreeSet;
use crate::abi::{
AbiInt, Access, ArgTypeInfo, BufferArg, EntryPoint, ParamBinding, ParamRole, Slot,
};
@@ -603,14 +605,29 @@ fn rewrite(
/// `first` to `first + 2`: each argument bound at a buffer index 3 past its own (an argument
/// buffer, a function table and an acceleration structure as a buffer), threadgroup memory,
/// textures and samplers at theirs, a 1D image's texture of the 2D type Metal's OpenCL binds for
/// it (`texture1d` as `texture2d`, `texture1d_array` as `texture2d_array`), and the buffers'
/// bindings after the entry's own.
pub fn entry(mut ep: EntryPoint, first: u32) -> Result<EntryPoint, Error> {
/// it (`texture1d` as `texture2d`, `texture1d_array` as `texture2d_array`) but at a texture index
/// of `lines`, a 1D texture's, which keeps its type, and the buffers' bindings after the entry's
/// own. With it, the texture indices of the entry's 1D images (`Entry::open_cl_1d_images`).
pub fn entry(
mut ep: EntryPoint,
first: u32,
lines: &BTreeSet<u32>,
) -> Result<(EntryPoint, BTreeSet<u32>), Error> {
let mut images = BTreeSet::new();
for p in &mut ep.params {
if let ParamRole::Texture(_) = p.role {
if let ParamRole::Texture(t) = &p.role {
let bound = (p.ty.name.as_ref()).and_then(|name| bound_texture(&name.to_string()));
if let Some(bound) = bound {
p.ty.name = Some(DiagName::new(bound));
let index = match t.location.index {
AbiInt::Const(index) => Some(index),
_ => None,
};
if let Some(index) = index {
images.insert(index);
}
if !index.is_some_and(|index| lines.contains(&index)) {
p.ty.name = Some(DiagName::new(bound));
}
}
continue;
}
@@ -653,7 +670,7 @@ pub fn entry(mut ep: EntryPoint, first: u32) -> Result<EntryPoint, Error> {
name: Some(DiagName::new(name)),
});
}
Ok(ep)
Ok((ep, images))
}
/// The MSL type of the texture Metal's OpenCL binds for an image argument whose type AIR names
+48 -10
View File
@@ -9,22 +9,29 @@
//! with and without a sampler, a sample at integer, unnormalized and normalized coordinates (a
//! linear filter at a border-clamped edge answers the texel, blending in no row of the border), a
//! write, `get_image_width` and `get_image_array_size` answer the 1D image's values. With 1D
//! textures bound, the M3 Max reads texel 0 at every coordinate.
//! textures bound, which Apple's OpenCL never binds, the Macs disagree: the M3 Max reads texel 0
//! at every coordinate, the Radeon Pro 5300M the 1D images' values, and an Intel UHD Graphics 630
//! layer 0 of a 1D array.
//!
//! [`expand`] makes each such call of a 1D texture in a kernel of OpenCL mode a call of a function
//! built here, and inlines it: the same operation of a 2D texture, or a 2D array texture for a 1D
//! array, its coordinate `(x, 0)`, a sampled coordinate `(x, 0.5)` (the row's centre in
//! normalized and unnormalized coordinates alike), its offset `(o, 0)` or, where the 1D form has
//! none, `(0, 0)`. Lowering then declares the slot, and the binder binds it, as the 2D texture
//! Metal's OpenCL binds. Not rewritten: `get_num_mip_levels`, whose 1D answer (0) a 2D texture's is
//! Metal's OpenCL binds. An image a 1D texture is bound for (`SpecRequest::open_cl_lines`, the
//! binder's variant) keeps its 1D operations, which read the 1D texture: the 5300M's answer.
//! Not rewritten: `get_num_mip_levels`, whose 1D answer (0) a 2D texture's is
//! not, and the image format queries, which read a hidden buffer whatever the shape
//! (`canon::opencl`); neither is OpenCL C's.
use std::collections::BTreeSet;
use crate::abi::{AbiInt, EntryPoint, ParamRole};
use crate::budget::Meter;
use crate::error::Error;
use crate::intrinsics::{AirIntrinsic, ImageDim, ImageShape, Query, TexOp, TexRole, Texture};
use crate::ir::{
ArgIdx, Body, Call, CallConv, Callee, Const, FnAttrs, FuncId, Function, InstId, InstKind,
ArgIdx, Body, Call, CallConv, Callee, Const, FnAttrs, FuncId, Function, Idx, InstId, InstKind,
Linkage, ModuleParts, Param, ParamAttrs, Type, TypeId, UnnamedAddr, Value, Visibility,
};
@@ -53,8 +60,9 @@ fn widened(t: Texture) -> Option<Texture> {
}
}
/// The 1D texture operation `kind` calls that [`expand`] rewrites, with its declaration and call.
fn site(kind: &InstKind) -> Option<(Texture, FuncId, &Call)> {
/// The 1D texture operation `kind` calls that [`expand`] rewrites, with its declaration and call:
/// not one of a texture parameter of `kept`, a 1D texture's.
fn site<'a>(kind: &'a InstKind, kept: &[u32]) -> Option<(Texture, FuncId, &'a Call)> {
let InstKind::Call(call) = kind else {
return None;
};
@@ -62,11 +70,36 @@ fn site(kind: &InstKind) -> Option<(Texture, FuncId, &Call)> {
Callee::Air {
decl,
op: AirIntrinsic::Texture(t),
} if widened(t).is_some() => Some((t, decl, call)),
} if widened(t).is_some() && !of_params(t, call, kept) => Some((t, decl, call)),
_ => None,
}
}
/// Whether operation `t`'s `call` names a texture that is one of the entry's parameters `kept`.
fn of_params(t: Texture, call: &Call, kept: &[u32]) -> bool {
let texture = t.layout().index(TexRole::Texture);
match texture.and_then(|i| call.args.get(i)) {
Some(Value::Arg(a)) => u32::try_from(a.index()).is_ok_and(|p| kept.contains(&p)),
_ => false,
}
}
/// The parameters of `ep` that bind a texture at an index of `lines`: the 1D images a 1D texture
/// is bound for, whose operations stay 1D.
fn kept_params(ep: &EntryPoint, lines: &BTreeSet<u32>, m: &mut Meter) -> Result<Vec<u32>, Error> {
let mut kept = Vec::new();
for p in &ep.params {
m.tick(1)?;
if let ParamRole::Texture(t) = &p.role {
if matches!(t.location.index, AbiInt::Const(index) if lines.contains(&index)) {
m.reserve(&mut kept, 1)?;
kept.push(p.param);
}
}
}
Ok(kept)
}
/// Whether `parts` declares a 1D texture operation [`expand`] rewrites. Every site calls one, so
/// a module that declares none has none, and [`expand`] need not read its instructions.
fn declares_sites(parts: &ModuleParts, m: &mut Meter) -> Result<bool, Error> {
@@ -87,23 +120,26 @@ fn declares_sites(parts: &ModuleParts, m: &mut Meter) -> Result<bool, Error> {
Ok(false)
}
/// Make each 1D texture operation of the entry `func`'s inlined `body` that the module doc lists
/// a call of a function built for it, and inline the result.
/// Make each 1D texture operation of the entry `ep`'s inlined `body` that the module doc lists a
/// call of a function built for it, and inline the result: each but those of an image at a
/// texture index of `lines`, which a 1D texture is bound for.
pub(super) fn expand(
body: Body,
parts: &mut ModuleParts,
func: FuncId,
(ep, lines): (&EntryPoint, &BTreeSet<u32>),
m: &mut Meter,
) -> Result<Body, Error> {
if !declares_sites(parts, m)? {
return Ok(body);
}
let func = ep.func;
let kept = kept_params(ep, lines, m)?;
// One function per operation and declaration, and each call's.
let mut made: Vec<((Texture, FuncId), FuncId)> = Vec::new();
let mut calls: Vec<(InstId, FuncId)> = Vec::new();
for (id, inst) in body.insts.iter() {
m.tick(1)?;
let Some((t, decl, call)) = site(&inst.kind) else {
let Some((t, decl, call)) = site(&inst.kind, &kept) else {
continue;
};
let f = match made.iter().find(|(k, _)| *k == (t, decl)) {
@@ -120,6 +156,8 @@ pub(super) fn expand(
}
m.release(made.capacity() * std::mem::size_of::<((Texture, FuncId), FuncId)>());
drop(made);
m.release(kept.capacity() * std::mem::size_of::<u32>());
drop(kept);
if calls.is_empty() {
m.release(calls.capacity() * std::mem::size_of::<(InstId, FuncId)>());
return Ok(body);
@@ -14,7 +14,9 @@
//! the one path the constants decide, a callee runs in a new frame, and every value is a
//! constant, a pointer into a global (`global + byte offset`), or **undefined from an unsupplied
//! function constant** (the SCCP lattice's `Fc`). What it evaluates: integer arithmetic,
//! comparisons, and casts ([`Folder`]), `fcmp` on constants with no subnormal operand, `select`,
//! comparisons, and casts ([`Folder`]), of scalars and of each lane of a vector whose every lane
//! is a known constant ([`Folder::lanewise`]: a vector with an `undef` lane is not evaluated),
//! `fcmp` on constants with no subnormal operand, `select`,
//! element and member access,
//! shuffles, `air.convert` of an integer or `bool`, a scalar or each lane of a vector, to another
//! integer (as C++ converts it) or to `bool` (`x != 0`), and of a scalar one to a float (rounded
@@ -599,7 +601,9 @@ impl<'a> Eval<'a> {
{
SVal::Fc(Undefined::Ir)
}
_ => self.pure2(a, b, &at, m, |f, x, y, m| f.binop(op, ty, x, y, m))?,
_ => self.pure2(a, b, &at, m, |f, x, y, m| {
f.lanewise(ty, x, y, m, |f, t, x, y, m| f.binop(op, t, x, y, m))
})?,
}
}
InstKind::FNeg { v, .. } => {
@@ -608,7 +612,9 @@ impl<'a> Eval<'a> {
}
InstKind::ICmp { pred, a, b } => {
let (p, a, b) = (*pred, val(*a)?, val(*b)?);
self.pure2(a, b, &at, m, |f, x, y, m| f.icmp(p, ty, x, y, m))?
self.pure2(a, b, &at, m, |f, x, y, m| {
f.lanewise(ty, x, y, m, |f, t, x, y, m| f.icmp(p, t, x, y, m))
})?
}
InstKind::FCmp { pred, a, b, .. } => {
let (p, a, b) = (*pred, val(*a)?, val(*b)?);
@@ -631,7 +637,10 @@ impl<'a> Eval<'a> {
SVal::Opaque => SVal::Opaque,
SVal::C(c) => match self.ptr_of(c, &at)? {
Some((g, o)) if reinterpret => SVal::Ptr(g, o),
_ => match self.folder.cast(op, c, ty, m)? {
_ => match self
.folder
.lanewise(ty, c, c, m, |f, t, x, _, m| f.cast(op, x, t, m))?
{
Some(c) => SVal::C(c),
None => self.unevaluated(&at)?,
},
+4 -1
View File
@@ -1,6 +1,6 @@
//! Canonicalization tests over IR built with the typed test builder.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use super::*;
use crate::abi::{
@@ -33,6 +33,7 @@ mod private_memory;
mod private_reach;
mod sampler_tables;
mod static_divisions;
mod static_vectors;
mod table_copies;
mod texture_writes;
mod unbound_immediates;
@@ -180,6 +181,7 @@ fn request(constants: &[(u32, ConstValue)]) -> SpecRequest {
SpecRequest {
call_stack_depth: 1,
open_cl_mode: false,
open_cl_lines: BTreeSet::new(),
entry: "k".into(),
constants: constants.iter().cloned().collect::<BTreeMap<_, _>>(),
}
@@ -2678,6 +2680,7 @@ fn a_static_initializer_branch_on_an_unsupplied_constant_takes_its_false_way() {
let r = SpecRequest {
call_stack_depth: 1,
open_cl_mode: false,
open_cl_lines: BTreeSet::new(),
entry: "k".into(),
constants: [(3, boolean(1))].into_iter().collect(),
};
@@ -4,6 +4,7 @@
use super::*;
use crate::error::{DiagName, GenericPointer};
use crate::intrinsics::{Elem, LlvmIntrinsic};
/// What [`queried`]'s generic pointer `p` holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -47,6 +48,15 @@ enum Held {
ArrayMixed,
/// Field 0 of a `{ptr, i32}` loaded from the thread's array.
FieldLoaded,
/// `in` stored at field 0 of a thread struct `{ptr, i64, ptr}` beside 7 and null, the struct
/// copied whole (`memcpy`) into another, and field 0 of the copy loaded back.
Copied,
/// As `Copied`, the copy copied whole on into a third struct, whose field 0 is loaded.
CopiedOn,
/// As `Copied`, the copy's bytes 4 to 24 only: field 0 straddles the copy's start.
CopiedPart,
/// As `Copied`, the copy loaded back at the pointer-sized field the float `in[0]` names.
CopiedAnywhere,
}
/// `kernel k(device float* out, device float* in)` with a generic pointer `p` that `held` gives:
@@ -238,6 +248,88 @@ fn queried(held: Held) -> Result<Entry, Error> {
store(&mut f, bits, o);
load(&mut f, generic, local)
}
Held::Copied | Held::CopiedOn | Held::CopiedPart | Held::CopiedAnywhere => {
let i8t = f.module().int(8);
let i64t = f.module().int(64);
let fields = f.module().struct_ty(&[generic, i64t, generic]);
let copy_ty = f.module().fn_ty(void, &[thread, thread, i64t, i1]);
let decl = f.module().declare("llvm.memcpy.p0.p0.i64", copy_ty);
let op = LlvmIntrinsic::Memcpy {
dst: AddrSpace::Thread,
src: AddrSpace::Thread,
len: Elem::I64,
volatile: false,
};
let object = |f: &mut FunctionBuilder<'_>| {
f.push(
thread,
InstKind::Alloca {
ty: fields,
count: one,
align: None,
},
)
};
// Byte `k` of `base`.
let byte = |f: &mut FunctionBuilder<'_>, base: Value, k: u64| {
let k = f.module().const_int(i64t, k);
f.push(
thread,
InstKind::Gep {
src_ty: i8t,
base,
indices: Box::new([k]),
inbounds: true,
},
)
};
let copy = |f: &mut FunctionBuilder<'_>, dst: Value, src: Value, len: u64| {
let len = f.module().const_int(i64t, len);
let volatile = f.module().const_int(i1, 0);
call(
f,
void,
Callee::Llvm { decl, op },
&[dst, src, len, volatile],
);
};
let first = object(&mut f);
store(&mut f, input, first);
let seven = f.module().const_int(i64t, 7);
let count = byte(&mut f, first, 8);
store(&mut f, seven, count);
let last = byte(&mut f, first, 16);
store(&mut f, null, last);
let second = object(&mut f);
if held == Held::CopiedPart {
let (to, from) = (byte(&mut f, second, 4), byte(&mut f, first, 4));
copy(&mut f, to, from, 20);
} else {
copy(&mut f, second, first, 24);
}
let read = if held == Held::CopiedOn {
let third = object(&mut f);
copy(&mut f, third, second, 24);
third
} else {
second
};
let from = if held == Held::CopiedAnywhere {
let word = load(&mut f, i32t, arg(1));
f.push(
thread,
InstKind::Gep {
src_ty: generic,
base: read,
indices: Box::new([word]),
inbounds: true,
},
)
} else {
read
};
load(&mut f, generic, from)
}
Held::Field
| Held::Fields
| Held::FieldSelect
@@ -532,3 +624,41 @@ fn a_generic_pointer_loaded_from_a_thread_slot_is_its_stores_space_s() {
);
}
}
/// A generic pointer stored into a thread struct that is copied whole, and on again, is loaded
/// from the copy as the pointer stored: a device pointer, its queries answered. The null stored
/// at another field of the struct does not reach it.
#[test]
fn a_generic_pointer_in_a_struct_copied_whole_keeps_its_space() {
for held in [Held::Copied, Held::CopiedOn] {
let e = queried(held).unwrap_or_else(|e| panic!("{held:?}: {e}"));
let text = body_text(&e);
assert!(!names_generic(&e), "{held:?}: {text}");
assert!(text.contains("[llvm Memcpy"), "{held:?}: {text}");
assert!(
!text
.lines()
.any(|l| l.contains("icmp ne") && l.contains("ptr addrspace(1) zeroinitializer")),
"{held:?}: {text}"
);
let words = stored(&e);
assert_eq!(
words[words.len().saturating_sub(2)..],
[Some(1.0), Some(0.0)],
"{held:?}: {text}"
);
}
}
/// A copy that splits a slot, or into a struct read at an offset only the run knows, writes
/// bytes the translation does not read as the pointer stored: the load is refused as memory.
#[test]
fn a_copy_that_splits_a_slot_or_meets_an_unknown_offset_is_refused() {
for held in [Held::CopiedPart, Held::CopiedAnywhere] {
assert!(
refused(queried(held), GenericPointer::Memory),
"{held:?}: {:?}",
queried(held).map(|e| body_text(&e))
);
}
}
@@ -332,6 +332,12 @@ attributes #3 = { nounwind willreturn }\n\
/// [`IMAGES`] specialized, in OpenCL mode where `open_cl_mode`; `None` without `llvm-as`.
fn images(test: &str, open_cl_mode: bool) -> Option<Entry> {
images_bound(test, open_cl_mode, BTreeSet::new())
}
/// [`IMAGES`] specialized, in OpenCL mode where `open_cl_mode`, a 1D texture bound for each 1D
/// image at a texture index of `lines`; `None` without `llvm-as`.
fn images_bound(test: &str, open_cl_mode: bool, lines: BTreeSet<u32>) -> Option<Entry> {
let bitcode = match metal2vulkan_devtools::llvm_assemble_text(&format!("{HEAD}{IMAGES}")) {
Ok(b) => b,
Err(e) => {
@@ -343,6 +349,7 @@ fn images(test: &str, open_cl_mode: bool) -> Option<Entry> {
let req = SpecRequest {
entry: "img".into(),
open_cl_mode,
open_cl_lines: lines,
..SpecRequest::default()
};
Some(specialize(d.module, &d.abi, &req, &mut meter()).expect("specialized"))
@@ -506,6 +513,87 @@ fn opencl_1d_images_are_read_written_and_queried_as_2d_textures() {
);
}
/// A 1D image a 1D texture is bound for (`SpecRequest::open_cl_lines`), which Apple's OpenCL never
/// binds, keeps its type and its 1D operations, which read that texture; every other 1D image is
/// the 2D texture's still. The entry names its 1D images in OpenCL mode alone, whatever is bound.
#[test]
fn opencl_1d_images_bound_to_1d_textures_keep_their_1d_operations() {
use crate::intrinsics::{ImageDim, Query};
let test = "opencl_1d_images_bound_to_1d_textures_keep_their_1d_operations";
let (Some(plain), Some(cl), Some(lines)) = (
images(test, false),
images(test, true),
images_bound(test, true, BTreeSet::from([1, 2])),
) else {
return;
};
let ops = |e: &Entry| {
let mut v: Vec<_> = texture_ops(e)
.into_iter()
.filter(|(op, ..)| {
!matches!(
op,
TexOp::Query(Query::ChannelOrder | Query::ChannelDataType)
)
})
.collect();
v.sort();
v
};
let width = TexOp::Query(Query::Width);
let layers = TexOp::Query(Query::ArraySize);
let sample = |e: &Entry| {
texture_ops(e)
.into_iter()
.find(|(op, ..)| matches!(op, TexOp::Sample { .. }))
.expect("a sample")
.0
};
// `b` (texture 1) and `c` (texture 2) stay 1D; `d` (texture 3) writes its 2D texture.
let mut want = vec![
(layers, ImageDim::D1, true),
(TexOp::Read, ImageDim::D1, false),
(sample(&lines), ImageDim::D1, true),
(width, ImageDim::D1, false),
(TexOp::Write, ImageDim::D2, false),
];
want.sort();
assert_eq!(ops(&lines), want, "{}", print(&lines.module));
let names = |e: &Entry| -> Vec<(u32, String)> {
e.ep.params
.iter()
.filter_map(|p| match &p.role {
ParamRole::Texture(t) => match t.location.index {
AbiInt::Const(index) => Some((index, p.ty.name.as_ref()?.to_string())),
_ => None,
},
_ => None,
})
.collect()
};
assert_eq!(
names(&lines),
[
(0, "texture2d<unknown, read>".to_owned()),
(1, "texture1d<unknown, read>".to_owned()),
(2, "texture1d_array<unknown, read>".to_owned()),
(3, "texture2d<unknown, write>".to_owned()),
]
);
assert_eq!(
names(&cl),
[
(0, "texture2d<unknown, read>".to_owned()),
(1, "texture2d<unknown, read>".to_owned()),
(2, "texture2d_array<unknown, read>".to_owned()),
(3, "texture2d<unknown, write>".to_owned()),
]
);
assert_eq!(cl.open_cl_1d_images, BTreeSet::from([1, 2, 3]));
assert_eq!(lines.open_cl_1d_images, BTreeSet::from([1, 2, 3]));
assert!(plain.open_cl_1d_images.is_empty());
}
#[test]
fn opencl_image_formats_of_buffer_and_depth_images_stay_undecoded() {
// Metal makes no pipeline of OpenCL mode that queries their formats (M3 Max, macOS 27.0.1;
@@ -0,0 +1,258 @@
//! A static initializer's integer vectors: lanes inserted into `undef`, compared, extended and
//! truncated, shifted and masked, each lane evaluated as its scalar is.
use super::*;
use crate::ir::ConstId;
/// The shape a stitchable library's initializer has: from the `ushort` function constant 0 (`x`)
/// it stores `lanes = <(x >> i & 1) ^ 1>` built lane by lane into `undef` (`<4 x i32>`), `bits =
/// zext <x & (1 << i) != 0>` built from scalar compares into an `undef` `<4 x i1>` (`<4 x i8>`),
/// `high = trunc(x) >> 4 & 1` (`i8`), and `vector = trunc(zext((splat(x) >> <0, 1, 2, 3> & 1) !=
/// 0))` computed on vectors throughout (`<4 x i8>`). The kernel stores, to buffers 0 to 3, the
/// lanes of each vector packed one per byte (lane `i` at bits `8 i`) and `high`. `complete`
/// false leaves lane 3 of `lanes` `undef` and masks the vector with ones. The specialization for
/// `x`.
fn initialized(x: u16, complete: bool) -> Result<Entry, Error> {
let mut m = ModuleBuilder::new();
let void = m.void();
let (i1, i8t, i16t, i32t, i64t) = (m.int(1), m.int(8), m.int(16), m.int(32), m.int(64));
let (v4i1, v4i8, v4i32) = (m.vector(i1, 4), m.vector(i8t, 4), m.vector(i32t, 4));
let dev = m.ptr(AddrSpace::Device);
let fc = fc_global(&mut m, "x", i16t);
let zero4 = m.constant(v4i32, Const::Null);
let zero8 = m.constant(v4i8, Const::Null);
let zero = m.constant(i8t, Const::Int(0));
let lanes = m.simple_global("lanes", v4i32, AddrSpace::Constant, Some(zero4));
let bits = m.simple_global("bits", v4i8, AddrSpace::Constant, Some(zero8));
let high = m.simple_global("high", i8t, AddrSpace::Constant, Some(zero));
let vector = m.simple_global("vector", v4i8, AddrSpace::Constant, Some(zero8));
let addrs = [fc, lanes, bits, high, vector].map(|g| m.global_addr(g));
let [fc_addr, lanes_addr, bits_addr, high_addr, vector_addr] = addrs;
let undef4 = Value::Const(m.constant(v4i32, Const::Undef));
let undef1 = Value::Const(m.constant(v4i1, Const::Undef));
let (k0, k1) = (m.const_int(i32t, 0), m.const_int(i32t, 1));
let k4 = m.const_int(i8t, 4);
let k1b = m.const_int(i8t, 1);
let lane = |m: &mut ModuleBuilder, i: u64| m.const_int(i64t, i);
let idx: Vec<Value> = (0..4).map(|i| lane(&mut m, i)).collect();
let shifts: Vec<ConstId> = (0..4)
.map(|i| match m.const_int(i32t, i) {
Value::Const(c) => c,
_ => unreachable!(),
})
.collect();
let shifts = Value::Const(m.constant(v4i32, Const::Aggregate(shifts.into())));
let ones: Vec<ConstId> = (0..4)
.map(|_| match k1 {
Value::Const(c) => c,
_ => unreachable!(),
})
.collect();
let ones = Value::Const(m.constant(v4i32, Const::Aggregate(ones.into())));
static_init(&mut m, "init", |f| {
let v = load(f, i16t, fc_addr);
let w = f.push(
i32t,
InstKind::Cast {
op: CastOp::ZExt,
v,
},
);
// `lanes`, scalar steps inserted lane by lane.
let mut acc = undef4;
for (i, &at) in idx.iter().enumerate().take(if complete { 4 } else { 3 }) {
let k = f.module().const_int(i32t, i as u64);
let s = f.bin(BinOp::LShr, w, k);
let b = f.bin(BinOp::And, s, k1);
let inv = f.bin(BinOp::Xor, b, k1);
acc = f.push(
v4i32,
InstKind::InsertElement {
vec: acc,
elt: inv,
idx: at,
},
);
}
// An incomplete vector takes one integer step, which its `undef` lane stops.
let acc = if complete {
acc
} else {
f.bin(BinOp::And, acc, ones)
};
store(f, acc, lanes_addr);
// `bits`, scalar compares inserted into an `undef` `<4 x i1>`, then a vector `zext`.
let mut acc = undef1;
for (i, &at) in idx.iter().enumerate() {
let k = f.module().const_int(i32t, 1 << i);
let b = f.bin(BinOp::And, w, k);
let c = f.push(
i1,
InstKind::ICmp {
pred: IntPredicate::Ne,
a: b,
b: k0,
},
);
acc = f.push(
v4i1,
InstKind::InsertElement {
vec: acc,
elt: c,
idx: at,
},
);
}
let z = f.push(
v4i8,
InstKind::Cast {
op: CastOp::ZExt,
v: acc,
},
);
store(f, z, bits_addr);
// `high`.
let t = f.push(
i8t,
InstKind::Cast {
op: CastOp::Trunc,
v,
},
);
let s = f.bin(BinOp::LShr, t, k4);
let h = f.bin(BinOp::And, s, k1b);
store(f, h, high_addr);
// `vector`, every step on vectors.
let mut splat = undef4;
for &at in &idx {
splat = f.push(
v4i32,
InstKind::InsertElement {
vec: splat,
elt: w,
idx: at,
},
);
}
let s = f.bin(BinOp::LShr, splat, shifts);
let b = f.bin(BinOp::And, s, ones);
let c = f.push(
v4i1,
InstKind::ICmp {
pred: IntPredicate::Ne,
a: b,
b: Value::Const(zero4),
},
);
let wide = f.push(
v4i32,
InstKind::Cast {
op: CastOp::ZExt,
v: c,
},
);
let narrow = f.push(
v4i8,
InstKind::Cast {
op: CastOp::Trunc,
v: wide,
},
);
store(f, narrow, vector_addr);
});
let fty = m.fn_ty(void, &[dev, dev, dev, dev]);
let mut f = m.define("k", fty);
// Lane `i` of the vector at `addr` (of `ty`, lanes of `bits` bits), zero-extended and shifted
// to bits `8 i`, or-ed into one `i32`.
let packed = |f: &mut FunctionBuilder<'_>, ty: TypeId, lane_ty: TypeId, addr: Value| {
let v = load(f, ty, addr);
let mut acc = k0;
for (i, &at) in idx.iter().enumerate() {
let e = f.push(lane_ty, InstKind::ExtractElement { vec: v, idx: at });
let e = if lane_ty == i32t {
e
} else {
f.push(
i32t,
InstKind::Cast {
op: CastOp::ZExt,
v: e,
},
)
};
let k = f.module().const_int(i32t, 8 * i as u64);
let e = f.bin(BinOp::Shl, e, k);
acc = f.bin(BinOp::Or, acc, e);
}
acc
};
let a = packed(&mut f, v4i32, i32t, lanes_addr);
store(&mut f, a, arg(0));
let b = packed(&mut f, v4i8, i8t, bits_addr);
store(&mut f, b, arg(1));
let h = load(&mut f, i8t, high_addr);
let h = f.push(
i32t,
InstKind::Cast {
op: CastOp::ZExt,
v: h,
},
);
store(&mut f, h, arg(2));
let v = packed(&mut f, v4i8, i8t, vector_addr);
store(&mut f, v, arg(3));
f.ret(None);
let k = f.finish();
let module = m.finish().unwrap();
let abi = abi(
vec![kernel(
k,
vec![buffer(0, 0), buffer(1, 1), buffer(2, 2), buffer(3, 3)],
)],
vec![fc_decl(0, fc, i16t)],
);
let value = ConstValue {
ty: DataType::UShort,
bytes: x.to_le_bytes().into(),
};
specialize(module, &abi, &request(&[(0, value)]), &mut meter())
}
fn stores(e: &Entry) -> Vec<String> {
body_text(e)
.lines()
.filter(|l| l.contains("store"))
.map(|l| l.trim().to_string())
.collect()
}
#[test]
fn a_static_initializer_evaluates_each_lane_of_its_integer_vectors() {
// `x` 22 (0b10110): its bits 0 to 3 are 0, 1, 1, 0.
let e = initialized(22, true).unwrap_or_else(|e| panic!("{e:?}"));
assert_eq!(
stores(&e),
[
// `lanes` <1, 0, 0, 1>.
"store i32 16777217, %a0, align 4",
// `bits` <0, 1, 1, 0>.
"store i32 65792, %a1, align 4",
// `high`: 22 >> 4 is 1.
"store i32 1, %a2, align 4",
// `vector` <0, 1, 1, 0>.
"store i32 65792, %a3, align 4",
]
);
assert!(!body_text(&e).contains("load"), "{}", body_text(&e));
}
#[test]
fn a_static_initializer_vector_with_an_undefined_lane_is_not_evaluated() {
// Lane 3 of `lanes` is never inserted: the vector holds an `undef` lane, which the evaluator
// does not carry through an integer step, so the module is refused as before.
let u = match initialized(22, false) {
Err(Error::Unsupported(u)) => u,
other => panic!("{:?}", other.map(|_| ())),
};
assert_eq!(u.feature, Feature::StaticInitializer);
}
+27 -27
View File
@@ -97,22 +97,22 @@ device-linear-texture-alignments llvmpipe divergent case/MTLPixelFormatRGB9E5Flo
device-linear-texture-alignments llvmpipe divergent case/MTLPixelFormatRGBA32Float/Ok Metal 16 (0x10), ours 64 (0x40) lavapipe's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs), and llvmpipe's images need 64 for these formats where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments llvmpipe divergent case/MTLPixelFormatRGBA8Unorm/Ok Metal 16 (0x10), ours 64 (0x40) lavapipe's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs), and llvmpipe's images need 64 for these formats where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments llvmpipe divergent case/MTLPixelFormatRGBA8Unorm_sRGB/Ok Metal 16 (0x10), ours 64 (0x40) lavapipe's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs), and llvmpipe's images need 64 for these formats where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatA8Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatBGRA8Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatBGRA8Unorm_sRGB/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatR16Float/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatR32Float/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatR32Uint/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatR8Snorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatR8Uint/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatR8Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatRG32Float/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatRG8Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatRGB10A2Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatRGB9E5Float/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatRGBA32Float/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatRGBA8Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV NAVI31 divergent case/MTLPixelFormatRGBA8Unorm_sRGB/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31, where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatA8Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatBGRA8Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatBGRA8Unorm_sRGB/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatR16Float/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatR32Float/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatR32Uint/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatR8Snorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatR8Uint/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatR8Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatRG32Float/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatRG8Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatRGB10A2Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatRGB9E5Float/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatRGBA32Float/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatRGBA8Unorm/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
device-linear-texture-alignments RADV divergent case/MTLPixelFormatRGBA8Unorm_sRGB/Ok Metal 16 (0x10), ours 256 (0x100) RADV's own answer, not a gap of ours: minimumLinearTextureAlignmentForPixelFormat answers, per format, the smallest power of two from 16 at which the device's linear images lie at the asked pitch (texture/linear_alignment.rs, which asks the driver for each image and binds none), and RADV takes no smaller power of two for every width the probe asks of these formats on NAVI31 and on PHOENIX (an RX 7900 XTX and a Radeon 780M, each Metal 16, ours 256), where Metal on the Apple M3 Max (this case's recording, macOS 27.0.1) answers 16. A texture over a buffer at a smaller multiple of 16 is still made, as Metal makes it: in place over host pages, else a shadow of the buffer's bytes, announced (shadowed-texture). Open: nothing; a driver that changes its answer moves these rows.
discard-quad-sum-placement 128 bits) divergent case/counted_atomic/texels 4 elements differ (I32), the largest difference 1 Metal counts the quads the discard drops whole in a simdgroup sum that sits ahead of the discard for a measured reason -- the discard's condition reads the sum (`counted_dependent`), or a device store (`counted_store`) or an atomic (`counted_atomic`) lies between them -- so each kept texel's first channel, `before > after`, is 1: the M3 Max's 32-lane simdgroup holds the 8 by 4 target's dropped quads beside the kept one. The module keeps the sum ahead of the discard as Metal's compiler does, and what differs is which pixels share the simdgroup: the device's own grouping, which Metal permits, recorded as `PrecisionNote::FragmentSimdgroupGrouping` and announced as `fragment-simdgroup-grouping`. A lavapipe built for 128-bit vectors runs 4-lane fragment subgroups, one quad each (`Tier::PartialFragment`), so the kept quad's subgroup holds no dropped quad and all four kept texels read 0, each by exactly one code. Measured 2026-11-07 on x86-64 lavapipe (Mesa, LLVM 23.1.4): at its default 256-bit vectors (8-lane subgroups, two quads) the three shapes answer Metal's 1, and under `LP_NATIVE_VECTOR_WIDTH=128` they read these rows, the module and the compiler unchanged; the gate container's arm64 `llvmpipe (LLVM 21.1.8, 128 bits)` reads them as well, and MoltenVK on the M3 Max answers 1 exactly. So the venue field is the width, `128 bits)`, and not one build. No exact form exists on such a device: no required subgroup size reaches 32 lanes there, and nothing in Vulkan relates the invocations of two fragment subgroups. The row stays because the note derives no tolerance (`replay::NATIVE_NOTES` states the rule for a device's own answer): it says what differs and that the answer is the device's.
discard-quad-sum-placement 128 bits) divergent case/counted_dependent/texels 4 elements differ (I32), the largest difference 1 Metal counts the quads the discard drops whole in a simdgroup sum that sits ahead of the discard for a measured reason -- the discard's condition reads the sum (`counted_dependent`), or a device store (`counted_store`) or an atomic (`counted_atomic`) lies between them -- so each kept texel's first channel, `before > after`, is 1: the M3 Max's 32-lane simdgroup holds the 8 by 4 target's dropped quads beside the kept one. The module keeps the sum ahead of the discard as Metal's compiler does, and what differs is which pixels share the simdgroup: the device's own grouping, which Metal permits, recorded as `PrecisionNote::FragmentSimdgroupGrouping` and announced as `fragment-simdgroup-grouping`. A lavapipe built for 128-bit vectors runs 4-lane fragment subgroups, one quad each (`Tier::PartialFragment`), so the kept quad's subgroup holds no dropped quad and all four kept texels read 0, each by exactly one code. Measured 2026-11-07 on x86-64 lavapipe (Mesa, LLVM 23.1.4): at its default 256-bit vectors (8-lane subgroups, two quads) the three shapes answer Metal's 1, and under `LP_NATIVE_VECTOR_WIDTH=128` they read these rows, the module and the compiler unchanged; the gate container's arm64 `llvmpipe (LLVM 21.1.8, 128 bits)` reads them as well, and MoltenVK on the M3 Max answers 1 exactly. So the venue field is the width, `128 bits)`, and not one build. No exact form exists on such a device: no required subgroup size reaches 32 lanes there, and nothing in Vulkan relates the invocations of two fragment subgroups. The row stays because the note derives no tolerance (`replay::NATIVE_NOTES` states the rule for a device's own answer): it says what differs and that the answer is the device's.
discard-quad-sum-placement 128 bits) divergent case/counted_store/texels 4 elements differ (I32), the largest difference 1 Metal counts the quads the discard drops whole in a simdgroup sum that sits ahead of the discard for a measured reason -- the discard's condition reads the sum (`counted_dependent`), or a device store (`counted_store`) or an atomic (`counted_atomic`) lies between them -- so each kept texel's first channel, `before > after`, is 1: the M3 Max's 32-lane simdgroup holds the 8 by 4 target's dropped quads beside the kept one. The module keeps the sum ahead of the discard as Metal's compiler does, and what differs is which pixels share the simdgroup: the device's own grouping, which Metal permits, recorded as `PrecisionNote::FragmentSimdgroupGrouping` and announced as `fragment-simdgroup-grouping`. A lavapipe built for 128-bit vectors runs 4-lane fragment subgroups, one quad each (`Tier::PartialFragment`), so the kept quad's subgroup holds no dropped quad and all four kept texels read 0, each by exactly one code. Measured 2026-11-07 on x86-64 lavapipe (Mesa, LLVM 23.1.4): at its default 256-bit vectors (8-lane subgroups, two quads) the three shapes answer Metal's 1, and under `LP_NATIVE_VECTOR_WIDTH=128` they read these rows, the module and the compiler unchanged; the gate container's arm64 `llvmpipe (LLVM 21.1.8, 128 bits)` reads them as well, and MoltenVK on the M3 Max answers 1 exactly. So the venue field is the width, `128 bits)`, and not one build. No exact form exists on such a device: no required subgroup size reaches 32 lanes there, and nothing in Vulkan relates the invocations of two fragment subgroups. The row stays because the note derives no tolerance (`replay::NATIVE_NOTES` states the rule for a device's own answer): it says what differs and that the answer is the device's.
@@ -1395,17 +1395,17 @@ blit-generated-mipmaps-bgra10xr llvmpipe divergent case/level-3 46 elements diff
blit-generated-mipmaps-bgra10xr llvmpipe divergent case/level-4 18 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Each differing field is one code of its 10 bits from Metal's (64 in the 16-bit field that holds the code in its top bits), the rest Metal's; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field here.
blit-generated-mipmaps-bgra10xr llvmpipe divergent case/level-5 5 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Each differing field is one code of its 10 bits from Metal's (64 in the 16-bit field that holds the code in its top bits), the rest Metal's; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field here.
blit-generated-mipmaps-bgra10xr llvmpipe divergent case/level-6 1 element differs (U16): Metal 32000 (0x7d00), ours 32064 (0x7d40) `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Each differing field is one code of its 10 bits from Metal's (64 in the 16-bit field that holds the code in its top bits), the rest Metal's; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field here.
blit-generated-mipmaps-bgr10xr RADV NAVI31 divergent case/level-1 803 elements differ (U32), the largest difference 1048577 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGR10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (803, 232, 58, 13 and 3 words), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgr10xr RADV NAVI31 divergent case/level-2 232 elements differ (U32), the largest difference 1049601 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGR10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (803, 232, 58, 13 and 3 words), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgr10xr RADV NAVI31 divergent case/level-3 58 elements differ (U32), the largest difference 1049601 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGR10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (803, 232, 58, 13 and 3 words), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgr10xr RADV NAVI31 divergent case/level-4 13 elements differ (U32), the largest difference 1049601 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGR10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (803, 232, 58, 13 and 3 words), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgr10xr RADV NAVI31 divergent case/level-5 3 elements differ (U32), the largest difference 1025 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGR10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (803, 232, 58, 13 and 3 words), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV NAVI31 divergent case/level-1 58 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV NAVI31 divergent case/level-2 78 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV NAVI31 divergent case/level-3 46 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV NAVI31 divergent case/level-4 18 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV NAVI31 divergent case/level-5 5 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV NAVI31 divergent case/level-6 1 element differs (U16): Metal 32000 (0x7d00), ours 32064 (0x7d40) `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgr10xr RADV divergent case/level-1 803 elements differ (U32), the largest difference 1048577 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGR10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (803, 232, 58, 13 and 3 words), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgr10xr RADV divergent case/level-2 232 elements differ (U32), the largest difference 1049601 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGR10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (803, 232, 58, 13 and 3 words), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgr10xr RADV divergent case/level-3 58 elements differ (U32), the largest difference 1049601 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGR10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (803, 232, 58, 13 and 3 words), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgr10xr RADV divergent case/level-4 13 elements differ (U32), the largest difference 1049601 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGR10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (803, 232, 58, 13 and 3 words), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgr10xr RADV divergent case/level-5 3 elements differ (U32), the largest difference 1025 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGR10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (803, 232, 58, 13 and 3 words), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV divergent case/level-1 58 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV divergent case/level-2 78 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV divergent case/level-3 46 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV divergent case/level-4 18 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV divergent case/level-5 5 elements differ (U16), the largest difference 64 `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
blit-generated-mipmaps-bgra10xr RADV divergent case/level-6 1 element differs (U16): Metal 32000 (0x7d00), ours 32064 (0x7d40) `generateMipmapsForTexture:` of a 64x64 `Shared` `BGRA10_XR` texture of seven levels is the runtime's bilinear compute filter in the device's `float` (`mipmap_filter.rs`; no Vulkan format holds an extended-range code, so no blit filters one), announced as `device-filtered-mipmaps` (in `replay::NATIVE_NOTES`), where Metal's levels are Apple's datapath (this case's committed recording, an Apple M3 Max under macOS 27.0.1). Every differing field is a tie, one code: its taps' exact average lies halfway between two codes, and the filter and Apple's datapath each answer one of the two (each level filtered from Metal's own level above by the filter's IEEE `f32` rule differs from Metal's at ties alone, and no one rule for the codes' average, half up, to even or down, gives Metal's levels). The filter's rule in IEEE `f32` on the CPU, from level 0, differs from Metal's levels in this venue's counts exactly (58, 78, 46, 18, 5 and 1 fields), as llvmpipe's levels do; level 0, and the host's round trip of it before the filter ran, are Metal's bytes. The note's documentation states no bound against Metal's answer, so what is open is that bound: one code of a 10-bit extended-range field, at a tie, here.
#
# A BC1 to BC5 texel on llvmpipe, whose driver is not measured to decode the formats as Metal
# does: the device's own decode of the texture's BC image, announced `compressed-texel-decode`
Can't render this file because it is too large.
@@ -0,0 +1,303 @@
// Whether a small command buffer committed on one queue after a burst of command buffers on
// another waits for the whole burst, on Metal.
//
// The runtime's scheduler makes command queues that share a `VkQueue` take turns there
// (`QueueTurnPolicy::Fair`, `queue_turns.rs`): a queue keeps about 2 ms of its own expected work
// submitted ahead while another submits there, 16 ms while none does, so another queue's command
// buffer committed after a burst waits behind that much of it and one command buffer, not the
// whole burst. This probe measures what Metal does in that shape.
//
// ONE CASE PER PROCESS, chosen on the command line; five rounds a case. In every round queue A
// runs one command buffer alone, then commits BURST (64) command buffers back to back, each one
// dispatch of a kernel that spins about 4 ms (calibrated first, alone) and writes A's buffer; 5 ms
// after A's last commit, B commits one small command buffer that writes B's own buffer:
//
// compute B: one dispatch of one thread on queue B (no copy engine).
// blit B: a 256-byte fill on queue B.
// render B: a render pass on queue B that clears a 4x4 texture and draws one triangle.
// same-queue control: B's compute on queue A, behind the whole burst by Metal's contract.
// one-long control: A commits the burst's 64 dispatches as ONE command buffer, then B's
// compute on queue B.
//
// Each round reports, in ms from B's commit: B's GPU start and end and its completed handler; how
// many of A's command buffers ended after B's commit and before B's GPU start (A's work B waited
// behind), and how many began after B's GPU end (A's work B went ahead of); and A's burst's last
// GPU end. Every resource is tracked; A and B share none. Each round's GPU work is about 0.26 s,
// far below Metal's 5 s command buffer timeout; no fault, no untracked write, no wait that can
// hang.
//
// WHAT IT MEASURED (MTL_DEBUG_LAYER unset; five rounds a case, one process a case; times from B's
// commit to its GPU start; "ahead of" counts A's command buffers that began after B's end):
//
// M3 Max, macOS 27.0.1: compute and blit 0.1-0.2 ms, render 4.2-4.4 ms, ahead of 56-62 of A's
// 64; same-queue 20.9 ms (34.0 in the first round), after 22-27 of A's 64 ended and ahead of
// 34 of them; one-long 0.16-0.21 ms, while A's one 244 ms command buffer ran.
// Radeon Pro 5300M, macOS 26.7.1: compute 98-111 ms, after 60-64 of A's 64 ended, ahead of
// none; blit and render 0.07-0.33 ms (6.9 and 7.1 ms in the first round), ahead of 59-61;
// same-queue 98.8-110.3 ms, after 60-64, ahead of none; one-long 92.3-99.4 ms, after A's
// command buffer ended.
// UHD 630, macOS 26.7.1: compute, blit and render 77-240 ms, after 60-63 of A's 64 ended;
// same-queue 77-194 ms, after 60-63, ahead of none; one-long 231-234 ms, 0.05 ms after A's
// command buffer ended.
//
// So the M3 runs a second queue's command buffer among the first queue's burst and beside its one
// long command buffer, and runs the same queue's later command buffer, which shares nothing with
// the burst, among it too; the 5300M runs a second queue's blit or render among the burst, but its
// compute after the burst and after the long command buffer; the 630 runs the burst and the long
// command buffer first in every case.
//
// A's queue allows BURST + 2 command buffers (`newCommandQueueWithMaxCommandBufferCount:`): at
// the default 64, same-queue's B, made on A's queue while A's 64 were not yet committed, would
// wait for a free one forever.
//
// Run with the case alone for the system default device, or with a part of a device's name
// first to pick it among `MTLCopyAllDevices()` (an x86 Mac's two GPUs: `5300M`, `630`):
// cross_queue_burst_turns [DEVICE] compute|blit|render|same-queue|one-long
//
// Build (no cargo target needed; add `-arch x86_64` for an x86 Mac):
// clang -fobjc-arc -O1 -fmodules -o cross_queue_burst_turns cross_queue_burst_turns.m \
// -framework Foundation -framework Metal
//
// Measuring runs keep `MTL_DEBUG_LAYER` OUT of the environment.
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <mach/mach_time.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static void P(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
fputs("RESULT ", stdout);
vfprintf(stdout, fmt, ap);
fputc('\n', stdout);
fflush(stdout);
va_end(ap);
}
/// The host's clock in seconds, the one `GPUStartTime` and `GPUEndTime` answer on.
static double host_seconds(void) {
static mach_timebase_info_data_t base;
if (base.denom == 0) {
mach_timebase_info(&base);
}
return (double)mach_absolute_time() * base.numer / base.denom / 1e9;
}
static const int BURST = 64;
static const int ROUNDS = 5;
static const NSUInteger THREADS = 256;
static NSString *const kSource =
@"#include <metal_stdlib>\n"
"using namespace metal;\n"
"kernel void spin(device uint *b [[buffer(0)]],\n"
" constant uint &iters [[buffer(1)]],\n"
" uint gid [[thread_position_in_grid]]) {\n"
" uint x = gid * 2654435761u;\n"
" for (uint i = 0; i < iters; i++) { x = x * 1664525u + 1013904223u; }\n"
" b[gid] = x == 0x12345678u ? 1u : 0xFFFFFFFFu;\n"
"}\n"
"kernel void one(device uint *b [[buffer(0)]]) { b[0] = 7u; }\n"
"vertex float4 corner(uint vid [[vertex_id]]) {\n"
" float2 p[3] = {float2(-1, -1), float2(3, -1), float2(-1, 3)};\n"
" return float4(p[vid], 0, 1);\n"
"}\n"
"fragment float4 shade() { return float4(0.25, 0.5, 0.75, 1); }\n";
typedef struct {
id<MTLDevice> device;
id<MTLComputePipelineState> spin;
id<MTLComputePipelineState> one;
id<MTLRenderPipelineState> draw;
id<MTLBuffer> a_words;
id<MTLBuffer> b_words;
id<MTLTexture> target;
} Probe;
static void encode_spin(Probe *p, id<MTLComputeCommandEncoder> e, uint32_t iters) {
[e setComputePipelineState:p->spin];
[e setBuffer:p->a_words offset:0 atIndex:0];
[e setBytes:&iters length:sizeof iters atIndex:1];
[e dispatchThreadgroups:MTLSizeMake(THREADS / 64, 1, 1)
threadsPerThreadgroup:MTLSizeMake(64, 1, 1)];
}
/// A command buffer of `dispatches` spins on `queue`.
static id<MTLCommandBuffer> spins(Probe *p, id<MTLCommandQueue> queue, uint32_t iters,
int dispatches) {
id<MTLCommandBuffer> cb = [queue commandBuffer];
id<MTLComputeCommandEncoder> e = [cb computeCommandEncoder];
for (int d = 0; d < dispatches; d++) {
encode_spin(p, e, iters);
}
[e endEncoding];
return cb;
}
static double time_alone(Probe *p, id<MTLCommandQueue> queue, uint32_t iters) {
id<MTLCommandBuffer> cb = spins(p, queue, iters, 1);
[cb commit];
[cb waitUntilCompleted];
return (cb.GPUEndTime - cb.GPUStartTime) * 1000.0;
}
/// B's small command buffer of `kind` on `queue`.
static id<MTLCommandBuffer> small(Probe *p, id<MTLCommandQueue> queue, const char *kind) {
id<MTLCommandBuffer> cb = [queue commandBuffer];
if (strcmp(kind, "blit") == 0) {
id<MTLBlitCommandEncoder> e = [cb blitCommandEncoder];
[e fillBuffer:p->b_words range:NSMakeRange(0, 256) value:1];
[e endEncoding];
} else if (strcmp(kind, "render") == 0) {
MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor];
pass.colorAttachments[0].texture = p->target;
pass.colorAttachments[0].loadAction = MTLLoadActionClear;
pass.colorAttachments[0].storeAction = MTLStoreActionStore;
pass.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 1);
id<MTLRenderCommandEncoder> e = [cb renderCommandEncoderWithDescriptor:pass];
[e setRenderPipelineState:p->draw];
[e drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[e endEncoding];
} else {
id<MTLComputeCommandEncoder> e = [cb computeCommandEncoder];
[e setComputePipelineState:p->one];
[e setBuffer:p->b_words offset:0 atIndex:0];
[e dispatchThreadgroups:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
[e endEncoding];
}
return cb;
}
static void round_of(Probe *p, const char *which, uint32_t iters, int round) {
BOOL same_queue = strcmp(which, "same-queue") == 0;
BOOL one_long = strcmp(which, "one-long") == 0;
const char *kind = same_queue || one_long ? "compute" : which;
id<MTLCommandQueue> queue_a = [p->device newCommandQueueWithMaxCommandBufferCount:BURST + 2];
id<MTLCommandQueue> queue_b = same_queue ? queue_a : [p->device newCommandQueue];
// A's queue warm, alone.
id<MTLCommandBuffer> warm = spins(p, queue_a, iters, 1);
[warm commit];
[warm waitUntilCompleted];
int count = one_long ? 1 : BURST;
NSMutableArray<id<MTLCommandBuffer>> *burst = [NSMutableArray arrayWithCapacity:count];
for (int c = 0; c < count; c++) {
[burst addObject:spins(p, queue_a, iters, one_long ? BURST : 1)];
}
id<MTLCommandBuffer> b = small(p, queue_b, kind);
__block double handled = 0;
[b addCompletedHandler:^(id<MTLCommandBuffer> cb) {
(void)cb;
handled = host_seconds();
}];
for (id<MTLCommandBuffer> cb in burst) {
[cb commit];
}
usleep(5000);
double committed = host_seconds();
[b commit];
[b waitUntilCompleted];
for (id<MTLCommandBuffer> cb in burst) {
[cb waitUntilCompleted];
}
int behind = 0, after = 0;
double last_end = 0;
for (id<MTLCommandBuffer> cb in burst) {
if (cb.GPUEndTime > committed && cb.GPUEndTime <= b.GPUStartTime) {
behind++;
}
if (cb.GPUStartTime >= b.GPUEndTime) {
after++;
}
last_end = MAX(last_end, cb.GPUEndTime);
}
double ms = 1000.0;
P("%s round %d: B's GPU start %.2f end %.2f completed handler %.2f ms; A's command buffers "
"ending between B's commit and its start %d, starting after B's end %d of %d; A's last end "
"%.2f ms; B %s",
which, round, (b.GPUStartTime - committed) * ms, (b.GPUEndTime - committed) * ms,
(handled - committed) * ms, behind, after, count, (last_end - committed) * ms,
b.error ? b.error.localizedDescription.UTF8String : "no error");
}
int main(int argc, char **argv) {
@autoreleasepool {
if (argc < 2 || argc > 3) {
fprintf(stderr, "usage: %s [DEVICE] compute|blit|render|same-queue|one-long\n", argv[0]);
return 2;
}
const char *which = argv[argc - 1];
const char *cases[] = {"compute", "blit", "render", "same-queue", "one-long"};
BOOL known = NO;
for (int c = 0; c < 5; c++) {
known |= strcmp(which, cases[c]) == 0;
}
if (!known) {
fprintf(stderr, "unknown case %s\n", which);
return 2;
}
Probe p;
p.device = MTLCreateSystemDefaultDevice();
if (argc == 3) {
p.device = nil;
for (id<MTLDevice> device in MTLCopyAllDevices()) {
if (strstr(device.name.UTF8String, argv[1])) {
p.device = device;
}
}
if (!p.device) {
P("no device named like %s", argv[1]);
return 1;
}
}
NSOperatingSystemVersion v = [[NSProcessInfo processInfo] operatingSystemVersion];
P("device %s macOS %ld.%ld.%ld case %s MTL_DEBUG_LAYER=%s", p.device.name.UTF8String,
(long)v.majorVersion, (long)v.minorVersion, (long)v.patchVersion, which,
getenv("MTL_DEBUG_LAYER") ? getenv("MTL_DEBUG_LAYER") : "unset");
NSError *error = nil;
id<MTLLibrary> library = [p.device newLibraryWithSource:kSource options:nil error:&error];
if (!library) {
P("library: %s", error.localizedDescription.UTF8String);
return 1;
}
p.spin = [p.device newComputePipelineStateWithFunction:[library newFunctionWithName:@"spin"]
error:&error];
p.one = [p.device newComputePipelineStateWithFunction:[library newFunctionWithName:@"one"]
error:&error];
MTLRenderPipelineDescriptor *desc = [MTLRenderPipelineDescriptor new];
desc.vertexFunction = [library newFunctionWithName:@"corner"];
desc.fragmentFunction = [library newFunctionWithName:@"shade"];
desc.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA8Unorm;
p.draw = [p.device newRenderPipelineStateWithDescriptor:desc error:&error];
if (!p.spin || !p.one || !p.draw) {
P("pipeline: %s", error.localizedDescription.UTF8String);
return 1;
}
p.a_words = [p.device newBufferWithLength:THREADS * 4 options:MTLResourceStorageModePrivate];
p.b_words = [p.device newBufferWithLength:4096 options:MTLResourceStorageModePrivate];
MTLTextureDescriptor *t =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:4
height:4
mipmapped:NO];
t.usage = MTLTextureUsageRenderTarget;
t.storageMode = MTLStorageModePrivate;
p.target = [p.device newTextureWithDescriptor:t];
id<MTLCommandQueue> calibration = [p.device newCommandQueue];
uint32_t iters = 1u << 10;
double ms = time_alone(&p, calibration, iters);
for (int step = 0; step < 12 && (ms < 3.5 || ms > 4.5); step++) {
double scale = ms > 0.1 ? 4.0 / ms : 8.0;
iters = (uint32_t)MIN((double)(1u << 28), MAX(1.0, iters * scale));
ms = time_alone(&p, calibration, iters);
}
P("one dispatch alone: %u iterations, %.2f ms", iters, ms);
for (int round = 0; round < ROUNDS; round++) {
round_of(&p, which, iters, round);
}
}
return 0;
}
@@ -0,0 +1,204 @@
// Whether Metal orders a fill and a copy inside one blit command encoder where the two meet only
// through memory two no-copy buffers share.
//
// The runtime's host aliases (`host_aliases.rs`) give each use of a no-copy buffer made over
// exactly the bytes of a live one a use of the memory's own key, so its tracker orders a write
// through one and a read through the other inside an encoder as it orders one resource's. This
// probe measures what Metal does in that shape: in ONE blit command encoder of one command buffer,
// `fillBuffer:` writes a value through no-copy buffer 1, then `copyFromBuffer:` reads no-copy
// buffer 2, over the same page-aligned pages, into a third, Shared buffer; the command buffer is
// committed and waited for, and the copy's bytes are compared with the fill's value.
//
// Cases, ROUNDS (20) rounds each, every round with its own fill value:
//
// nocopy-two-one-encoder the copy reads buffer 2.
// nocopy-one-one-encoder control: the copy reads buffer 1, the fill's own (it must see the
// whole fill).
//
// Before each round, with the GPU idle (the round before was waited for), the host writes the
// pages with another value (`before`) and the third buffer with a third. Each round reports its
// fill value, how many of the copy's 32-bit words held the fill's value, `before` or neither, how
// many of the pages' words held the fill's value after it, and the command buffer's GPU time. Each
// case ends with the rounds whose copy saw the whole fill, none of it, or part. Every buffer is
// Shared and tracked (`MTLHazardTrackingModeTracked`), 32 MiB each; no fault, no untracked access,
// no wait that can hang.
//
// WHAT IT MEASURED (MTL_DEBUG_LAYER unset; 20 rounds a case, one process a device):
//
// case M3 Max, 27.0.1 Radeon Pro 5300M, 26.7.1 UHD 630, 26.7.1
// nocopy-two-one-encoder part in 20 part in 20 whole in 20
// nocopy-one-one-encoder whole in 20 whole in 20 whole in 20
//
// Where the copy saw part of the fill, the rest of its 8.39M words held the bytes from before:
// about 8.07M-8.11M of them the fill on the M3, 0.18M-0.30M on the 5300M. So Metal orders the
// fill and the copy through one buffer on all three, and through two no-copy buffers over the
// same pages on the 630 alone: the M3 and the 5300M ran the copy alongside the fill.
//
// Run with the case alone for the system default device, or with a part of a device's name first
// to pick it among `MTLCopyAllDevices()` (an x86 Mac's two GPUs: `5300M`, `630`); `all` runs both
// cases, the control second:
// nocopy_alias_one_encoder [DEVICE] nocopy-two-one-encoder|nocopy-one-one-encoder|all
//
// Build (no cargo target needed; for an x86 Mac on an older macOS add `-arch x86_64` and a
// `-mmacosx-version-min=` no newer than its release):
// clang -fobjc-arc -O1 -fmodules -o nocopy_alias_one_encoder nocopy_alias_one_encoder.m \
// -framework Foundation -framework Metal
//
// Measuring runs keep `MTL_DEBUG_LAYER` OUT of the environment.
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static void P(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
fputs("RESULT ", stdout);
vfprintf(stdout, fmt, ap);
fputc('\n', stdout);
fflush(stdout);
va_end(ap);
}
static const NSUInteger kBytes = 32u << 20;
static const int kRounds = 20;
// How many of 32 MiB's words hold the fill's value, `before`, or neither.
typedef struct {
unsigned long fill, before, other;
} Words;
static Words count(const void *bytes, uint8_t fill, uint8_t before) {
Words w = {0, 0, 0};
const uint32_t f = fill * 0x01010101u, b = before * 0x01010101u;
const uint32_t *words = (const uint32_t *)bytes;
for (NSUInteger i = 0; i < kBytes / 4; i++) {
if (words[i] == f) {
w.fill++;
} else if (words[i] == b) {
w.before++;
} else {
w.other++;
}
}
return w;
}
static id<MTLBuffer> over_pages(id<MTLDevice> device, void *pages) {
return [device newBufferWithBytesNoCopy:pages
length:kBytes
options:MTLResourceStorageModeShared |
MTLResourceHazardTrackingModeTracked
deallocator:nil];
}
// One case's rounds; 1 where a buffer could not be made or a command buffer failed.
static int run_case(id<MTLDevice> device, id<MTLCommandQueue> queue, const char *name) {
const BOOL two = strcmp(name, "nocopy-two-one-encoder") == 0;
void *pages = NULL;
if (posix_memalign(&pages, (size_t)getpagesize(), kBytes) != 0) {
P("%s: no pages", name);
return 1;
}
int whole = 0, none = 0, part = 0, failed = 0;
@autoreleasepool {
id<MTLBuffer> one = over_pages(device, pages);
id<MTLBuffer> source = two ? over_pages(device, pages) : one;
id<MTLBuffer> out =
[device newBufferWithLength:kBytes
options:MTLResourceStorageModeShared |
MTLResourceHazardTrackingModeTracked];
if (!one || !source || !out) {
P("%s: a buffer was refused", name);
failed = 1;
}
for (int round = 0; round < kRounds && !failed; round++) {
@autoreleasepool {
const uint8_t fill = (uint8_t)(17 + round * 13);
const uint8_t before = fill ^ 0xff, mark = fill ^ 0x0f;
memset(pages, before, kBytes);
memset(out.contents, mark, kBytes);
id<MTLCommandBuffer> cb = [queue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
[blit fillBuffer:one range:NSMakeRange(0, kBytes) value:fill];
[blit copyFromBuffer:source
sourceOffset:0
toBuffer:out
destinationOffset:0
size:kBytes];
[blit endEncoding];
[cb commit];
[cb waitUntilCompleted];
if (cb.status != MTLCommandBufferStatusCompleted) {
P("%s round %d: status %ld, %s", name, round, (long)cb.status,
cb.error.localizedDescription.UTF8String);
failed++;
continue;
}
const Words copy = count(out.contents, fill, before);
const Words landed = count(pages, fill, before);
P("%s round %d: fill 0x%02x; the copy's words: %lu fill, %lu before, %lu other; the "
"pages' words: %lu fill of %lu; GPU %.3f ms",
name, round, fill, copy.fill, copy.before, copy.other, landed.fill,
(unsigned long)(kBytes / 4), (cb.GPUEndTime - cb.GPUStartTime) * 1e3);
if (copy.fill == kBytes / 4) {
whole++;
} else if (copy.fill == 0) {
none++;
} else {
part++;
}
}
}
}
free(pages);
P("%s: %d rounds; the copy saw the whole fill in %d, none of it in %d, part of it in %d; %d "
"failed",
name, kRounds, whole, none, part, failed);
return failed ? 1 : 0;
}
int main(int argc, char **argv) {
@autoreleasepool {
if (argc < 2 || argc > 3) {
fprintf(stderr, "usage: %s [DEVICE] nocopy-two-one-encoder|nocopy-one-one-encoder|all\n",
argv[0]);
return 2;
}
const char *which = argv[argc - 1];
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
if (argc == 3) {
device = nil;
for (id<MTLDevice> candidate in MTLCopyAllDevices()) {
if (strstr(candidate.name.UTF8String, argv[1])) {
device = candidate;
}
}
}
if (!device) {
P("no device named like %s", argc == 3 ? argv[1] : "the default");
return 1;
}
NSOperatingSystemVersion v = [[NSProcessInfo processInfo] operatingSystemVersion];
P("device %s macOS %ld.%ld.%ld", device.name.UTF8String, (long)v.majorVersion,
(long)v.minorVersion, (long)v.patchVersion);
id<MTLCommandQueue> queue = [device newCommandQueue];
const char *cases[] = {"nocopy-two-one-encoder", "nocopy-one-one-encoder"};
int ran = 0, failed = 0;
for (int c = 0; c < 2; c++) {
if (strcmp(which, "all") == 0 || strcmp(which, cases[c]) == 0) {
ran++;
failed += run_case(device, queue, cases[c]);
}
}
if (!ran) {
fprintf(stderr, "unknown case %s\n", which);
return 2;
}
return failed ? 1 : 0;
}
}
@@ -0,0 +1,362 @@
// What plain Metal answers for the 16x16x16 simdgroup matrix products,
// `air.simdgroup_matrix_16x16x16_[widening_]multiply_accumulate`: `<8 x R> (<8 x A>, i1,
// <8 x B>, i1, <8 x R>)`, each lane's eight cells of `A`, its transpose flag, of `B`, its flag,
// and of the accumulator `C`. MSL has no spelling for them; the owned fixture
// `engine/simd_matrix16.metal` declares one function per form, renamed to the intrinsic
// (scripts/regen-air-fixtures), in kernels `m16_<form>_<ta><tb>` that pass element `t` of each
// buffer as thread `t`'s cells: `float` factors (`f32_f32`), `half` factors (`f16_f16`) and signed
// 8-bit integers widened to `int` (`s_s`), each with the four flag pairs.
//
// Run with simd_matrix16.sh beside this file (it assembles the committed fixture's typed text
// into a metallib and builds this probe), or by hand:
// xcrun metal-as simd_matrix16.air.ll -o m.air && xcrun metallib m.air -o m.metallib
// clang -fobjc-arc -O1 -fmodules -o simd_matrix16 simd_matrix16.m \
// -framework Foundation -framework Metal
// ./simd_matrix16 m.metallib <form> (one form a process; MTL_DEBUG_LAYER unset)
//
// For each flag pair it prints whether a compute pipeline was made (or Metal's error), then, for
// a pipeline Metal made, the measured relation of the product, as dispatches of 256 one-simdgroup
// threadgroups:
//
// - `pairs`: cell `p` (lane `p >> 3`, element `p & 7`) of one factor is 1 and every other cell of
// it 0, the other factor's cell `q` holds a digit of `q` plus one (two passes for 8-bit
// integers), and `C` is 0; result cell `d` is then 0 or the digit of the one cell `q` the product
// pairs with `p` for `d`. A line `REL <form> <tt> <d> <hex>` lists, for result cell `d`, every
// pair (`A` cell, `B` cell) as two bytes, sorted.
// - `accumulate`: `A` and `B` 0, `C` distinct integers: the result equals `C` cell for cell.
// - `check`: small integer cells everywhere, every sum exact in the result format: the result
// equals `C + Σ A·B` over the measured pairs, cell for cell.
//
// Exit status: 0 when Metal answered (a refused pipeline is an answer), 2 when the probe could not
// ask (arguments, the metallib, a command buffer's error).
//
// WHAT IT MEASURED (Apple M3 Max, macOS 27.0.1, Apple metal 32023.922): Metal refuses every
// pipeline of the three forms and four flag pairs at its creation, in 1 to 42 ms, with
// `AGXMetalG15X_M1` code 3, "simdgroup_matrix<T,16,16x16> operations are supported by
// GPUFamily10 and later". No pipeline was made, so no relation was measured. The translator
// refuses these products `Unsupported{SimdgroupMatrix16x16x16}`, and the runtime answers that as
// Metal's own refusal (`Needs::MetalGpuFamily` of Apple10) on a device that does not claim
// Apple10.
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum { F32, F16, S8, I32 } Fmt;
typedef struct {
const char *name;
Fmt a, b, r;
} Form;
static const Form FORMS[] = {
{"f32_f32", F32, F32, F32},
{"f16_f16", F16, F16, F32},
{"s_s", S8, S8, I32},
};
enum { GROUPS = 256, CELLS = 256, NONE = 0xffff };
static unsigned fsize(Fmt f) {
switch (f) {
case F32:
case I32:
return 4;
case F16:
return 2;
case S8:
return 1;
}
return 4;
}
// The integers 1..base are exact in the format.
static unsigned base_of(Fmt f) { return f == S8 ? 16 : 256; }
static unsigned passes_of(Fmt f) {
unsigned b = base_of(f), n = 0, reach = 1;
while (reach < CELLS) {
reach *= b;
n++;
}
return n;
}
static void die(const char *what) {
printf("PROBE-ERROR %s\n", what);
exit(2);
}
static void put(Fmt f, uint8_t *base, size_t index, double v) {
uint8_t *p = base + index * fsize(f);
switch (f) {
case F32: {
float x = (float)v;
memcpy(p, &x, 4);
break;
}
case I32: {
int32_t x = (int32_t)v;
memcpy(p, &x, 4);
break;
}
case F16: {
_Float16 h = (_Float16)v;
if ((double)h != v) {
die("a half value is not exact");
}
memcpy(p, &h, 2);
break;
}
case S8:
if (v < -128 || v > 127) {
die("an int8 value out of range");
}
*p = (uint8_t)(int8_t)v;
break;
}
}
static double get(Fmt r, const uint8_t *base, size_t index) {
const uint8_t *p = base + index * fsize(r);
if (r == I32) {
int32_t x;
memcpy(&x, p, 4);
return x;
}
float x;
memcpy(&x, p, 4);
return x;
}
typedef struct {
id<MTLCommandQueue> q;
id<MTLComputePipelineState> pso;
const Form *form;
id<MTLBuffer> a, b, c, d;
} Run;
static void clear(Run *r) {
memset(r->a.contents, 0, r->a.length);
memset(r->b.contents, 0, r->b.length);
memset(r->c.contents, 0, r->c.length);
memset(r->d.contents, 0xa5, r->d.length);
}
static void dispatch(Run *r, NSUInteger groups) {
id<MTLCommandBuffer> cb = [r->q commandBuffer];
id<MTLComputeCommandEncoder> e = [cb computeCommandEncoder];
[e setComputePipelineState:r->pso];
[e setBuffer:r->a offset:0 atIndex:0];
[e setBuffer:r->b offset:0 atIndex:1];
[e setBuffer:r->c offset:0 atIndex:2];
[e setBuffer:r->d offset:0 atIndex:3];
[e dispatchThreadgroups:MTLSizeMake(groups, 1, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)];
[e endEncoding];
[cb commit];
[cb waitUntilCompleted];
if (cb.status != MTLCommandBufferStatusCompleted) {
printf("PROBE-ERROR command buffer status %ld: %s\n", (long)cb.status,
cb.error.description.UTF8String);
exit(2);
}
}
// Cell `p` of simdgroup `s`: element `s * 256 + p` (lane `p >> 3`, element `p & 7`).
static size_t at(unsigned s, unsigned p) { return (size_t)s * CELLS + p; }
static uint64_t lcg(uint64_t *x) {
*x = *x * 6364136223846793005ull + 1442695040888963407ull;
return *x >> 33;
}
static void measure(Run *r, const char *tt) {
const Form *f = r->form;
// The one-hot factor is `A`, the counted one `B` (both factors of a form share a format).
unsigned base = base_of(f->b), passes = passes_of(f->b);
static uint16_t rel[CELLS][CELLS]; // [p][d]: the counted cell
static int seen[CELLS][CELLS]; // passes with a nonzero result
memset(rel, 0, sizeof rel);
memset(seen, 0, sizeof seen);
unsigned odd = 0;
unsigned scale = 1;
for (unsigned pass = 0; pass < passes; pass++, scale *= base) {
clear(r);
for (unsigned s = 0; s < GROUPS; s++) {
put(f->a, r->a.contents, at(s, s), 1);
for (unsigned q = 0; q < CELLS; q++) {
put(f->b, r->b.contents, at(s, q), (q / scale) % base + 1);
}
}
dispatch(r, GROUPS);
for (unsigned s = 0; s < GROUPS; s++) {
for (unsigned d = 0; d < CELLS; d++) {
double v = get(f->r, r->d.contents, at(s, d));
if (v == 0) {
continue;
}
if (v != floor(v) || v < 1 || v > base) {
if (odd++ < 8) {
printf(" odd value %s %s pass %u p %u d %u: %.9g\n", f->name, tt, pass,
s, d, v);
}
continue;
}
seen[s][d]++;
rel[s][d] += (uint16_t)(((unsigned)v - 1) * scale);
}
}
}
unsigned mixed = 0, per_min = CELLS, per_max = 0;
static unsigned char pairs[CELLS][CELLS][2];
unsigned count[CELLS];
uint64_t h = 1469598103934665603ull;
for (unsigned d = 0; d < CELLS; d++) {
count[d] = 0;
// Ascending `A` cell, each with its one `B` cell: the pairs are sorted.
for (unsigned p = 0; p < CELLS; p++) {
if (seen[p][d] == 0) {
continue;
}
if (seen[p][d] != (int)passes || rel[p][d] >= CELLS) {
mixed++;
continue;
}
pairs[d][count[d]][0] = (unsigned char)p;
pairs[d][count[d]][1] = (unsigned char)rel[p][d];
count[d]++;
}
if (count[d] < per_min) per_min = count[d];
if (count[d] > per_max) per_max = count[d];
printf("REL %s %s %u ", f->name, tt, d);
for (unsigned i = 0; i < count[d]; i++) {
printf("%02x%02x", pairs[d][i][0], pairs[d][i][1]);
h = (h ^ pairs[d][i][0]) * 1099511628211ull;
h = (h ^ pairs[d][i][1]) * 1099511628211ull;
}
h = (h ^ 0xff) * 1099511628211ull;
printf("\n");
}
printf("%s %s pairs: per result cell %u..%u, odd values %u, partial cells %u, passes %u, "
"relation %016llx\n",
f->name, tt, per_min, per_max, odd, mixed, passes, (unsigned long long)h);
// accumulate: A = B = 0, C distinct integers in two simdgroups.
clear(r);
for (unsigned s = 0; s < 2; s++) {
for (unsigned d = 0; d < CELLS; d++) {
put(f->r, r->c.contents, at(s, d), 1000.0 * s + d + 1);
}
}
dispatch(r, 2);
unsigned acc_bad = 0;
for (unsigned s = 0; s < 2; s++) {
for (unsigned d = 0; d < CELLS; d++) {
if (get(f->r, r->d.contents, at(s, d)) != 1000.0 * s + d + 1) {
acc_bad++;
}
}
}
printf("%s %s accumulate: %u of 512 cells differ from C\n", f->name, tt, acc_bad);
// check: small integers everywhere against C + sum over the measured pairs.
enum { CHECK = 8 };
clear(r);
uint64_t x = 0x5eed1234u;
static double av[CHECK][CELLS], bv[CHECK][CELLS], cv[CHECK][CELLS];
for (unsigned s = 0; s < CHECK; s++) {
for (unsigned p = 0; p < CELLS; p++) {
av[s][p] = (double)(int)(lcg(&x) % 7) - 3;
bv[s][p] = (double)(int)(lcg(&x) % 7) - 3;
cv[s][p] = (double)(int)(lcg(&x) % 17) - 8;
put(f->a, r->a.contents, at(s, p), av[s][p]);
put(f->b, r->b.contents, at(s, p), bv[s][p]);
put(f->r, r->c.contents, at(s, p), cv[s][p]);
}
}
dispatch(r, CHECK);
unsigned bad = 0;
for (unsigned s = 0; s < CHECK; s++) {
for (unsigned d = 0; d < CELLS; d++) {
double want = cv[s][d];
for (unsigned i = 0; i < count[d]; i++) {
want += av[s][pairs[d][i][0]] * bv[s][pairs[d][i][1]];
}
double got = get(f->r, r->d.contents, at(s, d));
if (got != want && bad++ < 4) {
printf(" check %s %s simdgroup %u cell %u: %.9g, measured pairs give %.9g\n",
f->name, tt, s, d, got, want);
}
}
}
printf("%s %s check: %u of %u cells differ from C + sum over the measured pairs\n", f->name,
tt, bad, CHECK * CELLS);
}
int main(int argc, char **argv) {
@autoreleasepool {
if (argc != 3) {
die("usage: simd_matrix16 <metallib> <form>");
}
const Form *form = NULL;
for (size_t i = 0; i < sizeof FORMS / sizeof FORMS[0]; i++) {
if (strcmp(FORMS[i].name, argv[2]) == 0) {
form = &FORMS[i];
}
}
if (!form) {
die("unknown form");
}
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
if (!dev) {
die("no Metal device");
}
printf("device %s, form %s\n", dev.name.UTF8String, form->name);
NSError *err = nil;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:argv[1]]];
id<MTLLibrary> lib = [dev newLibraryWithURL:url error:&err];
if (!lib) {
printf("PROBE-ERROR library: %s\n", err.description.UTF8String);
return 2;
}
Run r = {.q = [dev newCommandQueue], .form = form};
r.a = [dev newBufferWithLength:GROUPS * CELLS * fsize(form->a)
options:MTLResourceStorageModeShared];
r.b = [dev newBufferWithLength:GROUPS * CELLS * fsize(form->b)
options:MTLResourceStorageModeShared];
r.c = [dev newBufferWithLength:GROUPS * CELLS * fsize(form->r)
options:MTLResourceStorageModeShared];
r.d = [dev newBufferWithLength:GROUPS * CELLS * fsize(form->r)
options:MTLResourceStorageModeShared];
static const char *TT[] = {"00", "01", "10", "11"};
for (int k = 0; k < 4; k++) {
NSString *name = [NSString stringWithFormat:@"m16_%s_%s", form->name, TT[k]];
id<MTLFunction> fn = [lib newFunctionWithName:name];
if (!fn) {
printf("%s %s function: missing from the library\n", form->name, TT[k]);
return 2;
}
err = nil;
NSDate *t0 = [NSDate date];
id<MTLComputePipelineState> pso = [dev newComputePipelineStateWithFunction:fn
error:&err];
double ms = -[t0 timeIntervalSinceNow] * 1000.0;
if (!pso) {
printf("%s %s pipeline: REFUSED after %.0f ms: %s\n", form->name, TT[k], ms,
err.description.UTF8String);
continue;
}
printf("%s %s pipeline: made in %.0f ms, threadExecutionWidth %lu\n", form->name,
TT[k], ms, (unsigned long)pso.threadExecutionWidth);
if (pso.threadExecutionWidth != 32) {
die("a simdgroup is not 32 threads");
}
r.pso = pso;
measure(&r, TT[k]);
}
}
return 0;
}
@@ -0,0 +1,28 @@
#!/bin/sh
# Runs simd_matrix16.m on this Mac's Metal over the committed fixture
# engine/simd_matrix16.air.ll: assembles its typed text into a metallib, builds the probe, and runs
# it once per form named, one process each, so that a compiler failure on one form leaves the
# others. Scratch files live in a temporary directory removed on exit.
#
# Usage: sh crates/metal2vulkan-conformance/probes/simd_matrix16.sh <form>...
# (forms: f32_f32 f16_f16 s_s)
set -u
unset MTL_DEBUG_LAYER
here=$(cd "$(dirname "$0")" && pwd)
fixture="$here/../../metal2vulkan-validation/fixtures/public/engine/simd_matrix16.air.ll"
work=$(mktemp -d "${TMPDIR:-/tmp}/simd_matrix16.XXXXXX") || exit 2
trap 'rm -rf "$work"' EXIT
sw_vers
xcrun -sdk macosx metal --version | head -1
xcrun -sdk macosx metal-as "$fixture" -o "$work/m.air" || exit 2
xcrun -sdk macosx metallib "$work/m.air" -o "$work/m.metallib" || exit 2
clang -fobjc-arc -O1 -fmodules -o "$work/probe" "$here/simd_matrix16.m" \
-framework Foundation -framework Metal || exit 2
status=0
for form in "$@"; do
"$work/probe" "$work/m.metallib" "$form"
code=$?
echo "EXIT $form=$code"
[ "$code" -eq 0 ] || status=1
done
exit $status
@@ -190,6 +190,15 @@ impl Call {
matches!(self, Call::Reset | Call::Copy)
}
/// Whether the call's GPU write is the first use of the buffer it writes: the copy's
/// destination, which the case makes and touches nowhere before the copy. On a device that
/// places records by their first use, that write places them in device-local memory, where the
/// host step of the execution after it reads them through copies. The reset's buffer is the
/// CPU's first, so its records lie in host memory; the optimize writes nothing.
const fn places_its_records_on_the_gpu(self) -> bool {
matches!(self, Call::Copy)
}
/// The piece of work the call encodes over `leg`, out of the leg's source buffer and, where
/// the call has one, its destination.
fn work(self, source: Handle, destination: Handle, leg: Leg) -> RenderWork {
@@ -354,12 +363,25 @@ impl Case for BlitIndirectCommands {
// nothing else (replay-nvidia.log). On MoltenVK, where
// the chip's GPU shares the CPU's memory, it cannot fire at all, which is why no
// recording of this suite declares it.
//
// On a device that places records by their first use, the copy case announces
// `staged-indirect-records` (`crate::replay::staged_records_notice` holds the whole
// reason). Measured on the RX 7900 XTX (RADV NAVI31), the case alone at 45e6784e91's
// runtime (`conformance cost --show --runs 1`): host_steps_recorded 3 and
// icb_records_staged_accesses 3 for the copy, the three executions after a copy of at
// least one command, each reading the records the copy wrote into device-local memory;
// the leg that copies none reads its never-written records in place. The reset read
// host_steps_recorded 3 and no staged access, its buffer the CPU's first, so it declares
// nothing. On unified memory, the M3 Max's included, it cannot fire.
let mut named = vec![crate::replay::shared_memory_notice()];
if self.call.replays_on_the_host() {
named.push(crate::replay::notice_allowance(
Degradation::HostReplayedIndirectCommands.code(),
));
}
if self.call.places_its_records_on_the_gpu() {
named.push(crate::replay::staged_records_notice());
}
named
}
@@ -9,9 +9,10 @@
//! holds before anything writes it is the allocation's: over a buffer of 4096 bytes, whose
//! `allocatedSize` is its length, it is the buffer allocated next, which no case can state; over
//! a buffer of 20000 bytes, whose `allocatedSize` is 32768, it is the rest of the buffer's own
//! allocation, and it reads zero. The runtime keeps those texels in a tail of the texture's own
//! (`metal2vulkan-runtime`'s `buffer_texture.rs`), zero when made, so this family asks the second
//! shape, where Metal's answer is one a case can compare: a 16 by 256 `RGBA8Uint` texture at
//! allocation, and it reads zero. The runtime's lie in the buffer's memory too, as a buffer of
//! 16 KiB or more holds its allocation, its length rounded up to 16 KiB, zero when made
//! (`metal2vulkan-runtime`'s `buffer_texture.rs`), so this family asks the second shape, where
//! Metal's answer is one a case can compare: a 16 by 256 `RGBA8Uint` texture at
//! offset 4096, its rows 64 bytes apart, over 20000 bytes. Its rows 0 to 247 lie inside the
//! length, row 248 crosses it 32 bytes (8 texels) in, and rows 249 to 255 lie past it.
//!
@@ -23,10 +24,11 @@
//! (wholly past it), copies rows 240 to 255 into a texture of its own, and reads every one of
//! those back, with the buffer's bytes.
//!
//! Every byte compares exactly. What differs is the announcing: the runtime keeps a texture with
//! a tail as a shadow image and announces `shadowed-texture`, which Metal never does, and a
//! device without unified memory announces `shared-in-system-memory` for the `Shared` buffers the
//! answers are read back through. Nothing here can fault a GPU: one small texture, one thread a
//! Every byte compares exactly. What differs is the announcing: where the device makes no image
//! over the buffer's memory on Metal's layout, the runtime keeps the texture as a shadow image and
//! announces `shadowed-texture`, which Metal never does, and a device without unified memory
//! announces `shared-in-system-memory` for the `Shared` buffers the answers are read back
//! through. Nothing here can fault a GPU: one small texture, one thread a
//! texel, no loop.
use crate::allowance::Allowance;
@@ -84,8 +86,9 @@ fn written(n: u64, set: u64) -> Vec<u8> {
/// What both cases loosen: the notices, and nothing else.
fn allowances() -> Vec<Allowance> {
// The runtime keeps a texture whose texels run past its buffer's length as a shadow image of
// the buffer's bytes and its tail, and announces `shadowed-texture`, which Metal never does.
// Where the device makes no image over the buffer's memory on Metal's layout, the runtime
// keeps the texture as a shadow image of the buffer's bytes, and announces
// `shadowed-texture`, which Metal never does.
// Every case reads its answers back through `Shared` buffers, so a device without unified
// memory announces `shared-in-system-memory` (`crate::replay::shared_memory_notice`).
vec![
@@ -53,9 +53,15 @@ pub const COMMAND_BUFFER_FACTS: &str = "command-buffer-facts";
/// placed their times as it does on an uncalibrated device (`gpu_time.rs`), and every value of
/// the case still compared exactly. The Radeon 780M (RADV PHOENIX) in the same machine agreed
/// with its calibration in the same runs (0) and announced nothing.
const GPU_TIME_NOTICES: [Degradation; 2] = [
///
/// `LooselyCalibratedGpuTimes` is here because a loaded host makes it: a calibration pair whose
/// readings each state the time the reading thread spent off the CPU stays beyond 20 us after
/// the runtime's four readings (the RX 7900 XTX stated 93 and 125 us in full parallel suites),
/// and its times, still inside the command buffer's life, are announced as such (`gpu_time.rs`).
const GPU_TIME_NOTICES: [Degradation; 3] = [
Degradation::GpuTimesFromHost,
Degradation::UncalibratedGpuTimes,
Degradation::LooselyCalibratedGpuTimes,
];
/// A case over one command buffer's own answers.
@@ -110,8 +116,10 @@ impl Case for CommandBufferFactsCase {
// driver's own timestamps wait for every queue's (MoltenVK on Apple's GPUs).
// `UncalibratedGpuTimes`: it places them without calibrated timestamps where the device
// offers none, or where the device's calibration disagrees with the command buffer's life
// (the RX 7900 XTX, `GPU_TIME_NOTICES`). The orderings this case compares do not depend on
// either, which is why the case can take the notice and still compare every value exactly.
// (the RX 7900 XTX, `GPU_TIME_NOTICES`). `LooselyCalibratedGpuTimes`: it places them by a
// calibration a loaded host left beyond 20 us. The orderings this case compares do not
// depend on any of them, which is why the case can take the notice and still compare every
// value exactly.
// Every row reads its answer back through a `Shared` buffer, so on a device without
// unified memory the runtime announces `shared-in-system-memory`
// (`crate::replay::shared_memory_notice` holds the whole reason). It declares the
@@ -148,10 +156,10 @@ impl Case for CommandBufferFactsCase {
mod tests {
use super::*;
/// The case states its inputs, names itself once, and declares the two notices the runtime can
/// announce over the GPU times, the venue's own memory notice, and nothing else.
/// The case states its inputs, names itself once, and declares the three notices the runtime
/// can announce over the GPU times, the venue's own memory notice, and nothing else.
///
/// A fourth notice slipping in would be a value the case took for a reason nobody wrote down,
/// A fifth notice slipping in would be a value the case took for a reason nobody wrote down,
/// which is what this count is for.
#[test]
fn the_case_states_its_inputs_and_only_the_gpu_time_notices() {
@@ -161,7 +169,7 @@ mod tests {
assert_eq!(case.name(), COMMAND_BUFFER_FACTS);
assert!(!case.inputs().expect("the inputs").is_empty());
let allowed = case.allowances();
// The two GPU-time notices, and the one a card without unified memory announces for the
// The three GPU-time notices, and the one a card without unified memory announces for the
// `Shared` buffer the case reads its answer back through.
assert_eq!(allowed.len(), GPU_TIME_NOTICES.len() + 1);
// And the case records more than one run, because two of its booleans read a clock.
@@ -74,10 +74,13 @@ impl Case for EmptyCommandBuffersCase {
// fill outside its life (`WorkCounts::calibration_disagreements` 1 in each of three `cost`
// runs); the Radeon 780M in the same machine agreed with its calibration (0). The orderings
// this case compares hold for every source, so every value still compares exactly; the
// notice site alone takes either notice.
// notice site alone takes each notice. `LooselyCalibratedGpuTimes`: it places them by a
// calibration pair a loaded host left beyond 20 us after its four readings, inside the
// command buffer's life (`gpu_time.rs`).
vec![
notice_allowance(Degradation::GpuTimesFromHost.code()),
notice_allowance(Degradation::UncalibratedGpuTimes.code()),
notice_allowance(Degradation::LooselyCalibratedGpuTimes.code()),
]
}
@@ -95,7 +98,7 @@ impl Case for EmptyCommandBuffersCase {
mod tests {
use super::*;
/// The case states its inputs, names itself once, takes the two GPU-time notices alone, and
/// The case states its inputs, names itself once, takes the three GPU-time notices alone, and
/// records more than one run.
#[test]
fn the_case_states_its_inputs_and_only_the_gpu_time_notices() {
@@ -104,7 +107,7 @@ mod tests {
let case = &cases[0];
assert_eq!(case.name(), EMPTY_COMMAND_BUFFERS);
assert!(!case.inputs().expect("the inputs").is_empty());
assert_eq!(case.allowances().len(), 2);
assert_eq!(case.allowances().len(), 3);
assert!(case.record_runs() > 1);
}
}
@@ -9,9 +9,10 @@
//! (`probes/texture_buffer_past_length.m`, an Apple M3 Max under macOS 27.0.1). Over a 4096-byte
//! buffer, whose `allocatedSize` is its length, that memory is the buffer allocated next, which no
//! case can state; over a 20000-byte buffer, whose `allocatedSize` is 32768, it is the rest of the
//! buffer's own allocation, and it reads zero. The runtime keeps those texels in a tail of the
//! texture buffer's own, zero when made, which its functions view. So the case asks the second
//! shape: 1024 `R32Uint` texels from byte 16384 of a 20000-byte buffer, the first 904 inside the
//! buffer's own allocation, and it reads zero. The runtime's lie in the buffer's memory too, as a
//! buffer of 16 KiB or more holds its allocation, its length rounded up to 16 KiB, zero when
//! made, which its functions view in place. So the case asks the second shape: 1024 `R32Uint`
//! texels from byte 16384 of a 20000-byte buffer, the first 904 inside the
//! length and the last 120 past it.
//!
//! `buffer-tails-texture-buffer` reads texels through `ob1_texel_buffer` (the owned fixture whose
@@ -22,10 +23,9 @@
//! reads it into a buffer as made, writes texels 880 to 943 by a blit from a buffer, and reads it
//! back by a blit and by `getBytes:`, with the buffer's bytes.
//!
//! Every byte compares exactly. What differs is the announcing: the runtime's functions view such
//! a texture buffer's tail as a staging buffer and it announces `staged-texture-buffer`, which
//! Metal never does, and a device without unified memory announces `shared-in-system-memory` for
//! the `Shared` buffers the answers are read back through. Nothing here can fault a GPU: one
//! Every byte compares exactly. What differs is the announcing: a device without unified memory
//! announces `shared-in-system-memory` for the `Shared` buffers the answers are read back
//! through. Nothing here can fault a GPU: one
//! small texture buffer, eight threads, no loop.
use crate::allowance::Allowance;
@@ -298,17 +298,9 @@ impl Case for TextureBufferTails {
}
fn allowances(&self) -> Vec<Allowance> {
// The runtime's functions view a texture buffer whose texels run past its buffer's length
// through its tail, a staging buffer, and it announces `staged-texture-buffer`, which
// Metal never does. Every answer is read back through `Shared` buffers, so a device
// without unified memory announces `shared-in-system-memory`
// (`crate::replay::shared_memory_notice`).
vec![
crate::replay::shared_memory_notice(),
crate::replay::notice_allowance(
metal2vulkan_runtime::Degradation::StagedTextureBuffer.code(),
),
]
// Every answer is read back through `Shared` buffers, so a device without unified memory
// announces `shared-in-system-memory` (`crate::replay::shared_memory_notice`).
vec![crate::replay::shared_memory_notice()]
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
+26 -6
View File
@@ -350,11 +350,12 @@ const POOL_STATE: &str = "a reading of how many pieces the device's pipeline poo
/// Why `encoder_primaries_begun_ahead` is reported and never gated.
///
/// The runtime documents it as a `VkCommandBuffer` begun "by the thread that completed the command
/// buffer that gave it back where no thread waited for that one", so whether this case's first
/// encoder finds a primary already begun depends on whether a completion thread got round to
/// beginning it, for a pool an earlier case gave back. It is also a *split* of
/// `encoder_command_buffers_begun`, which stays gated, so no work escapes the gate by it.
/// The runtime documents it as a `VkCommandBuffer` "begun on the device's begin-ahead thread once
/// the command buffer that gave it back completed", so whether this case's first encoder finds a
/// primary already begun depends on whether that thread got round to beginning it, for a pool an
/// earlier case gave back. It is also a *split* of `encoder_command_buffers_begun`, which stays
/// gated, so no work escapes the gate by it. Its own split `encoder_primaries_begun_ahead_missed`,
/// the encoders the thread had not reached yet, shares the name, and so the race and the reason.
///
/// Measured: `chroma-pair-copies-gbgr422` and `chroma-pair-texel-samples-gbgr422` read 2 and 1
/// inside the 393-case set where the measurement's most was 0, and **0** when each runs alone --
@@ -717,7 +718,7 @@ pub fn monotone(name: &str) -> Option<&'static str> {
/// truncated and it reran. The other read the counters behind its own movements and found every one
/// of them process-shared. Neither symptom could be read off a single run, which is the property
/// that makes this class worth naming rather than discovering again.
const SHARED: [(&str, &str); 23] = [
const SHARED: [(&str, &str); 36] = [
// `work_counts.rs`: "every batch, by how far its queue's work ran behind its submission".
// Four buckets of one histogram, and which bucket a batch lands in is decided by how fast the
// GPU drained what was submitted before it, earlier cases included. The sum is the case's own
@@ -738,6 +739,25 @@ const SHARED: [(&str, &str); 23] = [
// queue ran behind. They are here on their definitions alone, which is the point of the class.
("groups_kept_pending", QUEUE_DEPTH),
("groups_sent_for_waits", QUEUE_DEPTH),
// The batches of a `VkQueue` whose batches group that went alone, by why: whether one went at
// its commit, was held alone, kept, sent alone, or found with no group held as it took first
// work, and its queue's expected run (unknown, or past the bound), are what the host had seen
// complete when it went, and what else was ready beside it. Their refusals by what a batch is
// (an unshared queue's, a binary semaphore, a sparse update, pieces, a fence) stay gated. Here
// on their definitions.
("batches_alone_run_unknown", QUEUE_DEPTH),
("batches_alone_run_long", QUEUE_DEPTH),
("batches_alone_first_work", QUEUE_DEPTH),
("batches_alone_at_commit", QUEUE_DEPTH),
("batches_held_alone_one_pending", QUEUE_DEPTH),
("batches_held_alone_unshared_hold", QUEUE_DEPTH),
("batches_held_alone_gpu_waits", QUEUE_DEPTH),
("batches_held_alone_handlers", QUEUE_DEPTH),
("batches_held_alone_waited_for", QUEUE_DEPTH),
("batches_held_alone_kept", QUEUE_DEPTH),
("batches_held_alone_sent_by_next", QUEUE_DEPTH),
("batches_held_alone_other", QUEUE_DEPTH),
("batches_held_alone_unkept", QUEUE_DEPTH),
// "found a submission holding its place in the submissions' order and waited until that
// submission was made", on a device that cannot write heap sets while a command buffer binding
// them is pending. Whether a registration finds a submission holding the order is a race with
@@ -428,20 +428,26 @@ fn rust_files(root: &std::path::Path) -> Result<Vec<std::path::PathBuf>, String>
Ok(found)
}
/// One of the suite's own sources, read from the tree this crate was built in.
/// One of the suite's own sources, read from the checkout the binary runs from
/// ([`metal2vulkan_devtools::workspace_dir`]).
///
/// The census reads sources, so it needs the tree. This crate is never published
/// (`publish = false`), so its manifest directory is always a checkout.
/// (`publish = false`), so it always runs from a checkout.
fn read_source(file: &str) -> Result<String, String> {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
let path = (metal2vulkan_devtools::workspace_dir())
.join("crates")
.join("metal2vulkan-conformance")
.join("src")
.join(file);
std::fs::read_to_string(&path).map_err(|error| format!("{}: {error}", path.display()))
}
/// The runtime crate's sources, beside this crate's in the workspace.
/// The runtime crate's sources, beside this crate's in the checkout the binary runs from.
fn runtime_src() -> Result<std::path::PathBuf, String> {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-runtime/src");
let path = (metal2vulkan_devtools::workspace_dir())
.join("crates")
.join("metal2vulkan-runtime")
.join("src");
path.canonicalize()
.map_err(|error| format!("{}: {error}", path.display()))
}
@@ -486,10 +486,16 @@ impl std::fmt::Display for Stale {
}
}
/// The directory the recordings live in: this crate's own, beside its case set. They are the
/// conformance suite's files in the conformance suite's format, and nothing else reads them.
/// The directory the recordings live in: this crate's own, beside its case set, in the checkout
/// the binary runs from ([`metal2vulkan_devtools::workspace_dir`]: the one the runner names, else
/// the one it was built in), so a conformance binary carried to another machine reads that
/// machine's recordings. They are the conformance suite's files in the conformance suite's
/// format, and nothing else reads them.
pub fn recordings_dir() -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("recordings")
metal2vulkan_devtools::workspace_dir()
.join("crates")
.join("metal2vulkan-conformance")
.join("recordings")
}
/// `case`'s recording file.
@@ -364,6 +364,29 @@ pub fn shared_memory_notice() -> crate::allowance::Allowance {
notice_allowance(metal2vulkan_runtime::Degradation::SharedInSystemMemory.code())
}
/// The declaration a case needs for the second notice a **venue's memory model** provokes:
/// `staged-indirect-records`, which the runtime announces on a device without unified memory that
/// places an indirect command buffer's records by their first use, where a GPU write was the first
/// use, so the records lie in device-local memory, and a host step then reads them while the
/// command buffer that wrote them holds them, through the device's staging queue
/// ([`metal2vulkan_runtime::Degradation::StagedIndirectRecords`]).
///
/// **Why it is the venue's and not ours**, as [`shared_memory_notice`] is: every recording here
/// was taken on an Apple chip, whose GPU and CPU hold one memory, so there is no device-local
/// memory to place the records in and the notice cannot fire; MoltenVK on the same chip announces
/// nothing either. A discrete card keeps the records a GPU write placed in its own memory, which
/// the host reaches only through copies, and a host step must read what the GPU wrote. The
/// notice is the runtime reporting that cost honestly.
///
/// **It is a declaration and never an excuse.** Like every [`notice_allowance`] it loosens the
/// notices site alone: every value still compares against Metal's exactly. A case names it only
/// where a run on such a device announced it for the case's own work, and says in a comment which
/// run, and which counts showed the staged accesses were its host steps' reads of GPU-written
/// records; a staged access of records the GPU never wrote is a runtime defect, not this.
pub fn staged_records_notice() -> crate::allowance::Allowance {
notice_allowance(metal2vulkan_runtime::Degradation::StagedIndirectRecords.code())
}
/// The declaration a case needs for the split a **venue's driver** makes the runtime take between
/// two draws that read and write a color in the pixel interlock: `render-pass-split`, which the
/// runtime announces where a draw that reaches interlocked storage an earlier draw of its
+4
View File
@@ -13,3 +13,7 @@ publish = false
[dependencies]
# The synthetic metallib writer's function hashes (`metallib`).
sha2.workspace = true
# The scratch locks' file identity on Windows (`scratch.rs`'s `same_file`).
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }
+5 -3
View File
@@ -42,9 +42,11 @@ mod tests;
/// the manifest directory it names (`cargo test` and `cargo nextest` name the test's crate,
/// `crates/<name>`; a run of a nextest archive on another machine names it in that machine's
/// checkout, `--workspace-remap`) where that root holds the validation crate's fixtures, else above
/// this crate as it was built. Tests read the checkout through it and the helpers on it
/// ([`validation_dir`], [`fixtures_dir`], [`engine_dir`]), never through a path the build baked in
/// (`env!("CARGO_MANIFEST_DIR")`), which names the build machine's checkout.
/// this crate as it was built (a binary run outside cargo, which names no manifest directory).
/// Tests, and the validation library's paths to committed files (its profiles, corpus and lists),
/// read the checkout through it and the helpers on it ([`validation_dir`], [`fixtures_dir`],
/// [`engine_dir`]), never through a path the build baked in (`env!("CARGO_MANIFEST_DIR")`), which
/// names the build machine's checkout.
pub fn workspace_dir() -> PathBuf {
let root = |manifest: &Path| {
manifest
@@ -166,6 +166,7 @@ impl Owned {
/// Whether the open file `held` is still the file `path` names, by the one identity a file system
/// gives a file: its device and inode. A rename or an unlink of `path` makes this false, and
/// `held` keeps working on a file with no name.
#[cfg(unix)]
fn same_file(held: &File, path: &Path) -> io::Result<bool> {
use std::os::unix::fs::MetadataExt;
let held = held.metadata()?;
@@ -176,6 +177,37 @@ fn same_file(held: &File, path: &Path) -> io::Result<bool> {
}
}
/// [`same_file`] on Windows, by the identity NTFS gives a file: its volume's serial number and
/// its file index (`GetFileInformationByHandle`), of `held` and of `path` opened again.
#[cfg(windows)]
fn same_file(held: &File, path: &Path) -> io::Result<bool> {
match File::open(path) {
Ok(named) => Ok(file_identity(held)? == file_identity(&named)?),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// An open file's volume serial number and file index.
#[cfg(windows)]
fn file_identity(file: &File) -> io::Result<(u32, u32, u32)> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
};
// SAFETY: an all-zero `BY_HANDLE_FILE_INFORMATION` is a valid value of the plain struct.
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: the handle is open for the call, and `info` is a valid struct for it to fill.
if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
return Err(io::Error::last_os_error());
}
Ok((
info.dwVolumeSerialNumber,
info.nFileIndexHigh,
info.nFileIndexLow,
))
}
/// Whether [`Owned`] creates its directory or leaves it to whatever writes there.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Make {
+7 -5
View File
@@ -2,12 +2,14 @@
use std::path::{Path, PathBuf};
/// The test trees, relative to the workspace, that run from nextest archives carried to other
/// machines (`cargo nextest run --archive-file ... --workspace-remap <checkout>`): the runtime
/// lanes and the runtime's lib tests (`src/tests/` and the test modules beside its sources).
/// The trees, relative to the workspace, whose tests run from nextest archives carried to other
/// machines (`cargo nextest run --archive-file ... --workspace-remap <checkout>`): all of the
/// validation crate (its lib test binary holds the runtime lanes and the library code they call,
/// its integration tests and binaries ride a full archive), and the runtime's lib tests
/// (`src/tests/` and the test modules beside its sources).
const CARRIED: [&str; 3] = [
"crates/metal2vulkan-validation/src/runtime_lane",
"crates/metal2vulkan-validation/src/runtime_lane.rs",
"crates/metal2vulkan-validation/src",
"crates/metal2vulkan-validation/tests",
"crates/metal2vulkan-runtime/src",
];
+2 -2
View File
@@ -119,11 +119,11 @@ fn tool_bin(cmd: &str) -> PathBuf {
PathBuf::from(cmd)
}
#[cfg(test)]
// The test runs `/bin/sh`, which only unix hosts have.
#[cfg(all(test, unix))]
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn tool_runner_reports_output_exit_and_signal_without_retrying() {
let (stdout, stderr) =
+20 -5
View File
@@ -157,17 +157,32 @@ path = "examples/icb_reads.rs"
[dependencies]
# The translator, through its public API only: the compiler checks that the runtime
# reaches nothing else. `ash` gives `ash_interop`'s conversions and `DeviceDescription::query`.
metal2vulkan = { version = "0.2.0", path = "../metal2vulkan", features = ["ash"] }
# reaches nothing else. `ash` gives `ash_interop`'s conversions and `DeviceDescription::query`;
# `serde` the FALLBACK repro bundles' writer and their `device.json` (`repro.rs`).
metal2vulkan = { version = "0.2.0", path = "../metal2vulkan", features = ["ash", "serde"] }
# `ash/loaded` opens the Vulkan loader with `dlopen` when a device is created; nothing is linked at
# build time.
ash = { workspace = true, features = ["std", "loaded"] }
# No-copy buffers take the host's page size on unix; elsewhere they are
# refused typed. It also registers the exit guard's exit handler on unix.
libc.workspace = true
# The shader cache's entry names and the binary archive's keys.
sha2.workspace = true
# The host's pages, clocks, threads and exit handlers on unix.
[target.'cfg(unix)'.dependencies]
libc.workspace = true
# The same on Windows: pages (`VirtualQuery`, `VirtualAlloc`), the performance counter, thread
# times and the current process's memory reads.
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_Security",
"Win32_System_Diagnostics_Debug",
"Win32_System_Memory",
"Win32_System_Performance",
"Win32_System_SystemInformation",
"Win32_System_Threading",
] }
[dev-dependencies]
serde_json.workspace = true
# `llvm-as` for the device tests' owned fixture (`tests/pipeline_wait_order.rs`).
+282 -27
View File
@@ -65,6 +65,45 @@ ash = { version = "0.38", default-features = false, features = ["std"] }
directory, and in memory ([HOWTO](../../docs/HOWTO.md#the-runtimes-shader-cache)).
`ShaderCacheOptions` names another directory; give each test its own.
## Windows
The three crates build for Windows: `x86_64-pc-windows-gnullvm` first, and
`x86_64-pc-windows-msvc`. CI runs clippy for both targets from Linux; the suites run on Linux and
macOS only. The runtime opens `vulkan-1.dll`. Where it asks the system something on Linux or
macOS, it asks Win32 on Windows:
- Host pages a no-copy object names: `VirtualQuery` answers whether they are committed and
writable, and `GetSystemInfo` gives the page size. Pages the process cannot write are a copy
whose GPU writes are dropped (`copied-host-pages`), as on Linux. A view of a section
(`CreateFileMapping`, as a VMM's guest RAM is made) is imported by its pointer through
`VK_EXT_external_memory_host` where the driver takes it: `Device::imports_shared_host_pointers`
asks the driver with a section of the runtime's own. Where the driver refuses it, a no-copy
buffer or heap over such memory is a copy of the pages (`copied-host-pages`), a rebind to it is
refused (`Unsupported`, `HostMemory`), and a `HostRam` of it imports no chunk
([HOWTO](../../docs/HOWTO.md#guest-ram-imported-whole)), as on Linux for shared memory with no
dma-buf source.
- The host clock is the performance counter (`QueryPerformanceCounter`); calibrated timestamps use
`VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR`.
- Thread CPU times come from `GetThreadTimes`, and the runtime's exit handler is registered with
the C runtime's `atexit`.
- The default shader cache directory is `%LOCALAPPDATA%\metal2vulkan`; where `LOCALAPPDATA` is
unset or not absolute, a device keeps its shader cache in memory alone and says so
([HOWTO](../../docs/HOWTO.md#the-runtimes-shader-cache)). Its directories and files take the
access control list they inherit; the runtime sets no permissions of its own there.
The items that take or hand out file descriptors do not exist on Windows (they are absent at
compile time), and nothing stands in for them with Win32 handles:
- dma-buf sources: `HostMemory::with_dma_buf`, `HostRam::with_dma_buf`,
`HostRam::with_largest_dma_buf`, `HostRam::with_dma_buf_of_runs`, `DmaBufSource`,
`DmaBufRunsSource`, `DmaBufRequest`, `DmaBufChunk` and `DmaBufStandingRefusal`, and
`Device::import_shared_dma_buf` and `SharedDmaBufImport`;
- exported memory: `Device::new_exportable_buffer`, `Buffer::export_memory_fd`,
`Buffer::export_memory_dma_buf`, `Buffer::external_write_done` and `ExportedMemory`;
- exported semaphores and sync files: `Device::new_exportable_shared_event`,
`SharedEvent::export_semaphore_fd`, `CommandBuffer::add_completion_sync_file` and
`CommandBuffer::export_completion_sync_file`.
## A first dispatch
From [`examples/compute_dispatch.rs`](examples/compute_dispatch.rs):
@@ -198,12 +237,12 @@ Vulkan-side choices Metal has no counterpart for:
for want of its resources (`vkCreateDevice` answering `VK_ERROR_TOO_MANY_OBJECTS`,
`VK_ERROR_INITIALIZATION_FAILED`, `VK_ERROR_OUT_OF_DEVICE_MEMORY` or `VK_ERROR_OUT_OF_HOST_MEMORY`:
on NVIDIA's driver, other devices of the GPU, in this process or others, holding what it needs,
such as its channels), the runtime asks once more with its least
plan's: a round robin of one `VkQueue` and none reserved for presenting, the reserved, extra,
staging and fill queues kept (`queue_limits` of one and none, without that option's messages). A
device made so announces `metal2vulkan-degrade-least-queue-plan` once, as it is made: its command
queues share that one `VkQueue`. A device the driver refuses again, or whose least plan takes no
fewer queues, is refused, `Error::DeviceRefused`. On an RTX 2080 with a 256 MiB BAR (NVIDIA
such as its channels), the runtime asks once more with its least plan's: a round robin of one
`VkQueue` and none reserved for presenting, the extra, staging and fill queues kept, and as many
reserved queues as the plan reserves, no more (`queue_limits` of one and none, without that
option's messages). A device made so announces `metal2vulkan-degrade-least-queue-plan` once, as
it is made: its command queues share that one `VkQueue`. A device the driver refuses again, or
whose least plan takes no fewer queues, is refused, `Error::DeviceRefused`. On an RTX 2080 with a 256 MiB BAR (NVIDIA
620.70.06), sixteen processes started 3 s apart, each making one device: seven devices were made
with 17 `VkQueue`s and two more with 2 (one round-robin queue and the staging queue). The driver
refused the other seven with both plans, and the kernel logged that it could not allocate a
@@ -439,10 +478,24 @@ after it, and 0 of 80 with the device dropped first
`unsafe Device::new_heap_with_bytes_no_copy` is its heap twin.
`Buffer::rebind_bytes_no_copy` and `Heap::rebind_bytes_no_copy` move either to another range,
keeping the objects, addresses and IDs. A rebind is refused (`RebindProblem::EncodedUses`) while
a command buffer not yet committed, or an open encoder, used the bytes; a render encoder whose
attachment lies in them uses them from its open. Where a driver refuses the pointer (RADV
refuses shared mappings, a `memfd`'s among them), memory made with `HostMemory::with_dma_buf` is
imported from dma-bufs of its pages instead
a command buffer not yet committed, or an open encoder, used the bytes, or while one committed
that used them, with commands the runtime records once earlier work completed (an indirect
command buffer's executions the GPU writes, a dispatch left to its host step, a predicated
loop's run again of such work or of work on the GPU alone), has not completed; a render
encoder whose attachment lies in them uses them from its open. So is one while a command buffer
committed and not yet submitted used them in an encoder the runtime cannot encode again (a
compute encoder its unit of command predication reaches past, among others), until its last
submission (`WorkCounts::rebinds_refused_unsubmitted`). Other threads may encode and
commit command buffers that use the bytes during a rebind: a blit encoder, or a render encoder
that keeps a log, whose call raced it is encoded again over the new pages before its first
submission (`WorkCounts::encoders_raced_rebind` counts the encoders that raced). The calls of the
encoders the runtime may not be able to encode again (every compute encoder's, and a render
encoder's that keeps no log) never race it: the rebind waits up to 2 ms for such a call under way
and is refused past it (`EncodedUses`, counted by `WorkCounts::rebinds_refused_calls_in_flight`;
try again), and such a call that begins during the rebind waits for it; 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 are the caller's to exclude.
Where a driver refuses the pointer (RADV refuses shared mappings, a `memfd`'s among them), memory made
with `HostMemory::with_dma_buf` is imported from dma-bufs of its pages instead
([HOWTO](../../docs/HOWTO.md#6-host-memory-a-driver-refuses)), and a no-copy buffer or heap
over memory made without a source is a copy of its pages, as below. A device that enables no
`VK_EXT_external_memory_host` but imports dma-bufs imports only those: memory made with a
@@ -502,6 +555,16 @@ after it, and 0 of 80 with the device dropped first
holds it, so the live one's keep-alive is dropped, or, given none, its deallocator runs, only
once both are gone; with a keep-alive its deallocator still runs at its release, as Metal's
(`WorkCounts::host_releases_held_inside`).
- **Constants over imported memory.** On ANV on the Iris Xe RPL-P a uniform buffer read of memory
the device marks external (a no-copy buffer's host pages, a dma-buf) misses a cache: a kernel
whose invocations read one word of a 1 KiB window took 2.0 to 2.5 times as long there as over
device memory, and 5.2 to 5.5 times where each read its own. Where the device's view check
finds that (`ExternalUniformReadsSkipACache`), a `constant` slot with an indexed read whose
window the translation bounds to at most 4 KiB reads through a uniform texel buffer instead,
measured at 0.98 to 1.04 times the time over device memory: the runtime makes a view of the
bound range for each bind, counted in `WorkCounts::uniform_texels_bound`. A longer window keeps its uniform buffer and
stays slower over imported memory (`uniform_buffers_bound_to_16k`,
`uniform_buffers_bound_past_16k`; docs/FAST-PATHS.md, known gaps).
- **Hazards** are tracked as Metal tracks them. A heap's resources are untracked by default, so
encoders that share them order themselves with fences. Commands that reach a resource through an
address or ID in memory need it resident (`use_resource`, `use_heap`), as on Metal. The runtime
@@ -555,7 +618,10 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
ms or more of their expected GPU work is in flight on it (`UnsharedIsolationPolicy::Bounded`, the
default), and its command buffers wait behind about one batch of theirs, the whole of a long
one (docs/FAST-PATHS.md, known gaps; counted:
`WorkCounts::unshared_command_buffers_behind_other_queues`, and its wait's tallies). Under `QueueSharingPolicy::Adaptive` (the default), where the device's own check
`WorkCounts::unshared_command_buffers_behind_other_queues`, and its wait's tallies). The plain
queues there take turns (`QueueTurnPolicy::Fair`, the default): each keeps about 2 ms of its
own expected GPU work in flight while another submits there, so none waits behind another's
whole burst of command buffers (`WorkCounts::heads_held_for_queue_turns`). Under `QueueSharingPolicy::Adaptive` (the default), where the device's own check
finds its GPU idle between consecutive work of two `VkQueue`s (NVIDIA's driver), the other
command queues move among the `VkQueue`s of their family at their idle points and share them
([docs/API.md](../../docs/API.md#the-policy)); this one keeps the `VkQueue` it takes for its
@@ -572,6 +638,38 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
(`WorkCounts::unshared_queues_sharing_a_vk_queue`). A count of 0 and a lost device are refused
as `new_command_queue_with_max_command_buffer_count` refuses them.
- `Device::new_command_queue_for_copies()` makes a command queue whose command buffers run on the
device's copy engine (a queue family of transfers alone), beside the graphics family's work
rather than behind it: on an RTX 3090 a readback through another graphics-family queue waited
1.88 s for a 2 s kernel, where the copy engine's took 7.8 to 13.5 ms. Metal has no such queue.
It answers `None` where the device has no copy engine to give (MoltenVK, lavapipe, RADV unless
`RADV_PERFTEST=transfer_queue`, a copy engine of one queue, a device made with
`Device::from_raw`); keep a plain queue's path there. Every copy queue of a device submits to
one `VkQueue`: the copy engine's third queue, or, on NVIDIA's copy engine of two, the queue the
device's own fills from host memory take (`device/staging.rs`). Its command buffers take blit
encoders alone, and of those `copy_from_buffer_to_buffer`, `fill_buffer` and fence updates and
waits; anything else, and a buffer of the consumer's (`new_buffer_with_vk_buffer`) not
concurrent with the copy engine's family, is refused (`Invalid`, `Problem::CopyQueue`). Every
buffer the runtime makes, a no-copy buffer over host pages among them, is shared with that
family (`VK_SHARING_MODE_CONCURRENT`), so no buffer changes owner; hazards are tracked across
queues as for any queue, and its command buffers keep commit order: a copy that reads what
another queue's command buffer committed before it wrote (or writes what that one uses) waits
for it on the GPU, and where the runtime holds that command buffer back (for a pipeline still
being made, a host step, its submission checks), waits behind it in the scheduler with no host
wait; one held for an event the program has not signalled holds back no copy. On a device that
answers `None`, a plain queue used instead does not keep that order behind a command buffer held
for its pipelines' making (the pipeline waits, below): order such a copy after it with an event.
The completion sync file
(`CommandBuffer::export_completion_sync_file`) is signalled on the copy engine. Its batches are
counted (`WorkCounts::copy_queue_batches`).
- A blit encoder's consecutive `copy_from_buffer_to_buffer` calls between the same two buffers
that need no barrier between them (none reads or writes what an earlier one of the run wrote,
nor writes what it read) are one `vkCmdCopyBuffer` of many regions, on every queue
(`WorkCounts::buffer_copies_merged`). The encoder's hazard order keeps eight ranges of a buffer
and then one span over them all, so a copy into that span takes a barrier and starts a new run:
sort row copies by destination offset (rows in order, tile beside tile) to merge them all.
- `CommandBuffer::commit_failed(CommitFailure)` commits a command buffer as failed, running the
encoders Metal would still run and keeping its signals, as a consumer measured on an M3 Max.
- `CommandBuffer::set_submission_check` runs a check as the command buffer is submitted, and fails
@@ -588,7 +686,17 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
completion of one that needs no GPU work, taken with no submission behind no work in flight,
never waits for it), or sooner, as the command buffer becomes `Scheduled`, where its remaining
batches wait only for a host step of its queue's behind work already submitted (Metal schedules
it then, its dependencies resolved);
it then, its dependencies resolved). Which thread runs it: where the command buffer's own
`commit_and_submit` call took the last batch, that call's thread, inside the call; otherwise
one of the device's handler threads, those that run its scheduled and completed handlers, to
which the scheduler thread, or another `commit_and_submit` call's pass, hands it right after
taking the batch, going on with its submissions meanwhile. Two exceptions
run it on the scheduler thread or the hang's thread: a pass that settled a switch of a fetched
target's storage form before taking the batch (once the switch ended), and a command buffer
behind a GPU hang. Every command buffer's handlers run in submission order. The command buffer
becomes `Scheduled` (its scheduled handlers on) only after them; the completion of its queue's
earlier command buffer never waits for them, and its own completion, where its work ended
first, waits for them in its place without holding a thread;
`add_executed_commands_handler` each time an execution's indirect records are read.
- `CommandBuffer::add_completion_seen_handler` is called once the command buffer completed, its
status, error and GPU times final, on the runtime's thread that saw it complete (its queue's
@@ -604,25 +712,47 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
that one, as Metal's completion follows the GPU's). It must be short and never
block; a wait in it for what has not happened is refused
(`DeadlockCause::CompletionSeenHandler`).
- `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 submissions merge (`Device::submissions_merge`) and whose queues' failures are not relayed,
its batches may wait in the scheduler's group as every batch does under
`CompletionPolicy::Grouped`, so up to four batches of one `VkQueue` found ready together in one
pass go in one kernel submission, the first command buffer behind them that is not marked going
last in it and seen complete at its own end. The marked one is seen complete, and its event
signals reached, once the last of that submission completed (late by the GPU time of at most
three batches after it); the submission checks of the batches right behind it run with its own;
no group is kept past its pass under `Exact`, and an unmarked command buffer is never held back
for one. Announced `grouped-completion` once. A no-op elsewhere: under `Grouped`, on a device
whose check did not find the merge, and for a batch that never groups. No Metal counterpart.
- `CommandBuffer::commit_and_submit` commits as `commit` does, then submits on the calling thread
where no other submission pass is under way: the ready command buffers in commit order, this
one among them, each needing no host step and no switch of a storage form, up to the pass's
bound (under `CompletionPolicy::Grouped`, on a driver whose batches may wait in a group, one
bound, but for those of a `VkQueue` whose batches' `vkQueueSubmit` calls are slow (each of its
last 15 that submitted command buffers 100 us or more, as timed: a driver that lists every host
import in each kernel submission, RADV's over a guest's memory on a host of unified memory),
which the
scheduler's thread submits while the calling thread goes on
(`WorkCounts::scheduler_at_commit_left_slow_calls`; under `CompletionPolicy::Grouped`, on a driver whose batches may wait in a group, one
goes alone where its `VkQueue` runs at most one earlier submission not seen complete, and is
left to the scheduler's thread to group where two or more run; one held back, another queue's waiting for its check or an event, holds back only the
later commits that wait behind it, as on the scheduler's thread), their submission checks run
inside the call just before each submission (unless one waits for a shared event's GPU signal
to land, which the scheduler's thread waits for; a plain event's wait goes to the `VkQueue`, as
Metal submits an `MTLEvent` wait at once) and their submission handlers after it, in submission
order with every other command buffer's. What it leaves goes to the scheduler's thread, which
it wakes, as it does after a batch it submitted alone where the batch may wait in a group. No
wake and no thread hop lies on its way to the `VkQueue`, where `commit`'s submission is the
Metal submits an `MTLEvent` wait at once), and its own submission handlers after it, in
submission order with every other command buffer's (those of the other command buffers its pass
submits go to the device's handler threads as it goes on; where it has submission handlers, its
pass ends right after its own last batch, so they wait for no later batch's submission, and it
wakes the scheduler's thread for the rest before it runs them, which submits it meanwhile).
What it leaves goes to the scheduler's thread, which it wakes, as it does after a batch it submitted alone where the batch
may wait in a group. No wake and no thread hop lies on its way to the `VkQueue`, where `commit`'s submission is the
scheduler thread's, as Metal's is its own thread's
(`WorkCounts::scheduler_passes_at_commit`, `batches_submitted_at_commit`,
`batches_checked_at_commit`). Under `RenderLoweringPolicy::Worker`, one whose last render
encoder's end the lowering thread has not lowered returns as `commit` does, and the thread that
runs its commit once the end is lowered (the lowering thread, or one waiting for the command
buffer) makes that pass, its checks and handlers with it. How long the program's `commit`,
`batches_checked_at_commit`; why it made no pass, or made one that left its command buffer to
that thread, by reason: the `scheduler_at_commit_left_*` counts). Under
`RenderLoweringPolicy::Worker`, one whose last render encoder's end the lowering thread has not
lowered returns as `commit` does, and the thread that runs its commit once the end is lowered
(the lowering thread, or one waiting for the command buffer) makes that pass, its checks and
handlers with it. How long the program's `commit`,
`commit_and_submit` and `commit_failed` calls held its thread, and how much of it each phase
took (lowering, recording the work left to the commit, its pipeline waits, the scheduler lock's
wait, the pass, the submissions with their checks and handlers), each apart from the others:
@@ -667,7 +797,12 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
every such state of the command buffer may write, whichever encoder set it.
- `HostMemory::with_dma_buf` and its `DmaBufSource`: dma-bufs of a no-copy object's pages, for a
device that refuses their pointer, each chunk a dma-buf of its own or a piece of a file the
source shares among several objects (`DmaBufChunk`), which the device imports once.
source shares among several objects (`DmaBufChunk`), which the device imports once. A
source's error holding a `DmaBufStandingRefusal` stands for every range that holds the one it
refused while the texture that asked is made: the making asks the source for none of those
again, where any other error refuses only the request it answers.
- `Device::import_shared_dma_buf` and its `SharedDmaBufImport`: such a shared file imported ahead
and kept while the handle lives, so buffers over it that come and go join one import.
- `HostMemory::with_dirty_pages` and its `DirtyPages` (with `DirtyStamp`): the consumer's log of
the writes to a no-copy object's pages, by which every copy of them into memory of the device's
own (a shadow of a texture over them, a copied buffer or heap over them) copies in only the
@@ -682,6 +817,11 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
- `HostMemory::with_import_gate` and its `ImportGate` (with `ImportRequest`): the consumer's
gate over a no-copy buffer's, heap's or rebind's import of its pages; a refusal makes a copy of
them.
- `HostMemory::with_zero_from`: the consumer's promise that a no-copy buffer's bytes from an
offset to its length read zero at its making. A `Managed` one's GPU copy on a device without
unified memory then takes those bytes as zeros the device writes in its own memory, none copied
across the bus (`WorkCounts::managed_device_copies_zeroed`, `managed_bytes_zeroed`); nothing
else changes ([HOWTO](../../docs/HOWTO.md#copied-host-buffers)).
- `Buffer::host_backing` (with `HostBacking`): what the GPU uses for a no-copy buffer's bytes now,
or a no-copy heap's buffer's: the caller's pages, imported by their pointer, as dma-bufs or in a
guest RAM's chunk, a copy of them (`copied-host-pages`), which Metal never makes, or, for a
@@ -700,9 +840,17 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
device's buffer query takes both, in which no image is bound: a texture over it takes a
`DRM_FORMAT_MOD_LINEAR` image bound to a dedicated import of its block's dma-buf
(`WorkCounts::exported_dma_buf_images`), each import held costing each submission as a block
held does; elsewhere in a plain block of the runtime's memory, whose making holds the process's
submissions on RADV (`WorkCounts::plain_buffer_blocks_made`). No Metal counterpart; refused
(`PaddingUnobservedNoCopy`) with `NoCopy` contents.
held does. As the texture goes its image parks under the buffer, and the next texture over the
same buffer of the same plan at the same texels and pitches takes it, exporting and importing
nothing (`WorkCounts::exported_dma_buf_images_taken`; untaken, it is released at the residency
thread's next pass where held imports cost each submission, and as the buffer goes); elsewhere
in a plain block of the runtime's memory, whose making holds the process's
submissions on RADV (`WorkCounts::plain_buffer_blocks_made`). Its placement starts on the
device's linear images' memory alignment and takes whole units of it (4096 bytes on Intel's
driver for the UHD 630 on Windows, which rounds a small linear image's size up to it; every
placement meets the 256 or less of the other devices measured), so an image whose rows fill the
buffer lies in bytes the buffer owns, for at most that alignment less one byte more memory. No
Metal counterpart; refused (`PaddingUnobservedNoCopy`) with `NoCopy` contents.
- `BufferDescriptor::aligned_byte` (`with_aligned_byte`): a buffer of the runtime's own memory
laying one of its bytes on a multiple of 256 bytes of its memory, so a texture whose texels start
there (a decoded frame's plane 32 bytes into its surface, say) is a linear image aliasing the
@@ -723,6 +871,67 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
`Device::settle_in_place_checks` starts the check and says when its verdicts are known (a zero
timeout waits for nothing). `Buffer::tiled_texture_placement` answers it for
`new_tiled_texture`'s arguments.
- `Device::settle_view_check`, `Device::view_costs` (with `ViewCosts` and `ViewVerdict`) and
`Device::view_check_report`: the device's view check, which decides the two view cost facts
translation takes (`DeviceDescription::measured`) from the device's own timings, never from its
driver or GPU identity. It starts as the device is made, on a thread of its own, and no call
waits for it but `settle_view_check`. The device's work never waits on it: before each kernel's
making it stands by until no command buffer committed waits for its submission, none is in
flight and no `VkQueue` has been used for 20 ms since its start, and before each timed dispatch
for 1 ms, so a device whose work never pauses that long gets its answer once it does
(`WorkCounts::device_checks`, `view_check_stand_bys`); it stands by for no one while
`settle_view_check` waits. Eight kernels of 256 workgroups of 64 invocations each read
a 1 KiB and a 4 KiB window 256 times through a uniform buffer, a storage buffer and a uniform
texel buffer, every invocation the same vector at each step, each its own, or two fixed ones;
the window lies in the device's memory, and the uniform and per-lane reads through the uniform
and texel buffers run again over host pages the device imported by their pointer. Seven rounds
after a warm-up, the arms interleaved, medians of timestamps. `UniformBufferPerLaneReadsSerialize`
where the storage buffer's per-lane reads took less than 0.3 of the uniform buffer's at both
windows (NVIDIA's measured 0.011 to 0.107, RADV's 0.96 to 1.00). `ExternalUniformReadsSkipACache`
is judged on the reads it moves, over the imported pages: the uniform reads, and the per-lane
reads where the per-lane fact does not hold. It holds where, at both windows, the texel buffer
took less than the uniform buffer's time in every one of them and less than 0.7 of it in at
least one (ANV on the Iris Xe of RPL-P, from its records over host memory: 0.026 to 0.86 of
it, the least for each invocation walking a 1 KiB window, the most for each workgroup walking
4 KiB; RADV on the Radeon 780M 0.93 and 0.97 for the uniform reads). Both may hold: a slot
with a per-lane read then keeps its storage view, one with indexed reads all uniform takes the
texel view, and one read at constant offsets alone keeps its uniform buffer. `Unchecked`, never
fatal, with no fact, where the device writes no timestamps the host reads or refuses any part of
it. Measured on six devices (jobs m3-max-38378, 38379, 38380, 38382, 38389 and 38359): the
RTX 3090 and the RTX 2080 take `UniformBufferPerLaneReadsSerialize` alone (per-lane 0.073 and
0.102; the texel buffer 2.20 to 2.26 and 2.26 to 2.72 times the uniform buffer over imported
pages); the Iris Xe of RPL-P takes `ExternalUniformReadsSkipACache` alone (per-lane 4.84; the
texel buffer 0.22 to 0.76); the Radeon 780M, the RX 7900 XTX and lavapipe take neither (the
texel buffer 0.93 to 1.00, 0.99 to 1.41 and 0.86 to 1.84). It holds 4 KiB and 64 KiB of the
device's memory and 64 KiB of host pages while it runs. A cold run took 28 ms (RX 7900 XTX),
75 ms (Radeon 780M), 101 ms (RTX 3090), 134 ms (Iris Xe) and 136 ms (RTX 2080) from its
thread's start to its answer, 268 ms on lavapipe, of which its 24 arms' medians times its eight
rounds are 7.9, 17.0, 8.9, 43.2 and 12.5 ms of GPU time; a warm one reads its record and runs no
check. Until it answers, pipelines compile with the profile of the
device's identity alone (a uniform view stays a uniform buffer); once it answers with a fact,
every compile from then on takes the profile with those facts measured
(`Device::compile_device`), whose fingerprint, and so every shader cache key, differs; a
pipeline made before keeps its form. Its medians are kept in the shader cache's directory for the
driver, its release and the runtime's, so a later device of the same reads them as it is made
and compiles with its facts from its first pipeline.
- `Device::settle_tiling_cost_check`, `Device::tiling_cost` (with `TilingCost` and
`TilingVerdict`) and `Device::tiling_cost_check_report`: whether the device's GPU pays more for
a texture in place over host pages (a linear image) than for a `Private` one (optimal), measured
on the device, for a consumer that keeps a GPU copy of host pages where it does, as an x86 Mac's
GPU keeps one of each IOSurface. The check runs once the first `settle_tiling_cost_check`
asks, on a thread of its own: over 2048x1536 `BGRA8Unorm` images, a frame of a render pass
that loads and stores the whole target, each fragment fetching a source's texel, and a pass
that writes zero, into each arm's target from its source, and the copies between the optimal
image and the host pages both ways (a download at a CPU lock, an upload after a CPU write),
eight rounds after a warm-up, medians of timestamps. `LinearCostly` where the linear frame
passes the optimal one by more than 500 us and twice, else `LinearCheap` (measured: the Iris
Xe of RPL-P under ANV 2.1 to 4.7 ms against 0.40 to 0.89 ms, about 5.25 times, costly; lavapipe
3.2 against 2.9 ms, cheap; the check took 78 to 99 ms there); `Unchecked`,
never fatal, where the device writes no timestamps the host reads, imports no host pointer, or
makes or records any part of it otherwise. It holds 24 MiB of host pages and 24 MiB of the
device's memory while it runs, and keeps its medians in the shader cache's directory for the
driver, its release and the runtime's, so a later device of the same reads them at once. The
runtime makes no choice from it. No Metal counterpart.
- `Device::host_pages_texture_placement`: the same answer for a texture
`new_texture_with_iosurface_plane` would make over a no-copy buffer of host pages (`start`,
`length`) imported by pointer or as dma-bufs (`HostBacking::ImportedByPointer`,
@@ -734,6 +943,20 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
made. Where only an image or the import decides (the driver's linear image's layout, a
`DRM_FORMAT_MOD_LINEAR` plane, their requirements against the import, the dma-buf's source and
import), it answers `InPlace`. No Metal counterpart.
- `Texture::view_placement` (with `ViewPlacement` and `ViewShadowReason`): what a view of the
whole texture in a pixel format (`new_texture_view`) would be if made now: a Vulkan view of the
texture's image, whose copies, bindings and attachments are the image's and whose uses are
ordered with every other view's of it (the tracker keys a view's uses on its image); the image
through a swizzle (a view in other channels of the image's bits, which a render pass renders
into through a view shadow); a view shadow, an image of its own the encoders copy the texels
into and back out of (`shadowed-texture-view`), and why: the device's views reinterpret no
components, the formats' compatibility classes differ, or the image lists no such format (a
texture made without `PixelFormatView` usage takes views of its own format, its sRGB twin and,
where it renders, its channel-order sibling and that sibling's twin); or storage of its own over
the bytes the texture is over. The view's making takes the same decision, so the query refuses
what `new_texture_view` refuses, with the same error, but for storage over the bytes, refused
only as it is made. It makes nothing. No Metal counterpart: Metal makes the view of the
texture's own memory.
- `HostRam`, `Device::use_host_ram` (with `HostRamUse`) and `HostMemory::with_runs` (with
`RunResolver`): a guest's RAM imported whole, in 64 MiB chunks, for a device that refuses views
of guest pages made through dma-bufs; a no-copy object whose pages the consumer resolves to one
@@ -761,6 +984,18 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
`copy_runs_to_host_ram` take each run at a byte of the buffer of its own, so a buffer that
keeps a surface's layout (rows at a pitch, the padding between them untouched) is one call for
every row.
- `BlitCommandEncoder::copy_texture_from_host_ram` and `copy_texture_to_host_ram`: one 2D region
of a texture's slice and level filled from, or copied out into, a surface laid out in a used
guest RAM: the surface's bytes in order as host runs (as `copy_from_host_ram` takes them), the
region's rows from a byte of them at a pitch (Metal's buffer layout for
`copy_from_buffer_to_texture`). The rows whose host bytes lie the pitch apart in one chunk
(pages in a row) are one region of a `vkCmdCopyBufferToImage` or `vkCmdCopyImageToBuffer`
straight on the chunk's import (`bufferRowLength` the pitch), a row across a chunk's end or a
break in the host bytes a region for each piece, with no staging copy (first touch through the
CPU as the buffer forms); only the texels' bytes are
read or written; ordered and seen as the buffer forms are, the texture as a blit uses it
([HOWTO](../../docs/HOWTO.md#guest-ram-imported-whole)). For a single-sample texture of
uncompressed colour texels with an image of its own.
- `HostBytes`: bytes at a pointer that may change while a call reads them (a guest's memory),
which `Texture::replace_region_with_host_bytes` and `BufferContents::CopyHost` copy once through
the pointer, where the slice forms would need the caller's own copy first.
@@ -826,7 +1061,7 @@ message text. The ones a consumer meets most:
| `DriverSetting(DriverSetting)` | A driver setting the runtime cannot run under, such as MoltenVK with `MVK_CONFIG_USE_METAL_ARGUMENT_BUFFERS` off. |
| `DeviceRefused(DeviceRefused)` | The driver refused to make the device for want of its resources (`VK_ERROR_TOO_MANY_OBJECTS`, `VK_ERROR_INITIALIZATION_FAILED`, `VK_ERROR_OUT_OF_DEVICE_MEMORY` or `VK_ERROR_OUT_OF_HOST_MEMORY`), with its queue plan's `VkQueue`s and then with its least plan's; `attempts` names each. Other devices of the GPU, in any process, hold what it lacks; once fewer are live it may be made. |
| `WaitWouldDeadlock(DeadlockCause)` | A command buffer wait that would deadlock, refused at once instead of hanging. |
| `ShaderCache(...)` | The shader cache directory cannot be made or written. |
| `ShaderCache(...)` | The shader cache directory `ShaderCacheOptions::directory` names cannot be made or written. |
```rust,ignore
match device.new_render_pipeline_state(&descriptor, &PipelineOptions::default()) {
@@ -838,6 +1073,18 @@ match device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
}
```
A library or pipeline creation the runtime refuses can leave what replays it with the
translator's command line, a FALLBACK repro bundle, where `METAL2VULKAN_REPRO_DIR` names a
directory (unset, the runtime writes none): the library's bytes, `device.json` (the device's
description and policy, which the command line's `--device` reads), the request as the command
line's options and descriptor files, `repro.sh`, and `failure.txt` (the call, the refusal, and what
of the request the command does not replay). One is written for each distinct refusal of
`new_library_with_data`, a function's lookup, and a compute, tile or render pipeline state's
creation (not a mesh state's, nor a later variant's of a dispatch or draw), in a directory named by
its content, at most 32 bundles and 256 MiB per process; each is named in one line through the
device's message sink (id name `metal2vulkan-repro`) or on stderr. The refusal returned is the
same, with or without the variable.
A refused call records nothing. A command buffer that fails while it runs ends with status
`Error` and an `error()`; `metal_code()` gives Metal's code, and `origin()` whether Metal or the
runtime failed it. What a translated shader reports (a resident-set miss, for one) is a fact of
@@ -859,7 +1106,9 @@ calls that wait for the GPU (its completion or scheduling, an event it signals,
buffer of a queue whose most are all uncompleted) wait for it. No draw or dispatch is dropped for
its making's time. While it waits, another queue's command buffer committed after it goes first, even over a tracked
resource the two share, and the waiting one runs after it, as an x86 Mac's GPU may take a later
commit of another queue first; a fence the two share keeps commit order. One
commit of another queue first; a fence the two share keeps commit order, and so does a command
buffer of a queue made for copies (`Device::new_command_queue_for_copies`), which waits behind it
where the two conflict. One
call so waits for the driver's makings at most: a state's creation, its creation wait; a `commit`,
until its commit plus its commit wait (`DevicePolicy::pipeline_commit_wait`, 4.5 s by default),
for a pass that executes render commands the CPU writes, its pipelines and those its executions'
@@ -977,6 +1226,12 @@ meanwhile wait for it.
`Device::raw` answered is parked: a consumer leaves what it made with those handles (a
swapchain among them) and waits for none of its queues. Counted: `stall_probes_sent`,
`wedges_declared`, `watchdog_timeouts`, `longest_stall_nanos`.
- A command buffer whose work the driver dropped while its `VkDevice` goes on fails with
`GpuRecoveryVictim`, as Metal fails one its GPU's recovery discards, and its queue runs on: its
queue's timeline passed it while its own timestamps read unavailable. Linux's amdgpu ends a job
past its timeout (2 s by default); on a Radeon 780M (RADV) the command buffer queued behind such
a job on the same queue never ran either, and the device reported no error. A device that writes no timestamps for the command buffer cannot tell
(docs/FAST-PATHS.md, known gaps). Counted: `unrun_command_buffers`.
- `Device::raw` answers the new `VkDevice`'s handles once a later call asks; the handles it
answered before stay valid until then, and the lost `VkDevice` stays alive until then, so the
consumer destroys what it made with those handles (a swapchain, an import) first.
File diff suppressed because it is too large. Load diff
@@ -3,7 +3,7 @@
//! through the runtime's public calls alone, on one thread.
//!
//! ```sh
//! cargo run --release -p metal2vulkan-runtime --example draw_costs [-- [ws|many|10k|clips|damage|compositor|backdrops|pass1|pass17|scene|rebinds]... [--runs N] [--calls] [--counts] [--heap] [--shadowed] [--pages] [--states N] [--worker] [--threads N] [--metallib PATH]]
//! cargo run --release -p metal2vulkan-runtime --example draw_costs [-- [ws|many|10k|clips|damage|compositor|backdrops|pass1|pass17|scene|rebinds|restated|moved|guest]... [--runs N] [--calls] [--counts] [--heap] [--shadowed] [--pages] [--states N] [--worker] [--threads N] [--metallib PATH]]
//! ```
//!
//! Each shape is command buffers committed back to back, each of one render pass over a 512x512
@@ -48,8 +48,8 @@
//! view of icons: 8 command buffers of 16 passes of 1 draw, and of 4 passes of 17 draws. Each
//! pass loads and stores one of 8 surfaces of 256x256 over buffers of their own as the
//! compositor's are (`--pages` too), sets its viewport and draws the compositor's plain quads,
//! each after the pipeline state (once a pass: the next of 12 plain ones of their own blend
//! factors, so the state a pass draws through is none of the eight the last passes drew
//! each after the pipeline state (once a pass: the next of 20 plain ones of their own blend
//! factors, so the state a pass draws through is none of the sixteen the last passes drew
//! through, and its first draw takes every step, no kept draw of its state carried in; with
//! `--states N`, the first N of them), its
//! vertex buffers 0 and 1 and fragment buffer 0, fragment texture 0 (the next of its sampled
@@ -69,6 +69,18 @@
//! the mesh by 6 indices (`UInt16`) at the piece's offset.
//! - **rebinds**: as **scene**, but each draw first binds its material's 8 textures and 8
//! samplers again, the same objects within a material's run.
//! - **restated**: as **scene**, but each draw first sets a scissor rectangle of its own, the
//! next cell of **damage**'s grid, so nearly every draw is its pipeline state's kept draw
//! rebound with its scissor restated, its offsets moved and its own indices.
//! - **moved**: as **restated**, but each pass sets one material's pipeline state, textures and
//! samplers once, before its first draw, so every later draw of the pass changes only its
//! scissor rectangle, its offsets and its indices.
//! - **guest**, a guest's command buffers of a few render encoders: 16 command buffers of 4
//! passes over the target (the first cleared, the rest loaded) of 8 draws each. Each draw is a
//! 4-vertex triangle strip after `set_fragment_texture` (the next of 16), `set_vertex_buffer` at
//! its slot, then 16 bytes of `set_vertex_bytes` at index 1 and of `set_fragment_bytes` at
//! index 0, each its own; every second draw first `set_render_pipeline_state` (the next of 4)
//! and `set_fragment_sampler_states`.
//!
//! The slots lie in 64 KiB no-copy buffers over host pages (`new_buffer_with_bytes_no_copy`), as
//! a guest's upload chunks do, each command buffer's in chunks of its own. With `--heap`, the
@@ -99,9 +111,14 @@
//! A run is 2 untimed repetitions then 6 counted ones. Each repetition counts the calling
//! thread's CPU time and its instructions and cycles from the first command buffer's creation
//! through the last commit, then waits for every command buffer's handler outside the count, and
//! the process's page faults and voluntary context switches meanwhile (`getrusage`). On macOS the
//! instructions and cycles are libSystem's `thread_selfcounts` (readable unprivileged), which hold
//! the kernel's where it ran on the thread; on Linux they are the thread's own user-space counts
//! the process's page faults and voluntary context switches meanwhile (`getrusage`). On Linux,
//! the process's threads' CPU time over the counted repetitions, their waits included, is also
//! printed per draw by thread name (`DRAW-THREAD` lines, from each thread's `schedstat`, the
//! kernel's time on its behalf included; a thread that ended meanwhile is not counted; unnamed
//! threads under the program's name): the encoding thread's (`encoding`) against the runtime's own
//! threads' (its scheduler's submissions, its handler threads') and the driver's. On macOS the instructions and cycles are libSystem's
//! `thread_selfcounts` (readable unprivileged), which hold the kernel's where it ran on the
//! thread; on Linux they are the thread's own user-space counts
//! (`perf_event_open`, where `kernel.perf_event_paranoid` is at most 2; on a hybrid Intel CPU its
//! performance cores' counters alone, so pin the run there with `taskset`), with its L1 data
//! cache's read misses and its cache misses (`PERF_COUNT_HW_CACHE_MISSES`: the L2 on AMD's Zen,
@@ -117,10 +134,11 @@
//! each figure is then the threads' together a draw, so a cost that grows with the threads is
//! work they contend on (a lock, a counter every thread writes).
//!
//! With `--calls`, a run also counts each call's instructions apart, reading the counter around
//! With `--calls`, a run also counts each call's instructions apart, reading the counters around
//! each call (the read's own cost, measured as the run starts, taken off): printed per call
//! (`DRAW-CALL` lines), its calls a draw, its instructions a call and its share of a draw, the
//! median over the runs, with the lowest and highest a call. The reads cost the totals their own
//! median over the runs, with the lowest and highest a call, and its median cycles and cache
//! misses a call (no misses where the system counts none). The reads cost the totals their own
//! instructions, so a run's totals are read without `--calls`.
//!
//! With `--counts`, each shape's runs are bracketed by the device's work counts
@@ -202,10 +220,23 @@ enum Stream {
/// objects ([`Compositor::small_passes`]).
Passes(usize),
/// A 3D engine's frame of passes over four color targets ([`Scene`]), each draw binding its
/// material's textures and samplers again where `rebinds`.
Scene { rebinds: bool },
/// material's textures and samplers again where `rebinds`, and setting a scissor rectangle
/// of its own ([`damaged`]) where `scissors`; a material runs for `run` draws.
Scene {
rebinds: bool,
scissors: bool,
run: usize,
},
/// A guest's: [`GUEST_PASSES`] passes of [`GUEST_PASS_DRAWS`] draws, each draw a texture, its
/// vertex slot and its vertex and fragment bytes, every second one the pipeline state and the
/// sampler again ([`Bench::guest_steps`]).
Guest,
}
/// A guest shape's passes a command buffer, and a pass's draws.
const GUEST_PASSES: usize = 4;
const GUEST_PASS_DRAWS: usize = 8;
/// The columns of the grid of damaged rectangles a [`Stream::Damaged`] pass's draws take in turn,
/// and a cell's side in pixels.
const DAMAGE_COLUMNS: u64 = 25;
@@ -249,7 +280,7 @@ struct Shape {
}
/// The shapes, in the order they run.
const SHAPES: [Shape; 11] = [
const SHAPES: [Shape; 14] = [
Shape {
name: "ws",
buffers: 8,
@@ -308,13 +339,47 @@ const SHAPES: [Shape; 11] = [
name: "scene",
buffers: 8,
draws: SCENE_DRAWS,
stream: Stream::Scene { rebinds: false },
stream: Stream::Scene {
rebinds: false,
scissors: false,
run: SCENE_RUN,
},
},
Shape {
name: "rebinds",
buffers: 8,
draws: SCENE_DRAWS,
stream: Stream::Scene { rebinds: true },
stream: Stream::Scene {
rebinds: true,
scissors: false,
run: SCENE_RUN,
},
},
Shape {
name: "restated",
buffers: 8,
draws: SCENE_DRAWS,
stream: Stream::Scene {
rebinds: false,
scissors: true,
run: SCENE_RUN,
},
},
Shape {
name: "moved",
buffers: 8,
draws: SCENE_DRAWS,
stream: Stream::Scene {
rebinds: false,
scissors: true,
run: SCENE_PASS_DRAWS,
},
},
Shape {
name: "guest",
buffers: 16,
draws: GUEST_PASSES * GUEST_PASS_DRAWS,
stream: Stream::Guest,
},
];
@@ -322,7 +387,7 @@ impl Shape {
/// The slots a draw takes: its vertex bytes, and its fragment bytes in a compositor's stream.
fn slots(self) -> u64 {
match self.stream {
Stream::Bytes | Stream::Clipped | Stream::Damaged => 1,
Stream::Bytes | Stream::Clipped | Stream::Damaged | Stream::Guest => 1,
Stream::Layers => 2,
// Its slots lie in the compositor's or the scene's own buffer.
Stream::Composited { .. } | Stream::Passes(_) | Stream::Scene { .. } => 0,
@@ -343,7 +408,7 @@ impl Shape {
}
/// The calls `--calls` counts apart, by their index in a [`Tally`].
const CALLS: [&str; 17] = [
const CALLS: [&str; 19] = [
"command_buffer",
"render_command_encoder",
"set_render_pipeline_state",
@@ -361,37 +426,52 @@ const CALLS: [&str; 17] = [
"set_vertex_buffer_offset",
"set_fragment_buffer_offset",
"set_fragment_textures",
"set_vertex_bytes",
"set_fragment_bytes",
];
/// Each call's count and instructions, over a run's counted repetitions.
type Tally = [(u64, u64); CALLS.len()];
/// Each call's count, and its instructions, cycles and cache misses ([`call_counts`]), over a
/// run's counted repetitions.
type Tally = [(u64, [u64; 3]); CALLS.len()];
/// Run `body` as call `kind`, counting its instructions into `tally` where there is one.
/// The calling thread's instructions, cycles and cache misses so far, the misses 0 where the
/// system counts none ([`data_misses`]).
fn call_counts() -> Option<[u64; 3]> {
let [instructions, cycles] = instructions_and_cycles()?;
let misses = data_misses().map_or(0, |[_, cache]| cache);
Some([instructions, cycles, misses])
}
/// Run `body` as call `kind`, counting its instructions, cycles and cache misses into `tally`
/// where there is one.
fn call<T>(tally: &mut Option<&mut Tally>, kind: usize, body: impl FnOnce() -> T) -> T {
let Some(tally) = tally else {
return body();
};
let before = instructions_and_cycles();
let before = call_counts();
let answer = body();
if let Some((after, before)) = instructions_and_cycles().zip(before) {
if let Some((after, before)) = call_counts().zip(before) {
tally[kind].0 += 1;
tally[kind].1 += after[0] - before[0];
for (sum, (after, before)) in tally[kind].1.iter_mut().zip(after.into_iter().zip(before)) {
*sum += after - before;
}
}
answer
}
/// The instructions a read of the counter pair costs between them, the median of many.
fn read_cost() -> f64 {
/// The instructions, cycles and cache misses a read of the counters costs between them, the
/// median of many each.
fn read_cost() -> [f64; 3] {
let pairs = (0..10_000)
.filter_map(|_| {
let before = instructions_and_cycles()?;
let after = instructions_and_cycles()?;
Some((after[0] - before[0]) as f64)
let before = call_counts()?;
let after = call_counts()?;
Some([0, 1, 2].map(|at| (after[at] - before[at]) as f64))
})
.collect::<Vec<_>>();
match pairs.is_empty() {
true => 0.0,
false => spread(pairs).0,
true => [0.0; 3],
false => [0, 1, 2].map(|at| spread(pairs.iter().map(|pair| pair[at]).collect()).0),
}
}
@@ -418,6 +498,9 @@ enum Step<'a> {
Draw(PrimitiveType, u32),
/// Six `UInt16` indices of a triangle list at this offset of the buffer.
DrawIndexed(&'a Buffer, u64),
/// 16 bytes, each this value, at this vertex or fragment index.
VertexBytes(u8, u32),
FragmentBytes(u8, u32),
}
/// The objects every shape draws with.
@@ -425,6 +508,8 @@ struct Bench {
device: Device,
queue: CommandQueue,
pass: RenderPassDescriptor,
/// The pass, loading the target rather than clearing it.
loaded: RenderPassDescriptor,
pipelines: Vec<RenderPipelineState>,
textures: Vec<Texture>,
sampler: SamplerState,
@@ -517,6 +602,8 @@ impl Bench {
color.load_action = load;
color.store_action = StoreAction::Store;
color.clear_color = ClearColor::new(0.0, 0.0, 0.0, 1.0);
let mut loaded = pass.clone();
loaded.color_attachments[0].load_action = LoadAction::Load;
let compositor = match compositor {
Some(made) => Some(Compositor::new(&device, library, made)?),
None => None,
@@ -531,6 +618,7 @@ impl Bench {
constants: device.new_buffer(4096, ResourceOptions::shared())?,
device,
pass,
loaded,
pipelines,
textures,
_target_pages: target_pages,
@@ -626,8 +714,19 @@ impl Bench {
if let (Stream::Passes(each), Some(compositor)) = (shape.stream, &self.compositor) {
return compositor.small_passes(buffer, shape.draws / each, each);
}
if let (Stream::Scene { rebinds }, Some(scene)) = (shape.stream, &self.scene) {
return scene.steps(buffer, rebinds);
if let (
Stream::Scene {
rebinds,
scissors,
run,
},
Some(scene),
) = (shape.stream, &self.scene)
{
return scene.steps(buffer, (rebinds, scissors), run);
}
if shape.stream == Stream::Guest {
return self.guest_steps(chunks, shape, buffer);
}
let mut steps = vec![
Step::Pipeline(&self.pipelines[0]),
@@ -654,7 +753,10 @@ impl Bench {
steps.push(Step::VertexBuffer(&chunks[chunk], offset, 0));
steps.push(Step::Draw(PrimitiveType::TriangleStrip, 4));
}
Stream::Composited { .. } | Stream::Passes(_) | Stream::Scene { .. } => {}
Stream::Composited { .. }
| Stream::Passes(_)
| Stream::Scene { .. }
| Stream::Guest => {}
Stream::Clipped | Stream::Damaged => {
if draw % RUN == 0 {
steps.push(Step::Pipeline(&self.pipelines[draw / RUN % PIPELINES]));
@@ -678,6 +780,35 @@ impl Bench {
steps
}
/// Command buffer `buffer`'s calls of a guest shape ([`Stream::Guest`]), over `chunks`.
fn guest_steps<'a>(
&'a self,
chunks: &'a [Buffer],
shape: Shape,
buffer: usize,
) -> Vec<Step<'a>> {
let mut steps = Vec::new();
for draw in 0..shape.draws {
if draw % GUEST_PASS_DRAWS == 0 {
steps.push(Step::Begin(match draw {
0 => &self.pass,
_ => &self.loaded,
}));
}
if draw % 2 == 0 {
steps.push(Step::Pipeline(&self.pipelines[draw / 2 % PIPELINES]));
steps.push(Step::FragmentSampler(&self.sampler));
}
steps.push(Step::FragmentTexture(&self.textures[draw % TEXTURES], 0));
let (chunk, offset) = shape.slot(buffer, draw as u64);
steps.push(Step::VertexBuffer(&chunks[chunk], offset, 0));
steps.push(Step::VertexBytes(draw as u8, 1));
steps.push(Step::FragmentBytes(draw as u8, 0));
steps.push(Step::Draw(PrimitiveType::TriangleStrip, 4));
}
steps
}
/// One repetition: every command buffer's calls, counted from the first one's creation
/// through the last commit, then each handler waited for; each call counted apart into
/// `tally` where there is one.
@@ -760,6 +891,12 @@ impl Bench {
Step::Draw(primitive, count) => call(&mut tally, 7, || {
encoder.draw_primitives(primitive, 0, count, 1, 0)
}),
Step::VertexBytes(value, index) => call(&mut tally, 17, || {
encoder.set_vertex_bytes(&[value; 16], index)
}),
Step::FragmentBytes(value, index) => call(&mut tally, 18, || {
encoder.set_fragment_bytes(&[value; 16], index)
}),
Step::DrawIndexed(buffer, offset) => call(&mut tally, 13, || {
encoder.draw_indexed_primitives(
PrimitiveType::Triangle,
@@ -855,7 +992,7 @@ struct FrameDraw {
/// The plain pipeline states of the small passes ([`Stream::Passes`]), by their color's source
/// and destination blend factors: more than the eight a render encoder carries kept draws of (its
/// last state's and the seven its bind state sets aside).
const SMALL_BLENDS: [(BlendFactor, BlendFactor); 12] = [
const SMALL_BLENDS: [(BlendFactor, BlendFactor); 20] = [
(BlendFactor::One, BlendFactor::OneMinusSourceAlpha),
(BlendFactor::SourceAlpha, BlendFactor::OneMinusSourceAlpha),
(BlendFactor::One, BlendFactor::Zero),
@@ -868,6 +1005,14 @@ const SMALL_BLENDS: [(BlendFactor, BlendFactor); 12] = [
(BlendFactor::DestinationAlpha, BlendFactor::One),
(BlendFactor::OneMinusDestinationAlpha, BlendFactor::One),
(BlendFactor::SourceAlphaSaturated, BlendFactor::One),
(BlendFactor::SourceAlpha, BlendFactor::One),
(BlendFactor::One, BlendFactor::SourceAlpha),
(BlendFactor::Zero, BlendFactor::One),
(BlendFactor::Zero, BlendFactor::OneMinusSourceAlpha),
(BlendFactor::OneMinusSourceColor, BlendFactor::One),
(BlendFactor::DestinationColor, BlendFactor::One),
(BlendFactor::SourceAlpha, BlendFactor::Zero),
(BlendFactor::One, BlendFactor::SourceColor),
];
/// The compositor shape's objects (the module docs): its passes with their viewports, their
@@ -1375,8 +1520,9 @@ impl Scene {
/// Command buffer `buffer`'s steps: its passes and their draws, each draw's slots the next
/// of the buffer's; each draw binding its material's textures and samplers again where
/// `rebinds`.
fn steps(&self, buffer: usize, rebinds: bool) -> Vec<Step<'_>> {
/// `rebinds`, and setting a scissor rectangle of its own where `scissors`; a material runs
/// for `run` draws, a divisor of a pass's.
fn steps(&self, buffer: usize, (rebinds, scissors): (bool, bool), run: usize) -> Vec<Step<'_>> {
let mut steps = Vec::new();
for d in 0..SCENE_DRAWS {
if d % SCENE_PASS_DRAWS == 0 {
@@ -1385,14 +1531,17 @@ impl Scene {
steps.push(Step::VertexBuffer(&self.data, SCENE_TRANSFORMS, 1));
steps.push(Step::FragmentBuffer(&self.data, SCENE_SCALES, 0));
}
let material = (buffer * SCENE_DRAWS + d) / SCENE_RUN % SCENE_MATERIALS;
if d % SCENE_RUN == 0 {
let material = (buffer * SCENE_DRAWS + d) / run % SCENE_MATERIALS;
if d % run == 0 {
steps.push(Step::Pipeline(&self.pipelines[material % SCENE_PIPELINES]));
}
if rebinds || d % SCENE_RUN == 0 {
if rebinds || d % run == 0 {
steps.push(Step::FragmentTextures(&self.materials[material]));
steps.push(Step::FragmentSamplers(&self.samplers));
}
if scissors {
steps.push(Step::Scissor(damaged(d)));
}
let slot = (buffer * SCENE_DRAWS + d) as u64 % SCENE_SLOTS;
steps.push(Step::VertexOffset(SCENE_TRANSFORMS + slot * 256, 1));
steps.push(Step::FragmentOffset(SCENE_SCALES + slot * 256, 0));
@@ -1413,10 +1562,13 @@ struct Counts {
/// Its L1 data cache's read misses and its cache misses where the system counts them
/// ([`data_misses`]).
misses: Option<[u64; 2]>,
process: [u64; 2],
/// The process's minor faults and voluntary context switches where the system counts them
/// (`getrusage`; none on Windows).
process: Option<[u64; 2]>,
}
impl Counts {
#[cfg(unix)]
fn now() -> Counts {
let mut at = libc::timespec {
tv_sec: 0,
@@ -1434,7 +1586,31 @@ impl Counts {
nanos: at.tv_sec as u64 * 1_000_000_000 + at.tv_nsec as u64,
instructions: instructions_and_cycles(),
misses: data_misses(),
process: [usage.ru_minflt as u64, usage.ru_nvcsw as u64],
process: Some([usage.ru_minflt as u64, usage.ru_nvcsw as u64]),
}
}
/// The counts now on Windows: the thread's kernel and user times (`GetThreadTimes`, in 100 ns
/// units), and no process counts, which Windows does not keep per process.
#[cfg(windows)]
fn now() -> Counts {
let nanos = {
use windows_sys::Win32::Foundation::FILETIME;
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes};
let mut times = [FILETIME::default(); 4];
let [created, exited, kernel, user] = &mut times;
// SAFETY: the calling thread's pseudo-handle, and four `FILETIME`s for the call to fill.
let read = unsafe { GetThreadTimes(GetCurrentThread(), created, exited, kernel, user) };
assert_ne!(read, 0, "GetThreadTimes");
let ticks =
|t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
(ticks(kernel) + ticks(user)) * 100
};
Counts {
nanos,
instructions: instructions_and_cycles(),
misses: data_misses(),
process: None,
}
}
@@ -1450,10 +1626,10 @@ impl Counts {
.misses
.zip(start.misses)
.map(|(now, then)| [now[0] - then[0], now[1] - then[1]]),
process: [
self.process[0] - start.process[0],
self.process[1] - start.process[1],
],
process: self
.process
.zip(start.process)
.map(|(now, then)| [now[0] - then[0], now[1] - then[1]]),
}
}
@@ -1468,10 +1644,10 @@ impl Counts {
.misses
.zip(more.misses)
.map(|(a, b)| [a[0] + b[0], a[1] + b[1]]),
process: [
self.process[0] + more.process[0],
self.process[1] + more.process[1],
],
process: self
.process
.zip(more.process)
.map(|(a, b)| [a[0] + b[0], a[1] + b[1]]),
}
}
}
@@ -1638,15 +1814,19 @@ struct Options {
threads: usize,
}
/// What one thread's run answers ([`thread_run`]): its counts, its calls' tally, and each named
/// thread's CPU time.
type ThreadRun = (Counts, Tally, Vec<(String, u64)>);
/// One thread's run of its command buffers' `buffers`: its counted repetitions' counts together,
/// and its calls' tally where `calls`, each repetition started with the other threads' at
/// `start`.
/// its calls' tally where `calls`, and where `whole` the process's threads' CPU time over them
/// ([`thread_times`]), each repetition started with the other threads' at `start`.
fn thread_run(
bench: &Bench,
buffers: &[Vec<Step<'_>>],
calls: bool,
(calls, whole): (bool, bool),
start: &Barrier,
) -> Result<(Counts, Tally)> {
) -> Result<ThreadRun> {
// On a Mac, the performance cores, as the main thread asks for them.
#[cfg(target_os = "macos")]
// SAFETY: sets the calling thread's own class; it takes no pointer.
@@ -1654,16 +1834,70 @@ fn thread_run(
libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
}
let mut total: Option<Counts> = None;
let mut tally: Tally = [(0, 0); CALLS.len()];
let mut tally: Tally = [(0, [0; 3]); CALLS.len()];
let mut threads = Vec::new();
for repetition in 0..WARM + COUNTED {
let counted = repetition >= WARM;
start.wait();
if whole && repetition == WARM {
threads = thread_times();
}
let spent = bench.repetition(buffers, (calls && counted).then_some(&mut tally))?;
if counted {
total = Some(total.map_or(spent, |total| total.plus(spent)));
}
}
Ok((total.unwrap_or_default(), tally))
if whole {
let before = threads;
threads = thread_times();
for (name, spent) in &mut threads {
let then = before.iter().find(|(named, _)| named == name);
*spent = spent.saturating_sub(then.map_or(0, |(_, then)| *then));
}
}
Ok((total.unwrap_or_default(), tally, threads))
}
/// On Linux, the CPU time of each of the process's threads so far, summed by thread name
/// (`/proc/self/task/*/comm`), the calling thread's as `encoding` (an unnamed thread takes the
/// program's name): the first field of its `schedstat`, its nanoseconds on a CPU, the kernel's on
/// its behalf included. A thread that ended is no longer counted.
#[cfg(target_os = "linux")]
fn thread_times() -> Vec<(String, u64)> {
let mut times: Vec<(String, u64)> = Vec::new();
let Ok(tasks) = std::fs::read_dir("/proc/self/task") else {
return times;
};
// SAFETY: takes no argument and answers the calling thread's id.
let caller = unsafe { libc::gettid() }.to_string();
for task in tasks.flatten() {
let path = task.path();
let (Ok(name), Ok(stat)) = (
std::fs::read_to_string(path.join("comm")),
std::fs::read_to_string(path.join("schedstat")),
) else {
continue;
};
let Some(nanos) = (stat.split_whitespace().next()).and_then(|ns| ns.parse::<u64>().ok())
else {
continue;
};
let name = match task.file_name().to_str() == Some(caller.as_str()) {
true => "encoding",
false => name.trim(),
};
match times.iter_mut().find(|(named, _)| named == name) {
Some((_, total)) => *total += nanos,
None => times.push((name.to_owned(), nanos)),
}
}
times
}
/// Elsewhere, none: the threads' times are read on Linux alone.
#[cfg(not(target_os = "linux"))]
fn thread_times() -> Vec<(String, u64)> {
Vec::new()
}
/// Run `shape` `runs` times and print its figures a draw, and with `--calls` each call's.
@@ -1688,17 +1922,20 @@ fn measure(bench: &Bench, shape: Shape, runs: usize, options: Options) -> Result
let draws = (COUNTED * threads * shape.buffers * shape.draws) as f64;
let mut seen = Vec::with_capacity(runs);
let mut tallies = Vec::with_capacity(runs);
let mut threads_seen: Vec<Vec<(String, u64)>> = Vec::with_capacity(runs);
for _ in 0..runs {
let start = Barrier::new(threads);
let ran: Vec<Result<(Counts, Tally)>> = match threads {
1 => vec![thread_run(bench, &buffers[0], calls, &start)],
let ran: Vec<Result<ThreadRun>> = match threads {
1 => vec![thread_run(bench, &buffers[0], (calls, true), &start)],
_ => std::thread::scope(|scope| {
// Each thread's refusal as its text, which crosses threads.
let running: Vec<_> = (buffers.iter())
.map(|own| {
// Each thread's refusal as its text, which crosses threads; the first reads the
// process's threads' times.
let running: Vec<_> = (buffers.iter().enumerate())
.map(|(at, own)| {
let start = &start;
scope.spawn(move || {
thread_run(bench, own, calls, start).map_err(|error| error.to_string())
thread_run(bench, own, (calls, at == 0), start)
.map_err(|error| error.to_string())
})
})
.collect();
@@ -1711,17 +1948,23 @@ fn measure(bench: &Bench, shape: Shape, runs: usize, options: Options) -> Result
}),
};
let mut total: Option<Counts> = None;
let mut tally: Tally = [(0, 0); CALLS.len()];
let mut tally: Tally = [(0, [0; 3]); CALLS.len()];
for answer in ran {
let (spent, own) = answer?;
let (spent, own, times) = answer?;
if !times.is_empty() {
threads_seen.push(times);
}
total = Some(total.map_or(spent, |total| total.plus(spent)));
for (all, one) in tally.iter_mut().zip(own) {
*all = (all.0 + one.0, all.1 + one.1);
all.0 += one.0;
for (sum, more) in all.1.iter_mut().zip(one.1) {
*sum += more;
}
}
}
// The process's counts each thread took over the same span: theirs once.
let mut total = total.unwrap_or_default();
total.process = total.process.map(|count| count / threads as u64);
total.process = (total.process).map(|counts| counts.map(|count| count / threads as u64));
seen.push(total);
tallies.push(tally);
}
@@ -1750,12 +1993,14 @@ fn measure(bench: &Bench, shape: Shape, runs: usize, options: Options) -> Result
"cpu_ns",
seen.iter().map(|c| c.nanos as f64 / draws).collect(),
)];
for (figure, index) in [("process_faults", 0), ("process_switches", 1)] {
let values = seen
.iter()
.map(|c| c.process[index] as f64 / draws)
.collect();
figures.push((figure, values));
if seen.iter().all(|c| c.process.is_some()) {
for (figure, index) in [("process_faults", 0), ("process_switches", 1)] {
let values = seen
.iter()
.filter_map(|c| c.process.map(|p| p[index] as f64 / draws))
.collect();
figures.push((figure, values));
}
}
if seen.iter().all(|c| c.instructions.is_some()) {
for (figure, index) in [("instructions", 0), ("cycles", 1)] {
@@ -1782,26 +2027,58 @@ fn measure(bench: &Bench, shape: Shape, runs: usize, options: Options) -> Result
shape.name
);
}
// Each thread name's CPU time a draw, by the most first, and the threads' together.
let mut names: Vec<&str> = Vec::new();
for (name, _) in threads_seen.iter().flatten() {
if !names.contains(&name.as_str()) {
names.push(name);
}
}
let a_draw = |run: &Vec<(String, u64)>, name: Option<&str>| {
let spent = run
.iter()
.filter(|(named, _)| name.is_none_or(|name| named == name));
spent.map(|(_, nanos)| *nanos).sum::<u64>() as f64 / draws
};
let mut thread_figures: Vec<(&str, (f64, f64, f64))> = (names.iter())
.map(|&name| {
let values = threads_seen.iter().map(|run| a_draw(run, Some(name)));
(name, spread(values.collect()))
})
.collect();
thread_figures.sort_by(|(_, a), (_, b)| b.0.total_cmp(&a.0));
if !threads_seen.is_empty() {
let values = threads_seen.iter().map(|run| a_draw(run, None));
thread_figures.push(("all", spread(values.collect())));
}
for (name, (median, low, high)) in thread_figures {
println!(
"DRAW-THREAD {} {name} ns {median:.1} [{low:.1}, {high:.1}]",
shape.name
);
}
if calls && seen.iter().all(|c| c.instructions.is_some()) {
let read = read_cost();
println!(
"{}: a counter read's own instructions: {read:.1}",
shape.name
"{}: a counter read's own instructions, cycles and cache misses: {:.1}, {:.1}, {:.1}",
shape.name, read[0], read[1], read[2]
);
for (kind, name) in CALLS.iter().enumerate() {
let made = tallies[0][kind].0;
if made == 0 {
continue;
}
let each = tallies
.iter()
.map(|tally| tally[kind].1 as f64 / tally[kind].0 as f64 - read)
.collect();
let (median, low, high) = spread(each);
let a_call = |at: usize| {
let each = (tallies.iter())
.map(|tally| tally[kind].1[at] as f64 / tally[kind].0 as f64 - read[at]);
spread(each.collect())
};
let (median, low, high) = a_call(0);
let (cycles, misses) = (a_call(1).0, a_call(2).0);
let a_draw = made as f64 / draws;
println!(
"DRAW-CALL {} {name} calls_a_draw {a_draw:.3} a_call {median:.1} [{low:.1}, \
{high:.1}] a_draw {:.1}",
{high:.1}] a_draw {:.1} cycles_a_call {cycles:.0} misses_a_call {misses:.1}",
shape.name,
median * a_draw
);
@@ -1813,6 +2090,7 @@ fn measure(bench: &Bench, shape: Shape, runs: usize, options: Options) -> Result
/// `bytes` bytes of fresh host pages, read-write, never unmapped: private, as RADV refuses to
/// import shared anonymous memory (`host_memory.rs`'s `import_refused`).
fn host_pages(bytes: usize) -> Result<NonNull<u8>> {
#[cfg(unix)]
// SAFETY: a fresh anonymous mapping, read-write, never unmapped.
let pages = unsafe {
libc::mmap(
@@ -1824,6 +2102,18 @@ fn host_pages(bytes: usize) -> Result<NonNull<u8>> {
0,
)
};
#[cfg(windows)]
// SAFETY: a new allocation of its own, at an address the system picks.
let pages = unsafe {
windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
bytes,
windows_sys::Win32::System::Memory::MEM_RESERVE
| windows_sys::Win32::System::Memory::MEM_COMMIT,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
)
};
#[cfg(unix)]
if pages == libc::MAP_FAILED {
return Err(format!("mmap: {}", std::io::Error::last_os_error()).into());
}
@@ -1895,8 +2185,8 @@ fn main() -> Result<()> {
name => shapes.push(*SHAPES.iter().find(|shape| shape.name == name).ok_or_else(
|| {
format!(
"no shape {name}: ws, many, 10k, clips, damage, compositor, scene or \
rebinds"
"no shape {name}: ws, many, 10k, clips, damage, compositor, backdrops, \
pass1, pass17, scene, rebinds, restated, moved or guest"
)
},
)?),
@@ -1310,6 +1310,7 @@ impl Gpu for Runtime {
c.render_passes_begun_inline_splits,
),
("passes_begun_resolves", c.render_passes_begun_resolves),
("passes_continued", c.render_passes_continued),
("splits_barrier", c.instance_splits_barrier),
("splits_tile_dispatch", c.instance_splits_tile_dispatch),
("splits_tile_memory", c.instance_splits_tile_memory),
@@ -1523,6 +1524,10 @@ impl Gpu for Runtime {
("calibration_readings", c.calibration_readings),
("calibration_deviation_most", c.calibration_deviation_most),
("calibration_disagreements", c.calibration_disagreements),
(
"loosely_calibrated_gpu_times",
c.loosely_calibrated_gpu_times,
),
("storage_forms_taken", c.storage_forms_taken),
("addressable_buffers_made", c.addressable_buffers_made),
("mipmaps_filtered", c.mipmaps_filtered),
@@ -1656,6 +1661,10 @@ impl Gpu for Runtime {
"encoder_primaries_begun_ahead",
c.encoder_primaries_begun_ahead,
),
(
"encoder_primaries_begun_ahead_missed",
c.encoder_primaries_begun_ahead_missed,
),
("primaries_begun_ahead", c.primaries_begun_ahead),
("barrier_buffers_kept", c.barrier_buffers_kept),
("stamped_buffers_kept", c.stamped_buffers_kept),
@@ -1667,9 +1676,11 @@ impl Gpu for Runtime {
("group_ends_wait", c.group_ends_wait),
("group_ends_apart", c.group_ends_apart),
("group_ends_first_work", c.group_ends_first_work),
("group_ends_long", c.group_ends_long),
("group_ends_drained", c.group_ends_drained),
("group_ends_checks", c.group_ends_checks),
("group_ends_held", c.group_ends_held),
("group_ends_closed", c.group_ends_closed),
("batches_with_none_pending", c.batches_with_none_pending),
("batches_with_one_pending", c.batches_with_one_pending),
(
@@ -1850,6 +1861,12 @@ impl Gpu for Runtime {
c.set_zero_writes_if_shapes_shared,
),
("dispatches_pushing_set_zero", c.dispatches_pushing_set_zero),
(
"dispatch_set_zero_writes_pushed",
c.dispatch_set_zero_writes_pushed,
),
("dispatches_tracked", c.dispatches_tracked),
("dispatch_uses_tracked", c.dispatch_uses_tracked),
("set_zero_sets_reused", c.set_zero_sets_reused),
("set_zero_sets_found", c.set_zero_sets_found),
("draw_shapes_reused", c.draw_shapes_reused),
@@ -1940,6 +1957,7 @@ impl Gpu for Runtime {
c.host_imports_kept_no_stand_in,
),
("dma_buf_sparse_buffers", c.dma_buf_sparse_buffers),
("dma_buf_sparse_binds", c.dma_buf_sparse_binds),
("dma_buf_images", c.dma_buf_images),
("dma_buf_image_fallbacks", c.dma_buf_image_fallbacks),
("modifier_feature_queries", c.modifier_feature_queries),
@@ -49,6 +49,7 @@ fn ms(d: Duration) -> f64 {
}
/// The process's CPU time so far (user and system, every thread).
#[cfg(unix)]
pub fn process_cpu() -> Duration {
// SAFETY: `getrusage` writes the struct it is given.
let usage = unsafe {
@@ -60,7 +61,25 @@ pub fn process_cpu() -> Duration {
tv(usage.ru_utime) + tv(usage.ru_stime)
}
/// The process's CPU time so far (user and system, every thread): its kernel and user times
/// (`GetProcessTimes`), in 100 ns units.
#[cfg(windows)]
pub fn process_cpu() -> Duration {
Duration::from_nanos({
use windows_sys::Win32::Foundation::FILETIME;
use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes};
let mut times = [FILETIME::default(); 4];
let [created, exited, kernel, user] = &mut times;
// SAFETY: this process's pseudo-handle, and four `FILETIME`s for the call to fill.
let read = unsafe { GetProcessTimes(GetCurrentProcess(), created, exited, kernel, user) };
assert_ne!(read, 0, "GetProcessTimes");
let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
(ticks(kernel) + ticks(user)) * 100
})
}
/// The calling thread's CPU time so far.
#[cfg(unix)]
pub fn thread_cpu() -> Duration {
// SAFETY: `clock_gettime` writes the struct it is given.
let spec = unsafe {
@@ -74,6 +93,23 @@ pub fn thread_cpu() -> Duration {
Duration::new(spec.tv_sec as u64, spec.tv_nsec as u32)
}
/// The calling thread's CPU time so far: its kernel and user times (`GetThreadTimes`), in 100 ns
/// units.
#[cfg(windows)]
pub fn thread_cpu() -> Duration {
Duration::from_nanos({
use windows_sys::Win32::Foundation::FILETIME;
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes};
let mut times = [FILETIME::default(); 4];
let [created, exited, kernel, user] = &mut times;
// SAFETY: the calling thread's pseudo-handle, and four `FILETIME`s for the call to fill.
let read = unsafe { GetThreadTimes(GetCurrentThread(), created, exited, kernel, user) };
assert_ne!(read, 0, "GetThreadTimes");
let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
(ticks(kernel) + ticks(user)) * 100
})
}
/// The rectangles' buffers: [`RECTS`] rectangles each, one every [`RECT_STRIDE`] bytes.
const RECT_BUFFERS: usize = 4;
const RECTS: usize = 1024;
@@ -1454,6 +1490,7 @@ pub fn memory<G: Gpu>(g: &G, sizes: &Sizes, variants: &[String]) {
let mut times = vec![];
let mut maps = vec![];
for _ in 0..repeats(length) {
#[cfg(unix)]
// SAFETY: an anonymous private mapping of `length` bytes, unmapped below once every
// buffer over it is gone.
let pointer = unsafe {
@@ -1466,7 +1503,21 @@ pub fn memory<G: Gpu>(g: &G, sizes: &Sizes, variants: &[String]) {
0,
)
};
#[cfg(windows)]
// SAFETY: a new allocation of its own, at an address the system picks.
let pointer = unsafe {
windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
length,
windows_sys::Win32::System::Memory::MEM_RESERVE
| windows_sys::Win32::System::Memory::MEM_COMMIT,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
)
};
#[cfg(unix)]
assert_ne!(pointer, libc::MAP_FAILED);
#[cfg(windows)]
assert!(!pointer.is_null());
// SAFETY: the pages are mapped read-write; touch them as a program's own data is.
unsafe { std::ptr::write_bytes(pointer as *mut u8, 0x11, length) };
let t = Instant::now();
@@ -1489,7 +1540,19 @@ pub fn memory<G: Gpu>(g: &G, sizes: &Sizes, variants: &[String]) {
std::thread::sleep(Duration::from_millis(50));
for pointer in maps {
// SAFETY: mapped above, no buffer over it remains.
unsafe { libc::munmap(pointer, length) };
#[cfg(unix)]
unsafe {
libc::munmap(pointer, length)
};
#[cfg(windows)]
// SAFETY: as above; a release frees the allocation whole, from its base.
unsafe {
windows_sys::Win32::System::Memory::VirtualFree(
pointer,
0,
windows_sys::Win32::System::Memory::MEM_RELEASE,
)
};
}
}
// Buffers held, as a program that grows its memory makes them: each takes memory no buffer
@@ -1658,6 +1721,7 @@ pub fn frame<G: Gpu>(g: &G, s: &Scene<G>, sizes: &Sizes) {
emit("frame", &format!("{name}_process_cpu"), "us", cpu);
};
run("frame", &g.heap(size));
#[cfg(unix)]
// SAFETY: an anonymous private mapping of `size` bytes, never unmapped: the process's to its
// end, past the heap and every texture placed in it.
let pointer = unsafe {
@@ -1670,7 +1734,21 @@ pub fn frame<G: Gpu>(g: &G, s: &Scene<G>, sizes: &Sizes) {
0,
)
};
#[cfg(windows)]
// SAFETY: a new allocation of its own, at an address the system picks.
let pointer = unsafe {
windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
size,
windows_sys::Win32::System::Memory::MEM_RESERVE
| windows_sys::Win32::System::Memory::MEM_COMMIT,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
)
};
#[cfg(unix)]
assert_ne!(pointer, libc::MAP_FAILED);
#[cfg(windows)]
assert!(!pointer.is_null());
// SAFETY: page-aligned read-write memory of `size` bytes that outlives the heap.
if let Some(heap) = unsafe { g.heap_no_copy(pointer as *mut u8, size) } {
run("frame_no_copy", &heap);
@@ -1813,6 +1891,7 @@ pub fn drag<G: Gpu>(g: &G, s: &Scene<G>, sizes: &Sizes) {
///
/// Never unmapped: the caller keeps it for the process's life.
pub unsafe fn host_pages(size: usize) -> *mut u8 {
#[cfg(unix)]
// SAFETY: a new anonymous mapping, which nothing else holds.
let pointer = unsafe {
libc::mmap(
@@ -1824,7 +1903,21 @@ pub unsafe fn host_pages(size: usize) -> *mut u8 {
0,
)
};
#[cfg(windows)]
// SAFETY: a new allocation of its own, at an address the system picks.
let pointer = unsafe {
windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
size,
windows_sys::Win32::System::Memory::MEM_RESERVE
| windows_sys::Win32::System::Memory::MEM_COMMIT,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
)
};
#[cfg(unix)]
assert_ne!(pointer, libc::MAP_FAILED);
#[cfg(windows)]
assert!(!pointer.is_null());
pointer as *mut u8
}
@@ -631,6 +631,7 @@ fn private_with(device: &Device, bytes: &[u8]) -> Result<Buffer> {
/// A no-copy buffer of `bytes` bytes of fresh host pages with the private option bit
/// (`ResourceOptions::PRIVATE_BIT`): a read twin where the device imports the pages in place.
fn twinned(device: &Device, bytes: usize) -> Result<Buffer> {
#[cfg(unix)]
// SAFETY: a fresh anonymous mapping, read-write, never unmapped.
let pages = unsafe {
libc::mmap(
@@ -642,6 +643,18 @@ fn twinned(device: &Device, bytes: usize) -> Result<Buffer> {
0,
)
};
#[cfg(windows)]
// SAFETY: a new allocation of its own, at an address the system picks.
let pages = unsafe {
windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
bytes,
windows_sys::Win32::System::Memory::MEM_RESERVE
| windows_sys::Win32::System::Memory::MEM_COMMIT,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
)
};
#[cfg(unix)]
if pages == libc::MAP_FAILED {
return Err(format!("mmap: {}", std::io::Error::last_os_error()).into());
}
@@ -85,6 +85,7 @@ struct Pages(NonNull<u8>, u64);
impl Pages {
fn new(bytes: u64) -> Result<Pages> {
#[cfg(unix)]
// SAFETY: a new anonymous mapping, which nothing else uses.
let pointer = unsafe {
libc::mmap(
@@ -96,6 +97,18 @@ impl Pages {
0,
)
};
#[cfg(windows)]
// SAFETY: a new allocation of its own, at an address the system picks.
let pointer = unsafe {
windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
bytes as usize,
windows_sys::Win32::System::Memory::MEM_RESERVE
| windows_sys::Win32::System::Memory::MEM_COMMIT,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
)
};
#[cfg(unix)]
if pointer == libc::MAP_FAILED {
return Err("mmap failed".into());
}
@@ -113,7 +126,19 @@ impl Pages {
impl Drop for Pages {
fn drop(&mut self) {
// SAFETY: the mapping `new` made; every buffer over it went before it.
unsafe { libc::munmap(self.0.as_ptr().cast(), self.1 as usize) };
#[cfg(unix)]
unsafe {
libc::munmap(self.0.as_ptr().cast(), self.1 as usize)
};
#[cfg(windows)]
// SAFETY: as above; a release frees the allocation whole, from its base.
unsafe {
windows_sys::Win32::System::Memory::VirtualFree(
self.0.as_ptr().cast(),
0,
windows_sys::Win32::System::Memory::MEM_RELEASE,
)
};
}
}
@@ -68,6 +68,7 @@ struct Pages(NonNull<u8>);
impl Pages {
fn new() -> common::Result<Pages> {
#[cfg(unix)]
// SAFETY: a new anonymous mapping, which nothing else uses.
let pointer = unsafe {
libc::mmap(
@@ -79,6 +80,18 @@ impl Pages {
0,
)
};
#[cfg(windows)]
// SAFETY: a new allocation of its own, at an address the system picks.
let pointer = unsafe {
windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
BYTES as usize,
windows_sys::Win32::System::Memory::MEM_RESERVE
| windows_sys::Win32::System::Memory::MEM_COMMIT,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
)
};
#[cfg(unix)]
if pointer == libc::MAP_FAILED {
return Err("mmap failed".into());
}
@@ -89,7 +102,19 @@ impl Pages {
impl Drop for Pages {
fn drop(&mut self) {
// SAFETY: the mapping `new` made; every buffer over it went before it.
unsafe { libc::munmap(self.0.as_ptr().cast(), BYTES as usize) };
#[cfg(unix)]
unsafe {
libc::munmap(self.0.as_ptr().cast(), BYTES as usize)
};
#[cfg(windows)]
// SAFETY: as above; a release frees the allocation whole, from its base.
unsafe {
windows_sys::Win32::System::Memory::VirtualFree(
self.0.as_ptr().cast(),
0,
windows_sys::Win32::System::Memory::MEM_RELEASE,
)
};
}
}
@@ -56,6 +56,7 @@ struct Pages(NonNull<u8>, u64);
impl Pages {
fn new(bytes: u64) -> Result<Pages> {
#[cfg(unix)]
// SAFETY: a new anonymous mapping, which nothing else uses.
let pointer = unsafe {
libc::mmap(
@@ -67,6 +68,18 @@ impl Pages {
0,
)
};
#[cfg(windows)]
// SAFETY: a new allocation of its own, at an address the system picks.
let pointer = unsafe {
windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
bytes as usize,
windows_sys::Win32::System::Memory::MEM_RESERVE
| windows_sys::Win32::System::Memory::MEM_COMMIT,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
)
};
#[cfg(unix)]
if pointer == libc::MAP_FAILED {
return Err("mmap failed".into());
}
@@ -103,7 +116,19 @@ impl Pages {
impl Drop for Pages {
fn drop(&mut self) {
// SAFETY: the mapping `new` made; every buffer over it went before it.
unsafe { libc::munmap(self.0.as_ptr().cast(), self.1 as usize) };
#[cfg(unix)]
unsafe {
libc::munmap(self.0.as_ptr().cast(), self.1 as usize)
};
#[cfg(windows)]
// SAFETY: as above; a release frees the allocation whole, from its base.
unsafe {
windows_sys::Win32::System::Memory::VirtualFree(
self.0.as_ptr().cast(),
0,
windows_sys::Win32::System::Memory::MEM_RELEASE,
)
};
}
}
@@ -274,6 +274,7 @@ struct Slot {
}
/// The calling thread's CPU time in nanoseconds.
#[cfg(unix)]
fn thread_ns() -> u64 {
let mut at = libc::timespec {
tv_sec: 0,
@@ -285,6 +286,21 @@ fn thread_ns() -> u64 {
at.tv_sec as u64 * 1_000_000_000 + at.tv_nsec as u64
}
/// The calling thread's CPU time in nanoseconds: its kernel and user times (`GetThreadTimes`),
/// in 100 ns units.
#[cfg(windows)]
fn thread_ns() -> u64 {
use windows_sys::Win32::Foundation::FILETIME;
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes};
let mut times = [FILETIME::default(); 4];
let [created, exited, kernel, user] = &mut times;
// SAFETY: the calling thread's pseudo-handle, and four `FILETIME`s for the call to fill.
let read = unsafe { GetThreadTimes(GetCurrentThread(), created, exited, kernel, user) };
assert_ne!(read, 0, "GetThreadTimes");
let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
(ticks(kernel) + ticks(user)) * 100
}
/// The CPU time of a run's phases, in nanoseconds a pass, and of the begins inside the record
/// (`--begins`; 0 where untimed).
#[derive(Clone, Copy, Default)]
@@ -114,6 +114,7 @@ struct Pages(NonNull<u8>);
impl Pages {
fn new() -> common::Result<Pages> {
#[cfg(unix)]
// SAFETY: a new anonymous mapping, which nothing else uses.
let pointer = unsafe {
libc::mmap(
@@ -125,6 +126,18 @@ impl Pages {
0,
)
};
#[cfg(windows)]
// SAFETY: a new allocation of its own, at an address the system picks.
let pointer = unsafe {
windows_sys::Win32::System::Memory::VirtualAlloc(
std::ptr::null(),
BYTES as usize,
windows_sys::Win32::System::Memory::MEM_RESERVE
| windows_sys::Win32::System::Memory::MEM_COMMIT,
windows_sys::Win32::System::Memory::PAGE_READWRITE,
)
};
#[cfg(unix)]
if pointer == libc::MAP_FAILED {
return Err("mmap failed".into());
}
@@ -132,6 +145,7 @@ impl Pages {
}
/// Let the process only read them from now on.
#[cfg(unix)]
fn read_only(&self) -> common::Result<()> {
// SAFETY: the mapping `new` made, whole.
let done =
@@ -141,12 +155,44 @@ impl Pages {
_ => Err("mprotect failed".into()),
}
}
/// Let the process only read them from now on (`VirtualProtect`).
#[cfg(windows)]
fn read_only(&self) -> common::Result<()> {
use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_READONLY};
let mut old = 0;
// SAFETY: the allocation `new` made, whole, and `old` for the call to fill.
let done = unsafe {
VirtualProtect(
self.0.as_ptr().cast(),
BYTES as usize,
PAGE_READONLY,
&mut old,
)
};
match done {
0 => Err("VirtualProtect failed".into()),
_ => Ok(()),
}
}
}
impl Drop for Pages {
fn drop(&mut self) {
// SAFETY: the mapping `new` made; every buffer over it went before it.
unsafe { libc::munmap(self.0.as_ptr().cast(), BYTES as usize) };
#[cfg(unix)]
unsafe {
libc::munmap(self.0.as_ptr().cast(), BYTES as usize)
};
#[cfg(windows)]
// SAFETY: as above; a release frees the allocation whole, from its base.
unsafe {
windows_sys::Win32::System::Memory::VirtualFree(
self.0.as_ptr().cast(),
0,
windows_sys::Win32::System::Memory::MEM_RELEASE,
)
};
}
}
@@ -5,12 +5,13 @@
//! cargo run --release -p metal2vulkan-runtime --example queue_share -- <mode> \
//! [--policy adaptive|per-queue] [--seconds S] [--dispatches N] [--unshared] \
//! [--threads T --in-flight F [--one-vk-queue]] [--long-ms L] [--period-ms P] \
//! [--isolation bounded|off]
//! [--isolation bounded|off] [--turns fair|commit-order] [--fixture PATH]
//! ```
//!
//! Every command buffer is one of two kinds. A *draw*: a render pass over a 512x512 `RGBA8Unorm`
//! texture, cleared and one triangle drawn (`colored_vertex` and `colored_fragment` of the
//! repository's owned fixture `runtime_examples.metal`, assembled by `llvm-as` on `PATH`). A *long*
//! repository's owned fixture `runtime_examples.metal`, assembled by `llvm-as` on `PATH` from its
//! `.ll`, the repository's or `--fixture`'s, for a binary carried to another tree). A *long*
//! one: `--dispatches` dispatches of `scale_and_offset` over one buffer, sized as the run starts
//! so the command buffer's GPU time is `--long-ms` (30 ms by default). Latencies are a command
//! buffer's `commit` to the start of its completed handler, on the host's clock.
@@ -29,7 +30,9 @@
//! application's long command buffers a second, and the device's counts of command buffers that
//! waited behind another queue's batch (`WorkCounts::command_buffers_behind_other_queues` and
//! kin). `--unshared` makes the compositor's queue with `new_command_queue_unshared`;
//! `--isolation` sets `UnsharedIsolationPolicy` (`bounded`, the default, or `off`). The
//! `--isolation` sets `UnsharedIsolationPolicy` (`bounded`, the default, or `off`), and
//! `--turns` sets `QueueTurnPolicy` (`fair`, the default, or `commit-order`): without
//! `--unshared`, the compositor's plain queue and the application's take turns. The
//! application's GPU-busy share is its command buffers' GPU time over the span from its first
//! one's start to its last one's end; the GPU's idle share, that span less every command
//! buffer's GPU time, either queue's.
@@ -66,7 +69,9 @@
//! consumer that does so does not share `VkQueue`s. The compositor's latencies, the most queues
//! live at once, and the device's counts of command buffers that waited behind another queue's.
use metal2vulkan::device::{DevicePolicy, QueueSharingPolicy, UnsharedIsolationPolicy};
use metal2vulkan::device::{
DevicePolicy, QueueSharingPolicy, QueueTurnPolicy, UnsharedIsolationPolicy,
};
use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan_runtime::{
@@ -96,6 +101,7 @@ struct Options {
mode: String,
policy: QueueSharingPolicy,
isolation: UnsharedIsolationPolicy,
turns: QueueTurnPolicy,
seconds: f64,
dispatches: u64,
unshared: bool,
@@ -112,6 +118,8 @@ struct Options {
churn: usize,
/// The device answers GPU times from the host (`DeviceOptions::gpu_times_from_host`).
untimed: bool,
/// The fixture's LLVM text: the repository's where `None`.
fixture: Option<PathBuf>,
}
fn options() -> Options {
@@ -120,6 +128,7 @@ fn options() -> Options {
mode: args.next().unwrap_or_else(|| "isolation".to_owned()),
policy: QueueSharingPolicy::Adaptive,
isolation: UnsharedIsolationPolicy::Bounded,
turns: QueueTurnPolicy::Fair,
seconds: 2.0,
dispatches: 300,
unshared: false,
@@ -130,6 +139,7 @@ fn options() -> Options {
period: Duration::from_millis(16),
churn: 340,
untimed: false,
fixture: None,
};
while let Some(arg) = args.next() {
let mut value = || args.next().unwrap_or_else(|| panic!("{arg} needs a value"));
@@ -148,6 +158,13 @@ fn options() -> Options {
other => panic!("no isolation {other}"),
}
}
"--turns" => {
options.turns = match value().as_str() {
"fair" => QueueTurnPolicy::Fair,
"commit-order" => QueueTurnPolicy::CommitOrder,
other => panic!("no turns {other}"),
}
}
"--seconds" => options.seconds = value().parse().unwrap(),
"--dispatches" => options.dispatches = value().parse().unwrap(),
"--unshared" => options.unshared = true,
@@ -156,6 +173,7 @@ fn options() -> Options {
"--one-vk-queue" => options.one_vk_queue = true,
"--churn" => options.churn = value().parse().unwrap(),
"--untimed" => options.untimed = true,
"--fixture" => options.fixture = Some(PathBuf::from(value())),
"--long-ms" => {
options.long = Duration::from_secs_f64(value().parse::<f64>().unwrap() / 1e3)
}
@@ -196,7 +214,8 @@ impl Kit {
options.isolation,
device.queue_switch_check_report()
);
let library = metal2vulkan::library::Library::from_air(&fixture_bitcode()).unwrap();
let bitcode = fixture_bitcode(options.fixture.as_deref());
let library = metal2vulkan::library::Library::from_air(&bitcode).unwrap();
let library = device.new_library_with_compile_library(library);
let vertex = library.new_function_with_name("colored_vertex").unwrap();
let fragment = library.new_function_with_name("colored_fragment").unwrap();
@@ -352,21 +371,27 @@ impl Kit {
}
}
/// The system default device, of the default policy but for `queue_sharing` and
/// `unshared_isolation`, as `options` say.
/// The system default device, of the default policy but for `queue_sharing`,
/// `unshared_isolation` and `queue_turns`, as `options` say.
fn device(options: &Options) -> Device {
let mut device = DeviceOptions::default();
device.policy = DevicePolicy::UNTRUSTED;
device.policy.queue_sharing = options.policy;
device.policy.unshared_isolation = options.isolation;
device.policy.queue_turns = options.turns;
device.gpu_times_from_host = options.untimed;
Device::system_default_with(&device).unwrap()
}
/// The owned fixture's LLVM text, assembled to AIR bitcode by `llvm-as`.
fn fixture_bitcode() -> Vec<u8> {
let ll = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll");
/// The owned fixture's LLVM text, at `fixture` where given, assembled to AIR bitcode by `llvm-as`.
fn fixture_bitcode(fixture: Option<&std::path::Path>) -> Vec<u8> {
let ll = fixture.map_or_else(
|| {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll")
},
PathBuf::from,
);
let output = Command::new("llvm-as")
.arg("-o")
.arg("-")
@@ -594,9 +619,10 @@ fn frames(kit: &Arc<Kit>, options: &Options) {
let app_mean = app_spans.iter().sum::<f64>() / app_spans.len().max(1) as f64;
let submissions = c.queue_submissions - before.queue_submissions;
println!(
"frames (policy {:?}, isolation {:?}, compositor {} every {:?}, application {} in flight of {:.1} ms): compositor {}, {over_16} over 16 ms; application {:.2} long command buffers/s ({:.2} ms of GPU time each), GPU-busy {:.1}%; GPU idle {:.2}%; {:.0} kernel submissions/s; {} looks held a head for isolation",
"frames (policy {:?}, isolation {:?}, turns {:?}, compositor {} every {:?}, application {} in flight of {:.1} ms): compositor {}, {over_16} over 16 ms; application {:.2} long command buffers/s ({:.2} ms of GPU time each), GPU-busy {:.1}%; GPU idle {:.2}%; {:.0} kernel submissions/s; {} looks held a head for isolation, {} for its turn, {} let go on an idle turn",
options.policy,
options.isolation,
options.turns,
if options.unshared { "unshared" } else { "shared" },
options.period,
options.in_flight,
@@ -608,6 +634,8 @@ fn frames(kit: &Arc<Kit>, options: &Options) {
gpu_idle * 100.0,
submissions as f64 / elapsed,
c.heads_held_for_unshared_isolation - before.heads_held_for_unshared_isolation,
c.heads_held_for_queue_turns - before.heads_held_for_queue_turns,
c.heads_let_go_turn_idle - before.heads_let_go_turn_idle,
);
println!(
" behind other queues: {} ({} over 16 ms, {} over 33 ms, longest {:.1} ms); unshared {} ({} over 16 ms, {} over 33 ms, longest {:.1} ms); unshared waits over 16 ms: {:.2} batches ahead on average, at most {}, longest run {:.1} ms on average, {} behind one run over 16 ms",
@@ -387,6 +387,7 @@ fn cpu_by_group() -> Vec<(String, u64)> {
return groups;
}
// The process's CPU less this thread's.
#[cfg(unix)]
// SAFETY: plain calls with out-parameters of the right types.
let (process, own) = unsafe {
let mut usage: libc::rusage = std::mem::zeroed();
@@ -403,12 +404,15 @@ fn cpu_by_group() -> Vec<(String, u64)> {
spec.tv_sec as u64 * 1_000_000_000 + spec.tv_nsec as u64,
)
};
#[cfg(windows)]
let (process, own) = (process_cpu_nanos(), thread_cpu_nanos());
add("committer".to_owned(), own);
add("all-but-committer".to_owned(), process.saturating_sub(own));
groups
}
/// This thread's CPU so far, in nanoseconds.
#[cfg(unix)]
fn thread_cpu_nanos() -> u64 {
// SAFETY: a plain call with an out-parameter of the right type.
let spec = unsafe {
@@ -419,6 +423,36 @@ fn thread_cpu_nanos() -> u64 {
spec.tv_sec as u64 * 1_000_000_000 + spec.tv_nsec as u64
}
/// This thread's CPU so far, in nanoseconds: its kernel and user times (`GetThreadTimes`), in
/// 100 ns units.
#[cfg(windows)]
fn thread_cpu_nanos() -> u64 {
use windows_sys::Win32::Foundation::FILETIME;
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes};
let mut times = [FILETIME::default(); 4];
let [created, exited, kernel, user] = &mut times;
// SAFETY: the calling thread's pseudo-handle, and four `FILETIME`s for the call to fill.
let read = unsafe { GetThreadTimes(GetCurrentThread(), created, exited, kernel, user) };
assert_ne!(read, 0, "GetThreadTimes");
let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
(ticks(kernel) + ticks(user)) * 100
}
/// The process's CPU so far, every thread's, in nanoseconds: its kernel and user times
/// (`GetProcessTimes`), in 100 ns units.
#[cfg(windows)]
fn process_cpu_nanos() -> u64 {
use windows_sys::Win32::Foundation::FILETIME;
use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes};
let mut times = [FILETIME::default(); 4];
let [created, exited, kernel, user] = &mut times;
// SAFETY: this process's pseudo-handle, and four `FILETIME`s for the call to fill.
let read = unsafe { GetProcessTimes(GetCurrentProcess(), created, exited, kernel, user) };
assert_ne!(read, 0, "GetProcessTimes");
let ticks = |t: &FILETIME| (u64::from(t.dwHighDateTime) << 32) | u64::from(t.dwLowDateTime);
(ticks(kernel) + ticks(user)) * 100
}
/// The CPU each group spent between `before` and `after`, per command buffer, in microseconds.
fn print_cpu(label: &str, before: &[(String, u64)], after: &[(String, u64)], count: usize) {
let mut line = format!("{label}:");
+79 -4
View File
@@ -35,7 +35,16 @@
//! uses is checked against every write before it before the pass records. The images noted
//! apart stay noted in the new one, whose later writes their draws still follow. One whose
//! first instance records inline joins no group (`encoder_fold.rs`): its draws record from its
//! first on, before its later calls are known.
//! first on, before its later calls are known. It may continue the render pass instance the
//! encoder before it left open in the group's tail (`encoder_fold.rs`'s **Continued passes**),
//! which records what its pass records after what the group's encoders wrote there: it does so
//! only where no memory its draws use (noted apart), nor its attachments', nor that of the
//! copies and steps before its later instances, meets the group's writes of bytes
//! ([`AliasWrites::continues`]), and then notes those writes as its own, as a joining encoder
//! does; else its pass begins its own instance in a `VkCommandBuffer` of its own, counted as
//! a split. Its uses of bytes count there with its images': a texture whose image aliases a
//! buffer's bytes names them as the buffer's (`Texture::image_use`), which no use tells from a
//! use through the buffer.
//! - **Scope.** The measured direction alone: a use through an image after a write through a
//! buffer. A use through a buffer after a write through an image is not measured and takes no
//! split. A render pass's draws record inside its pass, where no `VkCommandBuffer` ends; what
@@ -95,6 +104,29 @@ impl Noted {
})
}
/// Whether a range of `other` meets a noted range: none where either noted nothing.
fn meets_any(&self, other: &Noted) -> bool {
let empty = |noted: &Noted| !noted.every && noted.ranges.is_empty();
if empty(self) || empty(other) {
return false;
}
self.every
|| other.every
|| (other.ranges.iter()).any(|(key, bytes)| self.meets(*key, bytes))
}
/// Note every range of `other`.
fn join(&mut self, other: Noted) {
if other.every {
self.every = true;
self.ranges.clear();
return;
}
for (key, bytes) in other.ranges {
self.add(key, bytes);
}
}
fn clear(&mut self) {
self.ranges.clear();
self.every = false;
@@ -112,6 +144,10 @@ pub(crate) struct AliasWrites {
/// later command there executes, use ([`noted_apart`](Self::noted_apart)): kept from one
/// `VkCommandBuffer` to the next, as those commands run after what either records before them.
apart: Noted,
/// The bytes of the keys the commands noted apart use through their bytes
/// ([`noted_apart`](Self::noted_apart)): what a texture whose image aliases a buffer's bytes
/// names of them too (`Texture::image_use`), which [`continues`](Self::continues) checks.
bytes_apart: Noted,
/// A command noted apart uses an image whose memory meets a noted write, or a write noted
/// since meets an image one uses: the next command recorded into the `VkCommandBuffer` goes
/// in a new one.
@@ -148,9 +184,14 @@ impl AliasWrites {
/// ([`meets`](Self::meets)).
pub(crate) fn noted_apart(&mut self, uses: &[Use<ResourceKey>]) {
for used in uses {
if let Some(bytes) = used.range.image_bytes() {
self.owed |= self.writes.meets(used.key, &bytes);
self.apart.add(used.key, bytes);
match &used.range {
UseRange::Bytes(bytes) => self.bytes_apart.add(used.key, bytes.clone()),
range => {
if let Some(bytes) = range.image_bytes() {
self.owed |= self.writes.meets(used.key, &bytes);
self.apart.add(used.key, bytes);
}
}
}
}
}
@@ -165,6 +206,40 @@ impl AliasWrites {
})
}
/// Whether the encoder's pass may continue the render pass instance the tail of the group
/// `order` describes holds open (`encoder_fold.rs`'s **Continued passes**), which puts what
/// its pass records into that `VkCommandBuffer`, after what the group's encoders wrote there,
/// its order's writes of bytes: where no memory its commands noted apart use (its draws',
/// [`noted_apart`](Self::noted_apart)) nor that of one of `uses` (what else its pass records
/// there: its attachments, and the copies and steps before its later instances) meets them.
/// Their uses of bytes count with their images': a texture whose image aliases a buffer's
/// bytes names them as the buffer's (`Texture::image_use`), as a use through the buffer does,
/// so either may be an image's. Then those writes are noted as written into the
/// `VkCommandBuffer` the encoder records into, the tail, as for an encoder that joined the
/// group ([`joining`](Self::joining)), so a command it records there after its pass that uses
/// an image over them goes in a new one; else nothing changes, and its pass begins its own
/// instance in a `VkCommandBuffer` of its own.
pub(crate) fn continues(
&mut self,
order: &FoldOrder<ResourceKey>,
uses: &[Use<ResourceKey>],
) -> bool {
let group = AliasWrites::joining(Some(order)).writes;
let meets = group.meets_any(&self.apart)
|| group.meets_any(&self.bytes_apart)
|| (uses.iter()).any(|used| {
let bytes = match &used.range {
UseRange::Bytes(bytes) => Some(bytes.clone()),
range => range.image_bytes(),
};
bytes.is_some_and(|bytes| group.meets(used.key, &bytes))
});
if !meets {
self.writes.join(group);
}
!meets
}
/// The encoder went on in a new `VkCommandBuffer`: no command wrote anything there yet, and
/// nothing is owed. The images noted apart stay: their commands run after what the new one
/// records before them.
+148 -58
View File
@@ -53,7 +53,10 @@ use super::tracker::{Access, Use};
use super::upload::Upload;
use super::work_counts::{Counting, ReshapedBy};
use ash::vk;
use metal2vulkan::bind::{BindState, BoundBuffer, BoundSampler, BoundTexture, StageTable};
use metal2vulkan::bind::{
BindState, BoundBuffer, BoundSampler, BoundTexture, BufferRanges, StageTable,
};
use metal2vulkan::device::DriverWorkaround;
use metal2vulkan::pipeline::{
BufferKind, PipelineInterface, RenderPipeline, SlotClass, SlotInterface, SlotRef, Stage,
};
@@ -91,11 +94,23 @@ const VIEW_STAGES: [Stage; 5] = [
/// bound at offsets that move takes one shape and one pipeline, its view read at its residual
/// (exact at any offset), not a shape and a pipeline for each in turn, whose draws would each
/// settle and switch pipelines on the encoding thread.
///
/// On a profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload` it keeps a second
/// set alike, the slots whose bind offset class tells offset 0 apart
/// (`StageTable::zero_offset_views`): at first those its functions read through a storage view
/// (`PipelineInterface::storage_view_buffers`), which a command bound at offset 0 reads at its bind
/// offset alone; a slot a command binds at another offset is left out from then on. Elsewhere that
/// set is empty, and every shape and plan is as without it.
pub(crate) struct AtBindViews {
/// Each stage's of [`VIEW_STAGES`], bit `i` for buffer index `i`.
slots: [AtomicU64; VIEW_STAGES.len()],
/// Each stage's of [`VIEW_STAGES`] that tell offset 0 apart, bit `i` for buffer index `i`.
zero_slots: [AtomicU64; VIEW_STAGES.len()],
/// The device's view base alignment (`BindState::view_base_alignment_of`).
alignment: u32,
/// The device's buffer range limits (`BufferRanges::of`), under which its states' tables
/// class their buffers' lengths (`StageTable::buffer_ranges`).
ranges: BufferRanges,
/// Whether the device reads every uniform view at its residual
/// (`pipeline::reads_views_at_bind`), which a bind state states
/// (`BindState::uniform_views_at_residual`).
@@ -108,18 +123,30 @@ impl AtBindViews {
/// The slots `interface`'s functions read through a uniform view, under the view base
/// alignment of `device`: on every device, so a command's shape and its plan are the ones the
/// translator makes of its binds there. On a device that reads every uniform view at its
/// residual (`pipeline::reads_views_at_bind`) only the key the plan gives takes its residual
/// form (`RenderVariant::plan`, `Variant::keyed_regions`). The state's bind state holds the
/// slots `read` holds.
/// residual (`pipeline::reads_views_at_bind`) only the key the plan gives takes its uniform
/// views' residual form (`RenderVariant::plan`, `Variant::keyed_regions`). The slots it reads
/// through a storage view tell offset 0 apart where the profile of `device` takes
/// `DriverWorkaround::PushReadsLengthenThreadPayload`, the one profile whose modules declare
/// their key (`lower::access`), which the plan keeps; none elsewhere. The state's bind state
/// holds the slots `read` holds.
pub(crate) fn new(
device: &Device,
interface: &PipelineInterface,
read: ReadSlots,
) -> AtBindViews {
let limits = device.compile_device().profile().limits();
let profile = device.compile_device().profile();
let limits = profile.limits();
let storage_at_bind =
(profile.workarounds()).contains(&DriverWorkaround::PushReadsLengthenThreadPayload);
let storage = |stage| match storage_at_bind {
true => interface.storage_view_buffers(stage),
false => 0,
};
AtBindViews {
slots: VIEW_STAGES.map(|stage| AtomicU64::new(interface.uniform_view_buffers(stage))),
zero_slots: VIEW_STAGES.map(|stage| AtomicU64::new(storage(stage))),
alignment: BindState::view_base_alignment_of(limits),
ranges: BufferRanges::of(limits),
at_residual: !crate::pipeline::reads_views_at_bind(device),
read,
}
@@ -146,13 +173,16 @@ impl AtBindViews {
self.at_residual
}
/// Whether `stage`'s slots are `slots` (none for a stage it does not keep): a table read under
/// them that binds the same offsets leaves the same out ([`ArgumentTable::at_bind_views`]),
/// as it left out its own as it was read.
pub(super) fn holds(&self, stage: Stage, slots: u64) -> bool {
self.of(stage)
.map_or(0, |kept| kept.load(Ordering::Relaxed))
== slots
/// Whether `stage`'s slots of both sets are those `table` holds (none for a stage it does not
/// keep), and its buffer range limits the device's: a table read under them that binds the
/// same offsets leaves the same out ([`ArgumentTable::at_bind_views`],
/// [`ArgumentTable::zero_offset_views`]), as it left out its own as it was read, and classes
/// its buffers' lengths alike.
pub(super) fn holds(&self, stage: Stage, table: &StageTable) -> bool {
let now = |slots: Option<&AtomicU64>| slots.map_or(0, |s| s.load(Ordering::Relaxed));
now(self.of(stage)) == table.at_bind_views
&& now(self.zero_of(stage)) == table.zero_offset_views
&& table.buffer_ranges == self.ranges
}
/// `stage`'s slots, none for a stage it does not keep.
@@ -160,6 +190,12 @@ impl AtBindViews {
let at = VIEW_STAGES.iter().position(|s| *s == stage)?;
Some(&self.slots[at])
}
/// `stage`'s slots that tell offset 0 apart, none for a stage it does not keep.
fn zero_of(&self, stage: Stage) -> Option<&AtomicU64> {
let at = VIEW_STAGES.iter().position(|s| *s == stage)?;
Some(&self.zero_slots[at])
}
}
/// The render stages whose slots [`ReadSlots`] tells apart, in its order.
@@ -1482,7 +1518,9 @@ impl ArgumentTable {
/// stops the command (an M3 Max and an M4), and so is a table bound where it reads a buffer,
/// whose slot then reads zeros, as plain Metal's read (an M4). Its slots that tell the device's
/// view base alignment apart are those of `views`, the state's, as
/// [`at_bind_views`](Self::at_bind_views) leaves them.
/// [`at_bind_views`](Self::at_bind_views) leaves them, its slots that tell offset 0 apart
/// as [`zero_offset_views`](Self::zero_offset_views) leaves them, and its buffers' lengths
/// classed under the device's buffer range limits, the state's `views` hold.
pub(super) fn stage_table_reading(
&self,
stage: Stage,
@@ -1491,6 +1529,8 @@ impl ArgumentTable {
) -> StageTable {
let mut table = self.stage_table();
table.at_bind_views = self.at_bind_views(stage, views);
table.zero_offset_views = self.zero_offset_views(stage, views);
table.buffer_ranges = views.ranges;
let read = |class, index| views.read.reads(stage, class, index);
table
.buffers
@@ -1509,21 +1549,35 @@ impl ArgumentTable {
/// each that binds a buffer here at an offset the alignment does not divide left out, now and
/// from then on ([`AtBindViews`]). Inline bytes leave none out.
fn at_bind_views(&self, stage: Stage, views: &AtBindViews) -> u64 {
let Some(kept) = views.of(stage) else {
let alignment = u64::from(views.alignment);
self.views_left(views.of(stage), |offset| {
alignment != 0 && !offset.is_multiple_of(alignment)
})
}
/// The slots of `stage` whose bind offset class tells offset 0 apart for a command binding
/// this table (`StageTable::zero_offset_views`): the state's `views` of it, each that binds a
/// buffer here at an offset other than 0 left out, now and from then on ([`AtBindViews`]).
/// Inline bytes leave none out.
fn zero_offset_views(&self, stage: Stage, views: &AtBindViews) -> u64 {
self.views_left(views.zero_of(stage), |offset| offset != 0)
}
/// The slots `kept` holds (none where it is `None`), each that binds a buffer here at an
/// offset `moved` holds of left out, in `kept` too.
fn views_left(&self, kept: Option<&AtomicU64>, moved: impl Fn(u64) -> bool) -> u64 {
let Some(kept) = kept else {
return 0;
};
let alignment = views.alignment;
let viewed = kept.load(Ordering::Relaxed);
let mut slots = viewed;
let mut left = viewed;
while left != 0 {
let index = left.trailing_zeros();
left &= left - 1;
let moved = alignment != 0
&& !self.bytes.contains_key(&index)
&& (self.buffers.get(&index))
.is_some_and(|(_, offset)| !offset.is_multiple_of(u64::from(alignment)));
if moved {
let out = !self.bytes.contains_key(&index)
&& (self.buffers.get(&index)).is_some_and(|(_, offset)| moved(*offset));
if out {
slots &= !(1 << index);
}
}
@@ -1569,10 +1623,15 @@ impl ArgumentTable {
reshape: &mut Reshape,
) {
let read = (stage, interface);
// The slots that tell the view base alignment apart first, which the buffers' shapes
// read.
// The slots that tell the view base alignment and offset 0 apart and the buffer range
// limits first, which the buffers' shapes read.
reshape.field(&mut kept.at_bind_views, self.at_bind_views(stage, views));
let alignment = views.alignment;
reshape.field(
&mut kept.zero_offset_views,
self.zero_offset_views(stage, views),
);
reshape.field(&mut kept.buffer_ranges, views.ranges);
let (alignment, ranges) = (views.alignment, views.ranges);
// The slots the state holds alone (`ReadSlots`).
let held = |class, index| views.read.reads(stage, class, index);
kept.buffers.retain(|&index, _| {
@@ -1595,7 +1654,7 @@ impl ArgumentTable {
if let Some(bound) = bound_buffer(buffer, *offset, stride) {
let a = kept.class_alignment(index, alignment);
reshape.slot(SlotClass::Buffer, &mut kept.buffers, index, bound, |b| {
b.shape(a)
b.shape(a, ranges)
});
}
}
@@ -1607,7 +1666,7 @@ impl ArgumentTable {
&mut kept.buffers,
index,
bound_bytes(bytes),
|b| b.shape(a),
|b| b.shape(a, ranges),
);
}
}
@@ -1691,8 +1750,12 @@ impl ArgumentTable {
let Some(changed) = self.changes.since(read) else {
return false;
};
// A buffer's shape reads these slots: where they changed, every buffer is read again.
if self.at_bind_views(stage, views) != kept.at_bind_views {
// A buffer's shape reads these slots and the buffer range limits: where they changed,
// every buffer is read again.
if self.at_bind_views(stage, views) != kept.at_bind_views
|| self.zero_offset_views(stage, views) != kept.zero_offset_views
|| views.ranges != kept.buffer_ranges
{
return false;
}
let alignment = views.alignment;
@@ -1783,7 +1846,7 @@ impl ArgumentTable {
(alignment, counts): (u32, Counting<'_>),
reshape: &mut Reshape,
) {
let a = kept.class_alignment(index, alignment);
let (a, ranges) = (kept.class_alignment(index, alignment), kept.buffer_ranges);
let held = (self.buffers.get(&index)).filter(|(buffer, offset)| *offset <= buffer.length());
let (Some((buffer, offset)), Some(slot)) = (held, kept.buffers.get_mut(&index)) else {
return self.refresh_buffer((kept, index), read, alignment, reshape);
@@ -1819,7 +1882,7 @@ impl ArgumentTable {
);
counts.bound_offset_moved();
reshape.replace_by(ReshapedBy::BufferOffset, slot, bound, |was, now| {
was.same_shape(now, a)
was.same_shape(now, a, ranges)
});
}
@@ -1843,20 +1906,20 @@ impl ArgumentTable {
}
return;
}
let a = kept.class_alignment(index, alignment);
let (a, ranges) = (kept.class_alignment(index, alignment), kept.buffer_ranges);
if let Some(bytes) = self.bytes.get(&index) {
reshape.slot(
SlotClass::Buffer,
&mut kept.buffers,
index,
bound_bytes(bytes),
|b| b.shape(a),
|b| b.shape(a, ranges),
);
} else if let Some((buffer, offset)) = self.buffers.get(&index) {
let stride = self.attribute_strides.get(&index).copied();
if let Some(bound) = bound_buffer(buffer, *offset, stride) {
reshape.slot(SlotClass::Buffer, &mut kept.buffers, index, bound, |b| {
b.shape(a)
b.shape(a, ranges)
});
}
}
@@ -1878,37 +1941,64 @@ impl ArgumentTable {
read: (Stage, &PipelineInterface),
(maps, views): (&SamplerMaps, &AtBindViews),
) {
// A call that raced a rebind on another thread may have kept what a reading now no longer
// finds; its hold tells it apart, and its encoder runs only encoded again
// (`rebind::call_may_have_raced`).
if crate::rebind::call_may_have_raced() {
return;
}
let (stage, _) = read;
const DIFFERS: &str = "a stage table brought in place that is not the table read whole";
// The slots that tell the view base alignment apart, which the buffers' shapes read: each
// binds no buffer here at an offset the alignment does not divide, and they hold every slot
// the state's views hold now. A slot leaves those for good, and another encoder of the
// state may leave one out after this table read them, so `kept` may hold more than a
// table read whole now would, never fewer.
let now = views
.of(stage)
.map_or(0, |slots| slots.load(Ordering::Relaxed));
assert!(
now & !kept.at_bind_views == 0,
"{DIFFERS}: {stage:?} tells the view base alignment apart at {:#x}, the state's views \
at {now:#x}",
kept.at_bind_views
);
let mut told = kept.at_bind_views;
while told != 0 {
let index = told.trailing_zeros();
told &= told - 1;
let moved = !self.bytes.contains_key(&index)
&& (self.buffers.get(&index)).is_some_and(|(_, offset)| {
views.alignment != 0 && !offset.is_multiple_of(u64::from(views.alignment))
});
// The slots that tell the view base alignment apart, and those that tell offset 0 apart,
// which the buffers' shapes read: each binds no buffer here at an offset the alignment
// does not divide, or other than 0, and they hold every slot the state's views hold now. A
// slot leaves those for good, and another encoder of the state may leave one out after
// this table read them, so `kept` may hold more than a table read whole now would, never
// fewer.
let alignment = u64::from(views.alignment);
let off_alignment = |offset: u64| alignment != 0 && !offset.is_multiple_of(alignment);
let off_zero = |offset: u64| offset != 0;
let sets: [(&str, u64, Option<&AtomicU64>, &dyn Fn(u64) -> bool); 2] = [
(
"the view base alignment",
kept.at_bind_views,
views.of(stage),
&off_alignment,
),
(
"offset 0",
kept.zero_offset_views,
views.zero_of(stage),
&off_zero,
),
];
for (what, told, slots, moved) in sets {
let now = slots.map_or(0, |slots| slots.load(Ordering::Relaxed));
assert!(
!moved,
"{DIFFERS}: {stage:?} buffer {index} tells the view base alignment {} apart at an \
offset it does not divide",
views.alignment
now & !told == 0,
"{DIFFERS}: {stage:?} tells {what} apart at {told:#x}, the state's views at \
{now:#x}"
);
let mut left = told;
while left != 0 {
let index = left.trailing_zeros();
left &= left - 1;
let out = !self.bytes.contains_key(&index)
&& (self.buffers.get(&index)).is_some_and(|(_, offset)| moved(*offset));
assert!(
!out,
"{DIFFERS}: {stage:?} buffer {index} tells {what} apart at an offset that \
leaves it out (view base alignment {alignment})"
);
}
}
assert!(
kept.buffer_ranges == views.ranges,
"{DIFFERS}: {stage:?} classes its buffers' lengths under {:?}, the device's limits \
are {:?}",
kept.buffer_ranges,
views.ranges
);
// A buffer slot as `stage_table_reading` reads it: inline bytes where they are bound,
// else the buffer within its length, and nothing where the function reads it unbound.
let held = |class, index| views.read.reads(stage, class, index);
+9 -14
View File
@@ -26,15 +26,20 @@
//! On those drivers ([`ends_order`]) the default form orders batches by their ends: every batch
//! ends with [`Barrier::to_all`], every write before every access of every later command of its
//! `VkQueue`, so the tracker plans no barrier after an access of an earlier batch there
//! ([`Tracker::by_ends`](crate::tracker::Tracker)), and a batch's start timestamp is written at the
//! bottom of the pipe ([`start_stage`]): once everything before it in submission order completed,
//! which is when such a driver starts it. A batch no longer needs a command buffer of barriers
//! ([`Tracker::by_ends`](crate::tracker::Tracker)). A batch's start timestamp, written at the top
//! of the pipe as on every driver (`gpu_time.rs`), is then written once everything before it in
//! submission order completed, which is when such a driver starts it: the earlier batch's
//! [`Barrier::to_all`] holds it, as "the second synchronization scope includes all commands that
//! occur later in submission order" (`vkCmdPipelineBarrier`), its destination stages all commands.
//! A start written at the bottom of the pipe there read late on RADV (Mesa 26.2.6) on an RX 7900
//! XTX and a Radeon 780M: in a traced compute benchmark's pass, a population of command buffers
//! read their start in the last tenth of their own kernel job, spans of 1 us on jobs of 4.5 to
//! 36.5 ms. A batch no longer needs a command buffer of barriers
//! for a dependency on the batch before it (on the UHD 770, with the consumer's frames over 520
//! host imports, 67.0 command buffers submitted a frame against 129.3 to 129.7), and runs as the
//! driver ran it before. Elsewhere, and under `BatchOrderPolicy::Exact`, the exact form.
use crate::tracker::Barrier;
use ash::vk;
use metal2vulkan::device::{BatchOrderPolicy, DevicePolicy};
use metal2vulkan::vk::DriverId;
@@ -61,13 +66,3 @@ pub(crate) fn end(by_ends: bool) -> Barrier {
false => Barrier::to_host(),
}
}
/// The stage a batch's start timestamp is written at where nothing is planned before it: the
/// top of the pipe, as its work begins, or, where batches are ordered `by_ends`, the bottom,
/// once everything before it completed.
pub(crate) fn start_stage(by_ends: bool) -> vk::PipelineStageFlags {
match by_ends {
true => vk::PipelineStageFlags::BOTTOM_OF_PIPE,
false => vk::PipelineStageFlags::TOP_OF_PIPE,
}
}
@@ -0,0 +1,163 @@
//! The device's begin-ahead thread: a settled spare command pool's primaries are begun here, for
//! the encoders of the command buffer that takes the pool next (`spares.rs`), off the thread that
//! completed the command buffer that gave the pool back.
//!
//! - **What is posted.** The first command pool of a command buffer that completed and ended
//! every command buffer its pools handed out, once its completed handlers ran, before its gate
//! opens (`command_buffer/mod.rs`, `command_buffer/gate.rs`): the completing thread posts the
//! pool and goes on, so neither the command buffer's waiters nor its queue's next transitions
//! wait for a begin, and a waiter's return comes after the post. On ANV a begin was 8 to 20 us
//! (`spares.rs`), which the completing thread spent before, one a command buffer, while the
//! queue's context was held, and only where no thread waited for the command buffer.
//! - **What it begins.** As many of the pool's primaries as encoders of the command buffer that
//! gave it back opened their own in it, one at least and `spares::AHEAD` at most, one at a time,
//! the pool out of the spares only while it begins one (`spares.rs`'s
//! `BeginTargets::begin_ahead`). A command buffer that takes the pool before the thread came
//! to it, or between two begins, takes it as it is: its encoders past those begun begin their
//! own, counted (`WorkCounts::encoder_primaries_begun_ahead_missed`).
//! - **Bounded.** One thread a device, started by its first post. At most [`QUEUE`] pools wait;
//! a pool posted while it waits waits once, and one that finds the queue full, the device's
//! teardown begun, or no thread, is begun by none: its command buffer's encoders begin their
//! own. Stopped and joined by the device's teardown, before the spares are released
//! ([`BeginAhead::stop`]).
//! - **Holds nothing of the device**: the spares' command pools, the device's functions, its
//! loader word and its counts (`spares.rs`'s `BeginTargets`), as the free thread does
//! (`free_thread.rs`). No release of the device's runs on it.
//! - **A section of the exit guard** for each begin (`exit_guard.rs`); once the process exits,
//! nothing more is begun and the thread ends.
//! - **At the user-interactive class** ([`exit_guard::spawn_user_interactive`]), as the handler
//! threads that began the primaries before: its begins race the next command buffer's take.
use crate::device::lock;
use crate::exit_guard;
use crate::spares::BeginTargets;
use ash::vk;
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::thread::JoinHandle;
/// The most pools that wait for the thread (the module docs).
pub(crate) const QUEUE: usize = 64;
/// A device's begin-ahead thread (the module docs).
#[derive(Default)]
pub(crate) struct BeginAhead {
shared: Arc<Shared>,
thread: Mutex<Option<JoinHandle<()>>>,
}
/// What the thread and the posters share.
#[derive(Default)]
struct Shared {
state: Mutex<State>,
/// A pool was posted, or the thread is asked to stop.
work: Condvar,
/// The crate's device tests' hold of each posted pool's begins as they start
/// (`tests/begin_ahead.rs`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
held: crate::freed_memory::held::Held,
/// A posted pool's begins ended, for the crate's device tests ([`BeginAhead::settle`]).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
idle: Condvar,
}
#[derive(Default)]
struct State {
queue: VecDeque<vk::CommandPool>,
/// The thread was started, or a start failed.
started: bool,
stopping: bool,
/// The thread makes a posted pool's begins, for the crate's device tests.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
running: bool,
}
impl BeginAhead {
/// Post the spare command pool `raw`, given back settled, for its primaries to be begun ahead
/// on the thread, started unless it runs, with what `targets` gives; nothing where the pool
/// waits already, the queue is full, the device's teardown began or the host starts no
/// thread (the module docs).
pub(crate) fn post(&self, raw: vk::CommandPool, targets: impl FnOnce() -> BeginTargets) {
let mut state = lock(&self.shared.state);
if state.stopping || state.queue.len() >= QUEUE || state.queue.contains(&raw) {
return;
}
if !state.started {
state.started = true;
let (shared, targets) = (Arc::clone(&self.shared), targets());
let builder = std::thread::Builder::new().name("metal2vulkan-begin-ahead".into());
match exit_guard::spawn_user_interactive(builder, move || run(&shared, &targets)) {
Ok(handle) => *lock(&self.thread) = Some(handle),
Err(_) => return,
}
}
if lock(&self.thread).is_none() {
return;
}
state.queue.push_back(raw);
drop(state);
self.shared.work.notify_one();
}
/// The device's teardown, before it releases the spares: no pool is posted from here on, the
/// thread ends once its begins in progress are done, joined; those still waiting are begun by
/// none.
pub(crate) fn stop(&self) {
lock(&self.shared.state).stopping = true;
self.shared.work.notify_all();
let handle = lock(&self.thread).take();
if let Some(handle) = handle {
let _ = handle.join();
}
}
/// The tests' hold of each posted pool's begins as they start.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn held(&self) -> &crate::freed_memory::held::Held {
&self.shared.held
}
/// Wait until no posted pool waits and the thread makes no begins, for the crate's device
/// tests: what the spares hold, and the counts of the begins, are then final for the command
/// buffers whose waits returned, as a waiter's return comes after its command buffer's post.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn settle(&self) {
let mut state = lock(&self.shared.state);
while state.running || !state.queue.is_empty() && lock(&self.thread).is_some() {
state = (self.shared.idle.wait(state)).unwrap_or_else(PoisonError::into_inner);
}
}
}
/// The thread's loop: each posted pool's begins in turn, until stopped or the process exits.
fn run(shared: &Shared, targets: &BeginTargets) {
loop {
let raw = {
let mut state = lock(&shared.state);
loop {
if state.stopping {
return;
}
if let Some(raw) = state.queue.pop_front() {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
{
state.running = true;
}
break raw;
}
state = (shared.work.wait(state)).unwrap_or_else(PoisonError::into_inner);
}
};
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
shared.held.pass();
if exit_guard::closed() {
return;
}
targets.begin_ahead(raw);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
{
lock(&shared.state).running = false;
shared.idle.notify_all();
}
}
}
+249 -20
View File
@@ -61,6 +61,8 @@ use super::device::lock;
use super::error::{internal, Error, RuntimeGap};
use super::function_table::{self, TableSnapshot, VisibleFunctionTable};
use super::heap_sets::{self, Keeper, SamplerTable, TextureTable, HEAP_SET};
#[cfg(debug_assertions)]
use super::kept_checks::KeptChecks;
use super::key_hash::KeyMap;
use super::render_pass::{PassLayout, Target};
use super::render_target;
@@ -69,19 +71,20 @@ use super::resource::ResourceKey;
use super::sampler::{HashedDesc, OwnedSampler, SamplerShared, SamplerState};
use super::texture::{Texture, TextureShared};
use super::tracker::{Access, Use, UseRange};
use super::uniform_texels::UniformTexels;
use super::upload::Upload;
use super::Device;
use ash::vk;
use metal2vulkan::bind::{
AccessClass, BindingPlan, BufferRange, DescriptorBytes, DescriptorRange, DescriptorWrite,
FunctionTableWords, HeapElements, HeapSource, ImageSource, ImageViewDesc, IndexBufferRef,
NeutralResource, PushConstantWrite, PushHole, ResourceUse, RootTable, SamplerDescriptor,
SamplerSource, UseTarget, ViewSetup, WriteSource,
AccessClass, BindingPlan, BufferExtent, BufferRange, DescriptorBytes, DescriptorRange,
DescriptorWrite, FunctionTableWords, HeapElements, HeapSource, ImageSource, ImageViewDesc,
IndexBufferRef, NeutralResource, PushConstantWrite, PushHole, ResourceUse, RootTable,
SamplerDescriptor, SamplerSource, UseTarget, ViewSetup, WriteSource,
};
use metal2vulkan::metal::format::writes_dropped;
use metal2vulkan::metal::sampler::{AddressModeMap, OpaqueBlackBorder, SamplerUse};
use metal2vulkan::pipeline::{
HandleClass, ImageAccess, SlotClass, SlotRef, Stage, StorageAttachmentView,
HandleClass, ImageAccess, SlotClass, SlotRef, Stage, StorageAttachmentView, Window,
};
use std::collections::BTreeSet;
use std::ops::{Deref, Range};
@@ -847,6 +850,9 @@ pub(super) struct Command<'a> {
/// they are among those.
pub(super) heap_tables: &'a [DescriptorBytes],
pub(super) descriptor_ranges: &'a [DescriptorRange],
/// The windows of its bound buffers' slots (`metal2vulkan::bind::BufferExtent`), which the
/// counts of uniform views by window read (`WorkCounts::uniform_buffers_bound_to_16k`).
pub(super) extents: &'a [BufferExtent],
/// Each stage's root table, by the stages its push hole names.
pub(super) root_tables: Vec<(metal2vulkan::vk::ShaderStageFlags, &'a RootTable)>,
/// Whether a function that reads one of them may write memory (stores or atomic updates,
@@ -958,9 +964,10 @@ fn dynamic_write(write: &mut Write, dynamic: &[u32], offsets: &mut [u32]) {
/// descriptor's sampler kept in `samplers` (emptied first) as [`bind_into`] keeps it, through
/// `memo` likewise. Its buffers' descriptors take nothing of the command buffer's state
/// ([`slot_descriptor`]), so it locks none. `Ok(false)` where a write of theirs is not at its
/// place among `writes` (a heap's, which skips writes), holds a keeper, or reads a changed slot
/// otherwise (a texel buffer, a YCbCr texture's planes, an argument sampler): the caller binds
/// whole.
/// place among `writes` (a heap's, which skips writes), holds a keeper, reads a changed slot
/// otherwise (a texel buffer, a YCbCr texture's planes, an argument sampler), or is a uniform
/// view's texel form of a changed or unbound slot, whose view its command buffer made for it
/// ([`written`]): the caller binds whole.
pub(super) fn rebind_into(
call: &'static str,
device: &Device,
@@ -1031,6 +1038,16 @@ pub(super) fn rebind_into(
{
return Ok(false)
}
// An unbound slot's uniform view in its texel form names a view of the zero buffer
// made for the write, which its command buffer holds ([`written`]), and a draw carried
// past the commit must name none: bound whole.
WriteSource::Neutral(
NeutralResource::ZeroBuffer { .. } | NeutralResource::Sink { .. },
) if vk::DescriptorType::from(planned.ty)
== vk::DescriptorType::UNIFORM_TEXEL_BUFFER =>
{
return Ok(false)
}
_ => continue,
};
let ty: vk::DescriptorType = planned.ty.into();
@@ -1038,11 +1055,19 @@ pub(super) fn rebind_into(
if place != (planned.set, planned.binding, planned.array_element) || write.held.is_some() {
return Ok(false);
}
// A changed slot's uniform view in its texel form takes a view made for its write, which
// the command buffer holds ([`written`]): bound whole.
if ty == vk::DescriptorType::UNIFORM_TEXEL_BUFFER {
return Ok(false);
}
let info = match buffer {
true => {
let spaces = memo.as_deref_mut().map(|memo| &mut memo.spaces);
match slot_descriptor(command, tables, planned, spaces)? {
Some(info) => Info::Buffer(info),
Some(info) => {
count_uniform_buffer(device, command, planned, ty);
Info::Buffer(info)
}
None => return Err(internal("a slot's buffer write of another source")),
}
}
@@ -1482,10 +1507,29 @@ fn written(
(WriteSource::HeapEntry { .. }, _) => {
return Err(internal("a heap entry outside the heap set"))
}
// A buffer slot's uniform view in its texel form (`DescriptorView::UniformTexel`): a view
// of the range its uniform buffer would bind, made for this write and held until the
// command buffer completed (`uniform_texels.rs`).
(
WriteSource::Buffer { .. }
| WriteSource::InlineBytes { .. }
| WriteSource::Neutral(NeutralResource::ZeroBuffer { .. } | NeutralResource::Sink { .. }),
vk::DescriptorType::UNIFORM_TEXEL_BUFFER,
) => {
let spaces = memo.as_deref_mut().map(|memo| &mut memo.spaces);
let range = descriptor(device, state, command, tables, (write, spaces))?;
let texels = UniformTexels::new(device, &range)?;
let view = texels.raw();
state.retain_own(texels);
device.shared().counts.thread().uniform_texels_bound();
Info::Texel(view)
}
(_, ty) => match ty {
vk::DescriptorType::UNIFORM_BUFFER | vk::DescriptorType::STORAGE_BUFFER => {
let spaces = memo.as_deref_mut().map(|memo| &mut memo.spaces);
Info::Buffer(descriptor(device, state, command, tables, (write, spaces))?)
let info = descriptor(device, state, command, tables, (write, spaces))?;
count_uniform_buffer(device, command, write, ty);
Info::Buffer(info)
}
vk::DescriptorType::UNIFORM_TEXEL_BUFFER | vk::DescriptorType::STORAGE_TEXEL_BUFFER => {
let storage = ty == vk::DescriptorType::STORAGE_TEXEL_BUFFER;
@@ -1852,8 +1896,9 @@ pub(super) unsafe fn write_sets(
/// - **No handle it holds names another object.** The set lies in its command buffer's pools,
/// which last until the command buffer completes; so do the objects its writes name, which a
/// command that recorded with them holds (its buffers, textures, views and samplers), the
/// command buffer's arena (uploads) or the device (neutrals). The memo lives with its encoder,
/// inside its command buffer's life.
/// command buffer's arena (uploads) or what it retained (a uniform view's texel buffer view,
/// made for its write: `uniform_texels.rs`), or the device (neutrals). The memo lives with its
/// encoder, inside its command buffer's life.
/// - **The writes compare by value** ([`SetWrite::same`], in order: each binding, element, type
/// and descriptor, a buffer's offset and range, an image's view, sampler and layout), so the set
/// is bound again only where every descriptor written is the one the command writes.
@@ -1893,6 +1938,145 @@ impl LastSetZero {
}
}
/// What a compute encoder's dispatches recorded at the compute bind point of the
/// `VkCommandBuffer` it records into, while it still holds there
/// (`EncoderCore::command_reaching_pushed`): the `VkPipeline` bound last, and set 0 as the
/// dispatches pushed it with a layout. A dispatch binds its first region's pipeline only where
/// another is bound, and pushes only the writes of its set 0 that differ from those set 0 holds
/// ([`carry`](Self::carry)), none where none differs, as a draw does in its secondary command
/// buffer (`render/bound.rs`). Exact, under Vulkan's rules:
///
/// - **Pushed descriptors last until overwritten.** `vkCmdPushDescriptorSet`: "Push descriptors
/// can be updated incrementally and cause shaders to use the updated descriptors for subsequent
/// bound pipeline commands with the pipeline type set by pipelineBindPoint until the descriptor
/// is overwritten, or else until the set is disturbed as described in Pipeline Layout
/// Compatibility. When the set is disturbed or push descriptors with a different descriptor set
/// layout are set, all push descriptors are undefined." So set 0 is held only as pushed with
/// the same `VkPipelineLayout` (one layout's set 0 is one set layout), of the same bindings and
/// elements in order; a dispatch of another layout forgets what was pushed
/// ([`records_with`](Self::records_with)), whatever it binds (a set 1 bound with a layout not
/// compatible for set 0 disturbs set 0), and so does a bind of set 0 from a set
/// ([`set_bound`](Self::set_bound)). Set 1 bound with the same layout disturbs no set 0, nor does
/// binding a pipeline (Pipeline Layout Compatibility: "When binding a descriptor set ... to set
/// number N, a previously bound descriptor set bound with lower index M than N is disturbed if
/// the pipeline layouts for set M and N are not compatible for set M. Otherwise, the bound
/// descriptor set in M is not disturbed.").
/// - **A pipeline stays bound** until another is bound at the same bind point.
/// - **Nothing else records there meanwhile.** It holds only while the dispatch records into the
/// `VkCommandBuffer` the encoder's last such dispatch recorded into and the encoder recorded
/// nothing else into it since ([`hold`](Self::hold): its count of recordings, bumped by every
/// command, barrier and copy run that takes the `VkCommandBuffer`, `EncoderCore::raw_recording`,
/// and by recorded gather runs), so no other command's pipeline, set or push at the compute bind
/// point (the runtime's own kernels, a flat dispatch's preprocess, which forgets it) comes
/// between; another `VkCommandBuffer` forgets it. Each encoder begins it empty, so one that
/// records on in the `VkCommandBuffer` of a group of encoders (`encoder_fold.rs`) takes nothing
/// the group's earlier encoders recorded there, and a dispatch recorded later into a segment of
/// its own (`pending_dispatch.rs`) pushes set 0 whole.
/// - **Where pushed descriptors go stale across a pipeline bind**
/// (`RuntimeDriverDefect::PushedDescriptorsStaleAfterPipelineBinds`), the push after a pipeline
/// bind carries at least one write (set 0's first where none changed), as a draw's does: the
/// dispatch binds its pipeline before it pushes.
#[derive(Default)]
pub(super) struct PushedSetZero {
raw: vk::CommandBuffer,
/// The encoder's count of recordings as the last dispatch that kept this recorded.
mark: u64,
pipeline: vk::Pipeline,
layout: vk::PipelineLayout,
/// Set 0's writes as pushed with `layout`: none where it holds no pushed set 0.
writes: Vec<SetWrite>,
/// The writes the last push carried, where it carried fewer than set 0's.
changed: Vec<SetWrite>,
/// A pipeline was bound since set 0's last push.
bound_since_push: bool,
}
impl PushedSetZero {
/// Forget what it held unless the command recording now records into `raw` with the
/// encoder's count of recordings at `mark`, one past the last dispatch's that kept it: that
/// dispatch's command's own taking of `raw` alone came between.
pub(super) fn hold(&mut self, raw: vk::CommandBuffer, mark: u64) {
if self.raw != raw || self.mark.checked_add(1) != Some(mark) {
self.forget();
}
}
/// What it holds now holds as recorded into `raw` at the encoder's count of recordings
/// `mark`.
pub(super) fn recorded(&mut self, raw: vk::CommandBuffer, mark: u64) {
(self.raw, self.mark) = (raw, mark);
}
/// Hold nothing: no pipeline and no pushed set 0 known.
pub(super) fn forget(&mut self) {
self.pipeline = vk::Pipeline::null();
self.set_bound();
self.bound_since_push = false;
}
/// Set 0 was bound from a set: no pushed set 0 held.
pub(super) fn set_bound(&mut self) {
self.layout = vk::PipelineLayout::null();
self.writes.clear();
}
/// A dispatch records its sets and push constants with `layout`: set 0 is held across
/// dispatches of one layout alone, so one of another forgets what was pushed, whatever it
/// binds or pushes.
pub(super) fn records_with(&mut self, layout: vk::PipelineLayout) {
if self.layout != layout {
self.set_bound();
}
}
/// Whether `pipeline` must be bound, another being bound or none known: it is bound from now.
pub(super) fn binds(&mut self, pipeline: vk::Pipeline) -> bool {
if self.pipeline == pipeline {
return false;
}
self.pipeline = pipeline;
self.bound_since_push = true;
true
}
/// The writes a push of set 0's `writes` with `layout` carries: where set 0 holds the same
/// bindings and elements pushed with `layout`, those that differ from what it holds, and
/// where `stale` and a pipeline was bound since the last push at least one (set 0's first
/// where none differs); else every one. Set 0 holds `writes` from now.
pub(super) fn carry<'a>(
&'a mut self,
layout: vk::PipelineLayout,
writes: &'a [SetWrite],
stale: bool,
) -> &'a [SetWrite] {
let renew = stale && self.bound_since_push;
self.bound_since_push = false;
let held = layout != vk::PipelineLayout::null()
&& self.layout == layout
&& !self.writes.is_empty()
&& self.writes.len() == writes.len()
&& (self.writes.iter().zip(writes))
.all(|(a, b)| (a.binding, a.element, a.ty) == (b.binding, b.element, b.ty));
if !held {
self.layout = layout;
self.writes.clear();
self.writes.extend_from_slice(writes);
return writes;
}
self.changed.clear();
for (old, new) in self.writes.iter_mut().zip(writes) {
if !old.same(new) {
*old = *new;
self.changed.push(*new);
}
}
if let (true, true, Some(&first)) = (renew, self.changed.is_empty(), writes.first()) {
self.changed.push(first);
}
&self.changed
}
}
/// The most sets 0 one generation of a [`SetCache`] keeps.
const SETS_KEPT: usize = 128;
@@ -1914,8 +2098,10 @@ const SETS_ROOM: usize = 8;
/// and only while the command buffer holds what its commands took strongly, which is until it
/// is committed (`command_buffer/mod.rs`): every object a kept set's writes name is held by the
/// command (its buffers, textures, views and samplers), the command buffer's arena (uploads) or
/// the device (neutrals), so no such object goes, nor can another take its handle, while its
/// sets are kept. A refused command's set is never kept. At the commit the holds go weak, so a
/// what it retained (a uniform view's texel buffer view, made for its write:
/// `uniform_texels.rs`), or the device (neutrals), so no such object goes, nor can another take
/// its handle, while its sets are kept. A view is made for one write alone, so no later
/// command finds a set that names one. A refused command's set is never kept. At the commit the holds go weak, so a
/// rebind may let the pages go, and the cache is shut there and keeps and serves nothing again
/// (`DescriptorArena::shut`): every command recorded from the commit on -- an encoder encoded
/// again at a rebind (`command_buffer/reencode.rs`), a host step's -- allocates and writes its
@@ -2096,12 +2282,17 @@ fn texel_descriptor(
let texels = texture
.texels()
.ok_or_else(|| internal("a texel buffer write of a texture with an image"))?;
let place = (write.set, write.binding, write.array_element);
let range = command
.descriptor_ranges
.iter()
.find(|r| (r.set, r.binding) == (write.set, write.binding))
.find(|r| (r.set, r.binding, r.element) == place)
.ok_or_else(|| internal("a texel buffer write without its range"))?
.range;
// A part of a texture buffer wider than one view holds (`bind::texel_parts`).
if write.array_element > 0 {
device.shared().counts.thread().texel_buffer_parts_bound();
}
texels.view(*format, storage, range)
}
WriteSource::Neutral(NeutralResource::TexelBuffer { format }) => {
@@ -2630,8 +2821,9 @@ fn unexpected(source: &WriteSource) -> Error {
/// The buffer descriptor of `write`.
/// Whether a buffer descriptor of `ty` is read-only to every shader that binds it: a uniform
/// buffer, whose block Vulkan and SPIR-V make read-only, so no store can reach it. A storage
/// buffer is not, whatever a particular shader does with it.
/// buffer, whose block Vulkan and SPIR-V make read-only, so no store can reach it, or a uniform
/// texel buffer (a uniform view's texel form), which a shader only fetches. A storage buffer is
/// not, whatever a particular shader does with it.
///
/// It decides which bindings may share the device's one neutral zero buffer (`neutral.rs`): a
/// writable binding keeps a region of its own, so nothing a shader stores is ever seen by another
@@ -2639,7 +2831,9 @@ fn unexpected(source: &WriteSource) -> Error {
fn read_only_buffer(ty: vk::DescriptorType) -> bool {
matches!(
ty,
vk::DescriptorType::UNIFORM_BUFFER | vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC
vk::DescriptorType::UNIFORM_BUFFER
| vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC
| vk::DescriptorType::UNIFORM_TEXEL_BUFFER
)
}
@@ -2663,6 +2857,28 @@ pub(super) fn binds_own_zeros(plan: &BindingPlan) -> bool {
})
}
/// Count `write`, a buffer write of type `ty` for `command`, where it is a bound buffer's uniform
/// view written as a uniform buffer: by its slot's window (`WorkCounts::uniform_buffers_bound_to_16k`).
fn count_uniform_buffer(
device: &Device,
command: &Command<'_>,
write: &DescriptorWrite,
ty: vk::DescriptorType,
) {
let (WriteSource::Buffer { slot }, vk::DescriptorType::UNIFORM_BUFFER) = (&write.source, ty)
else {
return;
};
let Some(extent) = command.extents.iter().find(|extent| extent.slot == *slot) else {
return;
};
let len = match extent.window {
Window::Bounded { len, .. } => Some(len),
_ => None,
};
device.shared().counts.thread().uniform_buffer_bound(len);
}
/// The range `command` plans for its buffer write at `key` (set and binding).
fn planned_range(command: &Command<'_>, key: (u32, u32)) -> Result<BufferRange, Error> {
(command.descriptor_ranges.iter())
@@ -3016,7 +3232,8 @@ pub(super) fn command_uses(
/// and stages the plan's, and its key and range the resource's own, which no call changes (a
/// resource's identity and length, a texture's levels and slices; `WorkCounts::resident_uses_made`
/// counts those made). Builds with debug assertions check those kept against the uses
/// [`command_uses`] makes whole.
/// [`command_uses`] makes whole, at their first uses after they were made and then at powers of
/// two (`kept_checks.rs`).
pub(super) fn command_uses_into(
call: &'static str,
(plan, command, tables): (&Arc<BindingPlan>, &Command<'_>, &Tables<'_>),
@@ -3025,7 +3242,8 @@ pub(super) fn command_uses_into(
) -> Result<(), Error> {
let kept = (&**plan, Some(plan), command, tables);
let keeps = uses_into(call, kept, (index, indirect), into)?;
if cfg!(debug_assertions) && keeps {
#[cfg(debug_assertions)]
if keeps && into.of.as_mut().is_some_and(|of| of.checks.due()) {
// Made whole over the last check's storage: a draw's allocations are bounded in builds
// with debug assertions too (`runtime_lane::frame_costs`). None past the thread's
// thread-locals' end (a program's exit handler, `this_thread.rs`).
@@ -3046,9 +3264,12 @@ pub(super) fn command_uses_into(
KEPT_RESIDENT_CHECKS.with(|checks| checks.set(checks.get() + 1));
}
}
#[cfg(not(debug_assertions))]
let _: bool = keeps;
Ok(())
}
#[cfg(debug_assertions)]
thread_local! {
/// The commands whose uses of what the encoder made resident this thread kept (none, where
/// their plan lists none) and checked against those made whole ([`command_uses_into`]), in builds with debug assertions.
@@ -3077,6 +3298,10 @@ struct ResidentOf {
/// Held in place, so a command that switches plan allocates nothing for them: one whose
/// plan lists other uses makes its uses again, and its own `ResidentOf`.
compared: [Option<(Weak<BindingPlan>, bool)>; COMPARED_PLANS],
/// The commands that kept them since they were made, in builds with debug assertions
/// (`kept_checks.rs`).
#[cfg(debug_assertions)]
checks: KeptChecks,
}
/// The most plans a [`ResidentOf`] keeps compared with its own: draws of one pipeline state whose
@@ -3151,6 +3376,8 @@ fn uses_into(
plan: Arc::downgrade(plan),
generation,
compared: Default::default(),
#[cfg(debug_assertions)]
checks: KeptChecks::default(),
});
// Kept from one command to the next alone, so the identity of those kept alone
// (none where there are none: `prefix` reads it only where there are some).
@@ -3889,6 +4116,8 @@ fn buffer_access(class: AccessClass) -> Result<(vk::AccessFlags2, vk::AccessFlag
match class {
AccessClass::Storage => Ok((A::SHADER_STORAGE_READ, A::SHADER_STORAGE_WRITE)),
AccessClass::Uniform => Ok((A::UNIFORM_READ, A::NONE)),
// A uniform view's texel form (`DescriptorView::UniformTexel`), a uniform texel buffer.
AccessClass::Sampled => Ok((A::SHADER_SAMPLED_READ, A::NONE)),
AccessClass::VertexInput => Ok((A::VERTEX_ATTRIBUTE_READ, A::NONE)),
AccessClass::Index => Ok((A::INDEX_READ, A::NONE)),
AccessClass::Indirect => Ok((A::INDIRECT_COMMAND_READ, A::NONE)),
@@ -11,6 +11,7 @@
//! image's other usages is valid.
use super::image_plan::{block_family, compatible, ImagePlan};
use super::pvrtc::holds_for_copies;
use super::view_plan::{ViewProblem, ViewRecord, ViewRefusal};
use ash::vk;
use metal2vulkan::bind::{ImageViewDesc, TextureFacts};
@@ -110,8 +111,10 @@ impl VkView {
/// (`Device::with_undeclared_usage`).
///
/// Refusals: where the image lacks the usage, the texture's usage lacking it too
/// (`NotImplemented(UndeclaredTextureUsage)`, the runtime's gap) or the device lacking the usage
/// for the format (`Unsupported{Format}`); a view format the image cannot take
/// (`NotImplemented(UndeclaredTextureUsage)`, the runtime's gap), the image being a carrier that
/// serves copies alone (`NotImplemented(Format)` naming the texture's format: a PVRTC, ETC2, EAC
/// or 4:2:2 texture without a decoded twin, `pvrtc.rs`) or the device lacking the usage for the
/// format (`Unsupported{Format}`); a view format the image cannot take
/// (`NotImplemented(TextureView)`); a swizzle on a storage image, whose view Vulkan cannot swizzle
/// (`NotImplemented(TextureSwizzle)`), but where the binding plan's function applies it
/// (`ImageViewDesc::shader_swizzle`: a swizzled texture or view at a storage slot, whose reads the
@@ -143,6 +146,13 @@ pub(super) fn binding_view(
Feature::UndeclaredTextureUsage,
)));
}
// A carrier serves copies alone (`pvrtc.rs`): a binding reaches it only where no decoded twin
// serves the texture's reads, which is the format's gap, not the view format's.
if !image.usage.contains(usage) && holds_for_copies(image) {
return Err(ViewRefusal::Unsupported(
Unsupported::not_implemented(Feature::Format).naming_format(record.pixel_format),
));
}
if !image.usage.contains(usage) {
return Err(ViewRefusal::Unsupported(Unsupported::needs(
Feature::Format,
+103 -23
View File
@@ -26,10 +26,11 @@
use super::blit_fill::FillTiles;
use super::buffer::Buffer;
use super::command_buffer::CommandBuffer;
use super::copy_run::CopyRun;
use super::degradation::Degradation;
use super::encoder::{EncoderCore, Replayed};
use super::encoder::{EncoderCore, HeldCore, Replayed};
use super::encoder_fold::Joining;
use super::error::{invalid, Error, Problem};
use super::error::{invalid, CopyQueueProblem, Error, Problem};
use super::fresh_unwritten::FreshRead;
use super::managed_copy::{AtCompletion, CopyBack, Staging, SyncTarget};
use super::managed_sync::{SyncCopy, Target};
@@ -177,6 +178,10 @@ pub struct BlitCommandEncoder {
/// The tiles its plain color fills cleared, which its later ones copy from again
/// (`blit_fill.rs`). An encoding again starts with none, so it clears them again.
fill_tiles: FillTiles,
/// Its buffer copies not yet recorded, which later copies between the same two buffers join
/// as one `vkCmdCopyBuffer` (`copy_run.rs`): recorded before its next other command, and at
/// its end.
run: Option<CopyRun>,
}
impl std::fmt::Debug for BlitCommandEncoder {
@@ -210,6 +215,7 @@ impl CommandBuffer {
log: Some(self.device().shared().scheduler.spare_logs().blit()),
aborts,
fill_tiles: FillTiles::default(),
run: None,
})
}
}
@@ -225,14 +231,19 @@ impl BlitCommandEncoder {
log: None,
aborts: None,
fill_tiles: FillTiles::default(),
run: None,
})
}
/// End an encoder made by [`replaying`](Self::replaying): what it recorded.
pub(super) fn finish_replay(self) -> Result<Replayed, Error> {
let BlitCommandEncoder {
mut core, pattern, ..
mut core,
pattern,
mut run,
..
} = self;
core.flush_copies(&mut run);
if let Some(pattern) = pattern {
core.retain(pattern);
}
@@ -249,11 +260,33 @@ impl BlitCommandEncoder {
call: impl FnOnce(&mut CallLog<BlitCall>) -> BlitCall,
run: impl FnOnce(&mut Self) -> Result<T, Error>,
) -> Result<T, Error> {
self.logged_after(true, call, run)
}
/// [`logged`](Self::logged), the encoder's run of buffer copies recorded first where
/// `flush` (`copy_run.rs`): every command but a buffer copy, which may join it.
fn logged_after<T>(
&mut self,
flush: bool,
call: impl FnOnce(&mut CallLog<BlitCall>) -> BlitCall,
run: impl FnOnce(&mut Self) -> Result<T, Error>,
) -> Result<T, Error> {
let _call = self.core.begin_call();
let _for = self.core.notices_for();
self.refuse_aborted()?;
if flush {
self.core.flush_copies(&mut self.run);
}
let copies = self.core.command_buffer().for_copies();
let at = match self.log.as_mut().filter(|log| !log.muted()) {
Some(log) => {
let call = call(log);
// A queue made for copies takes buffer copies and fills alone, refused before
// they are logged (an encoder made fresh logs every call it takes).
if let (true, Err(name)) = (copies, call.on_copy_engine()) {
let problem = Problem::CopyQueue(CopyQueueProblem::Command);
return Err(invalid(name, problem));
}
let extra = call.extra();
Some(log.push(call, extra))
}
@@ -279,6 +312,17 @@ impl BlitCommandEncoder {
}
}
/// Refuse `call` over `buffers` on a queue made for copies where the copy engine's family
/// does not share one of them: a buffer the caller made not concurrent with that family
/// (`Invalid`, `CopyQueueProblem::Buffer`, `Device::new_command_queue_for_copies`).
fn refuse_unshared(&self, call: &'static str, buffers: &[&Buffer]) -> Result<(), Error> {
let unshared = buffers.iter().any(|buffer| !buffer.copy_engine_shares());
match unshared && self.core.command_buffer().for_copies() {
true => Err(invalid(call, Problem::CopyQueue(CopyQueueProblem::Buffer))),
false => Ok(()),
}
}
/// Run `call`, a public call one of the encoder's own makes, unlogged: the call that makes
/// it is logged, and encoded again makes it again.
pub(super) fn unlogged<T>(&mut self, call: impl FnOnce(&mut Self) -> T) -> T {
@@ -351,6 +395,8 @@ impl BlitCommandEncoder {
(reads, covered): (&[FreshRead], &[Covered]),
record: impl FnOnce(&Vk, vk::CommandBuffer),
) -> Result<(), Error> {
// After the copies of the encoder's run, which records first (`copy_run.rs`).
self.core.flush_copies(&mut self.run);
let mut shadows = shadow::copies_used(self.shadows.iter(), uses);
shadow::overwritten(&mut shadows, uses, covered);
let copies = self.core.plan_shadows(&shadows, uses)?;
@@ -360,6 +406,27 @@ impl BlitCommandEncoder {
Ok(())
}
/// [`command`](Self::command) of a buffer copy, `copy` (its source, its destination and its
/// region) with `uses`, which joins the encoder's run of copies where it may
/// (`EncoderCore::copy_joining`, `copy_run.rs`): the copies into the heap shadows its uses
/// name go first, as for any command, and none joins a run past them.
fn copy_joining(
&mut self,
uses: &[Use<ResourceKey>],
copy: (vk::Buffer, vk::Buffer, vk::BufferCopy),
) -> Result<(), Error> {
let mut shadows = shadow::copies_used(self.shadows.iter(), uses);
shadow::overwritten(&mut shadows, uses, &[]);
let copies = self.core.plan_shadows(&shadows, uses)?;
if !copies.is_empty() {
self.core.flush_copies(&mut self.run);
}
self.core.shadow_copies(&copies);
self.core.copy_joining(uses, copy, &mut self.run);
self.core.shadows_used(&shadows, uses, &[]);
Ok(())
}
/// Note `texture`, which a blit names: where it is a heap shadow or a tiled texture of more
/// than one level, whose image the blit uses (a texture over a buffer blits on its bytes,
/// `blit_texture.rs`, `Texture::blit_texels`), its commands take its copies.
@@ -386,6 +453,14 @@ impl BlitCommandEncoder {
/// A size of 0 copies nothing, wherever its offsets lie, and the encoder's other commands
/// run, as plain Metal does (Metal's validation stops it).
///
/// Consecutive copies of the encoder between the same two buffers that need no barrier between
/// them (none reads or writes what an earlier one of the run wrote, nor writes what it read)
/// are one `vkCmdCopyBuffer` of a region each (`WorkCounts::buffer_copies_merged`). The
/// encoder's hazard order keeps eight ranges of a buffer and then one span from the lowest
/// byte of any to the highest, so a copy into that span of the earlier copies' destinations
/// takes a barrier and starts a new run: sort copies by destination offset (a picture's rows
/// in order, tile beside tile) to merge them all.
///
/// A no-copy source buffer is read past its length to the end of its host pages, the
/// caller's bytes, as plain Metal reads them (its validation stops it).
///
@@ -399,7 +474,9 @@ impl BlitCommandEncoder {
destination_offset: u64,
size: u64,
) -> Result<(), Error> {
self.logged(
// A copy may join the encoder's run of copies (`copy_run.rs`).
self.logged_after(
false,
|_| {
BlitCall::CopyBufferToBuffer(
source_buffer.clone(),
@@ -414,6 +491,7 @@ impl BlitCommandEncoder {
this.core.check_device(CALL, source_buffer.generation())?;
this.core
.check_device(CALL, destination_buffer.generation())?;
this.refuse_unshared(CALL, &[source_buffer, destination_buffer])?;
if size == 0 {
return Ok(());
}
@@ -487,20 +565,11 @@ impl BlitCommandEncoder {
)
});
} else {
this.command(
&[reads(source_buffer, from), writes(destination_buffer, to)],
|device, raw| {
// SAFETY: as above; the regions do not overlap.
unsafe {
device.cmd_copy_buffer(
raw,
source,
destination,
&[region(source_at, destination_at, size)],
);
}
},
)?;
// One region of the run of copies between the two buffers, where it joins
// (`copy_run.rs`); the regions do not overlap.
let uses = [reads(source_buffer, from), writes(destination_buffer, to)];
let copy = (source, destination, region(source_at, destination_at, size));
this.copy_joining(&uses, copy)?;
}
Ok(())
},
@@ -529,6 +598,7 @@ impl BlitCommandEncoder {
|this| {
const CALL: &str = "fill_buffer";
this.core.check_device(CALL, buffer.generation())?;
this.refuse_unshared(CALL, &[buffer])?;
let size = range.end.saturating_sub(range.start);
if size == 0 {
return Ok(());
@@ -649,15 +719,16 @@ impl BlitCommandEncoder {
/// The copy of a `Managed` texture's bytes over a buffer to the buffer's host copy, for
/// `synchronize_resource` and `synchronize_texture`: where the GPU or the CPU finds the texels
/// (an IOSurface plane's two layouts), in the buffer. Those past its length lie in the
/// texture's `Shared` tail, which takes no synchronization (`buffer_texture.rs`), and a texture
/// of an image alone takes none, its CPU access copying from its image.
/// (an IOSurface plane's two layouts), in the buffer's memory, past its length too where that
/// holds them (`Texels::kept`). Those past it lie in the texture's `Shared` tail, which takes
/// no synchronization (`buffer_texture.rs`), and a texture of an image alone takes none, its
/// CPU access copying from its image.
pub(super) fn synchronize_texels(&mut self, texture: &Texture) -> Result<(), Error> {
let Some(texels) = texture.buffer_texels() else {
return Ok(());
};
let span = texels.span();
let end = span.end.min(texels.buffer.length());
let end = span.end.min(texels.kept());
self.synchronize_bytes(&texels.buffer, span.start.min(end)..end)
}
@@ -740,10 +811,19 @@ impl BlitCommandEncoder {
log,
aborts: _,
fill_tiles: _,
mut run,
} = self;
let _call = core.begin_call();
core.flush_copies(&mut run);
if let Some(pattern) = pattern {
core.retain(pattern);
}
core.end_with_replay(EncoderKind::Blit, (None, None), log.map(Replay::Blit), None)
EncoderCore::end_with_replay(
HeldCore(core),
EncoderKind::Blit,
(None, None),
log.map(Replay::Blit),
None,
)
}
}
+3 -2
View File
@@ -65,7 +65,7 @@ impl BufferLayout {
/// `buffer_length` bytes; the bytes it spans from its offset. A layout of more than one image
/// reaches it within Metal's `bytesPerImage` rule ([`plan_buffer_copy`] places one off it first;
/// a texture over a buffer, and a depth or stencil format, has one image).
fn check_layout(
pub(super) fn check_layout(
layout: &BufferLayout,
size: [u32; 3],
unit: &CopyUnit,
@@ -921,7 +921,8 @@ impl RowsCopy {
}
/// This copy cut where a side's bytes pass `src_cut` or `dst_cut` (a texture's whose texels
/// run past its buffer's length, whose bytes past it lie in its tail, `buffer_texture.rs`):
/// run past those it keeps in its buffer, whose bytes past them lie in its tail,
/// `buffer_texture.rs`):
/// up to four copies, each `(whether its source rows lie past the source's cut, whether its
/// destination rows lie past the destination's, the copy)`, every row in exactly one of
/// them, cut where it crosses either cut. A side with no cut lies before it whole.
+17 -12
View File
@@ -104,8 +104,8 @@ use std::sync::Arc;
/// One side of a copy of rows (`BlitCommandEncoder::rows_copy`): the buffer whose bytes its uses
/// name, and the buffer its rows lie in, `rebase` bytes before their place in the first one's
/// space: the buffer itself, or for a texture's bytes past its buffer's length the texture's tail
/// (`buffer_texture::Past`).
/// space: the buffer itself, or for a texture's bytes past those it keeps in its buffer the
/// texture's tail (`buffer_texture::Past`).
#[derive(Clone, Copy)]
struct RowsSide<'a> {
uses: &'a Buffer,
@@ -152,7 +152,7 @@ fn write() -> Access {
}
/// The levels and layers of the image a region of `region`'s level and slices covers.
fn subresources(region: &ImageRegion) -> (Range<u32>, Range<u32>) {
pub(super) fn subresources(region: &ImageRegion) -> (Range<u32>, Range<u32>) {
(
region.level..region.level + 1,
region.layer..region.layer + region.layers,
@@ -163,7 +163,7 @@ fn subresources(region: &ImageRegion) -> (Range<u32>, Range<u32>) {
/// of 0 that a texture of the copy lacks, depth on all but 3D textures and height on 1D textures
/// and texture buffers, copies one texel there; `None` for a copy with another axis 0, which copies
/// nothing.
fn copy_size(size: Size, types: &[TextureType]) -> Option<Size> {
pub(super) fn copy_size(size: Size, types: &[TextureType]) -> Option<Size> {
use TextureType::{TextureBuffer, Type1D, Type1DArray, Type3D};
let any = |lacks: fn(TextureType) -> bool| types.iter().any(|&t| lacks(t));
let mut size = size;
@@ -178,7 +178,7 @@ fn copy_size(size: Size, types: &[TextureType]) -> Option<Size> {
/// `level` and `slice`, and `origin` and `size`, as a region of a texture; refused as Metal
/// refuses a region past the texture when a value is past any texture.
fn region(
pub(super) fn region(
call: &'static str,
origin: Origin,
size: Size,
@@ -389,7 +389,7 @@ fn plan_copy(
}
/// The Vulkan region of `region`.
fn buffer_image_region(region: &BufferImageRegion) -> vk::BufferImageCopy {
pub(super) fn buffer_image_region(region: &BufferImageRegion) -> vk::BufferImageCopy {
vk::BufferImageCopy {
buffer_offset: region.buffer_offset,
buffer_row_length: region.row_length,
@@ -455,7 +455,11 @@ fn regions_meet(a: &ImageRegion, b: &ImageRegion) -> bool {
impl BlitCommandEncoder {
/// Refuse `texture` of another device; note it for its heap shadow (`BlitCommandEncoder::see`).
fn check_texture(&mut self, call: &'static str, texture: &Texture) -> Result<(), Error> {
pub(super) fn check_texture(
&mut self,
call: &'static str,
texture: &Texture,
) -> Result<(), Error> {
self.core().check_device(call, texture.generation())?;
self.see(texture);
Ok(())
@@ -466,7 +470,7 @@ impl BlitCommandEncoder {
/// generation (`CommandBufferError::InvalidResource`, the encoder's whole run of blit
/// encoders running nothing, an M3 Max under macOS 27.0.1), so the encoder fails it and the
/// copy records nothing.
fn fails_on_memoryless(&mut self, textures: &[&Texture]) -> bool {
pub(super) fn fails_on_memoryless(&mut self, textures: &[&Texture]) -> bool {
let memoryless = textures.iter().any(|texture| texture.is_memoryless());
if memoryless {
self.core().fail_memoryless_use();
@@ -1966,8 +1970,9 @@ impl BlitCommandEncoder {
};
let layout =
texel_layout(&texels.layout, &unit, bytes, bytes.layer + layer);
// Texels past the buffer's length lie in its tail: the rows go through a
// scratch buffer of the encoder, as rows of the bytes they lie in.
// Texels past those kept in the buffer lie in its tail: the rows go
// through a scratch buffer of the encoder, as rows of the bytes they lie
// in.
if let Some(past) = texels.past() {
let [width, height, _] = bytes.size;
let row = u64::from(width) * u64::from(unit.bytes);
@@ -2022,7 +2027,7 @@ impl BlitCommandEncoder {
&region,
&image_unit,
&layout,
buffer.length(),
texels.kept(),
buffer.start(),
into_texture,
)
@@ -2041,7 +2046,7 @@ impl BlitCommandEncoder {
}
/// Record `copy` from `source`'s bytes into `destination`'s, as [`rows_copy`](Self::rows_copy)
/// does, where a side's bytes past its buffer's length lie in a texture's tail (`past`,
/// does, where a side's bytes past those kept in its buffer lie in a texture's tail (`past`,
/// `buffer_texture.rs`): the rows cut there, each part from and into the bytes it lies in,
/// its uses those of the buffer's bytes it stands for.
fn texels_rows_copy(
+418 -63
View File
@@ -35,10 +35,11 @@ use super::fresh_pages;
use super::generated_commands::PREPROCESS_BUFFER;
use super::heap::{Heap, HeapType};
use super::host_aliases::Alias;
use super::host_bytes::HostBytes;
use super::host_memory::{HeldBack, HostParts, KeepAlive, Release};
use super::host_ram::RamOnDevice;
#[cfg(unix)]
use super::host_residency::{Again, Residency};
use super::linear_plan::METAL_PAGE;
use super::managed_copy::{CallerCopy, SyncTarget};
use super::memory::{
BoundMemory, Holds, Mapped, MemoryClass, Placement, BLOCK_BYTES, FD_BLOCKS_HANDLE,
@@ -100,6 +101,12 @@ struct BufferShared {
/// Its identity (`object_id`).
object_id: ObjectId,
length: u64,
/// The bytes from byte 0 that Metal's allocation of the buffer holds as its own, which a
/// texture over it reaches in place ([`Buffer::texel_reach`]): for a buffer of at least
/// 16 KiB the program makes of the runtime's memory in the Metal address space, its length
/// rounded up to 16 KiB (Metal's `allocatedSize`), its `VkBuffer` and placement that long and
/// zero when made (`Device::placed_new_buffer`); its length for every other buffer.
allocation: u64,
/// The options with the hazard tracking mode resolved, as `resourceOptions` reports them.
options: ResourceOptions,
address: GpuAddress,
@@ -367,7 +374,8 @@ impl TexturesOver {
}
/// How many times a no-copy buffer of the process (or a no-copy heap's own buffer) came to lie
/// elsewhere ([`HostCell::replace`]: rebound or detached).
/// elsewhere ([`HostCell::replace`]: rebound or detached), and a rebind settled what lies over
/// its bytes ([`host_cells_settled`]).
static HOST_CELLS_MOVED: AtomicU64 = AtomicU64::new(0);
/// The count of the times a no-copy buffer of the process came to lie elsewhere (rebound or
@@ -377,6 +385,14 @@ pub(super) fn host_cells_moved() -> u64 {
HOST_CELLS_MOVED.load(Ordering::Acquire)
}
/// A rebind closed its publish (`Rebinds::published`): the images, views and texel views over the
/// moved buffer's bytes are made over its new pages, so a binding read since its move, while they
/// were being made, may hold the old pages' ones. Counted in [`host_cells_moved`] as a move: no
/// binding read before it is kept after it (`rebind.rs`, **Other threads**).
pub(super) fn host_cells_settled() {
HOST_CELLS_MOVED.fetch_add(1, Ordering::AcqRel);
}
/// The most buffers over host pages a [`KeptSpaces`] keeps where they lie.
const KEPT_SPACES: usize = 4;
@@ -414,12 +430,18 @@ impl KeptSpaces {
let at = Arc::as_ptr(cell);
let found = (self.kept.iter()).find(|kept| kept.moved == moved && kept.cell.as_ptr() == at);
if let Some(kept) = found {
// Unless it moved since `moved` was read, on another thread (`rebind.rs`, **Other
// threads**): the move is counted under the cell's lock, before a reading of it can
// see where it lies now, and the call's hold tells the race apart.
#[cfg(debug_assertions)]
assert_eq!(
kept.pages,
cell.binding_pages(),
"a buffer kept where it no longer lies"
);
{
let now = cell.binding_pages();
assert!(
kept.pages == now || host_cells_moved() != moved,
"a buffer kept where it no longer lies: {:?}, lying in {now:?}",
kept.pages
);
}
return kept.pages;
}
cell.device.shared().counts.thread().bind_space_read();
@@ -844,9 +866,19 @@ pub(super) struct FixedPages {
released: AtomicBool,
/// They went ([`FixedPages::release_lost`]): its drop lets go of nothing.
freed: AtomicBool,
/// The images of textures over them, of the runtime's memory exported as a dma-buf, parked
/// as their textures went (`dma_buf/parked.rs`): released as they go.
#[cfg(unix)]
parked_images: crate::dma_buf::parked::ParkedImages,
}
impl FixedPages {
/// The images parked under them (`dma_buf/parked.rs`).
#[cfg(unix)]
pub(super) fn parked_images(&self) -> &crate::dma_buf::parked::ParkedImages {
&self.parked_images
}
/// Destroy the `VkBuffer` and free the memory of the pages of a buffer its device's recovery
/// carried to the next generation, on the lost one at rest, marked let go of
/// ([`LostBuffer`]), and let go of its handle of that generation (`device/carry.rs`). Vulkan
@@ -859,6 +891,9 @@ impl FixedPages {
return;
};
let shared = self.device.shared();
// The images parked under them go with them, before their memory (`dma_buf/parked.rs`).
#[cfg(unix)]
crate::dma_buf::parked::release(self.parked_images.take_where(|_| true));
if self.owned {
// SAFETY: none of the lost generation's command buffers records or is pending, and
// every later one's work reaches the carried buffer's own pages.
@@ -1030,6 +1065,10 @@ impl Drop for FixedPages {
return;
};
let shared = self.device.shared();
// The images parked under them go first, before their memory is freed or recycled for
// another buffer (`dma_buf/parked.rs`).
#[cfg(unix)]
crate::dma_buf::parked::release(self.parked_images.take_where(|_| true));
// No pending command buffer uses the pages: one whose commands used the buffer holds it,
// and one whose resident set lists them holds them, until it completed.
let placement = &self.pages.memory.placement;
@@ -1107,6 +1146,21 @@ pub(super) struct HostPages {
made_of: OnceLock<HostParts>,
}
/// Where host pages lie in one import of a dma-buf dedicated to nothing
/// ([`HostPages::in_one_dma_buf_import`]).
#[cfg(unix)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct DmaBufImportAt {
/// The import's memory: `VK_NULL_HANDLE` where it was read as a blit reads it, unexposed.
pub(super) memory: vk::DeviceMemory,
/// Where the pages' bytes start in it.
pub(super) base: u64,
/// Its bytes from there to the end of the pages' placement.
pub(super) room: u64,
/// Its memory type.
pub(super) type_index: u32,
}
/// How new pages come to lie in an import ([`HostPages::new`]).
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Joining {
@@ -1284,7 +1338,6 @@ impl HostPages {
return None;
}
let pages = import.pages(ReadApart::VkBuffer);
#[cfg(unix)]
if matches!(pages, ImportPages::StandIn(_)) {
return None;
}
@@ -1336,6 +1389,45 @@ impl HostPages {
}))
}
/// Where they lie in one import of a dma-buf dedicated to nothing (`dma_buf.rs`), which an
/// image in place over their bytes binds in at its texels' offset, as several buffers bind in
/// one import (`texture/in_place_image.rs`): the import's memory, where their bytes start in
/// it, the bytes of it from there to their placement's end, and its memory type. `None` for
/// pages imported by their pointer, pages bound sparsely over several imports (the memory is
/// then none), and an import dedicated to the buffer bound in it, where the driver refused it
/// dedicated to nothing, which binds no image (`VUID-vkBindImageMemory-memory-10926`). Read as
/// a blit reads them where `expose` is false (`HostImport::blit_pages`), so an image's making
/// asks it before it binds and leaves a releasable import releasable, its memory unnamed
/// (`VK_NULL_HANDLE`); where `expose`, as [`HostPages::memory`] reads them, which keeps the
/// import imported for good from then on (`host_residency.rs`), for the image's bind.
/// Refused where the device cannot import them again.
#[cfg(unix)]
pub(super) fn in_one_dma_buf_import(
&self,
expose: bool,
) -> Result<Option<DmaBufImportAt>, Error> {
let pages = match expose {
true => self.import.pages(ReadApart::Texture),
false => self.import.blit_pages()?.0,
};
let placement = &pages.memory.placement;
let Some(imports) = placement.dma_buf_pages() else {
return Ok(None);
};
if placement.memory == vk::DeviceMemory::null() || imports.dedicated_to_buffer() {
return Ok(None);
}
Ok(Some(DmaBufImportAt {
memory: match expose {
true => placement.memory,
false => vk::DeviceMemory::null(),
},
base: placement.offset + pages.offset,
room: placement.size().saturating_sub(pages.offset),
type_index: placement.type_index(),
}))
}
/// As the buffer that lies in them is released (`BufferShared`'s drop, a no-copy heap's own
/// buffer's included), its listing let go of: a live buffers' table that still lists them is a
/// command buffer's, one that may reach them unnamed (its first submission's, a host step's,
@@ -1470,6 +1562,10 @@ pub(super) struct HostImport {
/// The logs of the writes to its pages, where their memory came with one
/// (`dirty_pages::PagesLog`): every buffer lying in it shares them.
log: OnceLock<Arc<PagesLog>>,
/// The images in place over its pages kept as their textures went, for the next texture over
/// them (`dma_buf/parked.rs`): released as it goes, before what waits for its free.
#[cfg(unix)]
parked_images: crate::dma_buf::parked::ParkedImages,
}
/// Where a host import's bytes lie in its `VkBuffer` and memory, which reading needs no
@@ -1613,7 +1709,6 @@ enum Objects {
/// Imported until the import goes.
Fixed(Imported),
/// Released while idle, and imported again at the next read (`host_residency.rs`).
#[cfg(unix)]
Releasable(Residency),
}
@@ -1621,11 +1716,9 @@ enum Objects {
/// keeps them, or held, from one that may release them, for as long as the read lasts.
pub(super) enum ImportPages<'a> {
Fixed(&'a Pages),
#[cfg(unix)]
Held(Arc<Imported>),
/// The device's stand-in, which a read of a released import takes where the device cannot
/// import it again ([`HostImport::pages`]).
#[cfg(unix)]
StandIn(Arc<FixedPages>),
}
@@ -1635,9 +1728,7 @@ impl std::ops::Deref for ImportPages<'_> {
fn deref(&self) -> &Pages {
match self {
ImportPages::Fixed(pages) => pages,
#[cfg(unix)]
ImportPages::Held(imported) => &imported.pages,
#[cfg(unix)]
ImportPages::StandIn(stand_in) => &stand_in.pages,
}
}
@@ -1668,12 +1759,13 @@ impl HostImport {
after_free: Mutex::new(Vec::new()),
copied: OnceLock::new(),
log: OnceLock::new(),
#[cfg(unix)]
parked_images: Default::default(),
}
}
/// The import of `pages`, no pages lying in it yet, which the device releases while idle and
/// `again` imports again (`host_residency.rs`).
#[cfg(unix)]
fn releasable(
device: &Device,
pages: Pages,
@@ -1695,9 +1787,17 @@ impl HostImport {
after_free: Mutex::new(Vec::new()),
copied: OnceLock::new(),
log: OnceLock::new(),
#[cfg(unix)]
parked_images: Default::default(),
}
}
/// The images parked under it (`dma_buf/parked.rs`).
#[cfg(unix)]
pub(super) fn parked_images(&self) -> &crate::dma_buf::parked::ParkedImages {
&self.parked_images
}
/// A live buffers' table listed pages lying in it ([`ListedPages`]): a rebind's import is
/// listed from now on (`WorkCounts::host_imports_rebound_unlisted`). A load once listed.
fn note_listed(&self) {
@@ -1761,7 +1861,6 @@ impl HostImport {
}
/// Its residency, where the device may release it while idle.
#[cfg(unix)]
pub(super) fn residency(&self) -> Option<&Residency> {
match &*self.objects {
Objects::Fixed(_) => None,
@@ -1777,7 +1876,6 @@ impl HostImport {
self.note_read_apart(reason);
match &*self.objects {
Objects::Fixed(imported) => ImportPages::Fixed(&imported.pages),
#[cfg(unix)]
Objects::Releasable(residency) => match residency.exposed() {
Some(held) => ImportPages::Held(held),
None => {
@@ -1796,7 +1894,6 @@ impl HostImport {
pub(super) fn blit_pages(&self) -> Result<(ImportPages<'_>, Option<ImportHold>), Error> {
match &*self.objects {
Objects::Fixed(imported) => Ok((ImportPages::Fixed(&imported.pages), None)),
#[cfg(unix)]
Objects::Releasable(residency) => {
let held = residency.for_blit()?;
let hold = ImportHold::Held(Arc::clone(&held));
@@ -1810,7 +1907,6 @@ impl HostImport {
fn listing(&self) -> Option<ImportPages<'_>> {
match &*self.objects {
Objects::Fixed(imported) => Some(ImportPages::Fixed(&imported.pages)),
#[cfg(unix)]
Objects::Releasable(residency) => residency.listing().map(ImportPages::Held),
}
}
@@ -1821,7 +1917,6 @@ impl HostImport {
self.note_read_apart(reason);
match &*self.objects {
Objects::Fixed(_) => false,
#[cfg(unix)]
Objects::Releasable(residency) => residency.expose(),
}
}
@@ -1851,7 +1946,6 @@ impl HostImport {
/// ([`Joining::Buffer`]): counted where it is releasable still, which it stays
/// (`WorkCounts::host_imports_joined_releasable`, `host_residency.rs`).
fn note_joined(&self) {
#[cfg(unix)]
if self.residency().is_some_and(Residency::releasable) {
(self.device.shared().counts).host_import_joined_releasable();
}
@@ -1932,6 +2026,10 @@ impl Drop for HostImport {
shared.counts.host_import_rebound_unlisted(false);
}
drop(busy);
// The images parked under it go first: their imports are of its pages too, which the
// keep-alive and the deallocators below let go of (`dma_buf/parked.rs`).
#[cfg(unix)]
crate::dma_buf::parked::release(self.parked_images.take_where(|_| true));
// Once freed, the keep-alive goes, and the deallocators that waited for the free run.
let kept = lock(&self.kept).take();
if kept.is_some() {
@@ -1982,7 +2080,6 @@ impl Drop for HostImport {
// replaced its pages), and what waits for the free with them: a driver may list a
// pointer import's memory in every submission, which fails where its pages were
// unmapped.
#[cfg(unix)]
Objects::Releasable(residency) => match residency.let_go() {
Some(mut held) => {
held.leave(left);
@@ -2325,14 +2422,16 @@ impl Pages {
/// last holder lets go of them, then. Pages bound in a guest RAM's chunk (`host_ram.rs`) free
/// no memory of their own, whatever the chunk's import: at once.
fn after_free(&self, after: Box<dyn Send>) {
let placement = &self.memory.placement;
#[cfg(unix)]
if let Some(imports) = placement
.dma_buf_pages()
.filter(|_| !placement.over_ram_chunk())
{
imports.after_free(after);
return;
let placement = &self.memory.placement;
if let Some(imports) = placement
.dma_buf_pages()
.filter(|_| !placement.over_ram_chunk())
{
imports.after_free(after);
return;
}
}
drop(after);
}
@@ -2481,7 +2580,11 @@ pub(super) enum Owner {
Caller,
/// The caller: a `VkBuffer` and the memory it is bound to, which the caller made and keeps
/// (`wrapped_buffer.rs`). The runtime destroys and frees neither.
Vulkan,
Vulkan {
/// The caller made it concurrent with the copy engine's queue family, the copy queue's
/// (`Device::new_command_queue_for_copies`), whose commands may then use it.
copy_engine: bool,
},
}
/// Whose memory a buffer's bytes are, where they are the caller's.
@@ -2553,7 +2656,7 @@ impl Buffer {
Lie::Fixed(fixed) => {
facts.push_str(", ");
facts.push_str(&fixed.pages.memory.placement.failure_facts(types));
if matches!(own.owner, Owner::Vulkan) {
if matches!(own.owner, Owner::Vulkan { .. }) {
facts.push_str(", the caller's VkBuffer");
}
match fixed.released.load(Ordering::Acquire) {
@@ -2616,7 +2719,6 @@ impl HostImport {
facts.push_str(&imported.pages.memory.placement.failure_facts(types));
Standing::Held
}
#[cfg(unix)]
Objects::Releasable(residency) => {
facts.push_str(", releasable, memory ");
facts.push_str(&types.of(shape.type_index));
@@ -2764,6 +2866,11 @@ pub(super) struct BufferParts {
pub(super) offset: u64,
pub(super) base: u64,
pub(super) length: u64,
/// The bytes from byte 0 that Metal's allocation of it holds as its own (`BufferShared`'s
/// `allocation`): its length, or for a buffer of at least 16 KiB the program makes of the
/// runtime's memory in the Metal address space, its length rounded up to 16 KiB, which its
/// `VkBuffer` holds.
pub(super) allocation: u64,
/// The bytes from byte 0 a copy reads in the `VkBuffer` ([`Buffer::copy_reach`]): the
/// length, or a no-copy buffer's bytes to the end of its `VkBuffer` in its pages.
pub(super) reach: u64,
@@ -2783,7 +2890,6 @@ pub(super) struct BufferParts {
pub(super) mirror: Option<HostCopy>,
/// What imports a no-copy buffer's dma-bufs again, where the device may release its import
/// while idle (`host_residency.rs`).
#[cfg(unix)]
pub(super) again: Option<Again>,
/// A new buffer, or the same buffer on its device's next generation.
pub(super) naming: Naming,
@@ -3298,6 +3404,14 @@ impl Device {
NewBufferOf::Unobserved | NewBufferOf::Check(_) => (false, FreshPages::WherePaid),
};
let plain = matches!(of, NewBufferOf::Check(_));
// A buffer whose maker declares its padding unobserved backs textures: its placement starts
// and ends on the device's linear images' memory alignment, so that such an image over its
// texels at offset 0 meets it and one whose size the driver rounds up to it fits in bytes
// the buffer owns (`Buffer::memory_room`).
let granule = match of {
NewBufferOf::Unobserved => self.linear_image_alignment(),
_ => LINEAR_IMAGE_ALIGNMENT,
};
if self.is_lost() {
return Err(self.lost_refusal());
}
@@ -3307,8 +3421,10 @@ impl Device {
let lead = aligned.map_or(0, |byte| {
(LINEAR_IMAGE_ALIGNMENT - byte % LINEAR_IMAGE_ALIGNMENT) % LINEAR_IMAGE_ALIGNMENT
});
let allocation =
metal_allocation(length, of, placement, self.properties().max_buffer_length);
// Padded to 16 bytes, so a device fill clears every byte too.
let size = length
let size = allocation
.checked_add(lead)
.and_then(|size| size.checked_next_multiple_of(16))
.ok_or_else(|| nil(call, Problem::BufferLength { length }))?;
@@ -3399,6 +3515,7 @@ impl Device {
class,
fresh_pages: wants_fresh,
holds,
granule,
});
let mut taken = making.and_then(|making| self.recycled_buffer(&making));
let fresh = match (&taken, wants_fresh) {
@@ -3458,7 +3575,7 @@ impl Device {
let placed = if of_heap {
self.place_heap_buffer(raw, length, class, placement)
} else {
self.place_buffer_in(raw, length, (class, holds), placement)
self.place_buffer_in(raw, length, (class, holds, granule), placement)
};
match placed {
Ok(placed) => {
@@ -3488,6 +3605,7 @@ impl Device {
offset: lead,
base: lead,
length,
allocation,
reach: length,
modes,
address,
@@ -3497,7 +3615,6 @@ impl Device {
of_heap,
drops_writes: false,
mirror,
#[cfg(unix)]
again: None,
naming: Naming::New,
});
@@ -3689,6 +3806,7 @@ impl Device {
offset: 0,
base: 0,
length: required.size,
allocation: required.size,
reach: required.size,
modes,
address,
@@ -3698,7 +3816,6 @@ impl Device {
of_heap: false,
drops_writes: false,
mirror: None,
#[cfg(unix)]
again: None,
naming: Naming::New,
}))
@@ -3712,6 +3829,7 @@ impl Device {
offset,
base,
length,
allocation,
reach,
modes,
address,
@@ -3721,7 +3839,6 @@ impl Device {
of_heap,
drops_writes,
mirror,
#[cfg(unix)]
again,
naming,
} = parts;
@@ -3737,10 +3854,7 @@ impl Device {
(false, true) => None,
(false, false) => Some(KeptBecause::Pointer),
};
#[cfg(unix)]
let import = self.host_import(pages, again, kept);
#[cfg(not(unix))]
let import = Arc::new(HostImport::new(self, pages, kept));
self.host_lie(
identity.key,
(import, Joining::First),
@@ -3748,12 +3862,14 @@ impl Device {
drops_writes,
)
}
Owner::Runtime | Owner::Vulkan => Lie::Fixed(Arc::new(FixedPages {
Owner::Runtime | Owner::Vulkan { .. } => Lie::Fixed(Arc::new(FixedPages {
device: MadeOn::new(self.clone()),
pages,
owned: matches!(owner, Owner::Runtime),
released: AtomicBool::new(false),
freed: AtomicBool::new(false),
#[cfg(unix)]
parked_images: Default::default(),
})),
};
let own = OwnBytes {
@@ -3764,13 +3880,12 @@ impl Device {
mirror,
range_token: KeptToken::default(),
};
self.buffer_lying(own, length, modes, address, naming)
self.buffer_lying(own, (length, allocation), modes, address, naming)
}
/// The import of a no-copy buffer's `pages`: one the device releases while idle where
/// `again` imports them again and the device keeps a stand-in for it and a thread to release
/// it (`host_residency.rs`), else one it keeps, for `kept` where nothing imports it again.
#[cfg(unix)]
fn host_import(
&self,
pages: Pages,
@@ -3818,7 +3933,7 @@ impl Device {
mirror: None,
range_token: KeptToken::default(),
};
self.buffer_lying(own, length, modes, address, naming)
self.buffer_lying(own, (length, length), modes, address, naming)
}
/// A no-copy buffer's lie, of `key`: pages of its own in `import`, released to `release`
@@ -3854,11 +3969,12 @@ impl Device {
Lie::Host(cell)
}
/// The buffer of `own`'s bytes, `length` long, of `modes`, at `address`, named by `naming`.
/// The buffer of `own`'s bytes, `length` long, Metal's allocation of it holding `allocation`
/// bytes, of `modes`, at `address`, named by `naming`.
fn buffer_lying(
&self,
own: OwnBytes,
length: u64,
(length, allocation): (u64, u64),
modes: Modes,
address: GpuAddress,
naming: Naming,
@@ -3879,6 +3995,7 @@ impl Device {
generation: std::ptr::from_ref(self.shared()).addr(),
object_id,
length,
allocation,
options,
address,
attributes,
@@ -3969,24 +4086,85 @@ impl Device {
class: MemoryClass,
at: Place,
) -> Result<(Placement, (GpuAddress, Held)), Error> {
self.place_buffer_in(raw, length, (class, Holds::Buffers), at)
let granule = LINEAR_IMAGE_ALIGNMENT;
self.place_buffer_in(raw, length, (class, Holds::Buffers, granule), at)
}
/// [`place_buffer`](Device::place_buffer) in a block that holds `holds`: `Holds::Buffers`, or
/// `Holds::FdBuffers` or `Holds::FdDmaBufs` for a buffer made for `FD_BLOCKS_HANDLE`
/// (`memory.rs`).
/// (`memory.rs`); its placement starting on `granule` and, short of half a block, ending on it
/// ([`placed`]).
fn place_buffer_in(
&self,
raw: vk::Buffer,
length: u64,
(class, holds): (MemoryClass, Holds),
(class, holds, granule): (MemoryClass, Holds, u64),
at: Place,
) -> Result<(Placement, (GpuAddress, Held)), Error> {
// SAFETY: `raw` is a live buffer of this device.
let requirements = unsafe { self.shared().vk().get_buffer_memory_requirements(raw) };
let own = unsafe { self.shared().vk().get_buffer_memory_requirements(raw) };
let requirements = vk::MemoryRequirements {
alignment: own.alignment.max(granule),
..own
};
self.place_buffer_with(raw, requirements, length, (class, holds), at, true)
}
/// The memory alignment the device's linear images take: `VkMemoryRequirements::alignment` of
/// one, a 64 by 8 `R8G8B8A8_UNORM` 2D image to sample and copy, made and released at the first
/// ask and kept for the device's life (`TextureState::linear_image_alignment`); at least
/// [`LINEAR_IMAGE_ALIGNMENT`], which it is where the device makes no such image. Intel's driver
/// for the UHD 630 on Windows answers 4096, and rounds a small linear image's size up to a
/// multiple of it.
pub(super) fn linear_image_alignment(&self) -> u64 {
let textures = &self.shared().textures;
*(textures.linear_image_alignment).get_or_init(|| {
(self.probed_linear_image_alignment())
.unwrap_or(LINEAR_IMAGE_ALIGNMENT)
.max(LINEAR_IMAGE_ALIGNMENT)
})
}
/// [`linear_image_alignment`](Self::linear_image_alignment)'s probe: `None` where the device
/// makes no such image (its format query) or making it failed.
fn probed_linear_image_alignment(&self) -> Option<u64> {
let shared = self.shared();
let raw_device = shared.vk();
let usage = vk::ImageUsageFlags::SAMPLED
| vk::ImageUsageFlags::TRANSFER_SRC
| vk::ImageUsageFlags::TRANSFER_DST;
let info = shared.sharing().image(
vk::ImageCreateInfo::default()
.image_type(vk::ImageType::TYPE_2D)
.format(vk::Format::R8G8B8A8_UNORM)
.extent(vk::Extent3D {
width: 64,
height: 8,
depth: 1,
})
.mip_levels(1)
.array_layers(1)
.samples(vk::SampleCountFlags::TYPE_1)
.tiling(vk::ImageTiling::LINEAR)
.usage(usage)
.initial_layout(vk::ImageLayout::PREINITIALIZED),
);
let limits = self.image_limits(&info, &[]).ok()?;
let fits = limits.max_extent.width >= 64
&& limits.max_extent.height >= 8
&& limits.sample_counts.contains(vk::SampleCountFlags::TYPE_1);
if !fits {
return None;
}
// SAFETY: the device is live and `info` valid and within the device's limits for it.
let raw = unsafe { crate::creation::image(raw_device, &info) }.ok()?;
// SAFETY: `raw` is a live image of this device.
let requirements = unsafe { raw_device.get_image_memory_requirements(raw) };
// SAFETY: the image is live and unbound, and no command uses it.
unsafe { release::object(raw_device, raw) };
Some(requirements.alignment)
}
/// [`place_buffer`](Device::place_buffer) for a heap's own buffer: where the heap's textures
/// can lie too (`Device::heap_requirements`).
pub(super) fn place_heap_buffer(
@@ -4116,6 +4294,31 @@ pub(super) enum NewBytes {
Zero,
}
/// The bytes Metal's allocation of a buffer of `length` made for `of` at `placement` holds as its
/// own (`BufferShared`'s `allocation`): a buffer of at least 16 KiB the program makes of the
/// runtime's memory (`NewBufferOf::Runtime(FreshPages::WherePaid)`, `NewBufferOf::Unobserved`) at
/// a range of the Metal address space (`AddressPlacement::Any` or a pin) holds its length rounded
/// up to 16 KiB, its `allocatedSize` on Metal, where that stays within `max_length`; every other
/// buffer its length: a shorter one, whose Metal allocation is its length (or a slot of a pool),
/// a heap's own, the runtime's own outside the space, an indirect command buffer's records and
/// the in-place check's.
fn metal_allocation(length: u64, of: NewBufferOf, placement: Place, max_length: u64) -> u64 {
let program = matches!(
of,
NewBufferOf::Runtime(FreshPages::WherePaid) | NewBufferOf::Unobserved
);
let in_space = matches!(
placement,
Place::At(AddressPlacement::Any | AddressPlacement::At(_))
);
match program && in_space && length >= METAL_PAGE {
true => (length.checked_next_multiple_of(METAL_PAGE))
.filter(|&allocation| allocation <= max_length)
.unwrap_or(length),
false => length,
}
}
/// The memory class of a buffer of `modes`' storage and CPU cache modes, for `call`: refused for
/// `Memoryless`, which is no buffer's. `Shared` storage is `MemoryClass::WriteCombined` in the
/// write-combined CPU cache mode, which the host does not read.
@@ -4146,6 +4349,7 @@ impl Heap {
generation: std::ptr::from_ref(heap_bytes.generation().shared()).addr(),
object_id: ObjectId::new(),
length,
allocation: length,
options,
address: GpuAddress(heap_bytes.gpu_address().0 + offset),
attributes: ResourceAttributes::new(),
@@ -4284,6 +4488,7 @@ impl Buffer {
/// `f` of the placement the buffer's own pages lie in and of the buffer's first byte's offset
/// in it (`exported_memory.rs`); `None` for a heap's buffer, whose bytes are its heap's.
#[cfg(unix)]
pub(super) fn own_placement<R>(&self, f: impl FnOnce(&Placement, u64) -> R) -> Option<R> {
match &self.s().bytes {
Bytes::Own(own) => Some(own.with(ReadApart::Binding, |pages| {
@@ -4296,24 +4501,50 @@ impl Buffer {
/// Whether the buffer's own pages, of the runtime's memory, lie in device-local memory; `None`
/// for a heap's buffer, whose bytes are its heap's. A buffer's pages are its for good.
pub(super) fn own_pages_device_local(&self) -> Option<bool> {
(self.own_pages_flags()).map(|flags| flags.contains(vk::MemoryPropertyFlags::DEVICE_LOCAL))
}
/// The property flags of the memory type the buffer's own pages lie in; `None` for a heap's
/// buffer, whose bytes are its heap's.
pub(super) fn own_pages_flags(&self) -> Option<vk::MemoryPropertyFlags> {
let s = self.s();
match &s.bytes {
Bytes::Own(own) => own.with(ReadApart::Binding, |pages| {
let memory = lock(&s.device.shared().memory);
Some(memory.is_device_local(&pages.memory.placement))
Some(memory.flags_of(&pages.memory.placement))
}),
Bytes::Heap(_) => None,
}
}
/// The length padded to 16 bytes: the bytes the `VkBuffer` holds from [`Buffer::base`].
/// Metal's allocation of the buffer padded to 16 bytes (its length, or its length rounded
/// up to 16 KiB, `BufferShared`'s `allocation`): the bytes the `VkBuffer` holds from
/// [`Buffer::base`], which its first fill clears.
pub(super) fn padded_length(&self) -> u64 {
self.s().length.next_multiple_of(16)
self.s().allocation.next_multiple_of(16)
}
/// The bytes from byte 0 that a texture over the buffer reaches in place in its memory
/// (`buffer_texture.rs`'s **Tails**; past them its texels lie in its tail): Metal's
/// allocation of a buffer of its own (its length, or its length rounded up to 16 KiB,
/// `BufferShared`'s `allocation`), a no-copy buffer's length, whose pages past it are the
/// caller's, and a heap's buffer's heap to its end, as Metal's texels there are the heap's
/// bytes.
pub(super) fn texel_reach(&self) -> u64 {
match &self.s().bytes {
Bytes::Own(_) => self.s().allocation,
Bytes::Heap(bytes) => bytes.bytes.texel_reach().saturating_sub(bytes.offset),
}
}
/// The bytes of the buffer's memory from its byte 0 ([`Buffer::memory`]'s offset) to the end
/// of the memory's placement: an import's, for a buffer over host pages (its last page's bytes
/// past the buffer's among them), or a heap's.
/// of the memory's placement, which no other resource is placed in: its own placement's, at
/// least its `VkBuffer`'s bytes, an import's, for a buffer over host pages (its last page's
/// bytes past the buffer's among them), or a heap's. An image over a texture's texels in that
/// memory may take them all (`texture.rs`'s aliasing image), its driver's bytes past the
/// texels among them: a linear image's size the driver rounds up to its alignment, which a
/// buffer whose maker declares its padding unobserved is placed on
/// (`Device::placed_new_buffer`).
pub(super) fn memory_room(&self) -> u64 {
match &self.s().bytes {
Bytes::Own(own) => own.with(ReadApart::Texture, |pages| {
@@ -4366,6 +4597,7 @@ impl Buffer {
/// Note the acquire of the buffer's `VkBuffer`, whole, from `families`' source, a queue family
/// reserved for external memory, for its target, for the device's next submission to record
/// before any of its commands (`exported_memory.rs`, `Buffer::external_write_done`).
#[cfg(unix)]
pub(super) fn note_acquire(&self, families: (u32, u32)) {
let s = self.s();
let (raw, _) = self.at(0);
@@ -4404,6 +4636,27 @@ impl Buffer {
)
}
/// Set the bytes `range` of a new two-copy buffer's device copy to zero (`managed_copy.rs`:
/// the bytes its caller promised read zero, `HostMemory::with_zero_from`), without waiting
/// for the GPU: by the device's next submission, before any of its commands, as
/// [`clear_first`](Self::clear_first) sets a device copy's bytes, and before the copies in
/// registered after it (`texture/first_move.rs`). The fill writes whole words, those `range`
/// touches: one `vkCmdFillBuffer` in the device's memory, never copies of the device's zeros,
/// which lie in host-visible memory. So the copies in of the bytes beside `range` are
/// registered after it, and land over the bytes of its first and last words that lie outside
/// it; the bytes of those words before the buffer's byte 0 or past its device copy's reach
/// are no buffer's (`Device::two_copy_buffer`).
pub(super) fn zero_device_copy_first(&self, range: Range<u64>) -> Result<(), Error> {
let s = self.s();
let (raw, start) = self.at(range.start);
let end = start + (range.end - range.start);
let words = (start - start % 4)..end.next_multiple_of(4);
let device = &s.device;
let weak: Weak<BufferShared> = Arc::downgrade(s);
let keeper: Weak<dyn Filled> = weak;
(device.shared().textures.first_moves).register_fill(device, keeper, raw, words)
}
/// Give a new buffer whose bytes the host cannot write (`Private` storage) the first `length`
/// bytes `staging` holds, without waiting for the GPU: copied by the device's next
/// submission before any of its commands, after the fill with zeros it took as it was made
@@ -4509,7 +4762,20 @@ impl Buffer {
/// (`exported_memory.rs`), which work of another API's may write.
pub(super) fn gpu_bytes_ordered(&self) -> bool {
let own = self.storage_mode() == StorageMode::Private || self.mirror().is_some();
own && !self.s().handed_out.load(Ordering::Acquire) && self.exported().is_none()
own && !self.s().handed_out.load(Ordering::Acquire) && !self.memory_exported()
}
/// Whether the buffer's memory was allocated exportable (`exported_memory.rs`): never where
/// the system has no handle the runtime exports memory as (file descriptors).
pub(super) fn memory_exported(&self) -> bool {
#[cfg(unix)]
{
self.exported().is_some()
}
#[cfg(not(unix))]
{
false
}
}
/// [`Buffer::at`] for `reason`, which a no-copy buffer's import counts its read apart for
@@ -4793,6 +5059,9 @@ impl Buffer {
None => Ok(()),
}
}
// A range of a few whole words written inline, read from the host copy as the
// submission that takes it is recorded (`managed.rs`).
_ if self.upload_inline(&range, commit) => return,
// Copies from the host copy (or a guest RAM's chunk imports that hold it), which stage
// nothing and go with this commit's batch; pages no import maps staged, a failed
// submission past the bound failing the device, which the commit's own submission
@@ -4808,6 +5077,58 @@ impl Buffer {
}
}
/// Write `range` of a buffer with a host copy ([`HostCopy`]) into its own bytes inline, taken
/// at the commit stamped `commit`, where it is at most `managed::INLINE_BYTES` of whole words
/// (its start in the buffer's `VkBuffer` and its length multiples of 4) and the host copy is
/// mapped: the device's next submission of a command buffer committed at or after that commit
/// that may reach the buffer reads the bytes from the host copy as it is recorded and writes
/// them before any of its commands, by `vkCmdUpdateBuffer`s in its command stream, as
/// [`upload`](Self::upload) would copy them, counted (`WorkCounts::managed_ranges_inlined`).
/// Whether it did; where not, the range is copied as ever. An unaligned range is copied: a
/// write widened to whole words would put the host copy's bytes over neighbours the GPU may
/// have written since.
fn upload_inline(&self, range: &Range<u64>, commit: u64) -> bool {
let s = self.s();
let device = &s.device;
let length = range.end - range.start;
let onto = self.at(range.start);
let words = onto.1.is_multiple_of(4) && length.is_multiple_of(4);
if length == 0 || length > super::managed::inline_bound(device) || !words {
return false;
}
let (from, keeps): (NonNull<u8>, Box<dyn Any + Send + Sync>) = match self.mirror() {
Some(HostCopy::Own(mirror)) => {
let Some(mapped) = mirror.placement.mapped else {
return false;
};
// The host copy holds the buffer's bytes from its start, `range` among them.
let at = mapped.as_ptr().wrapping_add(range.start as usize);
let Some(at) = NonNull::new(at) else {
return false;
};
(at, Box::new(Arc::clone(mirror)))
}
Some(HostCopy::Caller(caller)) => match caller.inline_source(range) {
Some(source) => source,
None => return false,
},
None => return false,
};
s.staged.store(true, Ordering::Relaxed);
let weak: Weak<BufferShared> = Arc::downgrade(s);
let keeper: Weak<dyn Filled> = weak;
let moves = &device.shared().textures.first_moves;
// SAFETY: `keeps` keeps the host copy mapped until the submission that reads the bytes
// completed (`FirstMoves::register_inline_upload`), and it holds the range; only the
// program's CPU, outside the runtime's Rust, writes it.
let from = unsafe { HostBytes::new(from, length as usize) };
moves.register_inline_upload(keeper, onto, from, keeps, commit);
if self.caller_copy().is_some() {
device.shared().counts.managed_copied(length, true);
}
true
}
/// Copy `range` of the bytes of `source` (a `VkBuffer`, and where the buffer's byte
/// `range.start` lies in it) into the buffer's own, by the device's next submission whose
/// commands may reach the buffer (or an internal one), before any of its commands, after the
@@ -5026,7 +5347,7 @@ impl Buffer {
..
}) => Some(CallerMemory::HostPages),
Bytes::Own(OwnBytes {
owner: Owner::Vulkan,
owner: Owner::Vulkan { .. },
..
}) => Some(CallerMemory::VkBuffer),
Bytes::Own(_) => None,
@@ -5035,10 +5356,26 @@ impl Buffer {
}
}
/// Whether the copy engine's queue family, the copy queue's
/// (`Device::new_command_queue_for_copies`), shares the buffer's `VkBuffer`: every one the
/// runtime made, which is concurrent among the device's families and the staging queue's
/// (`sharing.rs`); a caller's where the caller made it concurrent with that family
/// (`wrapped_buffer.rs`); a heap buffer's, its heap's.
pub(super) fn copy_engine_shares(&self) -> bool {
match &self.s().bytes {
Bytes::Own(OwnBytes {
owner: Owner::Vulkan { copy_engine },
..
}) => *copy_engine,
Bytes::Own(_) => true,
Bytes::Heap(bytes) => bytes.bytes.copy_engine_shares(),
}
}
/// The pages a buffer of its own lies in for good (the runtime's memory, or the caller's
/// `VkBuffer`); `None` for a no-copy buffer and a heap's.
#[cfg(unix)]
fn fixed_pages(&self) -> Option<Arc<FixedPages>> {
/// `VkBuffer`), under which the images of textures over its exported memory park
/// (`dma_buf/parked.rs`); `None` for a no-copy buffer and a heap's.
pub(super) fn fixed_pages(&self) -> Option<Arc<FixedPages>> {
match &self.s().bytes {
Bytes::Own(OwnBytes {
lie: Lie::Fixed(fixed),
@@ -5597,7 +5934,7 @@ impl Buffer {
return self.carry_no_copy(last, own, cell, to, of_heap)
}
(Owner::Caller, _) => return Err(Left::NoCopy),
(Owner::Vulkan, _) | (Owner::Runtime, Lie::Host(_)) => return Err(Left::Caller),
(Owner::Vulkan { .. }, _) | (Owner::Runtime, Lie::Host(_)) => return Err(Left::Caller),
};
let from = last.device.shared();
let placement = &fixed.pages.memory.placement;
@@ -5613,7 +5950,7 @@ impl Buffer {
let modes = Modes::of(last.options).map_err(|_| Left::Failed)?;
let class = buffer_class("carry", modes).map_err(|_| Left::Failed)?;
let (length, lead, reach) = (last.length, fixed.pages.offset, fixed.pages.reach);
let size = (length + lead).next_multiple_of(16);
let size = (last.allocation + lead).next_multiple_of(16);
let at = Place::Shared {
address: last.address,
held: own.reserved,
@@ -5675,9 +6012,15 @@ impl Buffer {
let raw =
unsafe { crate::creation::buffer(shared.vk(), &info) }.map_err(|_| Left::Failed)?;
shared.counts.buffer_made(info.usage);
// A buffer whose maker declares its padding unobserved on the device's linear images'
// alignment, as its making placed it.
let granule = match last.padding_unobserved.load(Ordering::Acquire) {
true => to.linear_image_alignment(),
false => LINEAR_IMAGE_ALIGNMENT,
};
let placed = match of_heap {
true => to.place_heap_buffer(raw, length, class, at),
false => to.place_buffer(raw, length, class, at),
false => to.place_buffer_in(raw, length, (class, Holds::Buffers, granule), at),
};
match placed {
Ok((placement, _shared_range)) => (raw, placement, Contents::Lost(length)),
@@ -5739,6 +6082,7 @@ impl Buffer {
generation: std::ptr::from_ref(to.shared()).addr(),
object_id: last.object_id,
length,
allocation: last.allocation,
options: last.options,
address: last.address,
attributes: last.attributes.carried(),
@@ -5749,6 +6093,8 @@ impl Buffer {
owned: true,
released: AtomicBool::new(false),
freed: AtomicBool::new(false),
#[cfg(unix)]
parked_images: Default::default(),
})),
reserved: own.reserved,
identity: own.identity,
@@ -5827,6 +6173,7 @@ impl Buffer {
generation: std::ptr::from_ref(to.shared()).addr(),
object_id: last.object_id,
length: last.length,
allocation: last.allocation,
options: last.options,
address: last.address,
attributes: last.attributes.carried(),
@@ -5899,7 +6246,15 @@ impl Buffer {
// SAFETY: the caller's pages stay mapped while the buffer lives, as the contract of the
// memory it was made or rebound over says (`HostMemory::new`).
let carried = unsafe {
to.buffer_over_host_parts(made, parts, None, of_heap, cell.drops_writes(), naming)
to.buffer_over_host_parts(
made,
parts,
None,
of_heap,
cell.drops_writes(),
naming,
None,
)
}
.map_err(|_| Left::Failed)?;
let (Bytes::Own(carried_own), Some(carried_pages)) =
@@ -10,12 +10,11 @@ use super::address::{
AddressPlacement, AddressRange, GpuAddress, Held, Place, PlacementConflict, RangeToken,
};
use super::address_pool::AddressPool;
use super::buffer::Pages;
use super::buffer::{
usage, Buffer, BufferParts, HostCell, HostImport, HostPages, Lying, Modes, Naming, Owner,
ReadApart, Replaces,
};
#[cfg(unix)]
use super::buffer::{ImportPages, Pages};
use super::copied::NotCopied;
use super::device::lock;
use super::dirty_pages::{DirtySource, PagesLog};
@@ -30,7 +29,6 @@ use super::host_memory::{
ImportRequest, ImportWindow, Importer, KeepAlive, PointerImport, Release, Source,
};
use super::host_ram::{RamOnDevice, Routed};
#[cfg(unix)]
use super::host_residency::Again;
use super::memory::{BoundMemory, ImportFailure, Mapped, MemoryClass, Placement};
use super::read_only_view::ReadOnlyView;
@@ -187,8 +185,12 @@ pub struct BufferDescriptor<'a> {
/// bound: a texture over it takes a `DRM_FORMAT_MOD_LINEAR` image at Metal's pitch bound to a
/// dedicated import of its block's dma-buf (`WorkCounts::exported_dma_buf_images`); elsewhere
/// in a plain block, whose making holds the process's submissions on RADV
/// (`WorkCounts::plain_buffer_blocks_made`). A
/// runtime extension with no Metal counterpart, for a consumer that owns every read of the
/// (`WorkCounts::plain_buffer_blocks_made`). Its placement starts on the device's linear
/// images' memory alignment and takes whole units of it (4096 bytes on Intel's driver for the
/// UHD 630 on Windows, which rounds a small linear image's size up to it; every placement
/// meets the 256 or less of the other devices measured), so an image whose rows fill the
/// buffer lies in bytes the buffer owns, for at most that alignment less one byte more memory.
/// A runtime extension with no Metal counterpart, for a consumer that owns every read of the
/// buffer's bytes; `false` by default, as Metal keeps every byte.
pub padding_unobserved: bool,
/// A byte of the buffer the runtime lays on a multiple of 256 bytes of its memory, the largest
@@ -525,7 +527,10 @@ impl Device {
/// source and target, but never copied: where the import is not made, the copies go through
/// staging buffers. A CPU write no `did_modify_range` names is not seen by the GPU. Where no
/// device-local memory has room for the GPU's copy, the buffer lies in the pages as a `Shared`
/// one does, announced (`device-memory-overflow`).
/// one does, announced (`device-memory-overflow`). Where the caller promised the bytes from
/// an offset read zero ([`HostMemory::with_zero_from`]), the GPU's copy takes those bytes as
/// zeros the device writes in its own memory, copied in from the pages only before the
/// offset.
///
/// Refused: a length of 0 or past `max_buffer_length` (`Nil`, as plain Metal answers nil);
/// `Private` or `Memoryless` storage, as Metal stops them, and an undefined option
@@ -602,7 +607,9 @@ impl Device {
/// The call may come at the unmap or after the new map, but before a buffer is made over the
/// new pages: a buffer made over those bytes while it runs may lie in either pages. The bytes
/// are an address range only, never read: they may be unmapped, and may cover a whole
/// reservation of many buffers. The call is safe from any thread while other calls run on
/// reservation of many buffers. An image in place over a dma-buf of those pages that the
/// device kept as its texture went, for the next texture over them (`HostMemory::with_dma_buf`),
/// goes in the call. The call is safe from any thread while other calls run on
/// others, a no-copy buffer's deallocator among them (the runtime holds no lock this call
/// takes while it runs a deallocator). It is cheap: with no no-copy buffer live it returns at
/// once, and otherwise it finds the buffers over the range by address, whether the range
@@ -615,11 +622,16 @@ impl Device {
pub(crate) fn host_range_remapped_now(&self, bytes: NonNull<u8>, length: u64) {
let start = bytes.as_ptr() as u64;
let shared = self.shared();
// The unit an import's pages round out to: an import by pointer over a page the call
// covers is taken anew at its next submission.
// The unit an import's pages round out to: the imports with a page the call covers are
// counted (`WorkCounts::host_imports_remapped`).
let unit = (shared.host_import.as_ref()).map_or(1, Importer::unit);
let imports = (shared.aliases).remapped(start, start.saturating_add(length), unit);
let end = start.saturating_add(length);
let imports = (shared.aliases).remapped(start, end, unit);
shared.counts.host_range_remapped(imports);
// The images parked over those pages go: a texture made over the new pages asks their
// source (`dma_buf/parked.rs`).
#[cfg(unix)]
shared.residency.remapped(start, end, unit);
}
/// A buffer of `length` zero bytes made as `made` says, for `call`: refused as
@@ -713,12 +725,21 @@ impl Device {
of_heap: bool,
drops_writes: bool,
) -> Result<Buffer, Error> {
let zero_from = memory.zero_from(length);
let parts = memory.into_parts();
let release = release.of(parts.pointer, length);
let made = (call, length, options, placement);
// SAFETY: the caller's contract.
unsafe {
self.buffer_over_host_parts(made, parts, release, of_heap, drops_writes, Naming::New)
self.buffer_over_host_parts(
made,
parts,
release,
of_heap,
drops_writes,
Naming::New,
zero_from,
)
}
}
@@ -727,7 +748,9 @@ impl Device {
/// `release`: a new buffer, or one its device's recovery carries to this generation
/// (`Buffer::carry`). A buffer's pages, a heap's own buffer's among them, keep what they were
/// made of, which a recovery makes the buffer again of ([`HostPages::made_of`]). A new `Managed` one on a
/// device without unified memory is two copies (`managed_copy.rs`).
/// device without unified memory is two copies (`managed_copy.rs`), its device copy zero from
/// `zero_from` where the caller promised its bytes read zero from there
/// (`HostMemory::with_zero_from`), which nothing else takes: the pages keep no such promise.
///
/// # Safety
///
@@ -740,6 +763,7 @@ impl Device {
of_heap: bool,
drops_writes: bool,
naming: Naming,
zero_from: Option<u64>,
) -> Result<Buffer, Error> {
let (call, length, options, _) = made;
let modes = Modes::of(options)?;
@@ -751,7 +775,7 @@ impl Device {
return Err(self.lost_refusal());
}
// SAFETY: the caller's contract.
return unsafe { self.two_copy_buffer(made, parts, release, naming) };
return unsafe { self.two_copy_buffer(made, parts, release, naming, zero_from) };
}
// SAFETY: the caller's contract.
unsafe { self.one_copy_buffer(made, parts, release, of_heap, drops_writes, naming) }
@@ -775,13 +799,7 @@ impl Device {
naming: Naming,
) -> Result<Buffer, Error> {
let modes = Modes::of(options)?;
let class = match modes.storage {
StorageMode::Shared => MemoryClass::Shared,
StorageMode::Managed => MemoryClass::Managed,
StorageMode::Private | StorageMode::Memoryless => {
return Err(invalid(call, Problem::StorageMode))
}
};
let class = host_class(call, modes)?;
if length == 0 || length > self.properties().max_buffer_length {
return Err(nil(call, Problem::BufferLength { length }));
}
@@ -1043,24 +1061,25 @@ impl Device {
// Whether the device was asked the pointer, or imports none, whose refusal a
// failed source leaves standing (the window takes it, and the memory is no
// dma-buf-only memory).
#[cfg(unix)]
let pointer_refused = host.by_pointer || host.pointerless;
let imported =
match unsafe { self.import_by_pointer(importer, pointer, length, host, class) }
{
Ok(Ok((buffer, memory))) => {
#[cfg(unix)]
let again = (!of_heap && !drops_writes)
.then(|| Again::pointer(self, pointer, (length, window, class)))
.flatten();
#[cfg(not(unix))]
let again = None;
Ok((buffer, memory, again))
}
// A heap's import is dedicated to nothing, as textures placed in the
// heap may be bound in its memory (`texture/heap.rs`); a buffer's own
// binds the buffer alone, its textures in place bound in imports of their
// own (`Device::dma_buf_image`).
// takes another buffer over part of its pages (`Device::bind_in_import`)
// and its textures in place only where the driver took it dedicated to
// nothing, else they are a copy or in imports of their own
// (`texture/in_place_image.rs`).
// SAFETY: as above.
#[cfg(unix)]
Ok(Err((source, refusal))) => unsafe {
let kept = (!of_heap, !of_heap);
let window = &window;
@@ -1083,6 +1102,9 @@ impl Device {
by_device,
)
}),
// No source of dma-bufs on this system.
#[cfg(not(unix))]
Ok(Err((source, _))) => match source {},
// The device's refusal of the pointer, with no source of dma-bufs of the
// pages to take instead.
Err(error) => {
@@ -1146,6 +1168,7 @@ impl Device {
offset: window.offset,
base: buffer.base,
length,
allocation: length,
reach: buffer.size - buffer.base,
modes,
address,
@@ -1155,7 +1178,6 @@ impl Device {
of_heap,
drops_writes,
mirror: None,
#[cfg(unix)]
again,
naming,
});
@@ -1224,7 +1246,10 @@ impl Device {
self.shared().deferred.lower_all();
let key = buffer.identity().key;
let encoded = || invalid(call, Problem::Rebind(RebindProblem::EncodedUses));
if self.rebind_pending(key) {
if let Some(refused) = self.rebind_pending(key) {
if let crate::rebind::Unreplaced::Unsubmitted = refused {
self.shared().counts.rebind_refused_unsubmitted();
}
return Err(encoded());
}
let shared = self.shared();
@@ -1528,6 +1553,7 @@ impl Device {
// The source is called with no lock of the runtime's held (`dma_buf.rs`):
// the textures over detached bytes are let go of meanwhile, and must be
// settled again after it.
#[cfg(unix)]
Ok(Err((source, refusal))) => {
let was_settled = settled.take().is_some();
// Kept by no descriptor; dedicated as a no-copy buffer's own import is
@@ -1579,6 +1605,9 @@ impl Device {
}
made
}
// No source of dma-bufs on this system.
#[cfg(not(unix))]
Ok(Err((source, _))) => match source {},
Err(failed) => Err(failed),
};
let (host, placement, remade, copied) = match imported {
@@ -1664,12 +1693,29 @@ impl Device {
// merged back from a copy of them.
pages.logged_as(key);
pages.copied_as(key);
// Refused where a hold refuses it, or where a call of an encoder the runtime may not
// encode again stays under way (`rebind::CallGate`): such a call reads the buffer wholly
// before the publish or wholly after it, never across it.
let (old, twins, again) = shared
.rebinds
.replace(key, cell, Arc::clone(&pages))
.map_err(|_| encoded())?;
// Its read twins over the old pages go, the rebinds' lock let go of (`LeftTwins`).
drop(twins);
.map_err(|refused| {
match refused {
crate::rebind::Unreplaced::Calls => {
shared.counts.rebind_refused_calls_in_flight();
}
crate::rebind::Unreplaced::Unsubmitted => {
shared.counts.rebind_refused_unsubmitted();
}
crate::rebind::Unreplaced::Held => {}
}
encoded()
})?;
// The publish is open from here to its close below, and as short as it can be: what lies
// over the bytes is made over the new pages, and nothing goes, nor any deallocator runs,
// until it closes (`rebind.rs`, **Other threads**).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
crate::rebind::pause::at(crate::rebind::pause::Point::Publishing, key);
// The buffer, or the heap's buffers, are reached unnamed again only once a command buffer
// uses it after the rebind, over the new pages.
shared.live_buffers.rebound(buffer, heap);
@@ -1729,9 +1775,19 @@ impl Device {
if rebound || !stood_in.is_empty() {
super::heap_sets::renew_over(self, key);
}
// Everything over the bytes is made over the new pages: the publish closes, marking the
// command buffers committed while it was open whose encoders named the buffer too.
let mut again = again;
for buffer in shared.rebinds.published(key) {
if !again.iter().any(|had| Arc::ptr_eq(had, &buffer)) {
again.push(buffer);
}
}
if !stood_in.is_empty() {
super::heap_sets::retire(self, Box::new(stood_in));
}
// Its read twins over the old pages go, the rebinds' lock let go of (`LeftTwins`).
drop(twins);
// The old pages go now where no command buffer holds them, their deallocator with them;
// the deallocator a detach held back runs now, inside the call, as Metal runs it at the
// replace (`HostCell::release_held_back`).
@@ -1855,7 +1911,11 @@ impl Device {
_ => not_importable(),
};
match source {
#[cfg(unix)]
Some(source) => Ok(Err((source, refusal))),
// No source of dma-bufs on this system.
#[cfg(not(unix))]
Some(source) => match source {},
None => Err(refusal),
}
}
@@ -1920,11 +1980,18 @@ impl Device {
/// The `VkBuffer` of a no-copy buffer of `length` bytes over `window`, whose pages all lie
/// inside those of `import`, a live import of the caller's pages (`host_aliases.rs`, "One
/// page, one import"), bound inside that import's memory where they lie, and its placement,
/// which holds the import: no import of its own, no pin and no gate. The import is kept
/// imported for good from now on (another buffer lies in its memory, `host_residency.rs`).
/// `None` where the buffer cannot be bound there exactly (its alignment, its memory types,
/// the imports of a buffer's own dma-bufs, whose memory is that buffer's alone, or the device
/// lost): the pages are then a copy, never a second import.
/// which holds the import: no import of its own, no pin and no gate. Once the buffer is bound
/// there, the import is kept imported for good (another buffer lies in its memory,
/// `host_residency.rs`); until then it is held as a blit's command holds it, so a releasable
/// import the buffer is not bound in stays releasable.
/// An import of dma-bufs takes it as an import of the pointer does where it is one
/// `VkDeviceMemory` dedicated to nothing (a no-copy buffer's own dma-buf, a piece of a shared
/// file's import, a guest RAM chunk's): the buffer is made for dma-bufs, the import's handle
/// type. `None` where the buffer cannot be bound there exactly (its alignment, its memory
/// types, an import of dma-bufs the driver took only dedicated to the buffer bound in it,
/// several bound to a sparse buffer, or a released import the device cannot import again):
/// the pages are then a copy, or, beside imports of dma-bufs alone, an import of their own
/// ([`Device::imports_beside`]).
///
/// # Safety
///
@@ -1938,15 +2005,18 @@ impl Device {
) -> Option<(HostBuffer, Placement)> {
let shared = self.shared();
let raw_device = shared.vk();
let pages = import.pages(ReadApart::Inside);
#[cfg(unix)]
if matches!(pages, ImportPages::StandIn(_)) {
return None;
}
// Held, imported again where released, only while the checks and the bind below read it,
// which leave a releasable import releasable: only a bound buffer exposes it (below).
let (pages, _) = import.blit_pages().ok()?;
let within = pages.placement();
// One dma-buf a buffer's own import made is dedicated to its `VkBuffer`
// (`VUID-vkBindBufferMemory-memory-01508`); a guest RAM chunk's import of one is not.
let dedicated = within.over_dma_buf() && !within.over_ram_chunk();
// A dma-buf import the driver took only dedicated to the buffer bound in it binds no other
// (`VUID-vkBindBufferMemory-memory-01508`); one dedicated to nothing binds any buffer made
// for its handle type (`VUID-vkBindBufferMemory-memory-02985`), as a guest RAM chunk's
// does. Several bound to a sparse buffer have no memory to bind in (below).
#[cfg(unix)]
let dedicated = (within.dma_buf_pages()).is_some_and(|pages| pages.dedicated_to_buffer());
#[cfg(not(unix))]
let dedicated = false;
let mapped = within.mapped.map(|mapped| mapped.as_ptr() as u64);
let (false, false, Some(mapped)) =
(dedicated, within.memory == vk::DeviceMemory::null(), mapped)
@@ -1969,6 +2039,8 @@ impl Device {
.map(|at| within.offset + into + at)
.filter(|at| at.is_multiple_of(requirements.alignment.max(1)))
.filter(|_| requirements.memory_type_bits & (1 << within.type_index()) != 0);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))]
let bound_at = bound_at.filter(|_| !BINDS_IN_IMPORTS_REFUSED.with(std::cell::Cell::get));
let start = NonNull::new(window.start as *mut u8);
let (Some(bound_at), Some(start)) = (bound_at, start) else {
// SAFETY: the buffer is unused.
@@ -1986,6 +2058,9 @@ impl Device {
unsafe { release::object(raw_device, buffer.raw) };
return None;
}
// Bound: the buffer reads the import's memory apart from blits while it lives, so the
// import stays imported for good from now on, still held here until it is.
import.expose(ReadApart::Inside);
let placement = Placement::in_import(
Arc::clone(import),
(within, handle),
@@ -2038,7 +2113,6 @@ impl Device {
/// the first was, over an import of the pages mapped at the pointer, the kept import's under
/// `HostMemory::new`'s contract. Refused as the first import may be, typed as the import
/// answers (out of memory among them), or with the device lost.
#[cfg(unix)]
pub(super) fn import_pointer_again(
&self,
pointer: NonNull<u8>,
@@ -2068,26 +2142,6 @@ impl Device {
))
}
/// No dma-buf is imported on this system: there is no source to call.
///
/// # Safety
///
/// None: it does nothing.
#[cfg(not(unix))]
unsafe fn import_from_source(
&self,
_call: &'static str,
_importer: &Importer,
_pointer: NonNull<u8>,
_length: u64,
_window: &ImportWindow,
source: Source,
_class: MemoryClass,
_keep: bool,
) -> Result<(HostBuffer, Placement, Option<std::convert::Infallible>), Error> {
match source {}
}
/// A copy of the `length` bytes at `pointer` for a rebind's new pages (`copied.rs`), laid out
/// as their import of `window` would be: a `VkBuffer` from the window's first page, the bytes
/// `window.offset` into it, in host-visible memory of the device's own, so the texel views
@@ -2485,6 +2539,7 @@ impl Device {
offset: 0,
base: 0,
length,
allocation: length,
reach: length,
modes,
address,
@@ -2494,7 +2549,6 @@ impl Device {
of_heap,
drops_writes: read_only,
mirror: None,
#[cfg(unix)]
again: None,
naming,
});
@@ -2687,6 +2741,21 @@ impl Device {
}
}
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))]
thread_local! {
/// Whether this thread's binds inside live imports are refused ([`refuse_binds_in_imports`]).
static BINDS_IN_IMPORTS_REFUSED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// A test hook, compiled into the crate's device tests on Linux alone: while `refused`, refuse
/// every bind of a no-copy buffer inside a live import that this thread asks
/// (`Device::bind_in_import`), as a requirement the import's memory misses refuses it, so a test
/// sees what a refused bind leaves of the import on any driver (`tests/pointer_residency.rs`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))]
pub(crate) fn refuse_binds_in_imports(refused: bool) {
BINDS_IN_IMPORTS_REFUSED.with(|cell| cell.set(refused));
}
/// `buffer`, the logs of the writes to its pages kept with them (`dirty_pages::PagesLog`), where
/// there are any, which hear of the GPU's writes through it where it lies in them in place; where
/// its pages are a copy, its key named to the copy, whose merges back compare it where a batch
@@ -2781,7 +2850,7 @@ fn routes_runs(drops_writes: bool) -> bool {
/// CPU's view of them as it was (an M3 Max under macOS 27.0.1, private and shared memory alike).
/// Pages whose write permission the caller vouched for (`vouched`, `HostMemory::assume_writable`)
/// are not asked about. Refused where the process's mappings cannot be asked
/// ([`refuse_unwritable`]); off Linux nothing is asked.
/// ([`refuse_unwritable`]); on Linux and Windows the system is asked, on macOS nothing.
fn unwritable_pages(host: &HostWindow, vouched: bool, counts: &Counters) -> Result<bool, Error> {
if vouched {
return Ok(false);
@@ -2793,6 +2862,17 @@ fn unwritable_pages(host: &HostWindow, vouched: bool, counts: &Counters) -> Resu
}
}
/// The memory class of a no-copy buffer or heap over the caller's bytes of `modes`' storage
/// mode, for `call`: `Shared` (whatever the CPU cache mode) or `Managed`; refused (`Invalid`,
/// `Problem::StorageMode`) for `Private` and `Memoryless`, as Metal stops them.
pub(super) fn host_class(call: &'static str, modes: Modes) -> Result<MemoryClass, Error> {
match modes.storage {
StorageMode::Shared => Ok(MemoryClass::Shared),
StorageMode::Managed => Ok(MemoryClass::Managed),
StorageMode::Private | StorageMode::Memoryless => Err(invalid(call, Problem::StorageMode)),
}
}
/// `options` of a no-copy buffer or heap over the caller's bytes without
/// [`ResourceOptions::PRIVATE_BIT`] and [`ResourceOptions::BIT_20`], and whether its memory drops the GPU's writes, as Metal's does
/// where the options set the bit: on macOS the runtime imports the pages through a read-only view
@@ -2885,6 +2965,7 @@ fn copies_after(error: &Error) -> bool {
/// of pages the kernel cannot pin ([`unpinnable`]) where the dma-bufs were refused too (no source
/// answered, or the device refused them), so the object is a copy of the pages as where no source
/// is given ([`copies_after`]); else `failed`, misuse and a lost device among it.
#[cfg(unix)]
fn source_failure(failed: Error, refusal: Error) -> Error {
match refused(&failed) && refusal == unpinnable() {
true => refusal,
+160 -75
View File
@@ -5,26 +5,33 @@
//! - **Metal's rules** decide which textures a buffer backs and where they lie in it
//! (`linear_plan.rs`); what Metal stops is refused `Invalid`, and an IOSurface plane past its
//! surface of a shape that keeps no tail (below), which Metal makes, `NotImplemented`.
//! - **Tails.** A 2D texture, an array or a texture buffer whose texels run past its buffer's
//! length, which plain Metal makes up to the buffer's allocation (`linear_plan.rs`'s
//! **Length**), and a colour texture of an IOSurface plane whose texels run past the buffer
//! standing for its surface (`linear_plan.rs`'s **Beyond the plane's rows**: announced
//! `SurfaceTexelsTail`), keep the texels' bytes past the length in a tail of their own
//! ([`Texels::past`]): a runtime `Shared` buffer of its bytes from the first to the last (a
//! texture buffer's from its functions' first, its offset rounded down to 16), zero when made.
//! Its texels inside the length are the buffer's bytes, as every texture's over a buffer are.
//! A 2D texture or array is a shadow image whose copies go through the tail, as a staging
//! buffer: in, the buffer's bytes inside the length into the tail and the tail into the image;
//! back, the image into the tail and the tail's rows inside the length into the buffer. A
//! texture buffer's bindings view the tail, as a staged texture buffer's view its staging
//! buffer, with the same copies in and back but the image. A merge back takes its current
//! bytes from both and gives them back to both (`shadow_merge.rs`). The CPU's `replace_region` and `get_bytes`, and a
//! blit's rows, take each row's bytes inside the length from the buffer and the rest from the
//! tail; a copy between such texels and an image goes through a scratch buffer of the
//! encoder, as those rows (`blit_texture.rs`). The tail's uses are the buffer's bytes past its
//! length, by the same key, so the tracker orders them as the texels' own. Metal's texels there
//! are the memory after the buffer's, another allocation's bytes (docs/API.md's accepted
//! differences); the tail answers every path alike and reaches no allocation but its own.
//! - **Tails.** A texture's texels lie in place up to the bytes its buffer's memory holds for
//! them ([`Texels::kept`], `Buffer::texel_reach`): Metal's allocation of a buffer of the
//! runtime's memory, which for one of at least 16 KiB the program makes in the Metal address
//! space is its length rounded up to 16 KiB, as long a `VkBuffer` and placement, zero when made
//! (`Device::placed_new_buffer`); a heap's buffer's heap to its end, Metal's texels there being
//! the heap's bytes; a no-copy buffer's length, past which its pages are the caller's. A 2D
//! texture, an array or a texture buffer whose texels run past those bytes, which plain Metal
//! makes up to the buffer's allocation (`linear_plan.rs`'s **Length**), and a colour texture of
//! an IOSurface plane whose texels run past the buffer standing for its surface
//! (`linear_plan.rs`'s **Beyond the plane's rows**: announced `SurfaceTexelsTail`), keep the
//! texels' bytes past them in a tail of their own ([`Texels::past`]): a runtime `Shared` buffer
//! of its bytes from the first to the last (a texture buffer's from its functions' first, its
//! offset rounded down to 16), zero when made. Its texels kept in place are the buffer's bytes,
//! as every texture's over a buffer are. A 2D texture or array is a shadow image whose copies
//! go through the tail, as a staging buffer: in, the buffer's bytes kept in place into the tail
//! and the tail into the image; back, the image into the tail and the tail's rows kept in place
//! into the buffer. A texture buffer's bindings view the tail, as a staged texture buffer's view
//! its staging buffer, with the same copies in and back but the image. A merge back takes its
//! current bytes from both and gives them back to both (`shadow_merge.rs`). The CPU's
//! `replace_region` and `get_bytes`, and a blit's rows, take each row's bytes kept in place
//! from the buffer and the rest from the tail; a copy between such texels and an image goes
//! through a scratch buffer of the encoder, as those rows (`blit_texture.rs`). The tail's uses
//! are the buffer's bytes past those kept in place, by the same key, so the tracker orders them
//! as the texels' own. Metal's texels there are memory past the buffer's own: a no-copy
//! buffer's caller pages, or the allocation Metal gives a buffer under 16 KiB (docs/API.md's
//! accepted differences); the tail answers every path alike and reaches no allocation but its
//! own.
//! - **Texture buffers** are the buffer's bytes ([`Texels`]), viewed as a texel buffer where a
//! function binds them: in the format the binding plan names, over the range it gives, made at
//! the first bind that needs it and kept with the texture. Their uses are uses of the buffer's
@@ -61,9 +68,9 @@ use super::host_backing::HostBacking;
use super::in_place::{Padding, PagesClass, RowEnds};
use super::key_hash::KeyMap;
use super::linear_plan::{
apart_from_plane, is_linear, plan_buffer_texture, plane_rows_share_bytes, BufferFacts,
BufferLayout, BufferRefusal, BufferTexture, BufferTextureCall, BufferTextureProblem, Placed,
LINEAR_ALIGNMENT,
apart_from_plane, is_linear, plan_buffer_texture, plane_rows_share_bytes, Allocation,
BufferFacts, BufferLayout, BufferRefusal, BufferTexture, BufferTextureCall,
BufferTextureProblem, Placed, LINEAR_ALIGNMENT, METAL_PAGE,
};
use super::resource::{Identity, ResourceKey};
use super::resource_ids::IdPlacement;
@@ -146,25 +153,30 @@ pub(super) struct Texels {
pub(super) objects: ObjectsToken,
/// The texels lie in an IOSurface's plane (`Buffer::new_texture_with_iosurface_plane`).
surface: bool,
/// The tail of a 2D texture, an array or a texture buffer whose texels run past the buffer's
/// length (`linear_plan.rs`'s **Length**), which holds the texels' bytes there: a runtime
/// `Shared` buffer of the bytes from the texels' first to their last, laid out as in the
/// buffer from its start (`Texels::tail_base`), zero when made. Its bytes inside the buffer's
/// length mirror the buffer's for the shadow's copies, which go through it
/// The tail of a 2D texture, an array or a texture buffer whose texels run past the bytes
/// they keep in place (`kept`; `linear_plan.rs`'s **Length**), which holds the texels' bytes
/// there: a runtime `Shared` buffer of the bytes from the texels' first to their last, laid
/// out as in the buffer from its start (`Texels::tail_base`), zero when made. Its bytes
/// before `kept` mirror the buffer's for the shadow's copies, which go through it
/// ([`Texels::shadow_copies`], `into_texture_buffer`); every other access to the texels (the
/// CPU's, a blit's rows) takes the bytes inside the length from the buffer and those past it
/// from here ([`Texels::past`]). `None` for texels inside their buffer.
/// CPU's, a blit's rows) takes the bytes kept in place from the buffer and those past them
/// from here ([`Texels::past`]). `None` for texels kept in place whole.
tail: Option<Buffer>,
/// Where the texels' bytes in place end: the buffer's length, but for a 2D array of more than
/// one slice over an IOSurface plane, whose slices past the first lie in the tail from their
/// first byte on (`linear_plan::Placed::kept`). The tail holds the texels' bytes from here.
/// Where the texels' bytes in place end: the bytes a texture over the buffer reaches in its
/// memory (`Buffer::texel_reach`: Metal's allocation of a buffer of its own, which for one
/// of at least 16 KiB runs past its length, a no-copy buffer's length, a heap's buffer's heap
/// to its end), but the buffer's length for an IOSurface plane's, and for a 2D array of more
/// than one slice over a plane, whose slices past the first lie in the tail from their first
/// byte on, that slice's first byte (`linear_plan::Placed::kept`). The tail holds the texels'
/// bytes from here.
kept: u64,
}
/// Where a texture's texels past its buffer's length lie ([`Texels::past`]): the buffer's bytes
/// from `length` on are the tail's, byte `v` of the buffer's space at `v - rebase` of the tail.
/// `length` is the buffer's own, but a 2D array's over an IOSurface plane whose slices past the
/// first lie in the tail ([`Texels::kept`]), where it is the second slice's first byte.
/// Where a texture's texels past the bytes they keep in place lie ([`Texels::past`]): the
/// buffer's bytes from `length` on are the tail's, byte `v` of the buffer's space at `v - rebase`
/// of the tail. `length` is where the texels in place end ([`Texels::kept`]): the bytes the
/// buffer's memory holds for them, its length for an IOSurface plane's, and a 2D array's over a
/// plane whose slices past the first lie in the tail, the second slice's first byte.
#[derive(Clone, Copy)]
pub(super) struct Past<'a> {
pub(super) tail: &'a Buffer,
@@ -433,13 +445,20 @@ impl Buffer {
/// Metal's validation stops it here.
///
/// A 2D texture or a texture buffer whose texels run past the buffer's length, which plain
/// Metal makes up to the buffer's `allocatedSize` (and answers nil past it, `Nil` with
/// `BufferTextureProblem::PastAllocation`), is made: its texels inside the length are the
/// buffer's bytes, and those past it lie in a tail the texture keeps, zero when made, which
/// its functions, blits and CPU calls read and write alike. Metal's texels there are the
/// memory after the buffer's, another allocation's bytes, which its writes there change
/// (docs/API.md's accepted differences). Such a 2D texture is a shadow image, announced
/// `shadowed-texture`; such a texture buffer's functions view its tail, announced
/// Metal makes while its last texel ends inside the buffer's allocation, counted from the
/// buffer's start (and answers nil past it, `Nil` with
/// `BufferTextureProblem::PastAllocation`): the buffer's `allocatedSize` (its length rounded
/// up to 16 KiB), a heap's buffer's heap's size, a no-copy buffer's pages (its pointer's
/// offset in its 16 KiB page plus its length, rounded up to 16 KiB), and no bound under
/// 16 KiB, is made. Its texels are the buffer's memory where that holds them: a buffer of at
/// least 16 KiB this device made holds its whole allocation, zero when made, and a heap's
/// buffer reaches the rest of its heap, so such a texture is made as one inside the length
/// is, its writes past the length landing in that memory as Metal's do. Past a no-copy
/// buffer's length, and past a shorter buffer's, its texels lie in a tail the texture keeps,
/// zero when made, which its functions, blits and CPU calls read and write alike; Metal's
/// texels there are the caller's pages, or memory past the buffer's own, which its writes
/// there change (docs/API.md's accepted differences). Such a 2D texture is a shadow image,
/// announced `shadowed-texture`; such a texture buffer's functions view its tail, announced
/// `staged-texture-buffer`.
pub fn new_texture(
&self,
@@ -489,10 +508,10 @@ impl Buffer {
/// before. The bytes-per-image argument is ignored, as plain Metal ignores it: its
/// validation alone asserts that it is a multiple of 128.
///
/// Refused as [`new_texture`](Self::new_texture) is; also an array whose slices end past the
/// buffer's `allocatedSize` (`Nil`, as Metal answers nil). An array whose texels run past the
/// buffer's length short of that is made as `new_texture` makes a 2D texture there, its
/// texels past the length in its tail.
/// Refused as [`new_texture`](Self::new_texture) is; an array counts its rounded slices
/// against the buffer's allocation, not its last texel (`Nil`, as Metal answers nil, once its
/// texels run past the length). An array whose texels run past the buffer's length short of
/// that is made as `new_texture` makes a 2D texture there.
pub fn new_linear_texture(
&self,
descriptor: &TextureDescriptor,
@@ -732,7 +751,8 @@ impl Buffer {
///
/// A plane of a 4:2:2 format (`GBGR422`, `BGRG422`: a CoreVideo `2vuy` or `yuvs` surface's)
/// is made as Metal makes it, 2 bytes a texel, copied as a 4:2:2 texture of the device's is
/// (`linear_plan.rs`).
/// (`linear_plan.rs`), and read through an image of its texels decoded from the pairs where
/// they lie (`texture/surface_pairs.rs`).
///
/// A two-plane YCbCr texture of 8 or 10 bits, converted (`YCBCR8_420_2P`,
/// `YCBCR10_444_2P`, ...), through the sRGB curve (their `_sRGB` twins) or read as codes
@@ -982,6 +1002,7 @@ impl Buffer {
let facts = OverFacts {
device: self.generation(),
length: self.length(),
allocation: self.allocation(),
detached: self.detached(),
options: self.resource_options(),
};
@@ -1073,7 +1094,7 @@ impl Buffer {
.with_options(options)
.over_surface(surface);
// Where it would lie: the route its making takes (`texture/route.rs`), with no tail
// made for texels past the buffer's length, which the route asks alone.
// made for texels past those kept in place, which the route asks alone.
if goal == Goal::Ask {
let past = texels.runs_past();
let asked = (descriptor, &layout);
@@ -1081,7 +1102,18 @@ impl Buffer {
let placement = (self.generation()).placement_over(call, bytes, asked, past)?;
return Ok(Over::Asked(placement));
}
// Texels past the buffer's length lie in a tail of their own (`linear_plan.rs`).
// A 4:2:2 texture is an image of its texels, decoded from the pairs where they lie
// (`texture/surface_pairs.rs`), where they lie so.
if let Some(place) = self.generation().pairs_in_place(&texels, &layout) {
let texture = self
.generation()
.new_pairs_texture(call, texels, descriptor, &layout, id_use, place)?;
if placed.narrow {
self.degrade_narrow_rows(&layout, &placed);
}
return Ok(Over::Made(texture));
}
// Texels past those kept in place lie in a tail of their own (the module's **Tails**).
let texels = texels.with_tail()?;
let tail = surface && texels.tail.is_some();
let texture = self
@@ -1175,11 +1207,14 @@ impl Device {
return Err(nil(call, Problem::BufferLength { length }));
}
plane.refuse_client_direction()?;
// A no-copy buffer made over the pages: of its length, its bytes in pages, its options
// never read (an IOSurface plane's texture takes its descriptor's).
// A no-copy buffer made over the pages: of its length, its bytes in pages from `start`,
// its options never read (an IOSurface plane's texture takes its descriptor's).
let facts = OverFacts {
device: self,
length,
allocation: Allocation::Pages {
page_offset: start % METAL_PAGE,
},
detached: false,
options: ResourceOptions::default(),
};
@@ -1221,13 +1256,15 @@ impl Device {
}
/// What the making of a texture over a buffer's bytes reads of the buffer before its bytes,
/// pages or memory ([`shape_over`]): the generation it is made on, its length, whether its bytes
/// are detached (`detach.rs`), and its resource options, which a texture over its bytes takes (an
/// IOSurface plane's takes its descriptor's). A no-copy buffer not made yet has them too
/// pages or memory ([`shape_over`]): the generation it is made on, its length, what its
/// allocation is ([`Buffer::allocation`]), whether its bytes are detached (`detach.rs`), and its
/// resource options, which a texture over its bytes takes (an IOSurface plane's takes its
/// descriptor's). A no-copy buffer not made yet has them too
/// (`Device::host_pages_texture_placement`).
struct OverFacts<'a> {
device: &'a Device,
length: u64,
allocation: Allocation,
detached: bool,
options: ResourceOptions,
}
@@ -1267,7 +1304,8 @@ enum ShapeKind {
impl Shape {
/// Whether no image in place takes a texture of this shape, over any bytes
/// ([`TexturePlacement::OtherShape`]): a rotated texture, one apart from its plane, one of a
/// surface's two planes, a converted one and a texture buffer.
/// surface's two planes, a converted one (a 4:2:2 one's an image of its decoded texels,
/// `texture/surface_pairs.rs`) and a texture buffer.
fn other(&self) -> bool {
match &self.kind {
ShapeKind::Rotated { .. } | ShapeKind::Apart => true,
@@ -1276,6 +1314,7 @@ impl Shape {
} => {
alpha.is_some()
|| converted.is_some()
|| chroma_pairs::is_four_two_two(self.layout.pixel_format)
|| self.layout.texture_type == TextureType::TextureBuffer
}
}
@@ -1360,6 +1399,7 @@ fn shape_over(
}
let buffer = BufferFacts {
length: facts.length,
allocation: facts.allocation,
};
let planar = matches!(form, BufferTextureCall::IoSurfacePlane { planar: true });
let converted = match &ycbcr_surface {
@@ -1400,8 +1440,8 @@ fn shape_over(
// 4:2:2 one, which a plain run makes over a buffer (its validation asserts; probe 9
// `fmt.240`, `fmt.241`) and the runtime holds over none: its textures' carrier
// (`chroma_pairs.rs`) is an image of their own. An IOSurface plane's (a CoreVideo `2vuy` or
// `yuvs` surface's) is made, as Metal makes it, 2 bytes a texel in the carrier
// (`linear_plan.rs`).
// `yuvs` surface's) is made, as Metal makes it, 2 bytes a texel (`linear_plan.rs`), read
// through an image of its texels (`texture/surface_pairs.rs`).
let pf = layout.pixel_format;
let four_two_two = chroma_pairs::is_four_two_two(pf);
// A depth or stencil texture over a surface's plane (`linear_plan.rs` stops every other
@@ -1595,6 +1635,22 @@ pub(super) fn rotated_rows(texture: &BufferTexture) -> BufferLayout {
}
impl Buffer {
/// What holds the buffer's bytes, as Metal's bound on a texture over it reads it
/// (`linear_plan.rs`'s **Length**): a heap's buffer its heap's size; a no-copy buffer (in its
/// pages, copied, two copies or detached) its pointer's offset in its 16 KiB page, which
/// [`contents`](Buffer::contents) answers in every form; any other its own memory.
fn allocation(&self) -> Allocation {
if let Some(heap) = self.heap() {
return Allocation::Heap { size: heap.size() };
}
match (self.host_backing(), self.contents()) {
(Some(_), Some(pointer)) => Allocation::Pages {
page_offset: pointer.as_ptr() as u64 % METAL_PAGE,
},
_ => Allocation::Own,
}
}
/// Announce `NarrowSurfaceRows` for an IOSurface plane of `layout` placed as `placed`, once
/// it is made (`linear_plan.rs`).
fn degrade_narrow_rows(&self, layout: &TextureLayout, placed: &Placed) {
@@ -1979,6 +2035,7 @@ impl Texels {
tracked: self.tracked(),
drops_writes: false,
levels: None,
decode: Default::default(),
backing: self.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
@@ -2086,7 +2143,7 @@ impl Texels {
/// without the declaration a plane's padding is kept.
pub(super) fn padding_owned(&self) -> bool {
let unobserved = self.buffer.padding_unobserved();
owns_padding(&self.layout, self.surface, unobserved, self.buffer.length())
owns_padding(&self.layout, self.surface, unobserved, self.kept)
}
/// The texture's resource options (the `options` field), its hazard tracking mode resolved.
@@ -2107,9 +2164,25 @@ impl Texels {
Texels { options, ..self }
}
/// These texels, in an IOSurface's plane where `surface`.
/// These texels, in an IOSurface's plane where `surface`: their bytes in place end at the
/// buffer's length, past which a plane's lie in its tail whatever the buffer's memory holds
/// (`linear_plan.rs`'s **Beyond the plane's rows**).
fn over_surface(self, surface: bool) -> Texels {
Texels { surface, ..self }
let kept = match surface {
true => self.kept.min(self.buffer.length()),
false => self.kept,
};
Texels {
surface,
kept,
..self
}
}
/// Where the texels' bytes in place end, in bytes of the buffer's space ([`Texels::kept`]):
/// those from here lie in their tail.
pub(super) fn kept(&self) -> u64 {
self.kept
}
/// Every byte of the buffer the texels lie in, for the GPU or the CPU: from the first to the
@@ -2124,10 +2197,10 @@ impl Texels {
}
}
/// Whether the texels lie in the buffer, or past its length in their tail (the module's
/// Whether the texels lie in the buffer's memory, or past it in their tail (the module's
/// **Tails**): every texture's but a rotated one's whose rows run past it (`rotated_rows`).
pub(super) fn reached(&self) -> bool {
self.tail.is_some() || self.span().end <= self.buffer.length()
self.tail.is_some() || self.span().end <= self.kept
}
/// Whether Metal's GPU reads and writes two of the texels' rows over bytes they share: an
@@ -2175,7 +2248,7 @@ impl Texels {
objects: ObjectsToken::default(),
surface: false,
tail: None,
kept: buffer.length(),
kept: buffer.texel_reach(),
buffer,
}
}
@@ -2266,8 +2339,9 @@ impl Texels {
/// device's `minTexelBufferOffsetAlignment`, which the binding plan holds a view's offset to,
/// divides the functions' offset in the buffer's `VkBuffer`; else through a staging buffer of
/// their own, at its start (a no-copy buffer's bytes, or Metal's offset, need not lie at a
/// multiple of it), and through their tail where they run past the buffer's length, which no
/// view of the buffer reaches. Refused as `new_buffer` refuses the staging buffer.
/// multiple of it), and through their tail where they run past the bytes they keep in place
/// ([`Texels::kept`]), which no view of the buffer reaches. Refused as `new_buffer` refuses
/// the staging buffer.
fn into_texture_buffer(self) -> Result<Texels, Error> {
let mut texels = self;
let placed = texels.layout;
@@ -2275,7 +2349,7 @@ impl Texels {
offset: placed.offset - placed.offset % LINEAR_ALIGNMENT,
..placed
};
// Texels past the buffer's length lie in a tail of their own (the module's **Tails**),
// Texels past those kept in place lie in a tail of their own (the module's **Tails**),
// which their bindings view, as a staging buffer's: no view of the buffer reaches them.
let mut texels = texels.with_tail()?;
let (raw, at) = (texels.buffer).at_for(texels.shader.offset, ReadApart::Texture);
@@ -2304,6 +2378,7 @@ impl Texels {
tracked: texels.tracked(),
drops_writes: false,
levels: None,
decode: Default::default(),
backing: texels.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
@@ -2314,7 +2389,7 @@ impl Texels {
texels.layout.offset,
limits.min_texel_buffer_offset_alignment,
);
let length = texels.buffer.length();
let kept = texels.kept;
texels
.buffer
.generation()
@@ -2322,8 +2397,9 @@ impl Texels {
let object = format!("texture buffer over a buffer at offset {offset}");
let reason = match past {
true => format!(
"its texels run past the buffer's {length} bytes, where no view of the \
buffer's VkBuffer reaches: those lie in a tail of the texture's own"
"its texels run past byte {kept} of the buffer, where its memory ends for \
them and no view of the buffer's VkBuffer reaches: those lie in a tail of \
the texture's own"
),
false => format!(
"its texels start at byte {at} of the buffer's VkBuffer, and the device \
@@ -2452,6 +2528,7 @@ impl Texels {
tracked: self.tracked(),
drops_writes: false,
levels: None,
decode: Default::default(),
backing: self.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
@@ -2531,12 +2608,18 @@ impl Texels {
/// What a binding plan reads of a texture buffer of `pixel_format` and `swizzle` over these
/// texels: the texels' offset in the `VkBuffer` its bindings view (`Texels::viewed`), which
/// the plan's view ranges address, and the swizzle a function's reads apply.
/// the plan's view ranges address, the swizzle a function's reads apply, and the texel buffer
/// views its texels take on the device (`bind::texel_buffer_parts`): past one where they
/// pass its `maxTexelBufferElements`, which a slot that reads them through their parts binds
/// (`bind::texel_parts`).
pub(super) fn bound(
&self,
pixel_format: PixelFormat,
swizzle: TextureSwizzleChannels,
) -> BoundTexture {
let device = self.buffer.generation();
let limits = device.compile_device().profile().limits();
let texels = self.shader.row_bytes / self.texel_bytes.max(1);
BoundTexture::Buffer {
pixel_format,
offset: self.viewed().1,
@@ -2544,6 +2627,7 @@ impl Texels {
bytes_per_row: self.shader.row_pitch,
resource_id: None,
swizzle,
parts: metal2vulkan::bind::texel_buffer_parts(limits, texels),
}
}
@@ -2705,9 +2789,10 @@ impl Texels {
.buffer
.mapped_contents()
.ok_or_else(|| invalid(call, Problem::Copy(CopyProblem::CpuAccessPrivate)))?;
// The texture lies in the buffer, and so do the rows of a region checked in its level.
// The texture lies in the buffer's memory, and so do the rows of a region checked in its
// level.
let end = len.and_then(|len| start.checked_add(len));
let Some(end) = end.filter(|&end| end <= self.buffer.length()) else {
let Some(end) = end.filter(|&end| end <= self.buffer.texel_reach()) else {
return Err(internal("a texture's rows past its buffer"));
};
// SAFETY: `start` lies in the buffer's mapped bytes (checked above).
@@ -2886,7 +2971,7 @@ pub(super) enum ViewUsage {
impl ViewUsage {
/// The usage a view of [`ViewUsage::Only`] names, or `None` for the buffer's.
fn named(self) -> Option<vk::BufferUsageFlags2KHR> {
pub(super) fn named(self) -> Option<vk::BufferUsageFlags2KHR> {
match self {
ViewUsage::Buffer => None,
ViewUsage::Only { storage: true } => {
@@ -31,10 +31,18 @@
//! the pairs through it (`bind::chroma_sample_module`), announced `decoded-texel-precision`
//! where a command first reads the twin. A texel reads the pair beside it, so a write's decode
//! is of whole rows (a host write of part of a row decodes its rows as the texture then holds
//! them). Refused: a
//! sparse heap's texture (`RuntimeGap::DecodedHeapTexture`). Without a twin (a heap's texture
//! over the caller's host pages or laid out apart from the heap's bytes) a command that binds
//! it for a read is refused.
//! them). A heap's texture, a shadow of the heap's bytes in Metal's rows (`texture/heap.rs`),
//! keeps a twin decoded whole after each copy in that moves its rows, through the device's
//! conversion where it converts the pairs, else Metal's decode. Refused: a sparse heap's texture
//! (`RuntimeGap::DecodedHeapTexture`). Only a heap's texture over the caller's host pages has
//! no twin: a command that binds it for a read is refused (`NotImplemented(Format)`, naming the
//! format: `binding_view.rs`).
//! - **Over a buffer's bytes** (an IOSurface plane's, `linear_plan.rs`): no carrier. The bytes
//! are the texture's truth, which its copies, blits and CPU calls move, and its reads and
//! samples present an `R8G8B8A8_UNORM` image of its texels alone, which each copy in writes from
//! the pairs where they lie, Metal's decode or the device's conversion as above
//! (`texture/surface_pairs.rs`), where they lie so; elsewhere it is held in the carrier, and a
//! read of it refused as a heap texture's without a twin is.
//! - **Through handles.** A function that reads texture handles from memory reaches such a
//! texture without a twin as a PVRTC carrier's (`pvrtc.rs`): the neutral texture, announced
//! once ([`Degradation::UnreadableHandleTexture`](super::degradation::Degradation)).
@@ -1571,6 +1571,35 @@ pub(crate) mod trace {
fails
}
/// The `VkQueue` the command buffer ran on and the host time, in nanoseconds, a completion
/// turn saw it complete (`finish`'s `seen`; 0 before): the completion latency's measurement
/// matches it to its queue waiter's steps (`tests::completion_latency`).
pub(crate) fn seen_of(command_buffer: &CommandBuffer) -> (usize, u64) {
let shared = &command_buffer.0;
let seen = crate::device::lock(&shared.state).times.completed;
(shared.queue.vk_queue(), seen)
}
/// The address of the shared part of the command buffer whose timestamps read unavailable
/// once, as a driver that dropped its work answers ([`unstamp_of`]).
static UNSTAMPED_OF: Mutex<Option<usize>> = Mutex::new(None);
/// The completion turn that reads `command_buffer`'s timestamps takes their availability as
/// 0, as where the driver dropped its work (`CommandBufferShared::read_stamps`); the work runs.
pub(crate) fn unstamp_of(command_buffer: &CommandBuffer) {
*UNSTAMPED_OF.lock().unwrap() = Some(Arc::as_ptr(&command_buffer.0).addr());
}
/// Whether `buffer`'s timestamps read unavailable so ([`unstamp_of`]), at most once.
pub(crate) fn unstamped(buffer: &CommandBufferShared) -> bool {
let mut armed = UNSTAMPED_OF.lock().unwrap();
let ours = Some(std::ptr::from_ref(buffer).addr()) == *armed;
if ours {
*armed = None;
}
ours
}
/// One step, its host time in nanoseconds of the host's clock (`gpu_time::host_nanos`).
#[derive(Clone, Copy, Debug)]
pub(crate) enum Traced {
@@ -1599,10 +1628,47 @@ pub(crate) mod trace {
/// Keep the steps from now on.
pub(crate) fn start() {
*LET_THROUGH.lock().unwrap() = None;
FINISHED_POSTS.lock().unwrap().clear();
STEPS.lock().unwrap().clear();
ON.store(true, Ordering::SeqCst);
}
/// How many batches that end their command buffers turns finished since [`start`]
/// ([`Traced::Finished`]), the steps kept.
pub(crate) fn finished_count() -> usize {
let steps = STEPS.lock().unwrap();
(steps.iter())
.filter(|step| matches!(step, Traced::Finished { .. }))
.count()
}
/// How many commits were posted to the scheduler since [`start`] (`Traced::Submitting`
/// "posted"), the steps kept.
pub(crate) fn posted_count() -> usize {
let steps = STEPS.lock().unwrap();
(steps.iter())
.filter(|step| matches!(step, Traced::Submitting { what: "posted", .. }))
.count()
}
/// Each transition to `Completed` or `Error` posted whole to its queue's context
/// (`CommandBufferShared::post_finished_transition`) since [`start`]: whether it went behind a
/// gate its submission handlers open, and the looks for a thread to run it its post made.
static FINISHED_POSTS: Mutex<Vec<(bool, u64)>> = Mutex::new(Vec::new());
/// Such a transition was posted, `gated` or not, with `serves` looks for a thread.
pub(crate) fn finished_posted(gated: bool, serves: u64) {
if ON.load(Ordering::Relaxed) {
FINISHED_POSTS.lock().unwrap().push((gated, serves));
}
}
/// The posts [`finished_posted`] kept since [`start`].
pub(crate) fn finished_posts() -> Vec<(bool, u64)> {
FINISHED_POSTS.lock().unwrap().clone()
}
/// Stop keeping steps, and the steps kept.
pub(crate) fn stop() -> Vec<Traced> {
ON.store(false, Ordering::SeqCst);
@@ -1664,10 +1730,17 @@ pub(crate) mod trace {
/// A steps' thread, once it recorded a host step, ended it and woke the scheduler's
/// thread (`scheduler/steps.rs`).
Stepped,
/// The scheduler's thread, once a pass that handed the submission handlers of the command
/// buffer a test names ([`hold_after_hand_off`]) to the device's handler threads let go
/// of the lock and counted out, before the pass's after-work (`scheduler::let_go`).
HandedOff,
/// A thread that committed with `commit_and_submit`, its commit posted, before its own
/// pass (`Scheduler::submit_at_commit`).
AtCommitPass,
}
/// Of each [`Point`]: whether a test holds threads there, and whether one reached it since.
static POINTS: Mutex<[(bool, bool); 8]> = Mutex::new([(false, false); 8]);
static POINTS: Mutex<[(bool, bool); 10]> = Mutex::new([(false, false); 10]);
static POINTS_CHANGED: std::sync::Condvar = std::sync::Condvar::new();
/// Hold every thread that reaches `point` from now on, until [`release`].
@@ -1690,6 +1763,35 @@ pub(crate) mod trace {
points[point as usize].1
}
/// The address of the shared part of the command buffer whose committing thread goes on from
/// [`Point::AtCommitPass`] while it is held ([`let_through`]).
static LET_THROUGH: Mutex<Option<usize>> = Mutex::new(None);
/// Let `command_buffer`'s committing thread go on from [`Point::AtCommitPass`], held there or
/// not yet, while every other stays held (`None`: none).
pub(crate) fn let_through(command_buffer: Option<&CommandBuffer>) {
*LET_THROUGH.lock().unwrap() = command_buffer.map(|it| Arc::as_ptr(&it.0).addr());
let _points = POINTS.lock().unwrap();
POINTS_CHANGED.notify_all();
}
/// A committing thread is at [`Point::AtCommitPass`] with `buffer`: held there while a test
/// holds it, unless the test lets `buffer`'s through ([`let_through`]).
pub(crate) fn at_commit_pass(buffer: &CommandBufferShared) {
let ours = std::ptr::from_ref(buffer).addr();
let point = Point::AtCommitPass as usize;
let mut points = POINTS.lock().unwrap();
if !points[point].0 {
return;
}
points[point].1 = true;
POINTS_CHANGED.notify_all();
let held = |points: &mut [(bool, bool); 10]| {
points[point].0 && *LET_THROUGH.lock().unwrap() != Some(ours)
};
drop(POINTS_CHANGED.wait_while(points, held));
}
/// A runtime thread is at `point`: held there while a test holds it.
pub(crate) fn at(point: Point) {
let mut points = POINTS.lock().unwrap();
@@ -1701,6 +1803,44 @@ pub(crate) mod trace {
drop(POINTS_CHANGED.wait_while(points, |points| points[point as usize].0));
}
/// The address of the shared part of the command buffer whose handed-off submission handlers
/// stop the scheduler's thread at [`Point::HandedOff`] ([`hold_after_hand_off`]).
static HAND_OFF_OF: Mutex<Option<usize>> = Mutex::new(None);
thread_local! {
/// The pass this thread makes handed off the submission handlers [`HAND_OFF_OF`] names.
static HANDED_OFF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// From now on, the scheduler's thread reaches [`Point::HandedOff`] after the pass that hands
/// `command_buffer`'s submission handlers to the device's handler threads (`None`: after no
/// pass): with the point held, a scheduler's thread held once it submitted that command
/// buffer, counted out, as it is while it runs the after-work of a pass.
pub(crate) fn hold_after_hand_off(command_buffer: Option<&CommandBuffer>) {
*HAND_OFF_OF.lock().unwrap() = command_buffer.map(|it| Arc::as_ptr(&it.0).addr());
}
/// The scheduler's thread hands `handed`'s submission handlers to the device's handler threads
/// (`scheduler::HandOff::post`), its lock held: noted where [`hold_after_hand_off`] named one.
pub(crate) fn handing_off(handed: &[Hold<CommandBufferShared>]) {
let armed = *HAND_OFF_OF.lock().unwrap();
let ours = |buffer: &Hold<CommandBufferShared>| {
let shared: &CommandBufferShared = buffer;
Some(std::ptr::from_ref(shared).addr()) == armed
};
if armed.is_some() && handed.iter().any(ours) {
HANDED_OFF.set(true);
}
}
/// The scheduler's thread let go of a pass's lock and counted out (`scheduler::let_go`): at
/// [`Point::HandedOff`] where that pass handed off what [`hold_after_hand_off`] named.
pub(crate) fn let_go() {
if HANDED_OFF.replace(false) {
at(Point::HandedOff);
}
}
/// Whether the completion turns wake the scheduler's thread for a met wait no more
/// ([`drop_completion_wakes`]).
static COMPLETION_WAKES_DROPPED: AtomicBool = AtomicBool::new(false);
@@ -370,6 +370,10 @@ impl State {
if !holds.is_empty() {
self.submitted_holds.push((group.end - 1, holds));
}
// Its last group is submitted: a rebind from here keeps the old pages for it.
if group.end == self.batches.all().len() {
self.held_to_submission.clear();
}
// The list changed since the commit: what it listed is listed again, a rebind having
// ended its use, and its resident set made of the list as it stands.
let changed = self
@@ -477,6 +481,10 @@ impl State {
&mut holds,
);
}
// Its last group is submitted: a rebind from here keeps the old pages for it.
if group.end == self.batches.all().len() {
self.held_to_submission.clear();
}
self.judged(&encoders, parts);
let failing = self.failing_submissions(&verdicts);
self.failing.extend(failing);
@@ -4,7 +4,8 @@
use super::{FailedEncoders, FailedSignals, Failure, State};
use crate::encoder::Overwrite;
use crate::encoder_fold::{Fold, FoldEnd, FoldOrder, Joining, Stashed};
use crate::encoder_fold::{Fold, FoldEnd, FoldOrder, Joining, Refusal, Stashed};
use crate::render_target::PassKey;
use crate::replay::Replay;
use crate::resource::ResourceKey;
use crate::tracker::Summary;
@@ -19,20 +20,38 @@ impl State {
/// the tail, which the encoder records into, and, where it is the group's second encoder, the
/// group's order built from its first part's summary (`Fold::order`). `None` where it joins
/// none, the group left in place: the encoder's open closes it once it opened
/// ([`close_fold`](Self::close_fold)). On a device that splits at aliases
/// ([`close_fold`](Self::close_fold)). A refusal is counted by its reason ([`Refusal`]): the
/// group's, or, where the tail holds none, why the encoder before left none
/// ([`unfolded`](Self::unfolded)); the command buffer's first encoder is refused nothing. On
/// a device that splits at aliases
/// (`alias_split.rs`), a render encoder whose pass records at its end joins as any encoder:
/// the first command it records into the tail at its end, where its pass or a draw of it uses
/// an image over bytes the group's earlier encoders wrote, goes in a new `VkCommandBuffer`.
pub(crate) fn join_fold(&mut self, joining: Joining, trail: bool) -> Option<Box<Fold>> {
let fold = self.fold.as_ref()?;
let joins = fold.admits(joining)
&& self.tail == Some(fold.tail)
&& self.batches.all().len() == fold.batches
&& !self.batches.signals_pending()
&& !self.predicated
&& self.protection.options() == 0
&& !trail;
if !joins {
pub(crate) fn join_fold(
&mut self,
joining: Joining,
trail: bool,
counts: &Counters,
) -> Option<Box<Fold>> {
let Some(fold) = self.fold.as_ref() else {
if let Some(why) = self.unfolded {
counts.fold_refused(why);
}
return None;
};
let refused = if !fold.admits(joining) {
Some(Refusal::Kind)
} else if self.tail != Some(fold.tail) {
Some(Refusal::Tail)
} else if self.batches.all().len() != fold.batches || self.batches.signals_pending() {
Some(Refusal::Batch)
} else if self.predicated || self.protection.options() != 0 || trail {
Some(Refusal::State)
} else {
None
};
if let Some(why) = refused {
counts.fold_refused(why);
return None;
}
// Its second encoder orders after its first part, as that part's end left it.
@@ -45,6 +64,67 @@ impl State {
if let Some(order) = order {
fold.order = order;
}
// It records into the tail outside any render pass instance (`encoder_fold.rs`'s
// **Continued passes**).
fold.end_open();
Some(fold)
}
/// What the render pass instance the group the tail holds left open renders, where it left
/// one (`encoder_fold.rs`'s **Continued passes**): what a render encoder opening now may
/// continue.
pub(crate) fn open_pass(&self) -> Option<PassKey> {
let fold = self.fold.as_ref()?;
let open = fold.open.as_ref()?;
(self.tail == Some(fold.tail)).then(|| open.key().clone())
}
/// The group whose tail holds the render pass instance `key` renders open, taken for the
/// encoder that continues it (`encoder_fold.rs`'s **Continued passes**), as
/// [`join_fold`](Self::join_fold) gives a joining encoder its group, its order noted
/// after the instance's draws so far: where the tail still holds that instance, the group
/// admits an encoder (its tail and batch, the command buffer's command predication and
/// protection options; the encoder trail is the caller's), and `writes` admits the group's
/// order (on a device that splits at aliases, where no image the encoder's pass uses meets
/// the bytes the group's encoders wrote: `AliasWrites::continues`; else nothing). `None` else,
/// the group left in place; one `writes` refused is counted as a split at aliases
/// (`WorkCounts::command_buffers_split_at_aliases`): the pass goes in a `VkCommandBuffer` of
/// its own.
pub(crate) fn continue_pass(
&mut self,
key: &PassKey,
counts: &Counters,
writes: impl FnOnce(&FoldOrder<ResourceKey>) -> bool,
) -> Option<Box<Fold>> {
let fold = self.fold.as_ref()?;
let open = fold.open.as_ref()?;
let admits = *open.key() == *key
&& self.tail == Some(fold.tail)
&& self.batches.all().len() == fold.batches
&& !self.batches.signals_pending()
&& !self.predicated
&& self.protection.options() == 0;
if !admits {
return None;
}
let order = match fold.members.len() {
1 => Some(FoldOrder::after(&self.recorded.get(fold.leader)?.summary)),
_ => None,
};
if !writes(order.as_ref().unwrap_or(&fold.order)) {
counts.command_buffer_split_at_aliases();
return None;
}
self.tail = None;
let mut fold = self.fold.take()?;
if let Some(order) = order {
fold.order = order;
}
fold.order.continued();
// The instance is the encoder's own from here: its pass holds it, and ends it or leaves
// it open again as it ends.
fold.open = None;
counts.render_pass_continued();
Some(fold)
}
@@ -61,18 +141,41 @@ impl State {
fold,
in_tail,
encoder,
plain,
ends,
summary,
log,
open,
} = end;
let may_lead = plain && !self.predicated && self.protection.options() == 0;
let leads = joining.filter(|_| may_lead);
// The group a render encoder that might have continued its open render pass instance
// kept, where it did not (`encoder_fold.rs`'s **Continued passes**), closes first.
let mut unkept = match fold.is_some() {
true => Vec::new(),
false => self.close_fold(counts),
};
// Why no group goes on past it, where none may.
self.unfolded = match (ends, joining) {
(Some(why), _) => Some(why),
(None, None) => Some(Refusal::State),
(None, Some(_)) if self.predicated || self.protection.options() != 0 => {
Some(Refusal::State)
}
(None, Some(_)) => None,
};
let leads = joining.filter(|_| self.unfolded.is_none());
let mut log = log.map(|(log, executions)| Stashed {
encoder,
log,
executions,
});
let mut unkept = Vec::new();
// The render pass instance it left open in its last `VkCommandBuffer`, the tail, goes on
// with its group, where the group goes on past it; else it ends here.
let mut open = match open {
Some(open) if Some(open.raw()) != self.tail => {
open.end();
None
}
open => open,
};
if let Some(mut fold) = fold {
fold.members.end = encoder + 1;
if let Some(record) = self.ended.get_mut(encoder) {
@@ -83,11 +186,12 @@ impl State {
if let (Some(joining), Some(summary), true) = (leads, &summary, goes_on) {
fold.went_on(joining, summary);
fold.batches = self.batches.all().len();
fold.open = open;
self.fold = Some(fold);
return unkept;
}
self.fold = Some(fold);
unkept = self.close_fold(counts);
unkept.extend(self.close_fold(counts));
}
match (leads, self.tail) {
(Some(joining), Some(tail)) => {
@@ -96,17 +200,25 @@ impl State {
record.in_tail = true;
}
let (leader, batches) = (self.recorded.len() - 1, self.batches.all().len());
// Its stash takes the room the command buffer's lists keep (`record_storage.rs`).
// Its stash takes the room the command buffer's lists keep (`spare_states.rs`).
let mut stashed = self.stash_room.take().unwrap_or_default();
stashed.extend(log);
let open = open.take();
self.fold = Some(Box::new(Fold::begun(
tail,
(leader, encoder),
(batches, joining),
stashed,
(stashed, open),
)));
}
_ => unkept.extend(log.map(|stashed| stashed.log)),
(Some(_), None) => {
self.unfolded = Some(Refusal::Tail);
unkept.extend(log.map(|stashed| stashed.log));
}
(None, _) => unkept.extend(log.map(|stashed| stashed.log)),
}
if let Some(open) = open {
open.end();
}
unkept
}
@@ -136,11 +248,12 @@ impl State {
/// commit, whose failure may split the group ([`split_failure`](Self::split_failure)). A lone
/// encoder's comes back, for the caller to give back to the device's spares without this lock
/// (`replay.rs`). A group of more gives the room of its stash back, emptied, for the next
/// group's (`record_storage.rs`).
/// group's (`spare_states.rs`).
pub(crate) fn close_fold(&mut self, counts: &Counters) -> Vec<Replay> {
let Some(fold) = self.fold.take() else {
let Some(mut fold) = self.fold.take() else {
return Vec::new();
};
fold.end_open();
let Fold {
members,
mut stashed,
@@ -12,28 +12,38 @@
//! completed handlers (`EventTimeline::signallers`). A batch of another queue's command buffer
//! that waits for one of those signals takes it as it is submitted, so its command buffer knows
//! whom it completes after.
//! - **Only where the signaller's transition leads its context.** Metal runs each queue's
//! transitions in their own context: while one of a queue's handlers blocks, another queue's
//! transitions go on (`contexts/mod.rs`). So a transition waits for the signaller's only where
//! the signaller's transition was posted to its context and no item there runs before it
//! ([`Follow::leads`]). An earlier command buffer of the signaller's queue whose waiters returned
//! runs nothing there any more, however long the host keeps the thread that ran it off the CPU:
//! a context is done with an item before the item's hold of its command buffer goes, which lets
//! those waiters return (`contexts/mod.rs`). That transition runs no code of the program's that
//! may block before its completed handlers, so the wait ends once a thread takes it and runs its
//! completion-seen handlers, and it holds no thread meanwhile: a gate in the waiting
//! transition's context (`contexts/lines.rs`). Behind any other item, the waiting transition
//! goes on, as Metal's does. The completion turns take the signaller's batch before the waiting one's
//! - **Only behind what blocks nothing.** Metal runs each queue's transitions in their own
//! context: while one of a queue's handlers blocks, another queue's transitions go on
//! (`contexts/mod.rs`). So a transition waits for the signaller's only where the signaller's
//! transition was posted to its context and nothing there before it may block
//! ([`Follow::leads`]): no item before it, nor what a thread runs there, runs a handler of the
//! program's but completion-seen handlers, which never block, or waits for one
//! (`Run::may_block`). An earlier command buffer's transition with no scheduled, submission or
//! completed handler left ends without the program, however long the host keeps the thread
//! that runs it off the CPU, so the waiting transition waits behind it: a program whose command
//! buffer waited on the GPU for another queue's never sees it complete while that one reads
//! short of `Completed` only because a host thread was slow. Its release of what it retained
//! may still run a deallocator of the program's (`program_objects.rs`), which the waiting
//! transition waits behind too. An earlier command buffer of the signaller's queue whose waiters
//! returned runs nothing there any more: a context is done with an item before the item's hold
//! of its command buffer goes, which lets those waiters return (`contexts/mod.rs`). The
//! signaller's transition runs no code of the program's that may block before its completed
//! handlers, so the wait ends once a thread takes it and runs its completion-seen handlers, and
//! it holds no thread meanwhile: a gate in the waiting transition's context
//! (`contexts/lines.rs`). Behind an item that may block, the waiting transition goes on, as
//! Metal's does. The completion turns take the signaller's batch before the waiting one's
//! (`completion.rs`), so the signaller's transition is posted by the time the waiting one's is.
//! - **Nothing of the signaller is held.** A [`Follow`] names its command buffer by address alone,
//! to pick out its transition among its context's items: the waiter that completes the follower
//! never holds the signaller's last reference, so never the device's.
//! Whether it leads is one look at its context's first item and first item that may block
//! (`Lines::leads`), however many items the context holds.
//! - **Nothing of the signaller is held.** A [`Follow`] names its command buffer's transition by
//! its place in its context alone: the waiter that completes the follower never holds the
//! signaller's last reference, so never the device's.
use super::super::contexts::Contexts;
use super::super::device::lock;
use super::super::event::EventShared;
use super::Item;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
/// The command buffer whose last batch's GPU signals another queue's command buffers may wait for,
@@ -42,15 +52,12 @@ use std::sync::{Arc, Mutex};
pub(crate) struct Follow {
/// Its queue's identity: its context's.
queue: u64,
/// Its address, which picks out its transition to `Completed` or `Error` among its context's
/// items (`Item::finishes`).
buffer: usize,
/// The gates of the transitions posted behind its own, each a context and a gate's token,
/// until its own reaches its completed handlers; `None` from then on.
gates: Mutex<Option<Vec<(u64, u64)>>>,
/// Its transition to `Completed` or `Error` was posted to its context, or ran
/// ([`Follow::posted`]): before then no item its context runs is it.
posted: AtomicBool,
/// The place its transition to `Completed` or `Error` took in its context as it was posted
/// ([`Follow::posted`], `Contexts::post`); 0 before then, and where it ran without a post.
at: AtomicU64,
}
/// What a command buffer's transition to `Completed` or `Error` lets go as it reaches its completed
@@ -63,13 +70,12 @@ pub(super) struct Release {
}
impl Follow {
/// The follow of the command buffer at `buffer`, of the queue `queue`.
pub(super) fn new(queue: u64, buffer: usize) -> Follow {
/// The follow of a command buffer of the queue `queue`.
pub(super) fn new(queue: u64) -> Follow {
Follow {
queue,
buffer,
gates: Mutex::new(Some(Vec::new())),
posted: AtomicBool::new(false),
at: AtomicU64::new(0),
}
}
@@ -78,22 +84,23 @@ impl Follow {
self.queue
}
/// Its transition to `Completed` or `Error` was posted to its context, or ran there.
pub(super) fn posted(&self) {
self.posted.store(true, Ordering::Release);
/// Its transition to `Completed` or `Error` was posted to its context, at the place `at`.
pub(super) fn posted(&self, at: u64) {
self.at.store(at, Ordering::Release);
}
/// Whether its transition to `Completed` or `Error` has not reached its completed handlers and
/// leads its context: it is there, and no item there runs before it.
/// leads its context: it was posted there, and nothing there before it may block.
pub(super) fn leads(&self, contexts: &Contexts<Item>) -> bool {
let gates = lock(&self.gates);
gates.is_some() && self.leads_its_context(contexts)
}
/// Whether its transition leads its context, where it has not reached its completed handlers.
/// Whether its transition leads its context, where it has not reached its completed handlers,
/// so is not done there.
fn leads_its_context(&self, contexts: &Contexts<Item>) -> bool {
let posted = self.posted.load(Ordering::Acquire);
contexts.leads(self.queue, |item| item.finishes(self.buffer), posted)
let at = self.at.load(Ordering::Acquire);
at > 0 && contexts.leads(self.queue, at)
}
/// Close `gate` of a transition of `queue`'s context until its own transition reaches its
@@ -83,8 +83,6 @@ struct GateState {
finished: bool,
/// The [`Hold`]s alive.
held: usize,
/// The threads blocked until it opens ([`Gate::awaited`]).
waiting: usize,
}
impl GateState {
@@ -117,13 +115,6 @@ impl Gate {
lock(&self.state).open()
}
/// Whether a thread is blocked until the gate opens, in [`wait`](Self::wait) or
/// [`wait_until`](Self::wait_until): what the thread that finishes the command buffer does
/// before its hold goes delays that thread's return.
pub(crate) fn awaited(&self) -> bool {
lock(&self.state).waiting > 0
}
/// Block until the gate opens, answering what the wait did ([`Waited`]). `Err` once the
/// process is exiting and it is not open: the runtime's threads that would open it end
/// (`exit_guard`).
@@ -135,7 +126,6 @@ impl Gate {
/// [`closed`](exit_guard::closed), or a test's own).
pub(crate) fn wait_unless(&self, exiting: impl Fn() -> bool) -> Result<Waited, Exiting> {
let mut state = lock(&self.state);
state.waiting += 1;
let mut did = Waited::default();
// Whether the sleep before this look ended at a notify rather than at its slice.
let mut notified = false;
@@ -155,7 +145,6 @@ impl Gate {
state = woke;
notified = !how.timed_out();
};
state.waiting -= 1;
waited
}
@@ -163,7 +152,6 @@ impl Gate {
/// at once once the process is exiting, as [`Gate::wait`].
pub(crate) fn wait_until(&self, deadline: Instant) -> Result<Waited, TimedOut> {
let mut state = lock(&self.state);
state.waiting += 1;
let mut did = Waited::default();
// Whether the sleep before this look ended at a notify rather than at its slice.
let mut notified = false;
@@ -184,7 +172,6 @@ impl Gate {
state = woke;
notified = !how.timed_out();
};
state.waiting -= 1;
waited
}
@@ -11,6 +11,14 @@
//! submits. Each command buffer of a group is exact on every driver by Vulkan's own rules (the
//! bullets below), so the check decides only where grouping pays.
//!
//! - **Marked under `CompletionPolicy::Exact`.** Under `Exact`, a batch waits here only where
//! its command buffer is marked to join the next ([`CommandBuffer::set_completion_joins_next`]);
//! the first batch of its `VkQueue` found ready behind such batches in the same pass that is not
//! marked may go last in their group (`CommandBufferShared::closes_groups`), and the group then
//! goes at once (`GroupEnd::Closed`), that batch's own signals ending it, so it is seen complete
//! at its own end and held back for nothing. No group is kept past its pass under `Exact`
//! ([`Group::keeps`], `Alone::Unkept`): a kept group may reach the GPU after the work ahead of
//! it ended, which would make the unmarked batch behind it complete later.
//! - **What waits.** A batch the scheduler submits waits here, submitted by nothing yet, where it
//! signals nothing but its queue's timeline and its events' semaphores: no binary semaphore,
//! no fence; binds no sparse update; does no first work; moves none of the caller's wrapped
@@ -25,6 +33,22 @@
//! be seen complete at that batch's end, however long, and kept, behind the batch the hold let
//! go meanwhile.
//! A group goes at once when it holds [`GROUP_BATCHES`], so no submission holds more.
//! - **Bounded by its expected run.** The driver runs a group as one kernel job, which a kernel's
//! job timeout ends as a whole: Linux's amdgpu ends one past 2 s by default, with no error the
//! device reports (`gpu_time.rs`), where each batch alone may finish within it. So a batch joins
//! only where its queue's expected GPU run is known and keeps the group's expected runs, summed,
//! within [`GROUP_RUN`] (16 ms): merging adds at most that much of the others' expected work to
//! any batch's job. The expected run follows the queue's command buffers' own GPU times as each
//! completes (`CommandBufferShared::place_gpu_times`), by their timestamps, which bracket their
//! own work alone, whatever other `VkDevice`s the GPU ran meanwhile; where the device answers GPU
//! times from the host (`DeviceOptions::gpu_times_from_host`), by those host times, which hold
//! other clients' work on the GPU too, so under contention there a queue's batches may stop
//! grouping. Otherwise the group goes first (`GroupEnd::Long`), and the batch leads the next
//! group where its own run is known and within the bound, else goes alone: a queue whose batches
//! none was seen complete yet, or whose recent ones ran longer, groups none until it has a run
//! within the bound. An expected run is a few recent batches' (raised at once by a longer one,
//! halved toward a shorter one), so a batch longer than its queue's recent ones may still join
//! a group; the others' expected runs it then carries stay within the bound.
//! - **Checked ahead.** A batch with submission checks is ready only once they ran
//! (`checks.rs`), which the scheduler does for each line's head; here it runs those of the
//! batches right behind a head that goes too, so a line of checked batches (the consumer checks
@@ -48,8 +72,9 @@
//! plan, its queue's value, the completed values its queue waited for) is changed as it is held,
//! so the next batch is planned after it. Where it ends its command buffer, on which no switch of
//! storage forms rides, the command buffer's kernel end and its transition to `Scheduled` come as
//! it is held, its submission handlers run before that on the scheduler's thread once its lock is
//! free, as a submitted batch's do ([`Group::schedule_held`]), as Metal schedules a command
//! it is held, its submission handlers run before that on the device's handler threads, which
//! the scheduler's thread hands them to as its pass goes on, as a submitted batch's
//! ([`Group::schedule_held`]), as Metal schedules a command
//! buffer committed behind running work at once: on an M3 Max under macOS 27.0.1, each of 8
//! committed behind a 55 ms kernel on its queue was `Scheduled` 0.04 to 0.18 ms after its commit,
//! its scheduled handler run, about 55 ms before that kernel ended (probe `scheduled`). Its queue
@@ -72,9 +97,11 @@
//! for one of its command buffers' completion (`CommandBuffer::wait_until_completed` marks it
//! and wakes the scheduler: [`CommandBufferShared::waits_for_completion`]). Nor is it kept
//! where the thread runs, once the pass ends, the submission handlers of a command buffer of
//! another logical queue (a batch held, or one submitted: `scheduler::holds_back_another_queue`):
//! it goes first, so no handler that waits for another queue's work holds that work back, as
//! Metal schedules one queue's command buffers whatever another queue's handler does (probe
//! another logical queue (a batch held, or one submitted, taken by a pass that settled a switch
//! of storage forms: `scheduler::holds_back_another_queue`; every other pass hands them to the
//! device's handler threads, where they hold back none of its passes): it goes first, so no
//! handler that waits for another queue's work holds that work back, as Metal schedules one
//! queue's command buffers whatever another queue's handler does (probe
//! `cross_queue_handler_waits`). The handlers of the batches' own queue keep it held: Metal
//! runs one queue's handlers one at a time, so a handler there that waits for a completed
//! handler of its own queue never sees it either (the probe's `scheduled-one-queue`). A group
@@ -95,17 +122,21 @@
//! `WorkCounts::groups_kept_pending`, `WorkCounts::groups_sent_for_waits`.
//! - **Counted by its end.** Each group held counts once by what sent it ([`GroupEnd`],
//! `WorkCounts::group_ends_full` and kin): so the consumer's counts say why its groups hold
//! fewer batches than they may.
//! fewer batches than they may. Each batch on a `VkQueue` whose batches group that goes in a
//! kernel submission of its own counts once by why ([`Alone`],
//! `WorkCounts::batches_alone_unshared` and kin): what refused it a place with no group held
//! (counted nowhere else), a committing thread's submission, or, where its group went holding
//! it alone, what sent that group; so the consumer's counts say why its batches did not group.
//! - **No allocation.** A group's submission names at most [`MOST_INFOS`] `VkSubmitInfo`s, built
//! in arrays on the thread's stack; its end's signals and its submissions go to lists the group
//! keeps with their room: the scheduler thread allocates nothing for it
//! (`runtime_lane::frame_costs`, `a_frame_s_commits_allocate_within_their_bound`).
use super::submit::Submission;
use super::{submission_error, CommandBufferShared};
use super::{submission_error, CommandBuffer, CommandBufferShared};
use crate::degradation::{Degradation, NoticesFor};
use crate::device::relay::Relayed;
use crate::error::CommandBufferError;
use crate::error::{invalid, CommandBufferError, Error, Problem};
use crate::exit_guard::{self, Call};
use crate::gpu_time;
use crate::submit_failure::{submit_failed, try_lock, Carried, Failed, TypeFlags};
@@ -119,6 +150,14 @@ use std::sync::Arc;
/// of at most this many less one.
pub(crate) const GROUP_BATCHES: usize = 4;
/// The most expected GPU run, in nanoseconds, of the batches one group holds, summed (the module
/// docs, "Bounded by its expected run"): 16 ms, the owner's line for an intolerable wait, which no
/// member's completion is then seen late by for the others' expected runs. It is 1/125 of the job
/// timeout Linux's amdgpu ends a kernel job at by default (2 s, its `lockup_timeout`, Linux 7.3.3),
/// past which a Radeon 780M's kernel ended a single command buffer of 3.2 s and dropped the one
/// behind it (`gpu_time.rs`).
pub(crate) const GROUP_RUN: u64 = 16_000_000;
/// The most `VkSubmitInfo`s a batch names: its work's and its finale's (`submit.rs`).
const BATCH_INFOS: usize = 2;
@@ -126,25 +165,113 @@ const BATCH_INFOS: usize = 2;
/// held, and for the batch after them its first work's beside its own.
const MOST_INFOS: usize = GROUP_BATCHES * BATCH_INFOS + 1 + BATCH_INFOS;
/// Whether `device`'s batches on `VkQueue` `queue` may wait in a group: its policy groups them,
/// its check found a submission that signals nothing merged into the next (the module docs),
/// the queue's failures are not relayed (each relayed batch takes a fence, `device/relay.rs`),
/// and its encoder trail is off (`encoder_trail.rs`: each batch goes alone).
pub(crate) fn groups(device: &Device, queue: usize) -> bool {
device.compile_device().policy().completion == CompletionPolicy::Grouped
&& device.submissions_merge_now()
/// Whether `device`'s batches on `VkQueue` `queue` may go to the driver in one kernel submission
/// at all: its check found a submission that signals nothing merged into the next (the module
/// docs), the queue's failures are not relayed (each relayed batch takes a fence,
/// `device/relay.rs`), and its encoder trail is off (`encoder_trail.rs`: each batch goes alone).
pub(crate) fn merges(device: &Device, queue: usize) -> bool {
device.submissions_merge_now()
&& device.shared().flights(queue).is_none()
// The encoder trail submits each batch alone (`encoder_trail.rs`).
&& !device.shared().encoder_trail
}
/// Whether every batch of `device`'s on `VkQueue` `queue` may wait in a group: its policy groups
/// them (`CompletionPolicy::Grouped`) and they merge ([`merges`]). Under `CompletionPolicy::Exact`
/// only a command buffer marked to join the next may (`CommandBufferShared::groups`).
pub(crate) fn groups(device: &Device, queue: usize) -> bool {
device.compile_device().policy().completion == CompletionPolicy::Grouped
&& merges(device, queue)
}
impl CommandBuffer {
/// Mark the command buffer's completion as joining the next one's: a runtime extension, no
/// Metal call (the crate's README, "Runtime extensions"). Metal has no counterpart; it reports
/// each command buffer complete at its own end. Under `CompletionPolicy::Exact`, on a device
/// whose batches merge (the device's check found one `vkQueueSubmit` of `VkSubmitInfo`s that
/// signal nothing to cost about one of its submissions, `Device::submissions_merge`; its
/// queue's failures not relayed), a batch of a marked command buffer may wait in the
/// scheduler's group as `CompletionPolicy::Grouped` lets every batch wait
/// (`command_buffer/group.rs`): up to four batches of one `VkQueue` found ready together go
/// in one kernel submission, only the last signalling. A batch of a command buffer not
/// marked never waits in a group, and is never held back for one: it may go last in the
/// group held before it, in the same pass and the same call, which then goes at once, and it
/// is seen complete at its own end, as alone. No group is kept past the pass that found it
/// under `Exact` (`CompletionPolicy::Grouped` keeps one while earlier work of its queue
/// runs), so no marked batch waits for later work to be committed.
///
/// What it delays: the marked command buffer is seen complete (its status, completed
/// handlers and waits), and the event values it signals are reached, once the last batch of
/// its kernel submission completed: late by the GPU time of the batches after it there, at
/// most three, never early and in commit order. Its submission waits for the next batch of
/// its queue found ready in the same pass of the scheduler, at most that pass. The
/// submission checks of the batches right behind it, the first one not marked among them, run
/// with its own, before its submission, so that they are found ready together; each still
/// runs once, in commit order, before its own batch's submission. Its commands, barriers and
/// GPU times are unchanged. The device announces `Degradation::GroupedCompletion` once, at its
/// first such submission.
///
/// It changes nothing where it cannot apply: under `CompletionPolicy::Grouped`, which groups
/// every batch already; on a device whose check did not find submissions merged, has not
/// answered, or relays its queues' failures (MoltenVK); with the encoder trail on; and for a
/// batch that groups in no case (it signals or waits for a binary semaphore, takes a fence,
/// binds a sparse update, does first work, or is an unshared queue's on a `VkQueue` other
/// queues' work is held back for it). Counted: `WorkCounts::grouped_submissions`,
/// `WorkCounts::batches_grouped`, `WorkCounts::group_ends_closed` and kin.
///
/// Refused, changing nothing, once the command buffer is committed (`Invalid`,
/// `Problem::AlreadyCommitted`).
pub fn set_completion_joins_next(&self, joins: bool) -> Result<(), Error> {
let state = self.state();
if state.enqueued() || state.committing {
return Err(invalid(
"set_completion_joins_next",
Problem::AlreadyCommitted,
));
}
match joins {
true => self.0.group_hold.fetch_or(JOINS_NEXT, Ordering::SeqCst),
false => self.0.group_hold.fetch_and(!JOINS_NEXT, Ordering::SeqCst),
};
Ok(())
}
}
impl CommandBufferShared {
/// Whether its batches may wait in a group ([`groups`]): never an unshared queue's on a
/// `VkQueue` other queues' work is held back from (the module docs).
/// Whether its batches may wait in a group: every batch where its queue's batches group
/// ([`groups`]), and under `CompletionPolicy::Exact` those of a command buffer marked to join
/// the next where they merge ([`merges`], [`CommandBuffer::set_completion_joins_next`]); never
/// an unshared queue's on a `VkQueue` other queues' work is held back from (the module docs).
pub(crate) fn groups(&self) -> bool {
let queue = self.queue.vk_queue();
groups(&self.device, queue)
&& !(self.queue.unshared() && self.device.holds_back_for_unshared(queue))
let may = match self.joins_next() {
true => merges(&self.device, queue),
false => groups(&self.device, queue),
};
may && self.not_held_apart(queue)
}
/// Whether a batch of it that waits in no group ([`groups`](Self::groups)) may still go last
/// in the group held before it on its `VkQueue`, which then goes at once: its batches merge
/// ([`merges`]), and it is no unshared queue's on a `VkQueue` other queues' work is held back
/// from. So under `CompletionPolicy::Exact` the command buffer right behind marked ones goes
/// in their kernel submission, seen complete at its own end
/// ([`CommandBuffer::set_completion_joins_next`]).
pub(crate) fn closes_groups(&self) -> bool {
let queue = self.queue.vk_queue();
merges(&self.device, queue) && self.not_held_apart(queue)
}
/// Whether it is not an unshared queue's on `VkQueue` `queue` while other queues' work is held
/// back there for it, whose batches never wait in a group (the module docs).
fn not_held_apart(&self, queue: usize) -> bool {
!(self.queue.unshared() && self.device.holds_back_for_unshared(queue))
}
/// Whether it is marked to join the next ([`CommandBuffer::set_completion_joins_next`]): set
/// before its commit, read after it.
fn joins_next(&self) -> bool {
self.group_hold.load(Ordering::SeqCst) & JOINS_NEXT != 0
}
/// Whether a committing thread submits a batch of it that may wait in a group
@@ -159,6 +286,13 @@ impl CommandBufferShared {
(self.device.shared().queues[self.queue.vk_queue()].pending_beyond_one()).is_none()
}
/// Whether a committing thread leaves its batches to the scheduler's thread, as its
/// `VkQueue`'s batches' `vkQueueSubmit` calls are slow (`device/submit_calls.rs`): read
/// without the queue's lock.
pub(crate) fn submits_slowly(&self) -> bool {
self.device.shared().submits_slowly(self.queue.vk_queue())
}
/// Its queue's identity: the logical queue its batches line up on in the scheduler's order
/// (`scheduler/order.rs`).
pub(crate) fn logical_queue(&self) -> u64 {
@@ -219,6 +353,17 @@ const IN_GROUP: u8 = 1;
/// A command buffer's `group_hold` bit: a thread waits for its completion.
const WAITED_FOR: u8 = 2;
/// A command buffer's `group_hold` bit: it is marked to join the next
/// ([`CommandBuffer::set_completion_joins_next`]).
const JOINS_NEXT: u8 = 4;
/// Whether a batch of expected run `run` (nanoseconds; `None` where its queue has none yet) may
/// join batches whose expected runs sum to `held`: its run is known and the sum stays within
/// [`GROUP_RUN`] (the module docs, "Bounded by its expected run").
pub(crate) fn within_run(held: u64, run: Option<u64>) -> bool {
run.is_some_and(|run| held.saturating_add(run) <= GROUP_RUN)
}
/// What sent a group held (`WorkCounts::group_ends_full` and kin).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum GroupEnd {
@@ -233,12 +378,78 @@ pub(crate) enum GroupEnd {
/// A batch that may join did first work or names a wrapped image: it went last in the group's
/// call.
FirstWork,
/// A batch that may otherwise join is of unknown length, or would take the group's expected
/// run past [`GROUP_RUN`].
Long,
/// The pass found no batch left to submit.
Drained,
/// The pass found none ready, with submission checks or host steps left for the thread to run.
Checks,
/// The pass found none ready, the rest held for events, gates, binary semaphores or decodes.
Held,
/// A batch of a command buffer not marked to join the next went last in it under
/// `CompletionPolicy::Exact` ([`CommandBuffer::set_completion_joins_next`]): it goes at once.
Closed,
}
/// Why a batch on a `VkQueue` whose batches group ([`groups`]) went in a kernel submission of its
/// own (`WorkCounts::batches_alone_unshared` and kin): each such batch counted once, by the first
/// reason that holds in this order. The first ten are batches that went with no group held and
/// were never held; the rest were held, and their group went holding them alone.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Alone {
/// An unshared queue's batch on a `VkQueue` other queues' work is held back from for it
/// (`unshared_hold.rs`), which never waits in a group (the module docs).
Unshared,
/// It waits for a binary semaphore (`encode_wait_for_vk_semaphore`, a sync file's wait).
BinaryWait,
/// It signals a binary semaphore (`encode_signal_vk_semaphore`, a completion sync file).
BinarySignal,
/// It binds a sparse update.
Sparse,
/// A segment cut its work into pieces, each a `VkSubmitInfo` of its own.
Pieced,
/// It ends its command buffer at a fence (`fences.rs`).
Fence,
/// Its queue's expected run is unknown: none of its command buffers was seen complete.
RunUnknown,
/// Its queue's expected run alone is past the group's bound.
RunLong,
/// It took the device's first work, staged copies or a fill, or names the caller's wrapped
/// image, with no group held: such a batch goes last in a group's call, never in a group.
FirstWork,
/// A committing thread submitted it alone, its `VkQueue` running at most one earlier
/// submission not seen complete (`CommandBufferShared::goes_alone_at_commit`).
AtCommit,
/// Held; the pass found no batch ready, and its `VkQueue` ran at most one earlier submission
/// not seen complete, so the group was not kept ([`Group::keeps`]).
OnePending,
/// Held; its `VkQueue` holds an unshared queue whose isolation holds other queues' work back
/// there, where no group is kept.
UnsharedHold,
/// Held; a head waited for the GPU (at its gate, or for a signal its checks wait for).
GpuWait,
/// Held; the thread ran another logical queue's submission handlers next.
Handlers,
/// Held; a thread waited for its command buffer's completion.
WaitedFor,
/// Held and kept while its queue ran earlier work, and no batch joined it before one
/// submission was left in flight.
Kept,
/// Held; a batch that may not join it came next: of another `VkQueue`, one refused, one
/// past the group's bound, or one that waits for a signal it holds.
SentByNext,
/// Held; a switch of storage forms rides on it, or the device was lost.
Other,
/// Held, of a command buffer marked to join the next under `CompletionPolicy::Exact`
/// ([`CommandBuffer::set_completion_joins_next`]); the pass found no batch ready, and no
/// group is kept under `Exact`.
Unkept,
}
impl Alone {
/// How many there are, for the counters' array.
pub(crate) const COUNT: usize = 19;
}
/// One `VkSubmitInfo`'s lists, kept with their room from batch to batch.
@@ -278,12 +489,14 @@ impl Info {
}
}
/// A batch held: its `VkSubmitInfo`s, how many command buffers they hold, and its submission,
/// published once the group is submitted.
/// A batch held: its `VkSubmitInfo`s, how many command buffers they hold, its submission,
/// published once the group is submitted, and its queue's expected run as it was held, in
/// nanoseconds.
struct Member {
infos: Vec<Info>,
buffers: usize,
submission: Submission,
run: u64,
}
/// The batches held for one kernel submission on one `VkQueue` (the module docs), in the
@@ -294,6 +507,9 @@ pub(crate) struct Group {
members: Vec<Member>,
/// It stayed held past a pass for the work its queue ran ([`keeps`](Group::keeps)).
kept: bool,
/// Its last batch held is of a command buffer not marked to join the next, under
/// `CompletionPolicy::Exact` ([`closed`](Group::closed)).
closed: bool,
/// The completed values `queue` waited for before the first batch held: put back where the
/// group's submission fails.
waited: Vec<u64>,
@@ -347,6 +563,12 @@ impl Group {
|| (joins && self.queue == queue && self.members.len() < GROUP_BATCHES)
}
/// Whether a batch of expected run `run` (nanoseconds; `None` where unknown) may wait in the
/// group as far as its run goes ([`within_run`]).
pub(crate) fn fits(&self, run: Option<u64>) -> bool {
within_run(self.members.iter().map(|member| member.run).sum(), run)
}
/// Whether a batch held signals the event of `semaphore` to `index` or above: only the group's
/// end meets a wait for it, so a batch with that wait goes after the group, in a submission
/// of its own (the module docs). A lower index was signalled before the group.
@@ -361,6 +583,13 @@ impl Group {
self.members.len() >= GROUP_BATCHES
}
/// Whether its last batch held is of a command buffer that waits in no group, which went last
/// in it ([`CommandBufferShared::closes_groups`]): the scheduler submits it at once, so that
/// batch is held back for nothing.
pub(crate) fn closed(&self) -> bool {
self.closed
}
/// A batch on `VkQueue` `queue` is held, before its submission changes the scheduler's
/// state: `waited` is what `queue` waited for so far, put back where the group's submission
/// fails. Its lists come once its changes are made ([`hold`](Group::hold)).
@@ -374,9 +603,16 @@ impl Group {
/// The batch [`open`](Group::open) took: its `VkSubmitInfo`s are `infos` (at most
/// [`BATCH_INFOS`]), with `buffers` command buffers, and its submission is published once the
/// group's is made. It signals each event's semaphore it names to its index, which the
/// group's end signals instead.
pub(crate) fn hold(&mut self, infos: &[InfoParts<'_>], buffers: usize, submission: Submission) {
/// group's is made; `run` its queue's expected run ([`fits`](Group::fits)). It signals each
/// event's semaphore it names to its index, which the group's end signals instead.
pub(crate) fn hold(
&mut self,
infos: &[InfoParts<'_>],
buffers: usize,
submission: Submission,
(run, closes): (u64, bool),
) {
self.closed = closes;
for (semaphore, index) in submission.event_signals() {
match self.events.iter_mut().find(|(held, ..)| *held == semaphore) {
Some((_, lowest, highest)) => {
@@ -395,6 +631,7 @@ impl Group {
infos: held,
buffers,
submission,
run,
});
}
@@ -414,31 +651,52 @@ impl Group {
/// device is not lost. The scheduler asks only where no handler it runs next is of another
/// logical queue's command buffer (the module docs).
/// The value of that queue's timeline whose completion leaves one submission in flight, for
/// the completion turns to wake the scheduler at. Counted once per group, and once more where
/// a waiter sends a group kept before.
pub(crate) fn keeps(&mut self) -> Option<u64> {
let first = self.members.first()?;
/// the completion turns to wake the scheduler at; else why it goes, for a group of one batch
/// ([`Alone`]). Counted once per group, and once more where a waiter sends a group kept
/// before.
pub(crate) fn keeps(&mut self) -> Result<u64, Alone> {
let Some(first) = self.members.first() else {
return Err(Alone::Other);
};
let device = first.submission.buffer().device();
if self.full()
|| device.is_lost()
|| (self.members.iter()).any(|member| member.submission.rides_forms())
|| device.holds_back_for_unshared(self.queue)
{
return None;
return Err(Alone::Other);
}
// Under `Exact` its batches are of command buffers marked to join the next, which wait for
// no later commit (`CommandBuffer::set_completion_joins_next`).
if device.compile_device().policy().completion != CompletionPolicy::Grouped {
return Err(Alone::Unkept);
}
if device.holds_back_for_unshared(self.queue) {
return Err(Alone::UnsharedHold);
}
let counts = &device.shared().counts;
if (self.members.iter()).any(|member| member.submission.buffer().is_waited_for()) {
if self.kept {
counts.group_sent_for_wait();
}
return None;
return Err(Alone::WaitedFor);
}
let value = device.shared().queues[self.queue].pending_beyond_one()?;
let Some(value) = device.shared().queues[self.queue].pending_beyond_one() else {
return Err(match self.kept {
true => Alone::Kept,
false => Alone::OnePending,
});
};
if !self.kept {
self.kept = true;
counts.group_kept_pending();
}
Some(value)
Ok(value)
}
/// Whether it holds exactly one batch: a group that goes so saves no kernel submission, and
/// its batch is counted by why it went alone ([`Alone`]).
pub(crate) fn holds_one(&self) -> bool {
self.members.len() == 1
}
/// Whether its `VkQueue` has not completed `value` yet, as the host saw ([`keeps`]'s value),
@@ -492,6 +750,7 @@ impl Group {
let count = self.members.len();
let alone = after.is_none();
self.kept = false;
self.closed = false;
let held_value = self.members[count - 1].submission.value();
// The held batches' end: each event's semaphore to the highest index a batch held
// signals it to, then the queue's timeline to the last one's value. It ends the
@@ -555,12 +814,16 @@ impl Group {
// executable and submitted once; every wait is for a signal submitted before; the one
// timeline signal is above the queue's value; the `VkQueue` is used under its lock.
let mut called = 0;
let submitted =
shared.submit_logged((queue, Some(value)), fence, &relayed, |vk_queue| unsafe {
let submitted = shared.submit_logged(
(queue, Some(value), buffers),
fence,
&relayed,
|vk_queue| unsafe {
shared.counts.queue_submitted(submits.len(), buffers);
called = gpu_time::host_nanos();
raw.queue_submit(vk_queue, submits, fence.unwrap_or(vk::Fence::null()))
});
},
);
// Where the device notes queue times, the call's return, for each command buffer a batch
// held ends (`CommandBuffer::submit_returned_time`).
let returned = shared.timing.queue_times().then(gpu_time::host_nanos);
@@ -671,11 +934,16 @@ fn submit_alone(device: &Device, after: After<'_>) -> Result<u64, vk::Result> {
} = after;
let mut called = 0;
// SAFETY: the batch's submission's own (`submit.rs`).
let submitted = shared.submit_logged((queue, Some(value)), fence, relayed, |vk_queue| unsafe {
shared.counts.queue_submitted(infos.len(), buffers);
called = gpu_time::host_nanos();
raw.queue_submit(vk_queue, infos, fence.unwrap_or(vk::Fence::null()))
});
let submitted = shared.submit_logged(
(queue, Some(value), buffers),
fence,
relayed,
|vk_queue| unsafe {
shared.counts.queue_submitted(infos.len(), buffers);
called = gpu_time::host_nanos();
raw.queue_submit(vk_queue, infos, fence.unwrap_or(vk::Fence::null()))
},
);
exit_guard::called(Call::QueueSubmit);
if let Err(result) = submitted {
let failed = Failed {
@@ -709,7 +977,7 @@ fn signal_alone(
// SAFETY: a submission of the signals a failed group's end held, each above its semaphore's
// value (no batch signalled them); the `VkQueue` is used under its lock.
let infos = [info];
let submitted = shared.submit_logged((queue, value), None, relayed, |vk_queue| unsafe {
let submitted = shared.submit_logged((queue, value, 0), None, relayed, |vk_queue| unsafe {
shared.counts.queue_submitted(1, 0);
raw.queue_submit(vk_queue, &infos, vk::Fence::null())
});
@@ -88,8 +88,9 @@ pub(crate) struct KeptBarriers {
/// The timestamps a barrier command buffer writes into a timed command buffer's slot of the
/// device's timestamp pools (`gpu_time::Slot`): with `start`, the slot reset before its barriers
/// and the start timestamp before them at the top of the pipe (the bottom where batches are
/// ordered by their ends: `batch_order.rs`), or with `after` after them at the bottom of the pipe;
/// and the start timestamp before them at the top of the pipe (`batch_order.rs`: where batches
/// are ordered by their ends, the earlier batch's end barrier holds it), or with `after` after them
/// at the bottom of the pipe;
/// with `end`, the end timestamp after them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SlotStamps {
@@ -396,13 +397,15 @@ impl KeptBarriers {
exit_guard::called(Call::CmdResetQueryPool);
}
if !stamps.after {
let stage = crate::batch_order::start_stage(shared.by_ends);
raw.cmd_write_timestamp(buffer, stage, stamps.queries, stamps.first);
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
raw.cmd_write_timestamp(buffer, top, stamps.queries, stamps.first);
exit_guard::called(Call::CmdWriteTimestamp);
}
}
// Of the queue's family: a copy engine's on the copy queue's `VkQueue`.
let reads = shared.memory_reads_of(queue);
for barrier in barriers {
barrier.record(raw, buffer);
barrier.record_reading(raw, buffer, reads);
exit_guard::called(Call::CmdPipelineBarrier);
}
if let Some(stamps) = stamps.filter(|stamps| stamps.start && stamps.after) {
File diff suppressed because it is too large. Load diff
@@ -13,9 +13,8 @@ pub(crate) enum Unlogged {
/// over host pages, a compute encoder that recorded a loop of command predication
/// (`predication.rs`), or one of a kind that logs none (a resource state encoder's).
NoCalls,
/// It left work for later that an encoding again does not record at once: a host step's (a
/// GPU-written indirect dispatch's, a scatter into a guest RAM staged through the CPU's,
/// `host_ram/copy.rs`), or a scrub's (`Segment::records_again`).
/// It left work for later that an encoding again does not record at once: a GPU-written
/// indirect dispatch's host step (`Segment::records_again`).
Segments,
/// The command buffer's failure fails it, or a fault of its own, as it commits.
Fails,
@@ -1,101 +0,0 @@
//! The storage of a command buffer's lists of what its encoders ended with, kept by its device
//! from one command buffer to the next: its ended encoders' records (`State::encoder_ended`), their
//! recordings (`State::end_encoder`), the logs of a group of encoders recorded into one
//! `VkCommandBuffer` its members did not keep (`encoder_fold.rs`'s `Fold`), and those held for its
//! commit (`fold.rs`). A command buffer starts on the latest storage a released one left, emptied
//! with its room kept, so its encoders' ends push into room the lists already had rather than
//! grow them one reallocation at a time over fresh pages; its release empties the lists and gives
//! their storage back ([`SpareRecordStorage`]). What the lists held goes as it went before, at the
//! release; only the room goes on, and only to command buffers of the same device.
use std::sync::Mutex;
use crate::device::lock;
use crate::encoder::Recorded;
use crate::encoder_fold::Stashed;
use crate::used_resources::EncoderRecord;
/// The storages a device keeps, at most: a command buffer made after another's release takes the
/// latest, so a program that makes one as one is released keeps one in use.
const SPARE_RECORD_STORAGES: usize = 2;
/// The room a kept storage's lists hold, at most, in bytes: a command buffer of more encoders
/// than that room holds lets its storage go. A command buffer of a few thousand one-dispatch
/// encoders fits.
const RECORD_STORAGE_BYTES: usize = 8 << 20;
/// The lists a command buffer keeps of what its encoders ended with, whose storage goes from one
/// command buffer of a device to the next (the module docs).
#[derive(Default)]
pub(crate) struct RecordStorage {
pub(super) ended: Vec<EncoderRecord>,
pub(super) recorded: Vec<Recorded>,
/// The storage the command buffer's next group of encoders stashes its members' logs in.
pub(super) stashed: Vec<Stashed>,
pub(super) held_logs: Vec<Stashed>,
}
impl RecordStorage {
/// The room its lists hold, each list's in entries.
pub(super) fn room(&self) -> Room {
Room([
self.ended.capacity(),
self.recorded.capacity(),
self.stashed.capacity(),
self.held_logs.capacity(),
])
}
/// The room its lists hold, in bytes.
fn bytes(&self) -> usize {
self.ended.capacity() * std::mem::size_of::<EncoderRecord>()
+ self.recorded.capacity() * std::mem::size_of::<Recorded>()
+ (self.stashed.capacity() + self.held_logs.capacity()) * std::mem::size_of::<Stashed>()
}
}
/// The room of each of a [`RecordStorage`]'s lists as a command buffer took it.
#[derive(Clone, Copy)]
pub(super) struct Room([usize; 4]);
impl Room {
/// How many of `storage`'s lists hold more room than this: those that grew since.
pub(super) fn grown(self, storage: &RecordStorage) -> u64 {
let Room(now) = storage.room();
let grown = (self.0.iter().zip(now)).filter(|&(&was, now)| now > was);
grown.count() as u64
}
}
/// A device's storages of the lists of records its released command buffers left, which the
/// command buffers it makes next start on (the module docs): at most [`SPARE_RECORD_STORAGES`],
/// each of at most [`RECORD_STORAGE_BYTES`], the latest given taken first.
#[derive(Default)]
pub(crate) struct SpareRecordStorage(Mutex<Vec<RecordStorage>>);
impl SpareRecordStorage {
/// The storage a command buffer being made starts on: the latest a released one gave back,
/// else lists of no room.
pub(super) fn take(&self) -> RecordStorage {
lock(&self.0).pop().unwrap_or_default()
}
/// Keep `storage`, a released command buffer's, emptied here (what its lists held goes) for
/// the next command buffer to start on, where its room is within [`RECORD_STORAGE_BYTES`]
/// and fewer than [`SPARE_RECORD_STORAGES`] are kept; else it goes. Whether it was kept.
pub(super) fn give(&self, mut storage: RecordStorage) -> bool {
storage.ended.clear();
storage.recorded.clear();
storage.stashed.clear();
storage.held_logs.clear();
if storage.bytes() > RECORD_STORAGE_BYTES {
return false;
}
let mut spare = lock(&self.0);
let keeps = spare.len() < SPARE_RECORD_STORAGES;
if keeps {
spare.push(storage);
}
keeps
}
}
@@ -127,7 +127,9 @@ impl CommandBufferShared {
/// its next group may go, and the scheduler looks again. Nothing here fails the rebind: an
/// encoder it cannot encode again, or work it cannot record on the GPU alone again, keeps its
/// first recording, which its group's submission fails. A command buffer that completed
/// encodes nothing again.
/// encodes nothing again. An encoder whose encoding again raced a rebind of a buffer it took
/// (`Taken::raced`, `rebind.rs`'s **Other threads**) is encoded again once no rebind's
/// publish is open (`Rebinds::wait_published`), until one does not race.
pub(crate) fn reencode(self: &Arc<Self>) {
let _for = self.notices_for();
let turn = lock(&self.reencoding);
@@ -135,6 +137,22 @@ impl CommandBufferShared {
if marked == 0 {
return;
}
while self.encode_moved() {
self.device.shared().rebinds.wait_published();
}
// Its next group's submission may go, unless a rebind marked it meanwhile: that rebind's
// turn comes next and encodes what moved since.
let _ = self
.reencode
.compare_exchange(marked, 0, Ordering::AcqRel, Ordering::Acquire);
drop(turn);
self.device.shared().scheduler.wake();
}
/// One turn of [`reencode`](Self::reencode), its caller holding the turn: each encoder that
/// moved encoded again and put in place, and the work on the GPU alone recorded again.
/// Whether an encoder it put in place raced a rebind as it was encoded again.
fn encode_moved(self: &Arc<Self>) -> bool {
let device = &self.device;
// The encoders of its event groups not submitted yet: those before were judged, and run
// over the pages they took.
@@ -392,13 +410,8 @@ impl CommandBufferShared {
}
}
drop(handle);
// Its next group's submission may go, unless a rebind marked it meanwhile: that rebind's
// turn comes next and encodes what moved since.
let _ = self
.reencode
.compare_exchange(marked, 0, Ordering::AcqRel, Ordering::Acquire);
drop(turn);
device.shared().scheduler.wake();
let state = lock(&self.state);
(spliced.iter()).any(|&at| state.ended[at].taken.raced())
}
/// Encode ended encoder `at` again from `replay`, its log, on the rebind's thread (the module
@@ -639,6 +652,7 @@ impl State {
|| segment.gpu_alone
|| segment.work.joins_a_run()
|| segment.work.recorded_by_an_encoding_again()
|| segment.work.left_again_by_an_encoding_again()
})
};
let unjudged = self.unjudged_parts();
@@ -667,9 +681,15 @@ impl State {
/// not since they were made (which goes, the encoding again having recorded those draws, or
/// left a segment of its own where it found them still being made), work its commit recorded
/// on the GPU alone, a run's merge (which
/// goes, the encoding again merging after itself, `pass_runs.rs`), or a staged gather (which
/// goes, the encoding again copying through the imports, `host_ram/copy.rs`), or its group
/// was submitted, or the command buffer completed.
/// goes, the encoding again merging after itself, `pass_runs.rs`), a staged gather (which
/// goes, the encoding again copying through the imports, or staging it again where the
/// imports would not copy it, `host_ram/copy.rs`), or a splice's or a merge on the host's CPU
/// part (which goes, the encoding again leaving its own over the new pages,
/// `shadow_splice.rs`), or a staged scatter's steps (which go, the encoding again staging it
/// again, `host_ram/copy.rs`), or a shadow's gated copy in (which goes, the encoding again
/// copying in for itself, `shadow::GatedCopyIn`), or a sparse texture's scrub (which goes, the
/// encoding again leaving its own, `sparse/emulated.rs`), or its group was submitted, or the
/// command buffer completed.
pub(super) fn splice_replay(
&mut self,
at: usize,
@@ -709,8 +729,9 @@ impl State {
recorded.raws = raws;
recorded.summary = summary;
// Its first segments go: the encoding again left a segment of its own in each
// pending dispatch's place, and its work on the GPU alone in segments of its own, and
// recorded each staged gather's copy at once.
// pending dispatch's, each splice's or merge on the host's, each staged copy step's it
// staged again, each gated copy in's and each scrub's place, and its work on the GPU
// alone in segments of its own, and recorded each other staged gather's copy at once.
// What the commit recorded of one stays retained, never submitted, as the first
// recording does.
for segment in recorded.segments.drain(..) {
@@ -848,13 +869,52 @@ impl State {
keys.dedup();
maps.sort_unstable();
maps.dedup();
let to_submission = self.unlogged_names_a_pin();
KeptReplays {
gone,
keys: keys.into_boxed_slice(),
maps: maps.into_boxed_slice(),
to_submission,
}
}
/// Whether an encoder that keeps no log, once its replays are kept ([`State::keep_replays`]),
/// named a buffer over host pages, by a command of its own or by work it left for later that
/// its commit did not record on the GPU alone: no rebind encodes or records that again, so the
/// command buffer holds its encoders' holds until its last event group is submitted
/// (`held_to_submission`), refusing a rebind meanwhile, which would fail that submission.
fn unlogged_names_a_pin(&self) -> bool {
// One its commit fails runs nothing whatever the rebind: it holds nothing past the commit.
let held =
|r: &super::EncoderRecord| r.replay.is_none() && r.unlogged != Some(Unlogged::Fails);
let unlogged = |at: usize| self.ended.get(at).is_some_and(held);
let own = (self.ended.iter()).any(|r| held(r) && r.taken.names_a_pin());
own || (self.recorded.iter())
.filter(|part| unlogged(part.encoder))
.flat_map(|part| &part.segments)
.filter(|segment| !segment.gpu_alone)
.filter_map(|segment| segment.recorded.as_ref())
.any(|done| done.taken.names_a_pin())
}
/// As it commits, once its replays are kept ([`State::keep_replays`]): whether an encoder a
/// call of which raced a rebind of a buffer it took (`Taken::raced`) is to be encoded again,
/// in the commit's call, before its first submission, its log kept. One that kept none keeps
/// its first recording, which that submission fails (`EncodedUseRebound`).
pub(super) fn raced_again(&self) -> bool {
(self.ended.iter()).any(|record| record.taken.raced() && record.replay.is_some())
}
/// As it commits, once its replays are kept: how many encoders a call of which raced a
/// rebind kept no log (`WorkCounts::encoders_raced_unreplayable`), each failing
/// `EncodedUseRebound` at its submission. None where every encoder that may keep none had its
/// calls gated (`rebind::CallGate`).
pub(super) fn raced_unreplayable(&self) -> usize {
(self.ended.iter())
.filter(|record| record.taken.raced() && record.replay.is_none())
.count()
}
/// As it commits, once its replays are kept ([`State::keep_replays`]): whether an encoder
/// whose pass took a rasterization-rate map since reset, before the commit, is to be encoded
/// again before its first submission, its log kept (`rate_mapped_pass.rs`); and why each that
@@ -884,6 +944,9 @@ pub(super) struct KeptReplays {
pub(super) keys: Box<[ResourceKey]>,
/// The identities of the rasterization-rate maps its encoders' passes are over.
pub(super) maps: Box<[usize]>,
/// An encoder that keeps no log named a buffer over host pages
/// (`State::unlogged_names_a_pin`): its holds stay until its last group's submission.
pub(super) to_submission: bool,
}
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -37,6 +37,17 @@
//! committed later on another queue that conflicts with the laying's uses waits behind it
//! (`CommandBufferShared::footprint`), as behind any host step. The batch's other segments step
//! once the check ends: they read what the laying leaves.
//! - **A rebind meanwhile** (`rebind.rs`). The check reads only the halt word, in the command
//! buffer's arena, and a laying that left no work apart is submitted again as it was encoded:
//! its command buffers name the pages of buffers over host pages that their first submission
//! took, which the command buffer holds until it completes, and the batch the check holds keeps
//! it from completing before the loop ends. So its commit holds none of those pages
//! (`Deferred::resolved_at_its_calls`): a rebind after that submission keeps the old pages for
//! every run again, as Metal's loop reads the pages its submission found, the loop's word
//! included; one before it fails that submission (`EncodedUseRebound`), its encoders keeping
//! no log to be encoded again from. Work apart is recorded again at each run, resolving the
//! buffers as they lie then, so a laying that left some holds every page its command buffer
//! used until it completes, and a rebind meanwhile is refused (`RebindProblem::EncodedUses`).
//! - **Ends.** As Metal's GPU runs a loop without bound on after the program let go of every
//! handle of its queue and its device, so does the thread, which holds the command buffer, and
//! through it the queue and the device. It stops only at a lost device, the GPU's recovery
@@ -204,6 +215,13 @@ impl LoopCheck {
self.from
}
/// Whether its laying left work apart, which each run again records again: a host step's
/// resolves the buffers its encoder named as it records, and work on the GPU alone records
/// over the buffers as they lie then (`Deferred::resolved_at_its_calls`).
pub(crate) fn leaves_work_apart(&self) -> bool {
(self.pieces.iter()).any(|piece| matches!(piece, Piece::Apart(_)))
}
/// At the commit, with its segments prepared: learn how each piece of work apart runs again
/// from the segment it left among `parts`, the laying's parts and those after it.
pub(crate) fn learn(&self, parts: &[Recorded]) {
@@ -471,7 +489,7 @@ pub(super) unsafe fn submit_fenced(
// SAFETY: the `VkQueue` is used under its lock; each command buffer is the caller's; the
// fence is unsignaled and in no pending submission.
let submitted = shared.submit_logged(
(queue, None),
(queue, None, raws.len()),
Some(fence),
&buffer.relayed,
|vk_queue| unsafe { raw.queue_submit(vk_queue, &submits, fence) },
@@ -0,0 +1,144 @@
//! The states of a device's released command buffers, kept for the command buffers it makes
//! next. A released command buffer's state is reset in place by the thread that releases it
//! ([`State::reset`]): what it held goes as it went before, at the release, and its lists of what
//! its encoders ended with (its ended encoders' records, their recordings, the logs of a group of
//! encoders recorded into one `VkCommandBuffer` its members did not keep, `encoder_fold.rs`'s
//! `Fold`, and those held for its commit, `fold.rs`) are emptied with their room kept. A command
//! buffer being made takes a kept state whole ([`SpareStates::take`]): its making neither
//! allocates nor fills one, and its encoders' ends push into room the lists already had rather
//! than grow them one reallocation at a time over fresh pages. A state goes on only to command
//! buffers of the device generation that made it, and the kept ones go with that generation.
use std::sync::atomic::AtomicU64;
use std::sync::{Arc, Mutex};
use super::State;
use crate::device::lock;
use crate::encoder::Recorded;
use crate::encoder_fold::Stashed;
use crate::used_resources::EncoderRecord;
/// The states a device keeps, at most: one per uncompleted command buffer of a queue of Metal's
/// default `maxCommandBufferCount`, so the releases of a queue's whole run of command buffers
/// serve the makings after them.
const SPARE_STATES: usize = 64;
/// The room a kept state's lists hold, at most, in bytes: a command buffer of more encoders than
/// that room holds lets its state go. A command buffer of a few thousand one-dispatch encoders
/// fits.
const STATE_ROOM_BYTES: usize = 8 << 20;
/// The room the kept states' lists hold together, at most, in bytes.
const SPARE_ROOM_BYTES: usize = 2 * STATE_ROOM_BYTES;
/// The room of each of a state's lists of records, in entries: its ended encoders' records, their
/// recordings, its stash of a group's logs and the logs it holds for its commit.
#[derive(Clone, Copy, Default)]
pub(super) struct Room(pub(super) [usize; 4]);
impl Room {
/// How many of the lists hold more room in `now` than in this: those that grew since.
pub(super) fn grown(self, now: Room) -> u64 {
let grown = (self.0.iter().zip(now.0)).filter(|&(&was, now)| now > was);
grown.count() as u64
}
/// The room, in bytes.
pub(super) fn bytes(self) -> usize {
let [ended, recorded, stashed, held_logs] = self.0;
ended * std::mem::size_of::<EncoderRecord>()
+ recorded * std::mem::size_of::<Recorded>()
+ (stashed + held_logs) * std::mem::size_of::<Stashed>()
}
}
/// A released command buffer's state, reset, as a device keeps it: the state, the revision its
/// parts that footprints are built from move (`Footprints::revision`), which the command buffer
/// that takes it builds its footprints against, and the room its lists hold, in bytes.
pub(super) struct KeptState {
pub(super) state: Arc<Mutex<State>>,
pub(super) revision: Arc<AtomicU64>,
bytes: usize,
}
impl KeptState {
/// `state`, reset, whose parts move `revision` and whose lists hold `room`.
pub(super) fn new(state: Arc<Mutex<State>>, revision: Arc<AtomicU64>, room: Room) -> KeptState {
KeptState {
state,
revision,
bytes: room.bytes(),
}
}
/// A state built for a command buffer being made, where the device keeps none: lists of no
/// room, under a revision of its own.
pub(super) fn fresh() -> KeptState {
let revision = Arc::default();
let state = Arc::new(Mutex::new(State::new(&revision)));
KeptState {
state,
revision,
bytes: 0,
}
}
}
/// A device's states of its released command buffers, which the command buffers it makes next
/// take (the module docs): at most [`SPARE_STATES`], whose lists hold at most
/// [`SPARE_ROOM_BYTES`] together and [`STATE_ROOM_BYTES`] each, the latest given taken first.
#[derive(Default)]
pub(crate) struct SpareStates(Mutex<Spare>);
/// What [`SpareStates`] holds.
#[derive(Default)]
struct Spare {
kept: Vec<KeptState>,
/// The room the kept states' lists hold, in bytes.
bytes: usize,
}
impl Spare {
/// Whether it has a place for a state whose lists hold `bytes`.
fn fits(&self, bytes: usize) -> bool {
bytes <= STATE_ROOM_BYTES
&& self.kept.len() < SPARE_STATES
&& self.bytes + bytes <= SPARE_ROOM_BYTES
}
}
impl SpareStates {
/// The state a command buffer being made takes: the latest a released one left, if any.
pub(super) fn take(&self) -> Option<KeptState> {
let mut spare = lock(&self.0);
let kept = spare.kept.pop()?;
spare.bytes -= kept.bytes;
Some(kept)
}
/// Whether it would keep a state whose lists hold `room` now: a released command buffer's
/// state is reset only where it would.
pub(super) fn wants(&self, room: Room) -> bool {
lock(&self.0).fits(room.bytes())
}
/// Keep `kept`, a released command buffer's state, reset, where it has a place for it; else
/// it goes with the command buffer. Whether it was kept.
pub(super) fn give(&self, kept: KeptState) -> bool {
let mut spare = lock(&self.0);
if !spare.fits(kept.bytes) {
return false;
}
spare.bytes += kept.bytes;
spare.kept.push(kept);
true
}
/// The states it keeps, and the room their lists hold, in bytes: a device test's
/// (`tests::spare_states`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn held(&self) -> (usize, usize) {
let spare = lock(&self.0);
(spare.kept.len(), spare.bytes)
}
}
@@ -159,7 +159,16 @@
//! ([`fences`](super::fences)), at which the command buffer then finishes.
//!
//! **GPU times** (`gpu_time.rs`). In a timed command buffer, the start timestamp is written at the
//! top of the pipe, before every barrier and encoder of its first batch: by its first encoder's
//! top of the pipe, before every barrier and encoder of its first batch. Where that batch has first
//! work (**New resources' first work**, above: zeros, moves, `Managed` copies in), the work's own
//! command buffer writes it first, after an execution barrier from every command before ("the
//! first synchronization scope includes all commands that occur earlier in submission order ...
//! the second synchronization scope includes all commands that occur later in submission order",
//! `vkCmdPipelineBarrier`), so the start follows every earlier command of the queue and precedes
//! the work, whose GPU time is the command buffer's: on an RX 7900 XTX, a command buffer's copies
//! in of the ranges `did_modify_range` named ran 4.5 to 36.5 ms before a start written after them.
//! (Whether Metal's span holds a `Managed` copy in on a Mac with a discrete GPU is not measured.)
//! Elsewhere it is written by its first encoder's
//! first command buffer, which wrote it into its slot's third query as it opened, where the batch
//! plans nothing before that encoder (no barrier, no image moved, and no
//! [`Barrier::after_completed`] where the driver stalls on semaphore operations) and the command
@@ -175,8 +184,10 @@
//! starts after that work ended, as Metal's does: on an M3 Max under macOS 27.0.1, a fill committed
//! behind a running fill of the same bytes started 0.5 to 0.9 us after the first's `GPUEndTime` (10
//! of 10), and one of other bytes while the first ran (probe `gpustart`). Where batches are ordered
//! by their ends (`batch_order.rs`), every start is written at the bottom of the pipe, as such a
//! driver starts no batch before the ones before it ended. The end of its last batch writes the end
//! by their ends (`batch_order.rs`), the end barrier of the batch before ([`Barrier::to_all`], all
//! commands to all commands) holds every start, at the top of the pipe, until the batches before it
//! ended, as such a driver starts no batch before them; one written at the bottom of the pipe there
//! read late on RADV. The end of its last batch writes the end
//! timestamp at the bottom of the pipe, after its barriers. The scheduler's host times as it begins
//! the first batch and ends the last submission are the kernel times.
//!
@@ -191,13 +202,18 @@
//! the hook before them.
//!
//! The submission of a command buffer's last batch, or its hold in a group (`group.rs`), leaves its
//! submission handlers to the submitting thread, once the scheduler's lock is free; its transition
//! to `Scheduled` waits for them.
//! submission handlers to the submitting thread: a committing thread runs them once the
//! scheduler's lock is free, and the scheduler's thread hands them to the device's handler
//! threads as its pass goes on (`scheduler/mod.rs`); its transition to `Scheduled` waits for
//! them.
//!
//! **No GPU work, no submission** ([`State::needs_no_gpu`]). A command buffer whose encoders
//! recorded nothing and whose one batch waits for and signals no event and no binary semaphore (so
//! presents no drawable) is taken, once it leads its logical queue's line, no group is held and
//! no first work of the device's waits (`texture/first_move.rs`), with no `vkQueueSubmit`: its batch is watched at its `VkQueue`'s last submitted value, so it
//! no first work of the device's waits but fills of the program's memory (`texture/first_move.rs`:
//! a new `Private` buffer's zeros, which only the GPU reads, and which a later batch or internal
//! submission takes before its commands), with no `vkQueueSubmit`: its batch is watched at its
//! `VkQueue`'s last submitted value, so it
//! completes in its queue's order, once the queue's work before it completed, or at once where the
//! queue has none in flight (`Completion::watch_unsubmitted`). Everything else its last batch's
//! taking does is done as for a submitted one: its kernel times, its scheduling (by a hang's
@@ -211,7 +227,7 @@
use super::completion::{Submitted, Waited};
use super::follow::{Follow, Release};
use super::gate::Hold;
use super::group::{After, GroupEnd, InfoParts};
use super::group::{After, Alone, GroupEnd, InfoParts};
use super::hang;
use super::kept_barriers::{KeptBarriers, SlotStamps};
use super::{lock, recording_error, submission_error, CommandBufferShared, State};
@@ -237,10 +253,10 @@ use crate::sparse::encoder::SparseUpdate;
use crate::submit_failure::{Carried, TypeFlags};
use crate::texture::decoded_twin::{SecondDecode, TwinWrite};
use crate::texture::faces::FaceFix;
use crate::texture::first_move::{last_of_each, FillTake};
use crate::texture::first_move::{last_of_each, Earlier, FillTake, Later};
use crate::texture::wrapped::Transition;
use crate::texture::Texture;
use crate::tracker::{Barrier, Point, Summary};
use crate::tracker::{Access, Barrier, Point, Summary};
use crate::used_resources::{EncoderKind, EncoderRecord};
use crate::work_counts::Begun;
use ash::vk;
@@ -473,28 +489,66 @@ impl CommandBufferShared {
// nothing changed, for the group to go first. Its event signals ride to the group's end;
// a wait for an event a batch held signals, which only that end meets, goes after it.
let met = (event_waits.iter()).any(|&wait| scheduler.group.meets(wait));
// Whether it may wait in a group, or else go last in the one held on its `VkQueue`, which
// then goes at once: under `CompletionPolicy::Exact`, a command buffer not marked to join
// the next behind marked ones (`CommandBuffer::set_completion_joins_next`), seen complete
// at its own end.
let holds = self.groups();
let closes = !holds
&& scheduler.group.holds()
&& scheduler.group.queue() == queue
&& self.closes_groups();
// A batch whose work a segment cut into pieces goes in a submission of its own, whose
// pieces are `VkSubmitInfo`s of their own (below).
let pieced = (state.recorded[state.batch_range(index)].iter())
.flat_map(|recorded| &recorded.segments)
.filter_map(|segment| segment.recorded.as_ref())
.any(|done| !done.piece_ends.is_empty());
let joins = {
// What refuses it a place in any group, of what it is (`group::Alone`), in the order its
// count takes: each read only where none before it refuses.
let refused = {
let sync = &state.batches.all()[index];
!alone
&& !pieced
&& self.groups()
&& !(last && super::fences::ends_at_fence(device, queue))
&& !met
&& sync.binary_waits.is_empty()
&& sync.binary_signals.is_empty()
&& (state.recorded[state.batch_range(index)].iter())
.all(|recorded| recorded.sparse.is_empty())
let sparse = || {
(state.recorded[state.batch_range(index)].iter())
.any(|recorded| !recorded.sparse.is_empty())
};
if !holds && !closes {
Some(Alone::Unshared)
} else if !sync.binary_waits.is_empty() {
Some(Alone::BinaryWait)
} else if !sync.binary_signals.is_empty() {
Some(Alone::BinarySignal)
} else if sparse() {
Some(Alone::Sparse)
} else if pieced {
Some(Alone::Pieced)
} else if last && super::fences::ends_at_fence(device, queue) {
Some(Alone::Fence)
} else {
None
}
};
let may_join = !alone && !met && refused.is_none();
// Its queue's expected GPU run: a batch of unknown length, or one that would take the
// group's past `GROUP_RUN`, joins none (`group.rs`).
let run = self.queue.group_run().nanos();
let fits = scheduler.group.fits(run);
let joins = may_join && fits;
// Where its `VkQueue`'s batches group at all, why it goes alone if it goes with no group
// held: what refuses it, or its run, else first work or a wrapped image (found below),
// else a committing thread's submission (`WorkCounts::batches_alone_unshared` and kin).
let counts_alone = super::group::groups(device, queue) || holds;
let alone_for = refused.or(match run {
None => Some(Alone::RunUnknown),
Some(_) if !fits => Some(Alone::RunLong),
Some(_) => None,
});
if !scheduler.group.admits(queue, joins) {
let end = match met {
true => GroupEnd::Wait,
false => GroupEnd::Apart,
let long = may_join && !fits && scheduler.group.queue() == queue;
let end = match (met, long) {
(true, _) => GroupEnd::Wait,
(false, true) => GroupEnd::Long,
(false, false) => GroupEnd::Apart,
};
return Ok(Submitting::AfterGroup(end));
}
@@ -524,16 +578,16 @@ impl CommandBufferShared {
let rebound = state.failing_at(device, index);
// One that needs no GPU work goes with no submission, in its queue's order (the module
// docs); behind a group held, it goes with the group as any batch that joins does, and
// where the device's first work waits, it carries it as any batch does: on a device with
// a fill queue, first work but the fills of the program's memory, which a batch whose
// commands name nothing leaves waiting (`texture/first_move.rs`, `FillTake::Reached`).
let fills_named_only = |key: ResourceKey| {
device.has_fill_queue() && crate::used_resources::owner_of(shared, key).is_some()
};
// where the device's first work waits, it carries it as any batch does, but the fills of
// the program's memory, which it leaves waiting: a later batch takes them before any of
// its commands (any batch on a device without a fill queue, one whose commands may reach
// them on a device with one: `texture/first_move.rs`, `FillTake`), and an internal
// submission takes every one.
let programs = |key: ResourceKey| crate::used_resources::owner_of(shared, key).is_some();
if !rebound
&& !scheduler.group.holds()
&& state.needs_no_gpu()
&& (shared.textures.first_moves).none_waiting_but(fills_named_only)
&& (shared.textures.first_moves).none_waiting_but(programs)
{
let taken = self.take_unsubmitted(&mut state, index, last, scheduler);
return Ok(Submitting::Submitted(taken));
@@ -636,6 +690,9 @@ impl CommandBufferShared {
// (`WorkCounts::batches_with_none_pending` and kin). A second read of the queue's value
// could see a completion the plan did not.
(shared.counts).batch_submitted_behind(scheduler.tracker.pending_before(at));
if self.queue.unshared() {
shared.counts.unshared_batch();
}
// One a hang's thread made `Scheduled` early began then (`hang.rs`).
if index == 0 && self.kernel.start() == 0 {
self.kernel.begin();
@@ -734,7 +791,13 @@ impl CommandBufferShared {
// moves' zeros go unrecorded (`texture/first_move.rs`).
let overwritten = first_overwrites(encoders, &state.ended);
let overwrites = |key: ResourceKey| overwritten.contains(&key);
let mut first_work = firsts.take_holding(|_| true, fill_take, hold, overwrites);
// A batch of a queue made for copies takes buffers' fills alone, which its family of
// transfers alone records: its commands name every buffer they reach and no image, and
// the moves and staged copies wait for the device's next submission elsewhere.
let mut first_work = match self.queue.for_copies() {
true => firsts.take_fills_alone(fill_take),
false => firsts.take_holding(|_| true, fill_take, hold, overwrites),
};
let every_fill = first_work.every_fill();
// What owns the memory of the first work it took, its fills for the fill queue among it.
let taken_owners = first_work.owners();
@@ -840,6 +903,14 @@ impl CommandBufferShared {
// module docs).
let by_barrier = shared.completed_by_barrier;
let mut completed_barrier = by_barrier.then(Barrier::after_completed);
// A first batch with first work (new resources' first moves and fills, copies in) writes
// the start in that work's command buffer, before the work, which runs in the batch's
// submission before its commands: the command buffer's GPU work begins there
// (**GPU times**, the module docs).
let first_start = start_stamp.filter(|_| first_work.has_first() || first_work.has_staged());
if first_start.is_some() {
start_stamp = None;
}
// The first encoder's prefix wrote the start where the batch plans nothing before that
// encoder (no barrier, no image moved, no barrier for completed work) and its first
// command buffer goes to the queue as recorded (`gpu_time.rs`): then no command buffer of
@@ -931,16 +1002,49 @@ impl CommandBufferShared {
// `WorkCounts::command_buffers_begun_batch_work`).
let has_first = first_work.has_first();
let has_staged = first_work.has_staged();
// First work of uploads alone takes no barrier from the commands before it, nor does the
// start written before it, where the device orders its batches by their ends and no
// internal submission may still run: the end of the batch before it on its `VkQueue`
// orders every command before it ahead of them (`first_move::Earlier::Ended`), and holds
// the start as it holds a first encoder's prefix's (`gpu_time.rs`). Read while the batch
// holds its place in the first work's order, which an internal submission takes before
// it is made, so none is made between this and the batch's submission.
let ended = shared.by_ends || unbarriered_forced(shared);
let earlier = match ended && first_work.uploads_only() && !shared.internal_running() {
true => Earlier::Ended,
false => Earlier::Barriered,
};
// And, on a device that orders its batches by their ends, no barrier to every later
// command after them, but to the batch's own commands' uses of the buffers they write
// (`first_move::Later::Batch`): the batch's end orders every later batch.
let later = match (earlier, shared.by_ends) {
(Earlier::Ended, true) => upload_readers(&state, start..end, first_work.upload_keys()),
_ => Later::All,
};
#[cfg(test)]
if let Later::Batch(stages, access) = later {
lock(&shared.upload_scopes).push((stages, access));
}
let recorded = (has_first || has_staged)
.then(|| {
self.record_raw(&mut state, |_, buffer| {
if let Some((queries, first, _)) = first_start {
// SAFETY: the command buffer is recording, outside a render pass, and is
// submitted first in the batch; the slot is the command buffer's, which
// only its batches write; with no barrier only after the end of the batch
// before (`Earlier::Ended`).
let barrier = earlier == Earlier::Barriered;
unsafe { record_first_start(shared, buffer, (queries, first), barrier) };
}
if has_first {
// SAFETY: the command buffer is recording, outside a render pass; it is
// submitted first in the batch, before any later one, and every batch on
// another `VkQueue` waits for the batch (`FirstMoves::waits`).
// another `VkQueue` waits for the batch (`FirstMoves::waits`); `earlier`
// as `Earlier::Ended` says (above).
unsafe {
let family = shared.queue_flags_of(queue);
first_work.record((raw, &shared.counts), buffer, family);
let order = (earlier, later);
first_work.record((raw, &shared.counts), buffer, family, order);
};
}
if has_staged {
@@ -1372,6 +1476,17 @@ impl CommandBufferShared {
false => GroupEnd::Wait,
};
shared.counts.group_ended(end);
} else if counts_alone {
let first = first_work.has_first()
|| first_work.has_staged()
|| filled.is_some()
|| !images.is_empty();
let why = (alone_for)
.or(first.then_some(Alone::FirstWork))
.or(alone.then_some(Alone::AtCommit));
if let Some(why) = why {
shared.counts.batch_alone(why);
}
}
// What the batch carried, for the line its failed submission logs
// (`submit_failure.rs`): read only once the call failed.
@@ -1515,11 +1630,12 @@ impl CommandBufferShared {
if prefixed {
shared.counts.prefixed_start();
}
// Its submission handlers run on this thread once the scheduler's lock is free, and a
// switch of storage forms riding on it ends there first (`scheduler/mod.rs`); its
// transition to `Scheduled`, posted as it is published or held, waits for them. One made
// `Scheduled` behind a host step ran them, or runs them, in that pass's turn: its flag
// stays as that pass left it.
// Its submission handlers run on a committing thread once the scheduler's lock is free,
// or on the device's handler threads, which the scheduler's thread hands them to; a
// switch of storage forms riding on it ends on the submitting thread first, which then
// runs them itself (`scheduler/mod.rs`). Its transition to `Scheduled`, posted as it is
// published or held, waits for them. One made `Scheduled` behind a host step ran them,
// or runs them, in that pass's turn: its flag stays as that pass left it.
let forms = last && state.storage_form.is_some();
let handlers = (schedules && !state.submission.is_empty()) || forms;
if !hang::scheduled_early(&state.hang_scheduling) {
@@ -1553,6 +1669,10 @@ impl CommandBufferShared {
state.retained.push(Box::new(held));
}
scheduler.values[queue] = at.value;
// A batch on the copy engine's `VkQueue` (`Device::new_command_queue_for_copies`).
if shared.copy_slot() == Some(queue) {
shared.counts.copy_queue_batch();
}
// Its command buffer's wait behind another command queue's batch there, from its first
// batch's submission or hold (`queue_wait.rs`).
let on = &shared.queues[queue];
@@ -1562,8 +1682,9 @@ impl CommandBufferShared {
});
let completed = || on.completed_value();
// Its place in the `VkQueue`'s flight, where an unshared queue holds it
// (`unshared_hold.rs`).
let flies = device.flies(queue, self.queue.unshared(), self.queue.expected());
// (`unshared_hold.rs`) or the device's queues take turns (`queue_turns.rs`).
let of = (self.queue.id(), self.queue.unshared());
let flies = device.flies(queue, of, self.queue.expected());
let taken = (at.value, self.queue.id(), flies);
(on.waits).taken(taken, first, completed, &shared.counts);
for image in &images {
@@ -1583,8 +1704,7 @@ impl CommandBufferShared {
// A last batch's signals name its command buffer, which another queue's command buffer
// that waits for one completes after; its transition to `Completed` lets them go
// (`follow.rs`).
let follow = (last && !kept.is_empty())
.then(|| Arc::new(Follow::new(self.queue.id(), Arc::as_ptr(self) as usize)));
let follow = (last && !kept.is_empty()).then(|| Arc::new(Follow::new(self.queue.id())));
for (event, signal, value) in &kept {
event.keep(
*signal,
@@ -1660,7 +1780,9 @@ impl CommandBufferShared {
(false, true) => &parts[..1],
(false, false) => &parts[..],
};
scheduler.group.hold(parts, buffers, submission);
scheduler
.group
.hold(parts, buffers, submission, (run.unwrap_or(0), closes));
Ok(Submitting::Grouped)
}
@@ -2173,13 +2295,15 @@ impl CommandBufferShared {
exit_guard::called(Call::CmdResetQueryPool);
}
if !stamps.after {
let stage = crate::batch_order::start_stage(device.shared().by_ends);
raw.cmd_write_timestamp(buffer, stage, queries, first);
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
raw.cmd_write_timestamp(buffer, top, queries, first);
exit_guard::called(Call::CmdWriteTimestamp);
}
}
// Of its queue's family: a copy engine's on a queue made for copies.
let reads = device.shared().memory_reads_of(self.queue.vk_queue());
for barrier in barriers {
barrier.record(raw, buffer);
barrier.record_reading(raw, buffer, reads);
exit_guard::called(Call::CmdPipelineBarrier);
}
if !transitions.is_empty() {
@@ -2226,6 +2350,97 @@ fn bind_error(device: &crate::Device, failure: BindFailure) -> CommandBufferErro
}
}
/// What a batch of `state`'s parts `parts` whose first work is uploads alone into the buffers
/// of `keys` makes that work visible to (`first_move::Later`): the stages and access types its
/// encoders' uses of those buffers name, joined; every later command where a command of the
/// command buffer may reach memory no use names, it binds a heap's set, its work may write
/// through its residency, an upload names no key (`None`), or the batch's uses name none of one
/// of them.
fn upload_readers(
state: &State,
parts: std::ops::Range<usize>,
keys: Option<Vec<ResourceKey>>,
) -> Later {
let Some(keys) = keys else {
return Later::All;
};
if state.reaches_unnamed || state.heaps.bound() || state.resident_writes.is_some() {
return Later::All;
}
let mut used = Access::NONE;
for key in keys {
let of_key = (state.recorded[parts.clone()].iter())
.flat_map(|part| part.summary.uses())
.filter(|used| used.key == key)
.fold(Access::NONE, |all, used| {
all.union(used.read).union(used.write)
});
if of_key.stages.is_empty() {
return Later::All;
}
used = used.union(of_key);
}
let (stages, access) = used.legacy();
Later::Batch(stages, access)
}
/// Whether a test forces first work of uploads alone to take no barrier from the commands before
/// it, the batches not ordered by their ends (`DeviceShared::uploads_unbarriered_forced`).
#[cfg(test)]
fn unbarriered_forced(shared: &crate::device::DeviceShared) -> bool {
(shared.uploads_unbarriered_forced).load(std::sync::atomic::Ordering::Relaxed)
}
/// No test forces it.
#[cfg(not(test))]
fn unbarriered_forced(_: &crate::device::DeviceShared) -> bool {
false
}
/// Record a first batch's start into `buffer`, the command buffer of its first work, before that
/// work: the reset of the slot's start and end where the device does not reset it on the host as
/// it is taken, where `barrier` an execution barrier from every command before to every command
/// after, then the start into query `first` of `queries` at the top of the pipe (**GPU times**,
/// the module docs).
///
/// # Safety
///
/// `buffer` is recording, outside a render pass, and is submitted first in its batch; the slot is
/// the command buffer's, which no other command buffer writes meanwhile; with no `barrier` only
/// where the end of the batch before it on its `VkQueue` orders every command before it
/// (`first_move::Earlier::Ended`).
unsafe fn record_first_start(
shared: &crate::device::DeviceShared,
buffer: vk::CommandBuffer,
(queries, first): (vk::QueryPool, u32),
barrier: bool,
) {
let raw = shared.vk();
let all = vk::PipelineStageFlags::ALL_COMMANDS;
// SAFETY: the caller's contract.
unsafe {
if !shared.timing.resets_on_host() {
raw.cmd_reset_query_pool(buffer, queries, first, 2);
exit_guard::called(Call::CmdResetQueryPool);
}
if barrier {
raw.cmd_pipeline_barrier(
buffer,
all,
all,
vk::DependencyFlags::empty(),
&[],
&[],
&[],
);
exit_guard::called(Call::CmdPipelineBarrier);
}
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
raw.cmd_write_timestamp(buffer, top, queries, first);
exit_guard::called(Call::CmdWriteTimestamp);
}
}
/// The timestamps a barrier command buffer writes into its command buffer's slot of the device's
/// timestamp pools, each the slot's pool, its first query and the holding's lease
/// (`gpu_time::Slot::lease`): the start (after resetting the slot) before its barriers at the top
File diff suppressed because it is too large. Load diff
+188 -41
View File
@@ -31,6 +31,21 @@
//! is made again, whole. The pipeline state's plan of a kept shape is found by identity first
//! (`ComputePipelineState::planned_for`), so a dispatch whose offsets alone moved compares no
//! shape at all, however many resources the encoder made resident.
//! - **One per pipeline state lately dispatched.** Beside the state its last dispatch brought in
//! place, the encoder sets aside the states of up to `live_bind::SET_ASIDE` (15) pipeline states
//! it dispatched before that one ([`LiveDispatch::select`]), each under the pipeline state whose
//! dispatch left it (held weakly), with its shape, what its table was read from, what its last
//! dispatch settled (`DispatchMemo`) and the commands it kept (`Instantiated`); a dispatch
//! starts from its pipeline state's, where one is set aside, as a render encoder's draw does
//! (`live_bind::start_from` chooses for both): dispatches that switch between pipeline states,
//! an encoder for each as a guest's are, each find their own state's shape kept, their table read
//! through their own interface, their commands kept while no value they may read moved, and,
//! within a command buffer, their own state's last settle (`WorkCounts::dispatches_from_set_aside`
//! and its split). Exact for the reason a dispatch's is: whichever state a dispatch starts from,
//! it brings every field in place, and a kept settle or kept commands are taken only under the
//! rules above. They go on with the state from one encoder to the next and to the device's
//! spares, as the state does, every one's memo let go or its sampler states unlisted where the
//! state's is.
//! - **Kept from one encoder to the next.** An encoder that ends leaves its state, with its shape,
//! to its command buffer's next compute encoder (**Parked in its command buffer**, below), and
//! the commit gives it to its device ([`SpareLiveDispatches`]), whose next compute encoder opened
@@ -88,10 +103,10 @@ use crate::encoder::{CoreBox, EncoderCore};
use crate::error::Error;
use crate::function_table::VisibleFunctionTable;
use crate::heap_sets;
use crate::live_bind::{Reshape, ValueKinds};
use crate::live_bind::{start_from, Reshape, Seat, ValueKinds, SET_ASIDE};
use crate::pipeline::{ComputePipelineState, WeakComputePipelineState};
use crate::pvrtc::ResidentUnreadable;
use crate::sampler::SamplerState;
use crate::sampler::ArgumentSamplers;
use crate::shadow::ResidentShadows;
use crate::work_counts::Counting;
@@ -104,8 +119,9 @@ const SPARE_LIVE_DISPATCHES: usize = 4;
#[derive(Default)]
pub(in crate::compute) struct LiveDispatch {
/// The state. Each dispatch that settles brings it to its own through [`Reshape`]
/// ([`refresh`](Self::refresh)).
pub(in crate::compute) state: BindState,
/// ([`refresh`](Self::refresh)). Boxed, so a dispatch of another pipeline state changes it
/// for one set aside by its address ([`select`](Self::select)).
pub(in crate::compute) state: Box<BindState>,
/// The state's shape, `None` where a change may have changed it.
shape: Option<Arc<BindShape>>,
/// The count of the device's sampler IDs' slots' changes (`DeviceShared::sampler_slots_changed`)
@@ -131,6 +147,38 @@ pub(in crate::compute) struct LiveDispatch {
/// The commands its last direct dispatch that instantiated made, while the state binds what
/// they read (`Instantiated`).
instantiated: Instantiated,
/// The pipeline state whose dispatch last brought the state in place
/// ([`select`](Self::select)), named without holding it; `None` before any did.
dispatched: Option<WeakComputePipelineState>,
/// The states the encoder's dispatches of other pipeline states brought in place, each as its
/// pipeline state's last dispatch left it ([`select`](Self::select)).
set_aside: [SetAside; SET_ASIDE],
/// How many times a state went aside: each set aside holds the count as it went, so the one
/// set aside longest holds the least.
asides: u64,
}
/// The bytes a state set aside takes beside its bind state's slots and lists, which grow with
/// what its dispatches bind: its own, and its bind state's box (read by
/// `tests::compute_set_aside`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) const SET_ASIDE_BYTES: usize =
std::mem::size_of::<SetAside>() + std::mem::size_of::<BindState>();
/// A bind state a [`LiveDispatch`] set aside, with what [`LiveDispatch`] holds of its last
/// dispatch's state beside it: its shape, its listing's count, what its table was read from, what
/// its last dispatch settled and the commands it kept, and the pipeline state that left it.
#[derive(Default)]
struct SetAside {
state: Box<BindState>,
shape: Option<Arc<BindShape>>,
listed_at: Option<u64>,
read_from: ReadFrom,
memo: DispatchMemo,
instantiated: Instantiated,
dispatched: Option<WeakComputePipelineState>,
/// [`LiveDispatch::asides`] as it went aside.
at: u64,
}
/// What a kept state's kernel table was read from at the dispatch that read it last
@@ -170,21 +218,82 @@ impl ReadFrom {
}
impl LiveDispatch {
/// Start a dispatch of `pipeline` from the state [`start_from`] picks (that pipeline state's
/// last dispatch left, where one is set aside): it and the state in place change places, and
/// the one it starts from it takes as `pipeline`'s. Whether it started from its pipeline
/// state's own state set aside. Exact whichever a dispatch starts from, as it brings every
/// field of the state in place (the module docs), so this chooses only what the dispatch may
/// keep and which reads it skips.
pub(in crate::compute) fn select(&mut self, pipeline: &ComputePipelineState) -> bool {
if self.dispatches(pipeline) {
return false;
}
let lives = |dispatched: &Option<WeakComputePipelineState>| {
(dispatched.as_ref()).is_some_and(WeakComputePipelineState::lives)
};
// A compute state's table is read through its own interface alone (`ReadFrom::reads`).
let in_place = Seat {
own: false,
lives: lives(&self.dispatched),
through: false,
at: 0,
};
let aside = self.set_aside.iter().map(|aside| Seat {
own: (aside.dispatched.as_ref()).is_some_and(|it| it.names(pipeline)),
lives: lives(&aside.dispatched),
through: false,
at: aside.at,
});
let from = start_from(in_place, aside);
let own = from.is_some_and(|at| {
let aside = &self.set_aside[at].dispatched;
aside.as_ref().is_some_and(|it| it.names(pipeline))
});
if let Some(at) = from {
self.swap_aside(at);
}
if !self.dispatches(pipeline) {
self.dispatched = Some(pipeline.downgrade());
}
own
}
/// Whether the state in place is the one `pipeline`'s last dispatch left, which a dispatch of
/// it starts from ([`select`](Self::select) keeps it).
fn dispatches(&self, pipeline: &ComputePipelineState) -> bool {
(self.dispatched.as_ref()).is_some_and(|it| it.names(pipeline))
}
/// Change the state in place for the one set aside at `at`.
fn swap_aside(&mut self, at: usize) {
self.asides += 1;
let aside = &mut self.set_aside[at];
std::mem::swap(&mut self.state, &mut aside.state);
std::mem::swap(&mut self.shape, &mut aside.shape);
std::mem::swap(&mut self.listed_at, &mut aside.listed_at);
std::mem::swap(&mut self.read_from, &mut aside.read_from);
std::mem::swap(&mut self.memo, &mut aside.memo);
std::mem::swap(&mut self.instantiated, &mut aside.instantiated);
std::mem::swap(&mut self.dispatched, &mut aside.dispatched);
aside.at = self.asides;
}
/// Bring the state to the one a dispatch of `tables` binds, in place (the module docs): the
/// kernel's table read as the pipeline state's interface reads it (a buffer where the kernel
/// reads a visible-function table reads as a null table: `ArgumentTable::refresh_reading`),
/// its samplers bound as `maps` binds them, its threadgroup memory lengths, the imageblock size
/// for a kernel with an explicit imageblock (one without plans with none, so its shape is the
/// one the executor computes for it), the stage-in region, the resources the encoder made
/// resident, `samplers` listed (the device's sampler states at `changed` changes of their
/// slots, those a variant's set-1 arrays hold alone where `trimmed`), and the live tables the
/// pipeline state made. Each change that may change the shape is noted, and the shape kept only
/// where none may have. The kinds of values it changed.
/// resident, the device's sampler states listed (those `samplers` took, which it takes where
/// the kept listing is not of every live state at `changed` changes of their slots:
/// `sampler::ArgumentSamplers`), and the live tables the pipeline state made. Each change that
/// may change the shape is noted, and the shape kept only where none may have. The kinds of
/// values it changed.
pub(in crate::compute) fn refresh(
&mut self,
tables: &DispatchTables<'_>,
maps: &SamplerMaps,
(changed, samplers, trimmed): (u64, &[SamplerState], bool),
(changed, samplers): (u64, &mut ArgumentSamplers),
function_tables: &[VisibleFunctionTable],
counts: Counting<'_>,
) -> ValueKinds {
@@ -210,7 +319,7 @@ impl LiveDispatch {
let kept = state.stages.entry(Stage::Kernel).or_default();
// Its slots that tell the view base alignment apart are as the state holds them
// (`AtBindViews::holds`): another table's offsets may have left some out since.
let views_held = views.holds(Stage::Kernel, kept.at_bind_views);
let views_held = views.holds(Stage::Kernel, kept);
let read_under = self.read_from.table.filter(|_| same && views_held);
if read_under == Some(table.stamp()) {
#[cfg(debug_assertions)]
@@ -251,13 +360,15 @@ impl LiveDispatch {
}
self.read_from.resident = Some(generation);
// Listed again only where the device's sampler states changed since: not where the
// listing kept is of every live state at the count of their slots' changes they were taken
// at; else they are compared state by state.
if trimmed || self.listed_at != Some(changed) {
if !heap_sets::lists(&state.argument_samplers, samplers) {
reshape.field(&mut state.argument_samplers, heap_sets::listed(samplers));
// listing kept is of every live state at the count of their slots' changes that holds;
// else they are taken and compared state by state.
let current = samplers.states().is_none() && self.listed_at == Some(changed);
if !current {
let states = samplers.take(tables.pipeline.generation());
if !heap_sets::lists(&state.argument_samplers, states) {
reshape.field(&mut state.argument_samplers, heap_sets::listed(states));
}
self.listed_at = (!trimmed).then_some(changed);
self.listed_at = samplers.listed_at();
}
let listed = function_tables
.iter()
@@ -271,7 +382,7 @@ impl LiveDispatch {
reshape.unshaped(&mut state.used_in_token_order, true);
reshape.unshaped(&mut state.resident_apart, true);
#[cfg(debug_assertions)]
self.check_whole(tables, maps, samplers, function_tables);
self.check_whole(tables, maps, samplers.states(), function_tables);
if reshape.may_reshape() {
self.shape = None;
}
@@ -283,16 +394,16 @@ impl LiveDispatch {
/// and parked (the module docs, **Parked in its command buffer**), serves a direct dispatch of
/// `tables` and `dispatch` at `counted` moves and sampler slot changes: it holds in every
/// input but its table's stamp (`DispatchMemo::holds_but_stamp`), and the table, read now with
/// its samplers' maps and `listing` (the device's sampler states at their count of changes),
/// brings in the very state it settled, no value of any kind changed, with the samplers' maps
/// it was settled with. Then it goes on under the table's stamp ([`Across::Taken`]). Where the
/// its samplers' maps and the device's sampler states `samplers` takes where it needs them
/// ([`refresh`](Self::refresh)), brings in the very state it settled, no value of any kind
/// changed, with the samplers' maps it was settled with. Then it goes on under the table's stamp ([`Across::Taken`]). Where the
/// entry holds but for the stamp, the state is brought in place either way, and a dispatch that
/// takes it not settles from the state as it lies ([`Across::Refreshed`]).
pub(in crate::compute) fn settled_across(
&mut self,
tables: &DispatchTables<'_>,
(dispatch, counted): (&Dispatch, (u64, u64)),
listing: (u64, &[SamplerState]),
samplers: &mut ArgumentSamplers,
function_tables: &[VisibleFunctionTable],
counts: Counting<'_>,
) -> Result<Across, Error> {
@@ -300,8 +411,7 @@ impl LiveDispatch {
return Ok(Across::Missed);
}
let maps = tables.sampler_maps()?;
let (changed, samplers) = listing;
let listing = (changed, samplers, false);
let listing = (counted.1, &mut *samplers);
let moved = self.refresh(tables, &maps, listing, function_tables, counts);
let same = moved == ValueKinds::default()
&& (self.memo.entry()).is_some_and(|kept| kept.settled.sampler_maps == maps);
@@ -313,23 +423,30 @@ impl LiveDispatch {
.is_some_and(|kept| *kept.settled.planned.shape == self.state.shape()),
"a parked dispatch memo taken for a state of another shape"
);
self.memo.restamp(tables.table.stamp(), samplers);
let device = tables.pipeline.generation();
self.memo.restamp(tables.table.stamp(), (samplers, device));
Ok(Across::Taken)
}
/// That the state brought in place is the one a dispatch of `tables` makes whole
/// (`DispatchTables::bind_state` with `maps` applied), field by field (debug builds): the
/// kernel's table as `ArgumentTable::check_reading` compares it (a float's sign told apart,
/// every NaN alike), and every other field equal.
/// every NaN alike), the argument samplers as `samplers` lists them where the dispatch took
/// the device's (else the kept listing is of every live state at the count that holds), and
/// every other field equal.
#[cfg(debug_assertions)]
fn check_whole(
&self,
tables: &DispatchTables<'_>,
maps: &SamplerMaps,
samplers: &[SamplerState],
samplers: Option<&[crate::sampler::SamplerState]>,
function_tables: &[VisibleFunctionTable],
) {
let mut whole = tables.bind_state(samplers, function_tables);
// As `ArgumentTable::check_reading`: not in a call that raced a rebind on another thread.
if crate::rebind::call_may_have_raced() {
return;
}
let mut whole = tables.bind_state(samplers.unwrap_or_default(), function_tables);
maps.apply(&mut whole);
let state = &self.state;
let kept = &state.stages[&Stage::Kernel];
@@ -342,12 +459,12 @@ impl LiveDispatch {
"{DIFFERS}: its threadgroup lengths"
);
assert!(
heap_sets::lists(&state.argument_samplers, samplers),
samplers.is_none_or(|samplers| heap_sets::lists(&state.argument_samplers, samplers)),
"{DIFFERS}: its argument samplers"
);
// Every other field equal, the table and the listing compared above, as their values
// print (a NaN LOD clamp equals none).
let mut rest = state.clone();
let mut rest = BindState::clone(state);
for of in [&mut whole, &mut rest] {
of.stages.clear();
of.argument_samplers.clear();
@@ -393,6 +510,24 @@ impl LiveDispatch {
self.memo = DispatchMemo::default();
}
/// [`let_go`](Self::let_go) of the state in place and of every state set aside: what each
/// one's last dispatch settled goes, as the device takes them (`SpareLiveDispatches::give`).
fn let_go_all(&mut self) {
self.let_go();
for aside in &mut self.set_aside {
aside.memo = DispatchMemo::default();
}
}
/// Let go of the device's sampler states the memo of the state in place and of every state set
/// aside listed (`DispatchMemo::unlist_samplers`), as they park in their command buffer.
fn unlist_samplers(&mut self) {
self.memo.unlist_samplers();
for aside in &mut self.set_aside {
aside.memo.unlist_samplers();
}
}
/// Its state and memo, read, beside the shadows of its resident textures, the last
/// dispatch's uses, its bind memo and its instantiated commands, kept.
pub(in crate::compute) fn parts(
@@ -404,7 +539,7 @@ impl LiveDispatch {
(&mut CommandUses, &mut BindMemo, &mut Instantiated),
) {
let kept = (&mut self.uses, &mut self.bind, &mut self.instantiated);
(&self.state, &self.memo, &mut self.shadows, kept)
(&*self.state, &self.memo, &mut self.shadows, kept)
}
}
@@ -427,10 +562,11 @@ impl SpareLiveDispatches {
}
/// Keep `live`, an ended compute encoder's state, for the next encoder to start from, its
/// memo let go ([`LiveDispatch::let_go`]) and its resident textures' lists emptied (its bind
/// memo kept), where fewer than [`SPARE_LIVE_DISPATCHES`] are kept; else it goes.
/// memo and those of the states it set aside let go ([`LiveDispatch::let_go_all`]) and its
/// resident textures' lists emptied (its bind memo kept), where fewer than
/// [`SPARE_LIVE_DISPATCHES`] are kept; else it goes.
pub(in crate::compute) fn give(&self, mut live: Box<LiveDispatch>) {
live.let_go();
live.let_go_all();
live.shadows.let_go();
live.unreadable.let_go();
let mut spare = lock(&self.0);
@@ -461,18 +597,29 @@ pub(crate) struct Parked {
live: Box<LiveDispatch>,
}
impl Parked {
/// `room` and `live`, an ended compute encoder's: the lists of its resident textures' shadows
/// and carriers emptied, as the device's spares empty them, and the sampler states its memo's
/// entry listed let go (the device's live ones, which its command buffer holds none of:
/// `DispatchMemo::unlist_samplers`).
pub(in crate::compute) fn new(room: CoreBox, mut live: Box<LiveDispatch>) -> Parked {
/// An ending compute encoder's bind state on its way to its command buffer's park, which the box
/// of its core joins, emptied, as the core ends (`EncoderCore::end_with_replay`): [`Parked`].
pub(crate) struct Parking(Box<LiveDispatch>);
impl Parking {
/// `live`, an ending compute encoder's: the lists of its resident textures' shadows and
/// carriers emptied, as the device's spares empty them, and the sampler states its memo's entry
/// and those of the states it set aside listed let go (the device's live ones, which its
/// command buffer holds none of: `DispatchMemo::unlist_samplers`).
pub(in crate::compute) fn new(mut live: Box<LiveDispatch>) -> Parking {
live.shadows.let_go();
live.unreadable.let_go();
live.memo.unlist_samplers();
Parked { room, live }
live.unlist_samplers();
Parking(live)
}
/// Parked with `room`, the box of the encoder's core, emptied.
pub(crate) fn with_room(self, room: CoreBox) -> Parked {
Parked { room, live: self.0 }
}
}
impl Parked {
/// The core's box and the bind state, for the compute encoder that opens on them.
pub(in crate::compute) fn into_parts(self) -> (CoreBox, Box<LiveDispatch>) {
(self.room, self.live)
@@ -10,6 +10,12 @@
//! **Gates.** An item may be pushed behind a gate ([`Lines::push_behind`]), which holds it, and its
//! line's later items, until every closing of the gate is opened again ([`Lines::close_new`],
//! [`Lines::close`], [`Lines::open`]): it keeps its place in its line meanwhile.
//!
//! **Places.** Each item pushed takes the next place, whatever its line, so places rise along a
//! line. A line keeps the places of its items that may block a thread that runs them (the
//! `may_block` of [`Lines::new`]), and whether what a thread runs of it may: whether an item
//! leads its line ([`Lines::leads`]) is a look at the line's first item and first such place,
//! however many items the line holds.
use std::collections::{HashMap, VecDeque};
@@ -22,13 +28,32 @@ pub(crate) struct Lines<I> {
ready: VecDeque<u64>,
/// The gates not yet open, by token: how many closings each still holds.
closed: HashMap<u64, u32>,
/// The places taken so far: the last item pushed took this one, the first 1.
placed: u64,
/// Whether an item may block a thread that runs it ([`Lines::new`]).
may_block: fn(&I) -> bool,
}
#[derive(Debug)]
struct Line<I> {
items: VecDeque<Entry<I>>,
/// The places of the items it holds that may block, in order.
blocking: VecDeque<u64>,
/// A thread runs the line's first item.
running: bool,
/// What that thread runs may block: false where no thread runs the line.
running_blocks: bool,
}
impl<I> Line<I> {
fn new(running: bool, running_blocks: bool) -> Line<I> {
Line {
items: VecDeque::new(),
blocking: VecDeque::new(),
running,
running_blocks,
}
}
}
#[derive(Debug)]
@@ -36,22 +61,26 @@ struct Entry<I> {
item: I,
/// The gate it waits behind, if any ([`Lines::push_behind`]).
gate: Option<u64>,
/// Its place ([`Lines::push`]).
place: u64,
}
impl<I> Default for Lines<I> {
fn default() -> Lines<I> {
impl<I> Lines<I> {
/// Lines in which `may_block` tells whether an item may block a thread that runs it: what
/// [`Lines::leads`] looks past.
pub(crate) fn new(may_block: fn(&I) -> bool) -> Lines<I> {
Lines {
lines: HashMap::new(),
ready: VecDeque::new(),
closed: HashMap::new(),
placed: 0,
may_block,
}
}
}
impl<I> Lines<I> {
/// Append `item` to `queue`'s line.
pub(crate) fn push(&mut self, queue: u64, item: I) {
self.push_entry(queue, Entry { item, gate: None });
/// Append `item` to `queue`'s line: its place.
pub(crate) fn push(&mut self, queue: u64, item: I) -> u64 {
self.push_entry(queue, item, None)
}
/// Close the new gate `token` once ([`Lines::push_behind`]).
@@ -60,22 +89,26 @@ impl<I> Lines<I> {
}
/// Append `item` to `queue`'s line behind the gate `token` ([`Lines::close_new`]): it runs once
/// every closing of the gate is opened ([`Lines::open`]).
pub(crate) fn push_behind(&mut self, queue: u64, item: I, token: u64) {
let gate = Some(token);
self.push_entry(queue, Entry { item, gate });
/// every closing of the gate is opened ([`Lines::open`]). Its place.
pub(crate) fn push_behind(&mut self, queue: u64, item: I, token: u64) -> u64 {
self.push_entry(queue, item, Some(token))
}
fn push_entry(&mut self, queue: u64, entry: Entry<I>) {
fn push_entry(&mut self, queue: u64, item: I, gate: Option<u64>) -> u64 {
self.placed += 1;
let place = self.placed;
let blocks = (self.may_block)(&item);
let entry = Entry { item, gate, place };
let open = self.open_entry(&entry);
let line = self.lines.entry(queue).or_insert_with(|| Line {
items: VecDeque::new(),
running: false,
});
let line = (self.lines.entry(queue)).or_insert_with(|| Line::new(false, false));
if line.items.is_empty() && !line.running && open {
self.ready.push_back(queue);
}
if blocks {
line.blocking.push_back(place);
}
line.items.push_back(entry);
place
}
/// Whether `entry` waits behind no gate that is still closed.
@@ -126,6 +159,10 @@ impl<I> Lines<I> {
let line = self.lines.get_mut(&queue)?;
line.running = true;
let entry = line.items.pop_front()?;
line.running_blocks = line.blocking.front() == Some(&entry.place);
if line.running_blocks {
line.blocking.pop_front();
}
Some((queue, entry.item))
}
@@ -136,6 +173,7 @@ impl<I> Lines<I> {
return;
};
line.running = false;
line.running_blocks = false;
let Some(first) = line.items.front() else {
self.lines.remove(&queue);
return;
@@ -150,12 +188,13 @@ impl<I> Lines<I> {
/// Take `queue`'s line for the calling thread, where no thread runs it and `plain` holds for
/// each item it holds, none behind a closed gate: those items, in order, which the caller
/// runs before anything it runs in the line itself; the line is running until
/// [`Lines::done`]. `None` otherwise, changing nothing.
/// runs before anything it runs in the line itself (which may block where `blocks`); the
/// line is running until [`Lines::done`]. `None` otherwise, changing nothing.
pub(crate) fn take_plain(
&mut self,
queue: u64,
plain: impl Fn(&I) -> bool,
blocks: bool,
) -> Option<VecDeque<I>> {
if let Some(line) = self.lines.get(&queue) {
let runs = |entry: &Entry<I>| plain(&entry.item) && self.open_entry(entry);
@@ -163,49 +202,48 @@ impl<I> Lines<I> {
return None;
}
}
let items: VecDeque<I> = (self.lines.remove(&queue)).map_or_else(VecDeque::new, |line| {
line.items.into_iter().map(|entry| entry.item).collect()
});
let (items, blocking) = match self.lines.remove(&queue) {
Some(line) => {
let items: VecDeque<I> = line.items.into_iter().map(|entry| entry.item).collect();
(items, !line.blocking.is_empty())
}
None => (VecDeque::new(), false),
};
if !items.is_empty() {
// A line that holds an item and runs on no thread is ready, once.
self.ready.retain(|ready| *ready != queue);
}
self.lines.insert(
queue,
Line {
items: VecDeque::new(),
running: true,
},
);
self.lines
.insert(queue, Line::new(true, blocking || blocks));
Some(items)
}
/// Take `queue`'s line for the calling thread where it holds no item and no thread runs it:
/// the line is running until [`Lines::done`]. False otherwise, changing nothing.
pub(crate) fn take_idle(&mut self, queue: u64) -> bool {
/// Take `queue`'s line for the calling thread where it holds no item and no thread runs it,
/// for what may block where `blocks`: the line is running until [`Lines::done`]. False
/// otherwise, changing nothing.
pub(crate) fn take_idle(&mut self, queue: u64, blocks: bool) -> bool {
if self.lines.contains_key(&queue) {
return false;
}
self.lines.insert(
queue,
Line {
items: VecDeque::new(),
running: true,
},
);
self.lines.insert(queue, Line::new(true, blocks));
true
}
/// Whether the item `is` picks out leads `queue`'s line: it is the first item and no thread
/// runs the line; or, where the caller knows it was pushed (`posted`) and is not done, a thread
/// runs the line and no item left in it is it, so the thread runs it.
pub(crate) fn leads(&self, queue: u64, is: impl Fn(&I) -> bool, posted: bool) -> bool {
/// Whether the item placed at `at` in `queue`'s line ([`Lines::push`]), which the caller knows
/// is not done, leads the line: where it waits there, no item before it may block, nor what a
/// thread runs of the line; where it no longer waits there, a thread runs it. One look at the
/// line's first item and first place that may block, however many items the line holds.
pub(crate) fn leads(&self, queue: u64, at: u64) -> bool {
let Some(line) = self.lines.get(&queue) else {
return false;
};
match line.running {
true => posted && !line.items.iter().any(|entry| is(&entry.item)),
false => line.items.front().is_some_and(|entry| is(&entry.item)),
let waits = line.items.front().is_some_and(|first| first.place <= at);
match waits {
true => {
let before = line.blocking.front().is_some_and(|&place| place < at);
!line.running_blocks && !before
}
false => line.running,
}
}
+89 -22
View File
@@ -9,14 +9,20 @@
//! holds only such transitions, in order after them ([`Contexts::run_here`],
//! `command_buffer/completion.rs`), and the scheduler such a transition to `Scheduled` where the
//! context runs on no thread and holds nothing ([`Contexts::run_alone`],
//! `CommandBufferShared::schedule`); neither runs a handler. (A transition to `Scheduled` waits
//! for its command buffer's submission handlers, which the thread that took its last batch for
//! its queue runs.) A release the scheduler's thread hands off (`Device::let_go_elsewhere`) runs
//! in a context of its own, behind no queue's handlers. A transition to `Completed` of a command
//! buffer that waited on the GPU for another queue's command buffer may be posted behind a gate
//! ([`Contexts::gate`], [`Contexts::post_behind`]), its place in its context kept, until that
//! command buffer's transition, which leads its own context ([`Contexts::leads`]), reaches its
//! handlers (`command_buffer/follow.rs`): a gate holds no thread.
//! `CommandBufferShared::schedule`); neither runs a handler. (A transition to `Scheduled` follows
//! its command buffer's submission handlers, which a `commit_and_submit` call that took its last
//! batch runs on its thread, and the scheduler's thread hands to these threads, in a context of
//! their own (`scheduler::Posted`); it is posted, or run alone, by the thread that ran them once
//! they ran. Where the command buffer's transition to `Completed` comes first, it waits behind a
//! gate those handlers open, its place kept, holding no thread
//! (`CommandBufferShared::gate_for_handlers`), and makes it `Scheduled` first.) A release the
//! scheduler's thread hands off (`Device::let_go_elsewhere`) runs in a context of its own, behind
//! no queue's handlers. A transition to `Completed` of a command buffer that waited on the GPU
//! for another queue's command buffer may be posted behind a gate ([`Contexts::gate`],
//! [`Contexts::post_behind`]), its place in its context kept, until that command buffer's
//! transition, which nothing that may block precedes in its own context ([`Contexts::leads`],
//! [`Run::may_block`]), reaches its handlers (`command_buffer/follow.rs`): a gate holds no
//! thread.
//! - **Done with an item before what it held goes.** The thread that ran an item marks its context
//! done with it, and only then lets go of what the item still holds ([`Run::Held`]): a
//! transition's hold of its command buffer, whose going lets that command buffer's waiters
@@ -74,6 +80,35 @@ pub(crate) const THREADS: usize = 512;
/// Each thread's stack, in bytes.
pub(crate) const STACK: usize = 512 * 1024;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
thread_local! {
/// The looks for a thread to run a ready context this thread made ([`Contexts::serve`]).
static SERVES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// The looks for a thread to run a ready context the calling thread made so far, in the device
/// tests' builds.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn serves_here() -> u64 {
SERVES.with(std::cell::Cell::get)
}
/// A device test's cap on the threads of the pools of devices made from now on, where not 0
/// ([`device_limit`]): a test drives the pool at its cap with a few contexts.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) static TEST_LIMIT: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);
/// The most threads a device's pool runs at once: [`THREADS`], or a device test's cap
/// (`TEST_LIMIT`).
pub(crate) fn device_limit() -> usize {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
if let limit @ 1.. = TEST_LIMIT.load(Ordering::Relaxed) {
return limit;
}
THREADS
}
/// How long a thread other than the first finds nothing to run before it ends.
const IDLE: Duration = Duration::from_secs(2);
@@ -101,6 +136,15 @@ pub(crate) trait Run: Send + 'static {
fn runs_where_seen(&self) -> bool {
self.plain()
}
/// Whether the item may block a thread that runs it, or wait for the program before it runs:
/// it runs a handler of the program's other than its completion-seen handlers, which never
/// block, or waits for one (a scheduled, submission or completed handler). Every item may by
/// default. A transition of another queue waits behind one that may not
/// (`command_buffer/follow.rs`).
fn may_block(&self) -> bool {
true
}
}
/// One device's handler threads. A clone is another handle of the same pool, which holds nothing
@@ -191,7 +235,7 @@ impl<I: Run> Contexts<I> {
pub(crate) fn start(limit: usize) -> Result<Contexts<I>, Error> {
let shared = Arc::new(Shared {
state: Mutex::new(State {
lines: Lines::default(),
lines: Lines::new(|item: &I| item.may_block()),
gates: 0,
free: 1,
parked: 0,
@@ -225,11 +269,12 @@ impl<I: Run> Contexts<I> {
}
/// Append `item` to the context of logical queue `queue`; start a thread when a context is
/// ready that no free thread will take, below the cap.
pub(crate) fn post(&self, queue: u64, item: I) {
/// ready that no free thread will take, below the cap. Its place there ([`Lines::push`]).
pub(crate) fn post(&self, queue: u64, item: I) -> u64 {
let mut state = lock(&self.shared.state);
state.lines.push(queue, item);
let place = state.lines.push(queue, item);
self.serve(state);
place
}
/// Run `item` in the context of logical queue `queue` on this thread, after the items that
@@ -242,7 +287,11 @@ impl<I: Run> Contexts<I> {
if !may_run(&item) {
return Err(item);
}
let Some(before) = lock(&self.shared.state).lines.take_plain(queue, may_run) else {
let blocks = item.may_block();
let taken = lock(&self.shared.state)
.lines
.take_plain(queue, may_run, blocks);
let Some(before) = taken else {
return Err(item);
};
let earlier: Vec<I::Held> = before.into_iter().map(Run::run).collect();
@@ -267,11 +316,24 @@ impl<I: Run> Contexts<I> {
/// Append `item` to the context of logical queue `queue` behind the gate `token`
/// ([`Contexts::gate`]): the item keeps its place in its context, and it and the items after it
/// run once the gate is open.
pub(crate) fn post_behind(&self, queue: u64, item: I, token: u64) {
/// run once the gate is open. Its place there ([`Lines::push`]).
pub(crate) fn post_behind(&self, queue: u64, item: I, token: u64) -> u64 {
let mut state = lock(&self.shared.state);
state.lines.push_behind(queue, item, token);
let place = state.lines.push_behind(queue, item, token);
self.serve(state);
place
}
/// Append `item` to the context of logical queue `queue` behind the gate `token`
/// ([`Contexts::gate`]) and open the caller's closing of it, under one lock: one look for a
/// thread to run it ([`post_behind`](Self::post_behind) and [`open`](Self::open) make one
/// each). It runs in its turn once the gate's other closings opened. Its place there.
pub(crate) fn post_gated(&self, queue: u64, item: I, token: u64) -> u64 {
let mut state = lock(&self.shared.state);
let place = state.lines.push_behind(queue, item, token);
state.lines.open(queue, token);
self.serve(state);
place
}
/// Close the gate `token` once more, where it is not open yet: whether it was not.
@@ -287,10 +349,11 @@ impl<I: Run> Contexts<I> {
self.serve(state);
}
/// Whether the item `is` picks out leads the context of `queue`: no item of the context runs
/// before it ([`Lines::leads`]; `posted` where the caller knows it was posted there).
pub(crate) fn leads(&self, queue: u64, is: impl Fn(&I) -> bool, posted: bool) -> bool {
lock(&self.shared.state).lines.leads(queue, is, posted)
/// Whether the item posted at the place `at` in the context of `queue`, which the caller knows
/// is not done, leads it: nothing there that may block runs before it ([`Lines::leads`],
/// [`Run::may_block`]).
pub(crate) fn leads(&self, queue: u64, at: u64) -> bool {
lock(&self.shared.state).lines.leads(queue, at)
}
/// Hold the context of logical queue `queue`, which holds no item and runs on no thread (a
@@ -298,7 +361,8 @@ impl<I: Run> Contexts<I> {
/// there waits until [`release`](Self::release). False where it held an item or ran, changing
/// nothing.
pub(crate) fn hold(&self, queue: u64) -> bool {
lock(&self.shared.state).lines.take_idle(queue)
// What it waits for may run the program's handlers.
lock(&self.shared.state).lines.take_idle(queue, true)
}
/// Let the context [`hold`](Self::hold) held run what was posted there meanwhile, in order.
@@ -313,7 +377,8 @@ impl<I: Run> Contexts<I> {
/// this thread meanwhile, so the items posted to it wait for `item`, then run on the pool's
/// threads. Else give `item` back, changing nothing.
pub(crate) fn run_alone(&self, queue: u64, item: I) -> Result<(), I> {
if !item.plain() || !lock(&self.shared.state).lines.take_idle(queue) {
let blocks = item.may_block();
if !item.plain() || !lock(&self.shared.state).lines.take_idle(queue, blocks) {
return Err(item);
}
let held = item.run();
@@ -327,6 +392,8 @@ impl<I: Run> Contexts<I> {
/// Start a thread where a context is ready that no free thread will take, below the cap, and
/// wake one where one sleeps and a context is ready: `state` was just changed.
fn serve(&self, mut state: std::sync::MutexGuard<'_, State<I>>) {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
SERVES.with(|serves| serves.set(serves.get() + 1));
if state.lines.ready() > state.free {
let start = {
let mut count = lock(&self.shared.census.count);
+21 -5
View File
@@ -1643,6 +1643,7 @@ impl CopiedBuffers {
/// Whether the merge back at the completion of work that wrote `written` may write the
/// caller's pages: a live copy with a base whose keys `written` meets, as
/// [`merge_back`](Self::merge_back) compares (`command_buffer/sync_file.rs`).
#[cfg(unix)]
pub(crate) fn merges_back(&self, written: &CopiesReached) -> bool {
self.live.load(Ordering::Relaxed) > 0
&& (lock(&self.entries).iter())
@@ -2615,7 +2616,7 @@ pub(crate) unsafe fn read_caller(
/// Read the caller's `into.len()` bytes at `pages` into `into` through the kernel, which answers a
/// page the process cannot read (unmapped, or mapped without read permission) with a failure, not a
/// fault: `false` then. On Linux `process_vm_readv` of the process's own pages; on macOS
/// `mach_vm_read_overwrite` of its own task's; elsewhere nothing is read and the answer is `false`.
/// `mach_vm_read_overwrite` of its own task's; on Windows `ReadProcessMemory` of its own.
#[cfg(target_os = "linux")]
pub(crate) fn read_pages(pages: NonNull<u8>, into: &mut [u8]) -> bool {
let mut done = 0;
@@ -2668,8 +2669,23 @@ pub(crate) fn read_pages(pages: NonNull<u8>, into: &mut [u8]) -> bool {
answer == libc::KERN_SUCCESS && read == into.len() as u64
}
/// [`read_pages`] where the system is not asked: nothing is copied.
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub(crate) fn read_pages(_pages: NonNull<u8>, _into: &mut [u8]) -> bool {
false
/// [`read_pages`] on Windows: `ReadProcessMemory` of the process's own pages, which answers a
/// page it cannot read with a failure.
#[cfg(windows)]
pub(crate) fn read_pages(pages: NonNull<u8>, into: &mut [u8]) -> bool {
use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let mut read = 0;
// SAFETY: the call writes `into`'s bytes alone, through the pseudo-handle of this process,
// and answers an unreadable page of the source with a failure.
let answer = unsafe {
ReadProcessMemory(
GetCurrentProcess(),
pages.as_ptr().cast(),
into.as_mut_ptr().cast(),
into.len(),
&mut read,
)
};
answer != 0 && read == into.len()
}
@@ -0,0 +1,82 @@
//! A blit encoder's run of buffer copies recorded as one `vkCmdCopyBuffer`
//! (`BlitCommandEncoder::copy_from_buffer_to_buffer`).
//!
//! - **Which copies join.** A copy between the same two `VkBuffer`s as the run's, which the
//! encoder's order needs no barrier after (`EncoderCore::copy_joining`): no copy of the run
//! wrote what it reads or reads or writes what it writes, per resource and range, untracked
//! resources' too (a blit's uses name every byte it touches, `tracker.rs`). The run's regions
//! then touch no byte both as a source and as a destination
//! (`VUID-vkCmdCopyBuffer-pRegions-00117`), and no two of them write one byte, so their order
//! inside the command is no order Metal sees. A program that copies tiles side by side, one copy
//! per row, makes one `vkCmdCopyBuffer` of all of them.
//! - **What ends a run.** Any other command of the encoder, a barrier, a copy between other
//! buffers, and the encoder's end: the run records first, in the `VkCommandBuffer` its first copy
//! would have recorded into, so every command keeps its place in encoded order.
//! - **Where a run breaks.** The encoder's order keeps at most eight ranges of a resource, then
//! merges them into one span, from the lowest byte of any to the highest
//! (`tracker::ENTRIES_PER_KEY`). A copy whose destination lies inside that span of the earlier
//! writes, though it meets none of them, takes a barrier there and starts a new run; so does one
//! whose source lies inside it where both are one buffer's. Copies whose destination offsets rise
//! from one copy to the next (a picture's rows in order, tile beside tile) join whole: sort them
//! by destination offset to merge them all.
//! - **Counted.** Each copy that joined a run as another region
//! (`WorkCounts::buffer_copies_merged`).
use crate::device::functions::Vk;
use crate::work_counts::Counters;
use ash::vk;
/// A run of copies from one `VkBuffer` into another, recorded as one `vkCmdCopyBuffer` (the
/// module docs).
pub(crate) struct CopyRun {
/// The `VkCommandBuffer` its first copy took, which records it.
raw: vk::CommandBuffer,
source: vk::Buffer,
destination: vk::Buffer,
regions: Vec<vk::BufferCopy>,
}
impl CopyRun {
/// A run of `region` of `source` into `destination`, to record into `raw`.
pub(crate) fn new(
raw: vk::CommandBuffer,
(source, destination, region): (vk::Buffer, vk::Buffer, vk::BufferCopy),
) -> CopyRun {
CopyRun {
raw,
source,
destination,
regions: vec![region],
}
}
/// Join `copy` to the run where it copies between its two buffers and records into `raw`, the
/// run's own: whether it joined.
pub(crate) fn join(
&mut self,
raw: vk::CommandBuffer,
(source, destination, region): (vk::Buffer, vk::Buffer, vk::BufferCopy),
) -> bool {
let joins = self.raw == raw && self.source == source && self.destination == destination;
if joins {
self.regions.push(region);
}
joins
}
/// Record the run: one `vkCmdCopyBuffer` of its regions, each past the first counted.
///
/// # Safety
///
/// The run's command buffer is recording, outside a render pass, and nothing was recorded
/// into it since the run's first copy; both buffers live until it completes, and every
/// region lies inside both.
pub(crate) unsafe fn record(self, device: &Vk, counts: &Counters) {
// SAFETY: the caller's contract; the regions touch no byte as both a source and a
// destination (the module docs).
unsafe {
device.cmd_copy_buffer(self.raw, self.source, self.destination, &self.regions);
}
counts.buffer_copies_merged(self.regions.len() as u64 - 1);
}
}
@@ -52,6 +52,7 @@ pub(crate) unsafe fn image(
///
/// As `vkCreateImage`'s: `device` is live, and `info` and its chain are valid for it.
#[track_caller]
#[cfg(unix)]
pub(crate) unsafe fn image_or_refusal(
device: &ash::Device,
info: &vk::ImageCreateInfo<'_>,
+149 -47
View File
@@ -20,6 +20,7 @@ use super::pipeline::ComputePipelineState;
use super::render::DeferredPass;
use super::resource::ResourceKey;
use super::shadow::GatedCopyIn;
use super::shadow_splice::ShadowSplices;
use super::sparse::emulated::Scrub;
use super::tracker::{EncoderUses, Summary, Use};
use super::Device;
@@ -67,6 +68,12 @@ pub(super) enum Deferred {
/// ([`StagedScatter::drain`]): the host step of a batch of its own records nothing, once the
/// work before it completed.
ScatterDrain(Arc<StagedScatter>),
/// The CPU's part of an encoder's copies back spliced and merges on the host at one place
/// (`shadow_splice.rs`, [`ShadowSplices::drain`]): its texels' bytes in lines the GPU's
/// copies left, copied from the arena into the pages, and the bytes its merges' commands
/// changed, stored there, by the host step of a batch of its own, which records nothing,
/// once the work before it completed.
ShadowSplice(Arc<ShadowSplices>),
}
// SAFETY: a `Deferred` holds one `Arc` of its variant's work, which is `Send` and `Sync` for every
@@ -96,6 +103,7 @@ const _: fn(&Deferred) = |work| {
Deferred::GatherStage(work) => shared(work),
Deferred::ScatterStage(work) => shared(work),
Deferred::ScatterDrain(work) => shared(work),
Deferred::ShadowSplice(work) => shared(work),
}
};
@@ -189,6 +197,7 @@ impl Deferred {
(Deferred::GatherStage(a), Deferred::GatherStage(b)) => Arc::ptr_eq(a, b),
(Deferred::ScatterStage(a), Deferred::ScatterStage(b)) => Arc::ptr_eq(a, b),
(Deferred::ScatterDrain(a), Deferred::ScatterDrain(b)) => Arc::ptr_eq(a, b),
(Deferred::ShadowSplice(a), Deferred::ShadowSplice(b)) => Arc::ptr_eq(a, b),
_ => false,
}
}
@@ -202,7 +211,8 @@ impl Deferred {
/// which is one of the encoder's shadow copies, nor a run's merge (`pass_runs.rs`): a linear
/// attachment's touches no shadowed texture, and a shadowed texture's is the copy back its
/// encoder took out of its shadows to leave there. A staged copy's do: a gather's writes the
/// buffer, a scatter's reads it and writes the pages, after every command before them.
/// buffer, a scatter's reads it and writes the pages, after every command before them. A
/// splice's CPU part does not: it ends copies back its encoder just recorded.
pub(super) fn leaves_shadows(&self) -> bool {
match self {
Deferred::Execute(_)
@@ -215,7 +225,8 @@ impl Deferred {
Deferred::RenderPass(_)
| Deferred::Pending(_)
| Deferred::GatedCopyIn(_)
| Deferred::RunMerge(_) => false,
| Deferred::RunMerge(_)
| Deferred::ShadowSplice(_) => false,
}
}
@@ -227,15 +238,18 @@ impl Deferred {
/// memory the work
/// before it may write. A render pass's, whether such a route met the buffer of one of its
/// executions, or one of them reads its range from a buffer. A staged scatter's CPU copy
/// reads the staging the GPU's copy before it wrote; a staged gather's, over a guest RAM chunk
/// that takes no import, reads pages a command before it may write
/// (`StagedGather::after_the_gpu`).
/// reads the staging the GPU's copy before it wrote; a staged gather's reads guest RAM pages
/// a command before it may write (`StagedGather::after_the_gpu`); a splice's CPU part reads
/// the region its copies back wrote.
pub(super) fn gpu_written(&self) -> bool {
match self {
Deferred::Execute(execute) => {
execute.icb.gpu_written() || execute.indirect() || execute.predicated()
}
Deferred::Dispatch(_) | Deferred::Loop(_) | Deferred::ScatterDrain(_) => true,
Deferred::Dispatch(_)
| Deferred::Loop(_)
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => true,
Deferred::GatherStage(gather) => gather.after_the_gpu(),
Deferred::SparseScrub(_)
| Deferred::GatedCopyIn(_)
@@ -462,23 +476,27 @@ impl Deferred {
held: false,
}),
// Recorded by host steps: a gather's and a scatter's GPU copy by its batch's
// (`records_at_its_step`); a scatter's CPU copy, which records nothing on the GPU,
// once the work before it completed. Their uses are their encoder's, noted at the call
// (`host_ram/copy.rs`): the steps' recordings name none of their own.
Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => {
Ok(Prepared {
recorded: None,
for_good: false,
inputs: StepInputs::Staged,
retained: None,
pipelines: false,
bound: match self {
Deferred::ScatterDrain(_) => Some(EncoderUses::new(true).finish()),
_ => None,
},
held: false,
})
}
// (`records_at_its_step`); a scatter's CPU copy, and a splice's, which record nothing
// on the GPU, once the work before it completed. Their uses are their encoder's, noted
// at the call (`host_ram/copy.rs`, `EncoderCore::shadow_copies`): the steps'
// recordings name none of their own.
Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => Ok(Prepared {
recorded: None,
for_good: false,
inputs: StepInputs::Staged,
retained: None,
pipelines: false,
bound: match self {
Deferred::ScatterDrain(_) | Deferred::ShadowSplice(_) => {
Some(EncoderUses::new(true).finish())
}
_ => None,
},
held: false,
}),
// Recorded now where its pipelines are made; else by a host step once they are,
// which makes again one whose making failed.
Deferred::Pending(dispatch) => {
@@ -540,15 +558,17 @@ impl Deferred {
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => None,
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => None,
}
}
/// Whether a rebind's encoding again of its encoder records it at once in its place, leaving
/// no segment of it (`command_buffer/reencode.rs`): a staged gather, which an encoder encoded
/// again copies through the imports (`host_ram/copy.rs`), but one over a chunk that takes no
/// import (`StagedGather::encoded_again_through_imports`), whose encoder keeps no log. The
/// encoding again's parts are the first's: such a gather's segment starts none.
/// import or in a part of its own (`StagedGather::encoded_again_through_imports`), which it
/// stages again ([`left_again_by_an_encoding_again`](Self::left_again_by_an_encoding_again)).
/// The encoding again's parts are the first's: such a gather's segment starts none.
pub(super) fn recorded_by_an_encoding_again(&self) -> bool {
match self {
Deferred::GatherStage(gather) => gather.encoded_again_through_imports(),
@@ -556,6 +576,34 @@ impl Deferred {
}
}
/// Whether a rebind's encoding again of its encoder leaves a segment of its own in its place
/// (`command_buffer/reencode.rs`): a splice's and a merge on the host's CPU part
/// (`shadow_splice.rs`), which the encoding again's copies back plan over the pages the
/// buffer lies in then and leave again, in a part as the first's (a rebind keeps the bytes'
/// offset in their page, `rebind.rs`, so the copies cut alike); a staged scatter's two
/// steps, which the encoding again stages again from where the buffer lies then, its CPU
/// copy in a part of its own as the first's; and a staged gather the imports would not copy
/// as the first staged it (over a chunk that takes no import, or in a part of its own:
/// `StagedGather::encoded_again_through_imports`), staged again so (`host_ram/copy.rs`'s
/// `HostRamCall::staged_again`); and a shadow's copy in left to its batch's submission
/// (`shadow::GatedCopyIn`), which the encoding again's copy in leaves again, gated as it
/// decides then (or records in place, where it decides to copy every texel): its gate of a
/// log, made after the commit's decisions (`DirtyShadows::committed`), holds no stamp and
/// copies every region (`CopyInGate::regions`); and a sparse texture's scrub, left for its
/// batch's submission (`sparse::emulated::Scrub`), which the blit or the pass encoded again
/// leaves again over the same texture. The first's go unrun.
pub(super) fn left_again_by_an_encoding_again(&self) -> bool {
match self {
Deferred::ShadowSplice(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_)
| Deferred::GatedCopyIn(_)
| Deferred::SparseScrub(_) => true,
Deferred::GatherStage(gather) => !gather.encoded_again_through_imports(),
_ => false,
}
}
/// Whether a commit may record it on the GPU alone, for good
/// ([`record_on_gpu`](Self::record_on_gpu)): an execution's, or a render pass's that executes
/// render commands.
@@ -594,7 +642,8 @@ impl Deferred {
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => Ok(None),
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => Ok(None),
}
}
@@ -648,6 +697,7 @@ impl Deferred {
Deferred::GatherStage(gather) => gather.stage(command_buffer),
Deferred::ScatterStage(scatter) => scatter.stage(command_buffer),
Deferred::ScatterDrain(scatter) => scatter.drain(command_buffer.device()),
Deferred::ShadowSplice(splices) => Ok(splices.drain(command_buffer.device())),
}
}
@@ -668,7 +718,8 @@ impl Deferred {
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => false,
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => false,
}
}
@@ -688,7 +739,8 @@ impl Deferred {
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => false,
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => false,
}
}
@@ -697,9 +749,10 @@ impl Deferred {
pub(super) fn holds(&self) -> bool {
match self {
Deferred::Loop(check) => check.running(),
Deferred::GatherStage(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => {
false
}
Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => false,
Deferred::Execute(_)
| Deferred::Dispatch(_)
| Deferred::SparseScrub(_)
@@ -734,7 +787,8 @@ impl Deferred {
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => false,
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => false,
}
}
@@ -756,7 +810,8 @@ impl Deferred {
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => false,
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => false,
}
}
@@ -772,21 +827,40 @@ impl Deferred {
/// bytes its encoder's commands named (a linear attachment's, none over host pages; a
/// shadowed texture's truth, whose uses its pass noted): a rebind of them encodes that
/// encoder again, the merge with it. So do a staged copy's steps, between the buffer its call
/// resolved (`blit_at`) and the pages it named. Everything else its step resolves as it
/// records: a rebind meanwhile is refused.
/// resolved (`blit_at`) and the pages it named, and a splice's and a merge on the host's CPU
/// part (`shadow_splice.rs`), which writes the pages the truth's buffer lay in at its
/// encoder's call, a shadow's gated copy in, which copies from the truth's `VkBuffer` as its
/// encoder's call found it (`shadow::GatedCopyIn`), and a sparse texture's scrub, which zeroes
/// tiles of its texture alone, as its batch mapped them, and reads no buffer
/// (`sparse::emulated::Scrub`): a rebind before the command buffer's submission encodes that
/// encoder again, its CPU part, its copy in or its scrub with it, and one after it keeps the
/// old pages until the command buffer completes (`rebind.rs`). So does a predicated loop's
/// check whose laying left no work apart (`command_buffer/rerun.rs`): its step reads only its
/// unit's halt word, in the command buffer's arena, and each run again submits the laying's
/// command buffers again as they were encoded, over the pages their first submission took,
/// which the command buffer holds until it completes. A rebind after that submission keeps
/// the old pages for every run again, as Metal's loop reads the pages its submission found;
/// one before it fails that submission (`EncodedUseRebound`,
/// `command_buffer/first_submission.rs`), as the laying's encoders keep no log to be encoded
/// again from (`predication.rs`).
/// Everything else its step resolves as it records (an execution, a dispatch left to its host
/// step, a loop's check whose laying left work apart, which each run again records again as
/// it records: a host step's work resolving the buffers its encoder named then, work on the
/// GPU alone over the buffers as they lie then): a rebind meanwhile is refused
/// (`RebindProblem::EncodedUses`), a known gap (`docs/FAST-PATHS.md`).
pub(super) fn resolved_at_its_calls(&self, pipelines: bool) -> bool {
match self {
Deferred::Pending(_)
| Deferred::RunMerge(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => true,
Deferred::RenderPass(pass) => pipelines && !pass.executes(),
Deferred::Execute(_)
| Deferred::Dispatch(_)
| Deferred::SparseScrub(_)
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_)
| Deferred::GatedCopyIn(_)
| Deferred::Loop(_) => false,
| Deferred::SparseScrub(_) => true,
Deferred::RenderPass(pass) => pipelines && !pass.executes(),
Deferred::Loop(check) => !check.leaves_work_apart(),
Deferred::Execute(_) | Deferred::Dispatch(_) => false,
}
}
@@ -807,7 +881,8 @@ impl Deferred {
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => false,
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => false,
}
}
@@ -830,7 +905,8 @@ impl Deferred {
| Deferred::GatedCopyIn(_)
| Deferred::RunMerge(_)
| Deferred::Loop(_)
| Deferred::ScatterDrain(_) => None,
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => None,
}
}
@@ -847,7 +923,8 @@ impl Deferred {
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => {}
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => {}
}
}
@@ -865,7 +942,31 @@ impl Deferred {
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => {}
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => {}
}
}
/// A weak reference to its work, which holds none of it: a device test's view of what still
/// holds the work (`tests::host_ram_copy_device`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(super) fn weak(&self) -> std::sync::Weak<dyn Any + Send + Sync> {
fn weak<T: Any + Send + Sync>(work: &Arc<T>) -> std::sync::Weak<dyn Any + Send + Sync> {
Arc::<T>::downgrade(work)
}
match self {
Deferred::Execute(work) => weak(work),
Deferred::Dispatch(work) => weak(work),
Deferred::SparseScrub(work) => weak(work),
Deferred::GatedCopyIn(work) => weak(work),
Deferred::RunMerge(work) => weak(work),
Deferred::RenderPass(work) => weak(work),
Deferred::Pending(work) => weak(work),
Deferred::Loop(work) => weak(work),
Deferred::GatherStage(work) => weak(work),
Deferred::ScatterStage(work) => weak(work),
Deferred::ScatterDrain(work) => weak(work),
Deferred::ShadowSplice(work) => weak(work),
}
}
@@ -881,7 +982,8 @@ impl Deferred {
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => {}
| Deferred::ScatterDrain(_)
| Deferred::ShadowSplice(_) => {}
Deferred::RenderPass(pass) => pass.degrade(device),
}
}
+64 -19
View File
@@ -312,7 +312,8 @@ degradations! {
copied in only at its first use and the first after each did_modify_data, and never \
back)";
/// A texture buffer is viewed through a staging buffer: its texels start where the
/// device views none (`minTexelBufferOffsetAlignment`), or run past its buffer's length,
/// device views none (`minTexelBufferOffsetAlignment`), or run past the bytes its
/// buffer's memory holds for them (a no-copy buffer's or a buffer's under 16 KiB length),
/// where its staging buffer is its tail.
StagedTextureBuffer = "staged-texture-buffer", Performance,
"its texels are copied into a staging buffer before each use and back after each \
@@ -747,13 +748,16 @@ degradations! {
/// where the records lie in device-local memory and must stay there: a `Private`
/// buffer's, whose records never leave it, or a `Shared` one's that the GPU used first
/// while a command buffer that used them is not complete or dropped
/// (`indirect_command_buffer/home.rs`). A `Shared` buffer's records move into host memory
/// at its first host access once no command buffer holds them, and stay there. To avoid
/// it, touch a `Shared` buffer from the CPU before the GPU uses it.
/// (`indirect_command_buffer/home.rs`). An access that only reads records the GPU never
/// wrote is not one: it reads host memory in place, which holds what device-local memory
/// does. A `Shared` buffer's records move into host memory at its first host access once
/// no command buffer holds them, and stay there. To avoid it, touch a `Shared` buffer from
/// the CPU before the GPU uses it.
StagedIndirectRecords = "staged-indirect-records", Performance,
"a round trip through the device's staging queue for each such access: the records it \
reads are copied into host memory first, and those it writes copied back after, \
each copy waited for, where Metal's CPU reads and writes the records in place";
reads are copied into host memory first where the GPU may have written them, and \
those it writes copied back after, each copy waited for, where Metal's CPU reads and \
writes the records in place";
/// A command buffer's GPU times on a device that calibrates its timestamps against no
/// host clock the runtime reads (no `VK_KHR_calibrated_timestamps` or
/// `VK_EXT_calibrated_timestamps` with the device's time domain and a monotonic host
@@ -763,6 +767,17 @@ degradations! {
UncalibratedGpuTimes = "uncalibrated-gpu-times", Precision,
"the end is the host time the runtime saw the command buffer complete, late by that \
latency, and the start the GPU's exact duration before it";
/// A command buffer's GPU times on a device whose calibration pair, taken as the command
/// buffer completed, stated a deviation above 20 us though the runtime read it again,
/// four readings at most, and placed them inside the command buffer's life by the
/// reading of the least deviation (`gpu_time.rs`). A reading's deviation holds the time
/// its thread spent off the CPU between its two values, so a loaded host states more: an
/// RX 7900 XTX (RADV) under full parallel test suites stated 93 and 125 us after four
/// readings.
LooselyCalibratedGpuTimes = "loosely-calibrated-gpu-times", Precision,
"each GPU time may stand from the moment the GPU wrote it by up to the deviation its \
reason states, more than the 20 us a settled calibration reading keeps to; the \
duration between them stays exact";
/// A command buffer's GPU times on a device whose timestamp pools had no slot free at
/// the command buffer's commit, and which could make no pool more: every slot was held
/// by a command buffer in flight (`gpu_time.rs`).
@@ -1695,9 +1710,17 @@ degradations! {
/// A command buffer's command named a buffer over the caller's host pages (a binding, a
/// blit's operand, an attachment, a texture over the pages, an indirect command's
/// resolved buffer) that was rebound (`rebind_bytes_no_copy`) after the command was
/// encoded and before the command buffer was first submitted
/// encoded and before the command buffer was first submitted, or that a rebind on another
/// thread raced the command's encoding of (its call held the buffer while the rebind was
/// making what lies over its bytes again, or after, having begun before: `rebind.rs`'s
/// **Other threads**, `WorkCounts::encoders_raced_rebind`: a blit or logged render
/// encoder whose commit failed it or whose encoding again a call that answers otherwise
/// refused, as the calls of compute encoders and of render encoders that keep no log are
/// gated, `rebind::CallGate`, and never race one; and a rebind after the commit of a
/// command buffer with an encoder that keeps no log that named the buffer is refused
/// until its last submission, `Holds::hold_to_submission`)
/// (`CommandBufferError::EncodedUseRebound`, `command_buffer/first_submission.rs`), in an
/// encoder the rebind could not encode again (a compute encoder its unit of command
/// encoder the runtime could not encode again (a compute encoder its unit of command
/// predication reaches past: one whose unit laid a step before it opened, or one of its
/// own that the unit's later encoders read, or whose unit holds a loop or leaves work
/// out; a render pass a host step records; work
@@ -2005,14 +2028,20 @@ degradations! {
/// value (`decoded-texel-precision`), a PVRTC texture's, an ASTC sRGB one's and an 8-bit
/// ETC2 or EAC one's 8-bit codes, exact, an ASTC HDR texture's halves, exact, decoded
/// after each write into it (a PVRTC
/// texture's whole levels). An ASTC texture's first view in its other colour space gives
/// texture's whole levels); a heap's texture whose image is a shadow of the heap's bytes
/// (`texture/heap.rs`), its whole twin after each copy in that moves its blocks. An ASTC
/// texture's first view in its other colour space gives
/// it a second twin of that form's decode. Also a texture of a 4:2:2 format (`GBGR422`,
/// `BGRG422`) on every device, whose Vulkan formats are viewed only through a sampler
/// Y′CbCr conversion: its texels' bytes lie in an `R8G8_UNORM` carrier, and its twin holds
/// its texels as 8-bit codes, decoded in whole rows: the device's own conversion of its
/// pairs where it converts the format with Metal's reconstruction
/// (`decoded-texel-precision`; every decode then a GPU pass, its CPU copies through
/// submissions), else Metal's texels, exact.
/// submissions), else Metal's texels, exact; a heap's such texture, a shadow of the
/// heap's bytes in Metal's rows, its whole twin after each copy in that moves its rows.
/// One over a buffer's bytes (an IOSurface
/// plane's) has no carrier: its samples read an image of its texels alone, written from
/// the pairs where they lie at each copy in (`texture/surface_pairs.rs`).
CarriedDecodedTwin = "carried-decoded-twin", Performance,
"a carrier image of its blocks, at most about 1 byte a texel (a 4:2:2 texture's 2), \
and a decoded twin of 4 bytes a texel (R8G8B8A8; an ASTC HDR texture's halves, 8 \
@@ -2021,7 +2050,8 @@ degradations! {
does not take those codes), two for an ASTC texture viewed in both colour \
spaces, and a decode after each write into it: a pass on the GPU for a blit, a copy from a texture or a CPU copy through a \
submission; on the CPU, on the device's decode thread, where its CPU copies go on \
the host or the staging queue";
the host or the staging queue; and a pass on the GPU after each copy in that moves \
the blocks or rows of a heap's texture whose image shadows the heap's bytes";
/// A texture with an ASTC LDR decoded twin (`carried-decoded-twin`) of 8-bit codes, or an
/// EAC 11-bit one of 16-bit codes: Metal decodes an ASTC LDR channel
/// to a 12-bit value (`C >> 4` over 4095 of the 16-bit interpolated channel `C`), which the
@@ -2203,7 +2233,9 @@ degradations! {
/// driver in one `vkQueueSubmit`, only the last signalling its queue's timeline and their
/// events (`CompletionPolicy::Grouped`, the default, on a driver whose queue
/// merges a submission that signals nothing into the next one: Mesa's drivers;
/// `command_buffer/group.rs`): one kernel submission for up to four batches. Announced
/// `command_buffer/group.rs`; under `CompletionPolicy::Exact`, batches of command buffers
/// marked to join the next, `CommandBuffer::set_completion_joins_next`, and the batch
/// found ready behind them): one kernel submission for up to four batches. Announced
/// once per device, on the scheduler's thread, as the first such submission is made,
/// whatever `DeviceOptions::announce_each` says: no program call or host step meets it.
GroupedCompletion = "grouped-completion", Precision,
@@ -2216,7 +2248,10 @@ degradations! {
submission checks of the batches behind \
a queue's next one run with its own, before the batch before them is submitted; \
their commands, barriers and GPU times are unchanged; CompletionPolicy::Exact \
submits and checks each batch alone";
submits and checks each batch alone but those of a command buffer marked to join \
the next (CommandBuffer::set_completion_joins_next), which go with the batches \
found ready behind them in the same pass, the last of those seen complete at its \
own end";
/// A command buffer's completion sync file (`CommandBuffer::export_completion_sync_file`)
/// whose command buffer's completion writes the caller's pages on the host after its GPU
/// work: the merge back of a copied host buffer its commands may have written
@@ -2325,10 +2360,11 @@ degradations! {
/// `VK_ERROR_OUT_OF_HOST_MEMORY`: on NVIDIA's driver, other devices of the GPU, in this
/// process or others, holding what it needs, such as its channels), made with those of its
/// least plan: a round robin of one `VkQueue` and none reserved for presenting, beside the
/// plan's reserved, extra, staging and fill queues (`DeviceOptions::queue_limits` of one
/// and none, without its informational messages). Announced once, as the device is made;
/// the payload names the device, the `VkQueue`s of each plan and the driver's answer. A
/// device the driver refuses with its least plan too is refused (`Error::DeviceRefused`).
/// plan's extra, staging and fill queues and as many reserved queues as the plan reserves,
/// no more (`DeviceOptions::queue_limits` of one and none, without its informational
/// messages). Announced once, as the device is made; the payload names the device, the
/// `VkQueue`s of each plan and the driver's answer. A device the driver refuses with its
/// least plan too is refused (`Error::DeviceRefused`).
LeastQueuePlan = "least-queue-plan", Performance,
"its command queues, presenting ones included, share one `VkQueue`, so one queue's \
command buffers wait behind another's whole command buffer where Metal's run beside \
@@ -2593,8 +2629,12 @@ degradations! {
/// temporary file in it or the rename over the entry failed, on the device's cache thread
/// or on the thread that handed the entry over past the queue's bound
/// (`shader_cache/store.rs`, `shader_cache/worker.rs`). A full or read-only directory, a
/// cap no entry fits in, or a write another process won. The work is never ended by it:
/// the pipeline state, the translation and the compile are the directory's regardless, and
/// cap no entry fits in, or a write another process won. Or the device has no directory
/// to write to: its options named none and the platform's default does not exist (the
/// variable it is found by is unset or not absolute) or takes no write, so it keeps its
/// cache in memory alone (`shader_cache/mod.rs`); that is announced as the device is made,
/// the payload naming the default directory and why. The work is never ended by it: the
/// pipeline state, the translation and the compile are the directory's regardless, and
/// the entry's absence costs only the next process that wants it. Announced once per
/// device; the payload names the directory, its cap and the largest entry it takes. Later
/// failures are counted alone
@@ -3738,6 +3778,7 @@ impl Device {
/// Say the message `message` makes, of kind `told`, unless the device said one of that kind
/// before: through the device's message sink, else on stderr, on the calling thread. A later
/// one is counted ([`Told`]) and not made.
#[cold]
pub(crate) fn tell(&self, told: Told, message: impl FnOnce() -> DebugMessage) {
let shared = self.shared();
if !shared.announced.first(told) {
@@ -3755,6 +3796,7 @@ impl Device {
/// for at each occurrence, `DeviceOptions::announce_each`), `describe` giving the object and
/// the reason: through the device's message sink, else on stderr, on the calling thread (the
/// module docs).
#[cold]
pub(super) fn degrade(
&self,
degradation: Degradation,
@@ -3771,6 +3813,7 @@ impl Device {
/// but once per reason rather than once per kind: the cause of a copy (`CopiedBecause`), or
/// `None` for a buffer lying in the live copy another buffer was made over. A consumer acts on
/// a refused import, a failed one and a move apart, so each is heard.
#[cold]
pub(super) fn degrade_copied_pages(
&self,
reason: Option<CopiedBecause>,
@@ -3785,6 +3828,7 @@ impl Device {
/// the rule that kept a render pass from the GPU form, which its notice names, a render pass's
/// step that names none, or a compute execution's. A walk of a program sees why each of its
/// GPU-driven passes takes the host step, not only the first one met.
#[cold]
pub(crate) fn degrade_host_step(
&self,
key: HostStepKey,
@@ -3807,6 +3851,7 @@ impl Device {
/// Announce `degradation` where `first` answers it is announced now, given the device's
/// record and whether a call is encoded again at a rebind ([`degrade`](Self::degrade)).
#[cold]
fn degrade_where(
&self,
degradation: Degradation,
@@ -289,11 +289,14 @@ impl Device {
let dma_buf_images = super::create::dma_buf_image_names(&listed).is_some();
// Nor whether `VK_KHR_external_memory_fd` was (`exported_memory.rs`): the consumer lists
// it.
#[cfg(unix)]
let memory_fd = super::create::memory_fd_name(&listed).is_some();
// Nor whether `VK_EXT_queue_family_foreign` was beside the dma-buf route's
// (`exported_memory.rs`): the consumer lists them.
#[cfg(unix)]
let foreign_family = super::create::foreign_family_name(&listed).is_some();
// Nor whether `VK_KHR_external_semaphore_fd` was (`exported_semaphore.rs`).
#[cfg(unix)]
let semaphore_fd = super::create::semaphore_fd_name(&listed).is_some();
let graphics_pipeline_library = super::create::graphics_pipeline_library(&listed, || {
// SAFETY: the consumer's physical device of its instance, which lists the
@@ -340,6 +343,7 @@ impl Device {
least_plan: false,
staging: None,
fill: None,
copies: None,
reserved_queues: Vec::new(),
extra_queues: Vec::new(),
compile,
@@ -352,8 +356,11 @@ impl Device {
.any(|name| name.as_c_str() == ash::ext::pipeline_creation_feedback::NAME),
dma_buf,
dma_buf_images,
#[cfg(unix)]
memory_fd,
#[cfg(unix)]
foreign_family,
#[cfg(unix)]
semaphore_fd,
calibration: gpu_time::Extension::among(&raw.device_extensions.into_iter().collect()),
gpu_times_from_host: raw.gpu_times_from_host,
@@ -363,6 +370,8 @@ impl Device {
load_no_dynamic_library_file: raw.load_no_dynamic_library_file,
pipeline_records: raw.pipeline_records,
fail_in_place_check: false,
#[cfg(test)]
view_facts: Some(std::collections::BTreeSet::new()),
assume_submissions_merge: false,
// On where `METAL2VULKAN_PENDING_AUDIT` is set (`assemble`).
pending_audit: false,
@@ -1,5 +1,6 @@
//! What a device's recovery carries to its next generation (`line.rs`): the program's events, its
//! uses of guest RAM, its no-copy buffers, the buffers of the runtime's memory whose bytes no
//! uses of guest RAM, its keeps of shared dma-bufs (`dma_buf/kept.rs`: each file kept on the new
//! generation, imported there at the first buffer over a piece of it), its no-copy buffers, the buffers of the runtime's memory whose bytes no
//! pointer of the program's reaches or whose pages the runtime owns, its `Private` heaps and its
//! heaps over the caller's memory with the buffers placed in them, its textures made by a call
//! the recovery makes again (those placed in the heaps it carries among them)
@@ -150,6 +151,8 @@
use super::{lock, Device, DeviceShared};
use crate::buffer::Buffer;
#[cfg(unix)]
use crate::dma_buf::KeptFile;
use crate::event::EventShared;
use crate::function_table::carry::WeakFunctionTable;
use crate::function_table::VisibleFunctionTable;
@@ -206,6 +209,10 @@ struct State {
/// The program's uses of guest RAM (`host_ram.rs`'s `HostRamUse`), held weakly: few, so their
/// gone entries are dropped at each keeping.
ram_uses: Vec<Weak<RamUseCell>>,
/// The program's keeps of shared dma-bufs (`dma_buf/kept.rs`'s `SharedDmaBufImport`), held
/// weakly: as `ram_uses`.
#[cfg(unix)]
kept_files: Vec<Weak<KeptFile>>,
/// The program's heaps, held weakly: as `ram_uses`.
heaps: Vec<WeakHeap>,
/// The program's textures and views (`texture/carry.rs`), held weakly, in the order they were
@@ -284,6 +291,8 @@ pub(crate) struct Taken {
buffers: Vec<Buffer>,
events: Vec<Arc<EventShared>>,
ram_uses: Vec<Arc<RamUseCell>>,
#[cfg(unix)]
kept_files: Vec<Arc<KeptFile>>,
heaps: Vec<Heap>,
textures: Vec<Texture>,
links: Vec<Arc<GenerationLink>>,
@@ -328,6 +337,16 @@ impl Carry {
state.taken
}
/// Keep `cell`, a keep of a shared dma-buf made or carried to this generation: as
/// [`ram_use`](Self::ram_use).
#[cfg(unix)]
pub(crate) fn kept_file(&self, cell: &Arc<KeptFile>) -> bool {
let mut state = lock(&self.state);
state.kept_files.retain(|cell| cell.strong_count() > 0);
state.kept_files.push(Arc::downgrade(cell));
state.taken
}
/// Keep `heap`, made on this generation: as [`ram_use`](Self::ram_use).
pub(crate) fn heap(&self, heap: &Heap) -> bool {
let mut state = lock(&self.state);
@@ -441,6 +460,8 @@ impl Carry {
buffers,
events: state.events.iter().filter_map(Weak::upgrade).collect(),
ram_uses: state.ram_uses.iter().filter_map(Weak::upgrade).collect(),
#[cfg(unix)]
kept_files: state.kept_files.iter().filter_map(Weak::upgrade).collect(),
heaps: state.heaps.iter().filter_map(WeakHeap::upgrade).collect(),
textures: (state.textures.iter())
.filter_map(WeakTexture::upgrade)
@@ -624,6 +645,7 @@ pub(crate) enum Left {
/// "identical to the buffer associated with the imported memory"
/// (`VUID-VkMemoryDedicatedAllocateInfo-buffer-01879`), and Vulkan defines no buffer of
/// another device so.
#[cfg(unix)]
DedicatedOpaqueFd,
}
@@ -647,9 +669,9 @@ impl HeapLeft {
match left {
Left::Pooled => HeapLeft::Pooled,
Left::NoCopy => HeapLeft::NoCopy,
Left::Heap | Left::Caller | Left::Exported | Left::Failed | Left::DedicatedOpaqueFd => {
HeapLeft::Failed
}
Left::Heap | Left::Caller | Left::Exported | Left::Failed => HeapLeft::Failed,
#[cfg(unix)]
Left::DedicatedOpaqueFd => HeapLeft::Failed,
}
}
}
@@ -937,6 +959,8 @@ impl Device {
buffers,
events,
ram_uses,
#[cfg(unix)]
kept_files,
heaps,
textures,
links,
@@ -970,6 +994,11 @@ impl Device {
for event in &events {
carried.event(event.carry(next));
}
// Before the buffers: a no-copy buffer over a piece of a kept file imports it kept there.
#[cfg(unix)]
for cell in &kept_files {
cell.carry(next);
}
// Before the buffers: a no-copy buffer over a RAM's pages lies in its chunks there.
for cell in &ram_uses {
carried.ram_use(cell.carry(next));
@@ -9,14 +9,26 @@
//! module's two entry points in place of the driver's ([`route`]), and so does the exit guard's
//! table made from them (`functions.rs`, [`entry`]). Every pipeline the runtime makes on the
//! device comes here, priming's too. Each entry point finds its device's own and calls it.
//! - **On a stack with room.** A driver compiles on the thread that makes the call, and its
//! compiler can take more stack than a thread has: ANV's on the Iris Xe recurses about 80 bytes
//! deep for each value of a chain of dependent values (a kernel of a 40,000-value chain
//! overflowed a pool thread's 2 MiB at 25,972 frames and 2.09 MB, and takes about 3.2 MB), and
//! compiles the device's priming kernel inside its making (`prime.rs`), on the thread that makes
//! the device. Metal compiles in a service of its own, so no program's stack takes its compiles.
//! A call runs on the asking thread only where its stack has [`COMPILE_ROOM`] left
//! (`this_thread::stack_room`): a program's main thread on Linux or macOS, and the pipeline
//! pool's threads, started with [`COMPILE_STACK`]. A thread with less (a Rust thread's 2 MiB, a
//! macOS secondary thread's 512 KiB, a Windows main thread's 1 MiB) or where the system does
//! not say hands the call to a thread of the runtime's own, as below, started with
//! [`COMPILE_STACK`].
//! - **On the asking thread at that class**: a thread of the pipeline pool's (`pipeline/pool.rs`),
//! or a program's thread at the user-initiated or user-interactive class.
//! or a program's thread at the user-initiated or user-interactive class, its stack with room.
//! - **Else on a thread of the runtime's own, the asking thread waiting** ([`at_user_initiated`]):
//! a thread started for the call at the user-initiated class. It makes the one Vulkan call with
//! the asking thread's arguments, hands back its result, and is joined before the call returns
//! (a full join). Nothing else is done there: what to make, in what order, and what the program
//! sees are decided on the asking thread, before and after. The asking thread's class, overrides
//! and scheduling stay as found.
//! a thread started for the call at the user-initiated class, with [`COMPILE_STACK`]. It makes
//! the one Vulkan call with the asking thread's arguments, hands back its result, and is joined
//! before the call returns (a full join). Nothing else is done there: what to make, in what
//! order, and what the program sees are decided on the asking thread, before and after. The
//! asking thread's class, overrides and scheduling stay as found.
//! - **The driver's measured diagnostics.** The driver reports a message on the thread that makes
//! the call, and the diagnostics the asking thread's call is measured to report are withheld
//! inside that call alone (`driver_facts.rs`). So the thread takes the asking thread's
@@ -47,7 +59,8 @@
//! a call relayed to a thread of the runtime's is counted there and none is dropped; the relay's
//! own thread start and join, which the asking thread pays, lie outside the window and are the
//! runtime's.
//! - Elsewhere than macOS there is no class: every call is made on the asking thread.
//! - Elsewhere than macOS there is no class: every call is made on the asking thread where its
//! stack has the room.
//!
//! The device's creation (`create.rs`) runs `vkCreateDevice` through [`at_user_initiated`] too,
//! since MoltenVK compiles its own command shaders there. The compiles MoltenVK makes inside
@@ -299,12 +312,27 @@ pub(crate) fn holding<R>(call: impl FnOnce() -> R) -> (R, Vec<(MessageSink, Debu
(made, messages)
}
/// The stack each thread of the runtime's own that makes a driver's compile starts with (the
/// module's **On a stack with room**): the 8 MiB the GNU C library gives a thread by default (the
/// customary `RLIMIT_STACK`), on which drivers' own compile threads run (Mesa's `util_queue`).
/// Address space alone: the system commits a stack's pages as they are touched.
pub(crate) const COMPILE_STACK: usize = 8 << 20;
/// The room a thread's stack must have left below the asking frame for a driver's compile to run
/// on it (the module's **On a stack with room**): half of [`COMPILE_STACK`], which a Linux or macOS
/// program's main thread has. ANV's compiler on the Iris Xe recurses about 80 bytes deep for each
/// value of a chain of dependent values: a kernel of a 40,000-value chain takes about 3.2 MB of
/// it (`tests::partial_threadgroups`).
pub(crate) const COMPILE_ROOM: usize = COMPILE_STACK / 2;
/// Run `call`, one Vulkan call that may compile, at the user-initiated quality of service or
/// above (the module docs). It runs here where this thread is at that class, and otherwise on a
/// thread of the runtime's own at it while this thread waits. It runs here too where no thread
/// starts or the process is exiting.
/// above and on a stack with [`COMPILE_ROOM`] left (the module docs). It runs here where this
/// thread is at that class and its stack has that room, and otherwise on a thread of the
/// runtime's own at that class, started with [`COMPILE_STACK`], while this thread waits. It runs
/// here too where no thread starts or the process is exiting.
pub(super) fn at_user_initiated<R: Send>(call: impl FnOnce() -> R + Send) -> R {
if exit_guard::at_least_user_initiated() {
let room = crate::this_thread::stack_room().is_some_and(|room| room >= COMPILE_ROOM);
if room && exit_guard::at_least_user_initiated() {
return call();
}
// The driver diagnostics this thread's call is measured to report: the driver reports them
@@ -315,7 +343,9 @@ pub(super) fn at_user_initiated<R: Send>(call: impl FnOnce() -> R + Send) -> R {
let taken = &mut asked;
let thread = exit_guard::spawn_scoped(
scope,
std::thread::Builder::new().name("metal2vulkan-compile".into()),
std::thread::Builder::new()
.name("metal2vulkan-compile".into())
.stack_size(COMPILE_STACK),
move || {
exit_guard::raise_to_user_initiated();
let _busy = exit_guard::enter()?;
@@ -642,10 +672,21 @@ mod tests {
/// `ask`'s answer on a thread that ran `set` first and marked itself the asking thread: a
/// thread started as the runtime starts its own (`exit_guard::spawn_scoped`), standing for a
/// program's thread here, since nothing on the way to the driver asks which it is.
/// program's thread here, since nothing on the way to the driver asks which it is. Its stack
/// is [`COMPILE_STACK`](super::COMPILE_STACK), with the room a call made on it takes.
fn asked<R: Send>(set: impl FnOnce() + Send, ask: impl FnOnce() -> R + Send) -> R {
asked_on(super::COMPILE_STACK, set, ask)
}
/// [`asked`] on a thread of `stack` bytes of stack.
fn asked_on<R: Send>(
stack: usize,
set: impl FnOnce() + Send,
ask: impl FnOnce() -> R + Send,
) -> R {
std::thread::scope(|scope| {
crate::exit_guard::spawn_scoped(scope, std::thread::Builder::new(), || {
let thread = std::thread::Builder::new().stack_size(stack);
crate::exit_guard::spawn_scoped(scope, thread, || {
set();
ASKING.with(|asking| asking.set(true));
ask()
@@ -656,6 +697,62 @@ mod tests {
})
}
/// A driver's `vkCreateGraphicsPipelines` that makes each pipeline's handle say the room its
/// thread's stack had left (`this_thread::stack_room`, 0 where none is known), and whether
/// that is the asking thread (bit 63).
unsafe extern "system" fn roomed(
_: vk::Device,
_: vk::PipelineCache,
count: u32,
_: *const vk::GraphicsPipelineCreateInfo<'_>,
_: *const vk::AllocationCallbacks<'_>,
pipelines: *mut vk::Pipeline,
) -> vk::Result {
let asking = u64::from(ASKING.with(Cell::get));
let room = crate::this_thread::stack_room().unwrap_or(0) as u64;
for at in 0..count as usize {
// SAFETY: the caller's array of `count` pipelines.
unsafe { *pipelines.add(at) = vk::Pipeline::from_raw(room | asking << 63) };
}
vk::Result::SUCCESS
}
/// A pipeline asked for on a thread whose stack has less than
/// [`COMPILE_ROOM`](super::COMPILE_ROOM) left (one of 256 KiB, as a program's thread that
/// makes a device may have) is made on a thread of the runtime's, whose stack has that room;
/// one asked for on a thread with that room (of [`COMPILE_STACK`](super::COMPILE_STACK)
/// bytes), on the asking thread (at the user-initiated class on macOS). A thread of 2 MiB goes
/// by the room it has: the GNU C library may give a thread a stack an ended thread left, up
/// to four times the size asked (8 MiB for 2 MiB). The asking thread's own stack never takes
/// a driver's compile without the room: ANV's compiler overflowed a 256 KiB and a 2 MiB one.
#[test]
fn a_pipeline_asked_for_on_a_small_stack_is_made_on_a_stack_with_the_room() {
let device = routed(0x6d32_7600_0005, roomed);
let room = super::COMPILE_ROOM;
let set = || {
#[cfg(target_os = "macos")]
at(libc::qos_class_t::QOS_CLASS_USER_INITIATED)();
};
for stack in [256 << 10, 2 << 20, super::COMPILE_STACK] {
let (asker, raw) = asked_on(stack, set, || {
(crate::this_thread::stack_room().unwrap_or(0), make(&device))
});
let (ran, asking) = ((raw & !(1 << 63)) as usize, raw >> 63 == 1);
assert!(
asking == (asker >= room) && ran >= room,
"asked on {stack} bytes with {asker} bytes of room: made on the asking thread \
{asking}, {ran} bytes of room"
);
if stack == 256 << 10 {
assert!(!asking, "on 256 KiB: on the runtime's thread");
}
if stack == super::COMPILE_STACK {
assert!(asking, "on the compile stack: on the asking thread");
}
}
unregister(device.handle());
}
/// The handle of a pipeline the routed device made.
fn make(device: &ash::Device) -> u64 {
let info = vk::GraphicsPipelineCreateInfo::default();
@@ -687,7 +784,8 @@ mod tests {
/// A pipeline asked for on a thread below the user-initiated class is made on a thread of
/// the runtime's at that class, the asking thread's class untouched; at that class or above,
/// on the asking thread. Elsewhere than macOS, always on the asking thread.
/// on the asking thread. Elsewhere than macOS, always on the asking thread, whose stack has
/// the room ([`asked`]).
#[test]
fn a_pipeline_is_made_at_the_user_initiated_class_and_the_asker_is_left_as_found() {
let device = routed(0x6d32_7600_0001, told);
@@ -26,8 +26,9 @@
//! extensions, recommended features and extensions to withhold, where debug-utils messages go,
//! which loader opens, which kind of physical device qualifies, and the shader cache directory.
//! Nothing is read from the environment, except where the platform keeps the default shader cache
//! directory (`HOME`, and `XDG_CACHE_HOME` off macOS) and, on macOS, where the Vulkan SDK is
//! (`VULKAN_SDK`), one of the places the default loader is looked for (`default_loaders`).
//! directory (`LOCALAPPDATA` on Windows, `HOME` on macOS, `XDG_CACHE_HOME` and `HOME` elsewhere)
//! and, on macOS, where the Vulkan SDK is (`VULKAN_SDK`), one of the places the default loader is
//! looked for (`default_loaders`).
use super::instance_requirements::instance_requirements_met;
use super::keeper::keep_drivers_loaded;
@@ -371,6 +372,12 @@ pub struct DeviceOptions {
/// `Device::queue_switch_check_report`) on a device whose queues the limits changed. No Metal
/// counterpart: a Vulkan-side option, for tests and tools that make many devices.
pub queue_limits: Option<QueueLimits>,
/// In the runtime's own tests, the view check's facts (`view_check.rs`): `Some` fixes them,
/// with no check run, so a test's compiles take one profile from the device's first pipeline
/// to its last (none by default: a uniform view stays a uniform buffer, as on a device whose
/// check found no fact); `None` runs the check as a device outside the tests does.
#[cfg(test)]
pub(crate) view_facts: Option<BTreeSet<metal2vulkan::device::DriverWorkaround>>,
}
/// The most `VkQueue`s a device takes for its command queues ([`DeviceOptions::queue_limits`]).
@@ -427,9 +434,11 @@ impl std::fmt::Debug for DeviceOptions {
extra_queues,
reserved_queues,
queue_limits,
#[cfg(test)]
view_facts,
} = self;
f.debug_struct("DeviceOptions")
.field("policy", policy)
let mut out = f.debug_struct("DeviceOptions");
out.field("policy", policy)
.field("layers", layers)
.field("layer_settings", layer_settings)
.field("instance_extensions", instance_extensions)
@@ -470,8 +479,10 @@ impl std::fmt::Debug for DeviceOptions {
.collect::<Vec<_>>(),
)
.field("reserved_queues", reserved_queues)
.field("queue_limits", queue_limits)
.finish()
.field("queue_limits", queue_limits);
#[cfg(test)]
out.field("view_facts", view_facts);
out.finish()
}
}
@@ -510,6 +521,8 @@ impl Default for DeviceOptions {
extra_queues: Default::default(),
reserved_queues: Default::default(),
queue_limits: default_queue_limits(),
#[cfg(test)]
view_facts: Some(BTreeSet::new()),
}
}
}
@@ -1246,6 +1259,15 @@ pub(crate) struct QueuePlan {
/// one; `None` otherwise. An extra queue the caller asks for takes it as a queue the plan
/// leaves free ([`extra_queue_places`]).
pub(crate) fill: Option<(u32, u32)>,
/// The queue the program's command queues made for copies submit to
/// (`Device::new_command_queue_for_copies`), of the staging queue's family where that family
/// is of transfers alone (a copy engine), has a second queue and writes timestamps of the
/// primary family's valid bits: its first queue past the staging and fill queues where it has
/// one, else the fill queue's, which the fill queue's submissions and those command queues'
/// then share under one lock (`device/staging.rs`); never the staging queue's, which waits
/// for no work in flight. `None` otherwise. An extra queue the caller asks for takes it as a
/// queue the plan leaves free ([`extra_queue_places`]).
pub(crate) copies: Option<(u32, u32)>,
}
/// The queues a device of `families` takes: where every family is equivalent to the first that
@@ -1369,6 +1391,12 @@ pub(crate) fn queue_plan_within(
let staging = copy_engine
.or_else(beside)
.map(|(index, _)| (index as u32, 0));
// The copy queue: a copy engine's third queue, else its second, the fill queue's.
let copies = copy_engine
.filter(|(_, family)| {
family.queue_count > 1 && family.timestamp_valid_bits == first.timestamp_valid_bits
})
.map(|(index, family)| (index as u32, if family.queue_count > 2 { 2 } else { 1 }));
// Where every family is equivalent, the primary is family 0, so either way the primary
// family's first queue leads (internal submissions go there).
Some(QueuePlan {
@@ -1378,9 +1406,18 @@ pub(crate) fn queue_plan_within(
reserved,
staging,
fill,
copies,
})
}
impl QueuePlan {
/// The copy queue's place where it is a `VkQueue` of its own, not the fill queue's: one more
/// queue the device takes (`families_taken`, [`vk_queues`]).
pub(crate) fn copy_queue_apart(&self) -> Option<(u32, u32)> {
self.copies.filter(|&place| Some(place) != self.fill)
}
}
/// What the queue plan gives a device of `families` whose queue limits
/// (`DeviceOptions::queue_limits`) gave it `plan` and `extra_places`, for `reserved` reserved and
/// `extra` extra queues asked for, on a device whose textures' images may lie in memory the host
@@ -1432,15 +1469,28 @@ pub(crate) const LEAST_QUEUE_LIMITS: QueueLimits = QueueLimits {
/// The least queue plan of a device of `families` made with `options`, its textures' images in
/// memory the host caches or not (`cached`, as [`queue_plan`] takes it): the plan within
/// [`LEAST_QUEUE_LIMITS`], with the reserved and extra queues `options` asks for, placed as
/// [`extra_queue_places`] places them.
/// [`LEAST_QUEUE_LIMITS`], with as many reserved queues as the device's own plan (within
/// `options`' queue limits) reserves of those `options` asks for, no more, and the extra queues
/// it asks for, placed as [`extra_queue_places`] places them. The least plan's round robin of
/// one leaves room for more reserved queues than the plan's floor of [`LEAST_QUEUES`] and
/// presenting's [`PRESENT_QUEUES`] do, but a device the driver refuses for want of its resources
/// takes no more queues for the caller than the plan gives: what the caller is given does not
/// change with the driver's answer (on an RTX 2080 asked for 11, 10 by the plan, not 11).
pub(crate) fn least_queue_plan(
families: &[vk::QueueFamilyProperties],
options: &DeviceOptions,
cached: bool,
) -> Option<PlacedQueues> {
let planned = queue_plan_within(
families,
options.reserved_queues,
options.queue_limits,
cached,
)?;
// At most the family's queue count, so within `u32`.
let reserved = planned.reserved.len() as u32;
let limits = Some(LEAST_QUEUE_LIMITS);
let mut plan = queue_plan_within(families, options.reserved_queues, limits, cached)?;
let mut plan = queue_plan_within(families, reserved, limits, cached)?;
let extra = extra_queue_places(families, &mut plan, &options.extra_queues);
Some((plan, extra))
}
@@ -1453,6 +1503,7 @@ pub(crate) fn vk_queues((plan, extra): &PlacedQueues) -> usize {
+ plan.reserved.len()
+ usize::from(plan.staging.is_some())
+ usize::from(plan.fill.is_some())
+ usize::from(plan.copy_queue_apart().is_some())
+ extra.iter().flatten().count()
}
@@ -1460,10 +1511,12 @@ pub(crate) fn vk_queues((plan, extra): &PlacedQueues) -> usize {
/// `VkDeviceQueueCreateInfo` each.
fn families_taken(plan: &QueuePlan, extra_places: &[Option<(u32, u32)>]) -> Vec<(u32, usize)> {
let mut taken: Vec<(u32, usize)> = Vec::new();
let copies = plan.copy_queue_apart();
let all = (plan.queues.iter().chain(&plan.present))
.chain(&plan.reserved)
.chain(&plan.staging)
.chain(&plan.fill)
.chain(&copies)
.chain(extra_places.iter().flatten());
for &(family, _) in all {
match taken.iter_mut().find(|(at, _)| *at == family) {
@@ -1619,8 +1672,10 @@ pub(crate) const QUEUE_LIMITS_REACHED: &str = "metal2vulkan-queue-limits-reached
/// at its lowest free index; else the last queue the plan reserved for presenting, then the last
/// of the round robin's but its first (internal submissions go there), then the staging queue, of
/// such a family, which `plan` then gives up; never a queue reserved for the caller. The fill
/// queue is one the plan leaves free: an extra queue may take it, and the plan then gives it up.
/// Flags that are empty, or that no family's contain, take none.
/// queue and the copy queue are queues the plan leaves free: an extra queue may take either, and
/// the plan then gives it up (and the copy queue with the fill queue, where it is the fill
/// queue's, or with the staging queue). Flags that are empty, or that no family's contain, take
/// none.
pub(crate) fn extra_queue_places(
families: &[vk::QueueFamilyProperties],
plan: &mut QueuePlan,
@@ -1661,13 +1716,22 @@ pub(crate) fn extra_queue_places(
});
if let Some(place) = place {
extra.push(place);
// The fill queue is a queue the plan leaves free to the caller's extra queues.
// The fill and copy queues are queues the plan leaves free to the caller's extra
// queues.
if plan.fill == Some(place) {
plan.fill = None;
}
if plan.copies == Some(place) {
plan.copies = None;
}
}
places.push(place);
}
// The copy queue's buffers are those shared with the staging queue's family (`sharing.rs`):
// it goes with that queue.
if plan.staging.is_none() {
plan.copies = None;
}
places
}
@@ -2513,6 +2577,7 @@ pub(super) fn create_on(
queues: plan.queues.into_iter().chain(plan.present).collect(),
staging: plan.staging,
fill: plan.fill,
copies: plan.copies,
reserved_queues: plan.reserved,
extra_queues: (options.extra_queues.iter().zip(&extra_places))
.filter_map(|(&flags, place)| place.map(|(family, index)| (flags, family, index)))
@@ -2530,6 +2595,8 @@ pub(super) fn create_on(
load_no_dynamic_library_file: options.load_no_dynamic_library_file,
pipeline_records: options.pipeline_records.clone(),
fail_in_place_check: options.fail_in_place_check,
#[cfg(test)]
view_facts: options.view_facts.clone(),
assume_submissions_merge: options.assume_submissions_merge,
pending_audit: options.pending_audit,
encoder_trail: options.encoder_trail,
@@ -2544,8 +2611,11 @@ pub(super) fn create_on(
creation_feedback: creation_feedback || feedback_asked,
dma_buf: dma_buf.is_some(),
dma_buf_images: dma_buf_images.is_some(),
#[cfg(unix)]
memory_fd: memory_fd.is_some(),
#[cfg(unix)]
foreign_family: foreign_family.is_some(),
#[cfg(unix)]
semaphore_fd: semaphore_fd.is_some(),
sparse_features,
memory_reads,
@@ -2746,8 +2816,10 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool {
extra_queues,
reserved_queues,
queue_limits,
#[cfg(test)]
view_facts,
} = a;
*policy == b.policy
let same = *policy == b.policy
&& *layers == b.layers
&& *layer_settings == b.layer_settings
&& *instance_extensions == b.instance_extensions
@@ -2775,7 +2847,10 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool {
&& *color_attachment_limit == b.color_attachment_limit
&& *extra_queues == b.extra_queues
&& *reserved_queues == b.reserved_queues
&& *queue_limits == b.queue_limits
&& *queue_limits == b.queue_limits;
#[cfg(test)]
let same = same && *view_facts == b.view_facts;
same
}
/// The group of `made` for `options`: the live one, or a new one on a new instance. Its index.
@@ -2846,11 +2921,20 @@ impl Device {
/// last device and load them again for the next, which some drivers cannot do indefinitely.
pub fn system_default_with(options: &DeviceOptions) -> Result<Device, Error> {
let cache = CacheSetup::of(&options.shader_cache, "system_default_with")?;
Device::system_default_set_up(options, &cache)
}
/// [`Device::system_default_with`] with its shader cache set up already as `cache`, which a
/// test sets up from an environment of its own (`tests::shader_cache_no_directory`).
pub(crate) fn system_default_set_up(
options: &DeviceOptions,
cache: &CacheSetup,
) -> Result<Device, Error> {
let mut made = lock(&MADE);
let (at, instance) = group(&mut made, options)?;
let mut refusal = None;
for physical in ranked(&instance, options)? {
match device_of(&mut made[at], &instance, physical, options, &cache) {
match device_of(&mut made[at], &instance, physical, options, cache) {
Ok(device) => return Ok(device),
Err(error) => {
refusal.get_or_insert(error);
@@ -1,5 +1,6 @@
//! The runtime's own holds of a device: its check of textures in place (`in_place_check.rs`) and
//! its warm pass (`warm/pass.rs`), each on a thread of its own, and a pool piece's making of a
//! The runtime's own holds of a device: its check of textures in place (`in_place_check.rs`), its
//! check of what linear images cost (`tiling_check.rs`) and its warm pass (`warm/pass.rs`), each
//! on a thread of its own, and a pool piece's making of a
//! render execution's draw replay kernels ahead (`owned_kernel.rs`), which hold the device while
//! they make objects on it and let it go between their steps; and a release it posts to a handler
//! thread for the program, a host import's that a keep-alive alone waits for (`buffer.rs`).
@@ -56,8 +57,21 @@ pub(crate) enum Holder {
/// The pool's making of a render execution's draw replay kernels ahead
/// (`Device::begin_draw_replay_kernels`), between its kernels.
DrawReplayKernels,
/// The pool's making of the rate-map routes' kernel ahead
/// (`Device::begin_route_counts_kernel`), before it.
RouteCountsKernel,
/// The check of what linear images cost against optimal ones, between its rounds
/// (`tiling_check.rs`).
TilingCheck,
/// The check of what a `constant` window's views cost, between its rounds
/// (`view_check.rs`).
ViewCheck,
}
/// The holders: one test hold each ([`Holds::held`]).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
const HOLDERS: usize = Holder::ViewCheck as usize + 1;
/// A device's registry of its handles and the runtime's own holds (the module docs).
#[derive(Default)]
pub(crate) struct Holds {
@@ -76,7 +90,7 @@ pub(crate) struct Holds {
/// The crate's device tests' holds of each holder between its steps
/// (`tests/teardown_threads.rs`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
held: [crate::freed_memory::held::Held; 3],
held: [crate::freed_memory::held::Held; HOLDERS],
}
/// The registry's count of the holders' handles, and its stop.
@@ -87,8 +87,12 @@ pub(crate) struct Invariant {
pub(crate) compile: metal2vulkan::device::Device,
pub(crate) enabled: EnableSet,
pub(crate) extensions: Vec<CString>,
/// The shader cache's directory (`Device::shader_cache_directory`).
pub(crate) cache_directory: PathBuf,
/// The shader cache's directory (`Device::shader_cache_directory`); `None` where it keeps
/// none.
pub(crate) cache_directory: Option<PathBuf>,
/// The view check (`view_check.rs`): its answer, and the compile device of its measured
/// facts once it holds any, which every compile then takes (`Device::compile_device`).
pub(crate) views: Arc<crate::view_check::ViewCheck>,
}
/// How the line makes its next `VkDevice`: what the first was made of (`create.rs`). None for a
+294 -53
View File
@@ -33,10 +33,13 @@ pub(crate) mod queue_quiet;
pub(crate) mod relay;
mod staging;
pub(super) mod submit;
pub(crate) mod submit_calls;
pub(crate) mod submit_stalls;
pub use adopt::RawDevice;
pub(crate) use compiles::holding;
#[cfg(test)]
pub(crate) use compiles::COMPILE_ROOM;
pub(crate) use compiles::{holding, COMPILE_STACK};
pub(crate) use create::{queue_limits_reached, QUEUE_LIMITS_REACHED};
pub use create::{
DebugMessage, DeviceOptions, LayerSetting, LayerSettingValue, MessageKind, MessageSeverity,
@@ -53,7 +56,7 @@ use super::capabilities::DeviceProperties;
use super::color_resolve::ColorResolveObjects;
use super::command_buffer::fences::Fences;
use super::command_buffer::{Completion, Item};
use super::contexts::{Contexts, THREADS};
use super::contexts::{self, Contexts};
use super::degradation::{Announced, Degradation, Told};
use super::depth_copy::DepthCopyObjects;
use super::depth_stencil_resolve::DepthStencilResolveObjects;
@@ -92,7 +95,7 @@ use super::stencil_copy::StencilCopyObjects;
use super::texture::TextureState;
use super::unique_identifier::UniqueIdentifiers;
use crate::image_barrier::MemoryReads;
use crate::recorder::{Command, MeshDraws, MultiDraws, Slot};
use crate::recorder::{Command, CountDraws, MeshDraws, MultiDraws, Slot};
use crate::release;
use ash::vk::{self, Handle};
use functions::{Functions, Vk};
@@ -104,7 +107,7 @@ use staging::Role;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, Weak};
use std::time::Instant;
use std::time::{Duration, Instant};
use submit::{Internal, OwnTimeline};
/// A Metal device (`MTLDevice`) on a Vulkan device. Cheap to clone (a retain); `Send + Sync`.
@@ -269,8 +272,11 @@ pub(super) struct DeviceShared {
/// buffers are shared among (`sharing.rs`).
pub(super) buffer_families: Vec<u32>,
/// How many of `queues`, the first, logical queues share round robin; the rest are reserved
/// for presenting queues.
/// for presenting queues, but the copy queue's.
round_robin: usize,
/// The index of the copy queue's `VkQueue` among `queues`, the last, where the device has
/// one (`queue.rs`, `Device::new_command_queue_for_copies`).
copy_slot: Option<usize>,
/// The logical queues made round robin so far, unshared ones among them: the next one's turn
/// among the round robin's `VkQueue`s the fewest live queues hold is this modulo
/// `round_robin` (`Device::take_round_robin`).
@@ -375,8 +381,8 @@ pub(super) struct DeviceShared {
/// `command_buffer/submit.rs`).
pub(super) completed_by_barrier: bool,
/// Each batch ends with `Barrier::to_all`, so a later batch of its `VkQueue` plans no barrier
/// for its accesses, and a batch's start timestamp is written at the bottom of the pipe
/// (`batch_order.rs`).
/// for its accesses, and holds a later batch's start timestamp, at the top of the pipe, until
/// it ended (`batch_order.rs`).
pub(crate) by_ends: bool,
/// The last sparse binding of a no-copy buffer's dma-bufs (`dma_buf.rs`) the host has not
/// seen complete: the internal timeline and the value it signals, which every later
@@ -426,8 +432,11 @@ pub(super) struct DeviceShared {
/// Its check of the first move of an image over host pages, per class of pages, and its
/// verdicts (`in_place.rs`).
pub(crate) in_place: crate::in_place::InPlaceChecks,
/// Its checks of what its submissions cost and whether its pointer imports follow their
/// address, and their verdicts (`submit_check.rs`).
/// Its check of what its linear images cost its GPU against its optimal ones, and its answer
/// (`tiling_check.rs`).
pub(crate) tiling: crate::tiling_check::TilingCheck,
/// Its checks of what its submissions cost (whether submissions that signal nothing merge,
/// and whether a held pointer import adds to each), and their verdicts (`submit_check.rs`).
pub(crate) submit_checks: Arc<crate::submit_check::SubmitChecks>,
/// How no-copy buffers import host memory, or why they are refused.
pub(super) host_import: Result<Importer, metal2vulkan::error::Unsupported>,
@@ -467,6 +476,9 @@ pub(super) struct DeviceShared {
/// and `shaderDrawParameters` and one command may draw at least two regions
/// (`rate_mapped_pass.rs`).
pub(super) multi_draws: Option<MultiDraws>,
/// The indirect-count draw commands a draw the GPU routes records its routes with, where the
/// device enabled `drawIndirectCount` and `multiDrawIndirect` (`render/gpu_routes.rs`).
pub(super) count_draws: Option<CountDraws>,
/// `vkCmdPushDescriptorSet`, from Vulkan 1.4 or `VK_KHR_push_descriptor`
/// (`binding::push_set`). Where the driver has `RuntimeDriverDefect::PushedBufferSizesUnset`
/// only the variants `pipeline::objects::pushes_set_zero` names push with it there, and no
@@ -535,6 +547,9 @@ pub(super) struct DeviceShared {
/// The crate-owned compute kernels the runtime dispatches for itself, made on first use
/// (`owned_kernel.rs`).
pub(super) owned_kernels: Mutex<OwnedKernels>,
/// A pass's first draw the GPU routes began the routes' kernel on the device's pool
/// (`Device::begin_route_counts_kernel`): no later draw begins it again.
pub(super) route_counts_begun: AtomicBool,
/// The two-plane YCbCr formats the device converts itself (`ycbcr_device.rs`).
pub(super) ycbcr_formats: crate::ycbcr_device::YCbCrFormats,
/// The spare scratch block of `generate_mipmaps`' filter chains (`mipmap_scratch.rs`).
@@ -612,12 +627,32 @@ pub(super) struct DeviceShared {
/// (`Device::fail_next_submissions_with`).
#[cfg(test)]
pub(crate) failing_result: std::sync::atomic::AtomicI32,
/// How long each `vkQueueSubmit` of a batch of command buffers takes more, in nanoseconds,
/// slept inside its timed call: the device tests' stand-in for a driver whose calls of
/// commands are slow (`Device::slow_submit_calls`).
#[cfg(test)]
pub(crate) submit_call_pause: AtomicU64,
/// Of those calls, each how manyth is not lengthened, and those counted since it was set: the
/// device tests' stand-in for a short call of commands among slow ones
/// (`Device::fast_submit_call_every`); 0 for none.
#[cfg(test)]
pub(crate) submit_call_fast: (AtomicU64, AtomicU64),
/// The call floor at or above which a committing thread leaves a `VkQueue`'s batches to
/// the scheduler's thread, where a device test set one (`Device::leave_calls_from`); 0 for
/// `submit_calls::SLOW_NANOS`.
#[cfg(test)]
pub(crate) slow_calls_from: AtomicU64,
/// Every linear image of a render target renders as a color attachment only under
/// `VK_NV_linear_color_attachment`'s rule, whatever the device's facts: for the tests of
/// `merge_scratch.rs` on a device that renders one beside any other
/// (`linear_attachment::bound`).
#[cfg(test)]
pub(crate) linear_rule_forced: AtomicBool,
/// Its encoders split at aliases as on a device whose driver has
/// `DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`, whatever its facts: for the
/// tests of `tests/render_fold.rs` on a device without it (`splits_at_aliases`).
#[cfg(test)]
pub(crate) aliases_split_forced: AtomicBool,
/// No linear image takes feedback loop usage (`texture::linear_feedback_candidate`), as
/// NVIDIA's drivers make none with it: for the tests of `tests/leading_snapshots.rs` on a
/// device that makes them so, whose readers then take leading snapshots
@@ -639,6 +674,22 @@ pub(super) struct DeviceShared {
/// shadow then lacks it and is sampled through a usage shadow.
#[cfg(test)]
pub(crate) sampled_costs_forced: AtomicBool,
/// The most bytes of a range `did_modify_range` names that is written inline
/// (`managed::inline_bound`): `managed::INLINE_BYTES`, but where a test sets another (0: none
/// is), for the tests and the bench of `tests/managed_inline.rs`.
#[cfg(test)]
pub(crate) managed_inline_bound: std::sync::atomic::AtomicU64,
/// A batch's first work of uploads alone takes no barrier from the commands before it on any
/// device, its batches ordered by their ends or not (`first_move::Earlier::Ended`): the
/// negative control of `tests/managed_inline.rs`'s write-after-read test, under the exact
/// batch order.
#[cfg(test)]
pub(crate) uploads_unbarriered_forced: AtomicBool,
/// The second scopes of the barriers that made batches' uploads visible to their own uses
/// alone (`first_move::Later::Batch`), in the order recorded: for the test of
/// `tests/managed_inline.rs` that the scope names every stage its batch uses the buffer in.
#[cfg(test)]
pub(crate) upload_scopes: Mutex<Vec<(vk::PipelineStageFlags, vk::AccessFlags)>>,
/// Its encoders record a command that writes a read twin, which they refuse otherwise: the
/// negative control of the tests of `tests/read_twin_device.rs` (`read_twin::refuses_writes`).
#[cfg(test)]
@@ -656,14 +707,14 @@ pub(super) struct DeviceShared {
/// The route a test takes for images over dma-buf pages, whatever the driver answers of an
/// explicit plane's offset (`dma_buf.rs`'s `PlaneRoute`, as its `u8`): for the tests of
/// `tests/dma_buf_plane_offset.rs` on a driver that answers the offset asked.
#[cfg(test)]
#[cfg(all(test, unix))]
pub(crate) plane_route_forced: std::sync::atomic::AtomicU8,
/// The device takes its driver for one whose shaders read an explicit
/// `DRM_FORMAT_MOD_LINEAR` plane's rows at another pitch where they lie a number of bytes
/// apart that is no multiple of 32 (`RuntimeDriverDefect::ExplicitPlanePitchMisread`,
/// `Device::explicit_plane_pitch`): for the tests of `tests/read_twin_device.rs` on a driver
/// that reads them right.
#[cfg(test)]
#[cfg(all(test, unix))]
pub(crate) explicit_plane_pitch_misread_forced: AtomicBool,
/// Where not 0, no image lies in place over host pages or a copy of them whose rows are not
/// that many bytes apart or whose texels do not start at that many bytes' multiple in their
@@ -694,7 +745,6 @@ pub(super) struct DeviceShared {
pub(crate) carry: carry::Carry,
/// The imports of the caller's dma-bufs it releases while idle, and the thread that releases
/// them (`host_residency.rs`).
#[cfg(unix)]
pub(super) residency: super::host_residency::Sweeper,
/// Its one import of each dma-buf a caller's source shares among the chunks of several
/// buffers and heaps, by the file's identity (`dma_buf.rs`'s `DmaBufFiles`).
@@ -703,6 +753,9 @@ pub(super) struct DeviceShared {
/// What lets go of its kept empty memory blocks and parked objects once their time passed,
/// whether or not the program makes anything more, and its thread (`idle_sweep.rs`).
pub(super) idle_sweep: crate::idle_sweep::IdleSweep,
/// The thread its settled spare command pools' primaries are begun ahead on
/// (`begin_ahead.rs`).
pub(crate) begin_ahead: crate::begin_ahead::BeginAhead,
/// How its command buffers are timed on the GPU (`gpu_time.rs`).
pub(super) timing: Timing,
/// Its Vulkan views may present an image in another component layout: it has no portability
@@ -743,9 +796,9 @@ pub(super) struct DeviceShared {
/// The bind states its ended compute encoders left, which the next ones start from
/// (`compute/live.rs`).
pub(super) live_dispatches: crate::compute::SpareLiveDispatches,
/// The storage of the lists of records its released command buffers left, which the next ones
/// start on (`command_buffer/record_storage.rs`).
pub(super) record_storage: crate::command_buffer::record_storage::SpareRecordStorage,
/// The states its released command buffers left, reset, which the next ones take
/// (`command_buffer/spare_states.rs`).
pub(super) spare_states: crate::command_buffer::spare_states::SpareStates,
/// The usage shadows its textures made (`texture/usage_shadow.rs`): a kept list of resident
/// textures' shadows is listed again where it moved (`shadow::ResidentShadows`).
pub(super) usage_shadows_made: std::sync::atomic::AtomicU64,
@@ -767,7 +820,8 @@ pub(super) struct DeviceShared {
/// split, which the next such instances take (`render/inline_splits.rs`).
pub(super) kept_rooms: crate::render::SpareKept,
/// Counts of its commit path's work, for the lanes (`work_counts.rs`). Shared with the
/// queue-switch check's thread (`queue_switch_check.rs`).
/// queue-switch check's thread (`queue_switch_check.rs`) and the begin-ahead thread
/// (`begin_ahead.rs`).
pub(super) counts: Arc<super::work_counts::Counters>,
/// Its uses of its `VkQueue`s seen as one, which its blocks made ahead wait on for a moment
/// right after a burst of submissions (`queue_quiet.rs`, `memory/ready.rs`). Shared with
@@ -804,8 +858,9 @@ pub(super) struct DeviceShared {
/// Its driver's image uses miss a write through a buffer over their memory recorded before
/// them in the same `VkCommandBuffer`
/// (`DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`): its encoders record such a
/// use in a new one (`alias_split.rs`).
pub(crate) splits_at_aliases: bool,
/// use in a new one (`alias_split.rs`). Read through
/// [`splits_at_aliases`](Self::splits_at_aliases).
driver_splits_at_aliases: bool,
/// It loads no dynamic library from a file (`DeviceOptions::load_no_dynamic_library_file`,
/// `dynamic_library.rs`).
pub(crate) load_no_dynamic_library_file: bool,
@@ -844,9 +899,47 @@ impl DeviceShared {
exit_guard::called(Call::QueueWaitIdle);
}
}
/// Whether a committing thread leaves the batches of `VkQueue` `queue` to the scheduler's
/// thread: each of its batches' last calls took `submit_calls::SLOW_NANOS` or more, as timed
/// (`submit_calls.rs`).
pub(crate) fn submits_slowly(&self, queue: usize) -> bool {
let bound = submit_calls::SLOW_NANOS;
#[cfg(test)]
let bound = match self.slow_calls_from.load(Ordering::Relaxed) {
0 => bound,
set => set,
};
self.queues[queue].calls.slow(bound)
}
/// How long the device's work has been quiet, for a step of its view check that the work
/// must never wait on (`view_check.rs`): `None` while a batch committed waits for its
/// submission, a batch submitted is not seen complete on its `VkQueue`, or a use of one of
/// its `VkQueue`s is under way; else the time since the last such use ended
/// (`queue_quiet.rs`).
pub(crate) fn work_quiet_for(&self) -> Option<Duration> {
let in_flight =
(self.queues.iter()).any(|slot| slot.completed_value() < slot.submitted_value());
if in_flight || !self.scheduler.holds_none() {
return None;
}
self.queue_quiet.unused_for()
}
}
impl DeviceShared {
/// Whether its encoders record a use of an image after a write through a buffer over its
/// memory in a new `VkCommandBuffer` (`alias_split.rs`): where its driver's image uses miss
/// such writes inside one (`DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`).
pub(crate) fn splits_at_aliases(&self) -> bool {
#[cfg(test)]
if self.aliases_split_forced.load(Ordering::Relaxed) {
return true;
}
self.driver_splits_at_aliases
}
/// Whether the generation's `VkDevice` was lost.
pub(crate) fn lost(&self) -> bool {
self.lost.load(Ordering::Acquire)
@@ -1070,19 +1163,12 @@ impl DeviceShared {
&self,
info: &vk::CommandBufferAllocateInfo<'_>,
) -> Result<Vec<vk::CommandBuffer>, Error> {
// SAFETY: the device is live; `info` names one of its pools, which the caller holds
// exclusively.
let allocated = unsafe {
self.loader_word
.restored(|| self.vk().allocate_command_buffers(info))
};
exit_guard::called(Call::AllocateCommandBuffers);
let allocated = allocate_command_buffers(self.vk(), &self.loader_word, &self.counts, info);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
if allocated.is_ok() {
self.counts.command_buffers_made(info.command_buffer_count);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
(self.spares).allocated(std::panic::Location::caller(), info.command_buffer_count);
}
allocated.map_err(super::error::vulkan)
allocated
}
/// Name `pipeline`, just made and held by this thread alone, for the layers' messages:
@@ -1133,18 +1219,45 @@ impl DeviceShared {
self.queues[index].flags
}
/// The reads a global memory barrier recorded for the device's `VkQueue` at `index` names
/// (`image_barrier::MemoryReads`): its family's.
pub(crate) fn memory_reads_of(&self, index: usize) -> MemoryReads {
self.queues[index].reads
}
/// Whether an internal submission (`submit.rs`) was made that the host has not seen
/// complete: its commands may still run on the device's first `VkQueue`, and end with no
/// barrier to the commands after them there. Read where no internal submission can be made
/// meanwhile (a batch's place in the first work's order, `texture/first_move.rs`), it holds
/// until that place goes.
pub(crate) fn internal_running(&self) -> bool {
self.internal_done.running()
}
/// How many of its `VkQueue`s, the first, the round robin lends logical queues; the rest are
/// reserved for presenting queues.
/// reserved for presenting queues, but the copy queue's.
pub(crate) fn round_robin(&self) -> usize {
self.round_robin
}
/// How many of its `VkQueue`s, after the round robin's, are reserved for presenting queues.
pub(crate) fn presenting(&self) -> usize {
self.queues.len() - self.round_robin - usize::from(self.copy_slot.is_some())
}
/// The index of the copy queue's `VkQueue`, where the device has one: the last of its
/// `VkQueue`s, of a family of transfers alone (`queue.rs`,
/// `Device::new_command_queue_for_copies`).
pub(crate) fn copy_slot(&self) -> Option<usize> {
self.copy_slot
}
/// Where the device's queue limits changed its round robin's or presenting queues'
/// `VkQueue`s from the queue plan's (`DeviceOptions::queue_limits`), how many it took of
/// each and how many the plan gives.
pub(crate) fn queues_limited(&self) -> Option<((usize, usize), (usize, usize))> {
let planned = self.planned?;
let taken = (self.round_robin, self.queues.len() - self.round_robin);
let taken = (self.round_robin, self.presenting());
(taken != planned).then_some((taken, planned))
}
@@ -1218,13 +1331,15 @@ impl Drop for DeviceShared {
// this teardown runs on its thread.
self.reaper.stop();
// What the residency thread releases holds the device: none is left.
#[cfg(unix)]
self.residency.stop();
// The idle sweep holds nothing of the device: it ends before the parked objects and the
// memory go below (`idle_sweep.rs`).
self.idle_sweep.stop();
self.completion.stop();
self.contexts.stop();
// No command buffer is left to post a pool to the begin-ahead thread, which holds nothing
// of the device: it ends before the spares go below (`begin_ahead.rs`).
self.begin_ahead.stop();
// The encoder times' last summary, where they are on: no completion tallies more
// (`encoder_times.rs`).
for line in self.timing.encoders().last() {
@@ -1377,11 +1492,17 @@ pub(crate) struct QueueSlot {
raw: Mutex<(vk::Queue, submit_stalls::Period)>,
/// Its place's `Period::may_be_due`, as of the last use: read without the lock.
stall_due: AtomicBool,
/// Its batches' last `vkQueueSubmit` calls' times and their floor (`submit_calls.rs`):
/// kept under the lock, the floor read without it.
pub(crate) calls: submit_calls::SubmitCalls,
/// The queue's family, which the command pools of what it runs are made for.
pub(super) family: u32,
/// The family's queue flags: the commands it runs, and so the accesses a barrier recorded
/// for it may name (`image_barrier.rs`).
flags: vk::QueueFlags,
/// The reads a global memory barrier recorded for it names: its family's
/// (`image_barrier::MemoryReads`), a copy engine's transfers alone on the copy queue's.
reads: MemoryReads,
/// The queue's loader word, which MoltenVK overwrites where a message names the queue
/// (`relay.rs`): put back before each use.
word: LoaderWord,
@@ -1619,6 +1740,32 @@ impl Device {
(self.shared().failing_result).store(result.as_raw(), Ordering::Relaxed);
self.fail_next_submissions(count);
}
/// Make each `vkQueueSubmit` of a batch that submits command buffers take `pause` more, inside
/// its timed call, from now on (`None`: no more): the tests' stand-in for a driver whose calls
/// of commands are slow, a call of none not (`submit_calls.rs`).
pub(crate) fn slow_submit_calls(&self, pause: Option<std::time::Duration>) {
let nanos = pause.map_or(0, |pause| pause.as_nanos() as u64);
(self.shared().submit_call_pause).store(nanos, Ordering::Relaxed);
}
/// Of the calls [`slow_submit_calls`](Self::slow_submit_calls) lengthens, leave each `every`th
/// from now on at the driver's own time, the first the `every`th to come (`None`: lengthen
/// each): the tests' stand-in for a short call of commands among slow ones
/// (`submit_calls.rs`, "One short call set aside").
pub(crate) fn fast_submit_call_every(&self, every: Option<u64>) {
let (fast, counted) = &self.shared().submit_call_fast;
counted.store(0, Ordering::Relaxed);
fast.store(every.unwrap_or(0), Ordering::Relaxed);
}
/// A committing thread leaves a `VkQueue`'s batches to the scheduler's thread where their
/// last calls each took `bound` nanoseconds or more, from now on (`None`:
/// `submit_calls::SLOW_NANOS` again): 1 leaves every batch of a queue whose calls were timed,
/// `u64::MAX` none.
pub(crate) fn leave_calls_from(&self, bound: Option<u64>) {
(self.shared().slow_calls_from).store(bound.unwrap_or(0), Ordering::Relaxed);
}
}
impl Device {
@@ -1688,9 +1835,19 @@ impl Device {
WeakDevice(Arc::downgrade(shared), Arc::clone(&shared.holds))
}
/// The compile-and-plan device this device compiles and plans for. No Metal counterpart.
/// The compile-and-plan device this device compiles and plans for now. No Metal counterpart.
/// Its profile is the device description's until the device's view check answers with a fact
/// (`view_check.rs`); from then on, the description's with the check's facts measured
/// ([`Device::view_costs`]), whose profile fingerprint differs. Read it once for one compile
/// and its link.
pub fn compile_device(&self) -> &metal2vulkan::device::Device {
&self.invariant().compile
let invariant = self.invariant();
(invariant.views.measured()).unwrap_or(&invariant.compile)
}
/// The device's view check (`view_check.rs`).
pub(crate) fn view_check(&self) -> &crate::view_check::ViewCheck {
&self.invariant().views
}
/// What the Vulkan device enabled, in the compile layer's vocabulary. No Metal counterpart.
@@ -1973,7 +2130,7 @@ impl Device {
if self.test_queue_limited() {
create::needs_the_queue_plan("made a command queue for presenting");
}
let reserved = self.shared().queues.len() - self.shared().round_robin;
let reserved = self.shared().presenting();
if let Some((_, planned)) = self.shared().planned {
let asked = (self.shared().presenting_asked).fetch_add(1, Ordering::Relaxed);
if create::shares_past_limit(asked, reserved, planned) {
@@ -2016,6 +2173,26 @@ impl Device {
}
}
/// `vkAllocateCommandBuffers` of `info` through `vk`: the loader serves it and reads the device's
/// loader word `word` first ([`DeviceWord::restored`]); counted in `counts`. The device's
/// ([`DeviceShared::allocate_command_buffers`]), and its begin-ahead thread's, which holds no
/// device (`spares.rs`'s `BeginTargets`).
pub(crate) fn allocate_command_buffers(
vk: &Vk,
word: &DeviceWord,
counts: &super::work_counts::Counters,
info: &vk::CommandBufferAllocateInfo<'_>,
) -> Result<Vec<vk::CommandBuffer>, Error> {
// SAFETY: the device is live; `info` names one of its pools, which the caller holds
// exclusively.
let allocated = unsafe { word.restored(|| vk.allocate_command_buffers(info)) };
exit_guard::called(Call::AllocateCommandBuffers);
if allocated.is_ok() {
counts.command_buffers_made(info.command_buffer_count);
}
allocated.map_err(super::error::vulkan)
}
/// The parts [`DeviceShared`] is built from, by `create.rs` and `adopt.rs` alike.
pub(super) struct Parts {
pub(super) instance: Arc<InstanceShared>,
@@ -2043,6 +2220,11 @@ pub(super) struct Parts {
/// `queues` (`staging.rs`): `None` for an adopted device, or where the staging queue's family
/// is not of transfers alone or has no second queue.
pub(super) fill: Option<(u32, u32)>,
/// The queue the program's command queues made for copies submit to
/// (`create.rs`'s `QueuePlan::copies`), its family (the staging queue's) and index there,
/// outside `queues`: the fill queue's where `fill` is the same place, which the two then
/// share; `None` for an adopted device, or where the plan has none.
pub(super) copies: Option<(u32, u32)>,
/// The queues reserved for the caller (`DeviceOptions::reserved_queues`), each its family and
/// index there, of `queues`' families, outside `queues` and `staging`: none for an adopted
/// device.
@@ -2078,6 +2260,10 @@ pub(super) struct Parts {
/// Its check of the first move over host pages fails whatever the moves did
/// (`DeviceOptions::fail_in_place_check`).
pub(super) fail_in_place_check: bool,
/// In the runtime's own tests, its view check's facts, fixed (`DeviceOptions::view_facts`).
#[cfg(test)]
pub(super) view_facts:
Option<std::collections::BTreeSet<metal2vulkan::device::DriverWorkaround>>,
/// Its submission check of merged submissions holds without its answer
/// (`DeviceOptions::assume_submissions_merge`).
pub(super) assume_submissions_merge: bool,
@@ -2128,13 +2314,16 @@ pub(super) struct Parts {
pub(super) dma_buf_images: bool,
/// It enables `VK_KHR_external_memory_fd` (`create.rs`'s `memory_fd_name`; `adopt.rs`, where
/// the consumer lists it), outside `enabled`'s vocabulary (`exported_memory.rs`).
#[cfg(unix)]
pub(super) memory_fd: bool,
/// It enables `VK_EXT_queue_family_foreign` beside the dma-buf route's extensions
/// (`create.rs`'s `foreign_family_name`; `adopt.rs`, where the consumer lists them), outside
/// `enabled`'s vocabulary (`exported_memory.rs`).
#[cfg(unix)]
pub(super) foreign_family: bool,
/// It enables `VK_KHR_external_semaphore_fd` (`create.rs`'s `semaphore_fd_name`; `adopt.rs`,
/// where the consumer lists it), outside `enabled`'s vocabulary (`exported_semaphore.rs`).
#[cfg(unix)]
pub(super) semaphore_fd: bool,
/// The sparse members of the core features it enables, outside `enabled`'s vocabulary
/// (`sparse/device.rs`).
@@ -2176,6 +2365,7 @@ impl Device {
least_plan,
staging: staging_place,
fill: fill_place,
copies: copy_place,
reserved_queues: reserved_places,
extra_queues: extra_places,
compile,
@@ -2191,6 +2381,8 @@ impl Device {
load_no_dynamic_library_file,
pipeline_records,
fail_in_place_check,
#[cfg(test)]
view_facts,
assume_submissions_merge,
pending_audit,
encoder_trail,
@@ -2207,16 +2399,10 @@ impl Device {
dma_buf_images,
#[cfg(unix)]
memory_fd,
#[cfg(not(unix))]
memory_fd: _,
#[cfg(unix)]
foreign_family,
#[cfg(not(unix))]
foreign_family: _,
#[cfg(unix)]
semaphore_fd,
#[cfg(not(unix))]
semaphore_fd: _,
sparse_features,
memory_reads,
owned,
@@ -2224,6 +2410,10 @@ impl Device {
line: recovering,
recipe,
} = parts;
// The copy queue's `VkQueue`, where the device has one, is the last of those the runtime
// submits to, after presenting's (`queue.rs`, `Device::new_command_queue_for_copies`).
let copy_slot = copy_place.map(|_| queue_places.len());
let queue_places: Vec<(u32, u32)> = queue_places.into_iter().chain(copy_place).collect();
// Every pipeline made on the device from here on is made at the user-initiated class.
// SAFETY: the device is live (the caller's contract), and its functions are its own.
let raw = unsafe { compiles::route(raw) };
@@ -2269,8 +2459,10 @@ impl Device {
// its queue, where the driver runs a queue's submissions one after another anyway
// (`batch_order.rs`).
let by_ends = crate::batch_order::by_ends(compile.policy(), description.driver_id);
let threads = Contexts::start(THREADS).and_then(|contexts| {
match Completion::start(queue_places.len()) {
let threads =
Contexts::start(contexts::device_limit()).and_then(|contexts| match Completion::start(
queue_places.len(),
) {
Ok(completion) => match Scheduler::start(queue_places.len(), by_ends) {
Ok(scheduler) => Ok((contexts, completion, scheduler)),
Err(error) => {
@@ -2283,8 +2475,7 @@ impl Device {
contexts.stop();
Err(error)
}
}
});
});
let (contexts, completion, scheduler) = match threads {
Ok(threads) => threads,
Err(error) => {
@@ -2318,8 +2509,10 @@ impl Device {
QueueSlot {
raw: Mutex::new((queue, submit_stalls::Period::new(stalls))),
stall_due: AtomicBool::new(false),
calls: submit_calls::SubmitCalls::default(),
family,
flags: flags_of(family),
reads: memory_reads.for_family(flags_of(family)),
// SAFETY: the queue was just returned, its word the loader's.
word: unsafe { LoaderWord::of_handle(queue.as_raw()) },
flights: OnceLock::new(),
@@ -2337,7 +2530,10 @@ impl Device {
.collect();
let mut queue_families: Vec<u32> = Vec::with_capacity(queues.len());
let reserved_families = reserved_places.iter().map(|&(family, _)| family);
for family in queues
// Not the copy queue's family: its command buffers use buffers alone, which are shared
// with it as the staging queue's family (below); images keep the device's own families.
let own_queues = &queues[..copy_slot.unwrap_or(queues.len())];
for family in own_queues
.iter()
.map(|slot| slot.family)
.chain(reserved_families)
@@ -2360,14 +2556,19 @@ impl Device {
})
}
});
// The fill queue, of the staging queue's family, whose sharing every buffer has.
// The fill queue, of the staging queue's family, whose sharing every buffer has. Where the
// copy queue's `VkQueue` is its own, its submissions take that queue's lock.
let fill_queue = fill_place.map(|(family, index)| {
// SAFETY: as the staging queue's.
unsafe {
let fills = unsafe {
loader_word.restored(|| {
let queue = raw.get_device_queue(family, index);
staging::StagingQueue::new(Role::Fills, family, flags_of(family), queue, &[])
})
};
match copy_place == Some((family, index)) {
true => fills.sharing_slot(copy_slot),
false => fills,
}
});
let reserved_queues = (reserved_places.iter())
@@ -2651,6 +2852,7 @@ impl Device {
16,
limits.min_storage_buffer_offset_alignment,
limits.min_uniform_buffer_offset_alignment,
limits.min_texel_buffer_offset_alignment,
]
.into_iter()
.fold(1, u64::max);
@@ -2900,6 +3102,15 @@ impl Device {
false => None,
}
};
// The indirect-count draw commands, where a draw the GPU routes records its routes with
// them (`render/gpu_routes.rs`): `multiDrawIndirect` makes `maxDrawIndirectCount` at
// least 65535, past any count a route reads.
let count_draws = {
use metal2vulkan::device::VkFeature as F;
let needs = [F::DrawIndirectCount, F::MultiDrawIndirect];
(needs.iter().all(|f| enabled.features.contains(f)))
.then(|| CountDraws::new(&raw, recording.as_ref()))
};
let budget = |header| {
crate::gpu_pools::pool_budget(
&memory_properties,
@@ -3017,12 +3228,17 @@ impl Device {
// The device's line: a new one for a device made now, else the line this generation
// recovers, whose address space, resource IDs, identifiers and counts it goes on with
// (`line.rs`).
let views = Arc::new(crate::view_check::ViewCheck::new(
properties.description.clone(),
*compile.policy(),
));
let invariant = line::Invariant {
properties,
compile,
enabled,
extensions,
cache_directory: shader_cache.directory_root(),
views,
};
let line = match recovering {
Some(line) => line,
@@ -3058,7 +3274,8 @@ impl Device {
physical,
functions,
queue_family,
round_robin: queues.len() - present_queues,
round_robin: queues.len() - present_queues - usize::from(copy_slot.is_some()),
copy_slot,
queues: queues.into(),
queue_families,
buffer_families,
@@ -3079,7 +3296,7 @@ impl Device {
deferred: crate::render::DeferredEncoders::default(),
record_executions,
encoder_trail: encoder_trail || metal2vulkan::env_vars::encoder_trail(),
splits_at_aliases,
driver_splits_at_aliases: splits_at_aliases,
load_no_dynamic_library_file,
views_epoch: AtomicU64::new(0),
pipeline_recording: crate::warm::Recording::new(pipeline_records),
@@ -3127,6 +3344,7 @@ impl Device {
fail_in_place_check,
limits.non_coherent_atom_size,
),
tiling: crate::tiling_check::TilingCheck::new(),
submit_checks: Arc::new(crate::submit_check::SubmitChecks::new(
assume_submissions_merge,
)),
@@ -3144,6 +3362,7 @@ impl Device {
sized_index_bind,
mesh_draws,
multi_draws,
count_draws,
push_descriptor,
pushes_after_pipeline_binds,
color_write_masks,
@@ -3168,6 +3387,7 @@ impl Device {
gpu_work: AtomicU64::new(0),
dynamic_multi_variable: OnceLock::new(),
owned_kernels: Mutex::new(OwnedKernels::default()),
route_counts_begun: AtomicBool::new(false),
ycbcr_formats,
mipmap_scratch: Mutex::default(),
planes: Mutex::new(PlanesObjects::default()),
@@ -3201,8 +3421,16 @@ impl Device {
#[cfg(test)]
failing_result: Default::default(),
#[cfg(test)]
submit_call_pause: Default::default(),
#[cfg(test)]
submit_call_fast: Default::default(),
#[cfg(test)]
slow_calls_from: Default::default(),
#[cfg(test)]
linear_rule_forced: Default::default(),
#[cfg(test)]
aliases_split_forced: Default::default(),
#[cfg(test)]
linear_feedback_withheld: Default::default(),
#[cfg(test)]
leading_snapshots_withheld: Default::default(),
@@ -3211,14 +3439,20 @@ impl Device {
#[cfg(test)]
sampled_costs_forced: Default::default(),
#[cfg(test)]
managed_inline_bound: crate::managed::INLINE_BYTES.into(),
#[cfg(test)]
uploads_unbarriered_forced: Default::default(),
#[cfg(test)]
upload_scopes: Default::default(),
#[cfg(test)]
read_twin_unguarded: Default::default(),
#[cfg(test)]
read_twin_unproven: Default::default(),
#[cfg(test)]
store_out_unfaulted: Default::default(),
#[cfg(test)]
#[cfg(all(test, unix))]
plane_route_forced: Default::default(),
#[cfg(test)]
#[cfg(all(test, unix))]
explicit_plane_pitch_misread_forced: Default::default(),
#[cfg(test)]
linear_pitch_rule_forced: Default::default(),
@@ -3230,11 +3464,11 @@ impl Device {
owners: Default::default(),
live_buffers: Default::default(),
carry: Default::default(),
#[cfg(unix)]
residency: Default::default(),
#[cfg(unix)]
dma_buf_files: Default::default(),
idle_sweep,
begin_ahead: Default::default(),
timing,
view_reinterpretation,
generated_commands,
@@ -3246,7 +3480,7 @@ impl Device {
live_binds: Default::default(),
coverage_pools: Default::default(),
live_dispatches: Default::default(),
record_storage: Default::default(),
spare_states: Default::default(),
usage_shadows_made: Default::default(),
face_swaps: Default::default(),
heap_textures_end: Default::default(),
@@ -3301,6 +3535,13 @@ impl Device {
// Its submission checks' verdicts, where a record holds them; else the checks start
// (`submit_check.rs`).
device.recall_submit_checks();
// Its view check's facts, where a record holds them; else the check starts
// (`view_check.rs`). In the runtime's own tests, the options' facts.
#[cfg(test)]
let forced = view_facts;
#[cfg(not(test))]
let forced = None;
device.recall_view_check(forced);
device.degrade_argument_buffers_unread();
device.degrade_float_tininess();
Ok(device)
@@ -53,6 +53,20 @@ impl QueueQuiet {
self.in_use.fetch_add(1, Ordering::AcqRel);
}
/// How long no use has been under way: `None` while one is, the time since the last one ended
/// otherwise, [`Duration::MAX`] before the first.
pub(crate) fn unused_for(&self) -> Option<Duration> {
if self.in_use.load(Ordering::Acquire) > 0 {
return None;
}
match self.ended_at.load(Ordering::Acquire) {
0 => Some(Duration::MAX),
ended_at => Some(Duration::from_nanos(
gpu_time::host_nanos().saturating_sub(ended_at),
)),
}
}
/// A use that [began](Self::began) ends.
pub(crate) fn ended(&self) {
self.ended_at
@@ -56,7 +56,7 @@
//! the device is lost), and a device whose instance lacks `VK_EXT_debug_utils` (the same).
use super::functions::Functions;
use super::submit_stalls::{Caller, Uses};
use super::submit_stalls::{thread_cpu, Caller, Uses};
use super::{lock, SlotHold};
use crate::exit_guard::{self, Call};
use crate::loader_word::LoaderWord;
@@ -461,11 +461,16 @@ impl super::DeviceShared {
/// batch that signals the queue's timeline to `value` notes it once submitted (the exit
/// hook's value, and where freed memory waits for the batches in flight, theirs, under the
/// gate's read lock: `freed_memory.rs`). The time `f` takes, the driver's, is counted
/// (`WorkCounts::batch_submit_nanos`), and the call counted in the queue's place in its
/// driver's period of stalls (`submit_stalls.rs`): `f` makes one signalling call.
/// (`WorkCounts::batch_submit_nanos`), with the calling thread's CPU time across it where the
/// device notes queue times (`WorkCounts::batch_submit_cpu_nanos`, and the long calls' apart),
/// and the call counted
/// in the queue's place in its driver's period of stalls (`submit_stalls.rs`): `f` makes one
/// signalling call. A batch's call that succeeded and submitted `buffers` command buffers,
/// one or more, is kept among the queue's last (`submit_calls.rs`), whose floor decides
/// whether a committing thread makes the next.
pub(crate) fn submit_logged(
&self,
(queue, value): (usize, Option<u64>),
(queue, value, buffers): (usize, Option<u64>, usize),
fence: Option<vk::Fence>,
failed: &Arc<Relayed>,
f: impl FnOnce(vk::Queue) -> Result<(), vk::Result>,
@@ -481,6 +486,9 @@ impl super::DeviceShared {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
crate::command_buffer::completion::trace::submitting("submit called");
let cpu = period.cpu_now();
// The thread's CPU time, a system call on Linux, read only where the device notes
// queue times (a default-off diagnostic).
let thread_before = self.timing.queue_times().then(thread_cpu).flatten();
let entered = crate::gpu_time::host_nanos();
// A device test's failure of the call, which is never made
// (`Device::fail_next_submissions`).
@@ -493,15 +501,36 @@ impl super::DeviceShared {
0 => vk::Result::ERROR_OUT_OF_DEVICE_MEMORY,
raw => vk::Result::from_raw(raw),
}),
Err(_) => f(vk_queue),
Err(_) => {
// A device test's slow call (`Device::slow_submit_calls`), a batch's
// that submits command buffers, but each of its fast ones
// (`Device::fast_submit_call_every`).
let pause = self.submit_call_pause.load(Ordering::Relaxed);
if pause > 0 && value.is_some() && buffers > 0 {
let (fast, counted) = &self.submit_call_fast;
let every = fast.load(Ordering::Relaxed);
let nth = counted.fetch_add(1, Ordering::Relaxed) + 1;
if every == 0 || !nth.is_multiple_of(every) {
std::thread::sleep(std::time::Duration::from_nanos(pause));
}
}
f(vk_queue)
}
}
};
let submitted = f(vk_queue);
let end = crate::gpu_time::host_nanos();
let spent =
thread_before.and_then(|start| thread_cpu().map(|now| now.saturating_sub(start)));
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
crate::command_buffer::completion::trace::submitting("submit returned");
let nanos = end.saturating_sub(entered);
(self.counts).batch_submitted_in(nanos);
(self.counts).batch_submitted_in(nanos, spent);
// A batch's call of commands, the queue's cost a committing thread reads; one of no
// command buffer is another call, and stays out (`submit_calls.rs`).
if submitted.is_ok() && value.is_some() && buffers > 0 {
slot.calls.called(nanos);
}
let took = period.took(nanos, cpu);
if submitted.is_ok() && period.called(Caller::Work, took, end) {
self.counts.submit_stall_on_work();
Loaded 100 of 693 files, more files were not shown because too many files have changed in this diff. Show more