Skip to main content

strat9_kernel/s9vm/
emulate.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! s9vm : in-kernel emulation of a minimal guest device set.
24//!
25//! Every access a guest makes to the legacy PIC pair, to the local APIC page
26//! or to the I/O APIC page causes a VM exit. Reporting those exits to policy
27//! would move the whole device model into the ABI, cost two world switches per
28//! interrupt acknowledgement, and let a guest drive the host scheduling with
29//! device traffic. The kernel therefore keeps a small model of these devices
30//! and *replays* the faulting instruction: the guest never observes the exit.
31//!
32//! # Contents
33//!
34//! - [`PhysMemory`]: the only side effect of the module (physical memory
35//!   access); the kernel uses the higher-half direct map, the tests a byte
36//!   vector;
37//! - [`MemoryView`]: guest-linear and guest-physical reads/writes, built on the
38//!   two page-table walks ([`walk_second_level`], [`walk_guest`]);
39//! - [`GuestContext`]: the few vCPU facts the replay needs (general registers,
40//!   instruction pointer, `CR3`, paging state);
41//! - [`Devices`]: the modeled devices;
42//! - [`handle_exit`]: the entry point, called once per exit, which returns
43//!   whether the exit was fully consumed.
44//!
45//! Everything here is pure apart from `PhysMemory`: page walks, instruction
46//! replay and device behaviour are all covered by host tests. The kernel
47//! supplies `PhysMemory` and `GuestContext` (see `machine.rs`).
48
49use alloc::vec::Vec;
50
51use super::{
52    apic::{reg as apic_reg, x2apic, LocalApic, TSC_DEADLINE_MSR},
53    decode::{self, Decoded, MemoryAccess, PortAccess},
54    dma::{self, Dma},
55    exit::ExitClass,
56    fdc::{self, FloppyController},
57    fwcfg::{self, FwCfg},
58    hpet::{self, Hpet},
59    ioapic::{IoApic, PIN_COUNT},
60    keyboard::KeyboardController,
61    msr::MsrModel,
62    pci::{self, PciHostBridge},
63    pic::Pic,
64    pit::{self, Pit},
65    rtc::{self, CmosRtc},
66    system::SystemControl,
67    uart::{self, Uart},
68    vga::Vga,
69    virtio::QueueMemory,
70    virtio_blk::VirtioBlk,
71    virtio_console::VirtioConsole,
72    virtio_net::VirtioNet,
73};
74
75/// Page size of the second-level and guest page tables.
76pub const PAGE_SIZE: u64 = 4096;
77/// Page offset mask.
78const PAGE_OFFSET_MASK: u64 = PAGE_SIZE - 1;
79/// Bits of an EPT (second-level) table entry holding the physical address.
80const EPT_ADDR_MASK: u64 = 0x000F_FFFF_FFFF_F000;
81/// Physical address mask for a 2 MiB EPT entry.
82const EPT_2M_ADDR_MASK: u64 = 0x000F_FFFF_FFE0_0000;
83/// Physical address mask for a 1 GiB EPT entry.
84const EPT_1G_ADDR_MASK: u64 = 0x000F_FFFF_C000_0000;
85/// Bits of a guest table entry holding the physical address.
86const GUEST_ADDR_MASK: u64 = 0x000F_FFFF_FFFF_F000;
87/// Physical address mask for a 2 MiB guest page.
88const GUEST_2M_ADDR_MASK: u64 = 0x000F_FFFF_FFE0_0000;
89/// Physical address mask for a 1 GiB guest page.
90const GUEST_1G_ADDR_MASK: u64 = 0x000F_FFFF_C000_0000;
91/// Large-page bit of a PDPTE/PDE.
92const LARGE_PAGE: u64 = 1 << 7;
93/// Present bit of a guest table entry.
94const GUEST_PRESENT: u64 = 1 << 0;
95/// Readable EPT entry (bit 0) : an EPT walk only succeeds on readable memory.
96const EPT_READ: u64 = 1 << 0;
97
98/// Base of the local APIC page in the conventional guest memory map.
99pub const APIC_BASE: u64 = 0xFEE0_0000;
100/// Base of the I/O APIC page in the conventional guest memory map.
101pub const IOAPIC_BASE: u64 = 0xFEC0_0000;
102/// Base of the virtio console transport page (virtio-mmio layout).
103pub const CONSOLE_BASE: u64 = 0xFEB0_0000;
104/// Base of the virtio block transport page (virtio-mmio layout).
105pub const BLK_BASE: u64 = 0xFEB0_1000;
106/// Interrupt vector used to signal the block device.
107pub const BLK_IRQ_VECTOR: u8 = 0x22;
108/// Base of the virtio network transport page (virtio-mmio layout).
109pub const NET_BASE: u64 = 0xFEB0_2000;
110/// Interrupt vector used to signal the network device.
111pub const NET_IRQ_VECTOR: u8 = 0x23;
112/// I/O APIC line wired to the console.
113pub const CONSOLE_IRQ_LINE: usize = 16;
114/// I/O APIC line wired to the block device.
115pub const BLK_IRQ_LINE: usize = 17;
116/// I/O APIC line wired to the network device.
117pub const NET_IRQ_LINE: usize = 18;
118/// Interrupt vector used to signal the console.
119///
120/// The virtio-mmio transport does not define its own interrupt: the platform
121/// wires the device to an interrupt line. Until the policy layer routes device
122/// lines through the I/O APIC, the kernel uses a fixed vector, which keeps the
123/// device usable by a driver that programs the corresponding IDT entry.
124pub const CONSOLE_IRQ_VECTOR: u8 = 0x21;
125/// First and last MSR of the x2APIC window (`0x800..=0x8FF`).
126pub const X2APIC_MSR_FIRST: u32 = 0x800;
127pub const X2APIC_MSR_LAST: u32 = 0x8FF;
128
129/// Base of the legacy PIC ports.
130pub const PIC_BASE_PORT: u16 = 0x20;
131/// POST/delay diagnostic port: writes are discarded, reads return zero.
132pub const POST_PORT: u16 = 0x80;
133/// QEMU debug console port (`-debugcon`): SeaBIOS' `dprintf` output.
134pub const DEBUG_PORT: u16 = 0x402;
135
136/// Interrupt vector the I/O APIC delivers for the 8254 timer line.
137pub const PIT_IRQ_VECTOR: u8 = 0x20;
138/// Interrupt vector the I/O APIC delivers for the COM1 line.
139pub const UART_IRQ_VECTOR: u8 = 0x24;
140/// Interrupt vector the I/O APIC delivers for the RTC line.
141pub const RTC_IRQ_VECTOR: u8 = 0x28;
142
143/// Global system interrupt an ISA interrupt line is wired to.
144///
145/// The MADT's interrupt source overrides describe the non-identity wiring
146/// (notably `IRQ0 -> GSI2` for the 8254 cascade); every other line is
147/// identity-mapped. Raising a device line on the I/O APIC must use the GSI,
148/// not the ISA number, or a guest that follows the firmware tables never
149/// receives the interrupt.
150pub fn isa_gsi(irq: u8) -> usize {
151    for entry in &super::acpi::ISA_OVERRIDES {
152        if entry.irq_source == irq {
153            return entry.gsi as usize;
154        }
155    }
156    usize::from(irq)
157}
158
159/// ISA interrupt line wired to a global system interrupt.
160///
161/// Inverse of [`isa_gsi`]: a device raises a *pin* (a GSI) and the 8259 pair is
162/// programmed with the *ISA IRQ* numbers, so the model needs the reverse
163/// mapping to drive both interrupt controllers. GSIs above the ISA range
164/// (16..) have no 8259 line and return `None`.
165pub fn gsi_isa_irq(gsi: usize) -> Option<u8> {
166    for entry in &super::acpi::ISA_OVERRIDES {
167        if entry.gsi as usize == gsi {
168            return Some(entry.irq_source);
169        }
170    }
171    if gsi < 16 {
172        Some(gsi as u8)
173    } else {
174        None
175    }
176}
177
178/// Emulation error. Any error means "not emulated here": the caller reports
179/// the exit to policy, exactly as if this module did not exist.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub enum EmuError {
182    /// The access targets memory that cannot be translated.
183    Unmapped,
184    /// The instruction could not be fetched or decoded.
185    BadInstruction,
186    /// The instruction, port or device is outside the modeled subset.
187    Unsupported,
188}
189
190/// Physical memory access used by the page walks and the instruction replay.
191///
192/// Implementations must be safe to call with any physical address obtained
193/// from a table walk: the kernel maps the whole physical address space in the
194/// higher-half direct map, and the tests back it with a byte vector.
195pub trait PhysMemory {
196    /// Copies `out.len()` bytes from `phys` into `out`.
197    fn read_bytes(&mut self, phys: u64, out: &mut [u8]) -> bool;
198    /// Reads a little-endian 64-bit value.
199    fn read_u64(&mut self, phys: u64) -> Option<u64> {
200        let mut bytes = [0u8; 8];
201        if self.read_bytes(phys, &mut bytes) {
202            Some(u64::from_le_bytes(bytes))
203        } else {
204            None
205        }
206    }
207    /// Copies `bytes` to `phys`.
208    fn write_bytes(&mut self, phys: u64, bytes: &[u8]) -> bool;
209}
210
211/// Walks the second-level (EPT) tables and returns the host-physical address
212/// backing `gpa`, with the size of the page that mapped it.
213///
214/// `ept_root` is the `EPT_POINTER` value: only bits 51:12 are significant for
215/// the walk (the low bits carry the memory type, the walk length and the
216/// accessed/dirty policy).
217pub fn walk_second_level<M: PhysMemory + ?Sized>(
218    memory: &mut M,
219    ept_root: u64,
220    gpa: u64,
221) -> Option<(u64, u64)> {
222    let table = ept_root & EPT_ADDR_MASK;
223
224    let entry = memory.read_u64(table + index(gpa, 39) * 8)?;
225    if entry & EPT_READ == 0 {
226        return None;
227    }
228    let table = entry & EPT_ADDR_MASK;
229
230    let entry = memory.read_u64(table + index(gpa, 30) * 8)?;
231    if entry & EPT_READ == 0 {
232        return None;
233    }
234    if entry & LARGE_PAGE != 0 {
235        // 1 GiB page: the whole address is taken from this entry.
236        return Some(((entry & EPT_1G_ADDR_MASK) | (gpa & 0x3FFF_FFFF), 1 << 30));
237    }
238    let table = entry & EPT_ADDR_MASK;
239
240    let entry = memory.read_u64(table + index(gpa, 21) * 8)?;
241    if entry & EPT_READ == 0 {
242        return None;
243    }
244    if entry & LARGE_PAGE != 0 {
245        // 2 MiB page.
246        return Some((entry & EPT_2M_ADDR_MASK | (gpa & 0x1F_FFFF), 1 << 21));
247    }
248    let table = entry & EPT_ADDR_MASK;
249
250    let entry = memory.read_u64(table + index(gpa, 12) * 8)?;
251    if entry & EPT_READ == 0 {
252        return None;
253    }
254    Some((
255        (entry & EPT_ADDR_MASK) | (gpa & PAGE_OFFSET_MASK),
256        PAGE_SIZE,
257    ))
258}
259
260/// Walks the guest page tables and returns the guest-physical address for the
261/// linear address `linear`.
262///
263/// `cr3` is the guest `CR3` (its low 12 bits are ignored); `ept_root` is used
264/// to reach the guest tables, which are themselves guest-physical. Returning
265/// `None` means the guest access cannot be resolved. When the guest has
266/// paging disabled, the linear address *is* the physical address and the
267/// caller must not use this function (see [`MemoryView`]).
268pub fn walk_guest<M: PhysMemory + ?Sized>(
269    memory: &mut M,
270    ept_root: u64,
271    cr3: u64,
272    linear: u64,
273) -> Option<u64> {
274    let table = cr3 & EPT_ADDR_MASK;
275    let entry = read_physical_u64(memory, ept_root, table + index(linear, 39) * 8)?;
276    if entry & GUEST_PRESENT == 0 {
277        return None;
278    }
279    let table = entry & GUEST_ADDR_MASK;
280
281    let entry = read_physical_u64(memory, ept_root, table + index(linear, 30) * 8)?;
282    if entry & GUEST_PRESENT == 0 {
283        return None;
284    }
285    if entry & LARGE_PAGE != 0 {
286        return Some((entry & GUEST_1G_ADDR_MASK) | (linear & 0x3FFF_FFFF));
287    }
288    let table = entry & GUEST_ADDR_MASK;
289
290    let entry = read_physical_u64(memory, ept_root, table + index(linear, 21) * 8)?;
291    if entry & GUEST_PRESENT == 0 {
292        return None;
293    }
294    if entry & LARGE_PAGE != 0 {
295        return Some((entry & GUEST_2M_ADDR_MASK) | (linear & 0x1F_FFFF));
296    }
297    let table = entry & GUEST_ADDR_MASK;
298
299    let entry = read_physical_u64(memory, ept_root, table + index(linear, 12) * 8)?;
300    if entry & GUEST_PRESENT == 0 {
301        return None;
302    }
303    Some((entry & GUEST_ADDR_MASK) | (linear & PAGE_OFFSET_MASK))
304}
305
306/// Reads a 64-bit value at a guest-physical address.
307fn read_physical_u64<M: PhysMemory + ?Sized>(
308    memory: &mut M,
309    ept_root: u64,
310    gpa: u64,
311) -> Option<u64> {
312    let (hpa, _) = walk_second_level(memory, ept_root, gpa & !0x7)?;
313    memory.read_u64(hpa)
314}
315
316/// Page-table index of `address` at `shift` (39, 30, 21 or 12).
317const fn index(address: u64, shift: u32) -> u64 {
318    (address >> shift) & 0x1FF
319}
320
321/// The vCPU facts the replay needs.
322///
323/// Register indices follow the x86 encoding order: `0` = RAX, `1` = RCX,
324/// `2` = RDX, `3` = RBX, `4` = RSP, `5` = RBP, `6` = RSI, `7` = RDI, then
325/// `8..=15` = R8..R15.
326pub trait GuestContext {
327    /// Reads a general-purpose register.
328    fn gpr(&self, register: u8) -> u64;
329    /// Writes a general-purpose register.
330    fn set_gpr(&mut self, register: u8, value: u64);
331    /// Guest instruction pointer.
332    fn rip(&self) -> u64;
333    /// Sets the guest instruction pointer.
334    fn set_rip(&mut self, rip: u64);
335    /// Guest `CR3`.
336    fn cr3(&self) -> u64;
337    /// True if guest paging is active (long mode with `CR0.PG` set).
338    fn paging(&self) -> bool;
339
340    /// Guest `RFLAGS`. The direction flag drives string-I/O addressing.
341    fn rflags(&self) -> u64 {
342        0
343    }
344
345    /// Base of the `ES` segment (destination of `INS`).
346    fn es_base(&self) -> u64 {
347        0
348    }
349
350    /// Base of the `DS` segment (source of `OUTS`).
351    fn ds_base(&self) -> u64 {
352        0
353    }
354
355    /// Base of the `CS` segment (instruction fetch).
356    fn cs_base(&self) -> u64 {
357        0
358    }
359
360    /// Per-vCPU MSR shadow model, when the caller provides one.
361    ///
362    /// The default is `None`, which makes replayed `RDMSR`/`WRMSR` exits
363    /// unhandleable (`Ok(false)`): the caller must then report them to policy.
364    /// A caller that omits the model can never let an unmodelled guest MSR
365    /// write reach the host MSR file, because the MSR bitmap intercepts all
366    /// writes and this path fails closed.
367    fn msr_model(&mut self) -> Option<&mut MsrModel> {
368        None
369    }
370}
371
372/// A window on guest memory.
373///
374/// Linear addresses go through the guest page tables when paging is active;
375/// physical addresses go through the second-level tables. Accesses crossing a
376/// page boundary are split, so an instruction fetch near the end of a page is
377/// still valid.
378pub struct MemoryView<'a> {
379    memory: &'a mut dyn PhysMemory,
380    ept_root: u64,
381    cr3: u64,
382    paging: bool,
383}
384
385impl<'a> MemoryView<'a> {
386    /// Builds a view. `ept_root` is the `EPT_POINTER` value of the vCPU.
387    pub fn new(memory: &'a mut dyn PhysMemory, ept_root: u64, cr3: u64, paging: bool) -> Self {
388        Self {
389            memory,
390            ept_root,
391            cr3,
392            paging,
393        }
394    }
395
396    /// Translates a linear address to a host-physical address.
397    fn translate(&mut self, linear: u64) -> Option<u64> {
398        let gpa = if self.paging {
399            walk_guest(self.memory, self.ept_root, self.cr3, linear)?
400        } else {
401            linear
402        };
403        let (hpa, _) = walk_second_level(self.memory, self.ept_root, gpa)?;
404        Some(hpa)
405    }
406
407    /// Reads `out.len()` bytes starting at a linear address.
408    pub fn read(&mut self, linear: u64, out: &mut [u8]) -> bool {
409        let mut done = 0usize;
410        while done < out.len() {
411            let address = linear.wrapping_add(done as u64);
412            let Some(hpa) = self.translate(address) else {
413                return false;
414            };
415            let chunk = core::cmp::min(
416                out.len() - done,
417                (PAGE_SIZE - (address & PAGE_OFFSET_MASK)) as usize,
418            );
419            if !self.memory.read_bytes(hpa, &mut out[done..done + chunk]) {
420                return false;
421            }
422            done += chunk;
423        }
424        true
425    }
426
427    /// Writes `bytes` starting at a linear address.
428    pub fn write(&mut self, linear: u64, bytes: &[u8]) -> bool {
429        let mut done = 0usize;
430        while done < bytes.len() {
431            let address = linear.wrapping_add(done as u64);
432            let Some(hpa) = self.translate(address) else {
433                return false;
434            };
435            let chunk = core::cmp::min(
436                bytes.len() - done,
437                (PAGE_SIZE - (address & PAGE_OFFSET_MASK)) as usize,
438            );
439            if !self.memory.write_bytes(hpa, &bytes[done..done + chunk]) {
440                return false;
441            }
442            done += chunk;
443        }
444        true
445    }
446
447    /// Reads `out.len()` bytes at a guest-physical address.
448    pub fn read_physical(&mut self, gpa: u64, out: &mut [u8]) -> bool {
449        let mut done = 0usize;
450        while done < out.len() {
451            let address = gpa.wrapping_add(done as u64);
452            let Some((hpa, _)) = walk_second_level(self.memory, self.ept_root, address) else {
453                return false;
454            };
455            let chunk = core::cmp::min(
456                out.len() - done,
457                (PAGE_SIZE - (address & PAGE_OFFSET_MASK)) as usize,
458            );
459            if !self.memory.read_bytes(hpa, &mut out[done..done + chunk]) {
460                return false;
461            }
462            done += chunk;
463        }
464        true
465    }
466
467    /// Writes `bytes` at a guest-physical address.
468    pub fn write_physical(&mut self, gpa: u64, bytes: &[u8]) -> bool {
469        let mut done = 0usize;
470        while done < bytes.len() {
471            let address = gpa.wrapping_add(done as u64);
472            let Some((hpa, _)) = walk_second_level(self.memory, self.ept_root, address) else {
473                return false;
474            };
475            let chunk = core::cmp::min(
476                bytes.len() - done,
477                (PAGE_SIZE - (address & PAGE_OFFSET_MASK)) as usize,
478            );
479            if !self.memory.write_bytes(hpa, &bytes[done..done + chunk]) {
480                return false;
481            }
482            done += chunk;
483        }
484        true
485    }
486
487    /// Fetches and decodes the instruction at the guest instruction pointer.
488    fn fetch(&mut self, guest: &dyn GuestContext) -> Result<Decoded, EmuError> {
489        let ip = guest.rip();
490        // Instruction fetch is `CS.base + IP` in real and 16-bit protected
491        // mode. SeaBIOS' 16-bit code runs with `CS.base = 0xF0000`, so reading
492        // at RIP alone would decode bytes from the wrong address.
493        let linear = guest.cs_base().wrapping_add(ip);
494        let mut bytes = [0u8; decode::MAX_INSTRUCTION];
495        if !self.read(linear, &mut bytes) {
496            return Err(EmuError::Unmapped);
497        }
498        // The decoder's `next_rip` is an IP offset, not a linear address.
499        decode::decode(&bytes, ip, |register| guest.gpr(register))
500            .map_err(|_| EmuError::BadInstruction)
501    }
502}
503
504impl QueueMemory for MemoryView<'_> {
505    fn read_gpa(&mut self, gpa: u64, out: &mut [u8]) -> bool {
506        self.read_physical(gpa, out)
507    }
508
509    fn write_gpa(&mut self, gpa: u64, bytes: &[u8]) -> bool {
510        self.write_physical(gpa, bytes)
511    }
512}
513
514/// PCI device slots used by the modeled virtio functions (bus 0).
515pub const PCI_CONSOLE_SLOT: u8 = 2;
516/// PCI slot of the block function.
517pub const PCI_BLK_SLOT: u8 = 3;
518/// PCI slot of the network function.
519pub const PCI_NET_SLOT: u8 = 4;
520
521/// Device model owned by a world: the chipset devices shared by all its
522/// vCPUs. The local APIC is per-vCPU and lives in the vCPU slot; the exit
523/// handlers receive it separately.
524#[derive(Debug)]
525pub struct Devices {
526    /// Cascaded 8259A pair.
527    pub pic: Pic,
528    /// I/O APIC (MMIO page).
529    pub ioapic: IoApic,
530    /// 8254 programmable interval timer (legacy ports 0x40..=0x43).
531    pub pit: Pit,
532    /// MC146818 CMOS real-time clock (ports 0x70/0x71).
533    pub rtc: CmosRtc,
534    /// 16550A serial port, COM1 (ports 0x3F8..=0x3FF).
535    pub uart: Uart,
536    /// 8042 keyboard controller (ports 0x60/0x64).
537    pub keyboard: KeyboardController,
538    /// VGA register file and status port (0x3B0..=0x3DF).
539    pub vga: Vga,
540    /// 8237 DMA controller register files (0x00..=0x0F, 0x81..=0x8F, 0xC0..=0xDF).
541    pub dma: Dma,
542    /// 82077AA floppy controller and its 1.44 MiB drive.
543    pub fdc: FloppyController,
544    /// Chipset system-control ports (`0x92` A20, `0xCF9` reset).
545    pub system: SystemControl,
546    /// QEMU `fw_cfg` selector/data pair.
547    pub fw_cfg: FwCfg,
548    /// SeaBIOS `dprintf` output captured from the QEMU debug port `0x402`.
549    debug_con: Vec<u8>,
550    /// PCI host bridge: configuration mechanism #1 and the virtio functions
551    /// the guest discovers through it (no MSI generation yet).
552    pub pci: PciHostBridge,
553    /// High-precision event timer (MMIO page at `0xFED0_0000`).
554    pub hpet: Hpet,
555    /// Virtio console (MMIO transport page).
556    pub console: VirtioConsole,
557    /// Virtio block device (MMIO transport page).
558    pub blk: VirtioBlk,
559    /// Virtio network device (MMIO transport page).
560    pub net: VirtioNet,
561    /// Deliver ISA interrupt lines to the 8259 pair only.
562    ///
563    /// A PC firmware (SeaBIOS, a DOS ROM) installs its `INT 08h`/`INT 0Eh`
564    /// handlers and expects the legacy vectors `0x08..=0x0F`. The local-APIC
565    /// delivery path reserves vectors below `0x10`, so such a guest needs the
566    /// runner to acknowledge the 8259 and inject the programmed vector itself.
567    /// When this flag is set, [`set_device_line`] no longer injects the I/O
568    /// APIC vector and [`flush_pic`] leaves the request in the `IRR` for the
569    /// runner.
570    legacy_pic: bool,
571    /// One-shot delay before the next legacy IRQ delivery.
572    ///
573    /// The floppy controller completes a command instantly in the model, while
574    /// real hardware takes long enough for SeaBIOS to enter `floppy_wait_irq`
575    /// and clear its BDA flag before the interrupt arrives. One preemption
576    /// interval of grace reproduces that ordering; the request stays in the
577    /// 8259 `IRR` meanwhile.
578    legacy_irq_grace: u8,
579}
580
581impl Devices {
582    /// Creates the device model.
583    ///
584    /// The I/O APIC redirection table is pre-programmed for the device lines
585    /// (`CONSOLE_IRQ_LINE`, `BLK_IRQ_LINE`, `NET_IRQ_LINE`) with the default
586    /// vectors and unmasked; the guest may reprogram them, and the kernel
587    /// reads the table when a device raises its line.
588    pub fn new() -> Self {
589        Self::new_with_virtio(true)
590    }
591
592    /// Creates the device model of a **legacy PC** with no PCI virtio
593    /// functions.
594    ///
595    /// A real firmware enumerates every PCI function and attaches the drivers
596    /// it knows; the s9vm virtio functions are modern virtio-pci devices, but
597    /// their BARs and capabilities are not needed to boot a floppy. Keeping
598    /// them out of the SeaBIOS world removes an entire probe path from the
599    /// firmware boot.
600    pub fn new_legacy() -> Self {
601        Self::new_with_virtio(false)
602    }
603
604    fn new_with_virtio(virtio: bool) -> Self {
605        let mut ioapic = IoApic::new(0);
606        ioapic.set_pin(CONSOLE_IRQ_LINE, CONSOLE_IRQ_VECTOR, false);
607        ioapic.set_pin(BLK_IRQ_LINE, BLK_IRQ_VECTOR, false);
608        ioapic.set_pin(NET_IRQ_LINE, NET_IRQ_VECTOR, false);
609        // Device interrupt lines are level-triggered (virtio asserts until the
610        // guest acknowledges the interrupt status): model the trigger mode so
611        // the remote-IRR/EOI path is exercised.
612        ioapic.set_pin_mode(CONSOLE_IRQ_LINE, CONSOLE_IRQ_VECTOR, false, true, false);
613        ioapic.set_pin_mode(BLK_IRQ_LINE, BLK_IRQ_VECTOR, false, true, false);
614        ioapic.set_pin_mode(NET_IRQ_LINE, NET_IRQ_VECTOR, false, true, false);
615        // Legacy devices, on the global system interrupts the MADT advertises
616        // (IRQ0 -> GSI2 for the 8254 cascade, IRQ4 serial, IRQ8 RTC). A guest
617        // that does not reprogram the redirection table still receives them;
618        // any real OS overrides these entries with its own policy.
619        let pit_pin = isa_gsi(pit::IRQ_LINE);
620        ioapic.set_pin_mode(pit_pin, PIT_IRQ_VECTOR, false, false, false);
621        let uart_pin = isa_gsi(uart::IRQ_LINE);
622        ioapic.set_pin_mode(uart_pin, UART_IRQ_VECTOR, false, true, false);
623        let rtc_pin = isa_gsi(rtc::IRQ_LINE);
624        ioapic.set_pin_mode(rtc_pin, RTC_IRQ_VECTOR, false, true, false);
625        // PCI: one host bridge and one virtio function per modeled device. The
626        // BARs start unprogrammed (the guest assigns them, as it does on real
627        // firmware), so an MMIO window only becomes visible once the guest has
628        // written the base address.
629        let mut pci = PciHostBridge::new();
630        if virtio {
631            let _ = pci.add_virtio(PCI_CONSOLE_SLOT, pci::virtio_device_type::CONSOLE);
632            let _ = pci.add_virtio(PCI_BLK_SLOT, pci::virtio_device_type::BLOCK);
633            let _ = pci.add_virtio(PCI_NET_SLOT, pci::virtio_device_type::NET);
634        }
635        Self {
636            pic: Pic::new(),
637            ioapic,
638            pit: Pit::new(),
639            rtc: CmosRtc::new(),
640            uart: Uart::new(),
641            keyboard: KeyboardController::new(),
642            vga: Vga::new(),
643            dma: Dma::new(),
644            fdc: FloppyController::new(),
645            system: SystemControl::new(),
646            fw_cfg: FwCfg::new(),
647            debug_con: Vec::new(),
648            pci,
649            hpet: Hpet::new(),
650            console: VirtioConsole::new(),
651            blk: VirtioBlk::new(64 * 1024),
652            net: VirtioNet::new(),
653            legacy_pic: false,
654            legacy_irq_grace: 0,
655        }
656    }
657
658    /// Loads the floppy image the controller serves.
659    pub fn load_floppy(&mut self, image: &[u8]) {
660        self.fdc.load_image(image);
661    }
662
663    /// Registers a `fw_cfg` file for the firmware (for example a VGA option
664    /// ROM under `vgaroms/vgabios-stdvga.bin`).
665    pub fn add_fw_cfg_file(&mut self, name: &str, data: &[u8]) {
666        let _ = self.fw_cfg.add_file(name, data);
667    }
668
669    /// Takes the bytes the firmware wrote to the QEMU debug console.
670    pub fn drain_debug_con(&mut self) -> Vec<u8> {
671        core::mem::take(&mut self.debug_con)
672    }
673
674    /// Selects legacy 8259 interrupt delivery (see the field documentation).
675    pub fn set_legacy_pic(&mut self, enabled: bool) {
676        self.legacy_pic = enabled;
677    }
678
679    /// True when legacy 8259 delivery is selected.
680    pub const fn legacy_pic(&self) -> bool {
681        self.legacy_pic
682    }
683
684    /// Delays the next legacy IRQ delivery by one preemption interval.
685    pub fn defer_legacy_irq(&mut self) {
686        self.legacy_irq_grace = 1;
687    }
688
689    /// Consumes one legacy-IRQ grace interval. Returns true while delivery
690    /// must still be postponed.
691    pub fn legacy_irq_deferred(&mut self) -> bool {
692        if self.legacy_irq_grace == 0 {
693            return false;
694        }
695        self.legacy_irq_grace = 0;
696        true
697    }
698
699    /// True if the port belongs to a device modeled here.
700    pub fn handles_port(port: u16) -> bool {
701        port_kind(port).is_some()
702    }
703}
704
705/// True if `port` is one of the PCI configuration mechanism #1 registers.
706/// Device class serving one legacy I/O port.
707///
708/// The kernel classifies an exiting port once, instead of asking every device
709/// model in turn whether the port belongs to it. The table is also what keeps
710/// the two overlapping legacy ranges unambiguous: the system-control port
711/// `0xCF9` lives inside the PCI configuration window and must win.
712#[derive(Debug, Clone, Copy, PartialEq, Eq)]
713pub enum PortKind {
714    /// Cascaded 8259A pair.
715    Pic,
716    /// 8254 programmable interval timer.
717    Pit,
718    /// MC146818 CMOS clock.
719    Rtc,
720    /// 16550A serial port.
721    Uart,
722    /// 8042 keyboard controller.
723    Keyboard,
724    /// VGA register file.
725    Vga,
726    /// 8237 DMA controller pair.
727    Dma,
728    /// 82077 floppy controller.
729    Fdc,
730    /// A20 and reset control.
731    System,
732    /// QEMU firmware configuration interface.
733    FwCfg,
734    /// PCI configuration mechanism #1.
735    Pci,
736    /// Platform POST diagnostic port.
737    Post,
738    /// Firmware debug console port.
739    Debug,
740}
741
742/// Classifies one legacy I/O port (`None` when no device model serves it).
743pub const fn port_kind(port: u16) -> Option<PortKind> {
744    match port {
745        0x20 | 0x21 | 0xA0 | 0xA1 => Some(PortKind::Pic),
746        0x40..=0x43 => Some(PortKind::Pit),
747        0x70 | 0x71 => Some(PortKind::Rtc),
748        0x3F8..=0x3FF => Some(PortKind::Uart),
749        0x60 | 0x64 => Some(PortKind::Keyboard),
750        // 0x3B0..=0x3BF (mono) and 0x3C0..=0x3DF (colour) are adjacent.
751        0x3B0..=0x3DF => Some(PortKind::Vga),
752        0x00..=0x0F | 0x81..=0x8F | 0xC0..=0xDF => Some(PortKind::Dma),
753        0x3F0..=0x3F5 | 0x3F7 => Some(PortKind::Fdc),
754        // `0xCF9` is inside the PCI window below: it must be matched first.
755        0x92 | 0xCF9 => Some(PortKind::System),
756        0x510 | 0x511 => Some(PortKind::FwCfg),
757        0xCF8..=0xCFF => Some(PortKind::Pci),
758        0x80 => Some(PortKind::Post),
759        // QEMU firmware debug console (not the DOS `0xE9` marker port, which
760        // the DOS runner intercepts before the device model).
761        0x402 => Some(PortKind::Debug),
762        _ => None,
763    }
764}
765
766pub fn handles_pci_port(port: u16) -> bool {
767    (pci::CONFIG_ADDRESS..pci::CONFIG_ADDRESS + 4).contains(&port)
768        || (pci::CONFIG_DATA..pci::CONFIG_DATA + 4).contains(&port)
769}
770
771impl Default for Devices {
772    fn default() -> Self {
773        Self::new()
774    }
775}
776
777/// What the execution loop must do before entering the guest to deliver a
778/// pending interrupt.
779#[derive(Debug, Clone, Copy, PartialEq, Eq)]
780pub enum InterruptAction {
781    /// A deliverable vector is waiting and the guest is interruptible: inject
782    /// it at the next entry.
783    Inject,
784    /// A deliverable vector is waiting but the guest has interrupts disabled:
785    /// arm interrupt-window exiting so the vector is injected as soon as the
786    /// guest enables interrupts.
787    ArmWindow,
788    /// No vector is waiting any more: disarm interrupt-window exiting,
789    /// otherwise the processor would exit after every guest instruction.
790    DisarmWindow,
791    /// Nothing to do.
792    None,
793}
794
795/// Decides the interrupt-delivery action for one guest entry.
796///
797/// `pending` is `true` when the local APIC has a deliverable vector,
798/// `interruptible` mirrors `RFLAGS.IF`, and `window_armed` tells whether
799/// interrupt-window exiting is currently armed.
800pub const fn interrupt_action(
801    pending: bool,
802    interruptible: bool,
803    window_armed: bool,
804) -> InterruptAction {
805    match (pending, interruptible, window_armed) {
806        (true, true, _) => InterruptAction::Inject,
807        (true, false, _) => InterruptAction::ArmWindow,
808        (false, _, true) => InterruptAction::DisarmWindow,
809        (false, _, false) => InterruptAction::None,
810    }
811}
812
813/// "Blocking by STI" bit of `GUEST_INTERRUPTIBILITY_INFO`.
814pub const INTERRUPTIBILITY_STI_BLOCKING: u32 = 1 << 0;
815/// "Blocking by MOV SS" bit of `GUEST_INTERRUPTIBILITY_INFO`.
816pub const INTERRUPTIBILITY_MOV_SS_BLOCKING: u32 = 1 << 1;
817
818/// True if a pending external interrupt can be delivered in this guest state.
819///
820/// `rflags_if` mirrors `RFLAGS.IF` and `interruptibility` the control-block
821/// `GUEST_INTERRUPTIBILITY_INFO` field. Delivery is inhibited while the guest
822/// is blocked by `STI` or by `MOV SS`: injecting a vector during that window
823/// makes the processor drop it : VM-entry interruption delivery is suppressed,
824/// but the vector was already taken out of the APIC, so it is lost. The
825/// execution loop must arm interrupt-window exiting instead, so the vector is
826/// injected as soon as the shadow clears.
827pub const fn interrupt_deliverable(rflags_if: bool, interruptibility: u32) -> bool {
828    rflags_if
829        && interruptibility & (INTERRUPTIBILITY_STI_BLOCKING | INTERRUPTIBILITY_MOV_SS_BLOCKING)
830            == 0
831}
832
833/// Tries to consume an exit by replaying the faulting instruction.
834///
835/// Returns `Ok(true)` when the exit was fully handled and the guest state has
836/// been advanced: the caller can resume the guest immediately. `Ok(false)`
837/// means the exit is outside the modeled subset and must be reported to
838/// policy. An error is treated like `Ok(false)`; it exists so the caller can
839/// log why the fast path declined.
840pub fn handle_exit(
841    devices: &mut Devices,
842    apic: &mut LocalApic,
843    view: &mut MemoryView<'_>,
844    guest: &mut dyn GuestContext,
845    class: ExitClass,
846    qualification: u64,
847    guest_physical_address: u64,
848) -> Result<bool, EmuError> {
849    handle_exit_with_length(
850        devices,
851        apic,
852        view,
853        guest,
854        class,
855        qualification,
856        guest_physical_address,
857        0,
858    )
859}
860
861/// [`handle_exit`] with the instruction length needed by string port I/O.
862pub fn handle_exit_with_length(
863    devices: &mut Devices,
864    apic: &mut LocalApic,
865    view: &mut MemoryView<'_>,
866    guest: &mut dyn GuestContext,
867    class: ExitClass,
868    qualification: u64,
869    guest_physical_address: u64,
870    instruction_length: u32,
871) -> Result<bool, EmuError> {
872    match class {
873        ExitClass::IoPort => handle_port_exit(
874            devices,
875            apic,
876            view,
877            guest,
878            qualification,
879            instruction_length,
880        ),
881        ExitClass::EptViolation => handle_mmio_exit(
882            devices,
883            apic,
884            view,
885            guest,
886            qualification,
887            guest_physical_address,
888        ),
889        ExitClass::Msr => handle_msr_exit(apic, devices, view, guest),
890        _ => Ok(false),
891    }
892}
893
894/// Maximum elements moved in one replayed `INS`/`OUTS` instruction.
895///
896/// A firmware file transfer is at most a few hundred KiB; a guest asking for
897/// billions of iterations would stall the host inside a single exit (the run
898/// loop only regains control between instructions).
899const MAX_STRING_IO_ELEMENTS: u64 = 1 << 20;
900
901/// Handles an I/O instruction exit (`IN`/`OUT`).
902fn handle_port_exit(
903    devices: &mut Devices,
904    apic: &mut LocalApic,
905    view: &mut MemoryView<'_>,
906    guest: &mut dyn GuestContext,
907    qualification: u64,
908    instruction_length: u32,
909) -> Result<bool, EmuError> {
910    // Exit qualification: bits 2:0 = size - 1, bit 3 = direction (1 = IN),
911    // bits 5:4 = string/repeated, bits 31:16 = port.
912    let string = (qualification >> 4) & 0x1 != 0;
913    let repeated = (qualification >> 5) & 0x1 != 0;
914    let port = ((qualification >> 16) & 0xFFFF) as u16;
915    if string || repeated {
916        return handle_string_port(
917            devices,
918            apic,
919            view,
920            guest,
921            port,
922            qualification,
923            repeated,
924            instruction_length,
925        );
926    }
927    // Some processors/VMM combinations report `rep insb`/`rep insw` with the
928    // string bits clear. That quirk is what the firmware file transfer depends
929    // on (SeaBIOS reads the VGA ROM through `fw_cfg` with `rep insb`), so the
930    // encoding is only inspected for that data port. Every other scalar
931    // access is described completely by the exit qualification: inspecting the
932    // instruction bytes here would fetch and decode them on every legacy port
933    // exit, which is the dominant cost of a DOS boot.
934    if port == fwcfg::DATA_PORT {
935        let mut op = [0u8; 3];
936        if view.read(guest.cs_base().wrapping_add(guest.rip()), &mut op) {
937            let mut index = 0usize;
938            let rep = op[0] == 0xF3;
939            if rep {
940                index += 1;
941            }
942            let mut size = 1u8;
943            if index < op.len() && op[index] == 0x66 {
944                size = 2;
945                index += 1;
946            }
947            if index < op.len() && matches!(op[index], 0x6C..=0x6F) {
948                let is_in = matches!(op[index], 0x6C | 0x6D);
949                let synthesized = (qualification & !0x3F)
950                    | u64::from(size - 1)
951                    | (u64::from(is_in) << 3)
952                    | 0x10
953                    | if rep { 0x20 } else { 0 };
954                return handle_string_port(
955                    devices,
956                    apic,
957                    view,
958                    guest,
959                    port,
960                    synthesized,
961                    rep,
962                    instruction_length,
963                );
964            }
965        }
966    }
967    if !Devices::handles_port(port) {
968        return Ok(false);
969    }
970    let size = ((qualification & 0x7) + 1) as u8;
971    if !matches!(size, 1 | 2 | 4) {
972        return Ok(false);
973    }
974    let is_in = (qualification >> 3) & 0x1 != 0;
975    if instruction_length == 0 {
976        // No usable instruction length (some callers synthesise exits): fall
977        // back to decoding the instruction so the guest still advances.
978        let Decoded::Port(access) = view.fetch(guest)? else {
979            return Ok(false);
980        };
981        if access.port != port || access.size != size || access.write == is_in {
982            return Ok(false);
983        }
984        if !serve_port(devices, apic, view, guest, &access) {
985            return Ok(false);
986        }
987        guest.set_rip(access.next_rip);
988        return Ok(true);
989    }
990    // Scalar IN/OUT always uses the accumulator; the qualification gives the
991    // size and direction, so no instruction decode is needed.
992    let access = PortAccess {
993        port,
994        size,
995        write: !is_in,
996        register: 0,
997        next_rip: guest.rip().wrapping_add(u64::from(instruction_length)),
998    };
999    if !serve_port(devices, apic, view, guest, &access) {
1000        return Ok(false);
1001    }
1002    guest.set_rip(access.next_rip);
1003    Ok(true)
1004}
1005
1006/// Handles a repeated or single `INS`/`OUTS` string transfer.
1007///
1008/// String port I/O is the transport of the QEMU `fw_cfg` interface: SeaBIOS
1009/// reads firmware files with `rep insb`, so the replay must move `RCX`
1010/// elements between the port and `ES:DI`/`DS:SI`, honouring the direction flag.
1011/// The port itself is served by the normal device model, one element at a
1012/// time, so side effects (a serial byte, a `fw_cfg` cursor) happen in order.
1013fn handle_string_port(
1014    devices: &mut Devices,
1015    apic: &mut LocalApic,
1016    view: &mut MemoryView<'_>,
1017    guest: &mut dyn GuestContext,
1018    port: u16,
1019    qualification: u64,
1020    repeated: bool,
1021    instruction_length: u32,
1022) -> Result<bool, EmuError> {
1023    if !Devices::handles_port(port) {
1024        return Ok(false);
1025    }
1026    let size = ((qualification & 0x7) + 1) as u8;
1027    if !matches!(size, 1 | 2 | 4) {
1028        return Ok(false);
1029    }
1030    let is_in = (qualification >> 3) & 0x1 != 0;
1031    let mut remaining = if repeated { guest.gpr(1) } else { 1 };
1032    if remaining > MAX_STRING_IO_ELEMENTS {
1033        return Ok(false);
1034    }
1035    let negative = guest.rflags() & (1 << 10) != 0;
1036    let step = i64::from(size) * if negative { -1 } else { 1 };
1037    let base = if is_in {
1038        guest.es_base()
1039    } else {
1040        guest.ds_base()
1041    };
1042    let mut index = if is_in { guest.gpr(7) } else { guest.gpr(6) };
1043
1044    while remaining != 0 {
1045        let address = base.wrapping_add(index);
1046        if is_in {
1047            let value;
1048            if port == fwcfg::DATA_PORT {
1049                if size != 1 {
1050                    return Ok(false);
1051                }
1052                value = u64::from(devices.fw_cfg.read_byte());
1053            } else {
1054                let access = PortAccess {
1055                    port,
1056                    size,
1057                    write: false,
1058                    register: 0,
1059                    next_rip: guest.rip(),
1060                };
1061                if !serve_port(devices, apic, view, guest, &access) {
1062                    return Ok(false);
1063                }
1064                value = guest.gpr(0);
1065            }
1066            let bytes = value.to_le_bytes();
1067            if !view.write(address, &bytes[..usize::from(size)]) {
1068                return Ok(false);
1069            }
1070        } else {
1071            let mut bytes = [0u8; 8];
1072            if !view.read(address, &mut bytes[..usize::from(size)]) {
1073                return Ok(false);
1074            }
1075            let previous = guest.gpr(0);
1076            let mask: u64 = match size {
1077                1 => 0xFF,
1078                2 => 0xFFFF,
1079                _ => 0xFFFF_FFFF,
1080            };
1081            let value = u64::from_le_bytes(bytes);
1082            guest.set_gpr(0, (previous & !mask) | (value & mask));
1083            let access = PortAccess {
1084                port,
1085                size,
1086                write: true,
1087                register: 0,
1088                next_rip: guest.rip(),
1089            };
1090            if !serve_port(devices, apic, view, guest, &access) {
1091                return Ok(false);
1092            }
1093        }
1094        index = (index as i64).wrapping_add(step) as u64;
1095        remaining -= 1;
1096    }
1097    if is_in {
1098        guest.set_gpr(7, index);
1099    } else {
1100        guest.set_gpr(6, index);
1101    }
1102    if repeated {
1103        guest.set_gpr(1, 0);
1104    }
1105    let length = if instruction_length == 0 {
1106        2
1107    } else {
1108        instruction_length
1109    };
1110    guest.set_rip(guest.rip().wrapping_add(u64::from(length)));
1111    Ok(true)
1112}
1113
1114/// Applies one decoded port access to the device model.
1115///
1116/// Byte-wide legacy devices (8259, 8254, CMOS RTC, 16550) are served here;
1117/// device interrupt lines are re-evaluated after the access so a guest that
1118/// unmasks an interrupt sees it without another exit.
1119fn serve_port(
1120    devices: &mut Devices,
1121    apic: &mut LocalApic,
1122    view: &mut MemoryView<'_>,
1123    guest: &mut dyn GuestContext,
1124    access: &PortAccess,
1125) -> bool {
1126    // Classify the port once. `handle_port_exit` and `handle_string_port`
1127    // already called `Devices::handles_port`, so probing every device model
1128    // again here re-derived the same answer on every legacy exit — the table is
1129    // now the only source of that decision.
1130    let kind = match port_kind(access.port) {
1131        Some(kind) => kind,
1132        None => return false,
1133    };
1134    if kind == PortKind::Pic {
1135        // The 8259A pair is byte-wide; a wider access is not PC-compatible.
1136        if access.size != 1 {
1137            return false;
1138        }
1139        if access.write {
1140            let value = (guest.gpr(access.register) & 0xFF) as u8;
1141            devices.pic.write(access.port, value);
1142            // Unmasking a line or ending an interrupt can make a pending
1143            // request deliverable: re-evaluate the cascade immediately so the
1144            // guest sees it without waiting for another device event.
1145            flush_pic(devices, apic);
1146        } else {
1147            let Some(value) = devices.pic.read(access.port) else {
1148                return false;
1149            };
1150            write_register(guest, access.register, access.size, u64::from(value));
1151        }
1152        return true;
1153    }
1154    if kind == PortKind::Pit {
1155        // The 8254 is byte-wide.
1156        if access.size != 1 {
1157            return false;
1158        }
1159        let offset = u32::from(access.port - pit::BASE_PORT);
1160        if access.write {
1161            let value = (guest.gpr(access.register) & 0xFF) as u8;
1162            devices.pit.write(offset, value);
1163        } else {
1164            let value = devices.pit.read(offset);
1165            write_register(guest, access.register, access.size, u64::from(value));
1166        }
1167        return true;
1168    }
1169    if kind == PortKind::Rtc {
1170        // The CMOS index/data ports are byte-wide.
1171        if access.size != 1 {
1172            return false;
1173        }
1174        if access.port == rtc::INDEX_PORT {
1175            if access.write {
1176                devices
1177                    .rtc
1178                    .write_index((guest.gpr(access.register) & 0xFF) as u8);
1179            } else {
1180                // The index port is write-only on the real chip.
1181                write_register(guest, access.register, access.size, 0xFF);
1182            }
1183        } else if access.write {
1184            devices
1185                .rtc
1186                .write_data((guest.gpr(access.register) & 0xFF) as u8);
1187        } else {
1188            let value = devices.rtc.read_data();
1189            write_register(guest, access.register, access.size, u64::from(value));
1190        }
1191        return true;
1192    }
1193    if kind == PortKind::Uart {
1194        // COM1 is byte-wide.
1195        if access.size != 1 {
1196            return false;
1197        }
1198        let offset = u32::from(access.port - uart::BASE_PORT);
1199        if access.write {
1200            let value = (guest.gpr(access.register) & 0xFF) as u8;
1201            devices.uart.write(offset, value);
1202        } else {
1203            let value = devices.uart.read(offset);
1204            write_register(guest, access.register, access.size, u64::from(value));
1205        }
1206        // The UART interrupt line is level-triggered: it stays asserted until
1207        // the driver services the source, so mirror the model's line state.
1208        set_device_line(
1209            devices,
1210            apic,
1211            isa_gsi(uart::IRQ_LINE),
1212            devices.uart.irq_asserted(),
1213        );
1214        return true;
1215    }
1216    if kind == PortKind::Keyboard {
1217        // The 8042 is byte-wide.
1218        if access.size != 1 {
1219            return false;
1220        }
1221        if access.write {
1222            devices
1223                .keyboard
1224                .write(access.port, (guest.gpr(access.register) & 0xFF) as u8);
1225        } else {
1226            let Some(value) = devices.keyboard.read(access.port) else {
1227                return false;
1228            };
1229            write_register(guest, access.register, access.size, u64::from(value));
1230        }
1231        return true;
1232    }
1233    if kind == PortKind::Vga {
1234        // VGA registers are byte-wide.
1235        if access.size != 1 {
1236            return false;
1237        }
1238        if access.write {
1239            devices
1240                .vga
1241                .write(access.port, (guest.gpr(access.register) & 0xFF) as u8);
1242        } else {
1243            let Some(value) = devices.vga.read(access.port) else {
1244                return false;
1245            };
1246            write_register(guest, access.register, access.size, u64::from(value));
1247        }
1248        return true;
1249    }
1250    if kind == PortKind::Dma {
1251        // The 8237 register files are byte-wide.
1252        if access.size != 1 {
1253            return false;
1254        }
1255        if access.write {
1256            devices
1257                .dma
1258                .write(access.port, (guest.gpr(access.register) & 0xFF) as u8);
1259        } else {
1260            let Some(value) = devices.dma.read(access.port) else {
1261                return false;
1262            };
1263            write_register(guest, access.register, access.size, u64::from(value));
1264        }
1265        return true;
1266    }
1267    if kind == PortKind::Fdc {
1268        // The 82077 interface is byte-wide.
1269        if access.size != 1 {
1270            return false;
1271        }
1272        if access.write {
1273            let event = devices
1274                .fdc
1275                .write(access.port, (guest.gpr(access.register) & 0xFF) as u8);
1276            match event {
1277                fdc::FdcEvent::None => {}
1278                fdc::FdcEvent::Irq => {
1279                    devices.fdc.take_irq();
1280                    devices.pic.raise(fdc::IRQ_LINE);
1281                }
1282                fdc::FdcEvent::Transfer(transfer) => {
1283                    perform_floppy_dma(devices, view, transfer);
1284                    devices.fdc.take_irq();
1285                    devices.pic.raise(fdc::IRQ_LINE);
1286                }
1287            }
1288        } else {
1289            let Some(value) = devices.fdc.read(access.port) else {
1290                return false;
1291            };
1292            write_register(guest, access.register, access.size, u64::from(value));
1293        }
1294        return true;
1295    }
1296    if kind == PortKind::System {
1297        // The system-control ports are byte-wide.
1298        if access.size != 1 {
1299            return false;
1300        }
1301        if access.write {
1302            devices
1303                .system
1304                .write(access.port, (guest.gpr(access.register) & 0xFF) as u8);
1305        } else {
1306            let Some(value) = devices.system.read(access.port) else {
1307                return false;
1308            };
1309            write_register(guest, access.register, access.size, u64::from(value));
1310        }
1311        return true;
1312    }
1313    if kind == PortKind::FwCfg {
1314        if access.port == fwcfg::CTL_PORT {
1315            // The selector is written with `outw` by SeaBIOS; accept a byte
1316            // access too, like the QEMU device.
1317            if access.size > 2 {
1318                return false;
1319            }
1320            if access.write {
1321                devices
1322                    .fw_cfg
1323                    .select((guest.gpr(access.register) & 0xFFFF) as u16);
1324            } else {
1325                write_register(
1326                    guest,
1327                    access.register,
1328                    access.size,
1329                    u64::from(devices.fw_cfg.selector()),
1330                );
1331            }
1332            return true;
1333        }
1334        if access.size != 1 {
1335            return false;
1336        }
1337        if access.write {
1338            devices
1339                .fw_cfg
1340                .write_byte((guest.gpr(access.register) & 0xFF) as u8);
1341        } else {
1342            let value = devices.fw_cfg.read_byte();
1343            write_register(guest, access.register, access.size, u64::from(value));
1344        }
1345        return true;
1346    }
1347    if kind == PortKind::Pci {
1348        // Configuration mechanism #1: one 32-bit CAM register and one 32-bit
1349        // data register. The model also accepts byte and word accesses on the
1350        // data register (some early probes use them).
1351        if access.write {
1352            let value = guest.gpr(access.register) as u32;
1353            if !devices.pci.io_write(access.port, access.size, value) {
1354                return false;
1355            }
1356        } else {
1357            let Some(value) = devices.pci.io_read(access.port, access.size) else {
1358                return false;
1359            };
1360            write_register(guest, access.register, access.size, u64::from(value));
1361        }
1362        return true;
1363    }
1364    if kind == PortKind::Post {
1365        // Diagnostic port: writes are discarded, reads return zero.
1366        if !access.write {
1367            write_register(guest, access.register, access.size, 0);
1368        }
1369        return true;
1370    }
1371    if kind == PortKind::Debug {
1372        // QEMU debug console: keep the firmware's `dprintf` output for the
1373        // runner diagnostics; reads return zero.
1374        if access.write {
1375            devices
1376                .debug_con
1377                .push((guest.gpr(access.register) & 0xFF) as u8);
1378        } else {
1379            write_register(guest, access.register, access.size, 0);
1380        }
1381        return true;
1382    }
1383    false
1384}
1385
1386/// Performs the DMA channel-2 transfer a floppy command requested.
1387///
1388/// The controller decoded the CHS parameters and queued its result bytes; the
1389/// physical transfer is the caller's job. The 8237 channel gives the 24-bit
1390/// address and the byte count (minus one); a firmware transfer is always
1391/// sector-aligned and never crosses a 64 KiB boundary, which SeaBIOS verifies
1392/// before programming the channel.
1393fn perform_floppy_dma(
1394    devices: &mut Devices,
1395    view: &mut MemoryView<'_>,
1396    transfer: fdc::FdcTransfer,
1397) {
1398    let Some(channel) = devices.dma.channel(dma::FLOPPY_CHANNEL) else {
1399        return;
1400    };
1401    let address = channel.physical_address() as u64;
1402    let capacity = channel
1403        .remaining()
1404        .min(u32::from(transfer.sectors) * fdc::SECTOR_SIZE as u32);
1405    let mut sector = [0u8; fdc::SECTOR_SIZE];
1406    let mut done: u32 = 0;
1407    for index in 0..u32::from(transfer.sectors) {
1408        if done + fdc::SECTOR_SIZE as u32 > capacity {
1409            break;
1410        }
1411        let lba = transfer.lba + u64::from(index);
1412        let offset = address + u64::from(done);
1413        let moved = if transfer.write {
1414            view.read_physical(offset, &mut sector) && devices.fdc.write_sector(lba, &sector)
1415        } else {
1416            devices.fdc.read_sector(lba, &mut sector) && view.write_physical(offset, &sector)
1417        };
1418        if !moved {
1419            break;
1420        }
1421        done += fdc::SECTOR_SIZE as u32;
1422    }
1423    devices.dma.complete(dma::FLOPPY_CHANNEL, done);
1424}
1425
1426/// Handles an `RDMSR`/`WRMSR` exit.
1427///
1428/// The x2APIC window (`0x800..=0x8FF`) is modeled when the guest actually uses
1429/// the x2APIC interface: the kernel enables MSR bitmaps for that window, so the
1430/// exit tells us the guest executed the instruction. `IA32_TSC_DEADLINE`
1431/// (`0x6E0`) is also routed to the local APIC timer even outside the x2APIC
1432/// window, because it is the programming interface of the TSC-deadline mode.
1433/// All other intercepted MSRs are replayed against the per-vCPU [`MsrModel`].
1434///
1435/// If the caller provides no model, or if the model rejects the access, the
1436/// exit is **not** consumed: `Ok(false)` reports it to policy. This path never
1437/// writes a host MSR, so an unmapped model fails closed. A modelled invalid
1438/// value (for example a reserved `IA32_EFER` bit) is also reported to policy
1439/// rather than injected as #GP here; the policy layer owns that decision.
1440///
1441/// `ECX` holds the MSR number, `EDX:EAX` the value (`rdmsr` writes them).
1442fn handle_msr_exit(
1443    apic: &mut LocalApic,
1444    devices: &mut Devices,
1445    view: &mut MemoryView<'_>,
1446    guest: &mut dyn GuestContext,
1447) -> Result<bool, EmuError> {
1448    let Decoded::Msr(access) = view.fetch(guest)? else {
1449        return Ok(false);
1450    };
1451    // RCX (encoding order index 1) selects the MSR.
1452    let msr = guest.gpr(1) as u32;
1453    let in_x2apic_window = (X2APIC_MSR_FIRST..=X2APIC_MSR_LAST).contains(&msr);
1454    let is_tsc_deadline = msr == TSC_DEADLINE_MSR;
1455
1456    if !in_x2apic_window && !is_tsc_deadline {
1457        if access.write {
1458            let value = ((guest.gpr(2) & 0xFFFF_FFFF) << 32) | (guest.gpr(0) & 0xFFFF_FFFF);
1459            let Some(model) = guest.msr_model() else {
1460                return Ok(false);
1461            };
1462            if model.write(msr, value).is_err() {
1463                return Ok(false);
1464            }
1465            // The caller refreshes the guest state/control block for the
1466            // returned effect (`MsrWrite`) before the next entry.
1467        } else {
1468            let value = {
1469                let Some(model) = guest.msr_model() else {
1470                    return Ok(false);
1471                };
1472                match model.read(msr) {
1473                    Ok(value) => value,
1474                    Err(_) => return Ok(false),
1475                }
1476            };
1477            write_register(guest, 0, 4, value & 0xFFFF_FFFF);
1478            write_register(guest, 2, 4, value >> 32);
1479        }
1480        guest.set_rip(access.next_rip);
1481        return Ok(true);
1482    }
1483
1484    if in_x2apic_window {
1485        debug_assert!(x2apic::TPR <= msr);
1486    }
1487    let eoi_vector = (access.write && in_x2apic_window && msr == x2apic::EOI)
1488        .then(|| in_service_vector(apic))
1489        .flatten();
1490    if access.write {
1491        let value = ((guest.gpr(2) & 0xFFFF_FFFF) << 32) | (guest.gpr(0) & 0xFFFF_FFFF);
1492        if is_tsc_deadline {
1493            apic.set_tsc_deadline(value);
1494        } else if !apic.x2apic_write(msr, value) {
1495            return Ok(false);
1496        }
1497    } else {
1498        let value = if is_tsc_deadline {
1499            Some(apic.tsc_deadline())
1500        } else {
1501            apic.x2apic_read(msr)
1502        };
1503        let Some(value) = value else {
1504            return Ok(false);
1505        };
1506        // RDMSR replaces the low 32 bits of EDX and EAX only.
1507        write_register(guest, 0, 4, value & 0xFFFF_FFFF);
1508        write_register(guest, 2, 4, value >> 32);
1509    }
1510    if let Some(vector) = eoi_vector {
1511        if let Some(reinject) = devices.ioapic.eoi(vector) {
1512            apic.inject(reinject);
1513        }
1514    }
1515    guest.set_rip(access.next_rip);
1516    Ok(true)
1517}
1518
1519/// Handles an EPT violation on a modeled device page.
1520///
1521/// The device pages are intentionally *not* mapped in the second-level tables:
1522/// the violation is what makes the access visible, and the replay below
1523/// services it from the device model.
1524fn handle_mmio_exit(
1525    devices: &mut Devices,
1526    apic: &mut LocalApic,
1527    view: &mut MemoryView<'_>,
1528    guest: &mut dyn GuestContext,
1529    qualification: u64,
1530    address: u64,
1531) -> Result<bool, EmuError> {
1532    // Bit 3 of the qualification distinguishes an instruction fetch (1) from
1533    // a data access (0); only data accesses are modeled here.
1534    if (qualification >> 3) & 0x1 != 0 {
1535        return Ok(false);
1536    }
1537    let Decoded::Memory(access) = view.fetch(guest)? else {
1538        return Ok(false);
1539    };
1540    let Some(page) = device_page(address) else {
1541        // A PCI function BAR is not a fixed device page: resolve it through
1542        // the bridge's live placement map, which only contains the BARs the
1543        // guest programmed.
1544        if !serve_pci_mmio(devices, guest, &access) {
1545            return Ok(false);
1546        }
1547        guest.set_rip(access.next_rip);
1548        return Ok(true);
1549    };
1550    // The HPET has 64-bit registers: serve it before the 32-bit merge path.
1551    if page == DevicePage::Hpet {
1552        if !serve_hpet(devices, guest, &access) {
1553            return Ok(false);
1554        }
1555        guest.set_rip(access.next_rip);
1556        return Ok(true);
1557    }
1558    // Only plain register/memory transfers of 1, 2 or 4 bytes are modeled.
1559    if !matches!(access.size, 1 | 2 | 4) {
1560        return Ok(false);
1561    }
1562    if !serve_mmio(devices, apic, view, guest, page, &access) {
1563        return Ok(false);
1564    }
1565    guest.set_rip(access.next_rip);
1566    Ok(true)
1567}
1568
1569/// Applies one decoded memory access to the high-precision event timer.
1570///
1571/// The model exposes 32- and 64-bit registers; an unaligned access or any other
1572/// width is outside the subset and is reported to policy.
1573fn serve_hpet(devices: &mut Devices, guest: &mut dyn GuestContext, access: &MemoryAccess) -> bool {
1574    let offset = (access.address & PAGE_OFFSET_MASK) as u16;
1575    if access.address % u64::from(access.size) != 0 {
1576        return false;
1577    }
1578    if access.write {
1579        let value = guest.gpr(access.register);
1580        devices.hpet.write(offset, access.size, value)
1581    } else {
1582        let Some(value) = devices.hpet.read(offset, access.size) else {
1583            return false;
1584        };
1585        write_register(guest, access.register, access.size, value);
1586        true
1587    }
1588}
1589
1590/// Applies one decoded memory access to a PCI function BAR.
1591///
1592/// The access must be naturally aligned for its size: the configuration and
1593/// transport windows are made of 32-bit registers, and a misaligned access is
1594/// outside the modeled subset (the exit is reported to policy).
1595fn serve_pci_mmio(
1596    devices: &mut Devices,
1597    guest: &mut dyn GuestContext,
1598    access: &MemoryAccess,
1599) -> bool {
1600    if access.address % u64::from(access.size) != 0 {
1601        return false;
1602    }
1603    if access.write {
1604        let value = guest.gpr(access.register) as u32;
1605        devices.pci.mmio_write(access.address, access.size, value)
1606    } else {
1607        let Some(value) = devices.pci.mmio_read(access.address, access.size) else {
1608            return false;
1609        };
1610        write_register(guest, access.register, access.size, u64::from(value));
1611        true
1612    }
1613}
1614
1615/// Device page targeted by a guest-physical address.
1616#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1617pub enum DevicePage {
1618    /// Local APIC MMIO page.
1619    Apic,
1620    /// I/O APIC MMIO page.
1621    IoApic,
1622    /// Virtio console transport page.
1623    Console,
1624    /// Virtio block transport page.
1625    Blk,
1626    /// Virtio network transport page.
1627    Net,
1628    /// High-precision event timer page.
1629    Hpet,
1630}
1631
1632/// Identifies the modeled device page containing `address`.
1633pub fn device_page(address: u64) -> Option<DevicePage> {
1634    let page = address & !PAGE_OFFSET_MASK;
1635    if page == APIC_BASE {
1636        Some(DevicePage::Apic)
1637    } else if page == IOAPIC_BASE {
1638        Some(DevicePage::IoApic)
1639    } else if page == CONSOLE_BASE {
1640        Some(DevicePage::Console)
1641    } else if page == BLK_BASE {
1642        Some(DevicePage::Blk)
1643    } else if page == NET_BASE {
1644        Some(DevicePage::Net)
1645    } else if page == hpet::BASE_GPA {
1646        Some(DevicePage::Hpet)
1647    } else {
1648        None
1649    }
1650}
1651
1652/// Base of the x86 APIC MSI address window.
1653pub const MSI_ADDRESS_BASE: u64 = 0xFEE0_0000;
1654/// Mask selecting the fixed MSI address prefix (bits 31:20).
1655pub const MSI_ADDRESS_MASK: u64 = 0xFFF0_0000;
1656
1657/// Decodes an x86 MSI write into `(vector, destination APIC id)`.
1658///
1659/// Supported subset (the one a virtio-MSI driver emits):
1660///
1661/// - address: low 32 bits only, `0xFEE0_0000` prefix (bits 31:20 = `0xFEE`),
1662///   destination APIC id in bits 19:12, and all low 12 bits zero (physical
1663///   destination, no redirect hint); high 32 bits zero;
1664/// - data: fixed delivery mode, edge trigger and no level/flag bits, i.e.
1665///   everything above the low vector byte is zero; the vector must be a
1666///   usable interrupt vector (`>= 16`).
1667///
1668/// Returns `None` for any other address/data combination; the caller then
1669/// ignores the write instead of injecting a bogus vector.
1670pub fn msi_write(address: u64, data: u32) -> Option<(u8, u8)> {
1671    if address >> 32 != 0 || address & 0xFFF != 0 {
1672        return None;
1673    }
1674    if address & MSI_ADDRESS_MASK != MSI_ADDRESS_BASE {
1675        return None;
1676    }
1677    if data & 0xFFFF_FF00 != 0 {
1678        return None;
1679    }
1680    let vector = (data & 0xFF) as u8;
1681    if vector < 16 {
1682        return None;
1683    }
1684    let destination = ((address >> 12) & 0xFF) as u8;
1685    Some((vector, destination))
1686}
1687
1688/// Delivers an MSI write directly to the local APIC (no I/O APIC involved).
1689///
1690/// Returns `true` when the address/data pair is in the supported subset and
1691/// the vector was injected into the local IRR. The destination APIC id is
1692/// decoded but there is a single modeled LAPIC, so it does not route.
1693pub fn deliver_msi(apic: &mut LocalApic, address: u64, data: u32) -> bool {
1694    match msi_write(address, data) {
1695        Some((vector, _destination)) => {
1696            apic.inject(vector);
1697            true
1698        }
1699        None => false,
1700    }
1701}
1702
1703/// Returns the highest in-service vector of the local APIC.
1704fn in_service_vector(apic: &LocalApic) -> Option<u8> {
1705    for index in (0..8usize).rev() {
1706        let word = apic.mmio_read(apic_reg::ISR + index * 16);
1707        if word != 0 {
1708            return Some((index as u8) * 32 + (31 - word.leading_zeros() as u8));
1709        }
1710    }
1711    None
1712}
1713
1714/// Applies a logical level to a device line and injects the vector, if any.
1715///
1716/// A device pin is wired to the I/O APIC and, on a PC chipset, to the 8259 pair
1717/// as well. Both controllers are driven so a guest that keeps the legacy pair
1718/// (or that has not reprogrammed the I/O APIC yet) still receives the
1719/// interrupt; the 8259 only delivers when it is initialised and unmasked, so a
1720/// guest in APIC mode : which masks the pair : is unaffected.
1721pub(crate) fn set_device_line(
1722    devices: &mut Devices,
1723    apic: &mut LocalApic,
1724    line: usize,
1725    asserted: bool,
1726) {
1727    if devices.legacy_pic {
1728        // A legacy firmware owns the 8259 vectors (`0x08..=0x0F`), which the
1729        // local APIC never delivers. Drive the pair only; the runner
1730        // acknowledges it and injects the programmed vector directly.
1731        if let Some(irq) = gsi_isa_irq(line) {
1732            if asserted {
1733                devices.pic.raise(irq);
1734            } else {
1735                devices.pic.lower(irq);
1736            }
1737        }
1738        return;
1739    }
1740    if let Some(vector) = devices.ioapic.set_line_level(line, asserted) {
1741        apic.inject(vector);
1742    }
1743    let Some(irq) = gsi_isa_irq(line) else {
1744        return;
1745    };
1746    if asserted {
1747        devices.pic.raise(irq);
1748        flush_pic(devices, apic);
1749    } else {
1750        devices.pic.lower(irq);
1751    }
1752}
1753
1754/// Delivers at most one pending 8259 request to the local APIC.
1755///
1756/// The 8259 asserts its `INT` output while a request is pending; the processor
1757/// acknowledges it during the interrupt cycle, which is the moment the model
1758/// must move the request from the `IRR` to the `ISR` and hand the vector to the
1759/// local APIC. Only one vector is taken per call: the local APIC `IRR` is what
1760/// queues the rest, and taking more would acknowledge requests the guest has
1761/// not seen yet. Delivery is skipped while a request is already in service, so
1762/// a level-triggered line that stays high cannot be acknowledged twice before
1763/// the guest end-of-interrupt.
1764pub(crate) fn flush_pic(devices: &mut Devices, apic: &mut LocalApic) {
1765    if devices.legacy_pic {
1766        // The legacy runner owns delivery: it must see the request in the IRR
1767        // to inject the `0x08..=0x0F` vector itself.
1768        return;
1769    }
1770    if devices.pic.master().isr() != 0 || devices.pic.slave().isr() != 0 {
1771        return;
1772    }
1773    if let Some(vector) = devices.pic.acknowledge() {
1774        apic.inject(vector);
1775    }
1776}
1777
1778/// Raises then lowers `pin` on the I/O APIC, delivering exactly one edge.
1779///
1780/// Used by the 8254 timer, whose channel-0 expiry is a pulse: an edge-triggered
1781/// redirection entry accepts it on the rising transition only, and a
1782/// level-triggered entry latches it in the remote-IRR and is serviced by the
1783/// guest's EOI.
1784pub fn pulse_device_line(devices: &mut Devices, apic: &mut LocalApic, pin: usize) {
1785    set_device_line(devices, apic, pin, true);
1786    set_device_line(devices, apic, pin, false);
1787}
1788
1789/// Applies one decoded memory access to a device page.
1790fn serve_mmio(
1791    devices: &mut Devices,
1792    apic: &mut LocalApic,
1793    view: &mut MemoryView<'_>,
1794    guest: &mut dyn GuestContext,
1795    page: DevicePage,
1796    access: &MemoryAccess,
1797) -> bool {
1798    let offset = (access.address & PAGE_OFFSET_MASK) as usize;
1799    let shift = ((offset as u32) & 0x3) * 8;
1800    let mask = width_mask(u64::from(access.size));
1801    if access.write {
1802        let value = guest.gpr(access.register);
1803        let word = read_mmio(devices, apic, page, offset);
1804        let merged = (word & !((mask as u32) << shift)) | (((value as u32) & mask as u32) << shift);
1805        write_mmio(devices, apic, view, page, offset, merged);
1806    } else {
1807        let word = read_mmio(devices, apic, page, offset);
1808        let value = (u64::from(word) >> shift) & mask;
1809        // `register_size == 0` marks a read-only probe (`test`/`cmp` with a
1810        // memory operand): the device read and its side effects happen, but
1811        // there is no destination register to update.
1812        if access.register_size != 0 {
1813            write_register(guest, access.register, access.size, value);
1814        }
1815    }
1816    true
1817}
1818
1819/// Reads the 32-bit device register containing `offset`.
1820fn read_mmio(devices: &Devices, apic: &LocalApic, page: DevicePage, offset: usize) -> u32 {
1821    match page {
1822        DevicePage::Apic => apic.mmio_read(offset & 0xFFF),
1823        DevicePage::IoApic => devices.ioapic.mmio_read(offset & 0xFF),
1824        DevicePage::Console => devices.console.read(offset as u32 & 0xFFF),
1825        DevicePage::Blk => devices.blk.read(offset as u32 & 0xFFF),
1826        DevicePage::Net => devices.net.read(offset as u32 & 0xFFF),
1827        // The HPET has 32/64-bit registers and is served before this path.
1828        DevicePage::Hpet => 0,
1829    }
1830}
1831
1832/// Writes the 32-bit device register containing `offset`.
1833fn write_mmio(
1834    devices: &mut Devices,
1835    apic: &mut LocalApic,
1836    view: &mut MemoryView<'_>,
1837    page: DevicePage,
1838    offset: usize,
1839    value: u32,
1840) {
1841    match page {
1842        DevicePage::Apic => {
1843            let eoi_vector = (offset & 0xFFF == apic_reg::EOI)
1844                .then(|| in_service_vector(apic))
1845                .flatten();
1846            apic.mmio_write(offset & 0xFFF, value);
1847            if let Some(vector) = eoi_vector {
1848                if let Some(reinject) = devices.ioapic.eoi(vector) {
1849                    apic.inject(reinject);
1850                }
1851            }
1852        }
1853        DevicePage::IoApic => {
1854            devices.ioapic.mmio_write(offset & 0xFF, value);
1855            // A redirection entry may have been unmasked or reprogrammed while
1856            // its input line was already asserted.
1857            for pin in 0..PIN_COUNT {
1858                if let Some(vector) = devices.ioapic.refresh_pin(pin) {
1859                    apic.inject(vector);
1860                }
1861            }
1862        }
1863        DevicePage::Console => {
1864            devices.console.write(offset as u32 & 0xFFF, value, view);
1865            // The line stays asserted until the guest acknowledges the virtio
1866            // interrupt status; a level-triggered entry therefore re-raises on
1867            // EOI while the status is still pending.
1868            let asserted = devices.console.interrupt_status() != 0;
1869            set_device_line(devices, apic, CONSOLE_IRQ_LINE, asserted);
1870        }
1871        DevicePage::Blk => {
1872            devices.blk.write(offset as u32 & 0xFFF, value, view);
1873            let asserted = devices.blk.interrupt_status() != 0;
1874            set_device_line(devices, apic, BLK_IRQ_LINE, asserted);
1875        }
1876        DevicePage::Net => {
1877            devices.net.write(offset as u32 & 0xFFF, value, view);
1878            let asserted = devices.net.interrupt_status() != 0;
1879            set_device_line(devices, apic, NET_IRQ_LINE, asserted);
1880        }
1881        // The HPET has 32/64-bit registers and is served before this path.
1882        DevicePage::Hpet => {}
1883    }
1884}
1885
1886/// Writes `size` bytes of `value` into a general-purpose register, preserving
1887/// the bits above the access width (as `IN` and `MOV` do).
1888fn write_register(guest: &mut dyn GuestContext, register: u8, size: u8, value: u64) {
1889    let mask = width_mask(u64::from(size));
1890    let current = guest.gpr(register);
1891    guest.set_gpr(register, (current & !mask) | (value & mask));
1892}
1893
1894/// Mask of the low `size` bytes.
1895const fn width_mask(size: u64) -> u64 {
1896    match size {
1897        1 => 0xFF,
1898        2 => 0xFFFF,
1899        4 => 0xFFFF_FFFF,
1900        _ => u64::MAX,
1901    }
1902}