Skip to content

openvmm: consecutive PIT low/high writes reuse the preceding count's low byte #1146

Closed

Description

@tangruize

A second PIT count written in low/high access mode gets the wrong value unless the guest also rewrites the control word. Completing the first count leaves the write phase stuck on its high byte.

In vm/devices/chipset/src/pit/mod.rs, Timer::write reads the pending low byte without consuming it:

            RwMode::LOW => self.state.cr = n,
            RwMode::HIGH => self.state.cr = n << 8,
            RwMode::LOW_HIGH => {
                if let Some(low) = self.state.cr_low {
                    self.state.cr = (n << 8) | (low as u16);
                } else {
                    self.state.cr_low = Some(n as u8);

After completing the count, cr_low remains Some(low). Both bytes of the next count are consequently treated as high bytes and combined with the preceding low byte.

Reproduction

Write control word 0x34 to port 0x43 to select channel 0, binary mode 2 and low/high access. Write 0x34, then 0x12, to counter port 0x40, programming count 0x1234.

Without another control word, write 0x78, then 0x56, to program 0x5678. The count register instead ends at 0x5634. Consecutive count writes are valid in periodic modes; requiring a new control word would change guest programming semantics.

Fix

fix.patch uses self.state.cr_low.take() when accepting the high byte. Completing a pair clears the pending low byte, returning the write phase to low for the next count. Low-only/high-only access and the existing control-word reset behavior are unchanged.

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..4e7fc27f3 100644
    --- a/vm/devices/chipset/src/pit/mod.rs
    +++ b/vm/devices/chipset/src/pit/mod.rs
    @@ -366,7 +366,9 @@ fn write(&mut self, n: u8) {
                 RwMode::LOW => self.state.cr = n,
                 RwMode::HIGH => self.state.cr = n << 8,
                 RwMode::LOW_HIGH => {
    -                if let Some(low) = self.state.cr_low {
    +                // The high byte completes the count and resets the write flip-flop:
    +                // the next byte is the low byte of a new count.
    +                if let Some(low) = self.state.cr_low.take() {
                         self.state.cr = (n << 8) | (low as u16);
                     } else {
                         self.state.cr_low = Some(n as u8);
    @@ -1356,4 +1358,120 @@ fn time_abi_rejects_periodic_channel0_at_save_and_restore() {
             device(true).restore(saved).unwrap();
             drop(keeper);
         }
    +
    +    /// PIT-4 (BUG-14), the witness flipped: in the low-then-high access mode the write flip-flop
    +    /// returns to the low byte after the high byte, so a second count written without a new
    +    /// control word takes its bytes as low then high, as the 8254 does (modes 2 and 3 take a new
    +    /// count without a control word, at the next period): after the count 0x1234, the count
    +    /// 0x5678 written as 0x78, 0x56 leaves CR at 0x5678 (before the fix, 0x5634).
    +    #[test]
    +    fn pit4_second_two_byte_count_takes_its_low_byte_first() {
    +        let mut timer = Timer::new(true, None);
    +        set_timer(&mut timer, Mode::RateGenerator, 0x1234, false);
    +        assert_eq!(timer.state.cr, 0x1234);
    +        timer.write(0x78);
    +        timer.write(0x56);
    +        assert_eq!(timer.state.cr, 0x5678);
    +        assert_eq!(timer.state.cr_low, None);
    +    }
    +
    +    /// The 8254 datasheet's count writes, as a reference model: the access mode (control word
    +    /// bits 4, 5) selects the low byte only (1), the high byte only (2), or the low byte then
    +    /// the high byte (3), between which the write flip-flop alternates; a control word for the
    +    /// counter resets the flip-flop. Returns the count a byte completes.
    +    struct DatasheetCountWrites {
    +        rw: u8,
    +        high_next: bool,
    +        low: u8,
    +    }
    +
    +    impl DatasheetCountWrites {
    +        fn control(&mut self, rw: u8) {
    +            self.rw = rw;
    +            self.high_next = false;
    +        }
    +
    +        fn write(&mut self, b: u8) -> Option<u16> {
    +            match self.rw {
    +                1 => Some(b as u16),
    +                2 => Some((b as u16) << 8),
    +                3 => {
    +                    if self.high_next {
    +                        self.high_next = false;
    +                        Some(((b as u16) << 8) | self.low as u16)
    +                    } else {
    +                        self.low = b;
    +                        self.high_next = true;
    +                        None
    +                    }
    +                }
    +                _ => unreachable!(),
    +            }
    +        }
    +    }
    +
    +    /// BUG-14: every access mode and every operating mode take counts as the datasheet's
    +    /// reference model does, for sequences of counts without control words and with control
    +    /// words in between (also between a low and a high byte): after every byte CR holds the
    +    /// count the model completed last, and the null count flag is set exactly when a byte
    +    /// completes a count (or a control word was written).
    +    #[test]
    +    fn pit_count_writes_follow_the_datasheet() {
    +        let mut checked = 0;
    +        for rw in 1..=3u8 {
    +            for mode in 0..=5u8 {
    +                for seed in 1..=20u64 {
    +                    let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1;
    +                    let mut next = || {
    +                        x ^= x << 13;
    +                        x ^= x >> 7;
    +                        x ^= x << 17;
    +                        x
    +                    };
    +                    let control = ControlWord::new().with_mode(mode).with_rw(rw);
    +                    let mut timer = Timer::new(true, None);
    +                    let mut model = DatasheetCountWrites {
    +                        rw: 0,
    +                        high_next: false,
    +                        low: 0,
    +                    };
    +                    timer.set_control(control);
    +                    model.control(rw);
    +                    let mut cr = 0;
    +                    for step in 0..100 {
    +                        if next() % 7 == 0 {
    +                            timer.set_control(control);
    +                            model.control(rw);
    +                            cr = 0;
    +                            assert!(timer.state.null);
    +                        }
    +                        // Clear the null count flag, to see whether the next byte sets it.
    +                        timer.state.null = false;
    +                        let b = next() as u8;
    +                        timer.write(b);
    +                        let completed = model.write(b);
    +                        if let Some(count) = completed {
    +                            cr = count;
    +                        }
    +                        assert_eq!(
    +                            timer.state.cr, cr,
    +                            "rw {rw} mode {mode} seed {seed} step {step}"
    +                        );
    +                        assert_eq!(
    +                            timer.state.null,
    +                            completed.is_some(),
    +                            "rw {rw} mode {mode} seed {seed} step {step}"
    +                        );
    +                        assert_eq!(
    +                            timer.state.cr_low.is_some(),
    +                            model.high_next,
    +                            "rw {rw} mode {mode} seed {seed} step {step}: the write flip-flop"
    +                        );
    +                        checked += 1;
    +                    }
    +                }
    +            }
    +        }
    +        assert_eq!(checked, 3 * 6 * 20 * 100);
    +    }
     }
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