From 1f2b0f2d39d062c6468c379737293e6f33bbc8b6 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 5 Nov 2026 14:46:09 -0800 Subject: [PATCH] Run a command buffer's completion-seen handlers where seen even with completed handlers A command buffer with completed handlers ran its whole transition to Completed on its queue's handler thread, its completion-seen handlers included, so they started a thread wake after the queue waiter's turn: the consumer's handler_cost bench (a completion-seen and a completed handler on each 4 KiB fill) put that wake into the completion-seen latency. On an idle M3 Max (MoltenVK 1.4.2) the turn-to-handler time was 22 us at the median with a completed handler against 1 us without. Now the waiter runs such a transition to its completion-seen handlers (To::Seen: its status final, those handlers run) where its queue's context is idle, and posts the rest (To::Rest: follow release, completed handlers, slot, releases, gate) to that context while it still runs it, so the queue's later items stay behind the rest. The rest holds its own Hold, so the gate, and wait_until_completed, open only after the completed handlers and once the context is done with the rest (the order a10704b730 set). A command buffer with a Follow (it signals at its end an event another queue's command buffer may wait for) keeps the whole transition on the handler thread, so the cross-queue order (follow.rs) is untouched. Where the waiter cannot run it here (the line busy, a deallocator held), the transition goes whole, as before (Item::whole). complete() is split into complete_seen() and complete_rest(), unchanged in order. Docs: add_completion_seen_handler, completion.rs, the runtime README and RUNTIME-PORTING. Not yet run on a device. (cherry picked from commit e1f36ec2f08735c92872a3d5eed8689b398373ce) --- crates/metal2vulkan-runtime/README.md | 12 +- .../src/command_buffer/completion.rs | 8 +- .../src/command_buffer/mod.rs | 149 ++++++++++++++++-- docs/RUNTIME-PORTING.md | 2 +- 4 files changed, 147 insertions(+), 24 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index e0d04b44d..b2f4f39f3 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -381,10 +381,14 @@ Calls Metal does not have, for a consumer that emulates a Metal device: status, error and GPU times final, on the runtime's thread that saw it complete (its queue's waiter) where its transition to `Completed` runs there, before its completed handlers and before `wait_until_completed` returns: one with no completed handler then finishes with no - handler thread woken. It runs on the queue's handler thread where the transition does (a - completed handler, an earlier transition of the queue still there, or the transition of another - queue's command buffer whose GPU signal it waited for not yet at that one's handlers: it - completes after that one, as Metal's completion follows the GPU's). It must be short and never + handler thread woken. One with completed handlers too has its status made final and these run + there, and the rest of its transition (its completed handlers on) goes to its queue's handler + thread, where its queue's later transitions follow it; unless another queue's command buffer + may complete after it (it signals an event at its end). It runs on the queue's handler thread + where the transition does (an earlier transition of the queue still there, a command buffer that + signals an event at its end with completed handlers, or the transition of another queue's + command buffer whose GPU signal it waited for not yet at that one's handlers: it completes after + that one, as Metal's completion follows the GPU's). It must be short and never block; a wait in it for what has not happened is refused (`DeadlockCause::CompletionSeenHandler`). - `CommandBuffer::commit_and_submit` commits as `commit` does, then submits on the calling thread diff --git a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs index b3bd9a9bc..b1fb84309 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs @@ -29,8 +29,12 @@ //! thread itself. Its completion-seen handlers (`CommandBuffer::add_completion_seen_handler`) //! then run on the waiter too, once its status is final, for a program that answers the //! completion where it is seen: one wake where a completed handler's is two (counted: -//! `WorkCounts::completion_seen_handlers_where_seen`). Everywhere else it is posted, as before, -//! and they run in it on the handler thread. Beside the +//! `WorkCounts::completion_seen_handlers_where_seen`). A command buffer with completed handlers +//! too, and no event signal at its end that another queue's command buffer may wait for, runs +//! there to its completion-seen handlers, and the rest, its completed handlers on, is posted +//! to its queue's context, which the waiter runs meanwhile, so the queue's later transitions +//! follow it (`Transition::seen_first`). Everywhere else it is posted, as before, and they run +//! in it on the handler thread. Beside the //! runtime lane's tests on the M3 Max at the utility clamp, the handler thread's wake between //! the turn and the program's thread took up to 13 to 55 ms at a light burst's 99th percentile //! of the queue storm (`runtime_lane::queue_storms`), over Metal's one wake from its completion; diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index f50f7d137..c0bb1470d 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -2769,11 +2769,15 @@ impl CommandBuffer { /// - **The thread.** The queue's waiter that saw the command buffer's work complete; for one /// that needs no GPU work (nothing it encoded recorded work, and it waits for and signals no /// event), taken with no submission where its queue had no work in flight, the scheduler's - /// thread that took it. Where its transition to `Completed` runs on its queue's handler - /// thread instead, so do these handlers, at the same point of it: where it has a completed - /// handler, an earlier - /// transition of its queue still runs or waits there (a scheduled or completed handler), or - /// the runtime holds a deallocator of the program's + /// thread that took it. A command buffer with completed handlers too runs these there all + /// the same, its status final, and the rest of its transition, its completed handlers on, + /// goes to its queue's handler thread, where its queue's later transitions wait for it (one + /// wake fewer before these handlers; counted: `WorkCounts::completed_where_seen`). Where its + /// transition to `Completed` runs on its queue's handler thread instead, so do these + /// handlers, at the same point of it: where it has a completed handler and signals at its + /// end an event that another queue's command buffer may wait for (that one completes after + /// it, `follow.rs`), an earlier transition of its queue still runs or waits there (a + /// scheduled or completed handler), or the runtime holds a deallocator of the program's /// ([`Device::new_buffer_with_bytes_no_copy`](super::Device::new_buffer_with_bytes_no_copy)), /// which no thread that sees command buffers complete may run (counted: /// `WorkCounts::completion_seen_handlers_run` and @@ -5036,9 +5040,18 @@ impl CommandBufferShared { contexts.open(queue, gate); return; } - let item = Item::Transition(Transition::finished(buffer, result)); - // A thread that may block for a command buffer runs none of the program's code here. - let may_run: fn(&Item) -> bool = match exit_guard::serving_completion() { + // A thread that may block for a command buffer runs none of the program's code here. A + // queue's waiter runs a transition with no completed handler here, and, of one with + // completed handlers and completion-seen handlers and no other queue's command buffer to + // complete after it (no `Follow`), its part to those handlers, posting the rest + // (`Transition::seen_first`): the handlers that may block run on the handler thread, and + // those that answer the completion where it is seen run where it is. + let serving = exit_guard::serving_completion(); + let item = match serving && own.is_none() && seen_first(&lock(&buffer.state)) { + true => Item::Transition(Transition::seen_first(buffer, result)), + false => Item::Transition(Transition::finished(buffer, result)), + }; + let may_run: fn(&Item) -> bool = match serving { true => Item::runs_where_seen, false => Item::plain, }; @@ -5053,17 +5066,26 @@ impl CommandBufferShared { } None => item, }; - contexts.post(queue, item); + contexts.post(queue, item.whole()); posted(); } /// Finish the command buffer with `result` (or the failure of a batch): take the device's - /// trail mark (`trails.rs`), set its status, decode its status words, run its completed - /// handlers on this thread, give its queue's slot back, release its uploads, pools and heap - /// versions, what it retained and its encoders' logs, then open its gate, which releases its - /// waiters once the transition's [`Hold`] (and every other) is gone, and they wait for the - /// trails below the mark. Waits from inside these steps answer as [`own`] says. + /// trail mark (`trails.rs`), set its status, decode its status words, run its completion-seen + /// handlers ([`complete_seen`](Self::complete_seen)), then its completed handlers on this + /// thread, give its queue's slot back, release its uploads, pools and heap versions, what it + /// retained and its encoders' logs, then open its gate, which releases its waiters once the + /// transition's [`Hold`] (and every other) is gone, and they wait for the trails below the + /// mark ([`complete_rest`](Self::complete_rest)). Waits from inside these steps answer as + /// [`own`] says. fn complete(self: &Arc, result: Result<(), CommandBufferError>) { + let rest = self.complete_seen(result); + self.complete_rest(rest); + } + + /// The first part of [`complete`](Self::complete), to its completion-seen handlers: its + /// status final, they ran. What the rest needs is answered. + fn complete_seen(self: &Arc, result: Result<(), CommandBufferError>) -> Rest { // A thread sleeps on `changed`, as the state's lock below reads. let parked; // Its command pool, where it settled, whose primary the device's spares begin ahead once @@ -5255,6 +5277,21 @@ impl CommandBufferShared { exit_guard::program(|| handler(&buffer)); } } + Rest { + settled_pool, + released_versions, + } + } + + /// The rest of [`complete`](Self::complete), once its status is final and its completion-seen + /// handlers ran ([`complete_seen`](Self::complete_seen)): its completed handlers, its queue's + /// slot, its releases and its gate. + fn complete_rest(self: &Arc, rest: Rest) { + let Rest { + settled_pool, + released_versions, + } = rest; + let buffer = CommandBuffer(Arc::clone(self)); // Its status is final and its completion-seen handlers, which never block, ran: the // command buffers of other queues that waited on the GPU for its signals complete from here // on, after it, as its completed handlers start, which may block (`follow.rs`). @@ -5379,8 +5416,8 @@ pub(crate) struct Transition { plain: bool, /// It runs none of the program's code but that and its completion-seen handlers, which a /// thread that saw its command buffer complete may run - /// ([`CommandBuffer::add_completion_seen_handler`]): plain, or a transition to `Completed` - /// with no completed handler. + /// ([`CommandBuffer::add_completion_seen_handler`]): plain, a transition to `Completed` + /// with no completed handler, or one that runs to its completion-seen handlers ([`To::Seen`]). where_seen: bool, } @@ -5389,6 +5426,23 @@ enum To { Scheduled, /// `Completed`, or `Error`. Finished(Result<(), CommandBufferError>), + /// `Completed`, or `Error`, run by a queue's waiter to its completion-seen handlers, the rest + /// posted to its queue's context behind it ([`Transition::seen_first`]). Never posted itself: + /// where it cannot run where seen it goes whole ([`Item::whole`]). + Seen(Result<(), CommandBufferError>), + /// The rest of a transition to `Completed` or `Error` that ran to its completion-seen handlers + /// where seen: its completed handlers, its releases and its gate, on a handler thread. + Rest(Rest), +} + +/// What a command buffer's transition to `Completed` or `Error` still does once its status is +/// final and its completion-seen handlers ran (`CommandBufferShared::complete_rest`). +pub(crate) struct Rest { + /// Its command pool, where it settled, whose primary the device's spares begin ahead once its + /// completed handlers ran. + settled_pool: Option, + /// The heap versions its commands bound, let go of once its completed handlers ran. + released_versions: Vec>, } impl Transition { @@ -5409,6 +5463,23 @@ impl Transition { } } + /// The transition of the command buffer `buffer` holds to `Completed` or `Error`, with + /// `result`, for a queue's waiter to run where its command buffer has completed handlers and + /// completion-seen handlers: its status and completion-seen handlers where seen, the rest + /// ([`To::Rest`]) posted to its queue's context, which it runs, so the queue's later items wait + /// for it (`CommandBufferShared::finish_here`). + fn seen_first( + buffer: Hold, + result: Result<(), CommandBufferError>, + ) -> Self { + Transition { + buffer, + to: To::Seen(result), + plain: false, + where_seen: true, + } + } + fn run(self) -> Kept { let on_handler_thread = contexts::on_handler_thread(); let Transition { buffer, to, .. } = self; @@ -5420,6 +5491,21 @@ impl Transition { } buffer.complete(result); } + To::Seen(result) => { + buffer.device.shared().counts.completed_where_seen(); + let rest = buffer.complete_seen(result); + // Posted while this thread runs the queue's context (`Contexts::run_here`): it + // runs there next, on a handler thread, and the queue's later items after it. Its + // own hold keeps the gate shut until it ran. + let rest = Item::Transition(Transition { + buffer: buffer.hold(), + to: To::Rest(rest), + plain: false, + where_seen: false, + }); + (buffer.device.shared().contexts).post(buffer.queue.id(), rest); + } + To::Rest(rest) => buffer.complete_rest(rest), } // The hold goes after the transition, once its context is done with it: the gate opens // then. On a queue's waiter (`CommandBufferShared::finish_here`) it goes short of the @@ -5472,8 +5558,29 @@ pub(crate) enum Item { } impl Item { + /// The item to post where a queue's waiter could not run it: a transition to its + /// completion-seen handlers ([`To::Seen`]) goes whole, its completed handlers and all, to its + /// queue's handler thread. + fn whole(self) -> Item { + match self { + Item::Transition(Transition { + buffer, + to: To::Seen(result), + .. + }) => Item::Transition(Transition { + buffer, + to: To::Finished(result), + plain: false, + where_seen: false, + }), + item => item, + } + } + /// Whether it is the transition to `Completed` or `Error` of the command buffer at the address - /// `buffer` (`follow.rs`). + /// `buffer` (`follow.rs`). A command buffer whose transition runs to its completion-seen + /// handlers where seen ([`To::Seen`]) has no [`Follow`]: no other queue's command buffer + /// looks for its transition. fn finishes(&self, buffer: usize) -> bool { match self { Item::Transition(transition) => { @@ -5513,6 +5620,14 @@ impl Run for Item { } } +/// Whether a queue's waiter runs a command buffer's transition to `Completed` or `Error` to its +/// completion-seen handlers and posts the rest ([`Transition::seen_first`]): it has completed +/// handlers, which may block, and completion-seen handlers, which answer the completion where it +/// is seen. None is added after the commit. +fn seen_first(state: &State) -> bool { + !state.completed.is_empty() && !state.seen.is_empty() +} + /// Whether a command buffer's transition runs none of the program's code ([`Transition::plain`]): /// it has no scheduled handler, none is added after its commit, and it waits for no submission /// handler. diff --git a/docs/RUNTIME-PORTING.md b/docs/RUNTIME-PORTING.md index 1b1ad14c4..42be18080 100644 --- a/docs/RUNTIME-PORTING.md +++ b/docs/RUNTIME-PORTING.md @@ -151,7 +151,7 @@ narrow refusal that the call's rustdoc describes. | `ended_encoders` | (none: a runtime extension) | `CommandBuffer::ended_encoders`: each ended encoder's kind, the event waits and signals before it, and what its own commands use; with `commit_failed`'s `FailedEncoders::Set`, what fails the one submission that uses a detached resource | | `add_submission_handler` | (none: a runtime extension) | `CommandBuffer::add_submission_handler`: a handler run once the command buffer's last batch reached its `VkQueue`, on the thread that submitted it (the device's scheduler thread, or one in `commit_and_submit`), in submission order, before it is `Scheduled`; never for one that fails before | | `commit_and_submit` | (none: a runtime extension) | `CommandBuffer::commit_and_submit`: `commit`, then the calling thread submits the ready command buffers committed first, this one among them, where no other pass is under way and each needs no host step or storage-form switch, running their submission checks just before each submission (one that waits for a shared event's GPU signal to land is left to the scheduler's thread; a plain event's wait goes to the `VkQueue`) and their submission handlers inside the call; the rest goes to the scheduler's thread | -| `add_completion_seen_handler` | (none: a runtime extension) | `CommandBuffer::add_completion_seen_handler`: a handler run once the command buffer completed, its status and GPU times final, on the runtime's thread that saw it complete where its transition to `Completed` runs there (else on its queue's handler thread), before its completed handlers; short, and never blocking | +| `add_completion_seen_handler` | (none: a runtime extension) | `CommandBuffer::add_completion_seen_handler`: a handler run once the command buffer completed, its status and GPU times final, on the runtime's thread that saw it complete where its transition to `Completed` runs there, or runs to its completion-seen handlers there (one with completed handlers, the rest on its queue's handler thread), else on its queue's handler thread, before its completed handlers; short, and never blocking | | `set_submission_check` | (none: a runtime extension) | `CommandBuffer::set_submission_check`: a check of each of Metal's submissions of the command buffer, run once its event waits are met (an `Event` wait for a submitted signal at once, its wait on the `VkQueue`; a `SharedEvent` wait only a GPU signal still running reaches once that signal lands, as Metal schedules each), just before it is submitted, on the thread that submits it (the device's scheduler thread, or one in `commit_and_submit`); a code it answers fails that submission alone, as Metal fails one that uses a resource detached by then | | `object_id` | (none: Metal names an object by pointer) | `Buffer::object_id`, `Texture::object_id`, `Heap::object_id`: an `ObjectId` unique for the object's life, never reused (a sparse heap's `gpu_address` is 0) |