From 8f1e4157d8cd405cf542926bd5c3dc81d58f0644 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 16 Nov 2026 16:01:06 -0800 Subject: [PATCH] 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. --- .../probes/cross_queue_burst_turns.m | 281 ++++++++++++++++++ crates/metal2vulkan-runtime/README.md | 5 +- .../examples/queue_share.rs | 29 +- .../src/command_buffer/mod.rs | 28 ++ .../src/command_buffer/submit.rs | 5 +- crates/metal2vulkan-runtime/src/lib.rs | 1 + crates/metal2vulkan-runtime/src/queue.rs | 16 +- .../metal2vulkan-runtime/src/queue_share.rs | 7 + .../metal2vulkan-runtime/src/queue_turns.rs | 66 ++++ crates/metal2vulkan-runtime/src/queue_wait.rs | 24 +- .../metal2vulkan-runtime/src/scheduler/mod.rs | 56 ++-- crates/metal2vulkan-runtime/src/tests/mod.rs | 1 + .../src/tests/queue_share_device.rs | 219 +++++++++++++- .../src/tests/queue_turns.rs | 253 ++++++++++++++++ .../src/tests/unshared_hold.rs | 44 +-- .../metal2vulkan-runtime/src/unshared_hold.rs | 145 +++++++-- .../metal2vulkan-runtime/src/work_counts.rs | 25 ++ crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/device/mod.rs | 5 +- crates/metal2vulkan/src/device/policy.rs | 59 +++- crates/metal2vulkan/src/tests/fast_paths.rs | 41 ++- crates/metal2vulkan/tests/api_signatures.tsv | 7 + crates/metal2vulkan/tests/api_surface.rs | 1 + docs/API.md | 16 + docs/FAST-PATHS.md | 52 +++- 25 files changed, 1290 insertions(+), 98 deletions(-) create mode 100644 crates/metal2vulkan-conformance/probes/cross_queue_burst_turns.m create mode 100644 crates/metal2vulkan-runtime/src/queue_turns.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/queue_turns.rs diff --git a/crates/metal2vulkan-conformance/probes/cross_queue_burst_turns.m b/crates/metal2vulkan-conformance/probes/cross_queue_burst_turns.m new file mode 100644 index 000000000..5f698457a --- /dev/null +++ b/crates/metal2vulkan-conformance/probes/cross_queue_burst_turns.m @@ -0,0 +1,281 @@ +// 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: not yet run. +// +// 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 +#import +#include +#include +#include +#include +#include +#include + +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 \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 device; + id spin; + id one; + id draw; + id a_words; + id b_words; + id target; +} Probe; + +static void encode_spin(Probe *p, id 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 spins(Probe *p, id queue, uint32_t iters, + int dispatches) { + id cb = [queue commandBuffer]; + id 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 queue, uint32_t iters) { + id 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 small(Probe *p, id queue, const char *kind) { + id cb = [queue commandBuffer]; + if (strcmp(kind, "blit") == 0) { + id 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 e = [cb renderCommandEncoderWithDescriptor:pass]; + [e setRenderPipelineState:p->draw]; + [e drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; + [e endEncoding]; + } else { + id 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 queue_a = [p->device newCommandQueue]; + id queue_b = same_queue ? queue_a : [p->device newCommandQueue]; + // A's queue warm, alone. + id warm = spins(p, queue_a, iters, 1); + [warm commit]; + [warm waitUntilCompleted]; + int count = one_long ? 1 : BURST; + NSMutableArray> *burst = [NSMutableArray arrayWithCapacity:count]; + for (int c = 0; c < count; c++) { + [burst addObject:spins(p, queue_a, iters, one_long ? BURST : 1)]; + } + id b = small(p, queue_b, kind); + __block double handled = 0; + [b addCompletedHandler:^(id cb) { + (void)cb; + handled = host_seconds(); + }]; + for (id cb in burst) { + [cb commit]; + } + usleep(5000); + double committed = host_seconds(); + [b commit]; + [b waitUntilCompleted]; + for (id cb in burst) { + [cb waitUntilCompleted]; + } + int behind = 0, after = 0; + double last_end = 0; + for (id 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 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 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 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; +} diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index c0656bbb2..c5dd49bc2 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -617,7 +617,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 diff --git a/crates/metal2vulkan-runtime/examples/queue_share.rs b/crates/metal2vulkan-runtime/examples/queue_share.rs index 827a09a7b..62dccf372 100644 --- a/crates/metal2vulkan-runtime/examples/queue_share.rs +++ b/crates/metal2vulkan-runtime/examples/queue_share.rs @@ -5,7 +5,7 @@ //! cargo run --release -p metal2vulkan-runtime --example queue_share -- \ //! [--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] //! ``` //! //! Every command buffer is one of two kinds. A *draw*: a render pass over a 512x512 `RGBA8Unorm` @@ -29,7 +29,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 +68,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 +100,7 @@ struct Options { mode: String, policy: QueueSharingPolicy, isolation: UnsharedIsolationPolicy, + turns: QueueTurnPolicy, seconds: f64, dispatches: u64, unshared: bool, @@ -120,6 +125,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, @@ -148,6 +154,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, @@ -352,13 +365,14 @@ 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() } @@ -594,9 +608,10 @@ fn frames(kit: &Arc, options: &Options) { let app_mean = app_spans.iter().sum::() / 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 +623,8 @@ fn frames(kit: &Arc, 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", diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 15785b1c6..1a23ba8cc 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -5524,6 +5524,34 @@ impl CommandBufferShared { } } + /// Where a batch of it, otherwise ready, is held back from its `VkQueue` for its turn there + /// (`queue_turns.rs`): that `VkQueue`'s index, the value of the oldest batch in flight there + /// the host has not seen complete, and in how many nanoseconds its own queue's work left there + /// falls under the budget where it does before that batch completes; `None` where it may go, + /// as on a lost device, whose submissions fail at once, and for an unshared queue's. The + /// budget is 2 ms while another command queue took a batch there within + /// `unshared_hold::ACTIVE`, else 16 ms (counted where only that let it go). + pub(crate) fn held_for_turn(&self) -> Option<(usize, u64, Option)> { + if self.queue.unshared() || self.device.is_lost() { + return None; + } + let index = self.queue.vk_queue(); + if !self.device.takes_turns_on(index) { + return None; + } + let shared = self.device.shared(); + let slot = &shared.queues[index]; + let own = (self.queue.id(), &**self.queue.expected()); + match slot.waits.turn_ahead(own, || slot.completed_value()) { + crate::unshared_hold::Room::Go => None, + crate::unshared_hold::Room::Idle => { + shared.counts.head_let_go_turn_idle(); + None + } + crate::unshared_hold::Room::Hold { after, through } => Some((index, through, after)), + } + } + /// Whether a batch of it goes before other queues' batches a pass finds ready with it /// (`scheduler/order.rs`, "Heads put first"): its queue is unshared, and its `VkQueue` holds /// other queues' work back for it (`unshared_hold.rs`). diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 3e7c2ffde..f7fbeffa4 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -1652,8 +1652,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 { diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 240ff426c..7d81d1635 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -199,6 +199,7 @@ mod pvrtc; mod queue; mod queue_share; mod queue_switch_check; +mod queue_turns; mod queue_wait; mod range; mod rate_map; diff --git a/crates/metal2vulkan-runtime/src/queue.rs b/crates/metal2vulkan-runtime/src/queue.rs index a98a345b0..8180abd7a 100644 --- a/crates/metal2vulkan-runtime/src/queue.rs +++ b/crates/metal2vulkan-runtime/src/queue.rs @@ -487,6 +487,17 @@ impl Drop for Slot { impl Device { /// `newCommandQueue`: a queue of at most 64 uncompleted command buffers, as Metal's. + /// + /// On a `VkQueue` it shares with other command queues (a device with one graphics queue: + /// RADV, ANV, lavapipe), under + /// [`QueueTurnPolicy::Fair`](metal2vulkan::device::QueueTurnPolicy::Fair) (the default) its + /// batches take turns there: one is held back while 2 ms or more of the queue's own expected + /// GPU work is in flight there (16 ms while no other command queue submitted there within the + /// last 50 ms), so another queue's command buffer committed after a burst of this one's waits + /// behind about that much of it and one batch, where Metal runs it beside them + /// (`WorkCounts::heads_held_for_queue_turns`). Under + /// [`CommitOrder`](metal2vulkan::device::QueueTurnPolicy::CommitOrder) every ready batch goes + /// at once, and a later commit of another queue waits behind all of them. pub fn new_command_queue(&self) -> Result { self.at_serving(|device| device.new_command_queue_now()) } @@ -497,8 +508,9 @@ impl Device { } /// `newCommandQueueWithMaxCommandBufferCount:`: a queue of at most `count` uncompleted - /// command buffers. A count of 0 is refused (`Invalid`, `MaxCommandBufferCount`), where - /// Metal's validation ends the process. + /// command buffers, whose batches take turns on a `VkQueue` it shares as + /// [`new_command_queue`](Self::new_command_queue)'s do. A count of 0 is refused (`Invalid`, + /// `MaxCommandBufferCount`), where Metal's validation ends the process. pub fn new_command_queue_with_max_command_buffer_count( &self, count: usize, diff --git a/crates/metal2vulkan-runtime/src/queue_share.rs b/crates/metal2vulkan-runtime/src/queue_share.rs index 7db726f7e..ab8dc9baa 100644 --- a/crates/metal2vulkan-runtime/src/queue_share.rs +++ b/crates/metal2vulkan-runtime/src/queue_share.rs @@ -239,6 +239,13 @@ impl SlotShare { (self.unshared_posted.load(Ordering::SeqCst), taken) } + /// Whether two or more command queues hold it, the round robin's and the unshared ones + /// counted (`queue_turns.rs`). + pub(crate) fn held_by_several(&self) -> bool { + let homes = self.homes.load(Ordering::SeqCst); + homes + self.unshared.load(Ordering::SeqCst) > 1 + } + /// Whether another command queue holds it beside the one unshared queue that took it. pub(crate) fn held_beside_unshared(&self) -> bool { self.homes.load(Ordering::SeqCst) > 0 || self.unshared.load(Ordering::SeqCst) > 1 diff --git a/crates/metal2vulkan-runtime/src/queue_turns.rs b/crates/metal2vulkan-runtime/src/queue_turns.rs new file mode 100644 index 000000000..b3f320484 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/queue_turns.rs @@ -0,0 +1,66 @@ +//! Command queues that share a `VkQueue` take turns there (`QueueTurnPolicy::Fair`, the default): +//! a command queue not made unshared keeps only about 2 ms of its own expected GPU work submitted +//! there while another command queue submits there, or 16 ms while none does, and another queue's +//! later commit goes ahead of its held batches. +//! +//! - **Why.** A `VkQueue` runs its submissions in order. Where one command queue commits a burst +//! of command buffers (a long command buffer cut into parts, a backlog of frames) on the one +//! graphics `VkQueue` of RADV, ANV, lavapipe or another driver that lends one, every ready batch +//! went to the `VkQueue` at its commit, and a command buffer another queue committed after the +//! burst waited for the whole of it. Metal ran a second queue's small command buffer beside a +//! first queue's 200 ms one (the consumer's oracles, an Intel UHD 630 and an AMD Radeon Pro +//! 5300M under macOS 26.7.1). +//! - **Where.** A batch of a command queue not made unshared, on a `VkQueue` two or more command +//! queues hold (`SlotShare::held_by_several`: the round robin's queues and the unshared ones +//! placed there), on a device whose policy is `Fair`. An unshared queue's batch is never held for +//! its turn: `unshared_hold.rs` bounds the other queues' work ahead of it, and a pass sends it +//! first. +//! - **The bound.** Such a batch, otherwise ready, goes only while less than the budget of its own +//! queue's expected work is in flight there (`unshared_hold::Flight::own_ahead`): its queue's +//! batches submitted there and not seen complete, each at its queue's expected run now +//! (`unshared_hold::Expected`), less what the oldest batch there ran since it became so, where +//! that one is its queue's. Each batch counts its queue's run now, not the one its queue had at +//! its submission, so a run longer than the queue's recent ones prices the rest of a burst at +//! once. +//! - **Two budgets.** `unshared_hold::BUDGET` (2 ms) while another command queue took a batch on +//! that `VkQueue` within `unshared_hold::ACTIVE` (50 ms; the flight keeps the latest batch's +//! queue and time, and the same of the latest of another queue before it), else +//! `unshared_hold::IDLE_BUDGET` (16 ms): a queue alone keeps about 16 ms queued, so a command +//! buffer another queue commits after a quiet stretch goes in behind about that much and one +//! batch, and from its submission on the 2 ms bound applies (`WorkCounts::heads_let_go_turn_idle` +//! counts the heads 2 ms would have held). +//! - **Unknown length.** A queue with no run seen yet keeps one batch in flight there until it is +//! seen complete, which gives the queue its run: it holds back its own next batches alone. +//! - **Turns.** A held batch keeps its place in the scheduler's order (`scheduler/order.rs`), as +//! one held for an unshared queue does: a later commit of another queue whose footprint runs in +//! commit order with it waits behind it, and one that shares nothing with it goes ahead of it. +//! It waits for its own queue's work already submitted alone, never for a later commit, so the +//! turns add no wait that can close a cycle. +//! - **When it goes.** As under `unshared_hold.rs`'s bound: a pass that holds such a batch leaves +//! the scheduler's thread waiting for the completion of the oldest batch in flight on its +//! `VkQueue`, and, where that batch is its own queue's, for the time its expected run brings the +//! work left under the budget, so the next batch goes before the one ahead ends. A committing or +//! waiting thread's pass leaves such a batch to the scheduler's thread +//! (`WorkCounts::scheduler_at_commit_left_turns`). +//! - **What it costs.** A batch already submitted runs to its end: one longer than its queue's +//! recent ones holds every later command buffer there for its whole length, as one command +//! buffer is one submission. The GPU waits for the scheduler's thread only where that thread +//! answers a completion later than the budget less one batch: a queue alone keeps 16 ms queued, +//! two queues submitting keep 2 ms each. Every batch on such a device takes a place in its +//! `VkQueue`'s flight, under the lock its waits take already. Counted: +//! `WorkCounts::heads_held_for_queue_turns` (each look that held a head so). + +impl crate::Device { + /// Whether the device's command queues take turns on the `VkQueue`s they share (the module + /// docs): its policy is `QueueTurnPolicy::Fair`. + pub(crate) fn takes_turns(&self) -> bool { + self.compile_device().policy().queue_turns == metal2vulkan::device::QueueTurnPolicy::Fair + } + + /// Whether a batch of a command queue not made unshared waits for its turn on `VkQueue` + /// `index` (the module docs): the device's queues take turns, and two or more command queues + /// hold it. + pub(crate) fn takes_turns_on(&self, index: usize) -> bool { + self.takes_turns() && self.shared().queues[index].share.held_by_several() + } +} diff --git a/crates/metal2vulkan-runtime/src/queue_wait.rs b/crates/metal2vulkan-runtime/src/queue_wait.rs index 872a7c9f2..d854ed3fe 100644 --- a/crates/metal2vulkan-runtime/src/queue_wait.rs +++ b/crates/metal2vulkan-runtime/src/queue_wait.rs @@ -113,7 +113,7 @@ impl QueueWaits { /// value the host saw the timeline reach, read under this lock: a completion that published a /// higher value before this lock was taken is seen here, one after takes the wait), the /// command buffer waits behind it: counted, and timed to that batch's completion. - /// It enters the `VkQueue`'s flight as `flies` says (`unshared_hold.rs`). + /// It enters the `VkQueue`'s flight as `flies` says (`unshared_hold.rs`, `queue_turns.rs`). pub(crate) fn taken( &self, (value, queue, flies): (u64, u64, crate::unshared_hold::Flies<'_>), @@ -122,7 +122,11 @@ impl QueueWaits { counts: &Counters, ) { let mut ahead = lock(&self.0); - ahead.flight.taken(value, flies); + if !matches!(flies, crate::unshared_hold::Flies::Not) { + ahead + .flight + .taken(value, flies, crate::gpu_time::host_nanos()); + } let through = match ahead.last { Some((last, by)) if by != queue => { ahead.other = last; @@ -212,4 +216,20 @@ impl QueueWaits { let ran = crate::gpu_time::host_nanos().saturating_sub(ahead.head_from); ahead.flight.room(ran, completed(), active) } + + /// Whether a batch of command queue `queue`, whose expected run is `expected`, may go to this + /// `VkQueue` now on its turn (`queue_turns.rs`), held against its own queue's work in flight + /// there, the batches at or below `completed` counted as left, as in + /// [`hold_ahead`](Self::hold_ahead). + pub(crate) fn turn_ahead( + &self, + (queue, expected): (u64, &crate::unshared_hold::Expected), + completed: impl FnOnce() -> u64, + ) -> crate::unshared_hold::Room { + let ahead = lock(&self.0); + let now = crate::gpu_time::host_nanos(); + let ran = now.saturating_sub(ahead.head_from); + let own = (queue, expected.nanos()); + ahead.flight.turn(own, ran, completed(), now) + } } diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index a23e32393..3a8634a1b 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -373,11 +373,14 @@ pub(crate) enum HeldFor { /// Other queues' work enough is in flight on its `VkQueue`, which an unshared queue holds /// (`unshared_hold.rs`). UnsharedIsolation, + /// Its own queue's work enough is in flight on its `VkQueue`, which other command queues + /// share: it waits for its turn there (`queue_turns.rs`). + QueueTurn, } impl HeldFor { /// How many there are, for the counters' array. - pub(crate) const COUNT: usize = 8; + pub(crate) const COUNT: usize = 9; } /// The lists the thread's wait for the GPU fills, kept with their room. @@ -745,8 +748,9 @@ pub(crate) struct State { pub(crate) group: Group, /// Those batches as the order held them, with their logical queues, in order. grouped: Vec<(u64, Held)>, - /// The earliest moment a head held back from a `VkQueue` an unshared queue holds may go - /// there, found by the last look (`await_unshared_room`): the thread sleeps no later. + /// The earliest moment a head held back from a `VkQueue` an unshared queue holds, or for its + /// turn there, may go there, found by the last look (`await_room`): the thread sleeps no + /// later. wake_by: Option, } @@ -1457,8 +1461,8 @@ fn run(shared: &Arc) { && !shared.inbox.holds_commits() && !shared.inbox.nudged() { - // A head held back from an unshared queue's `VkQueue` waits until it may go there at - // most (`await_unshared_room`): a pass looks at it again then. + // A head held back from an unshared queue's `VkQueue`, or for its turn there, waits + // until it may go there at most (`await_room`): a pass looks at it again then. let bound = match state.wake_by { None => None, Some(at) => match at.checked_duration_since(Instant::now()) { @@ -2000,10 +2004,10 @@ fn submit_ready( let binary = &state.binary; let decodes = &state.decodes; let untracked_decodes = state.untracked_decodes; - // The earliest time a head held back for an unshared queue may go before the completion - // of the oldest batch in flight on its `VkQueue` ([`await_unshared_room`]), and whether - // one was. - let (mut unshared_wake, mut isolating) = (None, false); + // The earliest time a head held back for an unshared queue, or for its turn, may go + // before the completion of the oldest batch in flight on its `VkQueue` ([`await_room`]), + // and whether one was. + let (mut room_wake, mut isolating) = (None, false); // The unshared queues' heads on their way, each with its `VkQueue` and its commit's place: // another queue's batch there whose room came after it was posted waits for it // (`unshared_hold.rs`, "Commits on their way"). @@ -2024,7 +2028,16 @@ fn submit_ready( // is in flight there. if let Some(room) = held.buffer.held_for_unshared() { held.held_for(HeldFor::UnsharedIsolation); - await_unshared_room(held, room, awaits, &mut unshared_wake); + await_room(held, room, awaits, &mut room_wake); + isolating = true; + return None; + } + // Held back from a `VkQueue` it shares with other command queues, while its own + // queue's work enough is in flight there (`queue_turns.rs`): another queue's later + // commit goes ahead of it. + if let Some(room) = held.buffer.held_for_turn() { + held.held_for(HeldFor::QueueTurn); + await_room(held, room, awaits, &mut room_wake); isolating = true; return None; } @@ -2045,7 +2058,7 @@ fn submit_ready( } waits }); - if let Some(at) = unshared_wake { + if let Some(at) = room_wake { state.wake_by = Some(state.wake_by.map_or(at, |by: Instant| by.min(at))); } // The heads this look found waiting behind a batch of an earlier commit on another logical @@ -2258,7 +2271,8 @@ fn goes_first(held: &Held) -> bool { held.buffer.goes_ahead_of_held_work() } -/// A head held back from `VkQueue` `queue` for an unshared queue there (`unshared_hold.rs`) until +/// A head held back from `VkQueue` `queue` for an unshared queue there (`unshared_hold.rs`), or for +/// its turn there (`queue_turns.rs`), until /// the batch there of value `through` completes, the oldest in flight past the completed value the /// hold read, or, where the work left ahead falls under the budget before then, `after` /// nanoseconds from now: the thread waits for that value (`awaits`), and until then at most @@ -2267,7 +2281,7 @@ fn goes_first(held: &Held) -> bool { /// above every batch in flight, which no completion meets. The gate goes to `awaits` before the /// completed value is read again, as [`Scheduler::completions`] says: a completion published /// before it wakes the thread at once, one after meets it. -fn await_unshared_room( +fn await_room( held: &Held, (queue, through, after): (usize, u64, Option), awaits: &Awaits, @@ -2841,6 +2855,8 @@ pub(crate) enum LeftAtCommit { BinaryWait, /// It is held back for an unshared queue (`unshared_hold.rs`). Unshared, + /// It waits for its turn on a `VkQueue` it shares (`queue_turns.rs`). + Turn, /// Anything else: a rebind encodes it again, a decode it reads is queued, a switch of /// storage forms rides on it, a group holds it or was held, or its submission was put back. Other, @@ -2848,7 +2864,7 @@ pub(crate) enum LeftAtCommit { impl LeftAtCommit { /// How many there are, for the counters' array. - pub(crate) const COUNT: usize = 11; + pub(crate) const COUNT: usize = 12; } /// How a commit hands its batches to the scheduler. @@ -2937,12 +2953,16 @@ fn plain( } // One held back for an unshared queue is the scheduler thread's to hold, and to wait for its // room (`unshared_hold.rs`), as is one an unshared queue's commit not yet taken in may hold - // (its passes note the commits it waits behind). + // (its passes note the commits it waits behind), and one that waits for its turn on its + // `VkQueue` (`queue_turns.rs`). let unshared = held.buffer.held_for_unshared().is_some() || (held.buffer.unshared_commits()).is_some_and(|(_, (posted, taken))| taken < posted); - match unshared { - true => Err(LeftAtCommit::Unshared), - false => Ok(()), + if unshared { + return Err(LeftAtCommit::Unshared); + } + match held.buffer.held_for_turn() { + Some(_) => Err(LeftAtCommit::Turn), + None => Ok(()), } } diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 1c77ba00c..e1ab62579 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -656,6 +656,7 @@ mod queue_share_device; mod queue_sharing; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod queue_switch_gate; +mod queue_turns; mod range; mod rate_map; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs b/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs index 9d83f3ac6..ca525acfe 100644 --- a/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs @@ -63,6 +63,12 @@ //! scheduler's own pass and by a committing thread's. One that waits behind an earlier commit of //! the held queue (a fill of the same range) holds nothing, nor one waiting for a value nothing //! submitted reaches: neither the held batch nor the unshared one waits for the other. +//! - **Turns** (`queue_turns.rs`). On a `VkQueue` two plain queues share, one commits a burst of +//! twelve command buffers of about 10 ms each at once, the other a small one once the burst's +//! first is scheduled: under `QueueTurnPolicy::Fair` the burst's queue keeps about 16 ms of its +//! own work in flight, so the small one goes before the burst's fourth (heads held for their +//! turns counted); under `CommitOrder` all twelve go at once, and it starts after the twelfth +//! ends. Every device, a `VkQueue` shared on purpose (`PerQueue`, the round robin wrapped). //! //! Where the device does not share (`PerQueue`, its check found no idling, or it has no two //! `VkQueue`s of one family: MoltenVK, RADV, lavapipe) each test asserts that no queue moves, and @@ -82,7 +88,8 @@ use crate::{ ResourceOptions, ShaderCacheOptions, Size, WorkCounts, }; use metal2vulkan::device::{ - CompletionPolicy, DevicePolicy, PipelineWaitPolicy, QueueSharingPolicy, UnsharedIsolationPolicy, + CompletionPolicy, DevicePolicy, PipelineWaitPolicy, QueueSharingPolicy, QueueTurnPolicy, + UnsharedIsolationPolicy, }; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{mpsc, Arc, Mutex}; @@ -98,7 +105,10 @@ const SETTLING: Duration = Duration::from_millis(50); /// The bytes one fill of a long command buffer writes. const FILL_BYTES: u64 = 64 << 20; -/// The options of the device the cfg selects under `queue_sharing`, its shader cache in `cache`. +/// The options of the device the cfg selects under `queue_sharing`, its shader cache in `cache`, +/// its queues taking no turns on a `VkQueue` they share (`QueueTurnPolicy::CommitOrder`): these +/// tests measure the sharing and the unshared hold alone, which the turns would hold work back +/// beside (the `Off` legs' controls among them); the turns' own test sets them. fn options(cache: &Scratch, queue_sharing: QueueSharingPolicy) -> DeviceOptions { let mut options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { @@ -121,6 +131,7 @@ fn options(cache: &Scratch, queue_sharing: QueueSharingPolicy) -> DeviceOptions }; options.policy = DevicePolicy::UNTRUSTED; options.policy.queue_sharing = queue_sharing; + options.policy.queue_turns = QueueTurnPolicy::CommitOrder; options } @@ -648,13 +659,18 @@ impl Isolation { /// The fills of one long command buffer of about 30 ms of GPU time over `target`, measured. fn long_fills(queue: &CommandQueue, target: &Buffer) -> usize { + fills_for(queue, target, 0.030) +} + +/// The fills of one command buffer of about `seconds` of GPU time over `target`, measured. +fn fills_for(queue: &CommandQueue, target: &Buffer, seconds: f64) -> usize { let mut fills = 64; for _ in 0..3 { let command_buffer = long(queue, target, fills); command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); let gpu = command_buffer.gpu_end_time().unwrap() - command_buffer.gpu_start_time().unwrap(); - fills = ((fills as f64 * 0.030 / gpu.max(1e-6)) as usize).clamp(8, 4096); + fills = ((fills as f64 * seconds / gpu.max(1e-6)) as usize).clamp(8, 4096); } fills } @@ -2012,3 +2028,200 @@ fn an_unshared_head_waiting_for_a_value_nothing_submitted_reaches_holds_nothing( assert_eq!(drawn.status(), CommandBufferStatus::Completed, "{leg}"); } } + +/// The GPU time of one command buffer of a [`TurnWork`] burst: 10 ms, so the 16 ms budget lets a +/// second go at once and a third once the first ran 4 ms, and holds a fourth until the first +/// completes (`queue_turns.rs`). +const TURN_RUN: f64 = 0.010; + +/// The command buffers of a [`TurnWork`] burst. +const BURST: usize = 12; + +/// The runs [`a_later_queue_s_command_buffer_takes_its_turn_ahead_of_another_queue_s_burst`] +/// makes under `Fair` for one whose small command buffer was committed before the burst's first +/// completed. +const TURN_RUNS: usize = 5; + +/// The turns test's device under `turns` (`PerQueue`), an application's queue, another plain +/// queue on its `VkQueue`, and the fills of a command buffer of about [`TURN_RUN`]. +struct TurnWork { + device: Device, + app: CommandQueue, + other: CommandQueue, + big: Buffer, + small: Buffer, + fills: usize, +} + +/// One run of [`TurnWork`]: the burst's command buffers' and the other queue's small one's kernel +/// starts (their first submissions), GPU starts and GPU ends, in seconds of the host's clock. +struct TurnRun { + burst: Vec<(f64, f64, f64)>, + small: (f64, f64, f64), + /// The host time the small one's commit returned. + committed: f64, + /// The looks that held a head for its turn (`WorkCounts::heads_held_for_queue_turns`). + held: u64, + /// The looks that let one go under the idle budget (`WorkCounts::heads_let_go_turn_idle`). + let_go_idle: u64, + /// The application queue's expected run as the burst was committed, in milliseconds. + expected: f64, +} + +impl TurnWork { + fn new(scratch: &Scratch, turns: QueueTurnPolicy) -> TurnWork { + let mut options = options(scratch, QueueSharingPolicy::PerQueue); + options.policy.queue_turns = turns; + let device = device_with_room(&options).unwrap(); + assert!(device.settle_queue_switch_check(WAIT), "the check settles"); + let app = device.new_command_queue().unwrap(); + let other = beside(&app, &|| device.new_command_queue().unwrap()); + let big = device + .new_buffer(FILL_BYTES, ResourceOptions::private()) + .unwrap(); + let small = device.new_buffer(4096, ResourceOptions::private()).unwrap(); + let fills = fills_for(&app, &big, TURN_RUN); + TurnWork { + device, + app, + other, + big, + small, + fills, + } + } + + /// Six of the burst's command buffers run alone (a queue's expected run halves toward a + /// shorter one: the calibration's longer runs are a 64th of their excess past it), then the + /// burst committed at once, each encoded before the first commit, and the other queue's small + /// one once the burst's first is scheduled. + fn run(&self) -> TurnRun { + for _ in 0..6 { + let warm = long(&self.app, &self.big, self.fills); + warm.commit().unwrap(); + warm.wait_until_completed_for(WAIT).unwrap(); + } + let expected = self.app.serving().expected().nanos().unwrap_or(0) as f64 / 1e6; + let before = self.device.work_counts(); + let burst: Vec = (0..BURST) + .map(|_| long(&self.app, &self.big, self.fills)) + .collect(); + let small = small_fill(&self.other, &self.small); + for command_buffer in &burst { + command_buffer.commit().unwrap(); + } + burst[0].wait_until_scheduled().unwrap(); + small.commit().unwrap(); + let committed = crate::host_time(); + small.wait_until_completed_for(WAIT).unwrap(); + for command_buffer in &burst { + command_buffer.wait_until_completed_for(WAIT).unwrap(); + } + let after = self.device.work_counts(); + let times = |command_buffer: &CommandBuffer| { + ( + command_buffer.kernel_start_time(), + command_buffer.gpu_start_time().unwrap(), + command_buffer.gpu_end_time().unwrap(), + ) + }; + TurnRun { + burst: burst.iter().map(times).collect(), + small: times(&small), + committed, + held: after.heads_held_for_queue_turns - before.heads_held_for_queue_turns, + let_go_idle: after.heads_let_go_turn_idle - before.heads_let_go_turn_idle, + expected, + } + } +} + +impl TurnRun { + fn print(&self, label: &str) { + let at = self.burst[0].1; + let ms = |time: f64| (time - at) * 1e3; + let burst: Vec = (self.burst.iter()) + .map(|&(kernel, start, end)| { + format!("{:.1} ({:.1}-{:.1})", ms(kernel), ms(start), ms(end)) + }) + .collect(); + println!( + "{label}: the burst's submissions (GPU runs) {} ms; the small one committed at {:.1}, \ + submitted at {:.1} ({:.1}-{:.1}) ms; {} looks held, {} let go under the idle budget; \ + the burst's queue's expected run {:.1} ms", + burst.join(", "), + ms(self.committed), + ms(self.small.0), + ms(self.small.1), + ms(self.small.2), + self.held, + self.let_go_idle, + self.expected, + ); + } +} + +/// On a `VkQueue` two plain command queues share, twelve command buffers of about 10 ms committed +/// at once on one, and a small one on the other once the first of them is scheduled: under +/// `QueueTurnPolicy::Fair` (the default) the burst's queue keeps about 16 ms of its own work in +/// flight there (its queue's expected run the burst's: six run alone first), so the small one is +/// submitted, and starts, before the burst's fourth, and heads were held for their turns; under +/// `CommitOrder` all twelve go at once, and the small one starts after the twelfth ends (with or +/// after it, on a device that answers GPU times from the host, MoltenVK among them, whose GPU +/// start is the command buffer's kernel end), with none held. +/// +/// The burst's fourth goes once the first completed: a run whose small one was committed only +/// after that (the test's thread late on a loaded host) shows nothing of the turns, and is made +/// again, up to [`TURN_RUNS`] runs. +#[test] +fn a_later_queue_s_command_buffer_takes_its_turn_ahead_of_another_queue_s_burst() { + for turns in [QueueTurnPolicy::Fair, QueueTurnPolicy::CommitOrder] { + let scratch = Scratch::new(&format!("queue-turns-{turns:?}")); + let work = TurnWork::new(&scratch, turns); + assert_eq!( + work.app.vk_queue_sharing().0, + work.other.vk_queue_sharing().0, + "the two queues share a VkQueue" + ); + let device_times = !work.device.shared().timing.answers_from_host(); + match turns { + QueueTurnPolicy::Fair => { + let run = (0..TURN_RUNS) + .map(|_| work.run()) + .inspect(|run| run.print("Fair")) + .find(|run| run.committed < run.burst[0].2) + .expect("a run committed the small one before the burst's first completed"); + assert!(run.held > 0, "heads were held for their turns"); + assert!( + run.small.0 < run.burst[3].0, + "the small one was submitted before the burst's fourth" + ); + if device_times { + assert!( + run.small.1 < run.burst[3].1, + "the small one started before the burst's fourth" + ); + } + } + _ => { + let run = work.run(); + run.print("CommitOrder"); + assert_eq!(run.held, 0, "none held"); + assert_eq!(run.let_go_idle, 0, "none let go under the idle budget"); + let last = run.burst[BURST - 1]; + assert!( + run.small.0 >= last.0, + "the small one was submitted after the burst's twelfth" + ); + let started = match device_times { + true => run.small.1, + false => run.small.2, + }; + assert!( + started >= last.2 - 0.001, + "the small one started after the burst's twelfth ended" + ); + } + } + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/queue_turns.rs b/crates/metal2vulkan-runtime/src/tests/queue_turns.rs new file mode 100644 index 000000000..ab346ac91 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/queue_turns.rs @@ -0,0 +1,253 @@ +//! Command queues taking turns on a `VkQueue` they share (`queue_turns.rs`), the parts that need +//! no device: each queue's own work in a `VkQueue`'s flight. +//! +//! - **Its own work alone.** A queue's batch is held only by its own queue's batches in flight, +//! each at its queue's expected run: another queue's burst ahead of it holds it not at all, so a +//! queue that submits after a burst goes at once. +//! - **Two budgets.** A queue alone keeps less than 16 ms of its own work in flight (the heads past +//! 2 ms let go as idle ones); once another queue took a batch there within 50 ms, less than +//! 2 ms; 50 ms after that queue's last, 16 ms again. An unshared queue's batches hold no turn of +//! their own, and count as another queue's. +//! - **Priced at the run now.** A run longer than a queue's recent ones prices every batch of it +//! still in flight at once, where the unshared bound prices each at its submission's run. +//! - **Unknown length.** A queue with no run seen keeps one batch in flight until it completes, +//! and holds no other queue back. +//! - **The oldest's run.** What the oldest batch in flight ran counts against its own queue's work +//! alone, and only while no completion past it was published; the hold waits for the oldest +//! batch's completion, and, where that is its own queue's, for the time its run brings the work +//! left under the budget. + +use crate::unshared_hold::{Expected, Flies, Flight, Room, ACTIVE, BUDGET, IDLE_BUDGET}; +use std::sync::Arc; + +const MS: u64 = 1_000_000; + +/// A host time well past 0, which stands for none. +const T0: u64 = 1_000 * MS; + +/// The burst's queue and another. +const A: u64 = 1; +const B: u64 = 2; +const UNSHARED: u64 = 3; + +/// A queue whose batches were seen to run `nanos`. +fn queue(nanos: u64) -> Arc { + let expected = Arc::new(Expected::default()); + expected.observed(nanos); + expected +} + +/// Queue `id`'s turn in `flight` at host time `now`, nothing completed, the oldest batch having +/// run `ran`. +fn turn(flight: &Flight, (id, of): (u64, &Expected), ran: u64, now: u64) -> Room { + flight.turn((id, of.nanos()), ran, 0, now) +} + +/// A queue alone keeps less than 16 ms of its 4 ms batches in flight: the second to the fourth +/// go as idle ones, which 2 ms would hold, and the fifth is held until the first has run 1 ns of +/// its expected run, or completes. +#[test] +fn a_queue_alone_keeps_less_than_16_ms_of_its_own_work_in_flight() { + let app = queue(4 * MS); + let mut flight = Flight::default(); + assert_eq!(turn(&flight, (A, &app), 0, T0), Room::Go, "none in flight"); + for value in 1..=3 { + flight.taken(value, Flies::Other(A, &app), T0); + assert_eq!( + turn(&flight, (A, &app), 0, T0), + Room::Idle, + "{value} in flight" + ); + } + flight.taken(4, Flies::Other(A, &app), T0); + assert_eq!( + turn(&flight, (A, &app), 0, T0), + Room::Hold { + after: Some(1), + through: 1 + } + ); + assert_eq!( + turn(&flight, (A, &app), 1, T0), + Room::Idle, + "1 ns of it ran" + ); +} + +/// Another queue's batch, taken there after a burst of A's, goes at once: A's work holds it not +/// at all. From then on A keeps less than 2 ms of its own in flight, until 50 ms after B's last. +#[test] +fn a_later_queue_goes_ahead_of_another_queue_s_burst() { + let (app, probe) = (queue(4 * MS), queue(MS / 10)); + let mut flight = Flight::default(); + for value in 1..=4 { + flight.taken(value, Flies::Other(A, &app), T0); + } + let later = T0 + 300 * MS; + assert_eq!( + turn(&flight, (B, &probe), 0, later), + Room::Go, + "the burst holds B not at all" + ); + flight.taken(5, Flies::Other(B, &probe), later); + // A's oldest ran 3 ms of its 4: 13 ms of A's left, 2 ms or more, which the 1 ms left of the + // oldest's run does not bring under 2 ms: held until it completes. + let a_held = Room::Hold { + after: None, + through: 1, + }; + assert_eq!(turn(&flight, (A, &app), 3 * MS, later + 1), a_held); + assert_eq!( + turn(&flight, (B, &probe), 3 * MS, later + 1), + Room::Go, + "0.1 ms of B's own left: under 2 ms" + ); + // B's last is 50 ms old: A's budget is 16 ms again, and 13 ms is under it. + assert_eq!(turn(&flight, (A, &app), 3 * MS, later + ACTIVE), Room::Idle); + assert_eq!( + turn(&flight, (A, &app), 3 * MS, later + ACTIVE - 1), + a_held, + "49.99 ms after B's last" + ); +} + +/// A batch of a queue whose last batch here is the latest (its own) finds the other queue's +/// latest one: B's batch, then A's, then A's turn sees B's as the other one's. +#[test] +fn the_latest_batch_of_another_queue_is_kept_behind_a_queue_s_own() { + let app = queue(4 * MS); + let mut flight = Flight::default(); + flight.taken(1, Flies::Other(B, &app), T0); + flight.taken(2, Flies::Other(A, &app), T0 + MS); + flight.taken(3, Flies::Other(A, &app), T0 + 2 * MS); + // A has 8 ms in flight: held under B's 2 ms budget, not under 16 ms. + assert!(matches!( + turn(&flight, (A, &app), 0, T0 + 3 * MS), + Room::Hold { .. } + )); + assert_eq!( + turn(&flight, (A, &app), 0, T0 + ACTIVE), + Room::Idle, + "B's batch went 50 ms ago" + ); +} + +/// An unshared queue's batches hold no turn of their own, and bring the 2 ms budget as another +/// queue's do. +#[test] +fn an_unshared_queue_s_batches_hold_no_turn_and_count_as_another_queue_s() { + let app = queue(4 * MS); + let mut flight = Flight::default(); + flight.taken(1, Flies::Other(A, &app), T0); + assert_eq!(turn(&flight, (A, &app), 0, T0), Room::Idle); + flight.taken(2, Flies::Unshared(UNSHARED), T0); + assert!(matches!(turn(&flight, (A, &app), 0, T0), Room::Hold { .. })); + assert_eq!( + turn(&flight, (UNSHARED, &app), 0, T0), + Room::Go, + "its own batch counts nothing" + ); +} + +/// A queue whose 0.5 ms batches went four at a time ran 8 ms in the first: the three left count +/// 8 ms each at once (24 ms: held under either budget), where the unshared bound still counts +/// the 0.5 ms each had at its submission. +#[test] +fn a_longer_run_prices_every_batch_of_its_queue_in_flight_at_once() { + let app = queue(MS / 2); + let mut flight = Flight::default(); + for value in 1..=4 { + flight.taken(value, Flies::Other(A, &app), T0); + } + flight.completed(1, 8 * MS); + assert_eq!(app.nanos(), Some(8 * MS)); + let held = Room::Hold { + after: None, + through: 2, + }; + assert_eq!(turn(&flight, (A, &app), 0, T0), held, "24 ms left"); + assert_eq!(flight.own_ahead((A, app.nanos()), 0, 0, IDLE_BUDGET), held); + assert_eq!( + flight.ahead(0, 0, BUDGET), + Room::Go, + "the unshared bound: 1.5 ms at the runs they were taken at" + ); +} + +/// A queue with no run seen keeps one batch in flight until it is seen complete, however long it +/// runs, and holds no other queue back. +#[test] +fn a_queue_with_no_run_seen_keeps_one_batch_in_flight() { + let (new, other) = (Arc::new(Expected::default()), queue(4 * MS)); + let mut flight = Flight::default(); + assert_eq!(turn(&flight, (A, &new), 0, T0), Room::Go, "the first goes"); + flight.taken(1, Flies::Other(A, &new), T0); + let first = Room::Hold { + after: None, + through: 1, + }; + assert_eq!(turn(&flight, (A, &new), 0, T0), first); + assert_eq!( + turn(&flight, (A, &new), 500 * MS, T0), + first, + "however long" + ); + assert_eq!( + turn(&flight, (B, &other), 0, T0), + Room::Go, + "another queue's batch goes" + ); + flight.completed(1, 3 * MS); + assert_eq!(new.nanos(), Some(3 * MS)); + assert_eq!(turn(&flight, (A, &new), 0, T0), Room::Go); +} + +/// The oldest batch's run counts against its own queue's work alone: A's work behind B's long +/// batch is held until B's completes, with no time to wait for; once A's is the oldest, its run +/// counts, and the hold waits for the time that brings A's work left under the budget. +#[test] +fn the_oldest_batch_s_run_counts_against_its_own_queue_s_work_alone() { + let (app, long) = (queue(4 * MS), queue(30 * MS)); + let mut flight = Flight::default(); + flight.taken(1, Flies::Other(B, &long), T0); + flight.taken(2, Flies::Other(A, &app), T0); + let now = T0 + MS; + // B's ran 20 ms: none of it counts for A, whose 4 ms waits behind it. + let behind = Room::Hold { + after: None, + through: 1, + }; + assert_eq!(turn(&flight, (A, &app), 20 * MS, now), behind); + // B's completion was published, not yet taken out: A's is the oldest, none of its run counts + // yet, and the hold waits for 2 ms more of it. + let published = Room::Hold { + after: Some(2 * MS + 1), + through: 2, + }; + assert_eq!(flight.turn((A, app.nanos()), 20 * MS, 1, now), published); + flight.completed(1, 30 * MS); + assert_eq!(turn(&flight, (A, &app), 0, now), published); + assert_eq!( + turn(&flight, (A, &app), 2 * MS + 1, now), + Room::Go, + "under 2 ms of A's left" + ); +} + +/// A batch whose completion was published counts as left before it is taken out of the flight. +#[test] +fn a_published_completion_counts_its_batches_as_left() { + let app = queue(4 * MS); + let mut flight = Flight::default(); + flight.taken(1, Flies::Other(A, &app), T0); + flight.taken(2, Flies::Other(A, &app), T0); + flight.taken(3, Flies::Other(B, &app), T0); + assert!(matches!( + flight.turn((A, app.nanos()), 0, 0, T0), + Room::Hold { .. } + )); + assert_eq!(flight.turn((A, app.nanos()), 0, 2, T0), Room::Go); + flight.completed(2, 8 * MS); + assert_eq!(turn(&flight, (A, &app), 0, T0), Room::Go); + assert_eq!(flight.len(), 1); +} diff --git a/crates/metal2vulkan-runtime/src/tests/unshared_hold.rs b/crates/metal2vulkan-runtime/src/tests/unshared_hold.rs index 25f1377ae..80bb85e51 100644 --- a/crates/metal2vulkan-runtime/src/tests/unshared_hold.rs +++ b/crates/metal2vulkan-runtime/src/tests/unshared_hold.rs @@ -52,7 +52,7 @@ fn a_batch_of_unknown_length_holds_the_next_back_until_it_completes() { let app = Arc::new(Expected::default()); let mut flight = Flight::default(); assert_eq!(flight.ahead(0, 0, BUDGET), Room::Go, "the first goes"); - flight.taken(1, Flies::Other(&app)); + flight.taken(1, Flies::Other(1, &app), 0); let first = Room::Hold { after: None, through: 1, @@ -66,7 +66,7 @@ fn a_batch_of_unknown_length_holds_the_next_back_until_it_completes() { flight.completed(1, 30 * MS); assert_eq!(app.nanos(), Some(30 * MS)); assert_eq!(flight.ahead(0, 0, BUDGET), Room::Go); - flight.taken(2, Flies::Other(&app)); + flight.taken(2, Flies::Other(1, &app), 0); assert_eq!( flight.ahead(0, 0, BUDGET), Room::Hold { @@ -103,7 +103,7 @@ fn a_queue_whose_batches_got_short_is_let_ahead_again_within_five_of_them() { let mut short = 0; loop { value += 1; - flight.taken(value, Flies::Other(&app)); + flight.taken(value, Flies::Other(1, &app), 0); // Another of its batches is ready as this one starts. if flight.ahead(0, 0, BUDGET) == Room::Go { break; @@ -127,10 +127,10 @@ fn a_queue_whose_batches_got_short_is_let_ahead_again_within_five_of_them() { fn an_unshared_queue_s_batches_count_no_work_ahead() { let mut flight = Flight::default(); for value in 1..=8 { - flight.taken(value, Flies::Unshared); + flight.taken(value, Flies::Unshared(9), 0); } assert_eq!(flight.ahead(0, 0, BUDGET), Room::Go); - flight.taken(9, Flies::Not); + flight.taken(9, Flies::Not, 0); assert_eq!(flight.len(), 8, "a batch that flies not is not kept"); } @@ -138,7 +138,7 @@ fn an_unshared_queue_s_batches_count_no_work_ahead() { fn a_batch_goes_while_less_than_the_budget_is_left_ahead() { let app = queue(30 * MS); let mut flight = Flight::default(); - flight.taken(1, Flies::Other(&app)); + flight.taken(1, Flies::Other(1, &app), 0); // 30 ms left at its start: held until 28 ms of it ran, or its completion. assert_eq!( flight.ahead(0, 0, BUDGET), @@ -156,7 +156,7 @@ fn a_batch_goes_while_less_than_the_budget_is_left_ahead() { ); assert_eq!(flight.ahead(28 * MS + 1, 0, BUDGET), Room::Go); // The next one went: 30 ms more ahead, which the oldest's run left does not cover. - flight.taken(2, Flies::Other(&app)); + flight.taken(2, Flies::Other(1, &app), 0); let both = Room::Hold { after: None, through: 1, @@ -178,10 +178,10 @@ fn a_run_several_batches_complete_in_is_shared_among_the_other_queues_batches() let first = queue(MS); let second = queue(MS); let mut flight = Flight::default(); - flight.taken(1, Flies::Other(&first)); - flight.taken(2, Flies::Unshared); - flight.taken(3, Flies::Other(&second)); - flight.taken(4, Flies::Other(&second)); + flight.taken(1, Flies::Other(2, &first), 0); + flight.taken(2, Flies::Unshared(9), 0); + flight.taken(3, Flies::Other(3, &second), 0); + flight.taken(4, Flies::Other(3, &second), 0); flight.completed(3, 9 * MS); assert_eq!( first.nanos(), @@ -204,11 +204,11 @@ fn a_run_several_batches_complete_in_is_shared_among_the_other_queues_batches() fn an_unshared_batch_seen_complete_with_another_queue_s_leaves_it_the_whole_run() { let app = queue(30 * MS); let mut flight = Flight::default(); - flight.taken(1, Flies::Other(&app)); - flight.taken(2, Flies::Unshared); + flight.taken(1, Flies::Other(1, &app), 0); + flight.taken(2, Flies::Unshared(9), 0); flight.completed(2, 30 * MS); assert_eq!(app.nanos(), Some(30 * MS)); - flight.taken(3, Flies::Other(&app)); + flight.taken(3, Flies::Other(1, &app), 0); assert_eq!( flight.ahead(14 * MS, 0, BUDGET), Room::Hold { @@ -218,7 +218,7 @@ fn an_unshared_batch_seen_complete_with_another_queue_s_leaves_it_the_whole_run( "half way through the next one, no other goes" ); // An unshared batch seen complete alone updates nothing. - flight.taken(4, Flies::Unshared); + flight.taken(4, Flies::Unshared(9), 0); flight.completed(3, 30 * MS); flight.completed(4, MS / 10); assert_eq!(app.nanos(), Some(30 * MS)); @@ -231,7 +231,7 @@ fn an_unshared_batch_seen_complete_with_another_queue_s_leaves_it_the_whole_run( fn a_batch_whose_completion_was_published_counts_as_left_before_it_leaves() { let app = Arc::new(Expected::default()); let mut flight = Flight::default(); - flight.taken(1, Flies::Other(&app)); + flight.taken(1, Flies::Other(1, &app), 0); assert_eq!( flight.ahead(0, 0, BUDGET), Room::Hold { @@ -246,8 +246,8 @@ fn a_batch_whose_completion_was_published_counts_as_left_before_it_leaves() { ); let long = queue(30 * MS); let mut flight = Flight::default(); - flight.taken(1, Flies::Other(&long)); - flight.taken(2, Flies::Other(&long)); + flight.taken(1, Flies::Other(4, &long), 0); + flight.taken(2, Flies::Other(4, &long), 0); assert_eq!( flight.ahead(20 * MS, 1, BUDGET), Room::Hold { @@ -289,7 +289,7 @@ fn super_resolution_s_iterations_are_never_held_beside_a_quiet_compositor() { let now = 1_000 * MS; for (last, quiet) in [(0, true), (now - ACTIVE, true), (now - MS, false)] { let mut flight = Flight::default(); - flight.taken(1, Flies::Unshared); + flight.taken(1, Flies::Unshared(9), 0); for value in 2..=5 { let room = flight.room(0, 1, active(last, now)); match (quiet, value) { @@ -303,7 +303,7 @@ fn super_resolution_s_iterations_are_never_held_beside_a_quiet_compositor() { break; } } - flight.taken(value, Flies::Other(&sr)); + flight.taken(value, Flies::Other(5, &sr), 0); } } } @@ -320,7 +320,7 @@ fn a_quiet_compositor_s_first_command_buffer_waits_behind_the_idle_budget_and_on let quiet = active(now - ACTIVE, now); let mut flight = Flight::default(); assert_eq!(flight.room(0, 0, quiet), Room::Go, "the first goes"); - flight.taken(1, Flies::Other(&long)); + flight.taken(1, Flies::Other(4, &long), 0); assert_eq!( flight.room(0, 0, quiet), Room::Hold { @@ -342,7 +342,7 @@ fn a_quiet_compositor_s_first_command_buffer_waits_behind_the_idle_budget_and_on Room::Idle, "under 16 ms left: it goes, where 2 ms would hold it" ); - flight.taken(2, Flies::Other(&long)); + flight.taken(2, Flies::Other(4, &long), 0); assert_eq!( flight.room(30 * MS - IDLE_BUDGET + 1, 0, quiet), Room::Hold { diff --git a/crates/metal2vulkan-runtime/src/unshared_hold.rs b/crates/metal2vulkan-runtime/src/unshared_hold.rs index bec8177e6..3339d4324 100644 --- a/crates/metal2vulkan-runtime/src/unshared_hold.rs +++ b/crates/metal2vulkan-runtime/src/unshared_hold.rs @@ -125,7 +125,7 @@ //! lock of its own at the submission and the completion. Counted: //! `WorkCounts::heads_held_for_unshared_isolation` (each look that held a head so). -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; @@ -198,12 +198,14 @@ impl Expected { /// How a batch taken on a `VkQueue` enters its [`Flight`]. pub(crate) enum Flies<'a> { - /// Not at all: no unshared queue holds the `VkQueue`, or the device's policy is `Off`. + /// Not at all: no unshared queue holds the `VkQueue` under `UnsharedIsolationPolicy::Bounded`, + /// and the device's queues take no turns (`QueueTurnPolicy::CommitOrder`). Not, - /// As an unshared queue's: in flight, with no expected run of other queues' work. - Unshared, - /// As another queue's, with its queue's expected run. - Other(&'a Arc), + /// As an unshared queue's (its `QueueGen::id`): in flight, with no expected run of other + /// queues' work, and no turn of its own. + Unshared(u64), + /// As another queue's: its `QueueGen::id`, and its queue's expected run. + Other(u64, &'a Arc), } /// One batch in a [`Flight`]. @@ -211,6 +213,8 @@ pub(crate) enum Flies<'a> { struct InFlight { /// Its value of its `VkQueue`'s timeline. value: u64, + /// Its command queue (`QueueGen::id`). + queue: u64, /// Its expected run, counted in [`Flight::expected`]; 0 for an unshared queue's, and for one /// whose queue had no run seen. expected: u64, @@ -220,8 +224,9 @@ struct InFlight { of: Option>, } -/// The batches taken on one `VkQueue` an unshared queue holds and not seen complete -/// (`queue_wait::Ahead::flight`), under that `VkQueue`'s waits' lock. +/// The batches taken on one `VkQueue` an unshared queue holds, or whose queues take turns +/// (`queue_turns.rs`), and not seen complete (`queue_wait::Ahead::flight`), under that `VkQueue`'s +/// waits' lock. #[derive(Debug, Default)] pub(crate) struct Flight { /// In the order of their values, which rises. @@ -230,6 +235,11 @@ pub(crate) struct Flight { expected: u64, /// How many among them are of unknown length. unseen: usize, + /// How many among them each command queue not made unshared has (`queue_turns.rs`), by its id. + turns: HashMap, + /// The latest batch's command queue and the host time it was taken, and the same of the + /// latest of another command queue before it (`queue_turns.rs`, **Two budgets**): 0 for none. + latest: [(u64, u64); 2], } /// Whether a batch may go to a `VkQueue` now ([`Flight::ahead`]). @@ -255,19 +265,28 @@ pub(crate) fn active(last: u64, now: u64) -> bool { } impl Flight { - /// A batch took `value`, entering as `flies` says. - pub(crate) fn taken(&mut self, value: u64, flies: Flies<'_>) { - let (expected, of) = match flies { + /// A batch took `value` at host time `now` (`gpu_time::host_nanos`), entering as `flies` + /// says. + pub(crate) fn taken(&mut self, value: u64, flies: Flies<'_>, now: u64) { + let (queue, expected, of) = match flies { Flies::Not => return, - Flies::Unshared => (Some(0), None), - Flies::Other(of) => (of.nanos(), Some(Arc::clone(of))), + Flies::Unshared(queue) => (queue, Some(0), None), + Flies::Other(queue, of) => { + *self.turns.entry(queue).or_default() += 1; + (queue, of.nanos(), Some(Arc::clone(of))) + } }; + match self.latest[0].0 == queue { + true => self.latest[0].1 = now, + false => self.latest = [(queue, now), self.latest[0]], + } let unseen = expected.is_none(); let expected = expected.unwrap_or(0); self.expected += expected; self.unseen += usize::from(unseen); self.batches.push_back(InFlight { value, + queue, expected, unseen, of, @@ -294,6 +313,12 @@ impl Flight { self.unseen -= usize::from(batch.unseen); if let Some(of) = batch.of { of.observed(share); + if let Some(count) = self.turns.get_mut(&batch.queue) { + *count -= 1; + if *count == 0 { + self.turns.remove(&batch.queue); + } + } } } } @@ -353,6 +378,82 @@ impl Flight { Room::Hold { after, through } } + /// Whether a batch of command queue `queue` may go now on its turn (`queue_turns.rs`): under + /// [`BUDGET`] where another command queue took a batch here within [`ACTIVE`] of `now` + /// (`gpu_time::host_nanos`), else under [`IDLE_BUDGET`], [`Room::Idle`] where only that let + /// it go. `expected` is its queue's expected run now; `ran` and `completed` are + /// [`ahead`](Self::ahead)'s. + pub(crate) fn turn( + &self, + (queue, expected): (u64, Option), + ran: u64, + completed: u64, + now: u64, + ) -> Room { + let [last, before] = self.latest; + let (_, other) = match last.0 == queue { + true => before, + false => last, + }; + if active(other, now) { + return self.own_ahead((queue, expected), ran, completed, BUDGET); + } + match self.own_ahead((queue, expected), ran, completed, IDLE_BUDGET) { + Room::Go if self.own_ahead((queue, expected), ran, completed, BUDGET) != Room::Go => { + Room::Idle + } + room => room, + } + } + + /// Whether a batch of command queue `queue`, whose expected run is `expected` now, may go + /// under `budget` of its own queue's work left in flight (`queue_turns.rs`): each of its + /// batches here counts that run, less what the oldest batch here ran (`ran`, as in + /// [`ahead`](Self::ahead)) where it is one of them; one of a queue with no run seen holds the + /// next until it completes. Held until the oldest batch here, of value `through`, completes, + /// or, where only the budget holds it and its own oldest runs now, until `after` + /// nanoseconds from now, where that batch's expected run brings its work left under the + /// budget then. + pub(crate) fn own_ahead( + &self, + (queue, expected): (u64, Option), + ran: u64, + completed: u64, + budget: u64, + ) -> Room { + let (gone, gone_own) = (self.batches.iter()) + .take_while(|batch| batch.value <= completed) + .fold((0, 0), |(gone, own), batch| { + (gone + 1, own + usize::from(batch.queue == queue)) + }); + let own = self.turns.get(&queue).map_or(0, |&count| count - gone_own); + let Some(oldest) = self.batches.get(gone) else { + return Room::Go; + }; + if own == 0 { + return Room::Go; + } + let through = oldest.value; + let Some(run) = expected else { + return Room::Hold { + after: None, + through, + }; + }; + let running = gone == 0 && oldest.queue == queue; + let credit = match running { + true => ran.min(run), + false => 0, + }; + let left = (own as u64).saturating_mul(run) - credit; + if left < budget { + return Room::Go; + } + let over = left - budget + 1; + let after = (oldest.queue == queue && run - credit >= over).then_some(over); + Room::Hold { after, through } + } + /// The batches in flight, of every queue. #[cfg(test)] pub(crate) fn len(&self) -> usize { @@ -369,18 +470,22 @@ impl crate::Device { == metal2vulkan::device::UnsharedIsolationPolicy::Bounded } - /// How a batch of a command queue (`unshared` where made so) taken on `VkQueue` `index` enters - /// its flight, `expected` its queue's expected run. + /// How a batch of command queue `queue` (`unshared` where made so) taken on `VkQueue` `index` + /// enters its flight, `expected` its queue's expected run: every batch where the device's + /// queues take turns (`queue_turns.rs`), else where other queues' work is held back there for + /// an unshared queue. pub(crate) fn flies<'a>( &self, index: usize, - unshared: bool, + (queue, unshared): (u64, bool), expected: &'a Arc, ) -> Flies<'a> { - match (self.holds_back_for_unshared(index), unshared) { - (false, _) => Flies::Not, - (true, true) => Flies::Unshared, - (true, false) => Flies::Other(expected), + if !self.takes_turns() && !self.holds_back_for_unshared(index) { + return Flies::Not; + } + match unshared { + true => Flies::Unshared(queue), + false => Flies::Other(queue, expected), } } } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 0cbf93dd6..cb8da7b42 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -330,6 +330,7 @@ pub(crate) struct Counters { heads_waiting_at_their_gate: AtomicU64, scheduled_behind_host_steps: AtomicU64, heads_let_go_unshared_idle: AtomicU64, + heads_let_go_turn_idle: AtomicU64, heads_held_for_unshared_commits: AtomicU64, host_step_gates_narrowed: AtomicU64, heads_awaiting_check_signals: AtomicU64, @@ -3842,6 +3843,13 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// A look let a head go on its turn under `unshared_hold::IDLE_BUDGET` that + /// `unshared_hold::BUDGET` would hold back: no other command queue took a batch on its + /// `VkQueue` within `unshared_hold::ACTIVE` (`queue_turns.rs`). + pub(crate) fn head_let_go_turn_idle(&self) { + self.heads_let_go_turn_idle.fetch_add(1, Ordering::Relaxed); + } + /// A look held a head whose room had come behind an unshared queue's commit on its `VkQueue` /// not yet taken into the scheduler's order, or leading its line on its way /// (`unshared_hold.rs`, "Commits not yet taken in", "Commits on their way"). @@ -8168,6 +8176,18 @@ pub struct WorkCounts { /// and the held head next. Commits posted after its room came never hold it, nor one that /// waits for anything else. pub heads_held_for_unshared_commits: u64, + /// Heads found held back for their turn on a `VkQueue` two or more command queues hold, + /// because 2 ms or more of their own queue's expected GPU work was in flight there + /// (`queue_turns.rs`, `QueueTurnPolicy::Fair`): another queue's command buffer committed later + /// goes in behind about that much of it and one batch, not its whole backlog. While no other + /// command queue took a batch there within the last 50 ms, 16 ms or more + /// (`heads_let_go_turn_idle`). An unshared queue's heads are never held so. + pub heads_held_for_queue_turns: u64, + /// Heads a look let go on their turn with 2 ms or more of their own queue's expected GPU work + /// in flight on their `VkQueue`, which would hold them (`heads_held_for_queue_turns`), because + /// no other command queue took a batch there within the last 50 ms and less than 16 ms was in + /// flight (`queue_turns.rs`'s idle budget): a queue alone keeps about 16 ms queued. + pub heads_let_go_turn_idle: u64, /// Times a look left a head that needs a host step waiting at its gate: the step reads what /// the GPU may write, so it waits until the batches that last wrote what it reads completed /// (`host_step_gates_narrowed`), or else until every `VkQueue` completed what was submitted to @@ -8297,6 +8317,8 @@ pub struct WorkCounts { pub scheduler_at_commit_left_binary_waits: u64, /// It is held back for an unshared queue (`unshared_hold.rs`). pub scheduler_at_commit_left_unshared: u64, + /// It waits for its turn on a `VkQueue` it shares (`queue_turns.rs`). + pub scheduler_at_commit_left_turns: u64, /// Anything else: a rebind encodes it again, a decode it reads is queued, a switch of storage /// forms rides on it, a group holds it or was held, or its submission was put back. pub scheduler_at_commit_left_other: u64, @@ -12551,6 +12573,8 @@ impl Device { heads_held_for_unshared_commits: counters .heads_held_for_unshared_commits .load(Ordering::Relaxed), + heads_held_for_queue_turns: held_for(HeldFor::QueueTurn), + heads_let_go_turn_idle: counters.heads_let_go_turn_idle.load(Ordering::Relaxed), heads_waiting_at_their_gate: counters .heads_waiting_at_their_gate .load(Ordering::Relaxed), @@ -12596,6 +12620,7 @@ impl Device { scheduler_at_commit_left_host_steps: left_at_commit(LeftAtCommit::HostStep), scheduler_at_commit_left_binary_waits: left_at_commit(LeftAtCommit::BinaryWait), scheduler_at_commit_left_unshared: left_at_commit(LeftAtCommit::Unshared), + scheduler_at_commit_left_turns: left_at_commit(LeftAtCommit::Turn), scheduler_at_commit_left_other: left_at_commit(LeftAtCommit::Other), footprints_built: counters.footprints_built.load(Ordering::Relaxed), footprint_lock_waits: counters.footprint_lock_waits.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index dafbad0cf..e3f580063 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 525; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2489; +pub const RUNTIME_VERSION: u32 = 2490; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/device/mod.rs b/crates/metal2vulkan/src/device/mod.rs index 3af566a26..aefcc6ad3 100644 --- a/crates/metal2vulkan/src/device/mod.rs +++ b/crates/metal2vulkan/src/device/mod.rs @@ -69,8 +69,9 @@ pub use policy::{ BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DevicePolicy, DontCareColorPolicy, ExtendedRangeBlitPolicy, HalfChainPolicy, HeapAnswerPolicy, HeapCompressionPolicy, HostPageTexturePolicy, IndirectRecordsPolicy, ManagedCopyInPolicy, PipelineWaitPolicy, - QueueSharingPolicy, RateMapRegionPolicy, RenderLoweringPolicy, UnsharedIsolationPolicy, - UnstoredDontCarePolicy, VertexReachPolicy, WideLinePolicy, YCbCrInPlacePolicy, + QueueSharingPolicy, QueueTurnPolicy, RateMapRegionPolicy, RenderLoweringPolicy, + UnsharedIsolationPolicy, UnstoredDontCarePolicy, VertexReachPolicy, WideLinePolicy, + YCbCrInPlacePolicy, }; pub(crate) use profile::whole_point_size; pub use profile::{DeviceProfile, SpirvValidation}; diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index e87f34bc1..92b248dd2 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -7,17 +7,19 @@ use std::time::Duration; /// Policy inputs of `Device::new`. Every field but `heap_compression`, `heap_answers`, /// `completion`, `batch_order`, `render_lowering`, `host_page_textures`, `pipeline_waits`, /// `pipeline_creation_wait`, `pipeline_commit_wait`, `wide_lines`, `extended_range_blits`, -/// `queue_sharing`, `unshared_isolation`, `dont_care_colors`, `unstored_dont_care_loads`, -/// `vertex_reach`, `rate_map_regions`, `managed_copy_in` and `indirect_records` can change emitted -/// code, so the profile carries it (containment as the encoding it selects) and its fingerprint -/// covers it; those nineteen are the runtime's alone (a heap's +/// `queue_sharing`, `unshared_isolation`, `queue_turns`, `dont_care_colors`, +/// `unstored_dont_care_loads`, `vertex_reach`, `rate_map_regions`, `managed_copy_in` and +/// `indirect_records` can change emitted code, so the profile carries it (containment as the +/// encoding it selects) and its fingerprint covers it; those twenty are the runtime's alone (a +/// heap's /// compressed texture's image, what a heap texture's size query answers, when the host sees a /// command buffer complete, how a batch begins after the earlier ones /// of its queue, where a render encoder's calls are lowered, what holds a sampled texture over host /// pages, whether and how long a pipeline the driver is still making is waited for, which lines /// draw a wide line, what a blit through a compressed extended-range texture writes, which /// `VkQueue` a command queue submits to, how much of other queues' work goes ahead of an unshared -/// queue's on a `VkQueue` they share, what a colour attachment stored `DontCare` keeps, what a pass +/// queue's on a `VkQueue` they share, how much of its own work a command queue keeps submitted +/// ahead on a `VkQueue` it shares, what a colour attachment stored `DontCare` keeps, what a pass /// reads of an attachment it loads `DontCare` and does not store, which draws fetch a vertex /// layout in the shader where the device's fixed-function input would wrap past 4 GiB, how a /// rate-mapped pass's draws reach its regions, when a `Managed` buffer's GPU copy takes the @@ -121,6 +123,12 @@ pub struct DevicePolicy { /// unshared queue's command buffers wait behind no deep backlog (the default), or submits /// every ready batch at once. The runtime's choice alone: no emitted code changes. pub unshared_isolation: UnsharedIsolationPolicy, + /// Whether command queues that share a `VkQueue` take turns there, each keeping only about + /// 2 ms of its own expected GPU work submitted ahead while another submits there, so a + /// command buffer of one waits behind no deep backlog of another's (the default), or every + /// ready batch is submitted at once, in commit order. The runtime's choice alone: no emitted + /// code changes. + pub queue_turns: QueueTurnPolicy, /// Whether a colour attachment of a texture's own image that a pass stores `DontCare` is /// stored as the driver stores it (the default) or renders through a backing so that the /// texture keeps the texels it held before the pass, as Apple's GPU leaves them. The runtime's @@ -170,7 +178,8 @@ impl DevicePolicy { /// being made waited for a bound (4.5 s at a state's creation, and 4.5 s from a commit), a /// wide line the device's own wherever it draws the width, command queues sharing /// `VkQueue`s where the device's GPU idles between work of different ones, other queues' work - /// held to about 2 ms ahead of an unshared queue's on a `VkQueue` they share, a colour stored + /// held to about 2 ms ahead of an unshared queue's on a `VkQueue` they share, each command + /// queue's own work held to about 2 ms ahead on a `VkQueue` it shares, a colour stored /// `DontCare` stored as the driver stores it, an attachment loaded `DontCare` and not stored /// cleared where its driver clears it no slower, a vertex layout pulled past a wrapping /// fixed-function input only where the draw's own values reach past 4 GiB, a rate-mapped @@ -198,6 +207,7 @@ impl DevicePolicy { extended_range_blits: ExtendedRangeBlitPolicy::Kept, queue_sharing: QueueSharingPolicy::Adaptive, unshared_isolation: UnsharedIsolationPolicy::Bounded, + queue_turns: QueueTurnPolicy::Fair, dont_care_colors: DontCareColorPolicy::Driver, unstored_dont_care_loads: UnstoredDontCarePolicy::Driver, vertex_reach: VertexReachPolicy::Bounded, @@ -236,8 +246,8 @@ impl DevicePolicy { /// on the CPU at the commit ([`ManagedCopyInPolicy::AtCommit`]), and every indirect command /// buffer's records in the runtime's own pages wherever the device imports host pointers, /// which a recovery keeps ([`IndirectRecordsPolicy::Carried`]). Every other field is kept, - /// `unshared_isolation` among them: its default is the one nearer Metal's, whose queues do - /// not wait for each other's whole command buffers. + /// `unshared_isolation` and `queue_turns` among them: their defaults are the ones nearer + /// Metal's, whose queues do not wait for each other's whole command buffers. pub const fn exact_answers(self) -> DevicePolicy { DevicePolicy { heap_compression: HeapCompressionPolicy::Uncompressed, @@ -679,6 +689,39 @@ pub enum UnsharedIsolationPolicy { Off, } +/// Whether command queues that share a `VkQueue` take turns there. A `VkQueue` runs its +/// submissions in order, so a command buffer there waits for every batch submitted before it: +/// where one command queue commits a burst of command buffers (a long one cut into parts, a +/// backlog of frames) on the one graphics queue of RADV, ANV, lavapipe or another driver that +/// lends one, a command buffer another queue commits after it waits for the whole burst, where +/// Metal ran a second queue's small command buffer beside a first queue's 200 ms one (an Intel +/// UHD 630 and an AMD Radeon Pro 5300M, macOS 26.7.1). A queue made with +/// `new_command_queue_unshared` is never held under either value; `UnsharedIsolationPolicy` +/// bounds the other queues' work ahead of it. The runtime's choice alone: no emitted code +/// changes. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum QueueTurnPolicy { + /// The default: on a `VkQueue` that two or more command queues hold, a batch of a queue not + /// made unshared is submitted 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 submitted there within the last + /// 50 ms), else held in the runtime's scheduler until enough of it completes, while a later + /// commit of another queue that shares nothing with it goes ahead of it. So another queue's + /// command buffer goes in behind about that much of each busy queue's work and one batch of + /// it, not its whole backlog. A batch's expected GPU work is its queue's expected run now + /// (the host's view of how long its recent batches ran, raised at once by a longer one and + /// halved toward a shorter one), so a run longer than the queue's recent ones prices every + /// batch of it in flight at once; while a batch of a queue with no run seen yet is in flight + /// there, no other batch of that queue is submitted until it completes. A batch already + /// submitted runs to its end. + #[default] + Fair, + /// Every ready batch is submitted at once, in commit order: a command buffer waits behind + /// every batch submitted before it on its `VkQueue`. + CommitOrder, +} + /// What a colour attachment of a texture's own image (not a texture over a buffer's bytes, not /// memoryless, resolving nothing) keeps after a render pass stores it `MTLStoreActionDontCare`. /// Metal's documentation leaves it open (`MTLStoreAction.dontCare`: "You need to assume that GPU diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index a8f3fe22c..49009e0d9 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -9,8 +9,8 @@ use crate::device::{ BatchOrderPolicy, CompletionPolicy, DevicePolicy, DontCareColorPolicy, ExtendedRangeBlitPolicy, HalfChainPolicy, HeapAnswerPolicy, HeapCompressionPolicy, HostPageTexturePolicy, IndirectRecordsPolicy, ManagedCopyInPolicy, PipelineWaitPolicy, QueueSharingPolicy, - RateMapRegionPolicy, RenderLoweringPolicy, UnsharedIsolationPolicy, UnstoredDontCarePolicy, - VertexReachPolicy, WideLinePolicy, YCbCrInPlacePolicy, + QueueTurnPolicy, RateMapRegionPolicy, RenderLoweringPolicy, UnsharedIsolationPolicy, + UnstoredDontCarePolicy, VertexReachPolicy, WideLinePolicy, YCbCrInPlacePolicy, }; use crate::pipeline::PrecisionNote; use std::collections::BTreeSet; @@ -67,8 +67,9 @@ fn choices() -> Vec { // how long a pipeline being made is waited for (the bounds' values: // `the_ledger_states_the_pipeline_wait_bounds`), which lines draw a wide line, what a // blit through a compressed extended-range texture writes, which `VkQueue` a command - // queue submits to, how much of other queues' work goes ahead of an unshared queue's, what - // a colour attachment stored `DontCare` keeps, what a pass reads of an attachment it loads + // queue submits to, how much of other queues' work goes ahead of an unshared queue's, how + // much of its own work a queue keeps ahead on a `VkQueue` it shares, what a colour + // attachment stored `DontCare` keeps, what a pass reads of an attachment it loads // `DontCare` and does not store, which draws pull a vertex layout past a wrapping // fixed-function input, how a rate-mapped pass's draws reach its regions, when a // `Managed` buffer's GPU copy takes the bytes `didModifyRange:` names, and where an @@ -87,6 +88,7 @@ fn choices() -> Vec { extended_range_blits: _, queue_sharing: _, unshared_isolation: _, + queue_turns: _, dont_care_colors: _, unstored_dont_care_loads: _, vertex_reach: _, @@ -112,6 +114,7 @@ fn choices() -> Vec { choice!(p.extended_range_blits: ExtendedRangeBlitPolicy { Kept, Canonical }), choice!(p.queue_sharing: QueueSharingPolicy { Adaptive, PerQueue }), choice!(p.unshared_isolation: UnsharedIsolationPolicy { Bounded, Off }), + choice!(p.queue_turns: QueueTurnPolicy { Fair, CommitOrder }), choice!(p.dont_care_colors: DontCareColorPolicy { Driver, Kept }), choice!(p.unstored_dont_care_loads: UnstoredDontCarePolicy { Driver, Cleared }), choice!(p.vertex_reach: VertexReachPolicy { Bounded, Exact }), @@ -661,6 +664,36 @@ fn the_runtime_s_unshared_isolation_choice_keys_no_profile() { } } +/// The runtime's choice of how much of its own work a command queue keeps ahead on a `VkQueue` it +/// shares (`queue_turns`) moves no committed profile's fingerprint: no profile carries it, so no +/// translation follows it. +#[test] +fn the_runtime_s_queue_turns_choice_keys_no_profile() { + use crate::spirv::testing::committed_profiles_with; + let fair = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles"); + let commit_order = committed_profiles_with(DevicePolicy { + queue_turns: QueueTurnPolicy::CommitOrder, + ..DevicePolicy::UNTRUSTED + }) + .expect("profiles"); + assert_eq!(fair.len(), commit_order.len()); + for ((stem, f), (other, c)) in fair.iter().zip(&commit_order) { + assert_eq!(stem, other); + assert_eq!(f.fingerprint(), c.fingerprint(), "{stem}"); + } +} + +/// `DevicePolicy::exact_answers()` keeps the queues' turns on a shared `VkQueue`, the default and +/// the value nearer Metal's. +#[test] +fn exact_answers_keep_the_queues_turns() { + assert_eq!(DevicePolicy::UNTRUSTED.queue_turns, QueueTurnPolicy::Fair); + assert_eq!( + DevicePolicy::UNTRUSTED.exact_answers().queue_turns, + QueueTurnPolicy::Fair + ); +} + /// `DevicePolicy::exact_answers()` keeps every command queue on the `VkQueue` it took at its /// creation, and the default shares them where the device's GPU idles between `VkQueue`s. #[test] diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 7dc09c949..f97d38955 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1561,6 +1561,7 @@ enum metal2vulkan::device::ManagedCopyInPolicy #[cfg_attr(feature = "serde", der enum metal2vulkan::device::PipelineWaitPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum PipelineWaitPolicy enum metal2vulkan::device::PointerDomain #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum PointerDomain enum metal2vulkan::device::QueueSharingPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum QueueSharingPolicy +enum metal2vulkan::device::QueueTurnPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum QueueTurnPolicy enum metal2vulkan::device::RateMapRegionPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RateMapRegionPolicy enum metal2vulkan::device::RenderLoweringPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RenderLoweringPolicy enum metal2vulkan::device::ResolveMode #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ResolveMode @@ -3170,9 +3171,11 @@ field metal2vulkan-runtime::WorkCounts.heads_held_for_decodes pub heads_held_for field metal2vulkan-runtime::WorkCounts.heads_held_for_earlier_commits pub heads_held_for_earlier_commits: u64 field metal2vulkan-runtime::WorkCounts.heads_held_for_event_values pub heads_held_for_event_values: u64 field metal2vulkan-runtime::WorkCounts.heads_held_for_host_steps pub heads_held_for_host_steps: u64 +field metal2vulkan-runtime::WorkCounts.heads_held_for_queue_turns pub heads_held_for_queue_turns: u64 field metal2vulkan-runtime::WorkCounts.heads_held_for_reencodes pub heads_held_for_reencodes: u64 field metal2vulkan-runtime::WorkCounts.heads_held_for_unshared_commits pub heads_held_for_unshared_commits: u64 field metal2vulkan-runtime::WorkCounts.heads_held_for_unshared_isolation pub heads_held_for_unshared_isolation: u64 +field metal2vulkan-runtime::WorkCounts.heads_let_go_turn_idle pub heads_let_go_turn_idle: u64 field metal2vulkan-runtime::WorkCounts.heads_let_go_unshared_idle pub heads_let_go_unshared_idle: u64 field metal2vulkan-runtime::WorkCounts.heads_waiting_at_their_gate pub heads_waiting_at_their_gate: u64 field metal2vulkan-runtime::WorkCounts.heap_arrays_copied pub heap_arrays_copied: u64 @@ -3640,6 +3643,7 @@ field metal2vulkan-runtime::WorkCounts.scheduler_at_commit_left_host_steps pub s field metal2vulkan-runtime::WorkCounts.scheduler_at_commit_left_other pub scheduler_at_commit_left_other: u64 field metal2vulkan-runtime::WorkCounts.scheduler_at_commit_left_passing pub scheduler_at_commit_left_passing: u64 field metal2vulkan-runtime::WorkCounts.scheduler_at_commit_left_taken_in pub scheduler_at_commit_left_taken_in: u64 +field metal2vulkan-runtime::WorkCounts.scheduler_at_commit_left_turns pub scheduler_at_commit_left_turns: u64 field metal2vulkan-runtime::WorkCounts.scheduler_at_commit_left_unshared pub scheduler_at_commit_left_unshared: u64 field metal2vulkan-runtime::WorkCounts.scheduler_gpu_waits pub scheduler_gpu_waits: u64 field metal2vulkan-runtime::WorkCounts.scheduler_passes pub scheduler_passes: u64 @@ -4701,6 +4705,7 @@ field metal2vulkan::device::DevicePolicy.pipeline_creation_wait pub pipeline_cre field metal2vulkan::device::DevicePolicy.pipeline_waits pub pipeline_waits: PipelineWaitPolicy field metal2vulkan::device::DevicePolicy.pointer_domain pub pointer_domain: PointerDomain field metal2vulkan::device::DevicePolicy.queue_sharing pub queue_sharing: QueueSharingPolicy +field metal2vulkan::device::DevicePolicy.queue_turns pub queue_turns: QueueTurnPolicy field metal2vulkan::device::DevicePolicy.rate_map_regions pub rate_map_regions: RateMapRegionPolicy field metal2vulkan::device::DevicePolicy.render_lowering pub render_lowering: RenderLoweringPolicy field metal2vulkan::device::DevicePolicy.unshared_isolation pub unshared_isolation: UnsharedIsolationPolicy @@ -14049,6 +14054,8 @@ variant metal2vulkan::device::PipelineWaitPolicy::Exact Exact variant metal2vulkan::device::PointerDomain::ResidentTable ResidentTable variant metal2vulkan::device::QueueSharingPolicy::Adaptive Adaptive variant metal2vulkan::device::QueueSharingPolicy::PerQueue PerQueue +variant metal2vulkan::device::QueueTurnPolicy::CommitOrder CommitOrder +variant metal2vulkan::device::QueueTurnPolicy::Fair Fair variant metal2vulkan::device::RateMapRegionPolicy::Exact Exact variant metal2vulkan::device::RateMapRegionPolicy::FanOut FanOut variant metal2vulkan::device::RenderLoweringPolicy::AtCall AtCall diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 42805d304..86662fb9e 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -242,6 +242,7 @@ surface! { enum ExtendedRangeBlitPolicy N; enum QueueSharingPolicy N; enum UnsharedIsolationPolicy N; + enum QueueTurnPolicy N; enum DontCareColorPolicy N; enum UnstoredDontCarePolicy N; enum VertexReachPolicy N; diff --git a/docs/API.md b/docs/API.md index 46b688d94..0b6166658 100644 --- a/docs/API.md +++ b/docs/API.md @@ -302,6 +302,22 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: `WorkCounts::heads_held_for_unshared_isolation`. `unshared_isolation = UnsharedIsolationPolicy::Off` submits every ready batch at once, so the unshared queue's command buffers wait behind every batch submitted before them there. +- **Command queues take turns on a `VkQueue` they share** (`QueueTurnPolicy::Fair`, the default; + the runtime's choice, no pipeline differs). On a `VkQueue` two or more command queues hold (a + device with one graphics queue: RADV, ANV, lavapipe), a batch of a queue not made unshared is + submitted there only while less than 2 ms of its own queue's expected GPU work is in flight on + it, or 16 ms while no other command queue submitted there within the last 50 ms; else the + scheduler holds it, in its place in the order, and a later commit of another queue that shares + nothing with it goes first. Each batch of a queue in flight counts the queue's expected run now + (as above), so a run longer than its recent ones prices the rest of a burst at once; a queue + with no run seen yet keeps one batch in flight until it completes. So a command buffer another + queue commits after one queue's burst of command buffers waits behind about 16 ms of it and one + batch, then about 2 ms and one batch while it keeps submitting, not the whole burst; a batch + already submitted still runs to its end. An unshared queue's batches are never held for their + turn. Counted: `WorkCounts::heads_held_for_queue_turns`, `heads_let_go_turn_idle`, + `scheduler_at_commit_left_turns`. `queue_turns = QueueTurnPolicy::CommitOrder` submits every + ready batch at once, in commit order, so a later commit of another queue waits behind every + batch submitted before it there (docs/FAST-PATHS.md has the trade). - **An attachment loaded `DontCare` and not stored, cleared where its driver clears it no slower** (`UnstoredDontCarePolicy::Driver`, the default; the runtime's choice, no pipeline differs). Metal's draws read zero (a colour) or the pass's clear value (depth, stencil) of such an attachment diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 9a336bae7..76f51eb2e 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -196,6 +196,41 @@ known. The rest of the differences are docs/API.md section 9's precision notes. `Off`, the gap before each frame 0.18 ms against 0.12 ms at the median, while under `Bounded` its batches waited 10.8 ms a frame in the scheduler instead of in the `VkQueue` (`WorkCounts::batch_hold_nanos`). The default on every driver with one graphics queue. +- `queue_turns = QueueTurnPolicy::Fair` (the default) makes command queues that share a + `VkQueue` take turns there (`queue_turns.rs`; every queue shares one on a device with one + graphics queue: RADV, ANV, lavapipe, Intel's Windows driver). A batch of a queue not made + unshared goes to a `VkQueue` two or more command queues hold only while less than 2 ms of its + own queue's expected GPU work is in flight there, or 16 ms while no other command queue took a + batch there within the last 50 ms; else the scheduler holds it in its place in the order, and a + later commit of another queue that shares nothing with it goes ahead of it (one whose footprint + runs in commit order with it still waits behind it). A batch's expected work is its queue's + expected run now (`unshared_hold::Expected`: the host's view of how long its recent batches ran, + raised at once by a longer one and halved toward a shorter one), so a run longer than the + queue's recent ones prices every batch of it in flight at once, where the unshared bound above + prices each at the run its queue had at its submission; while a batch of a queue with no run + seen yet is in flight there, that queue's next batch waits for its completion, and no other + queue's does. So a command buffer another queue commits after one queue's burst (a long command + buffer cut into parts, a backlog of frames) goes in behind about 16 ms of it and one batch, not + the whole burst, and from its submission on, while that queue keeps submitting there, behind + about 2 ms and one batch of each busy queue. An unshared queue's batches are never held for + their turn, and count as another queue's. The next batch goes in before the one ahead ends (the + scheduler's thread woken at the oldest batch's completion and at the time its run brings the + work left under the budget), so the GPU idles for the hold only where that thread answers later + than the budget less one batch: a queue alone keeps about 16 ms queued, two queues submitting + keep 2 ms each. A committing or waiting thread's pass leaves a held batch to the scheduler's + thread (`WorkCounts::scheduler_at_commit_left_turns`). Counted: + `WorkCounts::heads_held_for_queue_turns` and `heads_let_go_turn_idle` (heads 2 ms would have + held). `queue_turns = QueueTurnPolicy::CommitOrder` submits every ready batch at once, in commit + order: a later commit of another queue waits behind every batch submitted before it there. Not + an accuracy choice: it trades a queue's work submitted ahead for the other queues' waits; the + value nearer Metal's, whose second queue's small command buffer ran beside a first queue's + 200 ms one on the consumer's oracles (a UHD 630 and a Radeon Pro 5300M, macOS 26.7.1), and + `exact_answers()` keeps it. The runtime's choice: no pipeline differs. What stays is a batch + already submitted: it runs to its end (known gaps, below). On lavapipe, both values + (`queue_share_device::a_later_queue_s_command_buffer_takes_its_turn_ahead_of_another_queue_s_burst`: + twelve 10 ms command buffers of one queue committed at once, a small one of another queue after + the first was scheduled): under `Fair` the small one goes before the burst's fourth, under + `CommitOrder` after its twelfth. The default on every driver. - `pointer_domain`, `handle_domain`, `containment` and `isolation` choose how resources resolve and how guests are contained, not an answer of Metal's arithmetic or sampling. @@ -1388,15 +1423,18 @@ driver's. Each is open work. and `Device::host_range_remapped` does not release such an import. An import of dma-bufs (`HostMemory::with_dma_buf`) keeps its pages on every driver, but is taken only where the device refuses the pointer. -- **On a device with one graphics queue, a compositor's command buffers wait behind another - queue's long batch**: RADV, ANV and lavapipe expose a single graphics `VkQueue`, so every command - queue, `Device::new_command_queue_unshared`'s included, submits to it, in order +- **On a device with one graphics queue, a command buffer waits behind another queue's long + batch**: RADV, ANV, lavapipe and Intel's Windows driver expose a single graphics `VkQueue`, so + every command queue, `Device::new_command_queue_unshared`'s included, submits to it, in order (`WorkCounts::unshared_queues_sharing_a_vk_queue` counts each unshared queue so placed). Other queues' batches are held back to about 2 ms of expected work ahead of an unshared queue's - (`unshared_isolation = UnsharedIsolationPolicy::Bounded`, above), but a batch already submitted - runs to its end: a command buffer committed behind another queue's 200 ms one starts after it, - where Metal runs the compositor's beside it, and one behind a batch longer than its queue's - recent ones waits for the rest of that one too. On the Iris Xe (ANV, Mesa 26.2.6, i915) work of + (`unshared_isolation = UnsharedIsolationPolicy::Bounded`, above), and each plain queue's to + about 2 ms of its own while another queue submits there (`queue_turns = + QueueTurnPolicy::Fair`, above), so a burst of short batches no longer queues a later command + buffer behind all of it; but a batch already submitted runs to its end: a command buffer + committed behind another queue's 200 ms one starts after it, where Metal runs the compositor's + beside it, and one behind a batch longer than its queue's recent ones waits for the rest of that + one too. On the Iris Xe (ANV, Mesa 26.2.6, i915) work of another `VkDevice` (its own kernel context) ran only between submissions, never inside one, whatever its global priority (`HIGH` is refused without privilege; `MEDIUM` against `LOW` answered as equal priorities did): a light submission waited the whole of a 440 ms command