Skip to content

openvmm: frequent PIT reads make the counter run about 4.75% fast #1162

Closed

Description

@tangruize

The PIT's counting rate depends on how frequently the guest polls it. Evaluating every 900 ns over 90 ms produces about 4.75% more ticks than evaluating once over the same interval, distorting clock calibration without a snapshot operation.

In vm/devices/chipset/src/pit/mod.rs, PitDevice::evaluate advances its anchor by whole PIT ticks:

        let delta = now.checked_sub(self.last).unwrap_or(Duration::ZERO);
        let ticks = delta.as_nanos() as u64 / NANOS_PER_TICK;
        self.last = self
            .last
            .wrapping_add(Duration::from_nanos(ticks * NANOS_PER_TICK));
        self.timers[0].evaluate(ticks);
        self.timers[1].evaluate(ticks);
        self.timers[2].evaluate(ticks);

NANOS_PER_TICK is 838, but VmTime::wrapping_add truncates each anchor update to 100 ns units. The discarded fraction is included again in the next evaluation, so more frequent reads count more time.

Reproduction

Configure two PITs identically in channel-0 rate-generator mode with count 65535. Evaluate one every 900 ns for 100,000 steps and the other once at 90 ms. Their remaining counter values are 18572 and 23673 instead of matching. Rejecting active periodic channel 0 at snapshot capture does not prevent this steady-state error.

Fix

fix.patch retains the sub-100 ns consumed-tick remainder, incorporates it into evaluation and wakeup scheduling, and clears it on reset. A new default-zero protobuf field preserves the fraction across save/restore; values of 100 ns or more are rejected before changing device state.

Older snapshots restore with remainder zero, and older readers ignore the new field. Pending wakeups remain derived from the restored counters and are recomputed on start.

Activity

  1. tangruize commented on Nov 1, 2026

    @tangruize
    ContributorAuthor

    Proposed patch

    Patch against OpenVMM 998b9f2402050cd16d1faa897bc831ef1434be48. Save the contents below as fix.patch and run git apply fix.patch.

    fix.patch
    diff --git a/vm/devices/chipset/src/pit/mod.rs b/vm/devices/chipset/src/pit/mod.rs
    index 4f1e8bf90..36db227ad 100644
    --- a/vm/devices/chipset/src/pit/mod.rs
    +++ b/vm/devices/chipset/src/pit/mod.rs
    @@ -561,6 +561,7 @@ pub struct PitDevice {
     
         // Volatile state
         last: VmTime,
    +    tick_remainder_nanos: u8,
     }
     
     /// Channel 0 counts in a periodic mode, which the NVX time ABI forbids at
    @@ -582,6 +583,7 @@ pub fn new(interrupt: LineInterrupt, vmtime: VmTimeAccess) -> Self {
                     Timer::new(false, None),
                 ],
                 last: vmtime.now(),
    +            tick_remainder_nanos: 0,
                 vmtime,
                 dram_refresh: false,
                 time_abi: false,
    @@ -611,13 +613,17 @@ fn check_time_abi(&self) -> Result<(), PitActiveError> {
         fn evaluate(&mut self, now: VmTime) {
             // Accumulate an integer number of ticks.
             //
    -        // N.B. if self.last were set to now, then each call to evaluate
    -        // would leak a portion of a tick, causing timers to expire late.
    +        // `last` and the sub-100 ns remainder together locate the last tick.
    +        // Dropping the remainder would count it again on every evaluation.
             let delta = now.checked_sub(self.last).unwrap_or(Duration::ZERO);
    -        let ticks = delta.as_nanos() as u64 / NANOS_PER_TICK;
    -        self.last = self
    -            .last
    -            .wrapping_add(Duration::from_nanos(ticks * NANOS_PER_TICK));
    +        let ticks = delta
    +            .as_nanos()
    +            .saturating_sub(u128::from(self.tick_remainder_nanos))
    +            / u128::from(NANOS_PER_TICK);
    +        let consumed = ticks * u128::from(NANOS_PER_TICK) + u128::from(self.tick_remainder_nanos);
    +        self.last = VmTime::from_100ns(self.last.as_100ns().wrapping_add((consumed / 100) as u64));
    +        self.tick_remainder_nanos = (consumed % 100) as u8;
    +        let ticks = ticks as u64;
             self.timers[0].evaluate(ticks);
             self.timers[1].evaluate(ticks);
             self.timers[2].evaluate(ticks);
    @@ -629,10 +635,10 @@ fn arm_wakeup(&mut self) {
             if let Some(next) = self.timers[0].state.next_wakeup() {
                 // Delay waking up if the next wakeup is too soon to avoid spinning.
                 let next = next.max(20);
    -            self.vmtime.set_timeout_if_before(
    -                self.last
    -                    .wrapping_add(Duration::from_nanos(next * NANOS_PER_TICK)),
    -            );
    +            self.vmtime
    +                .set_timeout_if_before(self.last.wrapping_add(Duration::from_nanos(
    +                    next * NANOS_PER_TICK + u64::from(self.tick_remainder_nanos),
    +                )));
             }
         }
     }
    @@ -650,6 +656,7 @@ async fn reset(&mut self) {
                 timer.reset();
             }
             self.last = self.vmtime.now();
    +        self.tick_remainder_nanos = 0;
         }
     }
     
    @@ -826,6 +833,10 @@ pub struct SavedState {
                 pub timers: [SavedTimerState; 3],
                 #[mesh(2)]
                 pub last: VmTime,
    +            /// Fraction of the last tick not representable in VM time.
    +            /// Absent in older snapshots, which restore with no remainder.
    +            #[mesh(3)]
    +            pub tick_remainder_nanos: u8,
             }
         }
     
    @@ -833,6 +844,8 @@ pub struct SavedState {
         enum PitDeviceRestoreError {
             #[error("last tick time is after current time")]
             InvalidLastTick,
    +        #[error("tick remainder must be less than 100 ns")]
    +        InvalidTickRemainder,
         }
     
         impl SaveRestore for PitDevice {
    @@ -847,6 +860,7 @@ fn save(&mut self) -> Result<Self::SavedState, SaveError> {
                     dram_refresh: _,
                     time_abi: _,
                     last,
    +                tick_remainder_nanos,
                 } = self;
     
                 Ok(state::SavedState {
    @@ -887,11 +901,21 @@ fn save(&mut self) -> Result<Self::SavedState, SaveError> {
                     }),
     
                     last: *last,
    +                tick_remainder_nanos: *tick_remainder_nanos,
                 })
             }
     
             fn restore(&mut self, state: Self::SavedState) -> Result<(), RestoreError> {
    -            let state::SavedState { timers, last } = state;
    +            let state::SavedState {
    +                timers,
    +                last,
    +                tick_remainder_nanos,
    +            } = state;
    +            if tick_remainder_nanos >= 100 {
    +                return Err(RestoreError::InvalidSavedState(
    +                    PitDeviceRestoreError::InvalidTickRemainder.into(),
    +                ));
    +            }
     
                 for (timer, state) in self.timers.iter_mut().zip(timers) {
                     let state::SavedTimerState {
    @@ -932,6 +956,7 @@ fn restore(&mut self, state: Self::SavedState) -> Result<(), RestoreError> {
                 }
     
                 self.last = last;
    +            self.tick_remainder_nanos = tick_remainder_nanos;
                 if last.is_after(self.vmtime.now()) {
                     return Err(RestoreError::InvalidSavedState(
                         PitDeviceRestoreError::InvalidLastTick.into(),
    @@ -975,6 +1000,68 @@ fn test_bcd_comp() {
             }
         }
     
    +    #[test]
    +    fn pit_poll_frequency_does_not_change_elapsed_ticks() {
    +        use super::PitDevice;
    +        use vmcore::vmtime::VmTime;
    +
    +        let mut pool = pal_async::DefaultPool::new();
    +        let driver = pool.driver();
    +        let keeper = vmcore::vmtime::VmTimeKeeper::new(&driver, VmTime::from_100ns(0));
    +        let source = pool.run_until(keeper.builder().build(&driver)).unwrap();
    +        let mut incremental =
    +            PitDevice::new(LineInterrupt::detached(), source.access("incremental"));
    +        let mut elapsed = PitDevice::new(LineInterrupt::detached(), source.access("elapsed"));
    +        for pit in [&mut incremental, &mut elapsed] {
    +            set_timer(&mut pit.timers[0], Mode::RateGenerator, 65_535, false);
    +        }
    +
    +        for n in 1..=100_000 {
    +            incremental.evaluate(VmTime::from_100ns(n * 9));
    +        }
    +        elapsed.evaluate(VmTime::from_100ns(900_000));
    +        assert_eq!(incremental.timers[0].state.ce, elapsed.timers[0].state.ce);
    +        assert_eq!(incremental.last, elapsed.last);
    +        assert_eq!(
    +            incremental.tick_remainder_nanos,
    +            elapsed.tick_remainder_nanos
    +        );
    +    }
    +
    +    #[test]
    +    fn pit_snapshot_preserves_fractional_tick_and_rejects_invalid_remainder() {
    +        use super::PitDevice;
    +        use vmcore::device_state::ChangeDeviceState;
    +        use vmcore::save_restore::SaveRestore;
    +        use vmcore::vmtime::VmTime;
    +
    +        let mut pool = pal_async::DefaultPool::new();
    +        let driver = pool.driver();
    +        let mut keeper = vmcore::vmtime::VmTimeKeeper::new(&driver, VmTime::from_100ns(0));
    +        let source = pool.run_until(keeper.builder().build(&driver)).unwrap();
    +        let mut original = PitDevice::new(LineInterrupt::detached(), source.access("original"));
    +        let mut restored = PitDevice::new(LineInterrupt::detached(), source.access("restored"));
    +        set_timer(&mut original.timers[0], Mode::RateGenerator, 65_535, false);
    +        pool.run_until(keeper.advance(std::time::Duration::from_nanos(900)));
    +        original.evaluate(VmTime::from_100ns(9));
    +        let saved = original.save().unwrap();
    +        assert_eq!(saved.tick_remainder_nanos, 38);
    +        restored.restore(saved).unwrap();
    +        for n in 10..=1000 {
    +            let now = VmTime::from_100ns(n);
    +            original.evaluate(now);
    +            restored.evaluate(now);
    +            assert_eq!(original.timers[0].state.ce, restored.timers[0].state.ce);
    +            assert_eq!(original.last, restored.last);
    +        }
    +
    +        let mut saved = original.save().unwrap();
    +        saved.tick_remainder_nanos = 100;
    +        assert!(restored.restore(saved).is_err());
    +        pool.run_until(original.reset());
    +        assert_eq!(original.tick_remainder_nanos, 0);
    +    }
    +
         fn set_timer(timer: &mut Timer, mode: Mode, mut cr: u16, bcd: bool) {
             timer.set_control(
                 ControlWord::new()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions