Skip to content

chipset: PIT LSB/MSB access mode keeps the buffered LSB after the MSB write #1063

Closed

Description

@q5438722

Summary

In rw = 3 (LSB then MSB) mode, Timer::write stores the first byte in cr_low and completes the count on the second byte, but it never clears cr_low. Every later byte is taken as an MSB combined with the stale LSB, so a guest that reloads the count without writing a new control word programs a wrong count. On the 8254, writes in this mode keep alternating LSB, MSB.

Repro

pit_lsb_msb_reprogram.txt

Add the attached pit_lsb_msb_reprogram.rs (.txt) to vm/devices/chipset/tests/ and run:

cargo test -p chipset --test pit_lsb_msb_reprogram

On counter 0, with VM time frozen:

  1. Control word 0x30: LSB/MSB, mode 0.
  2. Write count 0x00, 0x00 (65536).
  3. Without a new control word, write 0x10, 0x00 (16).
  4. Advance ~100 ticks and latch the count.

Expected

A count of 16 reaches terminal count after 17 ticks, and OUT goes high.

Actual

thread 'second_lsb_msb_pair_programs_the_count' panicked at vm/devices/chipset/tests/pit_lsb_msb_reprogram.rs:62:9:
mode 0 with count 16 did not reach terminal count after 100 ticks (latched count 0xff9d)

Both 0x10 and 0x00 were taken as MSBs, so the count ended up as 65536.

Root cause

pit/mod.rs:326 reads the buffered LSB with if let Some(low) = self.state.cr_low, which leaves it set. Only set_control clears it, so guests that write a control word before every reload never see the bug.

Impact

Guests that reload a count without a new control word get the wrong timer period or one-shot length, and so the wrong IRQ0 rate. Nothing crashes.

Suggested fix

--- a/vm/devices/chipset/src/pit/mod.rs
+++ b/vm/devices/chipset/src/pit/mod.rs
@@ -323,7 +323,7 @@ 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 {
+                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);

cr_low is already part of the saved state, so the saved-state format does not change.

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