Skip to main content

strat9_kernel/s9vm/
selftest.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 : hardware smoke test of the engine.
24//!
25//! Goal: run minimal guests (64-bit long mode, EPT enabled, page tables built
26//! by the kernel) that exercise the full path : guest tables and second-level
27//! tables, control-block load, guest entry, exits, kernel fast paths and clean
28//! shutdown : without panicking: a failure is logged and boot continues.
29//!
30//! Phases, selected by the boot option `s9vm.selftest`:
31//!
32//! - `device` (`1`/`true`): canonical guest, legacy interrupt controller
33//!   fast path, I/O exit and `hlt`;
34//! - `irq`: interrupt delivery through the interrupt window;
35//! - `console`: virtio console transport, both directions;
36//! - `blk`: virtio block request replay;
37//! - `net`: virtio network transmit;
38//! - `loader`: an ELF64 image built in kernel memory, loaded into a world with
39//!   [`crate::s9vm::vm::load_image`] (mapping, file-backed copy, BSS zeroing),
40//!   then executed: the guest prints its marker on the debug port and halts;
41//! - `acpi`: the guest discovers the firmware tables written by
42//!   [`crate::s9vm::vm::write_acpi`] (RSDP scan, checksum, XSDT walk, MADT
43//!   Local APIC count). It needs a registered vCPU, so it runs at the
44//!   `kthread` stage (see [`s9vm_acpi_selftest`]) on a **detached** vCPU
45//!   driven by a direct run loop; it is opt-in in the `2`/`all` mode through
46//!   `s9vm.selftest.deferred=1`;
47//! - `smp`: one world with two vCPUs, each with its own page tables, code page
48//!   and stack, driven through the kernel vCPU tasks (`request_run`,
49//!   `complete_exit`) in an interleaved order. It validates that the two vCPU
50//!   contexts (CR3, RIP, RSP, marker) are independent and persisted across
51//!   runs; it is enabled by `s9vm.selftest.deferred=1` or explicitly with
52//!   `s9vm.selftest=smp`;
53//! - `guestos`: a guest "OS bootstrap": the phase stores a command line and one
54//!   module, writes the ACPI tables and the boot-parameter block (magic
55//!   `S9VMBP`, memory map, `rsdp_gpa`, counts), then runs a payload built with
56//!   [`crate::s9vm::guestprog::guestos`] that validates the block, scans the
57//!   legacy window for `RSD PTR `, checks the ACPI 1.0 checksum and reports
58//!   `b'O'` plus a status byte on the debug port. It registers a **detached**
59//!   vCPU (no scheduler) and runs synchronously at the `kthread` stage; it is
60//!   enabled by `s9vm.selftest.deferred=1` or explicitly with
61//!   `s9vm.selftest=guestos`;
62//! - `dos`: a real-mode 16-bit DOS-class guest booted through the BIOS model
63//!   (INT 10h/13h/16h/1Ah), with a 1.44 MiB demo disk; it needs VT-x and the
64//!   unrestricted-guest control. `dos_dry` performs and verifies the whole
65//!   preparation without VT-x; `freedos` boots the real FreeDOS 1.4 floppy
66//!   (`assets/disks/freedos-1.4-boot.img`) with the s9vm stub firmware and
67//!   `freedos_dry` verifies its installation without VT-x; `freedos_seabios`
68//!   boots the same floppy with the real SeaBIOS/SeaVGABIOS images
69//!   (`assets/firmware/`, FDC + DMA + PIC driven by the guest) and
70//!   `freedos_seabios_dry` verifies their placement without VT-x;
71//! - `2`/`all`: the six bootstrap phases; `acpi`, `smp` and `guestos` are added
72//!   by `s9vm.selftest.deferred=1`.
73//!
74//! The task path used by `smp` (kernel threads created from a component,
75//! bounded `RUN` and destroy) has its own diagnostic,
76//! `s9vm.kthread_smoke=1`, which runs on hosts without VT-x and reports
77//! PASS/FAIL through the serial log.
78//!
79//! The guest state is the canonical 64-bit flat shape produced by
80//! [`GuestState::long_mode_64`]; it is entered once. Any exit the engine does
81//! not expect is logged with its decoded reason so a failure is diagnosable on
82//! the target machine without rebuilding.
83
84use alloc::{vec, vec::Vec};
85use core::sync::atomic::{AtomicBool, Ordering};
86use strat9_abi::vmm::{exit_kind, VmmRegs, VMM_ABI_VERSION};
87use strat9_elf_core::{build::ImageWriter, ET_EXEC, PF_R, PF_X};
88
89use crate::{
90    memory::frame::{FrameAllocOptions, FramePurpose, PhysFrame},
91    s9vm::{
92        apic::LocalApic,
93        bootparams, bzimage,
94        caps::HwCaps,
95        dosboot,
96        emulate::{interrupt_action, interrupt_deliverable, InterruptAction},
97        exit::{reason_name, ExitClass, ExitReason},
98        guest::GuestState,
99        guestcode::{
100            ACPI_CODE, ACPI_MARKER, LOADER_CODE, LOADER_MARKER, SMP_CODE_0, SMP_CODE_1,
101            SMP_HLT_OFFSET, SMP_MARKERS, SMP_OUT_INSTRUCTION_LEN, SMP_SHARED_GPA,
102        },
103        guestprog::guestos,
104        guestpt::GuestPageTables,
105        linuxboot,
106        machine::Machine,
107        vcpu::{SecondLevelMemory, Vcpu, VcpuError},
108        virtio, virtio_blk, virtio_net, vm, zeropage,
109    },
110};
111
112/// Size of the test guest area: 6 pages (tables + code + stack).
113const GUEST_PAGES: u64 = 6;
114const GPA_PML4: u64 = 0x0000;
115const GPA_PDPT: u64 = 0x1000;
116const GPA_PD: u64 = 0x2000;
117const GPA_CODE: u64 = 0x3000;
118const GPA_STACK: u64 = 0x4000;
119const GPA_PT: u64 = 0x5000;
120const ENTRY_POINT: u64 = GPA_CODE;
121const STACK_TOP: u64 = GPA_STACK + 0x800;
122
123/// Byte written by the guest to the test port (0xE9).
124const TEST_BYTE: u8 = 0x41;
125/// I/O port used by the test (standard debug port of emulators).
126const TEST_PORT: u16 = 0xE9;
127/// Master PIC data port, used to check that the kernel *read path* is
128/// emulated (the guest reads back the interrupt mask it programmed).
129const PIC_DATA_PORT: u16 = 0x21;
130/// Interrupt mask read back by the guest after programming the PIC.
131const PIC_READBACK: u8 = 0xFF;
132
133// Interrupt-delivery phase.
134/// Guest pages for the interrupt test: the first six, plus IDT and GDT pages.
135const IRQ_GUEST_PAGES: u64 = 8;
136/// Guest-physical address of the IDT page (page 6).
137const GPA_IDT: u64 = 0x6000;
138/// Guest-physical address of the GDT page (page 7).
139const GPA_GDT: u64 = 0x7000;
140
141// Console phase.
142/// Guest-physical address of the virtio console transport page.
143#[allow(dead_code)] // Retained console self-test MMIO constant.
144const CONSOLE_MMIO_BASE: u64 = 0xFEB0_0000;
145/// Guest pages of the console phase: tables, code, stack, queues, buffer and
146/// the second page directory that maps the MMIO window.
147const CONSOLE_GUEST_PAGES: u64 = 9;
148/// Guest-physical address of the queue page (descriptor table + rings).
149const GPA_QUEUES: u64 = 0x6000;
150/// Guest-physical address of the console buffer page.
151const GPA_CONSOLE_BUFFER: u64 = 0x7000;
152/// Bytes the guest sends to the console.
153const CONSOLE_TEXT: &[u8] = b"ok\n";
154/// Byte queued by the kernel and delivered through the receive queue.
155const CONSOLE_RX_BYTE: u8 = b'R';
156
157const CONSOLE_GPA_PML4: u64 = 0x0000;
158const CONSOLE_GPA_PDPT: u64 = 0x1000;
159const CONSOLE_GPA_PD: u64 = 0x2000;
160const CONSOLE_GPA_PT: u64 = 0x3000;
161const CONSOLE_GPA_CODE: u64 = 0x4000;
162const CONSOLE_GPA_STACK: u64 = 0x5000;
163/// Second page directory, reached through PML4/PDPT entry 3.
164const CONSOLE_GPA_PD_HIGH: u64 = 0x8000;
165/// 2 MiB-aligned start of the window containing the console transport page.
166const CONSOLE_GPA_MMIO_WINDOW: u64 = 0xFEA0_0000;
167/// Page-directory index of that window (0xFEA0_0000 >> 21, low 9 bits).
168const CONSOLE_PD_MMIO_INDEX: usize = 0x1F5;
169
170/// Guest code of the console phase.
171///
172/// Programs the virtio console transport (status, transmit queue, queue
173/// address registers, ready, notify), then reports through the debug port and
174/// halts. All the queue structures are prepared by the kernel, so the guest
175/// only exercises the transport page.
176const CONSOLE_GUEST_CODE: &[u8] = &[
177    0xB8, 0x70, 0x00, 0xB0, 0xFE, // mov eax, CONSOLE_MMIO_BASE + 0x70 (STATUS)
178    0xB9, 0x0F, 0x00, 0x00, 0x00, // mov ecx, ACK | DRIVER | FEATURES_OK | DRIVER_OK
179    0x89, 0x08, //
180    0xB8, 0x30, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_SEL
181    0xB9, 0x01, 0x00, 0x00, 0x00, // mov ecx, 1 (transmit queue)
182    0x89, 0x08, //
183    0xB8, 0x38, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_NUM
184    0xB9, 0x08, 0x00, 0x00, 0x00, // mov ecx, 8
185    0x89, 0x08, //
186    0xB8, 0x80, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_DESC_LOW
187    0xB9, 0x00, 0x60, 0x00, 0x00, // mov ecx, GPA_QUEUES
188    0x89, 0x08, //
189    0xB8, 0x90, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_AVAIL_LOW
190    0xB9, 0x00, 0x61, 0x00, 0x00, // mov ecx, GPA_QUEUES + 0x100
191    0x89, 0x08, //
192    0xB8, 0xA0, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_USED_LOW
193    0xB9, 0x00, 0x62, 0x00, 0x00, // mov ecx, GPA_QUEUES + 0x200
194    0x89, 0x08, //
195    0xB8, 0x44, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_READY
196    0xB9, 0x01, 0x00, 0x00, 0x00, // mov ecx, 1
197    0x89, 0x08, //
198    0xB8, 0x50, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_NOTIFY
199    0xB9, 0x01, 0x00, 0x00, 0x00, // mov ecx, 1 (transmit queue)
200    0x89, 0x08, //
201    // Receive queue: separate tables in the queue page and a buffer at
202    // 0x7400. Its notification delivers the byte queued by the kernel.
203    0xB8, 0x30, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_SEL
204    0xB9, 0x00, 0x00, 0x00, 0x00, // mov ecx, 0 (receive queue)
205    0x89, 0x08, //
206    0xB8, 0x38, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_NUM
207    0xB9, 0x08, 0x00, 0x00, 0x00, // mov ecx, 8
208    0x89, 0x08, //
209    0xB8, 0x80, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_DESC_LOW
210    0xB9, 0x00, 0x64, 0x00, 0x00, // mov ecx, GPA_QUEUES + 0x400
211    0x89, 0x08, //
212    0xB8, 0x90, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_AVAIL_LOW
213    0xB9, 0x00, 0x65, 0x00, 0x00, // mov ecx, GPA_QUEUES + 0x500
214    0x89, 0x08, //
215    0xB8, 0xA0, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_USED_LOW
216    0xB9, 0x00, 0x66, 0x00, 0x00, // mov ecx, GPA_QUEUES + 0x600
217    0x89, 0x08, //
218    0xB8, 0x44, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_READY
219    0xB9, 0x01, 0x00, 0x00, 0x00, // mov ecx, 1
220    0x89, 0x08, //
221    0xB8, 0x50, 0x00, 0xB0, 0xFE, // mov eax, QUEUE_NOTIFY
222    0xB9, 0x00, 0x00, 0x00, 0x00, // mov ecx, 0 (receive queue)
223    0x89, 0x08, //
224    0x8A, 0x04, 0x25, 0x00, 0x74, 0x00, 0x00, // mov al, byte [0x7400]
225    0xE6, 0xE9, // out 0xE9, al
226    0xF4, // hlt
227];
228
229// Block phase.
230/// Guest-physical address of the virtio block transport page.
231#[allow(dead_code)] // Retained block self-test MMIO constant.
232const BLK_MMIO_BASE: u64 = 0xFEB0_1000;
233/// First byte of the disk sector the guest reads back.
234const BLK_MARKER: u8 = b'D';
235/// Guest code of the block phase.
236///
237/// Programs the virtio block transport (status, request queue, queue address
238/// registers, ready, notify), then reads the first byte of the data buffer
239/// (written by the kernel device model), reports it on the debug port and
240/// halts.
241const BLK_GUEST_CODE: &[u8] = &[
242    0xB8, 0x70, 0x10, 0xB0, 0xFE, // mov eax, BLK_MMIO_BASE + 0x70 (STATUS)
243    0xB9, 0x0F, 0x00, 0x00, 0x00, // mov ecx, ACK | DRIVER | FEATURES_OK | DRIVER_OK
244    0x89, 0x08, //
245    0xB8, 0x30, 0x10, 0xB0, 0xFE, // mov eax, QUEUE_SEL
246    0xB9, 0x00, 0x00, 0x00, 0x00, // mov ecx, 0 (request queue)
247    0x89, 0x08, //
248    0xB8, 0x38, 0x10, 0xB0, 0xFE, // mov eax, QUEUE_NUM
249    0xB9, 0x08, 0x00, 0x00, 0x00, // mov ecx, 8
250    0x89, 0x08, //
251    0xB8, 0x80, 0x10, 0xB0, 0xFE, // mov eax, QUEUE_DESC_LOW
252    0xB9, 0x00, 0x60, 0x00, 0x00, // mov ecx, GPA_QUEUES
253    0x89, 0x08, //
254    0xB8, 0x90, 0x10, 0xB0, 0xFE, // mov eax, QUEUE_AVAIL_LOW
255    0xB9, 0x00, 0x61, 0x00, 0x00, // mov ecx, GPA_QUEUES + 0x100
256    0x89, 0x08, //
257    0xB8, 0xA0, 0x10, 0xB0, 0xFE, // mov eax, QUEUE_USED_LOW
258    0xB9, 0x00, 0x62, 0x00, 0x00, // mov ecx, GPA_QUEUES + 0x200
259    0x89, 0x08, //
260    0xB8, 0x44, 0x10, 0xB0, 0xFE, // mov eax, QUEUE_READY
261    0xB9, 0x01, 0x00, 0x00, 0x00, // mov ecx, 1
262    0x89, 0x08, //
263    0xB8, 0x50, 0x10, 0xB0, 0xFE, // mov eax, QUEUE_NOTIFY
264    0xB9, 0x00, 0x00, 0x00, 0x00, // mov ecx, 0 (request queue)
265    0x89, 0x08, //
266    0x8A, 0x04, 0x25, 0x40, 0x70, 0x00, 0x00, // mov al, byte [0x7040]
267    0xE6, 0xE9, // out 0xE9, al
268    0xF4, // hlt
269];
270
271// Network phase.
272/// Guest-physical address of the virtio network transport page.
273#[allow(dead_code)] // Retained network self-test MMIO constant.
274const NET_MMIO_BASE: u64 = 0xFEB0_2000;
275/// Frame the kernel sends through the transmit queue.
276const NET_FRAME: &[u8] = b"PING";
277/// Marker written by the guest once the transmit queue was notified.
278const NET_MARKER: u8 = b'N';
279/// Guest code of the network phase.
280///
281/// Programs the virtio network transport (status, transmit queue, queue
282/// address registers, ready, notify), then reports through the debug port and
283/// halts. The kernel checks the frame captured by the device model.
284const NET_GUEST_CODE: &[u8] = &[
285    0xB8, 0x70, 0x20, 0xB0, 0xFE, // mov eax, NET_MMIO_BASE + 0x70 (STATUS)
286    0xB9, 0x0F, 0x00, 0x00, 0x00, // mov ecx, ACK | DRIVER | FEATURES_OK | DRIVER_OK
287    0x89, 0x08, //
288    0xB8, 0x30, 0x20, 0xB0, 0xFE, // mov eax, QUEUE_SEL
289    0xB9, 0x01, 0x00, 0x00, 0x00, // mov ecx, 1 (transmit queue)
290    0x89, 0x08, //
291    0xB8, 0x38, 0x20, 0xB0, 0xFE, // mov eax, QUEUE_NUM
292    0xB9, 0x08, 0x00, 0x00, 0x00, // mov ecx, 8
293    0x89, 0x08, //
294    0xB8, 0x80, 0x20, 0xB0, 0xFE, // mov eax, QUEUE_DESC_LOW
295    0xB9, 0x00, 0x60, 0x00, 0x00, // mov ecx, GPA_QUEUES
296    0x89, 0x08, //
297    0xB8, 0x90, 0x20, 0xB0, 0xFE, // mov eax, QUEUE_AVAIL_LOW
298    0xB9, 0x00, 0x61, 0x00, 0x00, // mov ecx, GPA_QUEUES + 0x100
299    0x89, 0x08, //
300    0xB8, 0xA0, 0x20, 0xB0, 0xFE, // mov eax, QUEUE_USED_LOW
301    0xB9, 0x00, 0x62, 0x00, 0x00, // mov ecx, GPA_QUEUES + 0x200
302    0x89, 0x08, //
303    0xB8, 0x44, 0x20, 0xB0, 0xFE, // mov eax, QUEUE_READY
304    0xB9, 0x01, 0x00, 0x00, 0x00, // mov ecx, 1
305    0x89, 0x08, //
306    0xB8, 0x50, 0x20, 0xB0, 0xFE, // mov eax, QUEUE_NOTIFY
307    0xB9, 0x01, 0x00, 0x00, 0x00, // mov ecx, 1 (transmit queue)
308    0x89, 0x08, //
309    0xB0, NET_MARKER, // mov al, marker
310    0xE6, 0xE9, // out 0xE9, al
311    0xF4, // hlt
312];
313
314// Loader phase.
315/// Guest-physical address of the page-table root used by the loaded guest.
316const LOADER_GPA_PML4: u64 = 0x0000;
317/// Guest-physical address of the page-directory pointer table.
318const LOADER_GPA_PDPT: u64 = 0x1000;
319/// Guest-physical address of the page directory.
320const LOADER_GPA_PD: u64 = 0x2000;
321/// Guest-physical address of the page table (identity maps 0..2 MiB).
322const LOADER_GPA_PT: u64 = 0x3000;
323/// Guest-physical base address where the generated ELF image is loaded.
324const LOADER_IMAGE_BASE: u64 = 0x1_0000;
325/// Guest-physical page used as the guest stack.
326const LOADER_GPA_STACK: u64 = 0x2_0000;
327/// Initial guest stack pointer (inside the stack page).
328const LOADER_STACK_TOP: u64 = LOADER_GPA_STACK + 0x800;
329/// Guest memory permissions of the loader phase (read | write | execute).
330const LOADER_GUEST_PERMS: u32 = 7;
331/// Offset of the guest code inside the generated image.
332const LOADER_CODE_OFFSET: u64 = 0x100;
333
334// ACPI-discovery phase.
335//
336// The guest scans the legacy BIOS window `ACPI_SCAN_START..ACPI_SCAN_END` for
337// the RSDP, validates it, walks the XSDT and the MADT. Every page the payload
338// touches is identity-mapped by one page table covering the first 2 MiB, so
339// the scan window, the code and the stack share the same flat mapping.
340/// Guest-physical address of the page-table root.
341const ACPI_GPA_PML4: u64 = 0x0000;
342/// Guest-physical address of the page-directory pointer table.
343const ACPI_GPA_PDPT: u64 = 0x1000;
344/// Guest-physical address of the page directory.
345const ACPI_GPA_PD: u64 = 0x2000;
346/// Guest-physical address of the page table (identity maps 0..2 MiB).
347const ACPI_GPA_PT: u64 = 0x3000;
348/// Guest-physical page holding the discovery payload.
349const ACPI_GPA_CODE: u64 = 0x1_0000;
350/// Guest-physical page used as the guest stack.
351const ACPI_GPA_STACK: u64 = 0x1_1000;
352/// Initial guest stack pointer (inside the stack page).
353const ACPI_STACK_TOP: u64 = ACPI_GPA_STACK + 0x800;
354/// First guest-physical address of the scan window (legacy EBDA/BIOS area).
355const ACPI_SCAN_START: u64 = vm::ACPI_GPA;
356/// End (exclusive) of the scan window covered by the ACPI specification.
357const ACPI_SCAN_END: u64 = 0x10_0000;
358/// Number of 4 KiB guest pages in the scan window.
359const ACPI_SCAN_PAGES: u64 = (ACPI_SCAN_END - ACPI_SCAN_START) / crate::s9vm::mmu::PAGE_SIZE;
360/// Guest memory permissions of the page tables, the code and the stack.
361const ACPI_GUEST_PERMS: u32 = 7;
362/// Read-only guest permissions of the scan window (the guest only reads it).
363const ACPI_SCAN_PERMS: u32 = 1;
364/// Maximum number of exits driven for the ACPI phase (safety bound).
365const ACPI_MAX_EXITS: u32 = 64;
366
367/// Deferred request flag for the ACPI phase (see [`s9vm_acpi_selftest`]).
368static ACPI_SELFTEST_REQUESTED: AtomicBool = AtomicBool::new(false);
369
370// Guest-OS bootstrap phase.
371//
372// The guest behaves like the first stage of a real operating system: it reads
373// the boot-parameter block written by `vm::write_boot_params`, checks that the
374// fields a kernel needs are populated, discovers the ACPI RSDP in the legacy
375// BIOS window and verifies its checksum. Its payload is built with
376// `guestprog::guestos` (typed, decoder-validated encodings) instead of a
377// hand-written byte array. The phase registers a **detached** vCPU (required by
378// `write_acpi`, which describes it in the MADT) and drives it with a direct run
379// loop, so it needs neither the scheduler nor a kernel thread.
380/// Guest-physical address of the page-table root.
381const GUESTOS_GPA_PML4: u64 = 0x0000;
382/// Guest-physical address of the page-directory pointer table.
383const GUESTOS_GPA_PDPT: u64 = 0x1000;
384/// Guest-physical address of the page directory.
385const GUESTOS_GPA_PD: u64 = 0x2000;
386/// Guest-physical address of the page table (identity maps 0..2 MiB).
387const GUESTOS_GPA_PT: u64 = 0x3000;
388/// Guest-physical page holding the bootstrap payload.
389const GUESTOS_GPA_CODE: u64 = 0x4000;
390/// Guest-physical page used as the guest stack.
391const GUESTOS_GPA_STACK: u64 = 0x5000;
392/// Initial guest stack pointer (inside the stack page).
393const GUESTOS_STACK_TOP: u64 = GUESTOS_GPA_STACK + 0x800;
394/// Guest-physical page holding the 1024-byte boot-parameter block.
395const GUESTOS_GPA_BOOT_PARAMS: u64 = 0x6000;
396/// Guest-physical page the initrd/module blob is loaded at.
397const GUESTOS_GPA_MODULE: u64 = 0x7000;
398/// Guest memory permissions of the page tables, the payload and the stack.
399const GUESTOS_GUEST_PERMS: u32 = 7;
400/// First guest-physical address of the RSDP scan window.
401const GUESTOS_SCAN_START: u64 = vm::ACPI_GPA;
402/// End (exclusive) of the RSDP scan window.
403const GUESTOS_SCAN_END: u64 = 0x10_0000;
404/// Number of 4 KiB guest pages in the scan window.
405const GUESTOS_SCAN_PAGES: u64 =
406    (GUESTOS_SCAN_END - GUESTOS_SCAN_START) / crate::s9vm::mmu::PAGE_SIZE;
407/// Read-only guest permissions of the scan window.
408const GUESTOS_SCAN_PERMS: u32 = 1;
409/// Command line stored by the phase before the boot block is written.
410const GUESTOS_CMDLINE: &[u8] = b"console=serial s9vm.selftest=guestos root=/dev/vda1 ro";
411/// Small initrd/module blob stored by the phase (never parsed).
412const GUESTOS_MODULE: &[u8] = b"\x7fELF-s9vm-module";
413/// Maximum number of exits driven for the guest-OS phase (safety bound).
414const GUESTOS_MAX_EXITS: u32 = 128;
415/// Maximum number of debug-port bytes collected from the guest.
416const GUESTOS_DEBUG_BYTES: usize = 8;
417
418/// Deferred request flag for the guest-OS phase (see
419/// [`s9vm_guestos_selftest`]).
420static GUESTOS_SELFTEST_REQUESTED: AtomicBool = AtomicBool::new(false);
421
422// SMP (multi-vCPU) phase.
423//
424// One world hosts two vCPUs. Each vCPU has its own page tables, code page and
425// stack page, so the two guest contexts differ in CR3, RIP, RSP and marker;
426// both also write their marker into one shared guest page. The phase drives
427// the vCPUs through the kernel tasks (`request_run`) in an interleaved order:
428// round 0 runs both vCPUs to their `out` exit, round 1 resumes both from their
429// saved state to the `hlt` exit.
430/// Guest-physical page-table root of the first vCPU.
431const SMP_VCPU0_GPA_PML4: u64 = 0x0000;
432/// Guest-physical page-directory pointer table of the first vCPU.
433const SMP_VCPU0_GPA_PDPT: u64 = 0x1000;
434/// Guest-physical page directory of the first vCPU.
435const SMP_VCPU0_GPA_PD: u64 = 0x2000;
436/// Guest-physical page table of the first vCPU.
437const SMP_VCPU0_GPA_PT: u64 = 0x3000;
438/// Code page of the first vCPU.
439const SMP_VCPU0_GPA_CODE: u64 = 0x1_0000;
440/// Stack page of the first vCPU.
441const SMP_VCPU0_GPA_STACK: u64 = 0x1_1000;
442/// Guest-physical page-table root of the second vCPU.
443const SMP_VCPU1_GPA_PML4: u64 = 0x8000;
444/// Guest-physical page-directory pointer table of the second vCPU.
445const SMP_VCPU1_GPA_PDPT: u64 = 0x9000;
446/// Guest-physical page directory of the second vCPU.
447const SMP_VCPU1_GPA_PD: u64 = 0xA000;
448/// Guest-physical page table of the second vCPU.
449const SMP_VCPU1_GPA_PT: u64 = 0xB000;
450/// Code page of the second vCPU.
451const SMP_VCPU1_GPA_CODE: u64 = 0x1_2000;
452/// Stack page of the second vCPU.
453const SMP_VCPU1_GPA_STACK: u64 = 0x1_3000;
454/// Guest memory permissions of the SMP page tables, code and stacks.
455const SMP_GUEST_PERMS: u32 = 7;
456/// Maximum number of `request_run` calls driven by the SMP phase.
457const SMP_MAX_RUNS: u32 = 8;
458/// Bounded wait for the two SMP RUN completions / idle transition (2 s).
459const SMP_EXIT_TIMEOUT_NS: u64 = 2_000_000_000;
460
461/// Static description of one vCPU of the SMP phase.
462struct SmpLayout {
463    pml4: u64,
464    pdpt: u64,
465    pd: u64,
466    pt: u64,
467    code: u64,
468    stack: u64,
469    stack_top: u64,
470    marker: u8,
471    payload: &'static [u8],
472}
473
474/// Layouts of the two vCPUs, in APIC-id order.
475const SMP_LAYOUTS: [SmpLayout; 2] = [
476    SmpLayout {
477        pml4: SMP_VCPU0_GPA_PML4,
478        pdpt: SMP_VCPU0_GPA_PDPT,
479        pd: SMP_VCPU0_GPA_PD,
480        pt: SMP_VCPU0_GPA_PT,
481        code: SMP_VCPU0_GPA_CODE,
482        stack: SMP_VCPU0_GPA_STACK,
483        stack_top: SMP_VCPU0_GPA_STACK + 0x800,
484        marker: SMP_MARKERS[0],
485        payload: SMP_CODE_0,
486    },
487    SmpLayout {
488        pml4: SMP_VCPU1_GPA_PML4,
489        pdpt: SMP_VCPU1_GPA_PDPT,
490        pd: SMP_VCPU1_GPA_PD,
491        pt: SMP_VCPU1_GPA_PT,
492        code: SMP_VCPU1_GPA_CODE,
493        stack: SMP_VCPU1_GPA_STACK,
494        stack_top: SMP_VCPU1_GPA_STACK + 0x800,
495        marker: SMP_MARKERS[1],
496        payload: SMP_CODE_1,
497    },
498];
499
500/// Bounded wait for one smoke RUN (500 ms).
501const KTHREAD_SMOKE_RUN_NS: u64 = 500_000_000;
502/// Bounded wait for destroying the smoke world (2 s).
503const KTHREAD_SMOKE_DESTROY_NS: u64 = 2_000_000_000;
504/// Deferred request flag for the SMP phase (see [`s9vm_smp_selftest`]).
505static SMP_SELFTEST_REQUESTED: AtomicBool = AtomicBool::new(false);
506
507/// Flat 64-bit code descriptor (selector `0x08`).
508///
509/// Interrupt delivery reloads `CS` from the gate selector, which requires the
510/// code-segment descriptor to exist in the GDT: without a GDT the delivery
511/// raises `#GP`, and with no handler for `#GP` the guest triple-faults.
512const GDT_CODE64: u64 = 0x00AF_9A00_0000_FFFF;
513/// Flat data descriptor (selector `0x10`).
514const GDT_DATA: u64 = 0x00CF_9200_0000_FFFF;
515/// Vector delivered by the kernel.
516const IRQ_VECTOR: u8 = 0x20;
517/// Byte written by the interrupt handler to the debug port.
518const IRQ_BYTE: u8 = 0x42;
519/// Offset of the handler inside the code page.
520const IRQ_HANDLER_OFFSET: u64 = 8;
521
522/// Guest code of the interrupt phase.
523///
524/// Entry: `sti` ; `nop` ; `hlt` ; padding. Handler (offset 8): writes the
525/// marker byte to the debug port, then halts.
526const IRQ_GUEST_CODE: [u8; 16] = [
527    0xFB, 0x90, 0xF4, 0x00, 0x00, 0x00, 0x00, 0x00, // sti ; nop ; hlt
528    0xB0, IRQ_BYTE, 0xE6, 0xE9, 0xF4, 0x00, 0x00, 0x00, // mov al,0x42; out 0xE9,al; hlt
529];
530
531/// Errors of the smoke test.
532#[derive(Debug, Clone, Copy, PartialEq, Eq)]
533pub enum SelftestError {
534    OutOfMemory,
535    Mmu,
536    Vcpu(VcpuError),
537    BadExit(&'static str),
538    VmFail(u32),
539}
540
541impl From<VcpuError> for SelftestError {
542    fn from(value: VcpuError) -> Self {
543        Self::Vcpu(value)
544    }
545}
546
547/// Detailed result, logged by the caller.
548pub struct SelftestReport {
549    pub io_exits: u32,
550    pub halt_exits: u32,
551    pub total_exits: u32,
552    /// Exits replayed by the kernel device model (never reported to policy).
553    pub emulated_exits: u32,
554    /// Last value read by the guest from the PIC data port.
555    pub pic_readback: Option<u8>,
556    /// Guest time slices that expired during the test.
557    pub timer_exits: u32,
558    pub observed_byte: Option<u8>,
559    /// Name of the guest-state variant that entered successfully.
560    pub variant: &'static str,
561}
562
563/// Allocates a zeroed frame for the guest.
564fn alloc_frame() -> Result<PhysFrame, SelftestError> {
565    crate::sync::with_irqs_disabled(|token| {
566        FrameAllocOptions::new()
567            .purpose(FramePurpose::KernelData)
568            .allocate(token)
569    })
570    .map_err(|_| SelftestError::OutOfMemory)
571}
572
573/// Writes a 64-bit value into a frame through the HHDM.
574fn write_u64(frame: &PhysFrame, offset: usize, value: u64) {
575    let base = crate::memory::phys_to_virt(frame.start_address.as_u64()) as *mut u8;
576    // SAFETY: the frame is 4 KiB and `offset` is a valid offset.
577    unsafe {
578        core::ptr::write_volatile(base.add(offset) as *mut u64, value);
579    }
580}
581
582/// Writes bytes at `offset` inside a frame through the HHDM.
583fn write_bytes_at(frame: &PhysFrame, offset: usize, bytes: &[u8]) {
584    let base = crate::memory::phys_to_virt(frame.start_address.as_u64()) as *mut u8;
585    // SAFETY: the frame is 4 KiB and `offset + bytes.len()` stays inside it.
586    unsafe {
587        for (index, byte) in bytes.iter().enumerate() {
588            core::ptr::write_volatile(base.add(offset + index), *byte);
589        }
590    }
591}
592
593/// Writes bytes into a frame through the HHDM.
594fn write_bytes(frame: &PhysFrame, bytes: &[u8]) {
595    let base = crate::memory::phys_to_virt(frame.start_address.as_u64()) as *mut u8;
596    // SAFETY: the frame is 4 KiB and `bytes` fits in one page.
597    unsafe {
598        for (index, byte) in bytes.iter().enumerate() {
599            core::ptr::write_volatile(base.add(index), *byte);
600        }
601    }
602}
603
604/// Enters the canonical guest and drives its exits. Returns a report on success.
605fn run_guest(
606    caps: &HwCaps,
607    second_level_pointer: u64,
608    guest: &GuestState,
609) -> Result<SelftestReport, SelftestError> {
610    let mut vcpu = Vcpu::new(caps, second_level_pointer)?;
611
612    // Local validation before entry: a state refused here would produce a
613    // "VM entry with invalid guest state" that is difficult to diagnose.
614    let fixed = crate::s9vm::guest::FixedBits {
615        cr0_fixed0: caps.cr0_fixed0,
616        cr0_fixed1: caps.cr0_fixed1,
617        cr4_fixed0: caps.cr4_fixed0,
618        cr4_fixed1: caps.cr4_fixed1,
619    };
620    if let Err(error) = guest.validate(&fixed, caps.unrestricted_guest) {
621        log::warn!("[s9vm] guest state refused by validate(): {:?}", error);
622    }
623
624    // SAFETY: VT-x is active on this CPU (checked by the caller), interrupts
625    // are disabled at the bootstrap stage, and the control
626    // block has just been created for this vCPU.
627    Vcpu::set_write_trace(true);
628    unsafe {
629        vcpu.load()?;
630        let error = vcpu.instruction_error();
631        if error != 0 {
632            log::warn!("[s9vm] instruction error after load: {:#x}", error);
633        }
634        vcpu.configure_host()?;
635        let error = vcpu.instruction_error();
636        if error != 0 {
637            log::warn!("[s9vm] instruction error after host state: {:#x}", error);
638        }
639        vcpu.configure(caps, guest)?;
640        let error = vcpu.instruction_error();
641        if error != 0 {
642            log::warn!("[s9vm] instruction error after guest state: {:#x}", error);
643        }
644        if let Some((field, error)) = Vcpu::write_trace_failure() {
645            log::warn!(
646                "[s9vm] first rejected vmwrite: field={:#x} error={:#x}",
647                field,
648                error
649            );
650        }
651    }
652    Vcpu::set_write_trace(false);
653
654    let mut report = SelftestReport {
655        io_exits: 0,
656        halt_exits: 0,
657        total_exits: 0,
658        emulated_exits: 0,
659        pic_readback: None,
660        timer_exits: 0,
661        observed_byte: None,
662        variant: "",
663    };
664
665    // Kernel device model: exits on these devices are replayed in place.
666    let mut machine = Machine::new();
667    let mut apic = LocalApic::new(0);
668
669    let mut outcome: Result<(), SelftestError> = Ok(());
670    for _ in 0..64 {
671        // SAFETY: `run` contract (block loaded, IRQs disabled).
672        let exit = match unsafe { vcpu.run() } {
673            Ok(exit) => exit,
674            Err(error) => {
675                // SAFETY: the control block is still loaded; useful
676                // diagnostic for `VmFail(8/9)` failures.
677                unsafe {
678                    log::warn!("[s9vm] {}", vcpu.host_diagnostics());
679                }
680                outcome = Err(SelftestError::from(error));
681                break;
682            }
683        };
684        report.total_exits += 1;
685        let class = ExitReason::decode(exit.raw_reason).class();
686        // Kernel fast path first: modeled device accesses are replayed in
687        // place and never reach the policy path.
688        if matches!(
689            class,
690            ExitClass::IoPort | ExitClass::Msr | ExitClass::EptViolation
691        ) {
692            // SAFETY: the control block is loaded and the guest is not
693            // running (we are in the exit handler).
694            match unsafe { machine.handle(&mut vcpu, &mut apic, &exit) } {
695                Ok(true) => {
696                    report.emulated_exits += 1;
697                    let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
698                    let is_in = (exit.qualification >> 3) & 0x1 != 0;
699                    if class == ExitClass::IoPort && port == PIC_DATA_PORT && is_in {
700                        report.pic_readback = Some((vcpu.guest().rax & 0xFF) as u8);
701                    }
702                    continue;
703                }
704                Ok(false) | Err(_) => {}
705            }
706        }
707        match class {
708            ExitClass::IoPort => {
709                report.io_exits += 1;
710                // I/O qualification: port in bits 16..31.
711                let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
712                if port == TEST_PORT {
713                    report.observed_byte = Some((vcpu.guest().rax & 0xFF) as u8);
714                }
715                log::info!(
716                    "[s9vm] I/O exit port={:#x} byte={:?} rip={:#x} len={}",
717                    port,
718                    report.observed_byte,
719                    vcpu.guest().rip,
720                    exit.instruction_length
721                );
722                // On a VM exit caused by an I/O instruction, GUEST_RIP points at
723                // the instruction itself, not the next one: the processor does
724                // not auto-advance. Skip it with the reported instruction length,
725                // otherwise the resume re-executes the `out` forever.
726                // SAFETY: the control block is loaded and the guest is inactive.
727                unsafe {
728                    vcpu.advance_rip(u64::from(exit.instruction_length))?;
729                }
730            }
731            ExitClass::Halt => {
732                report.halt_exits += 1;
733                break;
734            }
735            ExitClass::ExternalInterrupt | ExitClass::InterruptWindow => {
736                // At boot, host interrupts are masked: we simply
737                // resume the guest.
738            }
739            ExitClass::PreemptionTimer => {
740                // The guest time slice expired before the test finished: the
741                // test is short, so this only happens on a very slow host.
742                report.timer_exits += 1;
743            }
744            ExitClass::EntryFailure => {
745                // SAFETY: the control block is still loaded; diagnostic
746                // of the guest field refused by the processor.
747                unsafe {
748                    log::warn!("[s9vm] {}", vcpu.guest_diagnostics());
749                }
750                outcome = Err(SelftestError::BadExit("entry failure"));
751                break;
752            }
753            _ => {
754                let reason = ExitReason::decode(exit.raw_reason).reason;
755                log::warn!(
756                    "[s9vm] unexpected exit: reason={:#x} ({}) class={:?} qual={:#x} \
757                     rip={:#x} exits={}",
758                    reason,
759                    reason_name(reason),
760                    class,
761                    exit.qualification,
762                    vcpu.guest().rip,
763                    report.total_exits,
764                );
765                // SAFETY: the control block is still loaded.
766                unsafe {
767                    log::warn!("[s9vm] {}", vcpu.guest_diagnostics());
768                }
769                outcome = Err(SelftestError::BadExit("unexpected exit"));
770                break;
771            }
772        }
773    }
774
775    // SAFETY: the vCPU is no longer active; we unload its control block.
776    unsafe {
777        let _ = vcpu.clear();
778    }
779
780    match outcome {
781        Ok(())
782            if report.io_exits == 1
783                && report.halt_exits >= 1
784                && report.emulated_exits >= 1
785                && report.pic_readback == Some(PIC_READBACK) =>
786        {
787            Ok(report)
788        }
789        Ok(()) => Err(SelftestError::BadExit("guest device fast path failed")),
790        Err(error) => Err(error),
791    }
792}
793
794/// Runs the smoke test. Returns the report of the first variant that entered.
795pub fn run(caps: &HwCaps) -> Result<SelftestReport, SelftestError> {
796    if !caps.can_run() {
797        return Err(SelftestError::BadExit("platform cannot run"));
798    }
799
800    // Guest pages: PML4, PDPT, PD, code, stack, PT.
801    let pml4 = alloc_frame()?;
802    let pdpt = alloc_frame()?;
803    let pd = alloc_frame()?;
804    let code = alloc_frame()?;
805    let stack = alloc_frame()?;
806    let pt = alloc_frame()?;
807
808    // Guest paging tables: GVA = GPA identity over 6 pages.
809    //
810    // The entries must hold *guest-physical* addresses (the GPA_* constants),
811    // not the host-physical frame addresses: the guest MMU walk yields GPAs,
812    // which the EPT then translates to HPAs. Writing HPAs here sends the walk
813    // to an unmapped GPA (EPT violation on the second level).
814    write_u64(&pml4, 0, GPA_PDPT | 0x3);
815    write_u64(&pdpt, 0, GPA_PD | 0x3);
816    write_u64(&pd, 0, GPA_PT | 0x3);
817    for page in 0..GUEST_PAGES {
818        let gpa = page * crate::s9vm::mmu::PAGE_SIZE;
819        write_u64(&pt, page as usize * 8, gpa | 0x3);
820    }
821
822    // Guest code:
823    //   1. program the master 8259A (ICW1..ICW4) through ports 0x20/0x21;
824    //   2. mask every line, then read the mask back (kernel fast path);
825    //   3. write one byte to the debug port (policy path) and halt.
826    // Steps 1 and 2 must be serviced by the kernel without a policy exit.
827    write_bytes(
828        &code,
829        &[
830            0xB0,
831            0x11,
832            0xE6,
833            0x20, // mov al, 0x11 ; out 0x20, al (ICW1)
834            0xB0,
835            0x20,
836            0xE6,
837            0x21, // mov al, 0x20 ; out 0x21, al (ICW2)
838            0xB0,
839            0x04,
840            0xE6,
841            0x21, // mov al, 0x04 ; out 0x21, al (ICW3)
842            0xB0,
843            0x01,
844            0xE6,
845            0x21, // mov al, 0x01 ; out 0x21, al (ICW4)
846            0xB0,
847            0x00,
848            0xE6,
849            0x21, // mov al, 0x00 ; out 0x21, al (unmask)
850            0xE4,
851            0x21, // in al, 0x21 (mask = 0x00)
852            0xB0,
853            PIC_READBACK,
854            0xE6,
855            0x21, // mov al, 0xFF ; out 0x21, al
856            0xE4,
857            0x21, // in al, 0x21 (mask = 0xFF)
858            0xB0,
859            TEST_BYTE,
860            0xE6,
861            TEST_PORT as u8, // mov al, byte ; out 0xE9, al
862            0xF4,            // hlt
863        ],
864    );
865
866    // Second-level translation: GPA → HPA for the 6 pages.
867    let mut second_level = SecondLevelMemory::new().map_err(|_| SelftestError::Mmu)?;
868    let pages = [
869        (GPA_PML4, &pml4),
870        (GPA_PDPT, &pdpt),
871        (GPA_PD, &pd),
872        (GPA_CODE, &code),
873        (GPA_STACK, &stack),
874        (GPA_PT, &pt),
875    ];
876    for (gpa, frame) in pages {
877        second_level
878            .map_4k(
879                gpa,
880                frame.start_address.as_u64(),
881                crate::s9vm::mmu::Perms::read_write_execute(),
882            )
883            .map_err(|_| SelftestError::Mmu)?;
884    }
885    let pointer = second_level.pointer(caps);
886
887    let guest = GuestState::long_mode_64(ENTRY_POINT, STACK_TOP, GPA_PML4);
888    match run_guest(caps, pointer, &guest) {
889        Ok(mut report) => {
890            report.variant = "canonical";
891            log::info!("[s9vm] guest entered (canonical 64-bit flat state)");
892            Ok(report)
893        }
894        Err(error) => {
895            log::warn!("[s9vm] guest failed: {:?}", error);
896            Err(error)
897        }
898    }
899}
900
901/// Report of the interrupt-delivery phase.
902pub struct InterruptReport {
903    pub total_exits: u32,
904    pub window_exits: u32,
905    pub io_exits: u32,
906    pub halt_exits: u32,
907    pub injected: u32,
908    pub observed_byte: Option<u8>,
909}
910
911/// Interrupt-delivery test.
912///
913/// The guest installs an interrupt gate for [`IRQ_VECTOR`], enables
914/// interrupts, and expects the vector injected by the kernel. This exercises
915/// the interrupt window: the guest is not interruptible at entry (`IF = 0`),
916/// so the kernel arms interrupt-window exiting; the `sti` opens the window,
917/// the kernel injects the pending vector, and the handler runs.
918pub fn run_interrupt(caps: &HwCaps) -> Result<InterruptReport, SelftestError> {
919    if !caps.can_run() {
920        return Err(SelftestError::BadExit("platform cannot run"));
921    }
922
923    // Guest pages: tables, code, stack, IDT.
924    let pml4 = alloc_frame()?;
925    let pdpt = alloc_frame()?;
926    let pd = alloc_frame()?;
927    let code = alloc_frame()?;
928    let stack = alloc_frame()?;
929    let pt = alloc_frame()?;
930    let idt = alloc_frame()?;
931    let gdt = alloc_frame()?;
932
933    // Identity guest paging over the eight pages.
934    write_u64(&pml4, 0, GPA_PDPT | 0x3);
935    write_u64(&pdpt, 0, GPA_PD | 0x3);
936    write_u64(&pd, 0, GPA_PT | 0x3);
937    for page in 0..IRQ_GUEST_PAGES {
938        let gpa = page * crate::s9vm::mmu::PAGE_SIZE;
939        write_u64(&pt, page as usize * 8, gpa | 0x3);
940    }
941
942    write_bytes(&code, &IRQ_GUEST_CODE);
943
944    // Interrupt gate: present, DPL 0, 64-bit interrupt gate (type 0xE).
945    let handler = GPA_CODE + IRQ_HANDLER_OFFSET;
946    let low = (handler & 0xFFFF)
947        | (0x8 << 16)          // code selector
948        | (0x8E << 40)         // type: present, DPL 0, 64-bit interrupt gate
949        | (((handler >> 16) & 0xFFFF) << 48);
950    let high = handler >> 32;
951    let entry_offset = usize::from(IRQ_VECTOR) * 16;
952    write_u64(&idt, entry_offset, low);
953    write_u64(&idt, entry_offset + 8, high);
954
955    // Minimal GDT: null, 64-bit code (0x08), flat data (0x10).
956    write_u64(&gdt, 8, GDT_CODE64);
957    write_u64(&gdt, 16, GDT_DATA);
958
959    // Second-level translation.
960    let mut second_level = SecondLevelMemory::new().map_err(|_| SelftestError::Mmu)?;
961    let pages = [
962        (GPA_PML4, &pml4),
963        (GPA_PDPT, &pdpt),
964        (GPA_PD, &pd),
965        (GPA_CODE, &code),
966        (GPA_STACK, &stack),
967        (GPA_PT, &pt),
968        (GPA_IDT, &idt),
969        (GPA_GDT, &gdt),
970    ];
971    for (gpa, frame) in pages {
972        second_level
973            .map_4k(
974                gpa,
975                frame.start_address.as_u64(),
976                crate::s9vm::mmu::Perms::read_write_execute(),
977            )
978            .map_err(|_| SelftestError::Mmu)?;
979    }
980    let pointer = second_level.pointer(caps);
981
982    // The guest starts with interrupts disabled; the kernel will arm the
983    // interrupt window.
984    let mut guest = GuestState::long_mode_64(ENTRY_POINT, STACK_TOP, GPA_PML4);
985    guest.idtr_base = GPA_IDT;
986    guest.idtr_limit = u32::from(IRQ_VECTOR) * 16 + 15;
987    // Interrupt delivery reloads CS from the gate selector, which reads the
988    // code-segment descriptor from the GDT.
989    guest.gdtr_base = GPA_GDT;
990    guest.gdtr_limit = 16 + 7;
991
992    let mut vcpu = Vcpu::new(caps, pointer)?;
993    // SAFETY: VT-x is active on this CPU (checked above), interrupts are
994    // disabled, and the block was just created for this vCPU.
995    unsafe {
996        vcpu.load()?;
997        vcpu.configure_host()?;
998        vcpu.configure(caps, &guest)?;
999    }
1000
1001    let mut apic = LocalApic::new(0);
1002    apic.inject(IRQ_VECTOR);
1003
1004    let mut report = InterruptReport {
1005        total_exits: 0,
1006        window_exits: 0,
1007        io_exits: 0,
1008        halt_exits: 0,
1009        injected: 0,
1010        observed_byte: None,
1011    };
1012    let mut window_armed = false;
1013    let mut outcome: Result<(), SelftestError> = Ok(());
1014
1015    for _ in 0..32 {
1016        // Same delivery policy as the execution loop: RFLAGS.IF plus the
1017        // interruptibility state (blocking by STI/MOV SS suppresses delivery).
1018        let pending = apic.pending_vector();
1019        let mut interruptible = vcpu.guest().rflags & (1 << 9) != 0;
1020        if interruptible && pending.is_some() {
1021            // SAFETY: block loaded, guest inactive.
1022            match unsafe { vcpu.interruptibility() } {
1023                Ok(state) => interruptible = interrupt_deliverable(true, state),
1024                Err(error) => {
1025                    outcome = Err(SelftestError::from(error));
1026                    break;
1027                }
1028            }
1029        }
1030        match interrupt_action(pending.is_some(), interruptible, window_armed) {
1031            InterruptAction::Inject => {
1032                if let Some(vector) = pending {
1033                    // SAFETY: the block is loaded and the guest is inactive.
1034                    unsafe {
1035                        vcpu.inject_interrupt(vector)?;
1036                    }
1037                    let _ = apic.service();
1038                    report.injected += 1;
1039                }
1040                if window_armed {
1041                    // SAFETY: same contract.
1042                    unsafe {
1043                        vcpu.set_interrupt_window_exiting(caps, false)?;
1044                    }
1045                    window_armed = false;
1046                }
1047            }
1048            InterruptAction::ArmWindow => {
1049                // SAFETY: same contract.
1050                window_armed = unsafe { vcpu.set_interrupt_window_exiting(caps, true)? };
1051                if !window_armed {
1052                    outcome = Err(SelftestError::BadExit("interrupt window unavailable"));
1053                    break;
1054                }
1055            }
1056            InterruptAction::DisarmWindow => {
1057                // SAFETY: same contract.
1058                unsafe {
1059                    vcpu.set_interrupt_window_exiting(caps, false)?;
1060                }
1061                window_armed = false;
1062            }
1063            InterruptAction::None => {}
1064        }
1065
1066        // SAFETY: `run` contract (block loaded, IRQs disabled).
1067        let exit = match unsafe { vcpu.run() } {
1068            Ok(exit) => exit,
1069            Err(error) => {
1070                outcome = Err(SelftestError::from(error));
1071                break;
1072            }
1073        };
1074        report.total_exits += 1;
1075        match ExitReason::decode(exit.raw_reason).class() {
1076            ExitClass::IoPort => {
1077                report.io_exits += 1;
1078                let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
1079                if port == TEST_PORT {
1080                    report.observed_byte = Some((vcpu.guest().rax & 0xFF) as u8);
1081                }
1082                // SAFETY: block loaded, guest inactive.
1083                unsafe {
1084                    vcpu.advance_rip(u64::from(exit.instruction_length))?;
1085                }
1086            }
1087            ExitClass::Halt => {
1088                report.halt_exits += 1;
1089                break;
1090            }
1091            ExitClass::InterruptWindow => {
1092                report.window_exits += 1;
1093            }
1094            ExitClass::PreemptionTimer => {}
1095            ExitClass::ExternalInterrupt => {}
1096            other => {
1097                log::warn!(
1098                    "[s9vm] interrupt test: unexpected exit class={:?} reason={:#x} \
1099                     qual={:#x} intr={:#x} rflags={:#x} rip={:#x} window={}",
1100                    other,
1101                    exit.raw_reason,
1102                    exit.qualification,
1103                    exit.interrupt_info,
1104                    vcpu.guest().rflags,
1105                    vcpu.guest().rip,
1106                    window_armed
1107                );
1108                outcome = Err(SelftestError::BadExit("unexpected interrupt-test exit"));
1109                break;
1110            }
1111        }
1112    }
1113
1114    // SAFETY: the vCPU is no longer active.
1115    unsafe {
1116        let _ = vcpu.clear();
1117    }
1118
1119    match outcome {
1120        Ok(())
1121            if report.injected >= 1
1122                && report.halt_exits >= 1
1123                && report.observed_byte == Some(IRQ_BYTE) =>
1124        {
1125            Ok(report)
1126        }
1127        Ok(()) => Err(SelftestError::BadExit("interrupt was not delivered")),
1128        Err(error) => Err(error),
1129    }
1130}
1131
1132/// Report of the console phase.
1133pub struct ConsoleReport {
1134    pub total_exits: u32,
1135    pub emulated_exits: u32,
1136    pub io_exits: u32,
1137    pub halt_exits: u32,
1138    pub marker: Option<u8>,
1139    pub output: Vec<u8>,
1140}
1141
1142/// Console transport test.
1143///
1144/// The kernel prepares a transmit queue (descriptor, available ring, buffer)
1145/// **and** a receive queue in guest memory, and queues one input byte. The
1146/// guest programs the transport page, notifies the transmit queue (the device
1147/// must collect the buffer) and then the receive queue (the device must write
1148/// the queued byte into the guest buffer). The guest reports that byte on the
1149/// debug port. This validates both directions of the transport: EPT
1150/// violation, instruction replay, register file, split-queue access to guest
1151/// memory, and the input/output routing.
1152pub fn run_console(caps: &HwCaps) -> Result<ConsoleReport, SelftestError> {
1153    if !caps.can_run() {
1154        return Err(SelftestError::BadExit("platform cannot run"));
1155    }
1156
1157    let pml4 = alloc_frame()?;
1158    let pdpt = alloc_frame()?;
1159    let pd = alloc_frame()?;
1160    let pt = alloc_frame()?;
1161    let code = alloc_frame()?;
1162    let stack = alloc_frame()?;
1163    let queues = alloc_frame()?;
1164    let buffer = alloc_frame()?;
1165    let pd_high = alloc_frame()?;
1166
1167    // Identity guest paging over the nine pages, plus a 2 MiB identity page
1168    // covering the device MMIO window. Without it the guest would take a page
1169    // fault (unmapped linear address) *before* the EPT violation that the
1170    // transport emulation relies on, and with no IDT that is a triple fault.
1171    write_u64(&pml4, 0, CONSOLE_GPA_PDPT | 0x3);
1172    write_u64(&pdpt, 0, CONSOLE_GPA_PD | 0x3);
1173    write_u64(&pdpt, 3 * 8, CONSOLE_GPA_PD_HIGH | 0x3);
1174    write_u64(&pd, 0, CONSOLE_GPA_PT | 0x3);
1175    write_u64(
1176        &pd_high,
1177        CONSOLE_PD_MMIO_INDEX * 8,
1178        CONSOLE_GPA_MMIO_WINDOW | 0x83, // present | read-write | 2 MiB page
1179    );
1180    for page in 0..CONSOLE_GUEST_PAGES {
1181        let gpa = page * crate::s9vm::mmu::PAGE_SIZE;
1182        write_u64(&pt, page as usize * 8, gpa | 0x3);
1183    }
1184
1185    write_bytes(&code, CONSOLE_GUEST_CODE);
1186
1187    // Transmit queue prepared by the kernel:
1188    // - descriptor 0 at offset 0: device-readable buffer;
1189    // - available ring at offset 0x100: one published descriptor;
1190    // - used ring at offset 0x200: zeroed.
1191    let descriptor: [u8; 16] = {
1192        let mut bytes = [0u8; 16];
1193        bytes[..8].copy_from_slice(&GPA_CONSOLE_BUFFER.to_le_bytes());
1194        bytes[8..12].copy_from_slice(&(CONSOLE_TEXT.len() as u32).to_le_bytes());
1195        bytes
1196    };
1197    write_bytes(&queues, &descriptor);
1198    // flags = 0, idx = 1, ring[0] = 0 (transmit).
1199    write_u64(&queues, 0x100, 1 << 16);
1200
1201    // Receive queue: descriptor 0 at +0x400 points to the buffer at +0x7400
1202    // and is device-writable; available ring at +0x500 publishes it.
1203    let receive = [0u8; 16];
1204    let mut receive = receive;
1205    receive[..8].copy_from_slice(&(GPA_CONSOLE_BUFFER + 0x400).to_le_bytes());
1206    receive[8..12].copy_from_slice(&16u32.to_le_bytes());
1207    receive[12..14].copy_from_slice(&virtio::DESC_F_WRITE.to_le_bytes());
1208    write_bytes(&queues, &[]);
1209    write_bytes_at(&queues, 0x400, &receive);
1210    write_u64(&queues, 0x500, 1 << 16);
1211
1212    write_bytes(&buffer, CONSOLE_TEXT);
1213
1214    let mut second_level = SecondLevelMemory::new().map_err(|_| SelftestError::Mmu)?;
1215    let pages = [
1216        (CONSOLE_GPA_PML4, &pml4),
1217        (CONSOLE_GPA_PDPT, &pdpt),
1218        (CONSOLE_GPA_PD, &pd),
1219        (CONSOLE_GPA_PT, &pt),
1220        (CONSOLE_GPA_CODE, &code),
1221        (CONSOLE_GPA_STACK, &stack),
1222        (GPA_QUEUES, &queues),
1223        (GPA_CONSOLE_BUFFER, &buffer),
1224        (CONSOLE_GPA_PD_HIGH, &pd_high),
1225    ];
1226    for (gpa, frame) in pages {
1227        second_level
1228            .map_4k(
1229                gpa,
1230                frame.start_address.as_u64(),
1231                crate::s9vm::mmu::Perms::read_write_execute(),
1232            )
1233            .map_err(|_| SelftestError::Mmu)?;
1234    }
1235    let pointer = second_level.pointer(caps);
1236
1237    let guest = GuestState::long_mode_64(
1238        CONSOLE_GPA_CODE,
1239        CONSOLE_GPA_STACK + 0x800,
1240        CONSOLE_GPA_PML4,
1241    );
1242    let mut vcpu = Vcpu::new(caps, pointer)?;
1243    // SAFETY: VT-x is active on this CPU, interrupts are disabled and the
1244    // control block was just created for this vCPU.
1245    unsafe {
1246        vcpu.load()?;
1247        vcpu.configure_host()?;
1248        vcpu.configure(caps, &guest)?;
1249    }
1250
1251    let mut machine = Machine::new();
1252    // One byte is waiting in the console input queue before the guest starts.
1253    machine.devices_mut().console.push_input(&[CONSOLE_RX_BYTE]);
1254    let mut apic = LocalApic::new(0);
1255    let mut report = ConsoleReport {
1256        total_exits: 0,
1257        emulated_exits: 0,
1258        io_exits: 0,
1259        halt_exits: 0,
1260        marker: None,
1261        output: Vec::new(),
1262    };
1263    let mut outcome: Result<(), SelftestError> = Ok(());
1264
1265    for _ in 0..64 {
1266        // SAFETY: `run` contract (block loaded, IRQs disabled).
1267        let exit = match unsafe { vcpu.run() } {
1268            Ok(exit) => exit,
1269            Err(error) => {
1270                outcome = Err(SelftestError::from(error));
1271                break;
1272            }
1273        };
1274        report.total_exits += 1;
1275        let class = ExitReason::decode(exit.raw_reason).class();
1276        if matches!(
1277            class,
1278            ExitClass::IoPort | ExitClass::Msr | ExitClass::EptViolation
1279        ) {
1280            // SAFETY: block loaded, guest inactive.
1281            match unsafe { machine.handle(&mut vcpu, &mut apic, &exit) } {
1282                Ok(true) => {
1283                    report.emulated_exits += 1;
1284                    report.output.extend(machine.drain_console());
1285                    let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
1286                    if class == ExitClass::IoPort && port == TEST_PORT {
1287                        report.marker = Some((vcpu.guest().rax & 0xFF) as u8);
1288                    }
1289                    continue;
1290                }
1291                Ok(false) | Err(_) => {}
1292            }
1293        }
1294        match class {
1295            ExitClass::IoPort => {
1296                report.io_exits += 1;
1297                let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
1298                if port == TEST_PORT {
1299                    report.marker = Some((vcpu.guest().rax & 0xFF) as u8);
1300                }
1301                // SAFETY: block loaded, guest inactive.
1302                unsafe {
1303                    vcpu.advance_rip(u64::from(exit.instruction_length))?;
1304                }
1305            }
1306            ExitClass::Halt => {
1307                report.halt_exits += 1;
1308                break;
1309            }
1310            ExitClass::ExternalInterrupt | ExitClass::InterruptWindow => {}
1311            ExitClass::PreemptionTimer => {}
1312            other => {
1313                log::warn!(
1314                    "[s9vm] console test: unexpected exit class={:?} reason={:#x} \
1315                     qual={:#x} gpa={:#x} rip={:#x}",
1316                    other,
1317                    exit.raw_reason,
1318                    exit.qualification,
1319                    exit.guest_physical_address,
1320                    vcpu.guest().rip
1321                );
1322                outcome = Err(SelftestError::BadExit("unexpected console-test exit"));
1323                break;
1324            }
1325        }
1326    }
1327
1328    // SAFETY: the vCPU is no longer active.
1329    unsafe {
1330        let _ = vcpu.clear();
1331    }
1332
1333    match outcome {
1334        Ok(())
1335            if report.halt_exits >= 1
1336                && report.marker == Some(CONSOLE_RX_BYTE)
1337                && report.output == CONSOLE_TEXT =>
1338        {
1339            Ok(report)
1340        }
1341        Ok(()) => Err(SelftestError::BadExit("console data was not delivered")),
1342        Err(error) => Err(error),
1343    }
1344}
1345
1346/// Report of the block phase.
1347pub struct BlockReport {
1348    pub total_exits: u32,
1349    pub emulated_exits: u32,
1350    pub io_exits: u32,
1351    pub halt_exits: u32,
1352    pub marker: Option<u8>,
1353    pub requests: u32,
1354    pub status: u8,
1355}
1356
1357/// Block transport test.
1358///
1359/// The kernel publishes a read request in guest memory (header, 512-byte data
1360/// buffer, status byte) and pre-fills disk sector 0. The guest programs the
1361/// transport, notifies the request queue, and reads back the first byte of the
1362/// data buffer. This validates the block model end to end: EPT violation,
1363/// instruction replay, request parsing, disk access and completion.
1364pub fn run_blk(caps: &HwCaps) -> Result<BlockReport, SelftestError> {
1365    if !caps.can_run() {
1366        return Err(SelftestError::BadExit("platform cannot run"));
1367    }
1368
1369    let pml4 = alloc_frame()?;
1370    let pdpt = alloc_frame()?;
1371    let pd = alloc_frame()?;
1372    let pt = alloc_frame()?;
1373    let code = alloc_frame()?;
1374    let stack = alloc_frame()?;
1375    let queues = alloc_frame()?;
1376    let buffer = alloc_frame()?;
1377    let pd_high = alloc_frame()?;
1378
1379    // Same guest layout as the console phase: identity pages plus a 2 MiB
1380    // identity page covering the device MMIO window.
1381    write_u64(&pml4, 0, CONSOLE_GPA_PDPT | 0x3);
1382    write_u64(&pdpt, 0, CONSOLE_GPA_PD | 0x3);
1383    write_u64(&pdpt, 3 * 8, CONSOLE_GPA_PD_HIGH | 0x3);
1384    write_u64(&pd, 0, CONSOLE_GPA_PT | 0x3);
1385    write_u64(
1386        &pd_high,
1387        CONSOLE_PD_MMIO_INDEX * 8,
1388        CONSOLE_GPA_MMIO_WINDOW | 0x83,
1389    );
1390    for page in 0..CONSOLE_GUEST_PAGES {
1391        let gpa = page * crate::s9vm::mmu::PAGE_SIZE;
1392        write_u64(&pt, page as usize * 8, gpa | 0x3);
1393    }
1394
1395    write_bytes(&code, BLK_GUEST_CODE);
1396
1397    // Request prepared by the kernel:
1398    // - header at buffer+0x000 (type IN, sector 0);
1399    // - data buffer at buffer+0x040;
1400    // - status byte at buffer+0x400;
1401    // - descriptor chain: header (readable), data (writable), status (writable).
1402    write_u64(&buffer, 0, u64::from(virtio_blk::request::IN));
1403    write_u64(&buffer, 8, 0); // sector 0
1404    let mut descriptors = [0u8; 3 * 16];
1405    let header = virtio::Descriptor {
1406        addr: GPA_CONSOLE_BUFFER + 0x000,
1407        len: 16,
1408        flags: virtio::DESC_F_NEXT,
1409        next: 1,
1410    };
1411    let data = virtio::Descriptor {
1412        addr: GPA_CONSOLE_BUFFER + 0x040,
1413        len: 512,
1414        flags: virtio::DESC_F_NEXT | virtio::DESC_F_WRITE,
1415        next: 2,
1416    };
1417    let status = virtio::Descriptor {
1418        addr: GPA_CONSOLE_BUFFER + 0x400,
1419        len: 1,
1420        flags: virtio::DESC_F_WRITE,
1421        next: 0,
1422    };
1423    descriptors[..16].copy_from_slice(&header.encode());
1424    descriptors[16..32].copy_from_slice(&data.encode());
1425    descriptors[32..].copy_from_slice(&status.encode());
1426    write_bytes(&queues, &descriptors);
1427    // Available ring: idx = 1, ring[0] = 0.
1428    write_u64(&queues, 0x100, 1 << 16);
1429
1430    let mut second_level = SecondLevelMemory::new().map_err(|_| SelftestError::Mmu)?;
1431    let pages = [
1432        (CONSOLE_GPA_PML4, &pml4),
1433        (CONSOLE_GPA_PDPT, &pdpt),
1434        (CONSOLE_GPA_PD, &pd),
1435        (CONSOLE_GPA_PT, &pt),
1436        (CONSOLE_GPA_CODE, &code),
1437        (CONSOLE_GPA_STACK, &stack),
1438        (GPA_QUEUES, &queues),
1439        (GPA_CONSOLE_BUFFER, &buffer),
1440        (CONSOLE_GPA_PD_HIGH, &pd_high),
1441    ];
1442    for (gpa, frame) in pages {
1443        second_level
1444            .map_4k(
1445                gpa,
1446                frame.start_address.as_u64(),
1447                crate::s9vm::mmu::Perms::read_write_execute(),
1448            )
1449            .map_err(|_| SelftestError::Mmu)?;
1450    }
1451    let pointer = second_level.pointer(caps);
1452
1453    let guest = GuestState::long_mode_64(
1454        CONSOLE_GPA_CODE,
1455        CONSOLE_GPA_STACK + 0x800,
1456        CONSOLE_GPA_PML4,
1457    );
1458    let mut vcpu = Vcpu::new(caps, pointer)?;
1459    // SAFETY: VT-x active, interrupts disabled, control block freshly created.
1460    unsafe {
1461        vcpu.load()?;
1462        vcpu.configure_host()?;
1463        vcpu.configure(caps, &guest)?;
1464    }
1465
1466    let mut machine = Machine::new();
1467    // Disk content: first sector starts with the marker the guest reads back.
1468    let mut sector = [0u8; 512];
1469    sector[0] = BLK_MARKER;
1470    sector[1] = b'K';
1471    machine.devices_mut().blk.write_sector(0, &sector);
1472    let mut apic = LocalApic::new(0);
1473
1474    let mut report = BlockReport {
1475        total_exits: 0,
1476        emulated_exits: 0,
1477        io_exits: 0,
1478        halt_exits: 0,
1479        marker: None,
1480        requests: 0,
1481        status: 0,
1482    };
1483    let mut outcome: Result<(), SelftestError> = Ok(());
1484
1485    for _ in 0..64 {
1486        // SAFETY: `run` contract.
1487        let exit = match unsafe { vcpu.run() } {
1488            Ok(exit) => exit,
1489            Err(error) => {
1490                outcome = Err(SelftestError::from(error));
1491                break;
1492            }
1493        };
1494        report.total_exits += 1;
1495        let class = ExitReason::decode(exit.raw_reason).class();
1496        if matches!(
1497            class,
1498            ExitClass::IoPort | ExitClass::Msr | ExitClass::EptViolation
1499        ) {
1500            // SAFETY: block loaded, guest inactive.
1501            match unsafe { machine.handle(&mut vcpu, &mut apic, &exit) } {
1502                Ok(true) => {
1503                    report.emulated_exits += 1;
1504                    let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
1505                    if class == ExitClass::IoPort && port == TEST_PORT {
1506                        report.marker = Some((vcpu.guest().rax & 0xFF) as u8);
1507                    }
1508                    continue;
1509                }
1510                Ok(false) | Err(_) => {}
1511            }
1512        }
1513        match class {
1514            ExitClass::IoPort => {
1515                report.io_exits += 1;
1516                let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
1517                if port == TEST_PORT {
1518                    report.marker = Some((vcpu.guest().rax & 0xFF) as u8);
1519                }
1520                // SAFETY: block loaded, guest inactive.
1521                unsafe {
1522                    vcpu.advance_rip(u64::from(exit.instruction_length))?;
1523                }
1524            }
1525            ExitClass::Halt => {
1526                report.halt_exits += 1;
1527                break;
1528            }
1529            ExitClass::ExternalInterrupt | ExitClass::InterruptWindow => {}
1530            ExitClass::PreemptionTimer => {}
1531            other => {
1532                log::warn!(
1533                    "[s9vm] block test: unexpected exit class={:?} reason={:#x} qual={:#x} \
1534                     gpa={:#x} rip={:#x}",
1535                    other,
1536                    exit.raw_reason,
1537                    exit.qualification,
1538                    exit.guest_physical_address,
1539                    vcpu.guest().rip
1540                );
1541                outcome = Err(SelftestError::BadExit("unexpected block-test exit"));
1542                break;
1543            }
1544        }
1545    }
1546
1547    report.requests = machine.devices().blk.completed();
1548    report.status = machine.devices().blk.last_status();
1549
1550    // SAFETY: the vCPU is no longer active.
1551    unsafe {
1552        let _ = vcpu.clear();
1553    }
1554
1555    match outcome {
1556        Ok(())
1557            if report.halt_exits >= 1
1558                && report.marker == Some(BLK_MARKER)
1559                && report.status == virtio_blk::request_status::OK
1560                && report.requests >= 1 =>
1561        {
1562            Ok(report)
1563        }
1564        Ok(()) => Err(SelftestError::BadExit("block request was not served")),
1565        Err(error) => Err(error),
1566    }
1567}
1568
1569/// Report of the network phase.
1570pub struct NetworkReport {
1571    pub total_exits: u32,
1572    pub emulated_exits: u32,
1573    pub halt_exits: u32,
1574    pub marker: Option<u8>,
1575    pub transmitted: u32,
1576    pub payload: Vec<u8>,
1577}
1578
1579/// Network transport test.
1580///
1581/// The kernel publishes a transmit packet (10-byte virtio_net_hdr + payload)
1582/// in guest memory; the guest programs the transport and notifies the transmit
1583/// queue. The device model must capture the payload. This validates the
1584/// network transport page end to end.
1585pub fn run_net(caps: &HwCaps) -> Result<NetworkReport, SelftestError> {
1586    if !caps.can_run() {
1587        return Err(SelftestError::BadExit("platform cannot run"));
1588    }
1589
1590    let pml4 = alloc_frame()?;
1591    let pdpt = alloc_frame()?;
1592    let pd = alloc_frame()?;
1593    let pt = alloc_frame()?;
1594    let code = alloc_frame()?;
1595    let stack = alloc_frame()?;
1596    let queues = alloc_frame()?;
1597    let buffer = alloc_frame()?;
1598    let pd_high = alloc_frame()?;
1599
1600    write_u64(&pml4, 0, CONSOLE_GPA_PDPT | 0x3);
1601    write_u64(&pdpt, 0, CONSOLE_GPA_PD | 0x3);
1602    write_u64(&pdpt, 3 * 8, CONSOLE_GPA_PD_HIGH | 0x3);
1603    write_u64(&pd, 0, CONSOLE_GPA_PT | 0x3);
1604    write_u64(
1605        &pd_high,
1606        CONSOLE_PD_MMIO_INDEX * 8,
1607        CONSOLE_GPA_MMIO_WINDOW | 0x83,
1608    );
1609    for page in 0..CONSOLE_GUEST_PAGES {
1610        let gpa = page * crate::s9vm::mmu::PAGE_SIZE;
1611        write_u64(&pt, page as usize * 8, gpa | 0x3);
1612    }
1613
1614    write_bytes(&code, NET_GUEST_CODE);
1615
1616    // Transmit packet: zeroed network header, then the frame; one readable
1617    // descriptor publishes it.
1618    let mut packet = alloc::vec![0u8; virtio_net::NET_HDR_SIZE];
1619    packet.extend_from_slice(NET_FRAME);
1620    write_bytes(&buffer, &packet);
1621    let descriptor = virtio::Descriptor {
1622        addr: GPA_CONSOLE_BUFFER,
1623        len: packet.len() as u32,
1624        flags: 0,
1625        next: 0,
1626    };
1627    write_bytes(&queues, &descriptor.encode());
1628    // Available ring: idx = 1, ring[0] = 0.
1629    write_u64(&queues, 0x100, 1 << 16);
1630
1631    let mut second_level = SecondLevelMemory::new().map_err(|_| SelftestError::Mmu)?;
1632    let pages = [
1633        (CONSOLE_GPA_PML4, &pml4),
1634        (CONSOLE_GPA_PDPT, &pdpt),
1635        (CONSOLE_GPA_PD, &pd),
1636        (CONSOLE_GPA_PT, &pt),
1637        (CONSOLE_GPA_CODE, &code),
1638        (CONSOLE_GPA_STACK, &stack),
1639        (GPA_QUEUES, &queues),
1640        (GPA_CONSOLE_BUFFER, &buffer),
1641        (CONSOLE_GPA_PD_HIGH, &pd_high),
1642    ];
1643    for (gpa, frame) in pages {
1644        second_level
1645            .map_4k(
1646                gpa,
1647                frame.start_address.as_u64(),
1648                crate::s9vm::mmu::Perms::read_write_execute(),
1649            )
1650            .map_err(|_| SelftestError::Mmu)?;
1651    }
1652    let pointer = second_level.pointer(caps);
1653
1654    let guest = GuestState::long_mode_64(
1655        CONSOLE_GPA_CODE,
1656        CONSOLE_GPA_STACK + 0x800,
1657        CONSOLE_GPA_PML4,
1658    );
1659    let mut vcpu = Vcpu::new(caps, pointer)?;
1660    // SAFETY: VT-x active, interrupts disabled, control block freshly created.
1661    unsafe {
1662        vcpu.load()?;
1663        vcpu.configure_host()?;
1664        vcpu.configure(caps, &guest)?;
1665    }
1666
1667    let mut machine = Machine::new();
1668    let mut apic = LocalApic::new(0);
1669    let mut report = NetworkReport {
1670        total_exits: 0,
1671        emulated_exits: 0,
1672        halt_exits: 0,
1673        marker: None,
1674        transmitted: 0,
1675        payload: Vec::new(),
1676    };
1677    let mut outcome: Result<(), SelftestError> = Ok(());
1678
1679    for _ in 0..64 {
1680        // SAFETY: `run` contract.
1681        let exit = match unsafe { vcpu.run() } {
1682            Ok(exit) => exit,
1683            Err(error) => {
1684                outcome = Err(SelftestError::from(error));
1685                break;
1686            }
1687        };
1688        report.total_exits += 1;
1689        let class = ExitReason::decode(exit.raw_reason).class();
1690        if matches!(
1691            class,
1692            ExitClass::IoPort | ExitClass::Msr | ExitClass::EptViolation
1693        ) {
1694            // SAFETY: block loaded, guest inactive.
1695            match unsafe { machine.handle(&mut vcpu, &mut apic, &exit) } {
1696                Ok(true) => {
1697                    report.emulated_exits += 1;
1698                    let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
1699                    if class == ExitClass::IoPort && port == TEST_PORT {
1700                        report.marker = Some((vcpu.guest().rax & 0xFF) as u8);
1701                    }
1702                    continue;
1703                }
1704                Ok(false) | Err(_) => {}
1705            }
1706        }
1707        match class {
1708            ExitClass::IoPort => {
1709                let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
1710                if port == TEST_PORT {
1711                    report.marker = Some((vcpu.guest().rax & 0xFF) as u8);
1712                }
1713                // SAFETY: block loaded, guest inactive.
1714                unsafe {
1715                    vcpu.advance_rip(u64::from(exit.instruction_length))?;
1716                }
1717            }
1718            ExitClass::Halt => {
1719                report.halt_exits += 1;
1720                break;
1721            }
1722            ExitClass::ExternalInterrupt | ExitClass::InterruptWindow => {}
1723            ExitClass::PreemptionTimer => {}
1724            other => {
1725                log::warn!(
1726                    "[s9vm] network test: unexpected exit class={:?} reason={:#x} qual={:#x} \
1727                     gpa={:#x} rip={:#x}",
1728                    other,
1729                    exit.raw_reason,
1730                    exit.qualification,
1731                    exit.guest_physical_address,
1732                    vcpu.guest().rip
1733                );
1734                outcome = Err(SelftestError::BadExit("unexpected network-test exit"));
1735                break;
1736            }
1737        }
1738    }
1739
1740    report.transmitted = machine.devices().net.frames_sent();
1741    report.payload = machine.drain_network();
1742
1743    // SAFETY: the vCPU is no longer active.
1744    unsafe {
1745        let _ = vcpu.clear();
1746    }
1747
1748    match outcome {
1749        Ok(())
1750            if report.halt_exits >= 1
1751                && report.marker == Some(NET_MARKER)
1752                && report.transmitted >= 1
1753                && report.payload == NET_FRAME =>
1754        {
1755            Ok(report)
1756        }
1757        Ok(()) => Err(SelftestError::BadExit("network frame was not transmitted")),
1758        Err(error) => Err(error),
1759    }
1760}
1761
1762/// Report of the image-loader phase.
1763pub struct LoaderReport {
1764    pub total_exits: u32,
1765    pub io_exits: u32,
1766    pub halt_exits: u32,
1767    /// Byte written by the loaded guest on the debug port.
1768    pub marker: Option<u8>,
1769    /// Guest-physical entry point returned by the loader.
1770    pub entry: u64,
1771    /// Guest-physical image base address.
1772    pub image_base: u64,
1773    /// Guest pages covered by the loaded image span.
1774    pub pages: u64,
1775}
1776
1777/// Writes a little-endian `u16` at `offset` inside a byte buffer.
1778fn put_u16(bytes: &mut [u8], offset: usize, value: u16) {
1779    bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
1780}
1781
1782/// Writes a little-endian `u32` at `offset` inside a byte buffer.
1783fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
1784    bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
1785}
1786
1787/// Writes a little-endian `u64` at `offset` inside a byte buffer.
1788fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
1789    bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
1790}
1791
1792/// Builds a minimal ELF64 guest image in kernel memory.
1793///
1794/// Layout: ELF64 header, one `PT_LOAD` program header, then the guest code at
1795/// [`LOADER_CODE_OFFSET`]. The segment is loaded at [`LOADER_IMAGE_BASE`], its
1796/// file-backed prefix (`p_filesz`) covers the header and the code, and its
1797/// memory size (`p_memsz`) is one full page: the loader must zero the rest of
1798/// the page (BSS).
1799fn loader_image() -> Vec<u8> {
1800    let page_size = crate::s9vm::mmu::PAGE_SIZE;
1801    let code_offset = LOADER_CODE_OFFSET as usize;
1802    // Payload: zero padding up to the code page offset, then the code bytes.
1803    let mut image = vec![0u8; code_offset];
1804    image.extend_from_slice(LOADER_CODE);
1805    let file_size = image.len() as u64;
1806
1807    // File header and program header table, written by the shared builder.
1808    {
1809        let mut builder =
1810            ImageWriter::new(&mut image, ET_EXEC, LOADER_IMAGE_BASE + LOADER_CODE_OFFSET)
1811                .expect("static loader image: header fits");
1812        builder
1813            .add_load(
1814                PF_R | PF_X,
1815                0,
1816                LOADER_IMAGE_BASE,
1817                file_size,
1818                page_size,
1819                page_size,
1820            )
1821            .expect("static loader image: program header fits");
1822        let _ = builder.finish();
1823    }
1824    image
1825}
1826
1827/// Returns the HHDM pointer of the guest page at `gpa` in a world.
1828fn world_page(world_id: u64, gpa: u64) -> Result<*mut u8, SelftestError> {
1829    let hpa = vm::debug_translate(world_id, gpa).ok_or(SelftestError::Mmu)?;
1830    Ok(crate::memory::phys_to_virt(hpa) as *mut u8)
1831}
1832
1833/// Writes a 64-bit page-table entry at `offset` inside the guest page at `gpa`.
1834fn write_world_u64(
1835    world_id: u64,
1836    gpa: u64,
1837    offset: usize,
1838    value: u64,
1839) -> Result<(), SelftestError> {
1840    let page = world_page(world_id, gpa)?;
1841    // SAFETY: the page belongs to a world reserved for this test, is mapped by
1842    // the HHDM, and the callers keep `offset + 8` inside the 4 KiB page.
1843    unsafe {
1844        core::ptr::write_volatile(page.add(offset) as *mut u64, value);
1845    }
1846    Ok(())
1847}
1848
1849/// Reads one byte of the guest page at `gpa` in a world.
1850fn read_world_byte(world_id: u64, gpa: u64) -> Result<u8, SelftestError> {
1851    let page = world_page(world_id, gpa)?;
1852    // SAFETY: same invariant as `write_world_u64`; the first byte is inside
1853    // the page.
1854    Ok(unsafe { core::ptr::read_volatile(page) })
1855}
1856
1857/// Reads `out.len()` bytes at `gpa` in a world; the range must stay inside one
1858/// guest page.
1859fn read_world_bytes(world_id: u64, gpa: u64, out: &mut [u8]) -> Result<(), SelftestError> {
1860    let page_size = crate::s9vm::mmu::PAGE_SIZE as usize;
1861    let offset = (gpa as usize) & (page_size - 1);
1862    if out.len() > page_size || offset + out.len() > page_size {
1863        return Err(SelftestError::BadExit("read crosses a page boundary"));
1864    }
1865    let page = world_page(world_id, gpa)?;
1866    // SAFETY: the page belongs to a world reserved for this test, is mapped by
1867    // the HHDM, and the bounds check above keeps the read inside the page.
1868    unsafe {
1869        for (index, byte) in out.iter_mut().enumerate() {
1870            *byte = core::ptr::read_volatile(page.add(index));
1871        }
1872    }
1873    Ok(())
1874}
1875
1876/// Writes `bytes` at the start of the guest page at `gpa` in a world.
1877fn write_world_bytes(world_id: u64, gpa: u64, bytes: &[u8]) -> Result<(), SelftestError> {
1878    let page_size = crate::s9vm::mmu::PAGE_SIZE as usize;
1879    if bytes.len() > page_size {
1880        return Err(SelftestError::BadExit("payload crosses a page boundary"));
1881    }
1882    let page = world_page(world_id, gpa)?;
1883    // SAFETY: the page belongs to a world reserved for this test, is mapped by
1884    // the HHDM, and the length check above keeps the write inside the page.
1885    unsafe {
1886        for (index, byte) in bytes.iter().enumerate() {
1887            core::ptr::write_volatile(page.add(index), *byte);
1888        }
1889    }
1890    Ok(())
1891}
1892
1893/// Image-loader test.
1894///
1895/// Builds a small ELF64 image in kernel memory and loads it into a fresh world
1896/// with [`vm::load_image`]: guest pages mapped through `map_memory`, file-backed
1897/// bytes copied page by page (GPA -> HPA -> HHDM), zero-filled tail. The image
1898/// is then entered exactly like the other phases: the guest writes its marker
1899/// on the debug port and halts. The guest page tables are the canonical
1900/// identity layout; the run uses the world's own second-level tables
1901/// (`vm::second_level_pointer`), so the executed image and its EPT are exactly
1902/// the ones `map_memory`/`load_image` produced.
1903pub fn run_loader(caps: &HwCaps) -> Result<LoaderReport, SelftestError> {
1904    if !caps.can_run() {
1905        return Err(SelftestError::BadExit("platform cannot run"));
1906    }
1907    // The world is destroyed on every path, including failures.
1908    let record = vm::create(b"s9vm-loader", 0).ok_or(SelftestError::VmFail(1))?;
1909    let result = run_loader_in_world(caps, record.id);
1910    let _ = vm::destroy(record.id);
1911    result
1912}
1913
1914/// Loader phase without the guest entry.
1915///
1916/// Runs exactly the loader memory path of [`run_loader`] (world memory
1917/// mapping, guest page tables, [`vm::load_image`] with its copy and BSS
1918/// zero-fill, the post-load checks, then the world teardown) but stops before
1919/// the `Vcpu` is created. It therefore needs **no VT-x**: it is the diagnostic
1920/// of choice to check the frame/world bookkeeping of the loader on any host,
1921/// and it names a regression in that path from the serial log alone.
1922pub fn run_loader_dry(caps: &HwCaps) -> Result<LoaderReport, SelftestError> {
1923    let record = vm::create(b"s9vm-loader-dry", 0).ok_or(SelftestError::VmFail(1))?;
1924    let result = loader_dry_in_world(caps, record.id);
1925    let _ = vm::destroy(record.id);
1926    result
1927}
1928
1929/// Body of the dry loader phase; the caller owns and destroys the world.
1930fn loader_dry_in_world(caps: &HwCaps, world_id: u64) -> Result<LoaderReport, SelftestError> {
1931    let loaded = prepare_loader_world(caps, world_id)?;
1932    Ok(LoaderReport {
1933        total_exits: 0,
1934        io_exits: 0,
1935        halt_exits: 0,
1936        marker: None,
1937        entry: loaded.entry,
1938        image_base: loaded.image_base,
1939        pages: loaded.span_pages(),
1940    })
1941}
1942
1943/// Maps the loader test's world memory, installs the guest page tables and
1944/// loads the ELF image, checking the copy and the BSS zero-fill.
1945///
1946/// Shared by the full loader phase and the VT-x-free dry run.
1947fn prepare_loader_world(caps: &HwCaps, world_id: u64) -> Result<vm::LoadedImage, SelftestError> {
1948    let page_size = crate::s9vm::mmu::PAGE_SIZE;
1949
1950    // 1. Guest memory backing the page tables and the stack. The image pages
1951    //    are mapped by the loader itself, which also allocates them.
1952    for gpa in [
1953        LOADER_GPA_PML4,
1954        LOADER_GPA_PDPT,
1955        LOADER_GPA_PD,
1956        LOADER_GPA_PT,
1957        LOADER_GPA_STACK,
1958    ] {
1959        vm::map_memory(world_id, caps, gpa, page_size, LOADER_GUEST_PERMS, 0)
1960            .map_err(|_| SelftestError::VmFail(2))?;
1961    }
1962
1963    // 2. Identity guest paging over the pages the guest touches. A single page
1964    //    table maps the first 2 MiB, which covers every GPA of the phase.
1965    write_world_u64(world_id, LOADER_GPA_PML4, 0, LOADER_GPA_PDPT | 0x3)?;
1966    write_world_u64(world_id, LOADER_GPA_PDPT, 0, LOADER_GPA_PD | 0x3)?;
1967    write_world_u64(world_id, LOADER_GPA_PD, 0, LOADER_GPA_PT | 0x3)?;
1968    for gpa in [
1969        LOADER_GPA_PML4,
1970        LOADER_GPA_PDPT,
1971        LOADER_GPA_PD,
1972        LOADER_GPA_PT,
1973        LOADER_IMAGE_BASE,
1974        LOADER_GPA_STACK,
1975    ] {
1976        let index = (gpa / page_size) as usize;
1977        write_world_u64(world_id, LOADER_GPA_PT, index * 8, gpa | 0x3)?;
1978    }
1979
1980    // 3. Loads the image through the kernel loader.
1981    let image = loader_image();
1982    let loaded = vm::load_image(world_id, caps, &image, LOADER_IMAGE_BASE)
1983        .map_err(|_| SelftestError::VmFail(3))?;
1984    let expected_entry = LOADER_IMAGE_BASE + LOADER_CODE_OFFSET;
1985    if loaded.entry != expected_entry
1986        || loaded.image_base != LOADER_IMAGE_BASE
1987        || loaded.span_min != LOADER_IMAGE_BASE
1988        || loaded.span_max != LOADER_IMAGE_BASE + page_size
1989    {
1990        return Err(SelftestError::BadExit("loader returned an unexpected plan"));
1991    }
1992    // The copy and the zero-fill are observable through the world translation:
1993    // first opcode of the guest code, then one byte of the BSS tail.
1994    if read_world_byte(world_id, loaded.entry)? != LOADER_CODE[0] {
1995        return Err(SelftestError::BadExit("image data was not copied"));
1996    }
1997    if read_world_byte(world_id, LOADER_IMAGE_BASE + 0x800)? != 0 {
1998        return Err(SelftestError::BadExit("image BSS was not zeroed"));
1999    }
2000    Ok(loaded)
2001}
2002
2003/// Body of the loader phase; the caller owns and destroys the world.
2004fn run_loader_in_world(caps: &HwCaps, world_id: u64) -> Result<LoaderReport, SelftestError> {
2005    let loaded = prepare_loader_world(caps, world_id)?;
2006
2007    // Uses the world's own second-level translation tables: the run must
2008    // exercise the EPT built by `map_memory` and the loader, not a copy.
2009    let pointer = vm::second_level_pointer(world_id, caps).map_err(|_| SelftestError::VmFail(4))?;
2010
2011    // The vCPU allocation is the first typed frame allocation of this phase
2012    // (the buddy allocator itself only seeds segment bitmaps during boot):
2013    // report the frame-metadata state right before it, so a "not initialized"
2014    // panic is attributable to the boot plan or to a post-boot clobber.
2015    let (meta_base, meta_frames, meta_init, plan_ram, plan_bytes) =
2016        crate::memory::frame::metadata_snapshot();
2017    log::info!(
2018        "[s9vm] loadertest: creating the vCPU (metadata base={meta_base:#x} \
2019         frames={meta_frames} init={meta_init:#x} plan_ram={plan_ram:#x} \
2020         plan_bytes={plan_bytes})"
2021    );
2022
2023    // Enters the loaded image: RIP is the relocated entry point returned by
2024    // the loader, RSP points into the guest stack page.
2025    let guest = GuestState::long_mode_64(loaded.entry, LOADER_STACK_TOP, LOADER_GPA_PML4);
2026    let mut vcpu = Vcpu::new(caps, pointer)?;
2027    // SAFETY: VT-x is active on this CPU (checked by the caller), interrupts
2028    // are disabled and the control block was just created for this vCPU.
2029    unsafe {
2030        vcpu.load()?;
2031        vcpu.configure_host()?;
2032        vcpu.configure(caps, &guest)?;
2033    }
2034
2035    let mut report = LoaderReport {
2036        total_exits: 0,
2037        io_exits: 0,
2038        halt_exits: 0,
2039        marker: None,
2040        entry: loaded.entry,
2041        image_base: loaded.image_base,
2042        pages: loaded.span_pages(),
2043    };
2044    let mut outcome: Result<(), SelftestError> = Ok(());
2045    for _ in 0..32 {
2046        // SAFETY: `run` contract (block loaded, IRQs disabled).
2047        let exit = match unsafe { vcpu.run() } {
2048            Ok(exit) => exit,
2049            Err(error) => {
2050                outcome = Err(SelftestError::from(error));
2051                break;
2052            }
2053        };
2054        report.total_exits += 1;
2055        match ExitReason::decode(exit.raw_reason).class() {
2056            ExitClass::IoPort => {
2057                report.io_exits += 1;
2058                let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
2059                if port == TEST_PORT {
2060                    report.marker = Some((vcpu.guest().rax & 0xFF) as u8);
2061                }
2062                // SAFETY: the control block is loaded and the guest is
2063                // inactive (we are in the exit handler).
2064                unsafe {
2065                    vcpu.advance_rip(u64::from(exit.instruction_length))?;
2066                }
2067            }
2068            ExitClass::Halt => {
2069                report.halt_exits += 1;
2070                break;
2071            }
2072            ExitClass::ExternalInterrupt | ExitClass::InterruptWindow => {}
2073            ExitClass::PreemptionTimer => {}
2074            other => {
2075                // Report enough context to tell a bad guest payload from a
2076                // bad page table: how far the guest got (marker, I/O count) and
2077                // where it faulted.
2078                log::warn!(
2079                    "[s9vm] loader test: unexpected exit class={:?} reason={:#x} \
2080                     qual={:#x} rip={:#x} marker={:?} io={} total={}",
2081                    other,
2082                    exit.raw_reason,
2083                    exit.qualification,
2084                    vcpu.guest().rip,
2085                    report.marker,
2086                    report.io_exits,
2087                    report.total_exits
2088                );
2089                outcome = Err(SelftestError::BadExit("unexpected loader-test exit"));
2090                break;
2091            }
2092        }
2093    }
2094
2095    // SAFETY: the vCPU is no longer active.
2096    unsafe {
2097        let _ = vcpu.clear();
2098    }
2099
2100    match outcome {
2101        Ok(()) if report.halt_exits >= 1 && report.marker == Some(LOADER_MARKER) => Ok(report),
2102        Ok(()) => Err(SelftestError::BadExit(
2103            "loaded image did not report its marker",
2104        )),
2105        Err(error) => Err(error),
2106    }
2107}
2108
2109/// Report of the boot-protocol loader dry run.
2110pub struct BootProtocolReport {
2111    /// Guest-physical address the protected-mode image was copied to.
2112    pub kernel_base: u64,
2113    /// Length of the copied protected-mode part.
2114    pub kernel_bytes: u64,
2115    /// `init_size` window the kernel needs.
2116    pub init_size: u64,
2117    /// Guest-physical address of the 64-bit entry point.
2118    pub entry: u64,
2119    /// Guest-physical address of the boot parameter page.
2120    pub boot_params_gpa: u64,
2121    /// Guest-physical address of the command line.
2122    pub cmdline_gpa: u64,
2123    /// Guest-physical address of the entry-contract GDT.
2124    pub gdt_gpa: u64,
2125    /// Number of 4 KiB tables the guest page tables use.
2126    pub table_pages: u64,
2127    /// Number of identity ranges handed to the guest.
2128    pub identity_ranges: usize,
2129}
2130
2131/// Builds a minimal boot-protocol image in kernel memory.
2132///
2133/// Layout: one boot sector, four setup sectors (`setup_sects = 4`), then a
2134/// 64 KiB protected-mode body. The setup header carries the fields a loader
2135/// reads: `HdrS`, the boot flag, protocol 2.15, `LOADED_HIGH`, the 64-bit entry
2136/// (`XLF_KERNEL_64`), a relocatable image with a 2 MiB alignment and an 8 MiB
2137/// `init_size`. The body starts with the bytes the 64-bit entry point would
2138/// execute; the dry run checks they landed at `entry = base + 0x200`.
2139fn boot_protocol_image() -> Vec<u8> {
2140    const SETUP_SECTORS: u8 = 4;
2141    const PROTECTED_MODE_LEN: usize = 64 * 1024;
2142    const HEADER_VERSION: u16 = 0x020F;
2143    const INIT_SIZE: u32 = 8 * 1024 * 1024;
2144    const KERNEL_ALIGNMENT: u32 = 2 * 1024 * 1024;
2145
2146    let setup_bytes = (usize::from(SETUP_SECTORS) + 1) * bzimage::SECTOR_SIZE;
2147    let mut image = vec![0u8; setup_bytes + PROTECTED_MODE_LEN];
2148    // Setup header (boot protocol offsets).
2149    image[0x1F1] = SETUP_SECTORS;
2150    put_u16(&mut image, 0x1FE, bzimage::BOOT_FLAG);
2151    put_u32(&mut image, 0x202, bzimage::HEADER_MAGIC);
2152    put_u16(&mut image, 0x206, HEADER_VERSION);
2153    image[0x210] = 0xFF; // type_of_loader: undefined
2154    image[0x211] = bzimage::LOADED_HIGH | 0x80; // LOADED_HIGH | CAN_USE_HEAP
2155    put_u32(&mut image, 0x214, bzimage::DEFAULT_CODE32_START as u32);
2156    put_u32(&mut image, 0x22C, zeropage::DEFAULT_INITRD_ADDR_MAX); // initrd_addr_max
2157    put_u32(&mut image, 0x230, KERNEL_ALIGNMENT);
2158    image[0x234] = 1; // relocatable
2159    image[0x235] = 12; // min_alignment: 4 KiB
2160    put_u16(&mut image, 0x236, bzimage::XLF_KERNEL_64);
2161    put_u32(&mut image, 0x238, zeropage::DEFAULT_CMDLINE_SIZE);
2162    put_u32(&mut image, 0x23C, bzimage::SUBARCH_PC);
2163    put_u64(&mut image, 0x258, bzimage::DEFAULT_CODE32_START);
2164    put_u32(&mut image, 0x260, INIT_SIZE);
2165    // Protected-mode body: a deterministic pattern with the entry bytes at
2166    // offset 0x200 (the 64-bit entry is the loaded base plus 0x200).
2167    for (index, byte) in image[setup_bytes..].iter_mut().enumerate() {
2168        *byte = (index & 0xFF) as u8;
2169    }
2170    image[setup_bytes + bzimage::ENTRY_OFFSET_64 as usize] = 0xFA; // cli
2171    image[setup_bytes + bzimage::ENTRY_OFFSET_64 as usize + 1] = 0xF4; // hlt
2172    image
2173}
2174
2175/// Page-table provider writing the guest tables straight into world memory.
2176///
2177/// The tables are allocated from the low-memory reservation computed by the
2178/// layout planner and reached through the world's second-level translation
2179/// (the same path the loader uses for the image), so the dry run exercises the
2180/// exact memory path a real boot would.
2181struct WorldTables {
2182    world_id: u64,
2183    next: u64,
2184    end: u64,
2185    frames: Vec<u64>,
2186}
2187
2188impl WorldTables {
2189    fn new(world_id: u64, start: u64, pages: u64) -> Self {
2190        Self {
2191            world_id,
2192            next: start,
2193            end: start + pages * crate::s9vm::mmu::PAGE_SIZE,
2194            frames: Vec::new(),
2195        }
2196    }
2197
2198    fn page(&self, table: u64) -> Option<*mut u8> {
2199        world_page(self.world_id, table).ok()
2200    }
2201}
2202
2203impl crate::s9vm::mmu::TableMemory for WorldTables {
2204    fn alloc_table(&mut self) -> Option<u64> {
2205        let page_size = crate::s9vm::mmu::PAGE_SIZE;
2206        if self.next + page_size > self.end {
2207            return None;
2208        }
2209        let table = self.next;
2210        self.next += page_size;
2211        self.frames.push(table);
2212        let page = self.page(table)?;
2213        // SAFETY: the page belongs to the world, is mapped by the HHDM and is
2214        // a full 4 KiB frame; zeroing it is the provider contract.
2215        unsafe {
2216            core::ptr::write_bytes(page, 0, page_size as usize);
2217        }
2218        Some(table)
2219    }
2220
2221    fn free_table(&mut self, _table: u64) {
2222        // The world owns the frames: destroying the world releases them and
2223        // the second-level mapping at once.
2224    }
2225
2226    fn read_entry(&self, table: u64, index: usize) -> u64 {
2227        match self.page(table) {
2228            Some(page) => {
2229                // SAFETY: the index is bounded by the table format (512
2230                // entries) and the page is a full frame.
2231                unsafe { core::ptr::read_volatile(page.add(index * 8) as *const u64) }
2232            }
2233            None => 0,
2234        }
2235    }
2236
2237    fn write_entry(&mut self, table: u64, index: usize, value: u64) {
2238        if let Some(page) = self.page(table) {
2239            // SAFETY: same invariant as `read_entry`.
2240            unsafe {
2241                core::ptr::write_volatile(page.add(index * 8) as *mut u64, value);
2242            }
2243        }
2244    }
2245}
2246
2247/// Writes `bytes` at `gpa` across page boundaries in a world.
2248fn write_world_range(world_id: u64, gpa: u64, bytes: &[u8]) -> Result<(), SelftestError> {
2249    let page_size = crate::s9vm::mmu::PAGE_SIZE as usize;
2250    let mut offset = 0;
2251    while offset < bytes.len() {
2252        let current = gpa + offset as u64;
2253        let in_page = (current as usize) & (page_size - 1);
2254        let chunk = (page_size - in_page).min(bytes.len() - offset);
2255        let page = world_page(world_id, current & !(page_size as u64 - 1))?;
2256        // SAFETY: the page belongs to the world, is mapped by the HHDM, and
2257        // `chunk` keeps the write inside the page.
2258        unsafe {
2259            for index in 0..chunk {
2260                core::ptr::write_volatile(page.add(in_page + index), bytes[offset + index]);
2261            }
2262        }
2263        offset += chunk;
2264    }
2265    Ok(())
2266}
2267
2268/// Reads `out.len()` bytes at `gpa` across page boundaries in a world.
2269fn read_world_range(world_id: u64, gpa: u64, out: &mut [u8]) -> Result<(), SelftestError> {
2270    let page_size = crate::s9vm::mmu::PAGE_SIZE as usize;
2271    let mut offset = 0;
2272    while offset < out.len() {
2273        let current = gpa + offset as u64;
2274        let in_page = (current as usize) & (page_size - 1);
2275        let chunk = (page_size - in_page).min(out.len() - offset);
2276        let page = world_page(world_id, current & !(page_size as u64 - 1))?;
2277        // SAFETY: same invariant as `write_world_range`.
2278        unsafe {
2279            for index in 0..chunk {
2280                out[offset + index] = core::ptr::read_volatile(page.add(in_page + index));
2281            }
2282        }
2283        offset += chunk;
2284    }
2285    Ok(())
2286}
2287
2288/// Boot-protocol loader dry run: no VT-x, no guest entry.
2289///
2290/// Runs the whole 64-bit boot preparation : parse the image, plan the memory
2291/// layout, map the guest memory, copy the protected-mode part, build the boot
2292/// parameter page with its e820 map, install the command line and the entry
2293/// GDT, build the guest page tables through the world translation : then
2294/// verifies the result from the world memory and tears the world down.
2295///
2296/// It is the deterministic regression of the boot path on any host, and the
2297/// last checkpoint before the same sequence is entered on VT-x hardware.
2298pub fn run_boot_protocol_dry(caps: &HwCaps) -> Result<BootProtocolReport, SelftestError> {
2299    let record = vm::create(b"s9vm-boot-dry", 0).ok_or(SelftestError::VmFail(1))?;
2300    let result = boot_protocol_dry_in_world(caps, record.id);
2301    let _ = vm::destroy(record.id);
2302    result
2303}
2304
2305/// Body of the boot-protocol dry run; the caller owns and destroys the world.
2306fn boot_protocol_dry_in_world(
2307    caps: &HwCaps,
2308    world_id: u64,
2309) -> Result<BootProtocolReport, SelftestError> {
2310    const RAM_BYTES: u64 = 64 * 1024 * 1024;
2311    const CMDLINE: &[u8] = b"console=ttyS0\0";
2312
2313    // 1. Read and validate the image, then plan the layout from its header.
2314    let image = boot_protocol_image();
2315    let parsed = match bzimage::BzImage::parse(&image) {
2316        Ok(parsed) => parsed,
2317        Err(error) => {
2318            log::warn!("[s9vm] bootdry: image parse error {error:?}");
2319            return Err(SelftestError::BadExit("image rejected"));
2320        }
2321    };
2322    let request = linuxboot::LayoutRequest {
2323        ram_bytes: RAM_BYTES,
2324        pref_address: parsed.pref_address(),
2325        kernel_alignment: parsed.kernel_alignment(),
2326        init_size: u64::from(parsed.init_size()),
2327        relocatable: parsed.relocatable(),
2328        initrd_bytes: 0,
2329        cmdline_len: CMDLINE.len() as u64,
2330    };
2331    let layout = match linuxboot::plan(&request) {
2332        Ok(layout) => layout,
2333        Err(error) => {
2334            log::warn!("[s9vm] bootdry: layout error {error:?}");
2335            return Err(SelftestError::BadExit("boot layout rejected"));
2336        }
2337    };
2338    let plan = match parsed.load_plan(layout.kernel_base) {
2339        Ok(plan) => plan,
2340        Err(error) => {
2341            log::warn!("[s9vm] bootdry: image plan error {error:?}");
2342            return Err(SelftestError::BadExit("image plan rejected"));
2343        }
2344    };
2345    if plan.runtime_start != layout.kernel_base
2346        || plan.entry_gpa() != layout.entry_gpa()
2347        || plan.init_size != parsed.init_size()
2348    {
2349        return Err(SelftestError::BadExit("layout and image plan disagree"));
2350    }
2351
2352    // 2. Guest memory: the low range holding every boot object, and the
2353    //    kernel window the entry contract requires to be identity mapped.
2354    let page_size = crate::s9vm::mmu::PAGE_SIZE;
2355    let window = (u64::from(parsed.init_size()) + page_size - 1) & !(page_size - 1);
2356    vm::map_memory(
2357        world_id,
2358        caps,
2359        0,
2360        linuxboot::LOW_IDENTITY_END,
2361        LOADER_GUEST_PERMS,
2362        0,
2363    )
2364    .map_err(|_| SelftestError::VmFail(2))?;
2365    vm::map_memory(
2366        world_id,
2367        caps,
2368        layout.kernel_base,
2369        window,
2370        LOADER_GUEST_PERMS,
2371        0,
2372    )
2373    .map_err(|_| SelftestError::VmFail(3))?;
2374
2375    // 3. Entry-contract GDT and command line.
2376    write_world_range(
2377        world_id,
2378        layout.gdt_gpa,
2379        &crate::s9vm::guest::boot_gdt_bytes(),
2380    )?;
2381    write_world_range(world_id, layout.cmdline_gpa, CMDLINE)?;
2382
2383    // 4. Boot parameter page: e820 map, header copy, pointers.
2384    let header =
2385        zeropage::KernelHeader::parse(&image).map_err(|_| SelftestError::BadExit("bad header"))?;
2386    let mut boot_params = zeropage::ZeroPage::boot_params_for(layout.cmdline_gpa, RAM_BYTES)
2387        .map_err(|_| SelftestError::BadExit("boot params rejected"))?;
2388    boot_params = boot_params.with_kernel_header(header).with_loader_id(0xFF);
2389    boot_params
2390        .set_cmdline(layout.cmdline_gpa, CMDLINE.len() as u32)
2391        .map_err(|_| SelftestError::BadExit("command line rejected"))?;
2392    let mut boot_params_bytes = vec![0u8; zeropage::BOOT_PARAMS_SIZE];
2393    boot_params
2394        .write(&mut boot_params_bytes)
2395        .map_err(|_| SelftestError::BadExit("boot params write rejected"))?;
2396    write_world_range(world_id, layout.boot_params_gpa, &boot_params_bytes)?;
2397
2398    // 5. Copy the protected-mode kernel to its load address.
2399    write_world_range(world_id, layout.kernel_base, parsed.protected_mode())?;
2400
2401    // 6. Guest page tables, built through the world translation.
2402    let mut tables = WorldTables::new(world_id, layout.page_tables_gpa, layout.page_table_pages);
2403    let page_tables = GuestPageTables::build(&mut tables, &layout.identity)
2404        .map_err(|_| SelftestError::BadExit("guest page tables rejected"))?;
2405
2406    // 7. Verify the plan from guest memory: the entry bytes, the boot
2407    //    parameters, the command line and the mapping of every boot object.
2408    let mut entry_bytes = [0u8; 2];
2409    read_world_range(world_id, layout.entry_gpa(), &mut entry_bytes)?;
2410    let body = parsed.protected_mode();
2411    let entry_index = bzimage::ENTRY_OFFSET_64 as usize;
2412    if entry_bytes != [body[entry_index], body[entry_index + 1]] {
2413        log::warn!(
2414            "[s9vm] bootdry: entry bytes {entry_bytes:x?} expected {:x?} \
2415             (entry={:#x} body_len={} setup={} base={:#x})",
2416            [body[entry_index], body[entry_index + 1]],
2417            layout.entry_gpa(),
2418            body.len(),
2419            parsed.setup_bytes(),
2420            layout.kernel_base
2421        );
2422        return Err(SelftestError::BadExit("entry bytes were not copied"));
2423    }
2424    let mut magic = [0u8; 4];
2425    read_world_range(world_id, layout.boot_params_gpa + 0x202, &mut magic)?;
2426    if magic != bzimage::HEADER_MAGIC.to_le_bytes() {
2427        return Err(SelftestError::BadExit("boot params header was not written"));
2428    }
2429    let mut cmdline = [0u8; 4];
2430    read_world_range(world_id, layout.cmdline_gpa, &mut cmdline)?;
2431    if &cmdline != b"cons" {
2432        return Err(SelftestError::BadExit("command line was not written"));
2433    }
2434    for address in [
2435        layout.boot_params_gpa,
2436        layout.cmdline_gpa,
2437        layout.gdt_gpa,
2438        layout.page_tables_gpa,
2439        layout.entry_gpa(),
2440        layout.kernel_base,
2441    ] {
2442        let (physical, leaf) = page_tables
2443            .translate(&tables, address)
2444            .ok_or(SelftestError::BadExit("boot object is not identity mapped"))?;
2445        if physical != address || leaf & 1 == 0 {
2446            return Err(SelftestError::BadExit("guest mapping is wrong"));
2447        }
2448    }
2449
2450    Ok(BootProtocolReport {
2451        kernel_base: layout.kernel_base,
2452        kernel_bytes: plan.kernel_bytes,
2453        init_size: u64::from(plan.init_size),
2454        entry: layout.entry_gpa(),
2455        boot_params_gpa: layout.boot_params_gpa,
2456        cmdline_gpa: layout.cmdline_gpa,
2457        gdt_gpa: layout.gdt_gpa,
2458        table_pages: page_tables.table_count() as u64,
2459        identity_ranges: layout.identity.len(),
2460    })
2461}
2462
2463/// Report of the ACPI-discovery phase.
2464pub struct AcpiReport {
2465    pub total_exits: u32,
2466    pub io_exits: u32,
2467    pub halt_exits: u32,
2468    /// First byte written by the guest on the debug port (`b'A'` on success).
2469    pub marker: Option<u8>,
2470    /// Local APIC entries counted by the guest in the MADT.
2471    pub madt_apics: u8,
2472    /// Local APIC entries the kernel expects (one per registered vCPU).
2473    pub expected_apics: u8,
2474    /// Guest-physical address of the RSDP the guest validated.
2475    pub rsdp: u64,
2476}
2477
2478/// ACPI-discovery test.
2479///
2480/// Creates a fresh world with one registered vCPU (the MADT describes it),
2481/// maps a flat identity window covering the page tables, the payload, the
2482/// stack and the legacy BIOS scan window, asks the engine to write the
2483/// firmware tables with [`vm::write_acpi`], then runs the guest payload
2484/// [`ACPI_CODE`] with the world's own second-level tables.
2485///
2486/// The world (and its vCPU task) is destroyed on every path.
2487pub fn run_acpi(caps: &HwCaps) -> Result<AcpiReport, SelftestError> {
2488    if !caps.can_run() {
2489        return Err(SelftestError::BadExit("platform cannot run"));
2490    }
2491    // The world is destroyed on every path, including failures.
2492    let record = vm::create(b"s9vm-acpi", 0).ok_or(SelftestError::VmFail(1))?;
2493    let result = run_acpi_in_world(caps, record.id);
2494    let _ = vm::destroy(record.id);
2495    result
2496}
2497
2498/// Body of the ACPI phase; the caller owns and destroys the world.
2499fn run_acpi_in_world(caps: &HwCaps, world_id: u64) -> Result<AcpiReport, SelftestError> {
2500    let page_size = crate::s9vm::mmu::PAGE_SIZE;
2501
2502    // 1. A registered vCPU is required: `write_acpi` builds the MADT from the
2503    //    world's vCPU APIC identifiers. This phase therefore runs from a
2504    //    kernel thread (see `s9vm_acpi_selftest`), never from the early
2505    //    bootstrap where the scheduler is not available yet.
2506    log::info!("[s9vm] acpitest: registering the world vCPU");
2507    let _vcpu_id = vm::create_vcpu_detached(world_id, 0).map_err(|_| SelftestError::VmFail(2))?;
2508    log::info!("[s9vm] acpitest: mapping guest pages");
2509    let expected_apics = vm::get(world_id)
2510        .map(|record| record.vcpu_count as u8)
2511        .unwrap_or(0);
2512    if expected_apics == 0 {
2513        return Err(SelftestError::BadExit("ACPI phase has no vCPU"));
2514    }
2515
2516    // 2. Guest memory: page tables, payload, stack, then the whole scan
2517    //    window. The scan window is read-only for the guest; the copy done by
2518    //    `write_acpi` goes through the HHDM and does not need EPT write
2519    //    permission.
2520    for gpa in [
2521        ACPI_GPA_PML4,
2522        ACPI_GPA_PDPT,
2523        ACPI_GPA_PD,
2524        ACPI_GPA_PT,
2525        ACPI_GPA_CODE,
2526        ACPI_GPA_STACK,
2527    ] {
2528        vm::map_memory(world_id, caps, gpa, page_size, ACPI_GUEST_PERMS, 0)
2529            .map_err(|_| SelftestError::VmFail(3))?;
2530    }
2531    vm::map_memory(
2532        world_id,
2533        caps,
2534        ACPI_SCAN_START,
2535        ACPI_SCAN_PAGES * page_size,
2536        ACPI_SCAN_PERMS,
2537        0,
2538    )
2539    .map_err(|_| SelftestError::VmFail(4))?;
2540
2541    // 3. Identity guest paging: one page table maps the first 2 MiB, which
2542    //    covers the tables, the payload, the stack and the scan window.
2543    write_world_u64(world_id, ACPI_GPA_PML4, 0, ACPI_GPA_PDPT | 0x3)?;
2544    write_world_u64(world_id, ACPI_GPA_PDPT, 0, ACPI_GPA_PD | 0x3)?;
2545    write_world_u64(world_id, ACPI_GPA_PD, 0, ACPI_GPA_PT | 0x3)?;
2546    for gpa in [
2547        ACPI_GPA_PML4,
2548        ACPI_GPA_PDPT,
2549        ACPI_GPA_PD,
2550        ACPI_GPA_PT,
2551        ACPI_GPA_CODE,
2552        ACPI_GPA_STACK,
2553    ] {
2554        let index = (gpa / page_size) as usize;
2555        write_world_u64(world_id, ACPI_GPA_PT, index * 8, gpa | 0x3)?;
2556    }
2557    for page in 0..ACPI_SCAN_PAGES {
2558        let gpa = ACPI_SCAN_START + page * page_size;
2559        let index = (gpa / page_size) as usize;
2560        write_world_u64(world_id, ACPI_GPA_PT, index * 8, gpa | 0x3)?;
2561    }
2562
2563    // 4. Payload and firmware tables.
2564    write_world_bytes(world_id, ACPI_GPA_CODE, ACPI_CODE)?;
2565    log::info!("[s9vm] acpitest: writing the firmware tables");
2566    vm::write_acpi(world_id, caps, vm::ACPI_GPA).map_err(|_| SelftestError::VmFail(5))?;
2567    // The copy is observable through the world translation: first byte of the
2568    // RSDP signature.
2569    if read_world_byte(world_id, vm::ACPI_GPA)? != b'R' {
2570        return Err(SelftestError::BadExit("ACPI image was not copied"));
2571    }
2572
2573    // 5. Uses the world's own second-level translation tables.
2574    let pointer = vm::second_level_pointer(world_id, caps).map_err(|_| SelftestError::VmFail(6))?;
2575
2576    // 6. Enters the payload; the stack lives in its own identity-mapped page.
2577    let guest = GuestState::long_mode_64(ACPI_GPA_CODE, ACPI_STACK_TOP, ACPI_GPA_PML4);
2578    let mut vcpu = Vcpu::new(caps, pointer)?;
2579    // SAFETY: VT-x is active on this CPU (checked by the caller), the control
2580    // block was just created for this vCPU and no other CPU runs it.
2581    unsafe {
2582        vcpu.load()?;
2583        vcpu.configure_host()?;
2584        vcpu.configure(caps, &guest)?;
2585    }
2586
2587    let mut report = AcpiReport {
2588        total_exits: 0,
2589        io_exits: 0,
2590        halt_exits: 0,
2591        marker: None,
2592        madt_apics: 0,
2593        expected_apics,
2594        rsdp: vm::ACPI_GPA,
2595    };
2596    // The guest is entered from a kernel thread here; mask host interrupts for
2597    // the duration of the direct run loop, as the bootstrap phases do.
2598    log::info!("[s9vm] acpitest: entering the guest");
2599    let saved_flags = crate::arch::save_flags_and_cli();
2600    let mut debug_out = [0u8; 4];
2601    let mut debug_len = 0usize;
2602    let mut outcome: Result<(), SelftestError> = Ok(());
2603    for _ in 0..ACPI_MAX_EXITS {
2604        // SAFETY: `run` contract (control block loaded, IRQs disabled).
2605        let exit = match unsafe { vcpu.run() } {
2606            Ok(exit) => exit,
2607            Err(error) => {
2608                outcome = Err(SelftestError::from(error));
2609                break;
2610            }
2611        };
2612        report.total_exits += 1;
2613        match ExitReason::decode(exit.raw_reason).class() {
2614            ExitClass::IoPort => {
2615                report.io_exits += 1;
2616                let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
2617                if port == TEST_PORT && debug_len < debug_out.len() {
2618                    debug_out[debug_len] = (vcpu.guest().rax & 0xFF) as u8;
2619                    debug_len += 1;
2620                }
2621                // SAFETY: the control block is loaded and the guest is
2622                // inactive (we are in the exit handler).
2623                if let Err(error) = unsafe { vcpu.advance_rip(u64::from(exit.instruction_length)) }
2624                {
2625                    outcome = Err(SelftestError::from(error));
2626                    break;
2627                }
2628            }
2629            ExitClass::Halt => {
2630                report.halt_exits += 1;
2631                break;
2632            }
2633            ExitClass::ExternalInterrupt | ExitClass::InterruptWindow => {}
2634            ExitClass::PreemptionTimer => {}
2635            other => {
2636                log::warn!(
2637                    "[s9vm] acpi test: unexpected exit class={:?} reason={:#x} \
2638                     qual={:#x} rip={:#x} marker={:?} io={} total={}",
2639                    other,
2640                    exit.raw_reason,
2641                    exit.qualification,
2642                    vcpu.guest().rip,
2643                    report.marker,
2644                    report.io_exits,
2645                    report.total_exits
2646                );
2647                outcome = Err(SelftestError::BadExit("unexpected ACPI-test exit"));
2648                break;
2649            }
2650        }
2651    }
2652    crate::arch::restore_flags(saved_flags);
2653
2654    // SAFETY: the vCPU is no longer active.
2655    unsafe {
2656        let _ = vcpu.clear();
2657    }
2658
2659    report.marker = if debug_len > 0 {
2660        Some(debug_out[0])
2661    } else {
2662        None
2663    };
2664    report.madt_apics = if debug_len > 1 { debug_out[1] } else { 0 };
2665
2666    if let Err(error) = outcome {
2667        return Err(error);
2668    }
2669    if report.halt_exits == 0 {
2670        log::warn!(
2671            "[s9vm] acpi test: guest never halted (marker={:?} io={} total={})",
2672            report.marker,
2673            report.io_exits,
2674            report.total_exits
2675        );
2676        return Err(SelftestError::BadExit("ACPI guest did not halt"));
2677    }
2678    if report.marker != Some(ACPI_MARKER) {
2679        log::warn!(
2680            "[s9vm] acpi test: guest rejected the tables (marker={:?} expected={} io={} total={})",
2681            report.marker,
2682            ACPI_MARKER,
2683            report.io_exits,
2684            report.total_exits
2685        );
2686        return Err(SelftestError::BadExit("ACPI guest rejected the tables"));
2687    }
2688    if report.madt_apics != expected_apics {
2689        log::warn!(
2690            "[s9vm] acpi test: MADT Local APIC count={} expected={} \
2691             marker={:?} io={} total={}",
2692            report.madt_apics,
2693            expected_apics,
2694            report.marker,
2695            report.io_exits,
2696            report.total_exits
2697        );
2698        return Err(SelftestError::BadExit("unexpected MADT Local APIC count"));
2699    }
2700    Ok(report)
2701}
2702
2703/// Kthread-stage hook: vCPU kernel-task smoke test.
2704///
2705/// Enabled by `s9vm.kthread_smoke=1`. It proves the scheduling path used by a
2706/// real guest: the world and its vCPU are created (`create_vcpu` spawns the
2707/// kernel task from this kernel thread), a bounded RUN is requested (under a
2708/// host without VT-x this completes with `HardwareNotReady`, which already
2709/// proves the task was scheduled and executed), and the world is destroyed with
2710/// a bounded wait. A silent task-drop in the scheduler shows up as RUN timeout
2711/// or destroy timeout, with an explicit FAIL log instead of a silent hang.
2712#[cfg(target_arch = "x86_64")]
2713#[component::init_component(kthread, priority = 49)]
2714fn s9vm_kthread_smoke() -> Result<(), component::ComponentInitError> {
2715    // Read the option here, not at the early `s9vm_init` stage: this path must
2716    // run on hosts without VT-x (QEMU TCG) where the engine activation is
2717    // skipped, and the boot environment is still available at the kthread
2718    // stage.
2719    let requested = crate::boot_args()
2720        .and_then(|args| args.env_get("s9vm.kthread_smoke"))
2721        .map(|value| value == "1" || value == "true")
2722        .unwrap_or(false);
2723    if !requested {
2724        return Ok(());
2725    }
2726    // The kthread stage still runs on the boot context, before the preemptive
2727    // scheduler starts: blocking here would deadlock the boot. Spawn a task
2728    // that runs once the scheduler is live; if this spawn is dropped, the
2729    // QEMU boot test never sees the PASS marker (which is the diagnostic).
2730    match crate::process::kthread::spawn("s9vm-kthread-smoke", run_kthread_smoke) {
2731        Ok(task) => log::info!(
2732            "[s9vm] kthread-smoke: runner task {} spawned (kthread stage)",
2733            task.as_u64()
2734        ),
2735        Err(error) => log::warn!("[s9vm] kthread-smoke FAIL: cannot spawn runner ({})", error),
2736    }
2737    Ok(())
2738}
2739
2740/// Body of the vCPU kernel-task smoke test.
2741fn run_kthread_smoke() {
2742    let Some(record) = vm::create(b"s9vm-kthread-smoke", 0) else {
2743        log::warn!("[s9vm] kthread-smoke FAIL: cannot create the world");
2744        return;
2745    };
2746    let world_id = record.id;
2747    let vcpu = match vm::create_vcpu(world_id, 0) {
2748        Ok(vcpu) => vcpu,
2749        Err(error) => {
2750            log::warn!(
2751                "[s9vm] kthread-smoke FAIL: create_vcpu failed ({:?})",
2752                error
2753            );
2754            let _ = vm::destroy_timeout(world_id, KTHREAD_SMOKE_DESTROY_NS);
2755            return;
2756        }
2757    };
2758    log::info!(
2759        "[s9vm] kthread-smoke: world={} vcpu={} created (active_cpus={})",
2760        world_id,
2761        vcpu,
2762        crate::s9vm::active_cpu_count()
2763    );
2764
2765    // Let the freshly spawned task reach its wait loop (and let a sibling CPU
2766    // pick it up if the scheduler placed it there).
2767    for _ in 0..4 {
2768        crate::process::sleep_current_task_ticks(1);
2769    }
2770    let alive = vm::vcpu_snapshots(world_id)
2771        .map(|vcpus| vcpus.iter().any(|snapshot| snapshot.id == vcpu))
2772        .unwrap_or(false);
2773    if !alive {
2774        log::warn!("[s9vm] kthread-smoke FAIL: vCPU disappeared after creation");
2775        let _ = vm::destroy_timeout(world_id, KTHREAD_SMOKE_DESTROY_NS);
2776        return;
2777    }
2778
2779    // A RUN proves the task actually executes: under a host without VT-x the
2780    // request completes with HardwareNotReady, which is the expected result
2781    // here (TCG has no VMX). With VT-x active the smoke world has no mapped
2782    // guest memory (the smoke test only exercises the scheduling path), so
2783    // the request completes with NoMemory once the task reached `run_vcpu`;
2784    // both outcomes prove the vCPU task was scheduled and executed. A timeout
2785    // means the task was never scheduled.
2786    let run = vm::request_run_timeout(vcpu, KTHREAD_SMOKE_RUN_NS);
2787    let run_ok = matches!(
2788        run,
2789        Ok(()) | Err(vm::RunError::HardwareNotReady) | Err(vm::RunError::NoMemory)
2790    );
2791    log::info!("[s9vm] kthread-smoke: bounded RUN completed ({:?})", run);
2792
2793    let started = crate::process::scheduler::ticks();
2794    let destroyed = vm::destroy_timeout(world_id, KTHREAD_SMOKE_DESTROY_NS);
2795    let elapsed = crate::process::scheduler::ticks().saturating_sub(started);
2796    let destroyed_ok = destroyed.is_some();
2797    if run_ok && destroyed_ok {
2798        log::info!(
2799            "[s9vm] kthread-smoke PASS: run={:?} destroy_ticks={} vcpu={}",
2800            run,
2801            elapsed,
2802            vcpu
2803        );
2804    } else {
2805        log::warn!(
2806            "[s9vm] kthread-smoke FAIL: run={:?} destroyed={} destroy_ticks={}",
2807            run,
2808            destroyed_ok,
2809            elapsed
2810        );
2811    }
2812}
2813
2814/// Kthread-stage hook: runs the ACPI phase synchronously.
2815///
2816/// The phase used to spawn its own kernel thread (to get a scheduler for a
2817/// registered vCPU). It now registers a **detached** vCPU (no kernel task) and
2818/// drives it with a direct `Vcpu` loop, so it needs neither the scheduler nor
2819/// a nested kernel thread: it runs synchronously in this hook and cannot leave
2820/// a task waiting forever behind it.
2821#[cfg(target_arch = "x86_64")]
2822#[component::init_component(kthread, priority = 50)]
2823fn s9vm_acpi_selftest() -> Result<(), component::ComponentInitError> {
2824    if !ACPI_SELFTEST_REQUESTED.swap(false, Ordering::AcqRel) {
2825        return Ok(());
2826    }
2827    run_acpi_task();
2828    Ok(())
2829}
2830
2831/// Body of the ACPI selftest (synchronous).
2832fn run_acpi_task() {
2833    let Some(caps) = crate::s9vm::detect_vmx() else {
2834        log::warn!("[s9vm] acpitest FAIL: platform capabilities unavailable");
2835        return;
2836    };
2837    log::info!(
2838        "[s9vm] acpitest: running (active_cpus={})",
2839        crate::s9vm::active_cpu_count()
2840    );
2841    match run_acpi(&caps) {
2842        Ok(report) => log::info!(
2843            "[s9vm] acpitest PASS: total={} io={} hlt={} marker={:?} rsdp={:#x} \
2844             madt_apics={} expected={}",
2845            report.total_exits,
2846            report.io_exits,
2847            report.halt_exits,
2848            report.marker,
2849            report.rsdp,
2850            report.madt_apics,
2851            report.expected_apics
2852        ),
2853        Err(error) => log::warn!("[s9vm] acpitest FAIL: {:?}", error),
2854    }
2855}
2856
2857/// Report of the guest-OS bootstrap phase.
2858pub struct GuestOsReport {
2859    pub total_exits: u32,
2860    pub io_exits: u32,
2861    pub halt_exits: u32,
2862    /// First byte written by the guest on the debug port (`b'O'` on success).
2863    pub marker: Option<u8>,
2864    /// Second byte: the validation count on success, the failure step otherwise.
2865    pub status: Option<u8>,
2866    /// `cmdline_len` the guest read from the boot-parameter block.
2867    pub guest_cmdline_len: Option<u8>,
2868    /// `memory_count` the guest read from the boot-parameter block.
2869    pub guest_memory_count: Option<u8>,
2870    /// `cmdline_len` decoded by the kernel from the same block.
2871    pub cmdline_len: u32,
2872    /// `memory_count` decoded by the kernel from the same block.
2873    pub memory_count: u32,
2874    /// Number of initrd/module entries decoded by the kernel.
2875    pub module_count: u32,
2876    /// ACPI RSDP guest-physical address advertised by the block.
2877    pub rsdp: u64,
2878}
2879
2880/// Guest-OS bootstrap test.
2881///
2882/// Creates a fresh world with one **detached** vCPU (no kernel task), maps the
2883/// guest page tables, payload, stack and boot-parameter page, stores a command
2884/// line and one module, writes the firmware tables and the boot-parameter
2885/// block, then runs the payload built by
2886/// [`crate::s9vm::guestprog::guestos::build_payload`] with the world's own
2887/// second-level tables.
2888///
2889/// The world is destroyed on every path.
2890pub fn run_guestos(caps: &HwCaps) -> Result<GuestOsReport, SelftestError> {
2891    if !caps.can_run() {
2892        return Err(SelftestError::BadExit("platform cannot run"));
2893    }
2894    let record = vm::create(b"s9vm-guestos", 0).ok_or(SelftestError::VmFail(1))?;
2895    let result = run_guestos_in_world(caps, record.id);
2896    let _ = vm::destroy(record.id);
2897    result
2898}
2899
2900/// Body of the guest-OS phase; the caller owns and destroys the world.
2901fn run_guestos_in_world(caps: &HwCaps, world_id: u64) -> Result<GuestOsReport, SelftestError> {
2902    let page_size = crate::s9vm::mmu::PAGE_SIZE;
2903
2904    // 1. A detached vCPU is enough: `write_acpi` builds the MADT from the
2905    //    registered vCPU identifiers, and the phase drives the vCPU itself.
2906    log::info!("[s9vm] guestostest: registering the world vCPU");
2907    let _vcpu_id = vm::create_vcpu_detached(world_id, 0).map_err(|_| SelftestError::VmFail(2))?;
2908
2909    // 2. Guest memory: page tables, payload, stack, boot-parameter page, and
2910    //    the read-only legacy scan window.
2911    log::info!("[s9vm] guestostest: mapping guest pages");
2912    for gpa in [
2913        GUESTOS_GPA_PML4,
2914        GUESTOS_GPA_PDPT,
2915        GUESTOS_GPA_PD,
2916        GUESTOS_GPA_PT,
2917        GUESTOS_GPA_CODE,
2918        GUESTOS_GPA_STACK,
2919        GUESTOS_GPA_BOOT_PARAMS,
2920    ] {
2921        vm::map_memory(world_id, caps, gpa, page_size, GUESTOS_GUEST_PERMS, 0)
2922            .map_err(|_| SelftestError::VmFail(3))?;
2923    }
2924    vm::map_memory(
2925        world_id,
2926        caps,
2927        GUESTOS_SCAN_START,
2928        GUESTOS_SCAN_PAGES * page_size,
2929        GUESTOS_SCAN_PERMS,
2930        0,
2931    )
2932    .map_err(|_| SelftestError::VmFail(4))?;
2933
2934    // 3. Identity guest paging: one page table maps the first 2 MiB, which
2935    //    covers the tables, the payload, the stack, the boot block and the
2936    //    scan window.
2937    write_world_u64(world_id, GUESTOS_GPA_PML4, 0, GUESTOS_GPA_PDPT | 0x3)?;
2938    write_world_u64(world_id, GUESTOS_GPA_PDPT, 0, GUESTOS_GPA_PD | 0x3)?;
2939    write_world_u64(world_id, GUESTOS_GPA_PD, 0, GUESTOS_GPA_PT | 0x3)?;
2940    for gpa in [
2941        GUESTOS_GPA_PML4,
2942        GUESTOS_GPA_PDPT,
2943        GUESTOS_GPA_PD,
2944        GUESTOS_GPA_PT,
2945        GUESTOS_GPA_CODE,
2946        GUESTOS_GPA_STACK,
2947        GUESTOS_GPA_BOOT_PARAMS,
2948    ] {
2949        let index = (gpa / page_size) as usize;
2950        write_world_u64(world_id, GUESTOS_GPA_PT, index * 8, gpa | 0x3)?;
2951    }
2952    for page in 0..GUESTOS_SCAN_PAGES {
2953        let gpa = GUESTOS_SCAN_START + page * page_size;
2954        let index = (gpa / page_size) as usize;
2955        write_world_u64(world_id, GUESTOS_GPA_PT, index * 8, gpa | 0x3)?;
2956    }
2957
2958    // 4. Command line and initrd/module: `write_boot_params` copies both into
2959    //    the block, so the guest can check that they are non-zero.
2960    log::info!("[s9vm] guestostest: storing the command line and one module");
2961    let cmdline_len =
2962        vm::set_cmdline(world_id, GUESTOS_CMDLINE).map_err(|_| SelftestError::VmFail(5))?;
2963    log::info!(
2964        "[s9vm] guestostest: command line stored ({} byte(s))",
2965        cmdline_len
2966    );
2967    vm::load_module(world_id, caps, GUESTOS_GPA_MODULE, GUESTOS_MODULE)
2968        .map_err(|_| SelftestError::VmFail(6))?;
2969    if read_world_byte(world_id, GUESTOS_GPA_MODULE)? != GUESTOS_MODULE[0] {
2970        return Err(SelftestError::BadExit("guestos module was not copied"));
2971    }
2972
2973    // 5. Firmware tables (the RSDP the guest scans for) then the hand-off
2974    //    block.
2975    log::info!("[s9vm] guestostest: writing the firmware tables and boot block");
2976    vm::write_acpi(world_id, caps, vm::ACPI_GPA).map_err(|_| SelftestError::VmFail(7))?;
2977    if read_world_byte(world_id, vm::ACPI_GPA)? != b'R' {
2978        return Err(SelftestError::BadExit("guestos ACPI image was not copied"));
2979    }
2980    vm::write_boot_params(world_id, GUESTOS_GPA_BOOT_PARAMS)
2981        .map_err(|_| SelftestError::VmFail(8))?;
2982
2983    // 6. Kernel-side decode of the same block: the guest report is compared
2984    //    against an independent read of guest memory, not against the values
2985    //    the kernel believes it wrote.
2986    let mut block = [0u8; bootparams::SIZE];
2987    read_world_bytes(world_id, GUESTOS_GPA_BOOT_PARAMS, &mut block)?;
2988    let params = bootparams::BootParams::decode(&block).map_err(|error| {
2989        log::warn!("[s9vm] guestostest FAIL: boot block: {:?}", error);
2990        SelftestError::BadExit("guestos boot block is invalid")
2991    })?;
2992    if params.cmdline_len() != GUESTOS_CMDLINE.len()
2993        || params.memory_count() == 0
2994        || params.module_count() != 1
2995        || params.rsdp_gpa() != vm::ACPI_GPA
2996    {
2997        log::warn!(
2998            "[s9vm] guestostest FAIL: block fields cmdline={} expected={} mem={} \
2999             modules={} rsdp={:#x}",
3000            params.cmdline_len(),
3001            GUESTOS_CMDLINE.len(),
3002            params.memory_count(),
3003            params.module_count(),
3004            params.rsdp_gpa()
3005        );
3006        return Err(SelftestError::BadExit("guestos boot block fields"));
3007    }
3008
3009    // 7. Payload built with the typed assembler.
3010    let layout = guestos::GuestOsLayout {
3011        boot_params_gpa: GUESTOS_GPA_BOOT_PARAMS,
3012        acpi_gpa: vm::ACPI_GPA,
3013        scan_start_gpa: GUESTOS_SCAN_START,
3014        scan_end_gpa: GUESTOS_SCAN_END,
3015    };
3016    let payload = guestos::build_payload(&layout).map_err(|error| {
3017        log::warn!("[s9vm] guestostest FAIL: payload build: {:?}", error);
3018        SelftestError::BadExit("guestos payload build failed")
3019    })?;
3020    if payload.len() > page_size as usize {
3021        return Err(SelftestError::BadExit("guestos payload crosses a page"));
3022    }
3023    write_world_bytes(world_id, GUESTOS_GPA_CODE, payload.emit_bytes())?;
3024
3025    // 8. Uses the world's own second-level translation tables.
3026    let pointer = vm::second_level_pointer(world_id, caps).map_err(|_| SelftestError::VmFail(9))?;
3027
3028    // 9. Enters the payload; the stack lives in its own identity-mapped page.
3029    let guest = GuestState::long_mode_64(GUESTOS_GPA_CODE, GUESTOS_STACK_TOP, GUESTOS_GPA_PML4);
3030    let mut vcpu = Vcpu::new(caps, pointer)?;
3031    // SAFETY: VT-x is active on this CPU (checked by the caller), the control
3032    // block was just created for this vCPU and no other CPU runs it.
3033    unsafe {
3034        vcpu.load()?;
3035        vcpu.configure_host()?;
3036        vcpu.configure(caps, &guest)?;
3037    }
3038
3039    let mut report = GuestOsReport {
3040        total_exits: 0,
3041        io_exits: 0,
3042        halt_exits: 0,
3043        marker: None,
3044        status: None,
3045        guest_cmdline_len: None,
3046        guest_memory_count: None,
3047        cmdline_len: params.cmdline_len() as u32,
3048        memory_count: params.memory_count() as u32,
3049        module_count: params.module_count() as u32,
3050        rsdp: params.rsdp_gpa(),
3051    };
3052    log::info!("[s9vm] guestostest: entering the guest");
3053    let saved_flags = crate::arch::save_flags_and_cli();
3054    let mut debug_out = [0u8; GUESTOS_DEBUG_BYTES];
3055    let mut debug_len = 0usize;
3056    let mut outcome: Result<(), SelftestError> = Ok(());
3057    for _ in 0..GUESTOS_MAX_EXITS {
3058        // SAFETY: `run` contract (control block loaded, IRQs disabled).
3059        let exit = match unsafe { vcpu.run() } {
3060            Ok(exit) => exit,
3061            Err(error) => {
3062                outcome = Err(SelftestError::from(error));
3063                break;
3064            }
3065        };
3066        report.total_exits += 1;
3067        match ExitReason::decode(exit.raw_reason).class() {
3068            ExitClass::IoPort => {
3069                report.io_exits += 1;
3070                let port = ((exit.qualification >> 16) & 0xFFFF) as u16;
3071                if port == TEST_PORT && debug_len < debug_out.len() {
3072                    debug_out[debug_len] = (vcpu.guest().rax & 0xFF) as u8;
3073                    debug_len += 1;
3074                }
3075                // SAFETY: the control block is loaded and the guest is
3076                // inactive (we are in the exit handler).
3077                if let Err(error) = unsafe { vcpu.advance_rip(u64::from(exit.instruction_length)) }
3078                {
3079                    outcome = Err(SelftestError::from(error));
3080                    break;
3081                }
3082            }
3083            ExitClass::Halt => {
3084                report.halt_exits += 1;
3085                break;
3086            }
3087            ExitClass::ExternalInterrupt | ExitClass::InterruptWindow => {}
3088            ExitClass::PreemptionTimer => {}
3089            other => {
3090                log::warn!(
3091                    "[s9vm] guestos test: unexpected exit class={:?} reason={:#x} \
3092                     qual={:#x} rip={:#x} marker={:?} io={} total={}",
3093                    other,
3094                    exit.raw_reason,
3095                    exit.qualification,
3096                    vcpu.guest().rip,
3097                    report.marker,
3098                    report.io_exits,
3099                    report.total_exits
3100                );
3101                outcome = Err(SelftestError::BadExit("unexpected guestos-test exit"));
3102                break;
3103            }
3104        }
3105    }
3106    crate::arch::restore_flags(saved_flags);
3107
3108    // SAFETY: the vCPU is no longer active.
3109    unsafe {
3110        let _ = vcpu.clear();
3111    }
3112
3113    if let Err(error) = outcome {
3114        return Err(error);
3115    }
3116    report.marker = debug_out.first().copied().filter(|_| debug_len > 0);
3117    report.status = if debug_len > 1 {
3118        Some(debug_out[1])
3119    } else {
3120        None
3121    };
3122    if debug_len > 2 {
3123        report.guest_cmdline_len = Some(debug_out[2]);
3124    }
3125    if debug_len > 3 {
3126        report.guest_memory_count = Some(debug_out[3]);
3127    }
3128
3129    if report.halt_exits == 0 {
3130        log::warn!(
3131            "[s9vm] guestostest FAIL: guest never halted marker={:?} io={} total={}",
3132            report.marker,
3133            report.io_exits,
3134            report.total_exits
3135        );
3136        return Err(SelftestError::BadExit("guestos guest did not halt"));
3137    }
3138    if report.marker == Some(guestos::FAIL_MARKER) {
3139        log::warn!(
3140            "[s9vm] guestostest FAIL: guest rejected step {:?} io={} total={}",
3141            report.status,
3142            report.io_exits,
3143            report.total_exits
3144        );
3145        return Err(SelftestError::BadExit("guestos guest reported a failure"));
3146    }
3147    if report.marker != Some(guestos::PASS_MARKER) {
3148        log::warn!(
3149            "[s9vm] guestostest FAIL: marker={:?} expected={} io={} total={}",
3150            report.marker,
3151            guestos::PASS_MARKER,
3152            report.io_exits,
3153            report.total_exits
3154        );
3155        return Err(SelftestError::BadExit("guestos guest did not report PASS"));
3156    }
3157    if report.status != Some(guestos::STATUS_OK) {
3158        log::warn!(
3159            "[s9vm] guestostest FAIL: status={:?} expected={} io={} total={}",
3160            report.status,
3161            guestos::STATUS_OK,
3162            report.io_exits,
3163            report.total_exits
3164        );
3165        return Err(SelftestError::BadExit(
3166            "guestos guest reported a bad status",
3167        ));
3168    }
3169    if report.guest_cmdline_len != Some(report.cmdline_len as u8)
3170        || report.guest_memory_count != Some(report.memory_count as u8)
3171    {
3172        log::warn!(
3173            "[s9vm] guestostest FAIL: guest read cmdline={:?} mem={:?}, kernel decoded \
3174             cmdline={} mem={}",
3175            report.guest_cmdline_len,
3176            report.guest_memory_count,
3177            report.cmdline_len,
3178            report.memory_count
3179        );
3180        return Err(SelftestError::BadExit(
3181            "guestos guest read different block fields",
3182        ));
3183    }
3184    Ok(report)
3185}
3186
3187/// Report of the SMP (multi-vCPU) phase.
3188pub struct SmpReport {
3189    /// Number of vCPUs in the world (always 2 for this phase).
3190    pub vcpus: u32,
3191    /// Markers read back from the shared guest page, per vCPU index.
3192    pub markers: [Option<u8>; 2],
3193    /// Policy exits observed for each vCPU (`out` + `hlt`).
3194    pub exits_per_vcpu: [u32; 2],
3195    /// Total policy exits observed.
3196    pub exits: u32,
3197    /// `hlt` exits observed (one per vCPU).
3198    pub hlt: u32,
3199    /// `RUN` calls that reached the hardware (`WorldStats::runs`).
3200    pub runs: u64,
3201    /// APIC identifiers of the two vCPUs, sorted.
3202    pub apic_ids: [u32; 2],
3203    /// Final guest `RIP` of each vCPU (distinct code pages).
3204    pub rips: [u64; 2],
3205    /// Final guest `RSP` of each vCPU (distinct stacks).
3206    pub rsps: [u64; 2],
3207    /// Guest `CR3` of each vCPU (distinct page tables).
3208    pub cr3s: [u64; 2],
3209    /// True when both vCPU tasks overlapped on distinct scheduler CPUs.
3210    pub concurrent: bool,
3211    /// Number of scheduler CPUs visible to the phase.
3212    pub scheduler_cpus: u32,
3213    /// Wall-clock TSC cycles spent in the two concurrent RUN rounds.
3214    pub wall_cycles: u64,
3215    /// True when both RUN requests were queued back-to-back in every round.
3216    pub requested_together: bool,
3217    /// Number of RUNs executed by each vCPU task.
3218    pub runs_per_vcpu: [u64; 2],
3219}
3220
3221/// Builds the ABI register block that starts one SMP vCPU.
3222///
3223/// The long-mode guest state supplies the canonical CR0/CR4/EFER and the flat
3224/// segments; the caller only chooses the entry point, the stack and the page
3225/// tables, which is what makes the two vCPU contexts independent.
3226fn smp_guest_regs(entry: u64, stack_top: u64, cr3: u64) -> VmmRegs {
3227    let guest = GuestState::long_mode_64(entry, stack_top, cr3);
3228    VmmRegs {
3229        abi_version: VMM_ABI_VERSION,
3230        flags: 0,
3231        rax: guest.rax,
3232        rbx: guest.rbx,
3233        rcx: guest.rcx,
3234        rdx: guest.rdx,
3235        rsi: guest.rsi,
3236        rdi: guest.rdi,
3237        rbp: guest.rbp,
3238        rsp: guest.rsp,
3239        r8: guest.r8,
3240        r9: guest.r9,
3241        r10: guest.r10,
3242        r11: guest.r11,
3243        r12: guest.r12,
3244        r13: guest.r13,
3245        r14: guest.r14,
3246        r15: guest.r15,
3247        rip: guest.rip,
3248        rflags: guest.rflags,
3249        cr0: guest.cr0,
3250        cr3: guest.cr3,
3251        cr4: guest.cr4,
3252        efer: guest.efer,
3253    }
3254}
3255
3256/// Writes the identity page tables of one SMP vCPU.
3257///
3258/// The vCPU only touches its own code page, its own stack page and the shared
3259/// marker page, so the leaf page table maps exactly those three pages. The
3260/// table pages themselves are reached only by the hardware page walker.
3261fn smp_write_page_tables(
3262    world_id: u64,
3263    layout: &SmpLayout,
3264    page_size: u64,
3265) -> Result<(), SelftestError> {
3266    write_world_u64(world_id, layout.pml4, 0, layout.pdpt | 0x3)?;
3267    write_world_u64(world_id, layout.pdpt, 0, layout.pd | 0x3)?;
3268    write_world_u64(world_id, layout.pd, 0, layout.pt | 0x3)?;
3269    for gpa in [layout.code, layout.stack, SMP_SHARED_GPA] {
3270        let index = (gpa / page_size) as usize;
3271        write_world_u64(world_id, layout.pt, index * 8, gpa | 0x3)?;
3272    }
3273    Ok(())
3274}
3275
3276/// SMP (multi-vCPU) test.
3277///
3278/// Creates one world with two vCPUs (APIC ids 0 and 1), each with its own page
3279/// tables, code page and stack page, plus one shared guest page. The phase
3280/// drives the kernel vCPU tasks through `request_run` in an **interleaved**
3281/// order: round 0 runs both vCPUs to their `out` exit (the markers are written
3282/// to the shared page), round 1 resumes both from their saved context to the
3283/// `hlt` exit. Both contexts therefore survive a context switch between the
3284/// two vCPUs; this validates independent, persisted vCPU state, not parallel
3285/// host execution.
3286///
3287/// The world (and its vCPU tasks) is destroyed on every path.
3288/// SMP (multi-vCPU) test: two vCPUs executed concurrently when possible.
3289///
3290/// The phase queues both RUN requests through `vm::request_run_async` (kernel
3291/// internal, non-blocking), then collects both policy exits from the shared
3292/// queue. Expected serial line on a host with working VT-x and more than one
3293/// scheduler CPU:
3294///
3295/// ```text
3296/// [s9vm] smptest PASS: vcpus=2 ... concurrent=<bool> cpus=<n> \
3297///     requested_together=true wall_cycles=<cycles> runs_per_vcpu=[2, 2]
3298/// ```
3299///
3300/// `concurrent=true` requires both vCPUs to be observed with `in_guest` set at
3301/// the same time **and** more than one scheduler CPU; a single-CPU scheduler
3302/// legitimately reports `false` (both RUNs are queued but serialized).
3303pub fn run_smp(caps: &HwCaps) -> Result<SmpReport, SelftestError> {
3304    if !caps.can_run() {
3305        return Err(SelftestError::BadExit("platform cannot run"));
3306    }
3307    let record = vm::create(b"s9vm-smp", 0).ok_or(SelftestError::VmFail(1))?;
3308    let result = run_smp_in_world(caps, record.id);
3309    let _ = vm::destroy(record.id);
3310    result
3311}
3312
3313/// Body of the SMP phase; the caller owns and destroys the world.
3314fn run_smp_in_world(caps: &HwCaps, world_id: u64) -> Result<SmpReport, SelftestError> {
3315    let page_size = crate::s9vm::mmu::PAGE_SIZE;
3316
3317    // 1. Two vCPUs in the same world; the MADT/APIC ids are 0 and 1.
3318    log::info!("[s9vm] smptest: creating two vCPUs");
3319    let vcpus = [
3320        vm::create_vcpu(world_id, 0).map_err(|_| SelftestError::VmFail(2))?,
3321        vm::create_vcpu(world_id, 1).map_err(|_| SelftestError::VmFail(3))?,
3322    ];
3323    log::info!("[s9vm] smptest: mapping guest pages");
3324
3325    // 2. Guest memory: per-vCPU page tables, code and stack, plus one shared
3326    //    page both vCPUs write to.
3327    for layout in SMP_LAYOUTS.iter() {
3328        for gpa in [
3329            layout.pml4,
3330            layout.pdpt,
3331            layout.pd,
3332            layout.pt,
3333            layout.code,
3334            layout.stack,
3335        ] {
3336            vm::map_memory(world_id, caps, gpa, page_size, SMP_GUEST_PERMS, 0)
3337                .map_err(|_| SelftestError::VmFail(4))?;
3338        }
3339    }
3340    vm::map_memory(
3341        world_id,
3342        caps,
3343        SMP_SHARED_GPA,
3344        page_size,
3345        SMP_GUEST_PERMS,
3346        0,
3347    )
3348    .map_err(|_| SelftestError::VmFail(5))?;
3349
3350    // 3. Per-vCPU page tables, payload and initial register block.
3351    for (index, layout) in SMP_LAYOUTS.iter().enumerate() {
3352        smp_write_page_tables(world_id, layout, page_size)?;
3353        write_world_bytes(world_id, layout.code, layout.payload)?;
3354        let regs = smp_guest_regs(layout.code, layout.stack_top, layout.pml4);
3355        vm::set_vcpu_regs(vcpus[index], &regs).map_err(|_| {
3356            log::warn!(
3357                "[s9vm] smp test: vCPU {} rejected its register block",
3358                index
3359            );
3360            SelftestError::BadExit("smp register block rejected")
3361        })?;
3362    }
3363
3364    // 4. Concurrent execution. `request_run_async` posts the RUN and returns
3365    //    immediately, so both vCPU tasks are runnable at the same time. The
3366    //    exits are then collected from the shared queue while snapshots are
3367    //    sampled: `in_guest` on both vCPUs is the actual overlap evidence
3368    //    (unlike `executing`, which only says the request is queued).
3369    let scheduler_cpus = crate::arch::smp::cpu_count().max(1) as u32;
3370    let mut markers: [Option<u8>; 2] = [None; 2];
3371    let mut exits_per_vcpu: [u32; 2] = [0; 2];
3372    let mut hlt = 0u32;
3373    let mut total_runs = 0u32;
3374    let concurrent;
3375    let mut overlap_observed = false;
3376    let mut requested_together = false;
3377    let mut wall_cycles = 0u64;
3378    for round in 0..2u32 {
3379        let round_start = unsafe { core::arch::x86_64::_rdtsc() };
3380        let mut requested = [false; 2];
3381        for (index, vcpu) in vcpus.iter().enumerate() {
3382            if total_runs >= SMP_MAX_RUNS {
3383                return Err(SelftestError::BadExit("smp RUN budget exhausted"));
3384            }
3385            match vm::request_run_async(*vcpu) {
3386                Ok(()) => requested[index] = true,
3387                Err(error) => {
3388                    log::warn!(
3389                        "[s9vm] smp test: vCPU {} round {} async RUN failed: {:?} \
3390                         markers={:?} exits={:?} hlt={}",
3391                        index,
3392                        round,
3393                        error,
3394                        markers,
3395                        exits_per_vcpu,
3396                        hlt
3397                    );
3398                    return Err(SelftestError::BadExit("smp async RUN failed"));
3399                }
3400            }
3401            total_runs += 1;
3402        }
3403        requested_together = requested.iter().all(|value| *value);
3404        log::info!(
3405            "[s9vm] smptest: round {} both RUNs queued (requested={:?}, cpus={})",
3406            round,
3407            requested,
3408            scheduler_cpus
3409        );
3410
3411        // Collect both exits with a bounded poll; sampling the snapshots while
3412        // waiting is what detects (or disproves) overlap.
3413        let deadline_ticks = crate::process::scheduler::ticks()
3414            .saturating_add((SMP_EXIT_TIMEOUT_NS / crate::arch::timer::NS_PER_TICK).max(1));
3415        let mut events: [Option<strat9_abi::vmm::VmmExitEvent>; 2] = [None, None];
3416        let mut collected = 0usize;
3417        while collected < 2 {
3418            if let Some(snapshots) = vm::vcpu_snapshots(world_id) {
3419                if snapshots.len() == 2 && snapshots.iter().all(|snapshot| snapshot.in_guest) {
3420                    overlap_observed = true;
3421                }
3422            }
3423            if vm::exit_count(world_id).unwrap_or(0) > 0 {
3424                let event = vm::pop_exit(world_id)
3425                    .map_err(|_| SelftestError::BadExit("smp exit queue empty after RUN"))?;
3426                let index = if event.vcpu_id == vcpus[0] {
3427                    0
3428                } else if event.vcpu_id == vcpus[1] {
3429                    1
3430                } else {
3431                    log::warn!(
3432                        "[s9vm] smp test: exit for unknown vCPU {} (expected {:?})",
3433                        event.vcpu_id,
3434                        vcpus
3435                    );
3436                    return Err(SelftestError::BadExit("smp exit for unknown vCPU"));
3437                };
3438                if events[index].is_some() {
3439                    return Err(SelftestError::BadExit("smp duplicate exit for vCPU"));
3440                }
3441                events[index] = Some(event);
3442                collected += 1;
3443                continue;
3444            }
3445            if crate::process::scheduler::ticks() >= deadline_ticks {
3446                // Name the state of both vCPU tasks: a missing exit is either a
3447                // failed run (the error is published) or a task that never ran
3448                // (the request is still marked in flight).
3449                let states = [vm::run_completion(vcpus[0]), vm::run_completion(vcpus[1])];
3450                log::warn!(
3451                    "[s9vm] smp test: round {} exit timeout collected={} exits={:?} \
3452                         hlt={} overlap={} cpus={} states={:?}",
3453                    round,
3454                    collected,
3455                    exits_per_vcpu,
3456                    hlt,
3457                    overlap_observed,
3458                    scheduler_cpus,
3459                    states
3460                );
3461                return Err(SelftestError::BadExit("smp exit timeout"));
3462            }
3463            crate::process::sleep_current_task_ticks(1);
3464        }
3465        wall_cycles = wall_cycles
3466            .saturating_add(unsafe { core::arch::x86_64::_rdtsc().saturating_sub(round_start) });
3467
3468        for (index, layout) in SMP_LAYOUTS.iter().enumerate() {
3469            let event = events[index]
3470                .take()
3471                .ok_or(SelftestError::BadExit("smp missing exit for vCPU"))?;
3472            exits_per_vcpu[index] += 1;
3473            match event.kind {
3474                exit_kind::IO_PORT => {
3475                    if round != 0 || event.port as u16 != TEST_PORT || event.flags != 0 {
3476                        log::warn!(
3477                            "[s9vm] smp test: vCPU {} unexpected I/O exit round={} \
3478                             port={:#x} flags={:#x}",
3479                            index,
3480                            round,
3481                            event.port,
3482                            event.flags
3483                        );
3484                        return Err(SelftestError::BadExit("smp unexpected I/O exit"));
3485                    }
3486                    vm::complete_exit(
3487                        vcpus[index],
3488                        u64::from(layout.marker),
3489                        SMP_OUT_INSTRUCTION_LEN,
3490                    )
3491                    .map_err(|_| SelftestError::BadExit("smp complete_exit failed"))?;
3492                }
3493                exit_kind::HALT => {
3494                    if round != 1 {
3495                        log::warn!("[s9vm] smp test: vCPU {} halted in round {}", index, round);
3496                        return Err(SelftestError::BadExit("smp early hlt"));
3497                    }
3498                    hlt += 1;
3499                }
3500                other => {
3501                    log::warn!(
3502                        "[s9vm] smp test: vCPU {} round {} unexpected exit kind={} \
3503                         port={:#x} flags={:#x} gpa={:#x}",
3504                        index,
3505                        round,
3506                        other,
3507                        event.port,
3508                        event.flags,
3509                        event.gpa
3510                    );
3511                    return Err(SelftestError::BadExit("smp unexpected exit"));
3512                }
3513            }
3514        }
3515
3516        // The vCPU task publishes `run_done` just after the exit; wait for it
3517        // with the bounded async-completion helper before the next round.
3518        for vcpu in vcpus {
3519            if let Err(error) = vm::wait_run_complete(vcpu, SMP_EXIT_TIMEOUT_NS) {
3520                log::warn!(
3521                    "[s9vm] smp test: vCPU {} did not complete round {}: {:?}",
3522                    vcpu,
3523                    round,
3524                    error
3525                );
3526                return Err(SelftestError::BadExit("smp vCPU run not completed"));
3527            }
3528        }
3529    }
3530    // Real overlap needs more than one scheduler CPU; with one CPU the two
3531    // tasks are runnable together but serialized by the scheduler.
3532    concurrent = overlap_observed && scheduler_cpus > 1 && requested_together;
3533
3534    // 5. Markers: the shared page is the authoritative trace (written by the
3535    //    guest before the exit), and each vCPU context must also still hold
3536    //    its own marker in RAX.
3537    for index in 0..2 {
3538        let byte = read_world_byte(world_id, SMP_SHARED_GPA + index as u64)?;
3539        markers[index] = Some(byte);
3540    }
3541
3542    let mut rips = [0u64; 2];
3543    let mut rsps = [0u64; 2];
3544    let mut cr3s = [0u64; 2];
3545    for (index, layout) in SMP_LAYOUTS.iter().enumerate() {
3546        let regs = vm::get_vcpu_regs(vcpus[index])
3547            .ok_or(SelftestError::BadExit("smp vCPU register block missing"))?;
3548        rips[index] = regs.rip;
3549        rsps[index] = regs.rsp;
3550        cr3s[index] = regs.cr3;
3551        if (regs.rax & 0xFF) as u8 != layout.marker {
3552            log::warn!(
3553                "[s9vm] smp test: vCPU {} RAX marker={:#x} expected={:#x}",
3554                index,
3555                regs.rax & 0xFF,
3556                layout.marker
3557            );
3558            return Err(SelftestError::BadExit(
3559                "smp marker lost from the register block",
3560            ));
3561        }
3562    }
3563
3564    let expected_rip = [
3565        SMP_VCPU0_GPA_CODE + SMP_HLT_OFFSET,
3566        SMP_VCPU1_GPA_CODE + SMP_HLT_OFFSET,
3567    ];
3568    let expected_rsp = [SMP_VCPU0_GPA_STACK + 0x800, SMP_VCPU1_GPA_STACK + 0x800];
3569    let expected_cr3 = [SMP_VCPU0_GPA_PML4, SMP_VCPU1_GPA_PML4];
3570    if rips != expected_rip
3571        || rsps != expected_rsp
3572        || cr3s != expected_cr3
3573        || rips[0] == rips[1]
3574        || rsps[0] == rsps[1]
3575        || cr3s[0] == cr3s[1]
3576    {
3577        log::warn!(
3578            "[s9vm] smp test: contexts not independent rips={:?} rsps={:?} cr3s={:?}",
3579            rips,
3580            rsps,
3581            cr3s
3582        );
3583        return Err(SelftestError::BadExit(
3584            "smp vCPU contexts are not independent",
3585        ));
3586    }
3587
3588    // 6. APIC identifiers, per-vCPU run counters and engine counters.
3589    let mut apic_ids = [0u32; 2];
3590    let mut runs_per_vcpu = [0u64; 2];
3591    {
3592        let snapshots = vm::vcpu_snapshots(world_id)
3593            .ok_or(SelftestError::BadExit("smp world snapshots missing"))?;
3594        if snapshots.len() != 2 {
3595            return Err(SelftestError::BadExit("smp world does not have two vCPUs"));
3596        }
3597        apic_ids[0] = snapshots[0].apic_id;
3598        apic_ids[1] = snapshots[1].apic_id;
3599        apic_ids.sort_unstable();
3600        for (index, vcpu) in vcpus.iter().enumerate() {
3601            runs_per_vcpu[index] = snapshots
3602                .iter()
3603                .find(|snapshot| snapshot.id == *vcpu)
3604                .map(|snapshot| snapshot.runs)
3605                .unwrap_or(0);
3606        }
3607    }
3608    if apic_ids != [0, 1] {
3609        log::warn!("[s9vm] smp test: unexpected APIC ids {:?}", apic_ids);
3610        return Err(SelftestError::BadExit("smp unexpected APIC ids"));
3611    }
3612    if runs_per_vcpu != [2, 2] {
3613        log::warn!(
3614            "[s9vm] smp test: per-vCPU runs {:?} expected [2, 2] (total stats runs pending)",
3615            runs_per_vcpu
3616        );
3617        return Err(SelftestError::BadExit("smp per-vCPU run counters mismatch"));
3618    }
3619
3620    let stats = vm::stats(world_id).ok_or(SelftestError::BadExit("smp stats missing"))?;
3621    let pending = vm::exit_count(world_id).unwrap_or(0);
3622    let total_exits = exits_per_vcpu[0] + exits_per_vcpu[1];
3623    if hlt != 2
3624        || total_exits != 4
3625        || pending != 0
3626        || stats.runs < u64::from(total_runs)
3627        || stats.policy_exits != u64::from(total_exits)
3628    {
3629        log::warn!(
3630            "[s9vm] smp test: counters hlt={} exits={:?} pending={} runs={} \
3631             policy_exits={} markers={:?}",
3632            hlt,
3633            exits_per_vcpu,
3634            pending,
3635            stats.runs,
3636            stats.policy_exits,
3637            markers
3638        );
3639        return Err(SelftestError::BadExit("smp exit counters mismatch"));
3640    }
3641
3642    if markers != [Some(SMP_MARKERS[0]), Some(SMP_MARKERS[1])] {
3643        log::warn!(
3644            "[s9vm] smp test: shared markers={:?} expected={:?}",
3645            markers,
3646            SMP_MARKERS
3647        );
3648        return Err(SelftestError::BadExit("smp shared markers mismatch"));
3649    }
3650
3651    Ok(SmpReport {
3652        vcpus: 2,
3653        markers,
3654        exits_per_vcpu,
3655        exits: total_exits,
3656        hlt,
3657        runs: stats.runs,
3658        apic_ids,
3659        rips,
3660        rsps,
3661        cr3s,
3662        concurrent,
3663        scheduler_cpus,
3664        wall_cycles,
3665        requested_together,
3666        runs_per_vcpu,
3667    })
3668}
3669
3670/// Kthread-stage hook: runs the deferred SMP phase.
3671///
3672/// Like the ACPI phase, the SMP phase needs registered vCPUs and therefore the
3673/// scheduler: it is requested during the early bootstrap and executed here in
3674/// its own kernel thread.
3675#[cfg(target_arch = "x86_64")]
3676#[component::init_component(kthread, priority = 51)]
3677fn s9vm_smp_selftest() -> Result<(), component::ComponentInitError> {
3678    if !SMP_SELFTEST_REQUESTED.swap(false, Ordering::AcqRel) {
3679        return Ok(());
3680    }
3681    match crate::process::kthread::spawn("s9vm-smp-selftest", run_smp_task) {
3682        Ok(_) => {}
3683        Err(error) => log::warn!(
3684            "[s9vm] smptest FAIL: cannot spawn the guest task ({})",
3685            error
3686        ),
3687    }
3688    Ok(())
3689}
3690
3691/// Body of the deferred SMP selftest task.
3692fn run_smp_task() {
3693    let Some(caps) = crate::s9vm::detect_vmx() else {
3694        log::warn!("[s9vm] smptest FAIL: platform capabilities unavailable");
3695        return;
3696    };
3697    log::info!(
3698        "[s9vm] smptest: task start (active_cpus={})",
3699        crate::s9vm::active_cpu_count()
3700    );
3701    match run_smp(&caps) {
3702        Ok(report) => log::info!(
3703            "[s9vm] smptest PASS: vcpus={} markers={:?} exits={} hlt={} runs={} \
3704             apic_ids={:?} rips={:?} rsps={:?} cr3s={:?} concurrent={} cpus={} \
3705             requested_together={} wall_cycles={} runs_per_vcpu={:?}",
3706            report.vcpus,
3707            report.markers,
3708            report.exits,
3709            report.hlt,
3710            report.runs,
3711            report.apic_ids,
3712            report.rips,
3713            report.rsps,
3714            report.cr3s,
3715            report.concurrent,
3716            report.scheduler_cpus,
3717            report.requested_together,
3718            report.wall_cycles,
3719            report.runs_per_vcpu
3720        ),
3721        Err(error) => log::warn!("[s9vm] smptest FAIL: {:?}", error),
3722    }
3723}
3724
3725/// Kthread-stage hook: runs the guest-OS bootstrap phase synchronously.
3726///
3727/// The phase registers a **detached** vCPU and drives it with a direct `Vcpu`
3728/// loop, so it does not need the scheduler; it runs at this stage because the
3729/// firmware and boot-parameter writers expect a live boot environment.
3730#[cfg(target_arch = "x86_64")]
3731#[component::init_component(kthread, priority = 52)]
3732fn s9vm_guestos_selftest() -> Result<(), component::ComponentInitError> {
3733    if !GUESTOS_SELFTEST_REQUESTED.swap(false, Ordering::AcqRel) {
3734        return Ok(());
3735    }
3736    run_guestos_task();
3737    Ok(())
3738}
3739
3740/// Body of the guest-OS selftest (synchronous).
3741fn run_guestos_task() {
3742    let Some(caps) = crate::s9vm::detect_vmx() else {
3743        log::warn!("[s9vm] guestostest FAIL: platform capabilities unavailable");
3744        return;
3745    };
3746    log::info!(
3747        "[s9vm] guestostest: running (active_cpus={})",
3748        crate::s9vm::active_cpu_count()
3749    );
3750    match run_guestos(&caps) {
3751        Ok(report) => log::info!(
3752            "[s9vm] guestostest PASS: total={} io={} hlt={} marker={:?} magic=ok \
3753             mem={} cmdline={} rsdp={:#x} status={:?} modules={} guest_cmdline={:?} \
3754             guest_mem={:?}",
3755            report.total_exits,
3756            report.io_exits,
3757            report.halt_exits,
3758            report.marker,
3759            report.memory_count,
3760            report.cmdline_len,
3761            report.rsdp,
3762            report.status,
3763            report.module_count,
3764            report.guest_cmdline_len,
3765            report.guest_memory_count
3766        ),
3767        Err(error) => log::warn!("[s9vm] guestostest FAIL: {:?}", error),
3768    }
3769}
3770
3771/// Runs a VT-x-free dry run when the boot configuration asks for it.
3772///
3773/// Two modes are accepted:
3774///
3775/// - `s9vm.selftest=loader_dry` exercises the world memory mapping, the kernel
3776///   ELF loader (copy + BSS zero-fill) and the world teardown;
3777/// - `s9vm.selftest=linux_dry` exercises the whole 64-bit boot preparation:
3778///   image parse, layout plan, guest memory mapping, protected-mode copy, boot
3779///   parameter page with its e820 map, command line, entry GDT and the guest
3780///   page tables built through the world translation.
3781///
3782/// Neither enters a guest, so both work on hosts where VT-x is unavailable and
3783/// turn the boot path into a deterministic smoke test. They are called before
3784/// the VT-x detection in [`crate::s9vm::init`], with a default capability set
3785/// (the world memory layer does not depend on the hardware controls).
3786pub fn maybe_run_loader_dry_from_boot_env() {
3787    let mode = crate::boot_args()
3788        .and_then(|args| args.env_get("s9vm.selftest"))
3789        .unwrap_or("");
3790    if mode == "linux_dry" {
3791        log::info!("[s9vm] boot-protocol dry run requested (no VT-x required)");
3792        let caps = HwCaps::default();
3793        match run_boot_protocol_dry(&caps) {
3794            Ok(report) => log::info!(
3795                "[s9vm] bootdry PASS: kernel={:#x} bytes={} init_size={} entry={:#x} \
3796                 params={:#x} cmdline={:#x} gdt={:#x} tables={} ranges={} \
3797                 (parse + layout + zero page + guest tables, no guest entry)",
3798                report.kernel_base,
3799                report.kernel_bytes,
3800                report.init_size,
3801                report.entry,
3802                report.boot_params_gpa,
3803                report.cmdline_gpa,
3804                report.gdt_gpa,
3805                report.table_pages,
3806                report.identity_ranges
3807            ),
3808            Err(error) => log::warn!("[s9vm] bootdry FAIL: {:?}", error),
3809        }
3810        return;
3811    }
3812    if mode == "dos_dry" {
3813        log::info!("[s9vm] DOS boot dry run requested (no VT-x required)");
3814        let caps = HwCaps::default();
3815        match dosboot::run_dos_dry(&caps) {
3816            Ok(report) => log::info!(
3817                "[s9vm] dosdry PASS: boot={:#x} entry={:#x} sectors={} \
3818                 (low memory + BIOS ROM + IVT/BDA + boot sector + disk, no guest entry)",
3819                report.boot_sector_gpa,
3820                report.entry,
3821                report.disk_sectors
3822            ),
3823            Err(error) => log::warn!("[s9vm] dosdry FAIL: {:?}", error),
3824        }
3825        return;
3826    }
3827    if mode == "freedos_hello_dry" {
3828        log::info!("[s9vm] FreeDOS Hello/DIR dry run requested (no VT-x required)");
3829        let caps = HwCaps::default();
3830        match dosboot::run_freedos_hello_dry(&caps) {
3831            Ok(report) => log::info!(
3832                "[s9vm] freedos-hello-dry PASS: boot={:#x} entry={:#x} sectors={} \
3833                 (Hello/DIR image installed, no guest entry)",
3834                report.boot_sector_gpa,
3835                report.entry,
3836                report.disk_sectors
3837            ),
3838            Err(error) => log::warn!("[s9vm] freedos-hello-dry FAIL: {:?}", error),
3839        }
3840        return;
3841    }
3842    if mode == "freedos_seabios_dry" {
3843        log::info!("[s9vm] FreeDOS/SeaBIOS dry run requested (no VT-x required)");
3844        let caps = HwCaps::default();
3845        match dosboot::run_freedos_seabios_dry(&caps) {
3846            Ok(report) => log::info!(
3847                "[s9vm] freedos-seabios-dry PASS: reset={:#x} sectors={} \
3848                 (256 KiB SeaBIOS at 0xC0000 + SeaVGABIOS in its zero prefix + \
3849                 4 MiB window, no guest entry)",
3850                report.entry,
3851                report.disk_sectors
3852            ),
3853            Err(error) => log::warn!("[s9vm] freedos-seabios-dry FAIL: {:?}", error),
3854        }
3855        return;
3856    }
3857    if mode == "freedos_dry" {
3858        log::info!("[s9vm] FreeDOS boot dry run requested (no VT-x required)");
3859        let caps = HwCaps::default();
3860        match dosboot::run_freedos_dry(&caps) {
3861            Ok(report) => log::info!(
3862                "[s9vm] freedosdry PASS: boot={:#x} entry={:#x} sectors={} \
3863                 (low memory + BIOS ROM + IVT/BDA + FreeDOS boot sector + disk, \
3864                 no guest entry)",
3865                report.boot_sector_gpa,
3866                report.entry,
3867                report.disk_sectors
3868            ),
3869            Err(error) => log::warn!("[s9vm] freedosdry FAIL: {:?}", error),
3870        }
3871        return;
3872    }
3873    if mode == "freedos_prepare_dry" {
3874        log::info!("[s9vm] FreeDOS boot-preparation dry run requested (no VT-x required)");
3875        let caps = HwCaps::default();
3876        match dosboot::run_freedos_prepare_dry(&caps) {
3877            Ok(()) => log::info!(
3878                "[s9vm] freedos-prepare-dry PASS: world mapped with its second-level tables, \
3879                 firmware and disk installed, INT 13h adapter reads and writes (no guest entry)"
3880            ),
3881            Err(error) => log::warn!("[s9vm] freedos-prepare-dry FAIL: {:?}", error),
3882        }
3883        return;
3884    }
3885    if mode == "freedos_session_dry" {
3886        log::info!("[s9vm] FreeDOS live-session dry run requested (no VT-x required)");
3887        let caps = HwCaps::default();
3888        match dosboot::run_freedos_session_dry(&caps) {
3889            Ok(()) => log::info!(
3890                "[s9vm] freedos-session-dry PASS: world mapped, image installed, console input/\
3891                 output and VGA text round-tripped, disk write persisted (no guest entry)"
3892            ),
3893            Err(error) => log::warn!("[s9vm] freedos-session-dry FAIL: {:?}", error),
3894        }
3895        return;
3896    }
3897    if mode != "loader_dry" {
3898        return;
3899    }
3900    log::info!("[s9vm] image-loader dry run requested (no VT-x required)");
3901    let caps = HwCaps::default();
3902    match run_loader_dry(&caps) {
3903        Ok(report) => log::info!(
3904            "[s9vm] loaderdry PASS: entry={:#x} base={:#x} pages={} \
3905             (world memory + loader, no guest entry)",
3906            report.entry,
3907            report.image_base,
3908            report.pages
3909        ),
3910        Err(error) => log::warn!("[s9vm] loaderdry FAIL: {:?}", error),
3911    }
3912}
3913
3914///
3915/// Does nothing if VT-x is not active. Never panics.
3916///
3917/// The ACPI, SMP and guest-OS phases need a registered vCPU or a live boot
3918/// environment, so when requested they are deferred to the `kthread` stage
3919/// through [`s9vm_acpi_selftest`], [`s9vm_smp_selftest`] and
3920/// [`s9vm_guestos_selftest`]; the other phases run here, during the early
3921/// bootstrap.
3922pub fn maybe_run_from_boot_env(caps: &HwCaps) {
3923    // Value: 1/true = device fast path; 2/all = every phase; irq, console,
3924    // blk, net, loader, acpi, smp, guestos = one phase only.
3925    let mode = crate::boot_args()
3926        .and_then(|args| args.env_get("s9vm.selftest"))
3927        .unwrap_or("");
3928    if mode.is_empty() || mode == "0" || mode == "false" {
3929        return;
3930    }
3931    // Frame-metadata state at the start of the phase sequence: the typed frame
3932    // API (`Vcpu::new`, process page tables) panics with a clear message when
3933    // the array is unavailable, and this line tells whether it was already
3934    // missing at the start of the selftests or lost later.
3935    let (meta_base, meta_frames, meta_init, plan_ram, plan_bytes) =
3936        crate::memory::frame::metadata_snapshot();
3937    log::info!(
3938        "[s9vm] selftest start: metadata base={meta_base:#x} frames={meta_frames} \
3939         init={meta_init:#x} plan_ram={plan_ram:#x} plan_bytes={plan_bytes}"
3940    );
3941    let device_phase = matches!(mode, "1" | "true" | "2" | "all");
3942    let interrupt_phase = matches!(mode, "2" | "all" | "irq");
3943    let console_phase = matches!(mode, "2" | "all" | "console");
3944    let block_phase = matches!(mode, "2" | "all" | "blk");
3945    let network_phase = matches!(mode, "2" | "all" | "net");
3946    let loader_phase = matches!(mode, "2" | "all" | "loader");
3947    // The DOS phase boots a real-mode 16-bit guest through the BIOS model. It
3948    // needs VT-x (real-mode entry) and the `unrestricted guest` control; on a
3949    // host without them the phase reports SKIP, and `dos_dry` covers the whole
3950    // preparation without VT-x.
3951    let dos_phase = mode == "dos";
3952    // FreeDOS 1.4 boot through the same BIOS model, from the real boot floppy
3953    // shipped under `assets/disks/`. It also needs VT-x and the
3954    // `unrestricted guest` control; `freedos_dry` covers the preparation.
3955    let freedos_phase = mode == "freedos";
3956    let freedos_seabios_phase = mode == "freedos_seabios";
3957    let freedos_hello_phase = mode == "freedos_hello";
3958    // Live DOS session: boots through the session API, types `dir` through the
3959    // console queue and checks the listing. This is the interactive path
3960    // (resumed vCPU, 8259 delivery, 8042 keyboard) exercised without an
3961    // operator.
3962    let freedos_session_phase = mode == "freedos_session";
3963    // The phases that need a registered vCPU run from kernel threads at the
3964    // `kthread` stage. They are opt-in for the `2`/`all` mode: they exercise
3965    // the newest kernel-thread path, so a boot that must stay predictable can
3966    // keep them out while still running the six bootstrap phases.
3967    let deferred_enabled = crate::boot_args()
3968        .and_then(|args| args.env_get("s9vm.selftest.deferred"))
3969        .map(|value| value == "1" || value == "true")
3970        .unwrap_or(false);
3971    let all_phases = matches!(mode, "2" | "all");
3972    let acpi_phase = mode == "acpi" || (all_phases && deferred_enabled);
3973    // The SMP phase drives registered vCPUs through their kernel tasks. It is
3974    // enabled with the other deferred phases now that the task path has a
3975    // bounded RUN/destroy diagnostic (`s9vm.kthread_smoke`), and can still be
3976    // selected explicitly.
3977    let smp_phase = mode == "smp" || (all_phases && deferred_enabled);
3978    // The guest-OS bootstrap phase registers a detached vCPU and drives it
3979    // directly (no scheduler), but it is deferred with the other
3980    // firmware-hand-off phases so the default boot keeps its six phases.
3981    let guestos_phase = mode == "guestos" || (all_phases && deferred_enabled);
3982    if all_phases && !deferred_enabled {
3983        log::info!(
3984            "[s9vm] deferred phases (acpi, smp, guestos) not requested; set \
3985             s9vm.selftest.deferred=1 to run them"
3986        );
3987    }
3988
3989    if acpi_phase {
3990        // The ACPI phase registers a vCPU, which needs the scheduler: defer it
3991        // to the kthread stage instead of deadlocking the bootstrap.
3992        ACPI_SELFTEST_REQUESTED.store(true, Ordering::Release);
3993        log::info!("[s9vm] ACPI-discovery test requested (kthread stage)");
3994    }
3995    if smp_phase {
3996        // Same constraint as ACPI: two registered vCPUs require the scheduler.
3997        SMP_SELFTEST_REQUESTED.store(true, Ordering::Release);
3998        log::info!("[s9vm] SMP (two-vCPU) test requested (kthread stage, experimental)");
3999    }
4000    if guestos_phase {
4001        GUESTOS_SELFTEST_REQUESTED.store(true, Ordering::Release);
4002        log::info!("[s9vm] guest-OS bootstrap test requested (kthread stage)");
4003    }
4004
4005    if device_phase {
4006        log::info!("[s9vm] hardware smoke test requested");
4007        match run(caps) {
4008            Ok(report) => log::info!(
4009                "[s9vm] selftest PASS: variant={} exits={} io={} hlt={} emulated={} pic={:?} byte={:?}",
4010                report.variant,
4011                report.total_exits,
4012                report.io_exits,
4013                report.halt_exits,
4014                report.emulated_exits,
4015                report.pic_readback,
4016                report.observed_byte
4017            ),
4018            Err(error) => log::warn!("[s9vm] selftest FAIL: {:?}", error),
4019        }
4020    }
4021
4022    if console_phase {
4023        log::info!("[s9vm] console-transport test requested");
4024        match run_console(caps) {
4025            Ok(report) => log::info!(
4026                "[s9vm] consoletest PASS: exits={} emulated={} io={} hlt={} marker={:?} bytes={}",
4027                report.total_exits,
4028                report.emulated_exits,
4029                report.io_exits,
4030                report.halt_exits,
4031                report.marker,
4032                report.output.len()
4033            ),
4034            Err(error) => log::warn!("[s9vm] consoletest FAIL: {:?}", error),
4035        }
4036    }
4037
4038    if network_phase {
4039        log::info!("[s9vm] network-transport test requested");
4040        match run_net(caps) {
4041            Ok(report) => log::info!(
4042                "[s9vm] nettest PASS: exits={} emulated={} hlt={} marker={:?} transmitted={} payload={}",
4043                report.total_exits,
4044                report.emulated_exits,
4045                report.halt_exits,
4046                report.marker,
4047                report.transmitted,
4048                report.payload.len()
4049            ),
4050            Err(error) => log::warn!("[s9vm] nettest FAIL: {:?}", error),
4051        }
4052    }
4053
4054    if block_phase {
4055        log::info!("[s9vm] block-transport test requested");
4056        match run_blk(caps) {
4057            Ok(report) => log::info!(
4058                "[s9vm] blktest PASS: exits={} emulated={} io={} hlt={} marker={:?} requests={} status={}",
4059                report.total_exits,
4060                report.emulated_exits,
4061                report.io_exits,
4062                report.halt_exits,
4063                report.marker,
4064                report.requests,
4065                report.status
4066            ),
4067            Err(error) => log::warn!("[s9vm] blktest FAIL: {:?}", error),
4068        }
4069    }
4070
4071    if interrupt_phase {
4072        log::info!("[s9vm] interrupt-delivery test requested");
4073        match run_interrupt(caps) {
4074            Ok(report) => log::info!(
4075                "[s9vm] irqtest PASS: exits={} windows={} injected={} io={} hlt={} byte={:?}",
4076                report.total_exits,
4077                report.window_exits,
4078                report.injected,
4079                report.io_exits,
4080                report.halt_exits,
4081                report.observed_byte
4082            ),
4083            Err(error) => log::warn!("[s9vm] irqtest FAIL: {:?}", error),
4084        }
4085    }
4086
4087    if loader_phase {
4088        log::info!("[s9vm] image-loader test requested");
4089        match run_loader(caps) {
4090            Ok(report) => log::info!(
4091                "[s9vm] loadertest PASS: entry={:#x} base={:#x} pages={} exits={} io={} hlt={} marker={:?}",
4092                report.entry,
4093                report.image_base,
4094                report.pages,
4095                report.total_exits,
4096                report.io_exits,
4097                report.halt_exits,
4098                report.marker
4099            ),
4100            Err(error) => log::warn!("[s9vm] loadertest FAIL: {:?}", error),
4101        }
4102    }
4103
4104    if dos_phase {
4105        log::info!("[s9vm] DOS real-mode boot requested (VT-x required)");
4106        match dosboot::run_dos(caps) {
4107            Ok(report) => log::info!(
4108                "[s9vm] dostest PASS: boot={:#x} entry={:#x} marker={:?} exits={} \
4109                 io={} bios={} hlt={} sectors={} text={:?}",
4110                report.boot_sector_gpa,
4111                report.entry,
4112                report.marker,
4113                report.total_exits,
4114                report.io_exits,
4115                report.bios_calls,
4116                report.halt_exits,
4117                report.disk_sectors,
4118                report.text
4119            ),
4120            Err(dosboot::DosError::Unsupported) => log::warn!(
4121                "[s9vm] dostest SKIP: real-mode entry needs VT-x and the \
4122                 unrestricted-guest control"
4123            ),
4124            Err(error) => log::warn!("[s9vm] dostest FAIL: {:?}", error),
4125        }
4126    }
4127
4128    if freedos_phase {
4129        log::info!("[s9vm] FreeDOS real-mode boot requested (VT-x required)");
4130        match dosboot::run_freedos(caps) {
4131            Ok(report) => log::info!(
4132                "[s9vm] freedostest PASS: boot={:#x} entry={:#x} marker={:?} exits={} \
4133                 io={} bios={} hlt={} sectors={} text={:?}",
4134                report.boot_sector_gpa,
4135                report.entry,
4136                report.marker,
4137                report.total_exits,
4138                report.io_exits,
4139                report.bios_calls,
4140                report.halt_exits,
4141                report.disk_sectors,
4142                report.text
4143            ),
4144            Err(dosboot::DosError::Unsupported) => log::warn!(
4145                "[s9vm] freedostest SKIP: real-mode entry needs VT-x and the \
4146                 unrestricted-guest control"
4147            ),
4148            Err(error) => log::warn!("[s9vm] freedostest FAIL: {:?}", error),
4149        }
4150    }
4151
4152    if freedos_seabios_phase {
4153        log::info!("[s9vm] FreeDOS SeaBIOS boot requested (VT-x required)");
4154        match dosboot::run_freedos_seabios(caps) {
4155            Ok(report) => log::info!(
4156                "[s9vm] freedos-seabios PASS: reset={:#x} marker={:?} exits={} io={} \
4157                 bios={} hlt={} sectors={} text={:?}",
4158                report.entry,
4159                report.marker,
4160                report.total_exits,
4161                report.io_exits,
4162                report.bios_calls,
4163                report.halt_exits,
4164                report.disk_sectors,
4165                report.text
4166            ),
4167            Err(dosboot::DosError::Unsupported) => log::warn!(
4168                "[s9vm] freedos-seabios SKIP: real-mode entry needs VT-x and the \
4169                 unrestricted-guest control"
4170            ),
4171            Err(error) => log::warn!("[s9vm] freedos-seabios FAIL: {:?}", error),
4172        }
4173    }
4174
4175    if freedos_hello_phase {
4176        log::info!("[s9vm] FreeDOS Hello/DIR boot requested (VT-x required)");
4177        match dosboot::run_freedos_hello(caps) {
4178            Ok(report) => log::info!(
4179                "[s9vm] freedos-hello PASS: reset={:#x} marker={:?} exits={} io={} \
4180                 hlt={} sectors={} text={:?}",
4181                report.entry,
4182                report.marker,
4183                report.total_exits,
4184                report.io_exits,
4185                report.halt_exits,
4186                report.disk_sectors,
4187                report.text
4188            ),
4189            Err(dosboot::DosError::Unsupported) => log::warn!(
4190                "[s9vm] freedos-hello SKIP: real-mode entry needs VT-x and the \
4191                 unrestricted-guest control"
4192            ),
4193            Err(error) => log::warn!("[s9vm] freedos-hello FAIL: {:?}", error),
4194        }
4195    }
4196
4197    if freedos_session_phase {
4198        log::info!("[s9vm] FreeDOS live session requested (VT-x required)");
4199        match dosboot::run_freedos_session_selftest(caps) {
4200            Ok(()) => log::info!(
4201                "[s9vm] freedos-session PASS: booted to the prompt, typed `dir` and round-tripped a \
4202                 file over the session console"
4203            ),
4204            Err(dosboot::DosError::Unsupported) => log::warn!(
4205                "[s9vm] freedos-session SKIP: real-mode entry needs VT-x and the \
4206                 unrestricted-guest control"
4207            ),
4208            Err(error) => log::warn!("[s9vm] freedos-session FAIL: {:?}", error),
4209        }
4210    }
4211}