Study guides · Advanced

Resuming after a timer: rearming, masking, and measured invariants

Verify real guest resumption and three timer rearm cycles through pending-state preservation, delivery counts, and causal ordering rather than fixed counters.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Goal: move from one expiry to continuing execution
  2. Rearm only after completing the previous request
  3. Track physical notification and virtual retention while masked
  4. Measured trace: match three complete cycles
  5. Inspect whether boundaries and failures preserve machine state
  6. Runnable Rust: retention and rearm invariants
  7. Reproducibility separates fixed evidence from variable values
  8. Exercise: locate the first broken invariant
  9. Ask Logeia about this articleCheck your understanding

Goal: move from one expiry to continuing execution

Entering a timer handler once does not establish that the guest can continue afterward. Follow measured GUEST_RESUMED events, subsequent deadline programming, and three complete repetitions. Associate guest_main, arm_virtual_timer, handle_guest_irq, and handle_host_irq with their parts of the sequence. Timer programming and interrupt completion are separate responsibilities, and the next cycle depends on both being correct.

The scope remains one trusted guest. This is not a general vCPU scheduler, guest snapshot system, or Linux timekeeping implementation. Shared-RAM delivery counts expose progress through the lesson's ordinary guest code. Match each real deadline, physical notification, virtual acceptance, completion, and return, rather than accepting three printed timer messages as evidence of three complete cycles.

Rearm only after completing the previous request

On expiry, handle_host_irq disables the timer, completes the physical interrupt, and prepares the virtual IRQ. The guest completes the virtual side with IAR, EOIR, and DIR. guest_main checks its target delivery count, records GUEST_RESUMED, and then calls arm_virtual_timer again. Programming another deadline is not a substitute for deactivating the previous virtual interrupt.

Each cycle reads a new current count and adds an interval. It does not advance a permanently fixed schedule by adding to the preceding deadline. Handling and logging time therefore influence the next starting point. Unequal spacing between recorded deadlines does not immediately imply broken arithmetic. Explain the chosen reference point by locating the fresh now read in source.

Track physical notification and virtual retention while masked

timerMasked programs the timer while retaining the EL1 DAIF IRQ mask. Real expiry reaches EL2, PHYSICAL increases, and the virtual LR becomes Pending while DELIVERIES remains zero. After unmasking, the guest handler runs and DELIVERIES increases following DIR. A temporary difference between physical notification count and guest completion count is the intended observation.

This mask neither stops the timer nor suppresses every physical IRQ at EL2. It delays guest acceptance of the pending virtual IRQ. Pending LR state distinguishes retention from loss when physical handling has progressed but guest ACK is absent. Verify one acceptance after unmasking and inspect whether retention introduced duplicates or overwrote an existing request.

Measured trace: match three complete cycles

timerRepeated contains three groups of TIMER_ARM, TIMER_EXPIRED, GUEST_EOI_DIR, and GUEST_RESUMED. At each return PHYSICAL and DELIVERIES match at one, two, and three; DONE confirms three. The table extracts those measured counts and ordering. Preserve raw counters and deadlines in the original UART instead of replacing them with convenient constants; validate relationships and sequence.

For each cycle, check now plus delta equals CVAL, the expiry counter is at least CVAL, and injection follows physical notification. Also establish that GUEST_RESUMED precedes the next ARM. Together these observations show return and reprogramming, not merely a final count of three. Matching final totals and following the correct execution path are distinct properties.

CycleCounts at completion and returnNext check
1PHYSICAL=1 / DELIVERIES=1Next ARM follows RESUMED
2PHYSICAL=2 / DELIVERIES=2Completed LR can be reused
3PHYSICAL=3 / DELIVERIES=3GUEST_RESUMED is reached
FinishDONE: both equal threeNo extra delivery

Inspect whether boundaries and failures preserve machine state

The normal case runs one regular interval, repetition runs three, and the boundary uses one tick. Recording setup before enabling preserves an interpretable ARM-to-EXPIRED sequence even for the shortest interval. timerFailure rejects zero before TIMER_ARM or delivery. Host timer_deadline tests also reject overflow. Identify the stage preventing mutation instead of grouping every failure into one undifferentiated error case.

An occupied LR must not be overwritten by another request. If the previous interrupt remains Active, computing a new deadline does not make the virtual delivery resource available. Connect admission rejection with measured Invalid state after DIR. When delivery counts are short, distinguish absent expiry, retention after physical handling, and guest acceptance without completion.

Runnable Rust: retention and rearm invariants

The standalone host Rust program models a simplified cycle of arming, expiry, retention, and completion. It does not advance time or operate a GIC. expire is a transition invoked by the test, not evidence of real timer firing. Use it separately from machine UART to check design invariants: reject rearming while unfinished and count each completion once.

A masked completion attempt returns false and preserves Pending state. Arming an unfinished cycle is rejected; completion after unmasking increments the count. Repeat three times and verify that an extra completion does not increase it again. Actual IRQ handling contains EOI and DIR, so do not replace their detailed behavior with this coarse operation. State the abstraction and then map it to the measured path.

rust
#[derive(Default)]
struct Cycle { armed: bool, pending: bool, physical: u32, delivered: u32 }
impl Cycle {
    fn arm(&mut self) -> Result<(), &'static str> {
        if self.armed || self.pending { return Err("unfinished cycle"); }
        self.armed = true; Ok(())
    }
    fn expire(&mut self) -> Result<(), &'static str> {
        if !self.armed { return Err("not armed"); }
        self.armed = false; self.pending = true; self.physical += 1; Ok(())
    }
    fn complete(&mut self, masked: bool) -> bool {
        if masked || !self.pending { return false; }
        self.pending = false; self.delivered += 1; true
    }
}
fn main() {
    let mut c = Cycle::default();
    for n in 1..=3 {
        c.arm().unwrap(); c.expire().unwrap();
        assert!(!c.complete(true));
        assert!(c.pending);
        assert_eq!(c.arm(), Err("unfinished cycle"));
        assert!(c.complete(false));
        assert_eq!((c.physical, c.delivered), (n,n));
    }
    assert!(!c.complete(false));
    println!("physical={} delivered={} pending={}", c.physical, c.delivered, c.pending);
}

Reproducibility separates fixed evidence from variable values

ELF identity from fixed source and build settings is different from exact repetition of runtime counters. The recording preserves source identity, build command, QEMU command, ELF hash, and raw UART as one evidence bundle. Do not normalize counter differences and then present the normalized text as raw measurement. Define conditions that tolerate variable timestamps while still checking causality.

Useful conditions include expiry after the deadline, physical notification before virtual ACK, Invalid after DIR, rearming after return, and final counts. Find the first broken condition when a run fails, so downstream omissions are not mistaken for the original cause. Report which claims came from replay and which came from a rebuild and new execution. Both support learning, but establish different evidence boundaries.

Exercise: locate the first broken invariant

Split timerRepeated into cycles and tabulate ARM, EXPIRED, INJECT, ACK, EOI, DIR, and RESUMED. Check deadline arithmetic and delivery counts for each, then explain the successful evidence. Use timerMasked as a control: locate the point where only PHYSICAL has increased and connect Pending state there with later growth in DELIVERIES.

Consider three hypothetical faults: omitted DIR, failed deadline addition, and a guest that never unmasks. Predict the first observable condition each would break. Keep hypotheses separate from measured evidence in the submission, identifying executed cases, referenced recordings, and predictions. As an extension, compare a fixed-period schedule with this implementation's fresh-current-time approach and explain which timing relationships would change.

QEMU recording: timer expiry and guest resumption

Loading experiment checkpoint…

Reading and practice are recorded separately in this browser, for each language.

Choose a learning path