Commit Graph
9 Commits
Author SHA1 Message Date
Anees Iqbal e5d1616030 Take a commit left to the scheduler in before its next check, and bound a commit's passes
The scheduler review's work packet: the inbox's and the work loop's fixes, and race tests that catch
a lost wake.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

No behaviour change.

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

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

No run's results change.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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