Study guides · Advanced

Virtual timers in Rust: from deadline to interrupt

Follow a guest-programmed virtual timer from counter arithmetic to real EL2 expiry handling and virtual IRQ delivery, with explicit timing units.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Goal: connect deadline arithmetic with notification
  2. Keep counter and compare values in the same units
  3. Record the programmed deadline before enabling
  4. Measured trace: delivery follows the compare condition
  5. Do not equate expiry with instantaneous handler entry
  6. Runnable Rust: deadline arithmetic and boundaries
  7. Identify which stage masking stops
  8. Exercise: test causality rather than fixed timestamps
  9. Ask Logeia about this articleCheck your understanding

Goal: connect deadline arithmetic with notification

A message saying that time passed is weak evidence for a timer implementation. Here the EL1 guest programs a virtual timer compare value, real expiry produces PPI twenty-seven handled at EL2, and EL2 connects that event to a guest virtual interrupt. Read arm_virtual_timer and handle_host_irq, then follow measured TIMER_ARM, TIMER_EXPIRED, and INJECT events. This is not manual advancement of a display counter.

Counter values, frequency, interval ticks, and compare values are different quantities even when represented as integers. Preserve register names and units while calculating from the log. Explain how the deadline was constructed, where elapsed time was observed, and which operation notified the guest as one causal chain.

Keep counter and compare values in the same units

The guest reads the current virtual count from CNTVCT_EL0 and ticks per second from CNTFRQ_EL0. The normal interval is freq divided by one hundred, approximately ten milliseconds in this environment. The recording reports frequency 62,500,000 and interval 625,000 ticks. Do not read the interval as microseconds or treat a raw counter value as milliseconds since startup.

Virtual count involves an EL2 offset, fixed to zero in this experiment through CNTVOFF_EL2. This does not implement separate guest timelines or paused-time compensation. First establish that now and deadline share one counter domain. Mixing different counters can make apparently sensible arithmetic disagree with the actual compare condition, so retain register names as part of each observation.

Record the programmed deadline before enabling

arm_virtual_timer reads now, checks addition through timer_deadline, and writes CNTV_CVAL_EL0. It records now, deadline, interval, and frequency through an HVC before writing one to CNTV_CTL_EL0 to enable the timer. This ordering matters for the one-tick boundary: enabling before logging could let expiry be observed before the program's setup record.

The deadline helper rejects a zero interval and addition overflow. Blind unsigned addition could wrap an extreme value into a small compare value. Separating checked arithmetic from system-register writes allows rejection before changing machine state. A one-tick interval is a valid boundary; zero is rejected by this lesson's contract. Keep that distinction separate from assumptions about other timer APIs.

Measured trace: delivery follows the compare condition

timerNormal records now as 0x31a23, compare as 0xca38b, and delta as 0x98968; addition matches the programmed compare. At TIMER_EXPIRED, counter 0xd328b is at least the compare value, CNTV_CTL_EL0 is five, and physical IAR is twenty-seven. Raw counter values vary between runs, so repeated hexadecimal equality is not the acceptance criterion. Check deadline relationships and causal ordering.

handle_host_irq disables the timer, completes the physical interrupt with EOI and DIR, and injects virtual identifier twenty-seven. Guest ACK, EOI, and DIR follow. The same number appearing on physical and virtual paths does not make them one repeated register operation. Associate each log with its function to distinguish physical notification to EL2 from virtual notification delivered to EL1.

ObservationExample from timerNormalRelationship to check
TIMER_ARMnow=0x31a23 / delta=0x98968now + delta = 0xca38b
TIMER_EXPIREDcounter=0xd328b / CVAL=0xca38bcounter ≥ CVAL
Physical pathIAR=27 / CTL=5EL2 handles expiry
Virtual pathINJECT 27 → GUEST_ACK 27Delivery follows physical notification

Do not equate expiry with instantaneous handler entry

The compare condition becoming true and the UART printing TIMER_EXPIRED are not simultaneous observations. Exception delivery, vector code, Rust handling, and output take time. A measured count greater than the compare value can therefore be normal. It does not by itself show that the wrong deadline was programmed. A notification apparently before its deadline deserves investigation of counter domain and units.

A QEMU TCG recording does not guarantee hardware interrupt latency. Extra logging also changes timing. Normal validation checks expiry at or after the deadline and one delivery; the boundary uses one tick; failures cover zero and overflow. Prefer order and counts across setup, expiry, delivery, and return over exact repeated equality of raw timestamps.

Runnable Rust: deadline arithmetic and boundaries

The host Rust snippet checks only deadline arithmetic and comparison. Frequency 62,500,000 and now equal to one hundred are example inputs, not readings claimed from a machine. Compile it as one ordinary Rust file without AArch64 or QEMU. Do not describe it as firing a hardware timer or delivering an interrupt.

Separate assertions examine one tick before, exactly at, and after the deadline. Near the unsigned maximum, distinguish a valid result equal to the maximum from overflow beyond it. Compare this pure contract with distributed lib.rs tests, then inspect counter-versus-CVAL relationships in the QEMU recording. Arithmetic correctness and actual notification require different evidence, and the workflow deliberately supplies both.

rust
#[derive(Debug, PartialEq)]
enum Reject { ZeroInterval, Overflow }
fn deadline(now: u64, delta: u64) -> Result<u64, Reject> {
    if delta == 0 { return Err(Reject::ZeroInterval); }
    now.checked_add(delta).ok_or(Reject::Overflow)
}
fn expired(counter: u64, compare: u64) -> bool { counter >= compare }
fn main() {
    let now = 100_u64;
    let freq = 62_500_000_u64;
    let end = deadline(now, freq / 100).unwrap();
    assert_eq!(end, 625100);
    assert!(!expired(end - 1, end));
    assert!(expired(end, end));
    assert!(expired(end + 10, end));
    assert_eq!(deadline(100, 0), Err(Reject::ZeroInterval));
    assert_eq!(deadline(u64::MAX, 1), Err(Reject::Overflow));
    assert_eq!(deadline(u64::MAX - 1, 1), Ok(u64::MAX));
    println!("delta={} deadline={} boundary=ok", freq / 100, end);
}

Identify which stage masking stops

timerMasked retains the guest DAIF IRQ mask; it does not stop the virtual timer itself. Expiry PPI twenty-seven is handled at EL2 and virtual identifier twenty-seven becomes Pending in the LR. MASKED_PENDING records zero deliveries, and guest ACK follows unmasking. Without this distinction, a reader might incorrectly conclude that masking stops time or prevents the expiry event itself.

Timer control in CNTV_CTL_EL0 and CPU IRQ acceptance through DAIF are different layers. Whenever masking is discussed, name the register and blocked stage. This implementation routes physical notification to EL2 and delays later virtual acceptance at the guest, so TIMER_EXPIRED and INJECT still appear while the guest is masked. The resumption lesson examines preservation and eventual completion of that pending request.

Exercise: test causality rather than fixed timestamps

Extract frequency, now, delta, and CVAL from timerNormal and check the addition. Then establish that the expiry count is at least CVAL, physical IAR is twenty-seven, and virtual ACK occurs afterward. Write validation conditions that do not require identical raw counters, whether replaying a recording or executing a new machine run.

For timerBoundary, verify interval one and setup logging before expiry. For timerFailure, explain rejection before TIMER_ARM. Submit arithmetic, event ordering, counts, execution conditions, and source references. As an extension, design another positive interval and explain unit and overflow checks. Describe what these observations establish beyond a user interface merely displaying that a wait has completed.

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