Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(vmm): add the CMOS RTC and its IRQ 8 alarm (#2808)

Vitusecd1bbd8fecf
diff --git a/docs/contributing/architecture/vmm/README.md b/docs/contributing/architecture/vmm/README.md
index 681e6ca87..cb0ba9e29 100644
--- a/docs/contributing/architecture/vmm/README.md
+++ b/docs/contributing/architecture/vmm/README.md
@@ -310,7 +310,7 @@ On x86_64 the layout uses the values most surveyed VMMs share.
| `0xE000_0000`–`0xF000_0000` | PCI ECAM, reserved for M9 | alioth |
| `0xFEC0_0000`, `0xFEE0_0000` | IOAPIC and local APIC, both in the kernel on KVM; WHP (M10) emulates only the local APIC | architectural |
| above RAM | hotplug memory (M7), then a 64-bit PCI BAR window (M9) | as on arm64 |
-| ports `0x3F8`, `0x70`–`0x71`, `0x60` and `0x64` | 8250 UART on GSI 4, CMOS RTC, i8042 | PC standard |
+| ports `0x3F8`, `0x70`–`0x71`, `0x60` and `0x64` | 8250 UART on GSI 4, CMOS RTC with its alarm on GSI 8, i8042 | PC standard |
x86_64 guests boot without ACPI or a device tree, so the command line announces
each virtio-mmio device (`virtio_mmio.device=4K@0xd0000000:5`), as libkrun does
@@ -586,7 +586,7 @@ from the new VMM.
| Network | virtio-net to gvproxy in the shim (a stream socket with 4-byte length prefixes on Linux, datagrams with the `VFKT` handshake on macOS), with 192.168.127.2/24 set by the agent | unchanged; no TSI | M2 |
| Console | virtio-console `hvc0` into `console.log`, truncated at each boot | unchanged; M1 first boots on the PL011 or 8250 | M1–M2 |
| Other devices | virtio-rng, and virtio-balloon with free page reporting (`libkrun/src/devices/src/virtio/balloon/device.rs:28-30`) | unchanged | M2 |
-| Wall clock | PL031 (arm64) or CMOS (x86_64) at boot; on macOS, resync over vsock datagram port 123 | the same at boot; M2 chooses the resync mechanism | M1–M2 |
+| Wall clock | PL031 (arm64) or kvm-clock (x86_64) at boot; on macOS, resync over vsock datagram port 123 | the same at boot, with the CMOS RTC registered as `rtc0` on x86_64; M2 chooses the resync mechanism | M1–M2 |
| End of the VM | the agent writes `exit.json`, syncs and calls `reboot(RESTART)`; libkrun then exits the process | the same guest steps; `run()` returns `GuestReset` | M2 |
| Start failure | libkrun reports every error as `-EINVAL`, and the adapter probes the hypervisor for the cause | typed errors | M2 |
diff --git a/src/boxlite/src/litebox/init/tasks/guest_init.rs b/src/boxlite/src/litebox/init/tasks/guest_init.rs
index c54831205..a05996a29 100644
--- a/src/boxlite/src/litebox/init/tasks/guest_init.rs
+++ b/src/boxlite/src/litebox/init/tasks/guest_init.rs
@@ -332,6 +332,13 @@ mod tests {
}))
}
+ async fn sync_clock(
+ &self,
+ _: tonic::Request<boxlite_shared::SyncClockRequest>,
+ ) -> Result<tonic::Response<boxlite_shared::SyncClockResponse>, tonic::Status> {
+ Err(tonic::Status::unimplemented("not used by these tests"))
+ }
+
async fn shutdown(
&self,
_: tonic::Request<boxlite_shared::ShutdownRequest>,
diff --git a/src/vmm/README.md b/src/vmm/README.md
index a3e3126e1..0d9f34c37 100644
--- a/src/vmm/README.md
+++ b/src/vmm/README.md
@@ -12,7 +12,7 @@ lifecycle API, memory layout, buses, interrupts, and threads.
and `Result` are public, as are `BusKind` and `Conflict`, which `Error::ChipsetConflicts`
carries; M2's engine adapter consumes that API and inspects the error's host
cause.
-`Vm::new(config, console)` adds COM1, the i8042 and virtio-balloon; COM1
+`Vm::new(config, console)` adds COM1, the CMOS RTC, the i8042 and virtio-balloon; COM1
output reaches `console` through the
[console queue](#legacy-devices-and-the-console).
@@ -39,7 +39,7 @@ boxlite-vmm
| `bus` | `Bus`, `BusRange` and `BusDevice`, and `Buses::dispatch`, which serves the MMIO and port exits of a vCPU |
| `virtio` | The virtio common infrastructure: the synchronous device contract (`VirtioDevice`, `DeviceSpec`, `DeviceEvent`, `ActivationContext`, `EventRegistrar`, `Waker`, `WorkerControl`), the `VirtQueues` facade (dense preparation and validation, EVENT_IDX, exactly-once deferred completion, notification drain, the stored guest-memory view and negotiated indirect flag, and `save`/`restore` stubs that report snapshots unsupported until M8), the 4 KiB virtio-mmio transport (register file, feature negotiation, queue configuration and activation, Status=0 reset, post-activation queue-write rejection), `mmio::add_device`, which attaches any device through that transport, the MMIO interrupt handle, the default snapshot methods, and the virtio workers (`VirtioWorkers` over a `WorkerRuntime`; `SharedRuntime` runs every device's events on one thread) |
| `irq` | `IrqChip`, the host interrupt controller as devices see it, and `IrqLine`, one device line; HVF and KVM provide the controller, WHP (M10) only local APICs |
-| `devices` | `devices::add_all`, the one composition helper (add a device type as one `add_slot_device` line), the console queue, internal virtio-net device, output-only virtio console device, and on x86_64 the 8250 UART at COM1 and the i8042 reset, with `add_legacy_devices` |
+| `devices` | `devices::add_all`, the one composition helper (add a device type as one `add_slot_device` line), the console queue, internal virtio-net device, output-only virtio console device, and on x86_64 the 8250 UART at COM1, the CMOS RTC and the i8042 reset, with `add_legacy_devices` |
| `devices::balloon` | Reporting-only `VirtioBalloon`: configuration, negotiation, whole-chain prevalidation and a `ReclaimPolicy` chosen when the device is constructed; `devices::add_all` composes it after the disks, so it never renumbers them |
| `virtio::worker` | One lazy shared poller/thread, coalesced generation-bound queue kicks, backend readiness, stop barriers and VM shutdown |
| `events` | `Event`, which ends the VM, `EventSender`, which also latches the stop, and `EventLoop`, the poller that waits for the first event |
@@ -320,10 +320,11 @@ make test:integration:vmm:linux
Each builds a KVM `Vm` with `prepare` on the
[legacy devices](#legacy-devices-and-the-console) and runs it with `Vm::run`,
-with 256 MiB of RAM unless stated. The host VM is KVM behind a test wrapper
-that counts the edges devices raise on GSI 4 and can drop every interrupt. A
-watchdog stops a boot at its timeout, 30 seconds unless stated, so a failed
-boot reports the serial log so far.
+with 256 MiB of RAM unless stated. The CMOS RTC starts at
+`2026-01-02T03:04:05Z`. The host VM is KVM behind a test wrapper that counts
+the edges devices raise on GSI 4 and can drop every interrupt. A watchdog
+stops a boot at its timeout, 30 seconds unless stated, so a failed boot
+reports the serial log so far.
- With `earlycon=uart8250,io,0x3f8 keep_bootcon panic=-1 reboot=k`, one
vCPU and no initramfs, the log must show the kernel version, the exact
@@ -345,9 +346,16 @@ boot reports the serial log so far.
then reports CPU i, the log must show `exitcode=0x00000f00`.
- With `console=ttyS0 panic=-1 reboot=k`, one vCPU and an `/init` that
prints a line, waits for the tty to send it and restarts the machine, the
- log must show the 16550A on IRQ 4, that line and
- `reboot: Restarting system`, in that order, and GSI 4 must have been
- raised.
+ log must show the 16550A on IRQ 4, `rtc_cmos rtc_cmos: registered as
+ rtc0`, that line and `reboot: Restarting system`, in that order, and must
+ not show `setting system clock`: kvm-clock keeps the boot time. GSI 4 must
+ have been raised.
+- With `console=ttyS0 panic=-1 reboot=k`, one vCPU and an `/init` that
+ mounts devtmpfs, turns on update interrupts on `/dev/rtc0` with
+ `RTC_UIE_ON`, as `hwclock` does, and waits up to 2 s for one, the log must
+ show `rtc0` registered, the line `/init` prints once one arrives, and
+ `reboot: Restarting system`, with no panic. Linux serves update
+ interrupts with the CMOS alarm, so the line proves the alarm raised IRQ 8.
- The same boot with a console sink that takes nothing until the run has
ended, and a 4 KiB queue, must still end with `GuestReset`. The queue drops
the oldest bytes and counts them; the sink then gets the batch the worker
@@ -794,14 +802,25 @@ each one, which opens the image and attaches it in the slot `add_slot_device`
took, and then announces that slot on the kernel command line.
- **Slots.** `virtio::mmio::Slots` hands out `(window, line)` pairs in
- order: window `i` is `0xd000_0000 + i * 4 KiB`, line `i` is GSI `5 + i`,
- 19 slots in all (the legacy range above COM1 and below the MSI space, as
- Firecracker and libkrun allocate it). `Slot::cmdline_arg` renders the
+ order: window `i` is `0xd000_0000 + i * 4 KiB`, interrupt lines are GSI 5–7 and
+ 9–23, 18 slots in all. GSI 8 stays reserved for the CMOS alarm, while MMIO
+ windows and device order remain consecutive. `Slot::cmdline_arg` renders the
`virtio_mmio.device=4K@<base>:<gsi>` argument the kernel probes, and
`announce` puts one per slot at the front under the command-line budget, so the
chipset claim and the kernel's view come from the same value. Disks take
slots in `VmConfig::disks` order, so disk 0 is `/dev/vda`, disk 1 is
- `/dev/vdb`, and so on.
+ `/dev/vdb`, and so on. Production uses up to 13 slots with 8 disks, the
+ balloon, and optional aggregate filesystem, vsock, net and console devices.
+ The [M2 device plan](../../docs/contributing/architecture/vmm/README.md#devices-by-milestone)
+ adds rng for 14 devices within the 18-slot budget. IRQ 8 follows the
+ pinned Linux [RTC platform declaration](https://github.com/gregkh/linux/blob/v6.12.110/arch/x86/kernel/rtc.c#L114-L152),
+ and the upper GSI bound follows the 24-pin IOAPIC described in the
+ [Linux KVM IOAPIC source](https://github.com/gregkh/linux/blob/v6.12.110/arch/x86/include/uapi/asm/kvm.h#L77-L99).
+ The VM composition test uses the production attach and boot-loading paths
+ with eight distinct raw disks, with and without aggregate fs. It reads the
+ command line from guest RAM and checks consecutive MMIO windows, GSIs that
+ skip 8, disk capacities in configuration order, balloon/fs device IDs and
+ the real CMOS ports on a mock host VM; it does not boot a Linux guest.
- **Configuration.** `DiskConfig { block_id, path, format: Raw | Qcow2, read_only }`;
the format is stated, never probed from the file. A qcow2 image opens the
backing chain its header names. At most 8 disks; `blk::add_disk` fails with
@@ -1134,6 +1153,7 @@ windows, then adds the legacy devices:
| Ports | Device | Behavior |
| --- | --- | --- |
| `0x3F8`–`0x3FF` | `com1`, vm-superio's 16550A | Output goes to the console queue; a pending, enabled THRE or RDA raises an edge on GSI 4; no input yet |
+| `0x70`–`0x71` | `cmos` | See [CMOS RTC](#cmos-rtc) |
| `0x60`, `0x64` | `i8042`, vm-superio's controller | Reads 0; the first `0xFE` at `0x64` sends `GuestReset` |
- vm-superio must be 0.8.2 or later. It raises THRE on every IER write, so
@@ -1153,6 +1173,23 @@ windows, then adds the legacy devices:
- A failed interrupt sends `DeviceFailed`, once.
- The guest kernel has no i8042 driver, so the reset is all the device does.
+## CMOS RTC
+
+On x86_64, `CmosRtc` serves ports `0x70` (register select) and `0x71` (data).
+Linux exposes the clock as `/dev/rtc0` and takes its boot time from kvm-clock
+because `boot/kernel.config` disables `RTC_HCTOSYS`.
+
+- RTC time follows the host wall clock plus a guest-set offset. SET or a
+ divider reset freezes it. On release, the clock resumes half a second into
+ the written second, matching Linux's RTC write timing. Time registers read
+ in 24-hour BCD or binary.
+- Alarms match hours, minutes, and seconds in guest RTC time. The RTC latches
+ due matches in AF before rescheduling, even with AIE off. Enabling AIE with
+ AF set asserts IRQ 8. Reading register C clears the flags and rearms the
+ alarm. Clearing AIE lowers IRQ 8 and keeps AF.
+- Linux uses the alarm to emulate update interrupts for `hwclock`. A failed
+ IRQ update ends the VM with `DeviceFailed`.
+
## Build
`make vmm:boot` builds the pinned x86_64 ELF kernel (`vmlinux`) inside a pinned
@@ -1186,9 +1223,9 @@ port bus at its register offset, and an `IrqLine` sets GSI 4 and 5 through
`KVM_IRQ_LINE`, skipping a repeated level. Another flat guest reads a claimed
and an unclaimed port of a built chipset, and the device's line, armed by the
build, reaches KVM. A third runs on the [legacy devices](#legacy-devices-and-the-console):
-it prints `OK` on COM1, reads an unclaimed port and unmapped MMIO as all
-ones, and runs no instruction after its i8042 reset. CI runs the same tests
-through `make coverage:vmm:kvm`. When a change matches its `vmm` path filter,
+it prints `OK` on COM1, reads the CMOS seconds from a fixed clock, reads an
+unclaimed port and unmapped MMIO as all ones, and runs no instruction after
+its i8042 reset. CI runs the same tests through `make coverage:vmm:kvm`. When a change matches its `vmm` path filter,
and weekly, it also runs the [boot tests](#boot-tests) on the kernel it builds
with `make vmm:boot:host`, through `make coverage:vmm:boot`, which needs
`VMM_KERNEL` like `make test:integration:vmm:linux`. The Linux integration test
diff --git a/src/vmm/boot/kernel.config b/src/vmm/boot/kernel.config
index cc0098c46..253b5c5d7 100644
--- a/src/vmm/boot/kernel.config
+++ b/src/vmm/boot/kernel.config
@@ -29,7 +29,8 @@ CONFIG_SERIAL_8250_NR_UARTS=1
CONFIG_SERIAL_8250_RUNTIME_UARTS=1
CONFIG_RTC_CLASS=y
CONFIG_RTC_DRV_CMOS=y
-CONFIG_RTC_HCTOSYS=y
+CONFIG_RTC_INTF_DEV=y
+# CONFIG_RTC_HCTOSYS is not set
CONFIG_LOCALVERSION="-boxlite-m1"
# CONFIG_LOCALVERSION_AUTO is not set
# CONFIG_ACPI is not set
diff --git a/src/vmm/src/devices/cmos.rs b/src/vmm/src/devices/cmos.rs
new file mode 100644
index 000000000..84fffe950
--- /dev/null
+++ b/src/vmm/src/devices/cmos.rs
@@ -0,0 +1,573 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+//! The CMOS real-time clock (RTC) of a PC, at ports 0x70 and 0x71.
+//!
+//! The guest writes a register number to port 0x70, then reads or writes that
+//! register through port 0x71. Linux registers it as `rtc0`, but takes its
+//! boot time from kvm-clock: the guest kernel leaves `RTC_HCTOSYS` off, so
+//! this clock never overrides it.
+//!
+//! The time is an injected [`Clock`] plus an offset, so a time the guest
+//! writes stays set and keeps running. While the guest sets the time, the
+//! clock stops and the registers hold what it wrote; when the clock restarts,
+//! it starts half a second into the written second, because Linux writes the
+//! time half a second early (`set_offset_nsec` in `rtc-cmos.c`).
+//!
+//! Alarm matches latch AF in register C. IRQF and GSI 8 follow AF and AIE.
+//! Further matches coalesce until the guest reads C.
+//! Linux emulates update interrupts with that alarm, and `hwclock` waits
+//! on them. Not modelled: 12-hour mode, day and month alarms, and
+//! periodic and update-ended interrupts.
+
+use std::{
+ sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError},
+ thread::{self, JoinHandle},
+ time::{Duration, SystemTime, UNIX_EPOCH},
+};
+
+use crate::{
+ bus::{BusDevice, UNCLAIMED_READ},
+ error::Error,
+ events::{Event, EventSender},
+ irq::IrqLine,
+};
+
+/// The clock the RTC follows, in nanoseconds since the Unix epoch.
+pub(crate) type Clock = Box<dyn Fn() -> i64 + Send>;
+
+/// The host wall clock, in nanoseconds since the Unix epoch.
+pub(crate) fn host_clock() -> i64 {
+ match SystemTime::now().duration_since(UNIX_EPOCH) {
+ Ok(after) => i64::try_from(after.as_nanos()).unwrap_or(i64::MAX),
+ Err(before) => i64::try_from(before.duration().as_nanos()).map_or(i64::MIN, |ns| -ns),
+ }
+}
+
+// The registers the guest selects at port 0x70: the time, then the four
+// status registers.
+const SECONDS: usize = 0x00;
+const MINUTES: usize = 0x02;
+const HOURS: usize = 0x04;
+const DAY_OF_WEEK: usize = 0x06;
+const DAY_OF_MONTH: usize = 0x07;
+const MONTH: usize = 0x08;
+const YEAR: usize = 0x09;
+const STATUS_A: usize = 0x0a;
+const STATUS_B: usize = 0x0b;
+const STATUS_C: usize = 0x0c;
+const STATUS_D: usize = 0x0d;
+/// The century byte PC firmware uses; Linux reads it only through ACPI.
+const CENTURY: usize = 0x32;
+const TIME_REGISTERS: [usize; 8] = [
+ SECONDS,
+ MINUTES,
+ HOURS,
+ DAY_OF_WEEK,
+ DAY_OF_MONTH,
+ MONTH,
+ YEAR,
+ CENTURY,
+];
+
+/// Status A: the time is updating, which this clock never reports.
+const UPDATE_IN_PROGRESS: u8 = 0x80;
+/// Status A: the divider bits. Any value above `DIVIDER_32KHZ` holds the
+/// divider in reset, which stops the clock.
+const DIVIDER_BITS: u8 = 0x70;
+/// Status A: the divider counts a 32.768 kHz crystal, so the clock runs.
+const DIVIDER_32KHZ: u8 = 0x20;
+/// Status A at power-on: the 32.768 kHz divider and a 1024 Hz periodic rate.
+const STATUS_A_AT_POWER_ON: u8 = 0x26;
+/// Status B: set mode stops the clock so the guest can write the time.
+const SET_MODE: u8 = 0x80;
+/// Status B: the time registers hold plain numbers instead of BCD.
+const BINARY_MODE: u8 = 0x04;
+/// Status B: hours count 0 to 23, the only mode modelled.
+const HOURS_24_MODE: u8 = 0x02;
+/// Status D: the RAM and the time are valid.
+const TIME_VALID: u8 = 0x80;
+// The alarm registers, each matched against the time register before it.
+const SECONDS_ALARM: usize = 0x01;
+const MINUTES_ALARM: usize = 0x03;
+const HOURS_ALARM: usize = 0x05;
+/// An alarm byte at or above this matches any value ("don't care").
+const ALARM_ANY: u8 = 0xc0;
+/// Status B: an alarm match raises IRQ 8.
+const ALARM_INTERRUPT_ENABLE: u8 = 0x20;
+/// Status C: an enabled interrupt is pending, here always the alarm.
+const INTERRUPT_REQUEST: u8 = 0x80;
+/// Status C: the time matched the alarm.
+const ALARM_FLAG: u8 = 0x20;
+
+const NANOS_PER_SECOND: i64 = 1_000_000_000;
+const SECONDS_PER_DAY: i64 = 86_400;
+/// Resample an armed alarm within one RTC tick after the host clock jumps.
+const ALARM_RECHECK: Duration = Duration::from_secs(1);
+/// The Gregorian calendar repeats every 400 years, an era of this many days.
+const DAYS_PER_ERA: i64 = 146_097;
+/// The date helpers count years from March, so leap days fall at a year's
+/// end; this many days separate 0000-03-01 from 1970-01-01.
+const DAYS_FROM_0000_03_01_TO_1970: i64 = 719_468;
+
+/// The CMOS RTC and its 128 bytes of CMOS RAM.
+pub(crate) struct CmosRtc {
+ /// The register the next data-port access selects.
+ selected: usize,
+ /// The status registers, NVRAM, and the time while the clock is stopped.
+ registers: [u8; 128],
+ /// Whether the guest wrote the century byte, which then sets the century.
+ century_written: bool,
+ /// The alarm the worker raises, and register C's flags.
+ alarm: Arc<Alarm>,
+ /// The thread that raises the alarm; `drop` stops and joins it.
+ worker: Option<JoinHandle<()>>,
+}
+
+impl CmosRtc {
+ /// An RTC on `clock` that drives `irq`. The worker starts on the first
+ /// alarm configuration write, after the chipset has been built.
+ pub(crate) fn new(clock: Clock, irq: IrqLine, event_sender: EventSender) -> Self {
+ let mut registers = [0; 128];
+ registers[STATUS_A] = STATUS_A_AT_POWER_ON;
+ registers[STATUS_B] = HOURS_24_MODE;
+ registers[STATUS_D] = TIME_VALID;
+ let armed = Armed::after(
+ AlarmFields {
+ second: Some(0),
+ minute: Some(0),
+ hour: Some(0),
+ },
+ clock().div_euclid(NANOS_PER_SECOND),
+ );
+ Self {
+ selected: 0,
+ registers,
+ century_written: false,
+ alarm: Arc::new(Alarm {
+ state: Mutex::new(AlarmState {
+ clock,
+ offset_from_clock: 0,
+ irq,
+ event_sender,
+ armed: Some(armed),
+ matched: false,
+ aie: false,
+ stopping: false,
+ }),
+ changed: Condvar::new(),
+ }),
+ worker: None,
+ }
+ }
+
+ /// Starts the alarm thread once; a failed start ends the VM.
+ fn start_worker(&mut self) {
+ if self.worker.is_some() {
+ return;
+ }
+ let alarm = Arc::clone(&self.alarm);
+ match thread::Builder::new()
+ .name("cmos-alarm".into())
+ .spawn(move || alarm.run())
+ {
+ Ok(worker) => self.worker = Some(worker),
+ Err(source) => self.alarm.state().fail(Error::SpawnRtcAlarm(source)),
+ }
+ }
+
+ /// Whether the time advances: set mode is off and the divider is not in reset.
+ fn clock_running(&self) -> bool {
+ self.registers[STATUS_B] & SET_MODE == 0
+ && self.registers[STATUS_A] & DIVIDER_BITS <= DIVIDER_32KHZ
+ }
+
+ fn read_register(&mut self, register: usize) -> u8 {
+ match register {
+ _ if TIME_REGISTERS.contains(&register) && self.clock_running() => {
+ self.time_register(register, self.alarm.state().guest_time_nanos())
+ }
+ STATUS_A => self.registers[STATUS_A] & !UPDATE_IN_PROGRESS,
+ // Reading register C clears it.
+ STATUS_C => {
+ let mut state = self.alarm.state();
+ let now = state.guest_time_nanos();
+ state.settle_match(now);
+ let flags = state.flags();
+ if state.matched {
+ state.matched = false;
+ state.armed = self.next_alarm(now);
+ state.update_irq();
+ }
+ drop(state);
+ self.alarm.changed.notify_one();
+ flags
+ }
+ _ => self.registers[register],
+ }
+ }
+
+ fn write_register(&mut self, register: usize, value: u8) {
+ if matches!(register, STATUS_C | STATUS_D) {
+ return;
+ }
+ if register > STATUS_B && register != CENTURY {
+ self.registers[register] = value;
+ return;
+ }
+
+ let mut state = self.alarm.state();
+ let host_now = (state.clock)();
+ let now = host_now.saturating_add(state.offset_from_clock);
+ state.settle_match(now);
+
+ let was_running = self.clock_running();
+ let previous = self.registers[register];
+ match register {
+ STATUS_A => self.registers[register] = value & !UPDATE_IN_PROGRESS,
+ STATUS_B => self.registers[register] = value | HOURS_24_MODE,
+ _ => {}
+ }
+ let running = self.clock_running();
+ let writing_time = TIME_REGISTERS.contains(&register);
+ if was_running && (writing_time || !running) {
+ for field in TIME_REGISTERS {
+ self.registers[field] = self.time_register(field, now);
+ }
+ }
+ if !matches!(register, STATUS_A | STATUS_B) {
+ self.registers[register] = value;
+ self.century_written |= register == CENTURY;
+ }
+
+ if running && (writing_time || !was_running) {
+ let fraction = if was_running {
+ now.rem_euclid(NANOS_PER_SECOND)
+ } else {
+ // Linux writes half a second before the new time is due.
+ NANOS_PER_SECOND / 2
+ };
+ if let Some(nanos) = self.registers_time_nanos(fraction) {
+ state.offset_from_clock = nanos.saturating_sub(host_now);
+ }
+ }
+ let reschedule = match register {
+ STATUS_A => was_running != running,
+ STATUS_B => was_running != running || (previous ^ value) & BINARY_MODE != 0,
+ _ => true,
+ };
+ if reschedule {
+ state.armed = self.next_alarm(host_now.saturating_add(state.offset_from_clock));
+ }
+ state.aie = self.registers[STATUS_B] & ALARM_INTERRUPT_ENABLE != 0;
+ state.update_irq();
+ let start_worker = state.armed.is_some() && !state.stopping;
+ drop(state);
+ if start_worker {
+ self.start_worker();
+ }
+ self.alarm.changed.notify_one();
+ }
+
+ /// The time in the registers, `fraction_nanos` into its second, or `None`
+ /// when a field is out of range.
+ fn registers_time_nanos(&self, fraction_nanos: i64) -> Option<i64> {
+ let field = |register: usize| self.decode(self.registers[register]);
+ let (second, minute, hour) = (field(SECONDS)?, field(MINUTES)?, field(HOURS)?);
+ let (day, month, year) = (field(DAY_OF_MONTH)?, field(MONTH)?, field(YEAR)?);
+ if second > 59
+ || minute > 59
+ || hour > 23
+ || !(1..=31).contains(&day)
+ || !(1..=12).contains(&month)
+ || year > 99
+ {
+ return None;
+ }
+ let century = if self.century_written {
+ field(CENTURY).filter(|century| *century <= 99)?
+ } else if year < 70 {
+ 20
+ } else {
+ 19
+ };
+ let days = days_from_civil(century * 100 + year, month, day);
+ let seconds = days * SECONDS_PER_DAY + hour * 3600 + minute * 60 + second;
+ seconds
+ .checked_mul(NANOS_PER_SECOND)?
+ .checked_add(fraction_nanos)
+ }
+
+ /// Time register `register` at guest time `nanos`, in the format status B selects.
+ fn time_register(&self, register: usize, nanos: i64) -> u8 {
+ let seconds = nanos.div_euclid(NANOS_PER_SECOND);
+ let days = seconds.div_euclid(SECONDS_PER_DAY);
+ let second_of_day = seconds.rem_euclid(SECONDS_PER_DAY);
+ let (year, month, day) = civil_from_days(days);
+ let value = match register {
+ SECONDS => second_of_day % 60,
+ MINUTES => second_of_day / 60 % 60,
+ HOURS => second_of_day / 3600,
+ // 1970-01-01 was a Thursday, and Sunday is 1.
+ DAY_OF_WEEK => (days + 4).rem_euclid(7) + 1,
+ DAY_OF_MONTH => day,
+ MONTH => month,
+ YEAR => year.rem_euclid(100),
+ _ => year.div_euclid(100).rem_euclid(100),
+ };
+ self.encode(value as u8)
+ }
+
+ fn in_binary_mode(&self) -> bool {
+ self.registers[STATUS_B] & BINARY_MODE != 0
+ }
+
+ fn encode(&self, value: u8) -> u8 {
+ if self.in_binary_mode() {
+ value
+ } else {
+ ((value / 10) << 4) | (value % 10)
+ }
+ }
+
+ /// A time register value, or `None` for a byte that is not BCD in BCD mode.
+ fn decode(&self, raw: u8) -> Option<i64> {
+ if self.in_binary_mode() {
+ return Some(raw.into());
+ }
+ let (tens, ones) = (raw >> 4, raw & 0x0f);
+ (tens <= 9 && ones <= 9).then(|| i64::from(tens * 10 + ones))
+ }
+
+ /// The next matching guest second while the clock runs and the alarm
+ /// fields are valid.
+ fn next_alarm(&self, now: i64) -> Option<Armed> {
+ if !self.clock_running() {
+ return None;
+ }
+ let field = |register: usize, limit: i64| match self.registers[register] {
+ raw if raw >= ALARM_ANY => Some(None),
+ raw => self.decode(raw).filter(|value| *value < limit).map(Some),
+ };
+ let fields = AlarmFields {
+ second: field(SECONDS_ALARM, 60)?,
+ minute: field(MINUTES_ALARM, 60)?,
+ hour: field(HOURS_ALARM, 24)?,
+ };
+ Some(Armed::after(fields, now.div_euclid(NANOS_PER_SECOND)))
+ }
+}
+
+impl BusDevice for CmosRtc {
+ fn read(&mut self, offset: u64, data: &mut [u8]) {
+ match (offset, data) {
+ (1, [value]) => *value = self.read_register(self.selected),
+ // The select port is write-only, and registers take byte accesses.
+ (_, data) => data.fill(UNCLAIMED_READ),
+ }
+ }
+
+ fn write(&mut self, offset: u64, data: &[u8]) {
+ match (offset, data) {
+ // Bit 7 masks NMI on a PC; there is no NMI source to mask here.
+ (0, [value]) => self.selected = usize::from(value & 0x7f),
+ (1, [value]) => self.write_register(self.selected, *value),
+ _ => {}
+ }
+ }
+}
+
+impl Drop for CmosRtc {
+ fn drop(&mut self) {
+ self.alarm.state().stopping = true;
+ self.alarm.changed.notify_one();
+ if let Some(worker) = self.worker.take()
+ && worker.join().is_err()
+ {
+ tracing::warn!("the CMOS RTC alarm thread panicked");
+ }
+ }
+}
+
+/// The alarm's second, minute and hour; `None` matches any value.
+#[derive(Clone, Copy, Debug)]
+struct AlarmFields {
+ second: Option<i64>,
+ minute: Option<i64>,
+ hour: Option<i64>,
+}
+
+impl AlarmFields {
+ /// Seconds from `second_of_day` to the next second the alarm matches,
+ /// 1 to 86 400; an alarm that matches only `second_of_day` is a day away.
+ fn seconds_to_next_match(self, second_of_day: i64) -> i64 {
+ if let (Some(hour), Some(minute), Some(second)) = (self.hour, self.minute, self.second) {
+ let ahead = hour * 3600 + minute * 60 + second - second_of_day;
+ return if ahead > 0 {
+ ahead
+ } else {
+ ahead + SECONDS_PER_DAY
+ };
+ }
+ (1..SECONDS_PER_DAY)
+ .find(|ahead| self.matches((second_of_day + ahead).rem_euclid(SECONDS_PER_DAY)))
+ .unwrap_or(SECONDS_PER_DAY)
+ }
+
+ fn matches(self, second_of_day: i64) -> bool {
+ let matches = |field: Option<i64>, value: i64| field.is_none_or(|field| field == value);
+ matches(self.second, second_of_day % 60)
+ && matches(self.minute, second_of_day / 60 % 60)
+ && matches(self.hour, second_of_day / 3600)
+ }
+}
+
+/// A pending occurrence in guest RTC seconds since the Unix epoch.
+struct Armed {
+ target_second: i64,
+ observed_second: i64,
+ fields: AlarmFields,
+}
+
+impl Armed {
+ fn after(fields: AlarmFields, current_second: i64) -> Self {
+ let ahead = fields.seconds_to_next_match(current_second.rem_euclid(SECONDS_PER_DAY));
+ Self {
+ target_second: current_second + ahead,
+ observed_second: current_second,
+ fields,
+ }
+ }
+}
+
+/// RTC time, alarm flags and the IRQ line share one lock so a port access can
+/// settle an overdue match before acknowledging or reconfiguring it.
+struct AlarmState {
+ clock: Clock,
+ offset_from_clock: i64,
+ irq: IrqLine,
+ event_sender: EventSender,
+ armed: Option<Armed>,
+ matched: bool,
+ aie: bool,
+ stopping: bool,
+}
+
+impl AlarmState {
+ fn guest_time_nanos(&self) -> i64 {
+ (self.clock)().saturating_add(self.offset_from_clock)
+ }
+
+ fn settle_match(&mut self, now: i64) {
+ if self.matched {
+ return;
+ }
+ if let Some(armed) = &mut self.armed {
+ let second = now.div_euclid(NANOS_PER_SECOND);
+ if second < armed.observed_second {
+ *armed = Armed::after(armed.fields, second);
+ }
+ armed.observed_second = second;
+ self.matched = second >= armed.target_second;
+ }
+ }
+
+ fn flags(&self) -> u8 {
+ if !self.matched {
+ 0
+ } else if self.aie {
+ ALARM_FLAG | INTERRUPT_REQUEST
+ } else {
+ ALARM_FLAG
+ }
+ }
+
+ fn update_irq(&mut self) {
+ if !self.stopping
+ && let Err(error) = self.irq.set_level(self.matched && self.aie)
+ {
+ self.fail(error);
+ }
+ }
+
+ fn fail(&mut self, error: Error) {
+ self.stopping = true;
+ self.event_sender.send(Event::DeviceFailed(error));
+ }
+}
+
+struct Alarm {
+ state: Mutex<AlarmState>,
+ changed: Condvar,
+}
+
+impl Alarm {
+ fn state(&self) -> MutexGuard<'_, AlarmState> {
+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
+ }
+
+ fn run(&self) {
+ let mut state = self.state();
+ while !state.stopping {
+ if state.armed.is_none() || state.matched {
+ // Further matches coalesce while AF is pending.
+ state = self
+ .changed
+ .wait(state)
+ .unwrap_or_else(PoisonError::into_inner);
+ continue;
+ }
+
+ let now = state.guest_time_nanos();
+ state.settle_match(now);
+ if state.matched {
+ state.update_irq();
+ continue;
+ }
+
+ let armed = state.armed.as_ref().expect("alarm is armed");
+ let seconds = armed.target_second - now.div_euclid(NANOS_PER_SECOND);
+ let remaining = Duration::from_secs(seconds as u64)
+ - Duration::from_nanos(now.rem_euclid(NANOS_PER_SECOND) as u64);
+ state = self
+ .changed
+ .wait_timeout(state, remaining.min(ALARM_RECHECK))
+ .unwrap_or_else(PoisonError::into_inner)
+ .0;
+ }
+ }
+}
+
+/// The proleptic Gregorian date `days` after 1970-01-01, as Howard Hinnant's
+/// `civil_from_days` computes it.
+fn civil_from_days(days: i64) -> (i64, i64, i64) {
+ let days_since_0000_03_01 = days + DAYS_FROM_0000_03_01_TO_1970;
+ let era = days_since_0000_03_01.div_euclid(DAYS_PER_ERA);
+ let day_of_era = days_since_0000_03_01.rem_euclid(DAYS_PER_ERA);
+ let year_of_era =
+ (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
+ let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
+ let month_from_march = (5 * day_of_year + 2) / 153;
+ let day = day_of_year - (153 * month_from_march + 2) / 5 + 1;
+ let month = if month_from_march < 10 {
+ month_from_march + 3
+ } else {
+ month_from_march - 9
+ };
+ (era * 400 + year_of_era + i64::from(month <= 2), month, day)
+}
+
+/// Days from 1970-01-01 to a proleptic Gregorian date, the inverse of
+/// [`civil_from_days`]; days past the end of a month run into the next.
+fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
+ let year = year - i64::from(month <= 2);
+ let era = year.div_euclid(400);
+ let year_of_era = year.rem_euclid(400);
+ let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;
+ let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
+ era * DAYS_PER_ERA + day_of_era - DAYS_FROM_0000_03_01_TO_1970
+}
+
+#[cfg(test)]
+#[path = "../../tests/cmos/mod.rs"]
+mod tests;
diff --git a/src/vmm/src/devices/mod.rs b/src/vmm/src/devices/mod.rs
index 91409f85e..a72c688eb 100644
--- a/src/vmm/src/devices/mod.rs
+++ b/src/vmm/src/devices/mod.rs
@@ -4,6 +4,8 @@
//! The devices behind the buses, and the platform code that adds them.
pub(crate) mod balloon;
+#[cfg(target_arch = "x86_64")]
+pub(crate) mod cmos;
pub(crate) mod console;
#[cfg(target_arch = "x86_64")]
pub(crate) mod i8042;
@@ -42,7 +44,7 @@ pub(crate) fn add_all(
config: &mut VmConfig,
console: ConsoleWriter,
) -> Result<()> {
- add_legacy_devices(chipset, console.clone())?;
+ add_legacy_devices(chipset, console.clone(), Box::new(cmos::host_clock))?;
let mut slots = Slots::new();
let mut used = Vec::new();
diff --git a/src/vmm/src/devices/x86_64.rs b/src/vmm/src/devices/x86_64.rs
index 2542df260..447bbb4de 100644
--- a/src/vmm/src/devices/x86_64.rs
+++ b/src/vmm/src/devices/x86_64.rs
@@ -4,24 +4,35 @@
//! The x86_64 legacy platform: the PC ports Linux expects at boot, and
//! the windows KVM's in-kernel PIC, PIT and APICs serve.
-use super::{console::ConsoleWriter, i8042::I8042, serial::Serial8250};
+use super::{
+ cmos::{Clock, CmosRtc},
+ console::ConsoleWriter,
+ i8042::I8042,
+ serial::Serial8250,
+};
use crate::{
chipset::{BusKind, ChipsetBuilder},
error::Result,
};
-// COM1, the interrupt line (GSI) it raises, then the i8042 data and command ports.
+// COM1 and the interrupt line (GSI) it raises, the CMOS index port, whose
+// data port follows it, and the CMOS alarm's line, then the i8042 data and
+// command ports.
pub(crate) const COM1: u64 = 0x3f8;
pub(crate) const COM1_GSI: u32 = 4;
+pub(crate) const CMOS: u64 = 0x70;
+pub(crate) const CMOS_GSI: u32 = 8;
pub(crate) const I8042_DATA: u64 = 0x60;
pub(crate) const I8042_COMMAND: u64 = 0x64;
/// Reserves the windows the host serves in the kernel, so a device placed
-/// there fails the build, then adds COM1 on GSI 4, writing to `console`, and
-/// the i8042, whose reset ends the VM.
+/// there fails the build, then adds COM1 on GSI 4, writing to `console`, the
+/// CMOS RTC, which reads the time from `clock` and raises its alarm on GSI 8,
+/// and the i8042, whose reset ends the VM.
pub(crate) fn add_legacy_devices(
builder: &mut ChipsetBuilder,
console: ConsoleWriter,
+ clock: Clock,
) -> Result<()> {
for (base, len, owner) in [
(0x20, 2, "in-kernel PIC"),
@@ -39,6 +50,10 @@ pub(crate) fn add_legacy_devices(
r.pio(COM1, 8);
Ok(Serial8250::new(r.line(COM1_GSI), console, r.event_sender()))
})?;
+ builder.add("cmos", |r| {
+ r.pio(CMOS, 2);
+ Ok(CmosRtc::new(clock, r.line(CMOS_GSI), r.event_sender()))
+ })?;
builder.add("i8042", |r| {
r.pio(I8042_DATA, 1);
r.pio_with_offset(I8042_COMMAND, 1, 4);
diff --git a/src/vmm/src/error.rs b/src/vmm/src/error.rs
index ac4e60fa5..9b6c8dfb8 100644
--- a/src/vmm/src/error.rs
+++ b/src/vmm/src/error.rs
@@ -78,6 +78,8 @@ pub enum Error {
CreateBalloon(io::Error),
/// Starting the thread that writes the guest console failed.
SpawnConsole(io::Error),
+ /// Starting the thread that raises the CMOS RTC alarm failed.
+ SpawnRtcAlarm(io::Error),
/// Starting the thread of vCPU `vcpu` failed.
SpawnVcpu { vcpu: u32, source: io::Error },
/// vCPU `vcpu` exited in a way this host should never report, such as
@@ -151,6 +153,7 @@ impl fmt::Display for Error {
Self::EventLoop(_) => f.write_str("the VM event loop failed"),
Self::CreateBalloon(_) => f.write_str("failed to create the reporting balloon"),
Self::SpawnConsole(_) => f.write_str("failed to start the console thread"),
+ Self::SpawnRtcAlarm(_) => f.write_str("failed to start the RTC alarm thread"),
Self::SpawnVcpu { vcpu, .. } => write!(f, "failed to start vCPU {vcpu}"),
Self::UnexpectedExit { vcpu, exit } => {
write!(f, "vCPU {vcpu} exited unexpectedly: {exit}")
@@ -189,6 +192,7 @@ impl error::Error for Error {
| Self::SpawnVcpu { source, .. }
| Self::EventLoop(source)
| Self::CreateBalloon(source)
+ | Self::SpawnRtcAlarm(source)
| Self::SpawnConsole(source)
| Self::VirtioWorker(source) => Some(source),
Self::Hypervisor(source) => Some(source),
diff --git a/src/vmm/src/lib.rs b/src/vmm/src/lib.rs
index 117cb26bc..6ce1639c1 100644
--- a/src/vmm/src/lib.rs
+++ b/src/vmm/src/lib.rs
@@ -53,11 +53,8 @@ mod events;
)]
mod hotplug;
#[cfg_attr(
- not(test),
- expect(
- dead_code,
- reason = "Only tests use part of this API, and only Linux x86_64 adds devices yet."
- )
+ not(any(test, all(target_os = "linux", target_arch = "x86_64"))),
+ expect(dead_code, reason = "Only Linux x86_64 adds devices yet.")
)]
mod irq;
mod memory;
diff --git a/src/vmm/src/virtio/mmio.rs b/src/vmm/src/virtio/mmio.rs
index 9c81605bc..b43fcccfe 100644
--- a/src/vmm/src/virtio/mmio.rs
+++ b/src/vmm/src/virtio/mmio.rs
@@ -49,7 +49,7 @@ pub(crate) const MMIO_WINDOW_LEN: u64 = 0x1000;
/// Where the virtio-mmio windows start; slot `i` is `i` windows later.
const WINDOW_START: u64 = 0xd000_0000;
/// The interrupt lines the slots use, in order: the legacy range above COM1
-/// and below the MSI space, as Firecracker and libkrun allocate it.
+/// and below the MSI space, skipping GSI 8 reserved for the PC RTC.
const FIRST_GSI: u32 = 5;
const LAST_GSI: u32 = 23;
@@ -79,7 +79,7 @@ pub(crate) struct Slots {
impl Slots {
/// How many slots a VM has.
- pub(crate) const CAPACITY: u32 = LAST_GSI - FIRST_GSI + 1;
+ pub(crate) const CAPACITY: u32 = LAST_GSI - FIRST_GSI;
pub(crate) fn new() -> Self {
Self::default()
@@ -94,7 +94,7 @@ impl Slots {
self.taken += 1;
Ok(Slot {
base: WINDOW_START + u64::from(index) * MMIO_WINDOW_LEN,
- gsi: FIRST_GSI + index,
+ gsi: FIRST_GSI + index + u32::from(FIRST_GSI + index >= 8),
})
}
}
diff --git a/src/vmm/tests/boot/mod.rs b/src/vmm/tests/boot/mod.rs
index d20d61196..40181e08e 100644
--- a/src/vmm/tests/boot/mod.rs
+++ b/src/vmm/tests/boot/mod.rs
@@ -201,6 +201,9 @@ const LINUX_CMDLINE: &str = "earlycon=uart8250,io,0x3f8 keep_bootcon panic=-1 re
const CONSOLE_CMDLINE: &str = "console=ttyS0 panic=-1 reboot=k";
/// How long a real-kernel boot may take before the watchdog ends it.
const BOOT_TIMEOUT: Duration = Duration::from_secs(30);
+/// The time the CMOS RTC starts at, 2026-01-02T03:04:05Z, in nanoseconds. It
+/// then runs, so an alarm Linux sets for an update interrupt comes due.
+const CMOS_TIME: i64 = 1_767_323_045_000_000_000;
/// `vcpu_count` vCPUs and 256 MiB of RAM for `kernel` and `initramfs`,
/// booted with `cmdline`.
@@ -290,15 +293,15 @@ impl Console {
}
}
-/// KVM, counting the edges devices raise on GSI 4. With `deliver` off it
-/// drops every interrupt instead of passing it on.
-struct Gsi4Counter {
+/// Counts serial IRQ requests and RTC assertions accepted by KVM.
+struct KvmIrqCounter {
kvm: boxlite_hypervisor::KvmVm,
deliver: bool,
edges: Arc<AtomicUsize>,
+ gsi_8_assertions: Arc<AtomicUsize>,
}
-impl boxlite_hypervisor::Vm for Gsi4Counter {
+impl boxlite_hypervisor::Vm for KvmIrqCounter {
type Vcpu = boxlite_hypervisor::KvmVcpu;
unsafe fn map_memory(
@@ -325,14 +328,16 @@ impl boxlite_hypervisor::Vm for Gsi4Counter {
self.edges.fetch_add(1, Ordering::Relaxed);
}
if self.deliver {
- boxlite_hypervisor::Vm::set_irq_line(&self.kvm, line, level)
- } else {
- Ok(())
+ self.kvm.set_irq_line(line, level)?;
+ if line == 8 && level {
+ self.gsi_8_assertions.fetch_add(1, Ordering::Relaxed);
+ }
}
+ Ok(())
}
}
-impl boxlite_hypervisor::X86Vm for Gsi4Counter {
+impl boxlite_hypervisor::X86Vm for KvmIrqCounter {
fn supported_cpuid(&self) -> &[boxlite_hypervisor::X86CpuidEntry] {
boxlite_hypervisor::X86Vm::supported_cpuid(&self.kvm)
}
@@ -340,7 +345,7 @@ impl boxlite_hypervisor::X86Vm for Gsi4Counter {
/// A KVM VM booting `config` on the legacy devices, before it runs.
struct LinuxVm {
- vm: crate::Vm<Gsi4Counter>,
+ vm: crate::Vm<KvmIrqCounter>,
/// The zero page as `prepare` wrote it.
zero_page: boot_params,
/// The console worker behind COM1: a test finishes it once its sink can
@@ -348,6 +353,7 @@ struct LinuxVm {
console: ConsoleWorker,
/// The edges the serial port raised on GSI 4.
gsi_4_edges: Arc<AtomicUsize>,
+ gsi_8_assertions: Arc<AtomicUsize>,
}
fn probe_boot(config: &VmConfig) -> (boxlite_hypervisor::PreparedKvm, CheckedBootLeaf) {
@@ -365,7 +371,8 @@ fn probe_boot_with_leaf(
}
/// Builds a KVM VM for `config` with the legacy devices, COM1 writing to
-/// `console`. With `deliver_irqs` off, every device interrupt is dropped.
+/// `console` and the CMOS RTC running from `CMOS_TIME`. With `deliver_irqs`
+/// off, every device interrupt is dropped.
fn linux_vm(config: &VmConfig, deliver_irqs: bool, console: Console) -> LinuxVm {
linux_vm_with_leaf(config, deliver_irqs, console, BOOT_LEAF)
}
@@ -379,15 +386,18 @@ fn linux_vm_with_leaf(
let (prepared, leaf) = probe_boot_with_leaf(config, leaf);
let (writer, console) = ConsoleWorker::spawn(console.sink, console.capacity).unwrap();
let gsi_4_edges = Arc::new(AtomicUsize::new(0));
+ let gsi_8_assertions = Arc::new(AtomicUsize::new(0));
let edges = Arc::clone(&gsi_4_edges);
+ let rtc_assertions = Arc::clone(&gsi_8_assertions);
let mut zero_page = None;
let vm = crate::Vm::with_backend(
config.clone(),
move || {
- Ok(Gsi4Counter {
+ Ok(KvmIrqCounter {
kvm: boxlite_hypervisor::KvmVm::from_prepared(prepared)?,
deliver: deliver_irqs,
edges,
+ gsi_8_assertions: rtc_assertions,
})
},
|ram, config| {
@@ -396,7 +406,14 @@ fn linux_vm_with_leaf(
zero_page = Some(ram.memory().memory().read_obj(address).unwrap());
Ok(setup.boot_regs)
},
- |chipset, _| add_legacy_devices(chipset, writer),
+ |chipset, _| {
+ let started = Instant::now();
+ let clock = move || {
+ let elapsed = i64::try_from(started.elapsed().as_nanos()).unwrap_or(i64::MAX);
+ CMOS_TIME.saturating_add(elapsed)
+ };
+ add_legacy_devices(chipset, writer, Box::new(clock))
+ },
)
.expect("create the KVM VM");
LinuxVm {
@@ -404,6 +421,7 @@ fn linux_vm_with_leaf(
zero_page: zero_page.unwrap(),
console,
gsi_4_edges,
+ gsi_8_assertions,
}
}
@@ -415,6 +433,8 @@ struct LinuxRun {
exit: crate::Result<VmExit>,
/// The edges the serial port raised on GSI 4.
gsi_4_edges: usize,
+ /// RTC IRQ assertions accepted by KVM.
+ gsi_8_assertions: usize,
/// The console worker, still running: a test finishes it once its sink
/// can take the rest.
console: ConsoleWorker,
@@ -439,12 +459,14 @@ fn run_linux_vm(vm: LinuxVm, timeout: Duration) -> LinuxRun {
zero_page,
console,
gsi_4_edges,
+ gsi_8_assertions,
} = vm;
let (exit, elapsed) = run_with_watchdog(&mut vm, timeout);
LinuxRun {
zero_page,
exit,
gsi_4_edges: gsi_4_edges.load(Ordering::Relaxed),
+ gsi_8_assertions: gsi_8_assertions.load(Ordering::Relaxed),
console,
elapsed,
}
@@ -643,20 +665,20 @@ fn exit_program(code: u8) -> Vec<u8> {
static_program(&[0xbf, code, 0, 0, 0, 0xb8, 231, 0, 0, 0, 0x0f, 0x05])
}
-/// A static executable that writes `line` and a newline to its stdout, waits
-/// until the tty has sent them, and restarts the machine; `exit_group(1)`
-/// follows in case the restart returns.
-fn print_and_restart(line: &str) -> Vec<u8> {
- const CODE_LEN: u64 = 81;
- let message = format!("{line}\n");
- let message_addr = u32::try_from(PROGRAM_BASE + PROGRAM_HEADERS + CODE_LEN).unwrap();
- let message_len = u32::try_from(message.len()).unwrap();
+/// The bytes [`restart_code`] emits, and the offset of its `exit_group(1)`.
+const RESTART_LEN: usize = 81;
+const RESTART_EXIT: usize = 69;
+
+/// The end of every restarting `/init`: writes the `len` bytes at `message`
+/// to stdout, waits until the tty has sent them, and restarts the machine;
+/// `exit_group(1)` follows in case the restart returns.
+fn restart_code(message: u32, len: u32) -> Vec<u8> {
let mut text = Vec::new();
// mov eax, 1 (write); mov edi, 1; mov esi, message; mov edx, length; syscall
text.extend_from_slice(&[0xb8, 1, 0, 0, 0, 0xbf, 1, 0, 0, 0, 0xbe]);
- text.extend_from_slice(&message_addr.to_le_bytes());
+ text.extend_from_slice(&message.to_le_bytes());
text.push(0xba);
- text.extend_from_slice(&message_len.to_le_bytes());
+ text.extend_from_slice(&len.to_le_bytes());
text.extend_from_slice(&[0x0f, 0x05]);
// mov eax, 16 (ioctl); mov edi, 1; mov esi, 0x5409 (TCSBRK); mov edx, 1
// (drain, no break); syscall
@@ -669,9 +691,81 @@ fn print_and_restart(line: &str) -> Vec<u8> {
0xb8, 169, 0, 0, 0, 0xbf, 0xad, 0xde, 0xe1, 0xfe, 0xbe, 0x69, 0x19, 0x12, 0x28, 0xba, 0x67,
0x45, 0x23, 0x01, 0x45, 0x31, 0xd2, 0x0f, 0x05,
]);
+ assert_eq!(text.len(), RESTART_EXIT);
// mov edi, 1; mov eax, 231 (exit_group); syscall
text.extend_from_slice(&[0xbf, 1, 0, 0, 0, 0xb8, 231, 0, 0, 0, 0x0f, 0x05]);
- assert_eq!(text.len() as u64, CODE_LEN);
+ assert_eq!(text.len(), RESTART_LEN);
+ text
+}
+
+/// A static executable that writes `line` and a newline to its stdout, waits
+/// until the tty has sent them, and restarts the machine; `exit_group(1)`
+/// follows in case the restart returns.
+fn print_and_restart(line: &str) -> Vec<u8> {
+ let message = format!("{line}\n");
+ let message_addr = u32::try_from(PROGRAM_BASE + PROGRAM_HEADERS + RESTART_LEN as u64).unwrap();
+ let mut text = restart_code(message_addr, u32::try_from(message.len()).unwrap());
+ text.extend_from_slice(message.as_bytes());
+ static_program(&text)
+}
+
+/// A static executable that mounts devtmpfs on `/dev`, turns on update
+/// interrupts on `/dev/rtc0`, and waits up to 2 s for one. When one arrives
+/// it prints `line` and restarts like [`print_and_restart`]; otherwise it
+/// exits, so the kernel panics without printing `line`.
+fn read_rtc_update_and_restart(line: &str) -> Vec<u8> {
+ const SETUP_LEN: usize = 119;
+ const STRINGS: &[u8] = b"devtmpfs\0/dev\0/dev/rtc0\0";
+ let data = PROGRAM_BASE + PROGRAM_HEADERS + (SETUP_LEN + RESTART_LEN) as u64;
+ let at = |offset: u64| u32::try_from(data + offset).unwrap().to_le_bytes();
+ let (devtmpfs, dev, rtc0) = (at(0), at(9), at(14));
+ // A `jne` ending at `end` that lands on the restart code's exit_group(1).
+ let to_exit = |end: usize| u8::try_from(SETUP_LEN + RESTART_EXIT - end).unwrap();
+ let mut text = Vec::new();
+ // mount("devtmpfs", "/dev", "devtmpfs", 0, NULL): mov eax, 165; mov edi,
+ // source; mov esi, target; mov edx, type; xor r10d, r10d; xor r8d, r8d;
+ // syscall
+ text.extend_from_slice(&[0xb8, 165, 0, 0, 0, 0xbf]);
+ text.extend_from_slice(&devtmpfs);
+ text.push(0xbe);
+ text.extend_from_slice(&dev);
+ text.push(0xba);
+ text.extend_from_slice(&devtmpfs);
+ text.extend_from_slice(&[0x45, 0x31, 0xd2, 0x45, 0x31, 0xc0, 0x0f, 0x05]);
+ // ebx = open("/dev/rtc0", O_RDONLY): mov eax, 2; mov edi, path; xor esi,
+ // esi; syscall; mov ebx, eax
+ text.extend_from_slice(&[0xb8, 2, 0, 0, 0, 0xbf]);
+ text.extend_from_slice(&rtc0);
+ text.extend_from_slice(&[0x31, 0xf6, 0x0f, 0x05, 0x89, 0xc3]);
+ // ioctl(ebx, RTC_UIE_ON, 0): mov eax, 16; mov edi, ebx; mov esi, 0x7003;
+ // xor edx, edx; syscall
+ text.extend_from_slice(&[
+ 0xb8, 16, 0, 0, 0, 0x89, 0xdf, 0xbe, 0x03, 0x70, 0, 0, 0x31, 0xd2, 0x0f, 0x05,
+ ]);
+ // A pollfd {ebx, POLLIN} on the stack, then poll(rsp, 1, 2000) and exit
+ // unless the fd is ready: sub rsp, 8; mov [rsp], ebx; mov dword
+ // [rsp+4], 1; mov eax, 7; mov rdi, rsp; mov esi, 1; mov edx, 2000;
+ // syscall; cmp eax, 1; jne exit
+ text.extend_from_slice(&[
+ 0x48, 0x83, 0xec, 0x08, 0x89, 0x1c, 0x24, 0xc7, 0x44, 0x24, 0x04, 1, 0, 0, 0, 0xb8, 7, 0,
+ 0, 0, 0x48, 0x89, 0xe7, 0xbe, 1, 0, 0, 0, 0xba, 0xd0, 0x07, 0, 0, 0x0f, 0x05, 0x83, 0xf8,
+ 1, 0x75,
+ ]);
+ text.push(to_exit(text.len() + 1));
+ // read(ebx, rsp, 8), and exit unless it returned 8 bytes: xor eax, eax;
+ // mov edi, ebx; mov rsi, rsp; mov edx, 8; syscall; cmp eax, 8; jne exit
+ text.extend_from_slice(&[
+ 0x31, 0xc0, 0x89, 0xdf, 0x48, 0x89, 0xe6, 0xba, 8, 0, 0, 0, 0x0f, 0x05, 0x83, 0xf8, 8, 0x75,
+ ]);
+ text.push(to_exit(text.len() + 1));
+ assert_eq!(text.len(), SETUP_LEN);
+ let message = format!("{line}\n");
+ let message_addr = u32::try_from(data + STRINGS.len() as u64).unwrap();
+ text.extend(restart_code(
+ message_addr,
+ u32::try_from(message.len()).unwrap(),
+ ));
+ text.extend_from_slice(STRINGS);
text.extend_from_slice(message.as_bytes());
static_program(&text)
}
@@ -811,8 +905,9 @@ const INIT_MARKER: &str = "INIT-MARKER-0123456789ABCDEF";
/// Boots the kernel named by `VMM_KERNEL` with its console on the 8250 driver
/// and an `/init` that prints `INIT_MARKER` and restarts the machine. Linux
-/// must find a 16550A on IRQ 4, `/init`'s line must leave through the tty,
-/// and the restart must end the run with the i8042 reset.
+/// must find a 16550A on IRQ 4 and register the CMOS RTC as rtc0 without
+/// setting its clock from it, `/init`'s line must leave through the tty, and
+/// the restart must end the run with the i8042 reset.
#[test]
#[ignore = "requires Linux x86_64 with access to /dev/kvm and VMM_KERNEL naming an x86_64 vmlinux"]
fn boots_linux_on_the_legacy_devices_until_init_restarts() {
@@ -834,15 +929,54 @@ fn boots_linux_on_the_legacy_devices_until_init_restarts() {
&log,
&[
&serial_probe_line(),
+ "rtc_cmos rtc_cmos: registered as rtc0",
INIT_MARKER,
"reboot: Restarting system",
],
);
+ // The boot time comes from kvm-clock; the CMOS must not override it.
+ assert!(!log.contains("setting system clock"), "{log}");
assert!(!log.contains("Kernel panic"), "{log}");
assert!(run.gsi_4_edges > 0);
assert_eq!(run.console.dropped_bytes(), 0);
}
+/// The line the UIE test's `/init` prints once an update interrupt arrived.
+const RTC_UPDATE_MARKER: &str = "RTC-UPDATE-IRQ-0123456789ABCDEF";
+
+/// Boots the kernel named by `VMM_KERNEL` with an `/init` that turns on
+/// update interrupts on `/dev/rtc0`, as `hwclock` does, and waits up to 2 s
+/// for one. Linux can finish the read in software if alarm setup crosses a
+/// second boundary. The harness also checks that KVM accepted IRQ 8.
+#[test]
+#[ignore = "requires Linux x86_64 with access to /dev/kvm and VMM_KERNEL naming an x86_64 vmlinux"]
+fn an_rtc_update_interrupt_reaches_init_through_the_cmos_alarm() {
+ let archive = newc_archive("init", &read_rtc_update_and_restart(RTC_UPDATE_MARKER));
+ let initramfs = TempFile::new("rtc-update.cpio", &archive);
+
+ let log = SerialLog::default();
+ let mut run = run_linux(
+ &linux_config(1, CONSOLE_CMDLINE, Some(initramfs.0.clone())),
+ true,
+ BOOT_TIMEOUT,
+ Console::to(&log),
+ );
+
+ run.console.finish();
+ let log = log.text();
+ assert_reset(&run, &log);
+ assert_in_order(
+ &log,
+ &[
+ "rtc_cmos rtc_cmos: registered as rtc0",
+ RTC_UPDATE_MARKER,
+ "reboot: Restarting system",
+ ],
+ );
+ assert!(run.gsi_8_assertions > 0, "missing RTC IRQ 8 assertion");
+ assert!(!log.contains("Kernel panic"), "{log}");
+}
+
/// The line the M1 smoke test's `/init` prints.
const M1_MARKER: &str = "BOXLITE_M1_OK";
diff --git a/src/vmm/tests/boot/virtio_blk.rs b/src/vmm/tests/boot/virtio_blk.rs
index f7a725e6e..d001acf9e 100644
--- a/src/vmm/tests/boot/virtio_blk.rs
+++ b/src/vmm/tests/boot/virtio_blk.rs
@@ -338,7 +338,7 @@ fn boots_linux_and_drives_virtio_blk_through_the_workers() {
},
move |ram, config| crate::boot::prepare(ram, config, leaf).map(|setup| setup.boot_regs),
|chipset, ctx| {
- add_legacy_devices(chipset, writer)?;
+ add_legacy_devices(chipset, writer, Box::new(crate::devices::cmos::host_clock))?;
add_blk(chipset, ctx, device, slot)
},
)
diff --git a/src/vmm/tests/cmos/mod.rs b/src/vmm/tests/cmos/mod.rs
new file mode 100644
index 000000000..7cb032ec6
--- /dev/null
+++ b/src/vmm/tests/cmos/mod.rs
@@ -0,0 +1,579 @@
+// Copyright 2026 BoxLite Contributors
+// SPDX-License-Identifier: Apache-2.0
+
+//! The CMOS RTC on a clock the test moves: calendar encoding, the registers,
+//! the time-setting sequences Linux uses, and the alarm on its line. The 1999
+//! and 2000 vectors are crosvm's (`devices/src/cmos.rs`); the others come
+//! from Python's datetime.
+
+use std::{
+ sync::{
+ Arc,
+ atomic::{AtomicI64, Ordering},
+ mpsc::{self, Receiver, RecvTimeoutError, Sender},
+ },
+ time::Duration,
+};
+
+use super::{AlarmFields, CmosRtc};
+use crate::{
+ bus::{BusDevice, UNCLAIMED_READ},
+ error::Result,
+ events::EventLoop,
+ irq::{IrqChip, IrqLine},
+};
+
+const NANOS: i64 = 1_000_000_000;
+
+/// The indexes of seconds, minutes, hours, weekday, day, month, year and century.
+const TIME: [u8; 8] = [0x00, 0x02, 0x04, 0x06, 0x07, 0x08, 0x09, 0x32];
+
+/// Passes every level the RTC sets on its line to the test.
+struct Lines(Sender<(u32, bool)>);
+
+impl IrqChip for Lines {
+ fn set_line(&self, line: u32, level: bool) -> Result<()> {
+ // A test that stopped listening no longer cares.
+ let _ = self.0.send((line, level));
+ Ok(())
+ }
+}
+
+/// An RTC on a clock that starts at `seconds` past the epoch, and the levels
+/// it sets on line 8. The alarm state owns the only sender.
+fn rtc_with_line(seconds: i64) -> (CmosRtc, Arc<AtomicI64>, Receiver<(u32, bool)>) {
+ let clock = Arc::new(AtomicI64::new(seconds * NANOS));
+ let now = Arc::clone(&clock);
+ let (levels, changes) = mpsc::channel();
+ let line = IrqLine::new(Arc::new(Lines(levels)), 8);
+ let events = EventLoop::new().unwrap();
+ let rtc = CmosRtc::new(
+ Box::new(move || now.load(Ordering::SeqCst)),
+ line,
+ events.sender(),
+ );
+ (rtc, clock, changes)
+}
+
+/// An RTC on a clock that starts at `seconds` past the epoch.
+fn rtc_at(seconds: i64) -> (CmosRtc, Arc<AtomicI64>) {
+ let (rtc, clock, _) = rtc_with_line(seconds);
+ (rtc, clock)
+}
+
+fn advance(clock: &AtomicI64, nanos: i64) {
+ clock.fetch_add(nanos, Ordering::SeqCst);
+}
+
+fn read(rtc: &mut CmosRtc, index: u8) -> u8 {
+ rtc.write(0, &[index]);
+ let mut value = [0];
+ rtc.read(1, &mut value);
+ value[0]
+}
+
+fn write(rtc: &mut CmosRtc, index: u8, value: u8) {
+ rtc.write(0, &[index]);
+ rtc.write(1, &[value]);
+}
+
+fn time(rtc: &mut CmosRtc) -> [u8; 8] {
+ TIME.map(|index| read(rtc, index))
+}
+
+/// The fields Linux writes, in its order: year, month, day, hours, minutes,
+/// seconds (`mc146818_set_time`).
+type Fields = [u8; 6];
+
+fn write_fields(rtc: &mut CmosRtc, fields: Fields) {
+ for (index, value) in [0x09, 0x08, 0x07, 0x04, 0x02, 0x00].into_iter().zip(fields) {
+ write(rtc, index, value);
+ }
+}
+
+/// Linux on Intel: SET, then a divider reset, the fields, register B
+/// restored, then register A restored.
+fn set_time_intel(rtc: &mut CmosRtc, fields: Fields) {
+ let (b, a) = (read(rtc, 0x0b), read(rtc, 0x0a));
+ write(rtc, 0x0b, b | 0x80);
+ write(rtc, 0x0a, a | 0x70);
+ write_fields(rtc, fields);
+ write(rtc, 0x0b, b);
+ write(rtc, 0x0a, a);
+}
+
+/// Linux on AMD: SET, then the bank-select bit cleared instead of a divider
+/// reset, the fields, register B restored, then register A restored.
+fn set_time_amd(rtc: &mut CmosRtc, fields: Fields) {
+ let (b, a) = (read(rtc, 0x0b), read(rtc, 0x0a));
+ write(rtc, 0x0b, b | 0x80);
+ write(rtc, 0x0a, a & !0x10);
+ write_fields(rtc, fields);
+ write(rtc, 0x0b, b);
+ write(rtc, 0x0a, a);
+}
+
+#[test]
+fn reads_the_crosvm_vectors_in_bcd() {
+ let (mut rtc, _) = rtc_at(946_684_799);
+ assert_eq!(
+ time(&mut rtc),
+ [0x59, 0x59, 0x23, 0x06, 0x31, 0x12, 0x99, 0x19]
+ );
+ let (mut rtc, _) = rtc_at(946_684_800);
+ assert_eq!(
+ time(&mut rtc),
+ [0x00, 0x00, 0x00, 0x07, 0x01, 0x01, 0x00, 0x20]
+ );
+}
+
+#[test]
+fn follows_the_gregorian_leap_rules_and_times_before_the_epoch() {
+ for (seconds, expected) in [
+ // 2000-02-29, a Tuesday: 2000 is a leap year.
+ (
+ 951_782_400,
+ [0x00, 0x00, 0x00, 0x03, 0x29, 0x02, 0x00, 0x20],
+ ),
+ // 2100-02-28 23:59:59, a Sunday, then 2100-03-01: 2100 is not.
+ (
+ 4_107_542_399,
+ [0x59, 0x59, 0x23, 0x01, 0x28, 0x02, 0x00, 0x21],
+ ),
+ (
+ 4_107_542_400,
+ [0x00, 0x00, 0x00, 0x02, 0x01, 0x03, 0x00, 0x21],
+ ),
+ // 1969-12-31 23:59:59, a Wednesday.
+ (-1, [0x59, 0x59, 0x23, 0x04, 0x31, 0x12, 0x69, 0x19]),
+ ] {
+ let (mut rtc, _) = rtc_at(seconds);
+ assert_eq!(time(&mut rtc), expected, "at {seconds}");
+ }
+}
+
+#[test]
+fn rolls_over_into_the_next_day() {
+ // 2026-01-02 23:59:59, a Friday.
+ let (mut rtc, clock) = rtc_at(1_767_398_399);
+ assert_eq!(
+ time(&mut rtc),
+ [0x59, 0x59, 0x23, 0x06, 0x02, 0x01, 0x26, 0x20]
+ );
+ advance(&clock, NANOS);
+ assert_eq!(
+ time(&mut rtc),
+ [0x00, 0x00, 0x00, 0x07, 0x03, 0x01, 0x26, 0x20]
+ );
+}
+
+#[test]
+fn binary_mode_reads_and_sets_plain_numbers() {
+ let (mut rtc, _) = rtc_at(946_684_799);
+ write(&mut rtc, 0x0b, 0x06);
+ assert_eq!(time(&mut rtc), [59, 59, 23, 6, 31, 12, 99, 19]);
+
+ // 2030-05-06 07:08:09, a Monday, written in binary.
+ set_time_intel(&mut rtc, [30, 5, 6, 7, 8, 9]);
+ assert_eq!(time(&mut rtc), [9, 8, 7, 2, 6, 5, 30, 20]);
+}
+
+#[test]
+fn status_registers_keep_their_fixed_bits() {
+ let status = |rtc: &mut CmosRtc| [0x0a, 0x0b, 0x0c, 0x0d].map(|index| read(rtc, index));
+ let (mut rtc, _) = rtc_at(0);
+ assert_eq!(status(&mut rtc), [0x26, 0x02, 0x00, 0x80]);
+
+ write(&mut rtc, 0x0a, 0xa6); // UIP is read-only
+ write(&mut rtc, 0x0b, 0x00); // 12-hour mode is not modelled
+ write(&mut rtc, 0x0c, 0xff);
+ write(&mut rtc, 0x0d, 0x00);
+
+ assert_eq!(status(&mut rtc), [0x26, 0x02, 0x00, 0x80]);
+}
+
+#[test]
+fn a_time_set_the_linux_way_ticks_half_a_second_after_release() {
+ let sequences: [fn(&mut CmosRtc, Fields); 2] = [set_time_intel, set_time_amd];
+ for set_time in sequences {
+ let (mut rtc, clock) = rtc_at(1_767_323_045);
+ // 2030-05-06 07:08:09, a Monday.
+ set_time(&mut rtc, [0x30, 0x05, 0x06, 0x07, 0x08, 0x09]);
+ assert_eq!(
+ time(&mut rtc),
+ [0x09, 0x08, 0x07, 0x02, 0x06, 0x05, 0x30, 0x20]
+ );
+
+ advance(&clock, NANOS / 2 - 1_000_000);
+ assert_eq!(read(&mut rtc, 0x00), 0x09, "1 ms before the next second");
+ advance(&clock, 2_000_000);
+ assert_eq!(read(&mut rtc, 0x00), 0x10, "1 ms into the next second");
+ }
+}
+
+#[test]
+fn the_registers_hold_still_while_set_is_on() {
+ let (mut rtc, clock) = rtc_at(946_684_799);
+ write(&mut rtc, 0x0b, 0x82);
+ advance(&clock, 5 * NANOS);
+ assert_eq!(
+ time(&mut rtc),
+ [0x59, 0x59, 0x23, 0x06, 0x31, 0x12, 0x99, 0x19]
+ );
+
+ write(&mut rtc, 0x0b, 0x02);
+ assert_eq!(read(&mut rtc, 0x00), 0x59, "the held time resumes");
+ advance(&clock, NANOS / 2);
+ assert_eq!(
+ time(&mut rtc),
+ [0x00, 0x00, 0x00, 0x07, 0x01, 0x01, 0x00, 0x20]
+ );
+}
+
+#[test]
+fn a_write_while_running_takes_effect_at_once_within_the_same_second() {
+ let (mut rtc, clock) = rtc_at(946_684_799);
+ advance(&clock, NANOS * 3 / 4);
+
+ write(&mut rtc, 0x02, 0x30);
+ assert_eq!(time(&mut rtc)[..3], [0x59, 0x30, 0x23]);
+ advance(&clock, NANOS / 4);
+ assert_eq!(time(&mut rtc)[..3], [0x00, 0x31, 0x23]);
+}
+
+#[test]
+fn an_impossible_time_leaves_the_clock_alone() {
+ let (mut rtc, clock) = rtc_at(946_684_799);
+ write(&mut rtc, 0x0b, 0x82);
+ write(&mut rtc, 0x00, 0x60); // second 60
+ write(&mut rtc, 0x0b, 0x02);
+ advance(&clock, NANOS);
+ assert_eq!(
+ time(&mut rtc),
+ [0x00, 0x00, 0x00, 0x07, 0x01, 0x01, 0x00, 0x20]
+ );
+
+ write(&mut rtc, 0x02, 0x7a); // not BCD
+ assert_eq!(read(&mut rtc, 0x02), 0x00);
+}
+
+#[test]
+fn two_digit_years_pivot_at_70_unless_the_guest_writes_the_century() {
+ let (mut rtc, _) = rtc_at(0);
+ set_time_intel(&mut rtc, [0x69, 0x01, 0x01, 0x00, 0x00, 0x00]);
+ assert_eq!([read(&mut rtc, 0x09), read(&mut rtc, 0x32)], [0x69, 0x20]);
+ set_time_intel(&mut rtc, [0x70, 0x01, 0x01, 0x00, 0x00, 0x00]);
+ assert_eq!([read(&mut rtc, 0x09), read(&mut rtc, 0x32)], [0x70, 0x19]);
+
+ write(&mut rtc, 0x0b, 0x82);
+ write(&mut rtc, 0x32, 0x21);
+ write(&mut rtc, 0x09, 0x05);
+ write(&mut rtc, 0x0b, 0x02);
+ // 2105-01-01, a Thursday.
+ assert_eq!(
+ time(&mut rtc),
+ [0x00, 0x00, 0x00, 0x05, 0x01, 0x01, 0x05, 0x21]
+ );
+}
+
+#[test]
+fn a_day_past_the_month_end_runs_into_the_next_month() {
+ let (mut rtc, _) = rtc_at(0);
+ set_time_amd(&mut rtc, [0x01, 0x02, 0x31, 0x00, 0x00, 0x00]);
+ // 2001-02-31 is 2001-03-03, a Saturday.
+ assert_eq!(
+ time(&mut rtc),
+ [0x00, 0x00, 0x00, 0x07, 0x03, 0x03, 0x01, 0x20]
+ );
+}
+
+#[test]
+fn other_bytes_are_ram_and_odd_accesses_are_unclaimed() {
+ let (mut rtc, _) = rtc_at(0);
+ write(&mut rtc, 0x0e, 0xab);
+ write(&mut rtc, 0x7f, 0xcd);
+ write(&mut rtc, 0x01, 0x30); // the alarm seconds are plain storage
+ assert_eq!(
+ [0x0e, 0x7f, 0x01].map(|index| read(&mut rtc, index)),
+ [0xab, 0xcd, 0x30]
+ );
+ // Bit 7 of the index masks NMI on a PC and selects nothing.
+ assert_eq!(read(&mut rtc, 0x8e), 0xab);
+
+ let mut index_port = [0];
+ rtc.read(0, &mut index_port);
+ let mut wide = [0; 2];
+ rtc.read(1, &mut wide);
+ rtc.write(1, &[0x11, 0x22]);
+
+ assert_eq!(index_port, [UNCLAIMED_READ]);
+ assert_eq!(wide, [UNCLAIMED_READ; 2]);
+ assert_eq!(read(&mut rtc, 0x0e), 0xab, "a wide write changes nothing");
+}
+
+#[test]
+fn the_next_alarm_match_honours_wildcards_and_wraps_the_day() {
+ let at = |hour: i64, minute: i64, second: i64| hour * 3600 + minute * 60 + second;
+ let alarm = |second, minute, hour| AlarmFields {
+ second,
+ minute,
+ hour,
+ };
+ // Midnight from 23:59:59 is one second ahead, across the day.
+ let midnight = alarm(Some(0), Some(0), Some(0));
+ assert_eq!(midnight.seconds_to_next_match(at(23, 59, 59)), 1);
+ // Every field "don't care": every second.
+ assert_eq!(
+ alarm(None, None, None).seconds_to_next_match(at(12, 0, 0)),
+ 1
+ );
+ // Second 30 of any minute, from 12:00:45.
+ let second_30 = alarm(Some(30), None, None);
+ assert_eq!(second_30.seconds_to_next_match(at(12, 0, 45)), 45);
+ // Any second of 13:00: next second while in it, the next day after it.
+ let at_13_00 = alarm(None, Some(0), Some(13));
+ assert_eq!(at_13_00.seconds_to_next_match(at(13, 0, 30)), 1);
+ assert_eq!(at_13_00.seconds_to_next_match(at(13, 0, 59)), 86_341);
+ // An alarm on the current second alone is a day away.
+ let now = alarm(Some(5), Some(4), Some(3));
+ assert_eq!(now.seconds_to_next_match(at(3, 4, 5)), 86_400);
+}
+
+#[test]
+fn an_alarm_raises_line_8_and_reports_itself_once_in_register_c() {
+ // 1999-12-31 23:59:59, with the alarm at 00:00:00, a second ahead.
+ let (mut rtc, clock, changes) = rtc_with_line(946_684_799);
+ for index in [0x01, 0x03, 0x05] {
+ write(&mut rtc, index, 0x00);
+ }
+ write(&mut rtc, 0x0b, 0x22); // AIE, 24-hour mode
+ advance(&clock, NANOS);
+
+ let wait = Duration::from_secs(5);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, true)));
+ assert_eq!(changes.try_recv(), Err(mpsc::TryRecvError::Empty));
+ assert_eq!(read(&mut rtc, 0x0c), 0xa0, "IRQF and AF");
+ assert_eq!(changes.recv_timeout(wait), Ok((8, false)));
+ assert_eq!(read(&mut rtc, 0x0c), 0x00, "reading register C clears it");
+}
+
+#[test]
+fn clearing_aie_preserves_af_without_another_edge() {
+ // Half a second into 00:00:00, with every alarm field "don't care".
+ let (mut rtc, clock, changes) = rtc_with_line(0);
+ advance(&clock, NANOS / 2);
+ for index in [0x01, 0x03, 0x05] {
+ write(&mut rtc, index, 0xff);
+ }
+ write(&mut rtc, 0x0b, 0x22);
+ advance(&clock, NANOS / 2);
+ let wait = Duration::from_secs(5);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, true)));
+
+ write(&mut rtc, 0x0b, 0x02);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, false)));
+ advance(&clock, NANOS);
+ // Further matches coalesce while AF remains unacknowledged.
+ assert_eq!(
+ changes.recv_timeout(Duration::from_millis(1500)),
+ Err(RecvTimeoutError::Timeout)
+ );
+ assert_eq!(
+ read(&mut rtc, 0x0c),
+ 0x20,
+ "AF without IRQF once AIE is off"
+ );
+}
+
+/// Schedule a disabled wildcard match 100 ms from now through the guest ports.
+fn disabled_alarm() -> (CmosRtc, Arc<AtomicI64>, Receiver<(u32, bool)>) {
+ let (mut rtc, clock, changes) = rtc_with_line(0);
+ advance(&clock, NANOS - 100_000_000);
+ for index in [0x01, 0x03, 0x05] {
+ write(&mut rtc, index, 0xff);
+ }
+ (rtc, clock, changes)
+}
+
+#[test]
+fn a_disabled_alarm_latches_af_without_irqf_or_an_edge() {
+ let (mut rtc, clock, changes) = disabled_alarm();
+ advance(&clock, 100_000_000);
+ assert_eq!(changes.try_recv(), Err(mpsc::TryRecvError::Empty));
+ assert_eq!(read(&mut rtc, 0x0c), 0x20, "a disabled match must latch AF");
+}
+
+#[test]
+fn enabling_aie_delivers_a_match_that_occurred_while_disabled() {
+ let (mut rtc, clock, changes) = rtc_with_line(86_399);
+ advance(&clock, NANOS);
+ write(&mut rtc, 0x0b, 0x22);
+ assert_eq!(
+ changes.recv_timeout(Duration::from_millis(50)),
+ Ok((8, true)),
+ "pending AF must deliver before the next scheduled match"
+ );
+ assert_eq!(read(&mut rtc, 0x0c), 0xa0);
+ assert_eq!(changes.recv_timeout(Duration::from_secs(5)), Ok((8, false)));
+}
+
+#[test]
+fn reading_c_rearms_disabled_matches_after_coalescing() {
+ let (mut rtc, clock, changes) = disabled_alarm();
+ advance(&clock, 100_000_000);
+ write(&mut rtc, 0x0b, 0x22);
+ let wait = Duration::from_secs(5);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, true)));
+ write(&mut rtc, 0x0b, 0x02);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, false)));
+ advance(&clock, NANOS);
+ assert_eq!(read(&mut rtc, 0x0c), 0x20);
+ assert_eq!(read(&mut rtc, 0x0c), 0, "C clears AF immediately");
+ advance(&clock, NANOS);
+ assert_eq!(
+ read(&mut rtc, 0x0c),
+ 0x20,
+ "the next disabled match relatches AF"
+ );
+ assert_eq!(changes.try_recv(), Err(mpsc::TryRecvError::Empty));
+}
+
+#[test]
+fn reading_c_settles_an_overdue_unprocessed_match() {
+ let (mut rtc, clock, changes) = rtc_with_line(0);
+ write(&mut rtc, 0x01, 1); // A daily alarm at 00:00:01.
+ write(&mut rtc, 0x0b, 0x22);
+ // Hold the worker before its first match, without changing the schedule
+ // produced by the guest register writes.
+ rtc.alarm.state().stopping = true;
+ rtc.alarm.changed.notify_one();
+ rtc.worker.take().unwrap().join().unwrap();
+ rtc.alarm.state().stopping = false;
+ advance(&clock, 2 * NANOS);
+ assert_eq!(read(&mut rtc, 0x0c), 0xa0);
+ assert_eq!(read(&mut rtc, 0x0c), 0);
+ assert_eq!(changes.try_recv(), Err(mpsc::TryRecvError::Empty));
+}
+
+#[test]
+fn stopped_clocks_do_not_schedule_disabled_matches() {
+ for (register, value) in [(0x0b, 0x82), (0x0a, 0x76)] {
+ let (mut rtc, clock, changes) = rtc_with_line(0);
+ advance(&clock, NANOS - 100_000_000);
+ for index in [0x01, 0x03, 0x05] {
+ write(&mut rtc, index, 0xff);
+ }
+ assert!(rtc.alarm.state().armed.is_some());
+ write(&mut rtc, register, value);
+ assert!(rtc.alarm.state().armed.is_none());
+ advance(&clock, NANOS);
+ assert_eq!(changes.try_recv(), Err(mpsc::TryRecvError::Empty));
+ assert_eq!(read(&mut rtc, 0x0c), 0);
+ assert!(rtc.alarm.state().armed.is_none());
+ }
+}
+
+#[test]
+fn a_late_worker_coalesces_missed_matches_into_one() {
+ let (mut rtc, clock, changes) = disabled_alarm();
+ write(&mut rtc, 0x0b, 0x22);
+ advance(&clock, 3 * NANOS);
+ let wait = Duration::from_secs(5);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, true)));
+ assert_eq!(read(&mut rtc, 0x0c), 0xa0);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, false)));
+ assert_eq!(read(&mut rtc, 0x0c), 0);
+ advance(&clock, 100_000_000);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, true)));
+}
+
+#[test]
+fn dropping_the_rtc_stops_and_joins_its_alarm_worker() {
+ // At 00:00:00 the zeroed alarm registers match only now: a day away.
+ let (mut rtc, _, changes) = rtc_with_line(0);
+ write(&mut rtc, 0x0b, 0x22);
+
+ drop(rtc);
+ // A worker still holding the alarm state keeps the line's sender open.
+ assert_eq!(
+ changes.recv_timeout(Duration::from_secs(5)),
+ Err(RecvTimeoutError::Disconnected)
+ );
+}
+
+#[test]
+fn enabling_aie_delivers_an_unacknowledged_alarm() {
+ let (mut rtc, clock, changes) = rtc_with_line(0);
+ write(&mut rtc, 0x01, 1);
+ write(&mut rtc, 0x0b, 0x22);
+ advance(&clock, NANOS);
+ let wait = Duration::from_secs(5);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, true)));
+ write(&mut rtc, 0x0b, 0x02);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, false)));
+ write(&mut rtc, 0x0b, 0x22);
+ assert_eq!(
+ changes.recv_timeout(Duration::from_millis(250)),
+ Ok((8, true))
+ );
+ assert_eq!(read(&mut rtc, 0x0c), 0xa0);
+ assert_eq!(changes.recv_timeout(wait), Ok((8, false)));
+ assert_eq!(read(&mut rtc, 0x0c), 0);
+}
+
+#[test]
+fn amd_set_only_write_changes_january_31_to_february_28() {
+ let (mut rtc, clock) = rtc_at(1_769_860_799); // 2026-01-31 23:59:59 UTC
+ set_time_amd(&mut rtc, [0x26, 0x02, 0x28, 0x12, 0x34, 0x56]);
+ assert_eq!(
+ &time(&mut rtc)[..7],
+ &[0x56, 0x34, 0x12, 0x07, 0x28, 0x02, 0x26]
+ );
+ advance(&clock, NANOS / 2);
+ assert_eq!(read(&mut rtc, 0x00), 0x57);
+}
+
+#[test]
+fn a_failed_alarm_irq_stops_the_vm_and_the_worker() {
+ struct BrokenLine(std::sync::atomic::AtomicUsize);
+ impl IrqChip for BrokenLine {
+ fn set_line(&self, line: u32, level: bool) -> Result<()> {
+ assert_eq!((line, level), (8, true));
+ self.0.fetch_add(1, Ordering::SeqCst);
+ Err(crate::error::Error::Hypervisor(
+ boxlite_hypervisor::Error::SetIrqLine {
+ line,
+ source: std::io::Error::from_raw_os_error(5),
+ },
+ ))
+ }
+ }
+ let chip = Arc::new(BrokenLine(std::sync::atomic::AtomicUsize::new(0)));
+ let mut events = EventLoop::new().unwrap();
+ let sender = events.sender();
+ let clock = Arc::new(AtomicI64::new(NANOS - 1));
+ let now = Arc::clone(&clock);
+ let mut rtc = CmosRtc::new(
+ Box::new(move || now.load(Ordering::SeqCst)),
+ IrqLine::new(chip.clone(), 8),
+ sender.clone(),
+ );
+ for index in [0x01, 0x03, 0x05] {
+ write(&mut rtc, index, 0xff);
+ }
+ write(&mut rtc, 0x0b, 0x22);
+ advance(&clock, 1);
+ let event = events.wait(Some(Duration::from_secs(5))).unwrap();
+ let Some(crate::events::Event::DeviceFailed(crate::error::Error::Hypervisor(
+ boxlite_hypervisor::Error::SetIrqLine { line, source },
+ ))) = event
+ else {
+ panic!("unexpected event: {event:?}");
+ };
+ assert_eq!(line, 8);
+ assert_eq!(source.raw_os_error(), Some(5));
+ assert!(sender.is_stopping());
+ rtc.worker.take().unwrap().join().unwrap();
+ assert_eq!(chip.0.load(Ordering::SeqCst), 1);
+ assert!(events.wait(Some(Duration::ZERO)).unwrap().is_none());
+}
diff --git a/src/vmm/tests/devices/kvm.rs b/src/vmm/tests/devices/kvm.rs
index 90a465911..78a7dc3a8 100644
--- a/src/vmm/tests/devices/kvm.rs
+++ b/src/vmm/tests/devices/kvm.rs
@@ -2,8 +2,8 @@
// SPDX-License-Identifier: Apache-2.0
//! The legacy platform under a real KVM vCPU, without a kernel: a flat
-//! 32-bit guest writes COM1, reads what no device holds, and resets
-//! through the i8042.
+//! 32-bit guest writes COM1, reads the CMOS seconds and what no device
+//! holds, and resets through the i8042.
use std::{
io::{self, Write},
@@ -22,6 +22,8 @@ use crate::{
/// Where the guest stores what it read, and the byte it must never reach.
const RESULTS: u64 = 0x2000;
const AFTER_RESET: usize = 0xc;
+/// The CMOS RTC reports 2026-01-02T03:04:05Z.
+const CMOS_TIME: i64 = 1_767_323_045_000_000_000;
/// Guest serial output, shared with the test.
#[derive(Clone, Default)]
@@ -49,6 +51,11 @@ const PROGRAM: &[u8] = &[
0xba, 0x80, 0x00, 0x00, 0x00, // mov edx, 0x80: nobody's port
0xec, // in al, dx
0xa2, 0x00, 0x20, 0x00, 0x00, // mov [0x2000], al
+ 0xba, 0x70, 0x00, 0x00, 0x00, // mov edx, 0x70
+ 0xb0, 0x00, 0xee, // mov al, 0; out dx, al: CMOS seconds
+ 0xba, 0x71, 0x00, 0x00, 0x00, // mov edx, 0x71
+ 0xec, // in al, dx
+ 0xa2, 0x01, 0x20, 0x00, 0x00, // mov [0x2001], al
0xa1, 0x00, 0x00, 0x00, 0xd0, // mov eax, [0xd0000000]: nobody's MMIO
0xa3, 0x08, 0x20, 0x00, 0x00, // mov [0x2008], eax
0xc7, 0x05, 0x00, 0x00, 0x00, 0xd0, 0x78, 0x56, 0x34, 0x12, // mov dword [0xd0000000], 0x12345678
@@ -66,7 +73,7 @@ fn a_flat_guest_drives_the_legacy_platform_until_its_reset() {
let (writer, mut console) = ConsoleWorker::spawn(Box::new(output.clone()), 1024).unwrap();
let mut events = EventLoop::new().unwrap();
let mut builder = ChipsetBuilder::new(guest.vm().clone(), events.sender());
- add_legacy_devices(&mut builder, writer).unwrap();
+ add_legacy_devices(&mut builder, writer, Box::new(|| CMOS_TIME)).unwrap();
let chipset = builder.build().unwrap();
// The run stops at the first event, so the guest runs no instruction
@@ -86,6 +93,7 @@ fn a_flat_guest_drives_the_legacy_platform_until_its_reset() {
let mut results = [0u8; 0x10];
guest.read(RESULTS, &mut results);
assert_eq!(results[0], 0xff, "nobody's port reads all ones");
+ assert_eq!(results[1], 0x05, "CMOS seconds, in BCD, from the clock");
assert_eq!(&results[6..8], [0xff, 0xff], "a wide UART read is declined");
assert_eq!(&results[8..12], [0xff; 4], "nobody's MMIO reads all ones");
assert_eq!(
@@ -98,7 +106,7 @@ fn a_flat_guest_drives_the_legacy_platform_until_its_reset() {
(1, 1),
"the MMIO read and write"
);
- // 'O', 'K', the wide read, port 0x80, the MMIO read and write, and the
- // reset.
- assert_eq!(exits, 7);
+ // 'O', 'K', the wide read, port 0x80, the CMOS index and data, the MMIO
+ // read and write, and the reset.
+ assert_eq!(exits, 9);
}
diff --git a/src/vmm/tests/devices/mod.rs b/src/vmm/tests/devices/mod.rs
index 1d70e10f2..2b7657153 100644
--- a/src/vmm/tests/devices/mod.rs
+++ b/src/vmm/tests/devices/mod.rs
@@ -11,7 +11,7 @@ use std::{
time::Duration,
};
-use super::{COM1, I8042_COMMAND, I8042_DATA, add_legacy_devices};
+use super::{CMOS, COM1, I8042_COMMAND, I8042_DATA, add_legacy_devices};
use crate::{
bus::UNCLAIMED_READ,
chipset::{Chipset, ChipsetBuilder, Conflict},
@@ -70,7 +70,7 @@ impl Machine {
let (writer, console) =
ConsoleWorker::spawn(Box::new(output), DEFAULT_QUEUE_BYTES).unwrap();
let mut builder = ChipsetBuilder::new(vm.clone(), events.sender());
- add_legacy_devices(&mut builder, writer).unwrap();
+ add_legacy_devices(&mut builder, writer, Box::new(|| 0)).unwrap();
Self {
chipset: builder.build().unwrap(),
console,
@@ -161,12 +161,14 @@ fn the_legacy_ports_and_the_in_kernel_windows_are_the_only_claims() {
// The ports around each device, those between the i8042 ports, and the
// PIT's speaker port, which KVM serves and no device may take.
- for port in [0x3f7, 0x400, 0x5f, 0x61, 0x62, 0x63, 0x65, 0x80] {
+ for port in [0x3f7, 0x400, 0x6f, 0x72, 0x5f, 0x61, 0x62, 0x63, 0x65, 0x80] {
assert_eq!(machine.inb(port), UNCLAIMED_READ, "port {port:#x}");
}
- assert_eq!(machine.chipset.buses().pio.unclaimed(), (8, 0));
- // The transmitter is idle.
+ assert_eq!(machine.chipset.buses().pio.unclaimed(), (10, 0));
+ // The transmitter is idle, and CMOS register B reads 24-hour mode.
assert_eq!(machine.inb(LSR), 0x60);
+ machine.outb(CMOS, 0x0b);
+ assert_eq!(machine.inb(CMOS + 1), 0x02);
// The UART registers take byte accesses only.
let mut wide = [0; 2];
machine.chipset.buses().pio.read(COM1, &mut wide);
@@ -181,8 +183,8 @@ fn a_second_platform_conflicts_with_every_legacy_claim() {
let mut builder = ChipsetBuilder::new(vm, events.sender());
let (writer, _console) = ConsoleWorker::spawn(Box::new(Output::default()), 16).unwrap();
let (second, _second_console) = ConsoleWorker::spawn(Box::new(Output::default()), 16).unwrap();
- add_legacy_devices(&mut builder, writer).unwrap();
- add_legacy_devices(&mut builder, second).unwrap();
+ add_legacy_devices(&mut builder, writer, Box::new(|| 0)).unwrap();
+ add_legacy_devices(&mut builder, second, Box::new(|| 0)).unwrap();
let error = builder.build().err().expect("the ports are taken");
let Error::ChipsetConflicts(conflicts) = &error else {
@@ -201,6 +203,8 @@ fn a_second_platform_conflicts_with_every_legacy_claim() {
"in-kernel local APIC claims MMIO range 0xfee00000+0x1000, held by in-kernel local APIC",
"com1 claims port range 0x3f8+0x8, held by com1",
"com1 claims interrupt line 4, held by com1",
+ "cmos claims port range 0x70+0x2, held by cmos",
+ "cmos claims interrupt line 8, held by cmos",
"i8042 claims port range 0x60+0x1, held by i8042",
"i8042 claims port range 0x64+0x1, held by i8042",
]
diff --git a/src/vmm/tests/virtio/mmio.rs b/src/vmm/tests/virtio/mmio.rs
index 1ac9e63ec..c686b96c3 100644
--- a/src/vmm/tests/virtio/mmio.rs
+++ b/src/vmm/tests/virtio/mmio.rs
@@ -884,14 +884,14 @@ fn the_transport_claims_a_four_kib_window() {
}
#[test]
-fn slots_hand_out_consecutive_windows_and_lines_until_exhausted() {
+fn slots_hand_out_consecutive_windows_and_skip_the_rtc_line_until_exhausted() {
let mut slots = Slots::new();
for index in 0..Slots::CAPACITY {
let slot = slots.take().unwrap();
assert_eq!(slot.base, 0xd000_0000 + u64::from(index) * MMIO_WINDOW_LEN);
- assert_eq!(slot.gsi, 5 + index);
+ assert_eq!(slot.gsi, if index < 3 { 5 + index } else { 6 + index });
}
- assert_eq!(Slots::CAPACITY, 19);
+ assert_eq!(Slots::CAPACITY, 18);
assert!(matches!(slots.take(), Err(Error::VirtioSlotsExhausted)));
assert_eq!(
Error::VirtioSlotsExhausted.to_string(),
diff --git a/src/vmm/tests/vm/mod.rs b/src/vmm/tests/vm/mod.rs
index e462d71e4..ba698285e 100644
--- a/src/vmm/tests/vm/mod.rs
+++ b/src/vmm/tests/vm/mod.rs
@@ -1779,6 +1779,121 @@ fn a_kvm_vm_runs_until_its_guest_resets() {
assert_eq!(vm.run().unwrap(), VmExit::GuestReset);
}
+/// Exercises the production composition and boot loader at the disk limit;
+/// the backend is mocked, but none of the attached devices are test doubles.
+/// Eight disks, the balloon and the aggregate filesystem fill the slots up
+/// to and across the RTC's line, so every virtio GSI must land past GSI 8.
+#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
+#[test]
+fn rtc_coexists_with_max_disks_balloon_and_aggregate_filesystem() {
+ use boxlite_hypervisor::VcpuExit;
+ use linux_loader::loader::bootparam::boot_params;
+ use vm_memory::{Bytes, GuestAddress};
+
+ use crate::{
+ config::{DiskConfig, DiskFormat, MAX_DISKS},
+ devices::console::{ConsoleWorker, DEFAULT_QUEUE_BYTES},
+ x86_boot_layout::PageSize,
+ };
+
+ let directory = tempfile::tempdir().unwrap();
+ let kernel = directory.path().join("kernel.elf");
+ std::fs::write(&kernel, crate::boot::elf::tests::fixture()).unwrap();
+ let disks: Vec<_> = (0..MAX_DISKS)
+ .map(|index| {
+ let block_id = format!("disk-{index}");
+ let path = directory.path().join(&block_id);
+ std::fs::File::create(&path).unwrap().set_len(4096).unwrap();
+ DiskConfig {
+ block_id,
+ path,
+ format: DiskFormat::Raw,
+ read_only: false,
+ }
+ })
+ .collect();
+ let mut configuration = config(1, 2);
+ configuration.kernel = kernel;
+ configuration.cmdline = "console=ttyS0".into();
+ configuration.disks = disks;
+ configuration.filesystem = Some(crate::FsConfig {
+ tag: "aggregate-test".into(),
+ shares: vec![crate::FsShareConfig {
+ name: "BoxLiteShared".into(),
+ path: directory.path().to_owned(),
+ read_only: false,
+ }],
+ });
+ let (writer, mut console) =
+ ConsoleWorker::spawn(Box::new(io::sink()), DEFAULT_QUEUE_BYTES).unwrap();
+ let leaf = PageSize::Mib.checked(false).unwrap();
+ let vm = Vm::with_devices(
+ configuration,
+ || Ok(MockVm::new()),
+ |ram, config| crate::boot::prepare(ram, config, leaf).map(|setup| setup.boot_regs),
+ |chipset, ctx, config| crate::devices::add_all(chipset, ctx, config, writer),
+ )
+ .expect("real RTC and all configured virtio devices must compose without conflicts");
+
+ let memory = vm.ram.memory().memory();
+ let params: boot_params = memory.read_obj(GuestAddress(vm.boot_regs.rsi)).unwrap();
+ let mut line = vec![0; params.hdr.cmdline_size as usize];
+ memory
+ .read_slice(&mut line, GuestAddress(params.hdr.cmd_line_ptr.into()))
+ .unwrap();
+ let line = std::ffi::CStr::from_bytes_with_nul(&line)
+ .unwrap()
+ .to_str()
+ .unwrap();
+ let (announcements, _) = line.split_once("console=ttyS0").unwrap();
+ let announcements: Vec<_> = announcements.split_whitespace().collect();
+ assert_eq!(announcements.len(), MAX_DISKS + 2);
+ let gsis = [5, 6, 7, 9, 10, 11, 12, 13, 14, 15];
+ let chipset = vm.chipset.as_ref().unwrap();
+ for (index, argument) in announcements.iter().enumerate() {
+ let base = 0xd000_0000 + index as u64 * 0x1000;
+ assert_eq!(
+ *argument,
+ format!("virtio_mmio.device=4K@{base:#x}:{}", gsis[index])
+ );
+ let read = |offset, bytes: &mut [u8]| {
+ assert!(
+ chipset
+ .dispatch(VcpuExit::MmioRead {
+ guest_addr: base + offset,
+ bytes,
+ })
+ .is_none()
+ );
+ };
+ let mut id = [0; 4];
+ read(8, &mut id);
+ assert_eq!(
+ u32::from_le_bytes(id),
+ if index < MAX_DISKS {
+ 2
+ } else if index == MAX_DISKS {
+ 5
+ } else {
+ 26
+ }
+ );
+ }
+ // Register D's valid-RAM bit identifies the real CMOS device at its ports.
+ chipset.dispatch(VcpuExit::IoOut {
+ port: 0x70,
+ bytes: &[0x0d],
+ });
+ let mut status = [0];
+ chipset.dispatch(VcpuExit::IoIn {
+ port: 0x71,
+ bytes: &mut status,
+ });
+ assert_eq!(status, [0x80]);
+ drop(vm);
+ console.finish();
+}
+
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[test]
fn aggregate_filesystem_is_announced_and_exposes_its_transport_config() {