From 6783a94576b7c8997ba7c078b2b324dfd248fda1 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 11 Aug 2026 16:38:49 +0300 Subject: [PATCH] :sparkles: A drain of one channel stamps one slot, so it submits one command buffer and not eleven MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pathway: x86 macOS / Linux Vulkan, drain worker. Behavior change on the child FIFO's completion-stamp path, switched by `REIMS_VGPU_STAMP_COALESCE`. THE MEASUREMENT THAT ASKED FOR THIS `cb718e5f` split the drain residue's `regs` span three ways. Two driven macos-13 `blur=40` boots (`pin-split`), medians over 74 and 75 census windows: tailrd 0.49 / 0.48 ms/s 59 / 58 ns per op headwr 1.00 / 0.99 ms/s 128 / 127 ns per op stamp 92.29 / 98.59 ms/s 12266 / 13334 ns per op sum vs regs_us = 1.00 on every window The two accesses that really are four-byte guest word accesses cost **1.5 ms a second between them**. The stamp is **98.4 % of the span at 12.3 microseconds a packet**, because `write_stamp` is not a word write: on the Vulkan arm it takes the engine lock, binds the guest RAM reference, records a barrier and a `cmd_update_buffer`, reserves a timeline value, and **submits a command buffer**. `engine_delta` says the same thing from the other side, and this is the part that generalizes past the stamp: batch_opens=6812 batch_joins=3934 batch_flushes=6812 batch_flush_draws=10746 **`batch_flushes` equals `batch_opens` exactly, at 1.58 draws a flush.** The draw batch exists to amortize submits across draws and was never allowed to accumulate any, because `write_stamp_after_guest_writes` appends to the open batch and then flushes it. Every packet's stamp flushed whatever draws had gathered. WHAT THE CONTRACT LICENSES Two facts, neither of them a heuristic: 1. **A stamp wait is `>=`, not `==`.** `StampWait::satisfied_by` is `current.wrapping_sub(self.value) as i32 >= 0`, so a wait on V is discharged by any value at or past V in wrapping-signed order. Intermediate values need never appear. 2. **A drain of one channel stamps one slot.** `stamp_index` is read once from the channel's register block *before* the loop, so every packet in a `drain_child_fifo` call writes the same slot. A run of writes to one slot is observable only through its greatest value unless the guest samples between them. So `drain_child_fifo` now latches each packet's completion stamp into a `PendingStamp` and writes once, after the loop. A driven boot averages **11.6 packets per drain call** (`packets` ~6400/s over `setup_calls` ~550-600/s), so this removes roughly ten submissions in eleven. THE TWO HAZARDS IT HAD TO DISPOSE OF, AND HOW **A wait on the slot the drain is holding.** `note_packet_stamp_waits` reads the word out of guest RAM, which is now stale by exactly the stamps this drain has latched. A later packet in the same drain waiting on that slot would read the old value, return `Hold`, and park the channel against a stamp this device is itself sitting on — a deadlock introduced by the coalescing rather than by the guest. It now consults the latch first, and answering from it is not a shortcut: packets are processed in order on this thread, so a latched stamp is work that finished before the waiting packet was decoded. Counted as `packet_stamp_wait_met_pending` so the reliance is measurable rather than assumed. **A latched stamp that never lands.** Every `break` in that loop falls through to one site after it, which is why one flush is enough — a drain that stops on a held stamp, a deferred translation, a decode fault or a host-action yield owes what it latched exactly as one that ran the ring dry does. Leaving one unwritten is a guest waiting on a word that never arrives, and its own deadline is a second, so it would present as a stall rather than a hang. `PendingStamp::latch` keeps the **maximum in wrapping-signed order**, not the last value seen. For a well-formed guest those are the same value; taking the maximum means this device cannot publish a slot going backwards even if a regressing stamp arrives, which would unsatisfy a wait the guest had already been told was met. The main FIFO is unchanged and passes `None`: it stamps per packet and its slot is not fixed across a drain, so neither fact above holds there. It also executed zero times on this workload. SWITCH `REIMS_VGPU_STAMP_COALESCE=off` restores the per-packet arm on the same binary, because a change to *when* a completion becomes visible fails as a stall or a stutter rather than as a decline, and both arms have to be reachable for one A/B. Off is a refusal and never a permission — one write per packet is strictly more work than one per drain, and the coalesced arm needs no capability the per-packet arm does not. VERIFIED - 1881 tests pass (+2), `--test-threads=1`, backend-vulkan,host-window. - Both new tests fail without the change. `a_coalesced_stamp_keeps_the_latest_ value_across_the_u32_wrap` was probed by stubbing `latch` to last-write-wins and fails on the regressing-stamp assertion; the file was restored by copying it back, not with git. - Clippy `-D warnings` clean on all three arms. - `scripts/feature-matrix`: all supported arms compile, warnings=0, lib count 1881 (was 1879). NOT VERIFIED - **No boot.** Nothing here is measured on a guest yet: not the saving, not the frame rate, and not that the desktop still composites. That is the next step and it is an A/B against `=off` on one binary. - Whether `batch_flushes` actually falls and whether the draw batch then accumulates. The prediction is that it does and that the win is larger than the 92 ms/s the stamp span itself carries, but a prediction is not a reading. - The arm64/Metal pathway. The coalescing is backend-independent but `write_stamp`'s GPU rail is `backend-vulkan`-gated, so the saving is expected to differ there and no Apple host has booted it. Co-Authored-By: Claude --- crates/reims-vgpu/src/env.rs | 19 ++- crates/reims-vgpu/src/runtime/drain/mod.rs | 126 +++++++++++++++++-- crates/reims-vgpu/src/runtime/drain/tests.rs | 72 ++++++++++- 3 files changed, 206 insertions(+), 11 deletions(-) diff --git a/crates/reims-vgpu/src/env.rs b/crates/reims-vgpu/src/env.rs index ebab85b31..bb0552a03 100644 --- a/crates/reims-vgpu/src/env.rs +++ b/crates/reims-vgpu/src/env.rs @@ -200,6 +200,22 @@ pub const UNUSED_BINDS: &str = "REIMS_VGPU_UNUSED_BINDS"; /// less concurrency than several, never more. pub const PRESENT_DEPTH: &str = "REIMS_VGPU_PRESENT_DEPTH"; +/// **Default on.** Setting this off restores one completion-stamp write per +/// packet, which is what `drain_child_fifo` did before the stamps in a single +/// drain of one channel were collapsed into a single write at its end. +/// +/// Off is a refusal and never a permission: one write per packet is strictly +/// more work than one per drain, never less, and the coalesced arm needs no +/// capability the per-packet arm does not. +/// +/// It exists because the stamp is **12.3 us a packet** on the Vulkan arm — +/// `write_stamp` submits a command buffer rather than writing a word — and +/// because a change to when a completion becomes visible to the guest is the +/// kind whose failure is a stall or a stutter rather than a decline. The +/// previous behavior has to stay reachable without a rebuild so the two can be +/// A/B'd on one binary. +pub const STAMP_COALESCE: &str = "REIMS_VGPU_STAMP_COALESCE"; + /// **Probe, default off.** Setting this *on* cuts every guest-page scatter run /// into four contiguous sub-ranges that tile it exactly. /// @@ -503,7 +519,7 @@ pub fn switch(name: &str) -> Switch { /// Nothing enforces that a new `pub const` above is added to this list; the rule /// is stated and honestly unenforced. What keeps it small is that the list is /// next to the constants, and [`report_line`] is the only consumer. -pub const ALL: [&str; 14] = [ +pub const ALL: [&str; 15] = [ LAZY_WRITEBACK, SLAB_RETAIN, CLEAR_SEED, @@ -516,6 +532,7 @@ pub const ALL: [&str; 14] = [ BATCH_MIXED_TARGETS, UNUSED_BINDS, PRESENT_DEPTH, + STAMP_COALESCE, SCATTER_SPLIT, COMPUTE_SCATTER, ]; diff --git a/crates/reims-vgpu/src/runtime/drain/mod.rs b/crates/reims-vgpu/src/runtime/drain/mod.rs index 6e7e0fc68..4de85336d 100644 --- a/crates/reims-vgpu/src/runtime/drain/mod.rs +++ b/crates/reims-vgpu/src/runtime/drain/mod.rs @@ -824,6 +824,63 @@ impl StampWait { } } +/// The completion stamp one drain of one channel owes, coalesced. +/// +/// Every packet in a `drain_child_fifo` call stamps **the same slot** — the +/// index is read once from the channel's register block before the loop — and a +/// stamp wait is satisfied by any value at or past the one awaited +/// ([`StampWait::satisfied_by`]). So a run of stamps to one slot is observable +/// only through its greatest value unless the guest samples between the writes, +/// and writing only that value discharges every wait the run would have. +/// +/// That matters because a stamp is not a word write. On the Vulkan arm +/// `write_stamp` submits a command buffer, measured at **12.3 us a packet** +/// against 59 ns for the tail read beside it, and a driven macos-13 boot +/// averages **11.6 packets per drain call** — so collapsing the run removes +/// roughly ten submissions in eleven. `engine_delta` said the same thing from +/// the other side: `batch_flushes` equalled `batch_opens` at 1.58 draws a +/// flush, because each packet's stamp flushed whatever draws had gathered. +/// +/// [`Self::latch`] takes the **maximum in wrapping-signed order** rather than +/// the last value seen. For a well-formed guest those are the same, and taking +/// the maximum means this device cannot introduce a regressing stamp even if a +/// regressing one arrives — a slot going backwards would unsatisfy a wait the +/// guest had already been told was met. +#[derive(Clone, Copy, Default)] +pub struct PendingStamp { + /// `None` until a packet in this drain has completed. A drain that stamps + /// nothing owes nothing and must submit nothing. + value: Option, +} + +impl PendingStamp { + /// Fold one packet's completion stamp in, keeping the later of the two in + /// the same wrapping-signed order [`StampWait::satisfied_by`] compares in. + pub fn latch(&mut self, stamp: u32) { + self.value = Some(match self.value { + Some(held) if stamp.wrapping_sub(held) as i32 <= 0 => held, + _ => stamp, + }); + } + + /// The value owed, or `None` when this drain stamped nothing. + pub fn owed(self) -> Option { + self.value + } + + /// Whether `wait` is already discharged by what this drain has latched but + /// not yet written. + /// + /// Without this a packet waiting on the slot an earlier packet in the same + /// drain stamped would read the stale word out of guest RAM, return + /// [`StampVerdict::Hold`], and park the channel against a stamp this device + /// is itself holding. `slot` is the drain's own stamp index; a wait naming + /// any other slot is not ours to answer. + fn discharges(self, slot: u32, wait: StampWait) -> bool { + stamp_slot_index(wait.index) == slot && self.value.is_some_and(|v| wait.satisfied_by(v)) + } +} + /// Parsed FIFO packet (main + child share framing). /// /// `stamp_waits` is the record array between header and payload, decoded. The @@ -1147,6 +1204,7 @@ fn note_packet_stamp_waits( host: &H, channel: Option, packet: &Packet, + pending: Option<(u32, PendingStamp)>, ) -> StampVerdict { if packet.stamp_waits.is_empty() { return StampVerdict::Ready; @@ -1154,6 +1212,15 @@ fn note_packet_stamp_waits( let mut verdict = StampVerdict::Ready; for wait in &packet.stamp_waits { let index = stamp_slot_index(wait.index); + // Answered from the drain's own latch before guest RAM, because the word + // in guest RAM is stale by exactly the stamps this drain is holding. The + // ordering the wait asks about already holds: packets are processed in + // order on this thread, so a stamp latched here is work that finished + // before the packet doing the waiting was decoded. + if pending.is_some_and(|(slot, held)| held.discharges(slot, *wait)) { + note_store_route("packet_stamp_wait_met_pending"); + continue; + } let unresolvable = |reason: &'static str, detail: String| { note_store_route("packet_stamp_wait_unresolvable"); if crate::observe::first_sight("packet_stamp_wait_unresolvable", u64::from(index)) { @@ -2200,7 +2267,11 @@ pub fn drain_main_fifo(state: &mut DeviceState, host: & ring_size, ) { Ok(packet) => { - if note_packet_stamp_waits(state, host, None, &packet) == StampVerdict::Hold { + // The main FIFO stamps per packet and latches nothing, so there is + // no pending value here for a wait to be answered from. + if note_packet_stamp_waits(state, host, None, &packet, None) + == StampVerdict::Hold + { // Same hold as the child drain, and this is the timeline // where it matters most: the measured root wait is a // `DELETE_TASK` ordered behind a child FIFO's stamp, so @@ -4336,6 +4407,17 @@ pub fn drain_child_fifo( // See `drain_main_fifo`'s copy for what a sticky bit would cost. state.stamp_deferred_mask &= !bit; + // Every packet below stamps `stamp_index`, which was read once above, so the + // whole drain owes one slot one value. See [`PendingStamp`] for why that is + // collapsed rather than written per packet, and `env::STAMP_COALESCE` for + // the switch that restores the per-packet arm. + let coalesce = crate::env::switch(crate::env::STAMP_COALESCE) != crate::env::Switch::Off; + let mut pending = PendingStamp::default(); + // The slot the latch is about, resolved the same way `write_stamp` resolves + // it, so a wait naming that slot is compared against the same index the + // pending value will be written to. + let stamp_index_slot = stamp_slot_index(stamp_index); + loop { let regs_started = std::time::Instant::now(); let tail_read = crate::runtime::host::read_u32(host, regs_gpa + CHILD_REG_TAIL); @@ -4423,8 +4505,13 @@ pub fn drain_child_fifo( } match decode_packet(&snap, head, available, ring_length) { Ok(packet) => { - if note_packet_stamp_waits(state, host, Some(channel_id), &packet) - == StampVerdict::Hold + if note_packet_stamp_waits( + state, + host, + Some(channel_id), + &packet, + Some((stamp_index_slot, pending)), + ) == StampVerdict::Hold { // The guest ordered this packet behind work that has not // reached its stamp. Hold it: head and completion stamp stay @@ -4483,12 +4570,19 @@ pub fn drain_child_fifo( // an async execution path, that ordering has to come back with // it — and be written against the async model that then exists, // not inherited from an empty queue. - let stamp_started = std::time::Instant::now(); - write_stamp(state, host, stamp_index, packet.completion_stamp); - census::note_drain_regs( - census::RegsOp::Stamp, - stamp_started.elapsed().as_nanos() as u64, - ); + if coalesce { + // Deliberately untimed: the cost this span was measuring is + // the submit, and folding a value into a latch is not one. + // The submit it defers to is timed where it happens, below. + pending.latch(packet.completion_stamp); + } else { + let stamp_started = std::time::Instant::now(); + write_stamp(state, host, stamp_index, packet.completion_stamp); + census::note_drain_regs( + census::RegsOp::Stamp, + stamp_started.elapsed().as_nanos() as u64, + ); + } if state.pending.host_action_yield { if head != tail { state.pending.child_mask |= bit; @@ -4509,6 +4603,20 @@ pub fn drain_child_fifo( } } + // Every `break` above lands here, which is what makes one site enough: a + // drain that stops on a held stamp, a deferred translation, a decode fault + // or a host-action yield owes the stamps it already latched exactly as a + // drain that ran the ring dry does. Leaving one unwritten is a guest waiting + // on a word that never arrives. + if let Some(value) = pending.owed() { + let stamp_started = std::time::Instant::now(); + write_stamp(state, host, stamp_index, value); + census::note_drain_regs( + census::RegsOp::Stamp, + stamp_started.elapsed().as_nanos() as u64, + ); + } + state.draining_mask &= !bit; state.draining_channel = prev_channel; } diff --git a/crates/reims-vgpu/src/runtime/drain/tests.rs b/crates/reims-vgpu/src/runtime/drain/tests.rs index 4096a2c1a..d2e4370ff 100644 --- a/crates/reims-vgpu/src/runtime/drain/tests.rs +++ b/crates/reims-vgpu/src/runtime/drain/tests.rs @@ -4668,7 +4668,7 @@ fn a_stamp_wait_naming_a_slot_that_cannot_exist_runs_rather_than_parking() { ); let decoded = decode_packet(&both, 0, both.len() as u32, RING).expect("two records decode"); assert_eq!( - note_packet_stamp_waits(&state, &host, None, &decoded), + note_packet_stamp_waits(&state, &host, None, &decoded, None), StampVerdict::Unevaluable, "Unevaluable outranks Hold, or the packet parks forever on the wait that \ cannot clear while waiting for the one that could" @@ -5845,3 +5845,73 @@ fn the_map_interval_audit_counts_a_clean_pairing_and_not_only_a_finding() { "a finding must not also be counted as a clean pairing" ); } + +/// The coalesced stamp keeps the **greatest** value a drain latched, in the same +/// wrapping-signed order a wait is compared in. +/// +/// Not "the last one seen". For a well-formed guest the two agree, and the whole +/// point of taking the maximum is that a regressing stamp arriving from the +/// guest cannot make this device publish a slot going backwards — which would +/// unsatisfy a wait the guest had already been told was met. +#[test] +fn a_coalesced_stamp_keeps_the_latest_value_across_the_u32_wrap() { + let mut pending = PendingStamp::default(); + assert_eq!(pending.owed(), None, "a drain that stamped nothing owes nothing"); + + pending.latch(7); + pending.latch(9); + assert_eq!(pending.owed(), Some(9), "the later of two ascending stamps"); + + pending.latch(8); + assert_eq!( + pending.owed(), + Some(9), + "a stamp behind the one held must not pull the slot backwards" + ); + + // Across the wrap: 0xffff_fff0 then 4. The signed difference is +20, so 4 is + // *later*, and a plain `>=` would keep 0xffff_fff0 and stall every wait on + // the far side of the wrap. + let mut wrapped = PendingStamp::default(); + wrapped.latch(0xffff_fff0); + wrapped.latch(4); + assert_eq!( + wrapped.owed(), + Some(4), + "the wrap is a signed difference, not a magnitude comparison" + ); +} + +/// A wait on the slot the drain is holding is answered from the latch. +/// +/// Without this the packet reads the stale word out of guest RAM, returns +/// `Hold`, and parks the channel against a stamp this device is itself sitting +/// on — a deadlock introduced by the coalescing rather than by the guest. +#[test] +fn a_pending_stamp_discharges_a_wait_on_its_own_slot_and_no_other() { + const SLOT: u32 = 3; + let mut pending = PendingStamp::default(); + pending.latch(20); + + let met = StampWait { index: SLOT, value: 20 }; + assert!( + pending.discharges(SLOT, met), + "a wait at exactly the latched value is discharged" + ); + assert!( + pending.discharges(SLOT, StampWait { index: SLOT, value: 12 }), + "and so is one behind it" + ); + assert!( + !pending.discharges(SLOT, StampWait { index: SLOT, value: 21 }), + "a wait past the latched value is not discharged by it" + ); + assert!( + !pending.discharges(SLOT, StampWait { index: SLOT + 1, value: 1 }), + "a wait on another slot is not this drain's to answer" + ); + assert!( + !PendingStamp::default().discharges(SLOT, met), + "a drain that has latched nothing discharges nothing" + ); +}