⚡ A vblank tick that found the guest between one-shot arms spent the slot it was about to ask for, halving the compositor's pace

Component: `crates/reims-vgpu` — `runtime::drain::signal_display_refresh_classes`
and its two poll arms (`signal_display_vbl_at`, `device::vbl_contended_pulse`).
x86/Vulkan and arm64 alike; nothing here is pathway-specific.

VBL is what paces the guest's compositor — WindowServer produces a frame off its
display-link callback — so the delivered rate is a ceiling on guest frame rate
however fast the present path runs.

A macOS 13 guest arms VBL **one shot at a time**: it sets bit 0 of the shared
enable word, takes the delivery, clears it inside its handler, and sets it again
when it next wants a frame. `signal_display_refresh_classes`'s own doc already
recorded the `0xc <-> 0xd` oscillation. What nothing recorded is that both
callers claimed the grid slot *before* reading that word, so a tick that sampled
the guest mid-turnaround advanced the grid timestamp and spent the slot the
guest was about to ask for. The guest re-armed a millisecond later and then
waited a further full interval, so its deliveries aliased to every other grid
point — 60 Hz out of an advertised 120.

That is the boot-to-boot regime split this repository has been classifying
around rather than explaining. Six driven macos-13 boots (the `EXTENT_NARROW`
captures, re-read for this): claims land at 117.6-118.4 Hz in every one, so the
limiter and its phase lock were never at fault. What varied is how much of that
grid reached the guest:

    delivered/claimed   presented frames/s   draws/s
           61-67 %             109            ~29 700
           28-39 %              59            ~15 000

Correcting for the pre-online stretch matters when re-deriving this: `not_online`
accumulates for ~22 s before the display comes up, and dividing by the whole boot
makes a healthy 118 Hz limiter read as a broken 82 Hz one.

The fix is an ordering, not a new rail: read the enable mask first, and claim the
slot only once something is armed to receive it. It cannot deliver faster than
advertised — `claim_display_vbl` still gates every delivery on a full interval
since the last one — it only stops the device spending intervals on ticks that
deliver nothing.

The claim moved *into* the shared body rather than being reordered in each
caller. It was two lines duplicated across the locked and lock-free poll arms and
both copies carried the bug; as one line inside the body a third divergence
cannot reintroduce it. This is the same consolidation the enable-mask check
itself needed when the lock-free arm was found omitting it entirely.

Cost: the four-byte enable-mask read now happens once per poll (~240 Hz) instead
of once per claimed tick while the guest sits disarmed, off a page mapped for the
VM's lifetime.

Tests: two new, in `runtime::drain::tests`.
`a_disarmed_tick_does_not_spend_the_grid_slot` models the arm/deliver/disarm/
re-arm cycle and asserts the re-arm is served on the next poll. Verified to fail
against a hand-restored old ordering, with its own message, and to pass with it —
the probe was edited in and out rather than reverted with git.
`a_continuously_armed_guest_is_still_capped_at_the_advertised_rate` guards the
direction this change could have widened; it passes on both orderings by
construction, which is what a guard should do.

Verified: 1897 lib tests plus every integration target green serially; clippy
`-D warnings` clean on all three arms (Vulkan host, `x86_64-unknown-linux-gnu`,
and `aarch64-apple-darwin` `backend-metal`).

Not verified: no live boot yet — the A/B that would show the delivered fraction
and `present_hz` move is the next step and is not in this commit. The reasoning
is from six existing captures plus the unit model, so the mechanism is proven and
the frame-rate claim is not. arm64/Metal is untested as ever on this Linux host.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Anees IqbalandClaude committed 2026-08-11 20:28:59 +03:00
1 parent 43f005e2cb
commit cf77ab7e9e
3 files changed
+174 -19

No files matched your search

+5 -8
View File
@@ -756,13 +756,6 @@ fn vbl_contended_pulse(slot: &BoundDevice) {
let Some(ops) = slot.ops else {
return;
};
// Both poll paths share one limiter, so both have to report into one census
// or the delivered rate reads low by whatever share of polls found the
// device lock contended.
if !crate::runtime::drain::claim_display_vbl(&slot.vbl_last_us, crate::observe::elapsed_us()) {
crate::runtime::drain::note_vbl(crate::runtime::drain::VBL_NOT_CLAIMED, now);
return;
}
let page_size = slot.vbl_page_size.load(Ordering::Acquire);
if page_size == 0 {
// The locked poll publishes this with the rest of the snapshot, so a
@@ -776,13 +769,17 @@ fn vbl_contended_pulse(slot: &BoundDevice) {
// This arm used to carry its own copy, and the copy had already lost a term:
// it never read the enable word at all, so it set a pending bit the guest's
// ISR would never clear and counted the write as `delivered`.
//
// The shared limiter lives in there too, so both arms report into one census
// and neither can spend a grid slot on a tick that found the guest disarmed.
crate::runtime::drain::signal_display_refresh_classes(
&mut host,
gpa,
slot.vbl_display_index.load(Ordering::Acquire),
&slot.intr_disp,
page_size as usize,
now,
&slot.vbl_last_us,
crate::observe::elapsed_us(),
);
}
+61 -11
View File
@@ -5188,6 +5188,40 @@ pub(crate) fn display_event_enabled<H: HostMemory>(host: &H, gpa: u64, event_mas
/// One mask read, one pending read-modify-write and at most one interrupt per
/// tick, so arming both classes does not double the doorbell rate.
///
/// # The mask is read before the grid slot is claimed, and that ordering is load-bearing
///
/// A macOS 13 guest arms VBL **one shot at a time**: it sets bit 0, takes the
/// delivery, clears it inside its handler, and sets it again when it next wants
/// a frame. So on any given tick the mask is as likely to be mid-turnaround as
/// armed, and a tick that samples it disarmed owes nothing.
///
/// Both callers used to claim the slot *first* and read the mask second, which
/// meant a disarmed sample advanced the grid timestamp and **spent the slot the
/// guest was about to ask for**. The guest then re-armed a millisecond later and
/// waited a further full interval, so its delivery rate aliased to every other
/// grid point — 60 Hz out of an advertised 120.
///
/// That is the boot-to-boot regime split, measured over six driven macos-13
/// boots. Claims land at 117.6-118.4 Hz in every one of them, so the limiter and
/// its phase lock were never the problem; what varied was how much of that grid
/// reached the guest:
///
/// ```text
/// delivered/claimed presented frames/s draws/s
/// 61-67 % 109 ~29 700
/// 28-39 % 59 ~15 000
/// ```
///
/// Reading the mask first cannot deliver faster than the advertised rate —
/// [`claim_display_vbl`] still gates every delivery on a full interval having
/// elapsed since the last one. It only stops the device spending intervals on
/// ticks that deliver nothing, which makes the delivered rate converge on the
/// grid the timing table advertises instead of on a fraction of it.
///
/// The cost is that the four-byte enable-mask read now happens once per poll
/// (~240 Hz) rather than once per claimed tick while the guest sits disarmed.
/// That read is of a page already mapped for the VM's lifetime.
///
/// # Both poll arms call this
///
/// The locked poll and the lock-free one taken when the device lock is contended
@@ -5195,14 +5229,23 @@ pub(crate) fn display_event_enabled<H: HostMemory>(host: &H, gpa: u64, event_mas
/// had already diverged once — the lock-free one omitted the enable-mask check
/// entirely. Sharing the body is what keeps a third divergence from being
/// possible: there is one place that decides what a refresh tick writes.
///
/// The claim moved in here for the same reason. It was two lines in each caller,
/// and both copies had the ordering bug above; as one line inside the body, an
/// arm cannot reintroduce it without deleting it from the arm that works.
pub(crate) fn signal_display_refresh_classes<H: HostMemory + HostOps>(
host: &mut H,
gpa: u64,
display_index: u32,
intr_disp: &std::sync::atomic::AtomicU32,
page_size: usize,
now_ms: u64,
last_us: &std::sync::atomic::AtomicU64,
now_us: u64,
) {
// The limiter paces in microseconds because 120 Hz is not expressible in
// whole milliseconds; the census windows in milliseconds so its `t=` stays
// on the same scale as every other always-on line.
let now_ms = now_us / 1_000;
let mut mask_le = [0u8; 4];
if host
.read_gpa(gpa + DISPLAY_SHARED_ENABLE_MASK, &mut mask_le)
@@ -5220,9 +5263,22 @@ pub(crate) fn signal_display_refresh_classes<H: HostMemory + HostOps>(
let vbl = mask & DISPLAY_VBL_EVENT_MASK != 0;
let transaction = mask & DISPLAY_PRESENT_EVENT_MASK != 0;
// A tick that finds nothing armed returns **without consuming a grid slot**.
// This ordering is the whole of the one-shot fix; see the section on it in
// this function's doc.
if !vbl && !transaction {
note_vbl(VBL_NOT_ENABLED, now_ms);
return;
}
if !claim_display_vbl(last_us, now_us) {
note_vbl(VBL_NOT_CLAIMED, now_ms);
return;
}
// Counted after the limiter so the arm is on the same grid as `delivered`
// and the two are directly comparable; a guest that never enables VBL then
// reports the rate it *would* have been paced at.
// and the two are directly comparable. A guest that arms only the
// transaction class still reports `not_enabled` here, because this arm names
// the VBL class and not "did the tick do anything".
note_vbl(
if vbl { VBL_DELIVERED } else { VBL_NOT_ENABLED },
now_ms,
@@ -5230,9 +5286,6 @@ pub(crate) fn signal_display_refresh_classes<H: HostMemory + HostOps>(
if transaction {
note_display_present_signal(DISPLAY_PRESENT_REFRESH);
}
if !vbl && !transaction {
return;
}
let mut pending_le = [0u8; 4];
let pending = if host
@@ -5284,10 +5337,6 @@ fn signal_display_vbl_at<H: HostMemory + HostOps>(
note_vbl(VBL_NOT_ONLINE, now_ms);
return;
}
if !claim_display_vbl(last_us, now_us) {
note_vbl(VBL_NOT_CLAIMED, now_ms);
return;
}
let page_size = state.page_size() as usize;
signal_display_refresh_classes(
host,
@@ -5295,7 +5344,8 @@ fn signal_display_vbl_at<H: HostMemory + HostOps>(
state.display.display_index,
&state.gfx.interrupt_status_disp,
page_size,
now_ms,
last_us,
now_us,
);
}
@@ -3119,6 +3119,114 @@ fn claim_display_vbl_long_stall_resyncs_without_burst() {
assert!(!claim_display_vbl(&last, now + interval)); // same instant: no double
}
/// Stand up a display whose shared page is mapped and whose ONLINE is acked, so
/// `signal_display_vbl_at` reaches the enable-mask read.
#[cfg(test)]
fn one_shot_display() -> (DeviceState, FakeHost, u64) {
let mut state = DeviceState::new(DeviceId(1), PAGE_SHIFT_ARM64E);
let mut host = FakeHost::new();
let gpa = 0x7c000000u64;
host.map_range(gpa, PAGE_SIZE_ARM64E as usize, 0);
state.display.shared_gpa = gpa;
state.display.display_index = 0;
state.display.online_acked = true;
(state, host, gpa)
}
#[cfg(test)]
fn set_enable_mask(host: &mut FakeHost, gpa: u64, mask: u32) {
let mut m = [0u8; 4];
st32(&mut m, mask);
host.write_gpa(gpa + DISPLAY_SHARED_ENABLE_MASK, &m).unwrap();
}
/// Did this tick hand the guest a VBL? Consumes the pending bit the way the
/// guest's ISR does, so the next tick starts from a clean word.
#[cfg(test)]
fn took_vbl(host: &mut FakeHost, gpa: u64) -> bool {
let mut pending = [0u8; 4];
host.read_gpa(gpa + DISPLAY_SHARED_PENDING, &mut pending)
.unwrap();
let got = ld32(&pending) & DISPLAY_VBL_EVENT_MASK != 0;
let mut zero = [0u8; 4];
st32(&mut zero, 0);
host.write_gpa(gpa + DISPLAY_SHARED_PENDING, &zero).unwrap();
got
}
/// A tick that samples the guest mid-turnaround must not spend the grid slot the
/// guest is about to ask for.
///
/// macOS 13 arms VBL one shot at a time — it clears bit 0 inside its handler and
/// sets it again when it next wants a frame — so a poll is as likely to find the
/// mask disarmed as armed. While the claim happened *before* the mask read, that
/// disarmed sample advanced the grid timestamp, and the guest's re-arm a
/// millisecond later then waited a further full interval. Its delivery rate
/// aliased to every other grid point, which is the 60-vs-120 boot-to-boot split.
#[test]
fn a_disarmed_tick_does_not_spend_the_grid_slot() {
use std::sync::atomic::AtomicU64;
let interval = DISPLAY_VBL_MIN_INTERVAL_US;
let (mut state, mut host, gpa) = one_shot_display();
let last = AtomicU64::new(0);
// The guest arms, and one interval in it is served.
set_enable_mask(&mut host, gpa, DISPLAY_VBL_EVENT_MASK | DISPLAY_ONLINE_EVENT_MASK);
signal_display_vbl_at(&mut state, &mut host, &last, interval);
assert!(took_vbl(&mut host, gpa), "an armed guest is served");
// It disarms inside its handler. The next grid point finds nothing armed.
set_enable_mask(&mut host, gpa, DISPLAY_ONLINE_EVENT_MASK);
signal_display_vbl_at(&mut state, &mut host, &last, 2 * interval);
assert!(!took_vbl(&mut host, gpa), "a disarmed guest is owed nothing");
// It re-arms a millisecond later. A full interval has now passed since the
// last *delivery*, so it must be served on the very next poll rather than
// waiting out another interval it already waited.
set_enable_mask(&mut host, gpa, DISPLAY_VBL_EVENT_MASK | DISPLAY_ONLINE_EVENT_MASK);
signal_display_vbl_at(&mut state, &mut host, &last, 2 * interval + 1_000);
assert!(
took_vbl(&mut host, gpa),
"the disarmed tick spent this guest's slot — the 60-Hz latch"
);
}
/// Reading the mask before claiming must not let the guest outrun the refresh
/// rate the timing table advertises.
///
/// This is the direction the fix could have widened: the limiter is the only
/// thing standing between a 240 Hz poll and a guest that holds VBL armed
/// continuously, and it now runs after a read that succeeds far more often.
#[test]
fn a_continuously_armed_guest_is_still_capped_at_the_advertised_rate() {
use std::sync::atomic::AtomicU64;
let interval = DISPLAY_VBL_MIN_INTERVAL_US;
let (mut state, mut host, gpa) = one_shot_display();
let last = AtomicU64::new(0);
set_enable_mask(&mut host, gpa, DISPLAY_VBL_EVENT_MASK | DISPLAY_ONLINE_EVENT_MASK);
// Poll far faster than the grid, the way the 4 ms PCI heartbeat oversamples
// an 8333 us interval, and never disarm.
let step = interval / 8;
let polls = 400u64;
let mut delivered = 0u64;
for i in 1..=polls {
signal_display_vbl_at(&mut state, &mut host, &last, i * step);
if took_vbl(&mut host, gpa) {
delivered += 1;
}
}
let grid = polls * step / interval;
assert!(
delivered <= grid,
"delivered {delivered} exceeds the {grid} the advertised rate allows"
);
assert!(
delivered >= grid - 1,
"delivered {delivered} falls short of the grid {grid}"
);
}
/// After online is acked, a stale ONLINE bit (bit2) left in pending is
/// suppressed by the present/VBL signalers instead of re-delivered — else the
/// guest re-runs process_online → connectionChange → boot-progress overlay.