You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
RTC alarms can fire hours late because the deadline calculation treats decoded wildcard bytes as numeric fields and lets a borrow wrap an eight-bit delta.
In vm/devices/chipset/src/cmos_rtc.rs, Rtc::calculate_alarm_duration first converts the alarm fields:
In BCD mode, 0xff decodes to 165 and no longer matches the wildcard comparison. A seconds borrow also turns delta_min from zero into 255; when the alarm minute equals the current minute, subsequent arithmetic leaves that wrapped delta in place.
Reproduction
Through RTC ports 0x70/0x71, select 24-hour BCD mode and set the calendar to 00:01:10. Program hour/minute alarm bytes 0xff, second alarm 0x30, then enable the alarm. It should match in 20 seconds, but the decoded wildcards schedule it far later.
Separately, at 10:20:30, program a fixed alarm for 10:20:10. It is scheduled 255 min 40 s ahead instead of the next daily match, 23 h 59 min 40 s ahead. The minutes-to-hours borrow has the corresponding defect.
Fix
fix.patch recognizes every raw 0xc0..=0xff alarm byte as “don't care” before decoding, then finds the first strictly future instant matching the constrained fields within one day. The bounded search replaces the field-by-field subtraction and fixes both scheduling defects. Noon/midnight hour encoding is a separate conversion fix.
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/cmos_rtc.rs b/vm/devices/chipset/src/cmos_rtc.rs
index ae091aec8..dd3ffa6a1 100644
--- a/vm/devices/chipset/src/cmos_rtc.rs+++ b/vm/devices/chipset/src/cmos_rtc.rs@@ -135,7 +135,9 @@ pub struct StatusRegD {
pub vrt: bool,
}
- pub const ALARM_WILDCARD: u8 = 0xFF;+ /// An alarm byte with these two bits set is "don't care": it matches every+ /// value of its field (0xFF is the usual one).+ pub const ALARM_DONT_CARE: u8 = 0xC0;
}
open_enum::open_enum! {
@@ -358,8 +360,9 @@ pub fn new(
///
/// The alarm works like an alarm clock. So if you set it for 5:02:03, it
/// will go off every day at 5:02:03. But if any of the time elements are
- /// 0xFF, that acts as a wildcard. So 5:FF:03 would go off at 5:00:03 and- /// 5:01:03 and 5:02:03, etc. An alarm set for FF:FF:FF goes off every+ /// "don't care" (the two high bits set, 0xC0-0xFF, e.g. 0xFF), that acts as+ /// a wildcard, in every register format. So 5:FF:03 would go off at 5:00:03+ /// and 5:01:03 and 5:02:03, etc. An alarm set for FF:FF:FF goes off every
/// second.
///
/// The problem is, what happens if, when we compute when the timer should
@@ -375,14 +378,14 @@ pub fn new(
/// 5:FF:03? In this case, we need to go off again in a minute. For 5:02:FF,
/// it has to be in a second.
///
- /// Handling all of this is what the `go_around_again` variable is for.- ///- /// It will be set to the appropriate amount of time we need to wait if, by- /// calculation, the alarm time would be immediate, as just described (which- /// is the amount for the smallest unit of time which has a wildcard (24- /// hours if none)).+ /// So the result is the delay to the next instant strictly after now, within+ /// a day, at which every field that is not "don't care" matches: when the+ /// alarm matches now, that is the smallest unit of time which has a wildcard+ /// (24 hours if none), unless that unit carries into a field that must+ /// match (5:02:FF at 5:02:59 matches next tomorrow at 5:02:00). Without any+ /// match within a day (a field out of its range), it is a day.
fn calculate_alarm_duration(&self) -> Duration {
- use self::spec::ALARM_WILDCARD;+ use self::spec::ALARM_DONT_CARE;
let status_b = StatusRegB::from(self.state.cmos[CmosReg::STATUS_B]);
let (now_hour, now_min, now_sec) = canonical_hms(
@@ -391,79 +394,39 @@ fn calculate_alarm_duration(&self) -> Duration {
self.state.cmos[CmosReg::MINUTE],
self.state.cmos[CmosReg::SECOND],
);
- let (alarm_hour, alarm_min, alarm_sec) = canonical_hms(- status_b,- self.state.cmos[CmosReg::HOUR_ALARM],- self.state.cmos[CmosReg::MINUTE_ALARM],- self.state.cmos[CmosReg::SECOND_ALARM],- );-- let mut delta_hour: u8 = 0;- let mut delta_min: u8 = 0;- let mut delta_sec: u8 = 0;-- if alarm_sec == ALARM_WILDCARD {- delta_sec = 0;- } else {- delta_sec = delta_sec.wrapping_add(alarm_sec.wrapping_sub(now_sec));- if alarm_sec < now_sec {- delta_sec = delta_sec.wrapping_add(60);- delta_min = delta_min.wrapping_sub(1);- }- }-- if alarm_min == ALARM_WILDCARD {- delta_min = 0;- } else {- delta_min = delta_min.wrapping_add(alarm_min.wrapping_sub(now_min));- if alarm_min < now_min {- delta_min = delta_min.wrapping_add(60);- delta_hour = delta_hour.wrapping_sub(1);- }- }-- if alarm_hour == ALARM_WILDCARD {- delta_hour = 0;- } else {- delta_hour = delta_hour.wrapping_add(alarm_hour.wrapping_sub(now_hour));- if alarm_hour < now_hour {- delta_hour = delta_hour.wrapping_add(24);- }- }-- const DURATION_SEC: Duration = Duration::from_secs(1);- const DURATION_MIN: Duration = Duration::from_secs(60);- const DURATION_HOUR: Duration = Duration::from_secs(60 * 60);- const DURATION_DAY: Duration = Duration::from_secs(60 * 60 * 24);-- let go_around_again = match (alarm_sec, alarm_min, alarm_hour) {- (ALARM_WILDCARD, _, _) => DURATION_SEC,- (_, ALARM_WILDCARD, _) => DURATION_MIN,- (_, _, ALARM_WILDCARD) => DURATION_HOUR,- // if no wildcards were specified, then the alarm is set to fire in a day- _ => DURATION_DAY,- };-- let alarm_duration = {- DURATION_HOUR * delta_hour as u32- + DURATION_MIN * delta_min as u32- + DURATION_SEC * delta_sec as u32- };+ let raw_hour = self.state.cmos[CmosReg::HOUR_ALARM];+ let raw_min = self.state.cmos[CmosReg::MINUTE_ALARM];+ let raw_sec = self.state.cmos[CmosReg::SECOND_ALARM];+ let (alarm_hour, alarm_min, alarm_sec) =+ canonical_hms(status_b, raw_hour, raw_min, raw_sec);+ // An alarm byte with its two high bits set is "don't care" (MC146818):+ // it matches every value in every register format. Recognize it on the+ // raw byte, before the BCD and 12-hour decoding changes it.+ let any_hour = raw_hour & ALARM_DONT_CARE == ALARM_DONT_CARE;+ let any_min = raw_min & ALARM_DONT_CARE == ALARM_DONT_CARE;+ let any_sec = raw_sec & ALARM_DONT_CARE == ALARM_DONT_CARE;++ // The next instant within a day, after now, at which every alarm field+ // that is not "don't care" equals the time's field; without any match+ // within the day, a day.+ let now = now_hour as u32 * 3600 + now_min as u32 * 60 + now_sec as u32;+ let delay = (1..86_400)+ .find(|delay| {+ let t = now + delay;+ (any_sec || t % 60 == alarm_sec as u32)+ && (any_min || t / 60 % 60 == alarm_min as u32)+ && (any_hour || t / 3600 % 24 == alarm_hour as u32)+ })+ .unwrap_or(86_400);
tracing::debug!(
now = ?(now_hour, now_min, now_sec),
alarm = ?(alarm_hour, alarm_min, alarm_sec),
- delta = ?(delta_hour, delta_min, delta_sec),- ?go_around_again,- ?alarm_duration,+ ?delay,
"setting alarm"
);
- if alarm_duration.is_zero() {- go_around_again- } else {- alarm_duration- }+ Duration::from_secs(delay.into())
}
fn set_alarm_timer(&mut self, now: VmTime) {
@@ -1564,4 +1527,202 @@ fn hms_to_duration(h: u8, m: u8, s: u8) -> Duration {
// TODO: test some more alarm scenarios
}
++ /// Sets the RTC's mock UTC clock to `ms` milliseconds after the Unix+ /// epoch.+ fn set_clock_ms(time: &MockLocalClockAccessor, ms: i64) {+ let now = time.get_time().as_millis_since_unix_epoch();+ if ms >= now {+ time.tick(Duration::from_millis((ms - now) as u64));+ } else {+ time.tick_backwards(Duration::from_millis((now - ms) as u64));+ }+ }++ /// Steps the stopped VM time and the RTC's clock by `d` together, as a+ /// running VM would, then polls the RTC.+ fn run_rtc(+ pool: &mut pal_async::DefaultPool,+ keeper: &mut vmcore::vmtime::VmTimeKeeper,+ time: &MockLocalClockAccessor,+ rtc: &mut Rtc,+ d: Duration,+ ) {+ pool.run_until(keeper.advance(d));+ time.tick(d);+ rtc.poll_device(&mut std::task::Context::from_waker(std::task::Waker::noop()));+ }++ /// The seconds from VM time 0 at which the alarm is armed to fire.+ fn alarm_due_secs(rtc: &Rtc) -> u64 {+ rtc.vmtime_alarm.get_timeout().unwrap().as_100ns() / 10_000_000+ }++ /// Regression test of BUG-08: an alarm byte with its two high bits set+ /// (0xc0..=0xff, "don't care" in the MC146818) matches every value in+ /// every register format. Before the fix `calculate_alarm_duration`+ /// compared the decoded fields with 0xff, so in BCD mode (0xff decodes to+ /// 165) and for the 12-hour hour (97 in BCD, 139 in binary) the wildcard+ /// was a value: an alarm "every minute at :30" set at 00:01:10 was armed+ /// 165 h 164 min 20 s ahead. Now it is due in 20 s and fires, "every+ /// second" in 1 s, in 24- and 12-hour BCD and binary mode, for the+ /// don't-care bytes 0xc0, 0xe5 and 0xff.+ #[test]+ fn rtc_alarm_wildcard_matches_in_every_format() {+ for status_b in [0x22u8, 0x20, 0x24, 0x26] {+ for dont_care in [0xffu8, 0xc0, 0xe5] {+ let binary = status_b & 0x04 != 0;+ let at_30 = if binary { 30 } else { 0x30 };+ for (second_alarm, delay) in [(at_30, 20u64), (dont_care, 1)] {+ let (mut pool, mut keeper, time, mut rtc) = new_test_rtc();+ set_clock_ms(&time, 70_000); // 00:01:10+ set_cmos_data(&mut rtc, CmosReg::STATUS_B, status_b & !0x20);+ set_cmos_data(&mut rtc, CmosReg::HOUR_ALARM, dont_care);+ set_cmos_data(&mut rtc, CmosReg::MINUTE_ALARM, dont_care);+ set_cmos_data(&mut rtc, CmosReg::SECOND_ALARM, second_alarm);+ set_cmos_data(&mut rtc, CmosReg::STATUS_B, status_b);+ let case = format!(+ "status B {status_b:#x}, alarm {dont_care:#x}:{dont_care:#x}:{second_alarm:#x}"+ );+ assert_eq!(alarm_due_secs(&rtc), delay, "{case}");+ // The deadline passes 1 ms later (a timer fires strictly+ // after its deadline).+ let d = Duration::from_millis(delay * 1000 + 1);+ run_rtc(&mut pool, &mut keeper, &time, &mut rtc, d);+ let status_c = get_cmos_data(&mut rtc, CmosReg::STATUS_C);+ assert_eq!(status_c & 0x20, 0x20, "{case}");+ }+ }+ }+ }++ /// Regression test of BUG-09: a borrow from the seconds or the minutes+ /// onto an equal field is carried. Before the fix the field-by-field u8+ /// subtraction wrapped the minutes' (or hours') delta to 255: at 10:20:30+ /// an alarm for 10:20:10 was armed 255 min 40 s ahead and one for 10:19:40+ /// 255 h 59 min 10 s ahead. Now they are the next match, 23 h 59 min 40 s+ /// and 23 h 59 min 10 s ahead; the cases without such a borrow keep their+ /// delays.+ #[test]+ fn rtc_alarm_borrow_onto_an_equal_field_is_carried() {+ let s = |h: u64, m: u64, sec: u64| h * 3600 + m * 60 + sec;+ for (alarm, expected) in [+ ((0x10u8, 0x20u8, 0x10u8), s(23, 59, 40)),+ ((0x10, 0x19, 0x40), s(23, 59, 10)),+ ((0x10, 0x21, 0x10), s(0, 0, 40)),+ ((0x11, 0x19, 0x40), s(0, 59, 10)),+ ((0x10, 0x20, 0x30), s(24, 0, 0)),+ ] {+ let (_, _, time, mut rtc) = new_test_rtc();+ set_clock_ms(&time, s(10, 20, 30) as i64 * 1000); // 10:20:30, 24-hour BCD+ set_cmos_data(&mut rtc, CmosReg::HOUR_ALARM, alarm.0);+ set_cmos_data(&mut rtc, CmosReg::MINUTE_ALARM, alarm.1);+ set_cmos_data(&mut rtc, CmosReg::SECOND_ALARM, alarm.2);+ set_cmos_data(&mut rtc, CmosReg::STATUS_B, 0x22);+ assert_eq!(alarm_due_secs(&rtc), expected, "alarm {alarm:x?}");+ }+ }++ /// The alarm's reference model (MC146818), written independently of the+ /// implementation: an alarm field that is not "don't care" (`None`)+ /// matches when it equals the time's field; the delay is that of the first+ /// instant strictly after `now` (seconds since midnight), within a day, at+ /// which every field matches (a second-by-second scan), or a day when none+ /// does. Returns that delay for an alarm `[hour, minute, second]`.+ fn alarm_reference(now: u64) -> impl Fn([Option<u64>; 3]) -> u64 {+ // The index of the fields of `f` that `mask` selects (bit 0 the hour,+ // bit 1 the minute, bit 2 the second; 0 for the others).+ let index = |mask: usize, f: [u64; 3]| {+ let [h, m, s] = [0, 1, 2].map(|i| if mask & (1 << i) != 0 { f[i] } else { 0 });+ mask * 86_400 + (h * 3600 + m * 60 + s) as usize+ };+ let mut first = vec![0; 8 * 86_400];+ for e in 1..=86_400u64 {+ let t = (now + e) % 86_400;+ let f = [t / 3600, t / 60 % 60, t % 60];+ for mask in 0..8 {+ let i = index(mask, f);+ if first[i] == 0 {+ first[i] = e;+ }+ }+ }+ move |alarm| {+ let mask = (0..3).filter(|&i| alarm[i].is_some()).map(|i| 1 << i).sum();+ match first[index(mask, alarm.map(|v| v.unwrap_or(0)))] {+ 0 => 86_400,+ e => e,+ }+ }+ }++ /// BUG-08 and BUG-09 against the reference model: in all four formats+ /// (24- and 12-hour, BCD and binary), at three times of day (10:20:30,+ /// 12:00:00, 23:59:59), alarms whose hour is now's, the next, the previous+ /// or don't care, and whose minute and second are each 0, now's, one+ /// before or after now's (the borrows), or don't care (1,200 alarms):+ /// `calculate_alarm_duration` is the reference's delay. The alarm bytes+ /// are the fields in status B's format (hours as the RTC's calendar+ /// encodes them); the don't-care bytes are 0xff, 0xc0 and 0xe5 in turn.+ #[test]+ fn rtc_alarm_matches_the_reference_model() {+ let mut checked = 0;+ for now in [10 * 3600 + 20 * 60 + 30u64, 12 * 3600, 86_399] {+ let reference = alarm_reference(now);+ let (h, m, sec) = (now / 3600, now / 60 % 60, now % 60);+ let hours = [Some(h), Some((h + 1) % 24), Some((h + 23) % 24), None];+ let around = |v: u64| {+ [+ Some(0),+ Some(v),+ Some((v + 59) % 60),+ Some((v + 1) % 60),+ None,+ ]+ };+ for status_b in [0x02u8, 0x06, 0x00, 0x04] {+ let binary = status_b & 0x04 != 0;+ let h24 = status_b & 0x02 != 0;+ let enc = |v: u64| if binary { v as u8 } else { to_bcd(v as u8) };+ let hour_byte = |h: u64| {+ if h24 {+ enc(h)+ } else if h > 12 {+ enc(h - 12) | 0x80+ } else {+ enc(h)+ }+ };+ let (_, _, time, mut rtc) = new_test_rtc();+ set_clock_ms(&time, now as i64 * 1000 + 250);+ rtc.state.cmos[CmosReg::STATUS_B] = status_b;+ rtc.sync_clock_to_cmos();+ let dont_care = [0xffu8, 0xc0, 0xe5];+ let mut i = 0;+ for alarm_h in hours {+ for alarm_m in around(m) {+ for alarm_s in around(sec) {+ let byte = |v: Option<u64>, encode: &dyn Fn(u64) -> u8| {+ v.map_or(dont_care[i % 3], encode)+ };+ let hb = byte(alarm_h, &hour_byte);+ let mb = byte(alarm_m, &enc);+ let sb = byte(alarm_s, &enc);+ rtc.state.cmos[CmosReg::HOUR_ALARM] = hb;+ rtc.state.cmos[CmosReg::MINUTE_ALARM] = mb;+ rtc.state.cmos[CmosReg::SECOND_ALARM] = sb;+ assert_eq!(+ rtc.calculate_alarm_duration(),+ Duration::from_secs(reference([alarm_h, alarm_m, alarm_s])),+ "status B {status_b:#x} now {now} alarm {hb:#x}:{mb:#x}:{sb:#x}"+ );+ i += 1;+ checked += 1;+ }+ }+ }+ }+ }+ assert_eq!(checked, 3 * 4 * 4 * 5 * 5);+ }
}
Closing: this is an OpenVMM bug outside NVX, and upstream fixed it in two pull requests: microsoft/openvmm#4963, chipset: recognize all RTC alarm wildcard encodings, merged on 2026-11-06, decodes the wildcards, and microsoft/openvmm#4971, rtc: Fix next-match alarm scheduling, merged on 2026-11-09, replaces the wrapping field borrows. NVX's OpenVMM pin, 58d3c3b1d, includes microsoft/openvmm#4963; microsoft/openvmm#4971 reaches NVX with the next rebase of the microVM chain onto upstream main.
Activity
tangruize commentedon Nov 1, 2026
Proposed patch
Patch against OpenVMM
998b9f2402050cd16d1faa897bc831ef1434be48. Save the contents below asfix.patchand rungit apply fix.patch.fix.patchppenna commentedon Nov 11, 2026
Closing: this is an OpenVMM bug outside NVX, and upstream fixed it in two pull requests: microsoft/openvmm#4963,
chipset: recognize all RTC alarm wildcard encodings, merged on 2026-11-06, decodes the wildcards, and microsoft/openvmm#4971,rtc: Fix next-match alarm scheduling, merged on 2026-11-09, replaces the wrapping field borrows. NVX's OpenVMM pin,58d3c3b1d, includes microsoft/openvmm#4963; microsoft/openvmm#4971 reaches NVX with the next rebase of the microVM chain onto upstreammain.