Skip to main content

strat9_kernel/s9vm/
vm.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 : registry of virtual worlds and guest memory.
24//!
25//! This layer keeps the world registry (opaque identifier, name, owning silo,
26//! state) and owns, for each world, its guest memory: pinned frames, GPA map
27//! (`GuestMap`) and second-level translation tables (`SecondLevelMemory`).
28//!
29//! Invariants:
30//! - a guest frame is **pinned** for as long as the world lives (never
31//!   swapped, never freed);
32//! - destruction order frees the translation tables first, then the guest
33//!   frames;
34//! - no frame allocation is done while holding the registry lock: memory is
35//!   taken out of the registry, manipulated, then put back in place.
36//!
37//! No policy is decided here: access checks are done by the syscall layer
38//! (capabilities).
39
40use alloc::{boxed::Box, collections::BTreeMap, sync::Arc, vec::Vec};
41use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
42
43use crate::{
44    hardware::iommu::{DmaProt, Domain as HardwareIommuDomain, FaultPolicy, MappingKind, Sbdf},
45    memory::frame::{FrameAllocOptions, FramePurpose, PhysFrame},
46    process::{kthread, scheduler::ticks, sleep_current_task_ticks, TaskId},
47    s9vm::{
48        apic::LocalApic,
49        backend::{HwVcpu, VcpuOps},
50        caps::HwCaps,
51        emulate::{interrupt_action, interrupt_deliverable, InterruptAction},
52        exit::ExitClass,
53        exitqueue::ExitQueue,
54        guest::{FixedBits, GuestState},
55        image::{Image, Segment},
56        iommu::{DeviceId, DomainId, IommuError, IommuModel},
57        machine::Machine,
58        memmap::{contiguous_2m_aligned, perms_from_abi, plan_map, GuestMap, MapError, MAX_GPA},
59        mmu::{Perms as MmuPerms, PAGE_SIZE},
60        timing::{ExitLatencyHistogram, WorldTiming, EXIT_LATENCY_BUCKETS},
61        vcpu::{ExitInfo, SecondLevelMemory, VcpuError},
62        virtio_blk::VirtioBlk,
63    },
64    sync::{SpinLock, WaitQueue},
65};
66use strat9_abi::vmm::{
67    exit_kind, VmmExitEvent, VmmRegs, VMM_DISK_DEFAULT_BYTES, VMM_DISK_MAX_BYTES,
68    VMM_DISK_SECTOR_SIZE, VMM_IOMMU_MAX_MAP_BYTES,
69};
70
71/// Maximum number of simultaneous worlds (safety bound).
72pub const MAX_WORLDS: usize = 64;
73/// Maximum length of a name.
74pub const NAME_MAX: usize = 32;
75/// Maximum number of vCPUs per world (safety bound, before quotas).
76pub const MAX_VCPUS_PER_WORLD: usize = 32;
77/// Maximum number of guest modules/initrd ranges per world.
78pub const MAX_MODULES_PER_WORLD: usize = 4;
79/// Maximum size of one guest module copied through `SYS_VMM_LOAD_MODULE`.
80pub const MAX_MODULE_BYTES: usize = 64 * 1024 * 1024;
81/// Maximum length of the guest command line stored by `SYS_VMM_SET_CMDLINE`.
82pub const CMDLINE_MAX: usize = 256;
83/// Maximum bytes covered by one `SYS_VMM_MAP_IOMMU` request (1 GiB).
84pub const IOMMU_MAX_MAP_BYTES: u64 = VMM_IOMMU_MAX_MAP_BYTES;
85/// Granularity of one IOMMU leaf installed by `SYS_VMM_MAP_IOMMU`.
86const IOMMU_PAGE_SIZE: u64 = PAGE_SIZE;
87/// Size of a large IOMMU leaf (2 MiB) installed when `REQUIRE_2M` is set.
88const IOMMU_LARGE_PAGE_SIZE: u64 = 2 * 1024 * 1024;
89/// Default guest page quota (1 GiB).
90pub const DEFAULT_QUOTA_PAGES: u64 = 262_144;
91/// `RFLAGS.IF`: the guest is interruptible.
92const RFLAGS_IF: u64 = 1 << 9;
93/// Maximum bytes queued for the guest console at once.
94pub const MAX_CONSOLE_PENDING: usize = 64 * 1024;
95/// Maximum bytes of console output kept for the user side.
96pub const MAX_CONSOLE_OUTPUT: usize = 64 * 1024;
97/// Maximum frames queued for the guest network device.
98pub const MAX_PENDING_FRAMES: usize = 64;
99/// Maximum size of one injected network frame.
100pub const MAX_FRAME_SIZE: usize = 64 * 1024;
101/// Maximum number of guest-transmitted frames buffered for the network
102/// front-end.
103pub const MAX_NETWORK_OUTPUT_FRAMES: usize = 64;
104/// Maximum number of guest-transmitted octets buffered for the network
105/// front-end.
106pub const MAX_NETWORK_OUTPUT_BYTES: usize = 256 * 1024;
107
108/// Public record of a world.
109#[derive(Debug, Clone, Copy)]
110pub struct WorldRecord {
111    /// Opaque identifier (never 0).
112    pub id: u64,
113    /// Name (truncated UTF-8, zero-padded).
114    pub name: [u8; NAME_MAX],
115    /// Usable length of the name.
116    pub name_len: u8,
117    /// Owning silo (0 = kernel world).
118    pub silo_id: u32,
119    /// State (`strat9_abi::vmm::state` constants).
120    pub state: u32,
121    /// Number of registered vCPUs.
122    pub vcpu_count: u32,
123    /// Mapped guest pages.
124    pub mapped_pages: u64,
125}
126
127impl WorldRecord {
128    fn new(id: u64, name: &[u8], silo_id: u32) -> Self {
129        let mut stored = [0u8; NAME_MAX];
130        let length = name.len().min(NAME_MAX);
131        stored[..length].copy_from_slice(&name[..length]);
132        Self {
133            id,
134            name: stored,
135            name_len: length as u8,
136            silo_id,
137            state: strat9_abi::vmm::state::CREATED,
138            vcpu_count: 0,
139            mapped_pages: 0,
140        }
141    }
142
143    /// Name as a slice of usable bytes.
144    pub fn name_slice(&self) -> &[u8] {
145        &self.name[..self.name_len as usize]
146    }
147}
148
149/// Cumulative execution counters of a world.
150///
151/// They are diagnostics only: nothing in the engine depends on them. They are
152/// updated by the execution loop and exposed read-only through `/dev/vmm`.
153#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
154pub struct WorldStats {
155    /// `RUN` calls that reached the hardware.
156    pub runs: u64,
157    /// Exits handed to policy through the event queue.
158    pub policy_exits: u64,
159    /// Exits replayed in the kernel by the device model.
160    pub emulated_exits: u64,
161    /// Replayed I/O instructions (PIC ports, POST port).
162    pub emulated_io: u64,
163    /// Replayed MMIO accesses (APIC and I/O APIC pages).
164    pub emulated_mmio: u64,
165    /// Replayed MSR accesses (x2APIC window).
166    pub emulated_msr: u64,
167    /// Interrupts injected into the guest.
168    pub injected_interrupts: u64,
169    /// Times interrupt-window exiting was armed.
170    pub windows_armed: u64,
171    /// Guest time slices that expired (preemption timer).
172    pub timer_exits: u64,
173}
174
175impl WorldStats {
176    /// Adds another set of counters to this one.
177    pub fn add(&mut self, other: &Self) {
178        self.runs += other.runs;
179        self.policy_exits += other.policy_exits;
180        self.emulated_exits += other.emulated_exits;
181        self.emulated_io += other.emulated_io;
182        self.emulated_mmio += other.emulated_mmio;
183        self.emulated_msr += other.emulated_msr;
184        self.injected_interrupts += other.injected_interrupts;
185        self.windows_armed += other.windows_armed;
186        self.timer_exits += other.timer_exits;
187    }
188}
189
190/// Number of exit classes tracked by [`WorldTimingSnapshot`].
191pub const TIMING_CLASS_COUNT: usize = WorldTiming::class_count();
192
193/// Compact, `Copy` view of a world's cumulative timing aggregates.
194///
195/// Produced by the read-only `timing()` accessor. Latencies are expressed in
196/// time-stamp counter cycles, as measured on the CPU that ran the vCPU; no
197/// conversion to nanoseconds is done here, because the time-stamp counter
198/// frequency is a property of the host and must be supplied by the reader.
199///
200/// Semantics:
201/// - the histogram is **cumulative** for the lifetime of the world;
202/// - `window` and `peak_window` are the counts of the current and peak
203///   sliding windows of the global exit-rate meter, one slot per `run_vcpu`
204///   invocation (one time slice);
205/// - percentiles are conservative upper bounds of logarithmic buckets, never
206///   lower than the exact percentile (see the `timing` module).
207#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
208pub struct WorldTimingSnapshot {
209    /// Number of exits recorded since the world was created.
210    pub exits: u64,
211    /// Mean latency of every recorded exit, in cycles (0 when `exits == 0`).
212    pub mean_cycles: u64,
213    /// 95th percentile upper bound of every recorded exit, in cycles.
214    pub p95_cycles: u64,
215    /// Smallest recorded exit latency, in cycles (0 when `exits == 0`).
216    pub min_cycles: u64,
217    /// Largest recorded exit latency, in cycles (0 when `exits == 0`).
218    pub max_cycles: u64,
219    /// Number of in-kernel device-model replays measured.
220    pub handler_samples: u64,
221    /// Mean device-model replay latency, in cycles (0 when no sample).
222    pub handler_mean_cycles: u64,
223    /// 95th percentile upper bound of the device-model replay latency.
224    pub handler_p95_cycles: u64,
225    /// Cumulative number of exits per class, indexed by
226    /// [`WorldTiming::class_index`] (always `TIMING_CLASS_COUNT` entries).
227    pub per_class: [u64; TIMING_CLASS_COUNT],
228    /// Exits recorded in the current sliding window (all classes).
229    pub window: u64,
230    /// Highest sliding-window value observed (all classes).
231    pub peak_window: u64,
232}
233
234/// Guest memory layer errors.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub enum VmError {
237    /// Unknown world.
238    Unknown,
239    /// Invalid reservation (alignment, overlap, quota).
240    Map(MapError),
241    /// No more frames available.
242    OutOfMemory,
243    /// Second-level translation error.
244    Translation(VcpuError),
245}
246
247impl From<MapError> for VmError {
248    fn from(value: MapError) -> Self {
249        Self::Map(value)
250    }
251}
252
253impl From<VcpuError> for VmError {
254    fn from(value: VcpuError) -> Self {
255        Self::Translation(value)
256    }
257}
258
259/// Allocates a guest RAM frame (zeroed, non-movable, pinned).
260fn alloc_guest_frame() -> Option<PhysFrame> {
261    crate::sync::with_irqs_disabled(|token| {
262        FrameAllocOptions::new()
263            .purpose(FramePurpose::KernelData)
264            .allocate(token)
265            .ok()
266    })
267}
268
269/// Frees a list of guest frames.
270fn free_guest_frames(frames: Vec<PhysFrame>) {
271    if frames.is_empty() {
272        return;
273    }
274    crate::sync::with_irqs_disabled(|token| {
275        for frame in frames {
276            crate::memory::free_frame(token, frame);
277        }
278    });
279}
280
281/// Guest memory of a world.
282pub struct WorldMemory {
283    second_level: SecondLevelMemory,
284    map: GuestMap,
285    frames: Vec<PhysFrame>,
286}
287
288impl WorldMemory {
289    /// Creates empty guest memory.
290    pub fn new(quota_pages: u64) -> Result<Self, VmError> {
291        Ok(Self {
292            second_level: SecondLevelMemory::new()?,
293            map: GuestMap::new(quota_pages),
294            frames: Vec::new(),
295        })
296    }
297
298    /// Reserved pages.
299    pub fn pages(&self) -> u64 {
300        self.map.pages()
301    }
302
303    /// Maps a GPA range into guest RAM (frames allocated and pinned).
304    ///
305    /// `memtype` must be `0` (default write-back); the other types are not yet
306    /// supported and are rejected by the caller.
307    ///
308    /// # Granularity
309    ///
310    /// The range is split by [`memmap::plan_map`]: a 2 MiB-aligned middle is
311    /// mapped with 2 MiB second-level leaves when the 512 newly allocated
312    /// host frames are 2 MiB aligned and physically contiguous, while a
313    /// partial head or tail stays on 4 KiB pages. A 2 MiB segment whose frames
314    /// are not contiguous (fragmented allocator) falls back to 4 KiB pages for
315    /// that segment, so correctness never depends on host contiguity.
316    ///
317    /// Large leaves reduce second-level table memory and TLB pressure; the
318    /// fallback keeps the mapping usable when the allocator cannot provide a
319    /// contiguous block.
320    ///
321    /// On failure, every mapping and every frame allocated during the call is
322    /// undone: the world's memory stays consistent. Quota accounting is
323    /// unchanged: a 2 MiB leaf still counts as 512 pages.
324    pub fn map(
325        &mut self,
326        _caps: &HwCaps,
327        gpa: u64,
328        len: u64,
329        perms_bits: u32,
330        memtype: u8,
331    ) -> Result<u64, VmError> {
332        // 1. Plan the granularity, then validate and reserve the quota before
333        //    allocating anything.
334        let plan = plan_map(gpa, len)?;
335        self.map.reserve(gpa, len, perms_bits, memtype)?;
336        let decoded = perms_from_abi(perms_bits);
337        let perms = MmuPerms {
338            read: decoded.read,
339            write: decoded.write,
340            execute: decoded.execute,
341        };
342        let pages = len / PAGE_SIZE;
343        let mut allocated: Vec<PhysFrame> = Vec::with_capacity(pages as usize);
344        // Installed mappings, in order: (gpa, len, is_2m_leaf).
345        let mut installed: Vec<(u64, u64, bool)> = Vec::new();
346
347        for segment in &plan {
348            let frame_count = (segment.len / PAGE_SIZE) as usize;
349            let first_frame = allocated.len();
350            for _ in 0..frame_count {
351                let Some(frame) = alloc_guest_frame() else {
352                    self.rollback_mapping(&installed, allocated);
353                    self.map.remove(gpa);
354                    return Err(VmError::OutOfMemory);
355                };
356                allocated.push(frame);
357            }
358
359            if segment.is_large() {
360                let hp_as: Vec<u64> = allocated[first_frame..]
361                    .iter()
362                    .map(|frame| frame.start_address.as_u64())
363                    .collect();
364                let base = hp_as.iter().copied().min().unwrap_or(0);
365                if contiguous_2m_aligned(base, &hp_as) {
366                    match self.second_level.map_2m(segment.gpa, base, perms) {
367                        Ok(()) => {
368                            installed.push((segment.gpa, segment.len, true));
369                            continue;
370                        }
371                        Err(error) => {
372                            self.rollback_mapping(&installed, allocated);
373                            self.map.remove(gpa);
374                            return Err(VmError::Translation(error));
375                        }
376                    }
377                }
378                // Fragmented or unaligned host frames: fall through to 4 KiB
379                // pages for this 2 MiB segment.
380            }
381
382            for index in 0..frame_count {
383                let hpa = allocated[first_frame + index].start_address.as_u64();
384                let page_gpa = segment.gpa + index as u64 * PAGE_SIZE;
385                match self.second_level.map_4k(page_gpa, hpa, perms) {
386                    Ok(()) => installed.push((page_gpa, PAGE_SIZE, false)),
387                    Err(error) => {
388                        self.rollback_mapping(&installed, allocated);
389                        self.map.remove(gpa);
390                        return Err(VmError::Translation(error));
391                    }
392                }
393            }
394        }
395
396        self.frames.extend(allocated);
397        Ok(pages)
398    }
399
400    /// Maps a GPA range as an **alias** of already-mapped guest memory.
401    ///
402    /// The source pages are translated through the second-level tables and the
403    /// destination GPA is mapped to the same host frames; no frame is
404    /// allocated or freed. This is how the PC maps the BIOS ROM at both
405    /// `0xC0000` and the top-of-4GiB alias (`0xFFFC0000`) that the reset
406    /// vector and SeaBIOS' high code use.
407    pub fn alias(
408        &mut self,
409        gpa: u64,
410        source_gpa: u64,
411        len: u64,
412        perms_bits: u32,
413    ) -> Result<u64, VmError> {
414        if len == 0 || gpa % PAGE_SIZE != 0 || source_gpa % PAGE_SIZE != 0 || len % PAGE_SIZE != 0 {
415            return Err(VmError::Map(crate::s9vm::memmap::MapError::InvalidRange));
416        }
417        self.map.reserve(gpa, len, perms_bits, 0)?;
418        let decoded = perms_from_abi(perms_bits);
419        let perms = MmuPerms {
420            read: decoded.read,
421            write: decoded.write,
422            execute: decoded.execute,
423        };
424        let pages = len / PAGE_SIZE;
425        let mut installed: Vec<u64> = Vec::with_capacity(pages as usize);
426        for index in 0..pages {
427            let source = source_gpa + index * PAGE_SIZE;
428            let Some(hpa) = self.second_level.translate(source) else {
429                self.rollback_alias(&installed, gpa);
430                return Err(VmError::Map(crate::s9vm::memmap::MapError::InvalidRange));
431            };
432            let target = gpa + index * PAGE_SIZE;
433            if let Err(error) = self.second_level.map_4k(target, hpa, perms) {
434                self.rollback_alias(&installed, gpa);
435                return Err(VmError::Translation(error));
436            }
437            installed.push(target);
438        }
439        Ok(pages)
440    }
441
442    /// Undoes an alias mapping without touching the source frames.
443    fn rollback_alias(&mut self, installed: &[u64], gpa: u64) {
444        for target in installed.iter().rev() {
445            let _ = self.second_level.unmap_4k(*target);
446        }
447        self.map.remove(gpa);
448    }
449
450    /// Undoes installed mappings and frees every frame of a failed `map`.
451    ///
452    /// Mappings are torn down in reverse installation order; 2 MiB leaves use
453    /// `unmap_2m`, 4 KiB pages use `unmap_4k`. The frame list is then returned
454    /// to the allocator exactly once (it is moved in, so no double free is
455    /// possible).
456    fn rollback_mapping(&mut self, installed: &[(u64, u64, bool)], frames: Vec<PhysFrame>) {
457        for &(segment_gpa, segment_len, is_large) in installed.iter().rev() {
458            if is_large {
459                let _ = self
460                    .second_level
461                    .root
462                    .unmap_2m(&mut self.second_level.tables, segment_gpa);
463            } else {
464                let page_count = segment_len / PAGE_SIZE;
465                for index in 0..page_count {
466                    let _ = self.second_level.unmap_4k(segment_gpa + index * PAGE_SIZE);
467                }
468            }
469        }
470        free_guest_frames(frames);
471    }
472
473    /// Translates a GPA (diagnostic).
474    pub fn translate(&self, gpa: u64) -> Option<u64> {
475        self.second_level.translate(gpa)
476    }
477
478    /// Reserved guest-physical ranges, in address order.
479    pub fn regions(&self) -> impl Iterator<Item = &crate::s9vm::memmap::Region> {
480        self.map.regions()
481    }
482
483    /// Value of the translation pointer (EPTP) for the control block.
484    pub fn second_level_pointer(&self, caps: &HwCaps) -> u64 {
485        self.second_level.pointer(caps)
486    }
487
488    /// Frees the translation tables, then the guest frames.
489    pub fn destroy(mut self) {
490        let frames = core::mem::take(&mut self.frames);
491        self.map.clear();
492        self.second_level.destroy();
493        free_guest_frames(frames);
494    }
495}
496
497/// Registered world: public record + lazy guest memory +
498/// logical vCPUs.
499struct World {
500    record: WorldRecord,
501    memory: Option<WorldMemory>,
502    vcpus: Vec<VcpuSlot>,
503    exits: ExitQueue,
504    /// Destruction in progress: any new operation is refused and the vCPU
505    /// tasks are stopped before the memory is freed.
506    closing: bool,
507    /// Paused world: `RUN`s are refused (`Paused`) until resumed.
508    paused: bool,
509    /// Guest chipset devices (8259A pair, I/O APIC) and the kernel bridge
510    /// that replays their accesses without leaving the kernel.
511    machine: Machine,
512    /// Cumulative execution counters (diagnostics).
513    stats: WorldStats,
514    /// Cumulative exit-latency aggregates, per exit class (diagnostics).
515    ///
516    /// Taken out of the registry while a vCPU of the world runs, with the same
517    /// take/put pattern as `stats`, so that the running guest never takes the
518    /// registry lock and the exit path never allocates.
519    timing: WorldTiming,
520    /// Cumulative latency of the in-kernel device-model replay (fast-path
521    /// exits), in time-stamp counter cycles. Same lifetime and take/put rules
522    /// as `timing`.
523    handler_timing: ExitLatencyHistogram,
524    /// Console input queued by the user side, delivered at the next `RUN`.
525    pending_console_input: Vec<u8>,
526    /// Console output produced by the guest, drained by the user side.
527    console_output: Vec<u8>,
528    /// Frames queued for the guest network device, delivered at the next
529    /// `RUN`.
530    pending_frames: Vec<Vec<u8>>,
531    /// Frames transmitted by the guest, waiting for the network front-end.
532    network_output: Vec<Vec<u8>>,
533    /// Octets currently queued in `network_output` (bounded).
534    network_output_bytes: usize,
535    /// Guest modules/initrd ranges (bounded, insertion order).
536    modules: Vec<GuestModule>,
537    /// Guest command line (NUL padded; `cmdline_len` is authoritative).
538    cmdline: [u8; CMDLINE_MAX],
539    /// Number of valid bytes in `cmdline`.
540    cmdline_len: usize,
541    /// Device translation model of this world (IOMMU).
542    ///
543    /// The model is pure and owns no frame: it maps device-visible addresses
544    /// to host frames already owned by `memory`. It is empty until the first
545    /// `SYS_VMM_MAP_IOMMU` call, which lazily allocates the domain.
546    iommu: IommuModel,
547    /// Address space allocated in `iommu`, if any.
548    iommu_domain: Option<DomainId>,
549}
550
551/// One guest module/initrd range recorded for the boot-parameter block.
552#[derive(Debug, Clone, Copy, PartialEq, Eq)]
553pub struct GuestModule {
554    /// Guest-physical base address.
555    pub base: u64,
556    /// Length in bytes.
557    pub len: u64,
558}
559
560/// Logical vCPU: opaque identifier, APIC id and ABI register block.
561///
562/// The hardware context (control block, host stack, guest state) is created at
563/// execution time, not at logical creation time: a world can be configured
564/// (memory, vCPUs, registers) before the hardware is activated.
565///
566/// ADR-4 model: each vCPU is driven by a dedicated **kernel task**
567/// ([`VcpuSlot::task`]). The task waits for a `RUN` request, runs the guest
568/// until the next policy exit, queues the event, then waits again. The kernel
569/// thus guarantees that a guest never runs on the syscall caller's stack.
570pub struct VcpuSlot {
571    /// Opaque identifier of the vCPU.
572    pub id: u64,
573    /// Guest APIC identifier.
574    pub apic_id: u32,
575    /// ABI register block.
576    pub regs: VmmRegs,
577    /// Hardware context (created on the first `RUN`).
578    hardware: Option<HwVcpu>,
579    /// Guest local APIC (architectural state, MMIO page and x2APIC MSR).
580    apic: LocalApic,
581    /// NMI pending injection at the next `RUN`.
582    pending_nmi: bool,
583    /// Kernel task driving this vCPU (created with the vCPU).
584    task: Option<TaskId>,
585    /// A `RUN` has been requested and has not been taken into account yet.
586    run_requested: bool,
587    /// A `RUN` is in flight: a single caller at a time.
588    run_in_flight: bool,
589    /// The last requested `RUN` is finished.
590    run_done: bool,
591    /// The vCPU task is currently inside `execute_one_run` (guest mode).
592    in_guest: bool,
593    /// Number of `RUN`s executed by this vCPU task.
594    runs: u64,
595    /// Result of the last `RUN` (valid when `run_done`).
596    run_result: Option<Result<(), RunError>>,
597    /// Shutdown requested (vCPU or world destruction).
598    shutdown: bool,
599    /// The kernel task has finished and its hardware resources are unloaded.
600    exited: bool,
601    /// Wake-up of the vCPU task on a `RUN` request (or shutdown).
602    run_wait: Arc<WaitQueue>,
603    /// Wake-up of callers blocked on the end of a `RUN` or on a shutdown.
604    done_wait: Arc<WaitQueue>,
605}
606
607/// Global world registry.
608/// Registry type: worlds are **boxed** so that creating or destroying one does
609/// not move the (large) World value through the kernel stack. The early
610/// bootstrap runs on an 8 KiB stack; a stack-sized move there is a page fault.
611type WorldMap = BTreeMap<u64, Box<World>>;
612
613static WORLDS: SpinLock<WorldMap> = SpinLock::new(BTreeMap::new());
614/// Next identifier (1 = first world; 0 is reserved for the global summary).
615static NEXT_ID: AtomicU64 = AtomicU64::new(1);
616
617/// Creates a world. Returns `None` if the registry is full or if the name is
618/// empty.
619pub fn create(name: &[u8], silo_id: u32) -> Option<WorldRecord> {
620    if name.is_empty() || name.len() > NAME_MAX {
621        return None;
622    }
623    let mut worlds = WORLDS.lock();
624    if worlds.len() >= MAX_WORLDS {
625        return None;
626    }
627    let mut id = NEXT_ID.fetch_add(1, Ordering::AcqRel);
628    while id == 0 || worlds.contains_key(&id) {
629        id = NEXT_ID.fetch_add(1, Ordering::AcqRel);
630    }
631    let record = WorldRecord::new(id, name, silo_id);
632    worlds.insert(
633        id,
634        Box::new(World {
635            record,
636            memory: None,
637            vcpus: Vec::new(),
638            exits: ExitQueue::default(),
639            closing: false,
640            paused: false,
641            machine: Machine::new(),
642            stats: WorldStats::default(),
643            timing: WorldTiming::default(),
644            handler_timing: ExitLatencyHistogram::default(),
645            pending_console_input: Vec::new(),
646            console_output: Vec::new(),
647            pending_frames: Vec::new(),
648            network_output: Vec::new(),
649            network_output_bytes: 0,
650            modules: Vec::new(),
651            cmdline: [0u8; CMDLINE_MAX],
652            cmdline_len: 0,
653            iommu: IommuModel::new(),
654            iommu_domain: None,
655        }),
656    );
657    Some(record)
658}
659
660/// Destroys a world and frees its guest memory.
661///
662/// The vCPU tasks are stopped and joined **before** the memory is freed: a
663/// task still in flight could otherwise dereference the world's second-level
664/// tables. A second concurrent call during the close returns `None`.
665///
666/// The timing aggregates (`timing`, `handler_timing`) are plain values owned by
667/// the world: they are dropped with it, so no separate reset is needed and no
668/// snapshot can outlive the world (the snapshot is `Copy`).
669pub fn destroy(id: u64) -> Option<WorldRecord> {
670    destroy_inner(id, None)
671}
672
673/// Destroys a world, waiting at most `timeout_ns` for its vCPU tasks.
674///
675/// Returns `None` when the world does not exist, is already closing, or when a
676/// vCPU task did not finish within the budget. In the timeout case the world
677/// stays in the registry with `closing` set, so its memory is not freed while a
678/// task could still reference it; the caller should treat that as a defect and
679/// report it.
680pub fn destroy_timeout(id: u64, timeout_ns: u64) -> Option<WorldRecord> {
681    destroy_inner(id, Some(timeout_ns))
682}
683
684fn destroy_inner(id: u64, timeout_ns: Option<u64>) -> Option<WorldRecord> {
685    // 1. Marks the world closed and wakes all vCPU tasks.
686    let mut to_join: Vec<u64> = Vec::new();
687    let mut wakers: Vec<Arc<WaitQueue>> = Vec::new();
688    {
689        let mut worlds = WORLDS.lock();
690        let world = worlds.get_mut(&id)?;
691        if world.closing {
692            return None;
693        }
694        world.closing = true;
695        for slot in world.vcpus.iter_mut() {
696            slot.shutdown = true;
697            wakers.push(Arc::clone(&slot.run_wait));
698            wakers.push(Arc::clone(&slot.done_wait));
699            if slot.task.is_some() {
700                to_join.push(slot.id);
701            }
702        }
703    }
704    for waiter in wakers {
705        waiter.wake_all();
706    }
707    // 2. Waits for the vCPU tasks to exit, without holding the lock.
708    for vcpu in to_join {
709        let exited = match timeout_ns {
710            Some(timeout_ns) => wait_vcpu_exited_timeout(vcpu, timeout_ns),
711            None => {
712                wait_vcpu_exited(vcpu);
713                true
714            }
715        };
716        if !exited {
717            log::warn!(
718                "[s9vm] destroy: vCPU task {} did not exit within {} ns; world {} kept closing",
719                vcpu,
720                timeout_ns.unwrap_or(0),
721                id
722            );
723            return None;
724        }
725    }
726    // 3. Removes the world and frees the guest memory.
727    let mut world = {
728        let mut worlds = WORLDS.lock();
729        worlds.remove(&id)?
730    };
731    // The IOMMU model owns no frame, but its domains and device bindings must
732    // not outlive the world: drop them explicitly before the guest frames.
733    // The host VT-d mirror domains are released first (outside the registry
734    // lock), which clears their hardware shadow mappings.
735    release_host_iommu_domains(id);
736    world.iommu.destroy();
737    world.iommu_domain = None;
738    if let Some(memory) = world.memory.take() {
739        memory.destroy();
740    }
741    Some(world.record)
742}
743
744/// Finds a world and the index of a vCPU in that world.
745fn locate_slot(worlds: &mut WorldMap, vcpu_id: u64) -> Option<(&mut World, usize)> {
746    for world in worlds.values_mut() {
747        if let Some(index) = world.vcpus.iter().position(|slot| slot.id == vcpu_id) {
748            return Some((world, index));
749        }
750    }
751    None
752}
753
754/// Waits at most `timeout_ns` for a vCPU's kernel task to finish.
755///
756/// Returns `false` on timeout. The world stays in the registry in that case;
757/// `destroy_inner` reports the defect instead of freeing memory a task could
758/// still reference.
759fn wait_vcpu_exited_timeout(vcpu_id: u64, timeout_ns: u64) -> bool {
760    let budget_ticks = (timeout_ns / crate::arch::timer::NS_PER_TICK).max(1);
761    let deadline = ticks().saturating_add(budget_ticks);
762    loop {
763        {
764            let mut worlds = WORLDS.lock();
765            let Some((world, index)) = locate_slot(&mut worlds, vcpu_id) else {
766                return true;
767            };
768            let slot = &world.vcpus[index];
769            if slot.exited || slot.task.is_none() {
770                return true;
771            }
772        }
773        if ticks() >= deadline {
774            return false;
775        }
776        sleep_current_task_ticks(1);
777    }
778}
779
780/// Waits for a vCPU's kernel task to finish (or for the vCPU to disappear from
781/// the registry).
782fn wait_vcpu_exited(vcpu_id: u64) {
783    loop {
784        let waiters = {
785            let mut worlds = WORLDS.lock();
786            let Some((world, index)) = locate_slot(&mut worlds, vcpu_id) else {
787                return;
788            };
789            let slot = &world.vcpus[index];
790            if slot.exited || slot.task.is_none() {
791                return;
792            }
793            Arc::clone(&slot.done_wait)
794        };
795        waiters.wait_until(|| {
796            let mut worlds = WORLDS.lock();
797            match locate_slot(&mut worlds, vcpu_id) {
798                Some((world, index)) if !world.vcpus[index].exited => None,
799                _ => Some(()),
800            }
801        });
802    }
803}
804
805/// Removes a vCPU from the registry without waiting for a task.
806fn remove_vcpu(vcpu_id: u64) -> bool {
807    let mut worlds = WORLDS.lock();
808    for world in worlds.values_mut() {
809        if let Some(index) = world.vcpus.iter().position(|slot| slot.id == vcpu_id) {
810            world.vcpus.remove(index);
811            world.record.vcpu_count = world.vcpus.len() as u32;
812            return true;
813        }
814    }
815    false
816}
817
818/// Creates the registry entry of a vCPU.
819fn new_vcpu_slot(id: u64, apic_id: u32) -> VcpuSlot {
820    let regs = strat9_abi::vmm::VmmRegs {
821        abi_version: strat9_abi::vmm::VMM_ABI_VERSION,
822        ..Default::default()
823    };
824    VcpuSlot {
825        id,
826        apic_id,
827        regs,
828        hardware: None,
829        apic: LocalApic::new(apic_id),
830        pending_nmi: false,
831        task: None,
832        run_requested: false,
833        run_in_flight: false,
834        run_done: false,
835        in_guest: false,
836        runs: 0,
837        run_result: None,
838        shutdown: false,
839        exited: false,
840        run_wait: Arc::new(WaitQueue::new()),
841        done_wait: Arc::new(WaitQueue::new()),
842    }
843}
844
845/// Returns a record.
846pub fn get(id: u64) -> Option<WorldRecord> {
847    WORLDS.lock().get(&id).map(|world| world.record)
848}
849
850/// Lists the worlds (identifier order).
851pub fn list() -> Vec<WorldRecord> {
852    WORLDS.lock().values().map(|world| world.record).collect()
853}
854
855/// Logs an engine snapshot (kernel diagnostic).
856pub fn debug_dump() {
857    let worlds = list();
858    log::info!(
859        "[s9vm] debug: {} world(s), {} active CPU(s)",
860        worlds.len(),
861        crate::s9vm::active_cpu_count()
862    );
863    for world in worlds {
864        let name = core::str::from_utf8(world.name_slice()).unwrap_or("<non-utf8>");
865        log::info!(
866            "[s9vm] debug: world {} name={} silo={} state={} vcpus={} pages={}",
867            world.id,
868            name,
869            world.silo_id,
870            world.state,
871            world.vcpu_count,
872            world.mapped_pages
873        );
874        let worlds = WORLDS.lock();
875        if let Some(entry) = worlds.get(&world.id) {
876            log::info!(
877                "[s9vm] debug:   irqchip pic(imr={:#x}, irr={:#x}, isr={:#x}) ioapic(id={})",
878                entry.machine.devices().pic.master().mask(),
879                entry.machine.devices().pic.master().irr(),
880                entry.machine.devices().pic.master().isr(),
881                entry.machine.devices().ioapic.apic_id()
882            );
883            for slot in &entry.vcpus {
884                log::info!(
885                    "[s9vm] debug:   vcpu {} apic={} tpr={} irr={} isr={} irq={:?} nmi={} task={:?}",
886                    slot.id,
887                    slot.apic.apic_id(),
888                    slot.apic.tpr(),
889                    slot.apic.has_pending(),
890                    slot.apic.in_service(),
891                    slot.apic.pending_vector(),
892                    slot.pending_nmi,
893                    slot.task
894                );
895            }
896        }
897    }
898}
899
900/// Number of worlds.
901pub fn count() -> usize {
902    WORLDS.lock().len()
903}
904
905/// Updates a world's state. Returns `false` if the world is unknown.
906pub fn set_state(id: u64, state: u32) -> bool {
907    let mut worlds = WORLDS.lock();
908    match worlds.get_mut(&id) {
909        Some(world) => {
910            world.record.state = state;
911            true
912        }
913        None => false,
914    }
915}
916
917/// Updates a world's vCPU count.
918pub fn set_vcpu_count(id: u64, count: u32) -> bool {
919    let mut worlds = WORLDS.lock();
920    match worlds.get_mut(&id) {
921        Some(world) => {
922            world.record.vcpu_count = count;
923            true
924        }
925        None => false,
926    }
927}
928
929/// Maps guest memory into a world.
930///
931/// The memory is taken out of the registry during allocation (never allocate
932/// frames under the lock), then put back in place. If the world was destroyed
933/// in the meantime, the memory is freed immediately.
934pub fn map_memory(
935    id: u64,
936    caps: &HwCaps,
937    gpa: u64,
938    len: u64,
939    perms_bits: u32,
940    memtype: u8,
941) -> Result<u64, VmError> {
942    // The registry is locked for as short a time as possible: the existing
943    // memory is retrieved (or its absence noted), then the lock is released
944    // before any frame allocation.
945    enum Slot {
946        Existing(WorldMemory),
947        Empty,
948    }
949    let slot = {
950        let mut worlds = WORLDS.lock();
951        let world = worlds.get_mut(&id).ok_or(VmError::Unknown)?;
952        match world.memory.take() {
953            Some(memory) => Slot::Existing(memory),
954            None => Slot::Empty,
955        }
956    };
957    let mut memory = match slot {
958        Slot::Existing(memory) => memory,
959        Slot::Empty => WorldMemory::new(DEFAULT_QUOTA_PAGES)?,
960    };
961    let result = memory.map(caps, gpa, len, perms_bits, memtype);
962    let mut worlds = WORLDS.lock();
963    match worlds.get_mut(&id) {
964        Some(world) => {
965            if result.is_ok() {
966                world.record.mapped_pages = memory.pages();
967            }
968            world.memory = Some(memory);
969            result
970        }
971        None => {
972            drop(worlds);
973            memory.destroy();
974            Err(VmError::Unknown)
975        }
976    }
977}
978
979/// Maps a GPA range as an alias of an existing range in a world.
980///
981/// Frames are shared with the source range: no allocation and no extra free.
982pub fn alias_memory(
983    id: u64,
984    gpa: u64,
985    source_gpa: u64,
986    len: u64,
987    perms_bits: u32,
988) -> Result<u64, VmError> {
989    enum Slot {
990        Existing(WorldMemory),
991        Empty,
992    }
993    let slot = {
994        let mut worlds = WORLDS.lock();
995        let world = worlds.get_mut(&id).ok_or(VmError::Unknown)?;
996        match world.memory.take() {
997            Some(memory) => Slot::Existing(memory),
998            None => Slot::Empty,
999        }
1000    };
1001    let mut memory = match slot {
1002        Slot::Existing(memory) => memory,
1003        Slot::Empty => WorldMemory::new(DEFAULT_QUOTA_PAGES)?,
1004    };
1005    let result = memory.alias(gpa, source_gpa, len, perms_bits);
1006    let mut worlds = WORLDS.lock();
1007    match worlds.get_mut(&id) {
1008        Some(world) => {
1009            if result.is_ok() {
1010                world.record.mapped_pages = memory.pages();
1011            }
1012            world.memory = Some(memory);
1013            result
1014        }
1015        None => {
1016            drop(worlds);
1017            memory.destroy();
1018            Err(VmError::Unknown)
1019        }
1020    }
1021}
1022
1023/// A guest image loaded into a world's guest memory.
1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1025pub struct LoadedImage {
1026    /// Guest-physical entry point, relocated to the load base.
1027    pub entry: u64,
1028    /// Guest-physical base address where the image was loaded.
1029    pub image_base: u64,
1030    /// Lowest guest-physical address covered by the image (inclusive).
1031    pub span_min: u64,
1032    /// Highest guest-physical address covered by the image (exclusive).
1033    pub span_max: u64,
1034}
1035
1036impl LoadedImage {
1037    /// Number of guest pages in the image span, holes included.
1038    pub const fn span_pages(&self) -> u64 {
1039        (self.span_max - self.span_min) / PAGE_SIZE
1040    }
1041}
1042
1043/// Loads an ELF64 guest image into a world's guest memory.
1044///
1045/// The image is parsed and validated by [`Image::parse`]; every `PT_LOAD`
1046/// segment is then mapped through [`map_memory`] with its ELF permissions and
1047/// default write-back memory type. The file-backed prefix of each segment is
1048/// copied page by page into the pinned frames (GPA -> HPA -> HHDM) and the
1049/// remaining bytes (BSS) are zeroed. Nothing is executed: the policy layer
1050/// decides the initial registers.
1051///
1052/// `load_base_gpa` is the guest-physical address of the image base
1053/// ([`Image::base_vaddr`]) and must be 4 KiB aligned; the image virtual
1054/// addresses are relocated by the same delta. Loading is not atomic: if a
1055/// later segment cannot be mapped, the segments already mapped stay in place
1056/// and the world must be destroyed (the world memory layer has no unmap
1057/// primitive yet). A malformed image is rejected before any mapping.
1058pub fn load_image(
1059    world_id: u64,
1060    caps: &HwCaps,
1061    image_bytes: &[u8],
1062    load_base_gpa: u64,
1063) -> Result<LoadedImage, VmError> {
1064    let image = Image::parse(image_bytes).map_err(|error| {
1065        log::warn!("[s9vm] guest image rejected ({:?})", error);
1066        VmError::Map(MapError::InvalidRange)
1067    })?;
1068    if load_base_gpa % PAGE_SIZE != 0 {
1069        return Err(VmError::Map(MapError::InvalidRange));
1070    }
1071    let (span_min, span_max) = image
1072        .load_span(load_base_gpa)
1073        .filter(|(_, end)| *end <= MAX_GPA)
1074        .ok_or(VmError::Map(MapError::InvalidRange))?;
1075    let entry = image
1076        .entry_gpa(load_base_gpa)
1077        .ok_or(VmError::Map(MapError::InvalidRange))?;
1078    if !image.entry_is_mapped() {
1079        log::warn!(
1080            "[s9vm] guest image entry {:#x} is outside every loadable segment",
1081            image.entry()
1082        );
1083    }
1084
1085    // 1. Maps the page-aligned footprint of every segment. `map_memory` keeps
1086    //    the registry lock out of the frame allocation path.
1087    for segment in image.segments() {
1088        let gpa = image
1089            .segment_gpa(load_base_gpa, segment)
1090            .ok_or(VmError::Map(MapError::InvalidRange))?;
1091        map_memory(
1092            world_id,
1093            caps,
1094            gpa,
1095            segment.page_len(),
1096            segment.perms_bits(),
1097            0,
1098        )?;
1099    }
1100
1101    // 2. Fills the frames: file-backed bytes, then the zero-filled tail. No
1102    //    allocation happens here, so the registry lock can be held while the
1103    //    guest memory is populated.
1104    {
1105        let mut worlds = WORLDS.lock();
1106        let world = worlds.get_mut(&world_id).ok_or(VmError::Unknown)?;
1107        let memory = world
1108            .memory
1109            .as_ref()
1110            .ok_or(VmError::Map(MapError::NotMapped))?;
1111        for segment in image.segments() {
1112            copy_segment(memory, &image, segment, load_base_gpa)?;
1113        }
1114    }
1115
1116    log::info!(
1117        "[s9vm] image loaded at {:#x}: {} segment(s), {} page(s), entry {:#x}",
1118        load_base_gpa,
1119        image.segment_count(),
1120        image.total_pages(),
1121        entry
1122    );
1123    Ok(LoadedImage {
1124        entry,
1125        image_base: load_base_gpa,
1126        span_min,
1127        span_max,
1128    })
1129}
1130
1131/// Loads a guest module/initrd blob into a world's guest memory.
1132///
1133/// This is the initrd/module companion of [`load_image`]: the bytes are not
1134/// parsed, they are mapped read/write at `gpa` and copied verbatim. `gpa` must
1135/// be 4 KiB aligned, the blob must be non-empty and at most
1136/// [`MAX_MODULE_BYTES`], and at most [`MAX_MODULES_PER_WORLD`] ranges can be
1137/// recorded per world. The range is recorded for [`write_boot_params`].
1138///
1139/// Loading is not atomic: if the module table is full, or if the copy cannot
1140/// translate a page, the pages already mapped stay in place (the world memory
1141/// layer has no unmap primitive) and the caller should destroy the world.
1142pub fn load_module(world_id: u64, caps: &HwCaps, gpa: u64, bytes: &[u8]) -> Result<(), VmError> {
1143    if gpa % PAGE_SIZE != 0 || bytes.is_empty() || bytes.len() > MAX_MODULE_BYTES {
1144        return Err(VmError::Map(MapError::InvalidRange));
1145    }
1146    let len = bytes.len() as u64;
1147    if gpa.checked_add(len).is_none_or(|end| end > MAX_GPA) {
1148        return Err(VmError::Map(MapError::InvalidRange));
1149    }
1150    {
1151        let worlds = WORLDS.lock();
1152        let world = worlds.get(&world_id).ok_or(VmError::Unknown)?;
1153        if world.closing || world.modules.len() >= MAX_MODULES_PER_WORLD {
1154            return Err(VmError::Map(MapError::InvalidRange));
1155        }
1156    }
1157    let page_len = len.div_ceil(PAGE_SIZE) * PAGE_SIZE;
1158    map_memory(world_id, caps, gpa, page_len, 0b011, 0)?;
1159    let mut worlds = WORLDS.lock();
1160    let world = worlds.get_mut(&world_id).ok_or(VmError::Unknown)?;
1161    if world.closing || world.modules.len() >= MAX_MODULES_PER_WORLD {
1162        return Err(VmError::Map(MapError::InvalidRange));
1163    }
1164    let memory = world
1165        .memory
1166        .as_ref()
1167        .ok_or(VmError::Map(MapError::NotMapped))?;
1168    let mut offset = 0usize;
1169    while offset < bytes.len() {
1170        let page_offset = (offset as u64) & (PAGE_SIZE - 1);
1171        let chunk = core::cmp::min(bytes.len() - offset, (PAGE_SIZE - page_offset) as usize);
1172        let hpa = memory
1173            .translate(gpa + offset as u64)
1174            .ok_or(VmError::Map(MapError::NotMapped))?;
1175        // SAFETY: `hpa` belongs to a frame reserved for this world and is
1176        // mapped through the HHDM; `chunk` stays inside one page.
1177        unsafe {
1178            core::ptr::copy_nonoverlapping(
1179                bytes[offset..].as_ptr(),
1180                crate::memory::phys_to_virt(hpa) as *mut u8,
1181                chunk,
1182            );
1183        }
1184        offset += chunk;
1185    }
1186    world.modules.push(GuestModule { base: gpa, len });
1187    log::info!(
1188        "[s9vm] module loaded at {:#x}: {} byte(s), {}/{} module(s)",
1189        gpa,
1190        len,
1191        world.modules.len(),
1192        MAX_MODULES_PER_WORLD
1193    );
1194    Ok(())
1195}
1196
1197/// Stores the guest kernel command line for a world.
1198///
1199/// At most [`CMDLINE_MAX`] bytes are accepted. The buffer is NUL-padded and
1200/// **not** NUL-terminated: its stored length is authoritative and is returned.
1201pub fn set_cmdline(world_id: u64, bytes: &[u8]) -> Result<usize, VmError> {
1202    if bytes.len() > CMDLINE_MAX {
1203        return Err(VmError::Map(MapError::InvalidRange));
1204    }
1205    let mut worlds = WORLDS.lock();
1206    let world = worlds.get_mut(&world_id).ok_or(VmError::Unknown)?;
1207    if world.closing {
1208        return Err(VmError::Unknown);
1209    }
1210    world.cmdline = [0u8; CMDLINE_MAX];
1211    world.cmdline[..bytes.len()].copy_from_slice(bytes);
1212    world.cmdline_len = bytes.len();
1213    log::info!("[s9vm] command line stored: {} byte(s)", bytes.len());
1214    Ok(bytes.len())
1215}
1216
1217/// Modules recorded for a world, in insertion order.
1218pub fn modules(world_id: u64) -> Option<Vec<GuestModule>> {
1219    WORLDS
1220        .lock()
1221        .get(&world_id)
1222        .map(|world| world.modules.clone())
1223}
1224
1225/// Command line recorded for a world, with its authoritative length.
1226pub fn cmdline(world_id: u64) -> Option<Vec<u8>> {
1227    WORLDS
1228        .lock()
1229        .get(&world_id)
1230        .map(|world| world.cmdline[..world.cmdline_len].to_vec())
1231}
1232
1233/// Copies the file-backed bytes of one segment and zeroes its BSS.
1234fn copy_segment(
1235    memory: &WorldMemory,
1236    image: &Image<'_>,
1237    segment: &Segment,
1238    load_base_gpa: u64,
1239) -> Result<(), VmError> {
1240    let file_bytes = image
1241        .bytes_for_segment(segment)
1242        .ok_or(VmError::Map(MapError::NotMapped))?;
1243    let page_gpa = image
1244        .segment_gpa(load_base_gpa, segment)
1245        .ok_or(VmError::Map(MapError::InvalidRange))?;
1246    let page_start = segment.page_start();
1247    let file_end_vaddr = segment.vaddr + segment.filesz;
1248    let end_vaddr = segment.end_vaddr();
1249    for index in 0..segment.page_count() {
1250        let page_vaddr = page_start + index * PAGE_SIZE;
1251        let page_end_vaddr = page_vaddr + PAGE_SIZE;
1252        let hpa = memory
1253            .translate(page_gpa + index * PAGE_SIZE)
1254            .ok_or(VmError::Map(MapError::NotMapped))?;
1255        let page_virt = crate::memory::phys_to_virt(hpa) as *mut u8;
1256        // File-backed bytes of this page.
1257        let copy_start = core::cmp::max(page_vaddr, segment.vaddr);
1258        let copy_end = core::cmp::min(page_end_vaddr, file_end_vaddr);
1259        if copy_start < copy_end {
1260            let length = (copy_end - copy_start) as usize;
1261            let source_offset = (copy_start - segment.vaddr) as usize;
1262            let destination_offset = (copy_start - page_vaddr) as usize;
1263            // SAFETY: the page is owned by this world and mapped by the HHDM;
1264            // `length` bytes stay inside one page, and `source_offset` stays
1265            // inside the file-backed slice of the segment.
1266            unsafe {
1267                core::ptr::copy_nonoverlapping(
1268                    file_bytes.as_ptr().add(source_offset),
1269                    page_virt.add(destination_offset),
1270                    length,
1271                );
1272            }
1273        }
1274        // Zero-filled tail (BSS) of this page.
1275        let zero_start = core::cmp::max(page_vaddr, file_end_vaddr);
1276        let zero_end = core::cmp::min(page_end_vaddr, end_vaddr);
1277        if zero_start < zero_end {
1278            let length = (zero_end - zero_start) as usize;
1279            let destination_offset = (zero_start - page_vaddr) as usize;
1280            // SAFETY: same page as above; the zeroed range stays inside it.
1281            unsafe {
1282                core::ptr::write_bytes(page_virt.add(destination_offset), 0, length);
1283            }
1284        }
1285    }
1286    Ok(())
1287}
1288
1289/// vCPU layer errors.
1290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1291pub enum VcpuRegistryError {
1292    /// Unknown world.
1293    WorldUnknown,
1294    /// Unknown vCPU.
1295    Unknown,
1296    /// vCPU limit reached for this world.
1297    Limit,
1298    /// Incompatible ABI version.
1299    BadAbiVersion,
1300    /// The vCPU's kernel task could not be created.
1301    Thread,
1302}
1303
1304/// vCPU execution errors.
1305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1306pub enum RunError {
1307    /// Unknown vCPU.
1308    UnknownVcpu,
1309    /// The world has no mapped guest memory.
1310    NoMemory,
1311    /// The supplied guest state is invalid (see `guest::GuestError`).
1312    InvalidGuestState,
1313    /// Hardware is not activated on this CPU.
1314    HardwareNotReady,
1315    /// Hardware error during execution.
1316    Hardware(VcpuError),
1317    /// The limit of consecutive summarized exits is reached (pathological
1318    /// loop).
1319    ExitStorm,
1320    /// A `RUN` is already in flight for this vCPU.
1321    Busy,
1322    /// The world is paused.
1323    Paused,
1324    /// The operation did not complete within the caller's budget.
1325    Timeout,
1326}
1327
1328impl From<VcpuError> for RunError {
1329    fn from(value: VcpuError) -> Self {
1330        Self::Hardware(value)
1331    }
1332}
1333
1334/// Maximum number of "resumable" exits handled internally before handing
1335/// control back to policy (protection against an interrupt storm).
1336const MAX_RESUMED_EXITS: u32 = 64;
1337
1338/// True if an exit can be resumed immediately by the kernel.
1339const fn is_resumable(class: ExitClass) -> bool {
1340    matches!(
1341        class,
1342        ExitClass::ExternalInterrupt | ExitClass::InterruptWindow | ExitClass::Apic
1343    )
1344}
1345
1346fn regs_from_guest(guest: &GuestState, base: &VmmRegs) -> VmmRegs {
1347    VmmRegs {
1348        abi_version: strat9_abi::vmm::VMM_ABI_VERSION,
1349        flags: base.flags,
1350        rax: guest.rax,
1351        rbx: guest.rbx,
1352        rcx: guest.rcx,
1353        rdx: guest.rdx,
1354        rsi: guest.rsi,
1355        rdi: guest.rdi,
1356        rbp: guest.rbp,
1357        rsp: guest.rsp,
1358        r8: guest.r8,
1359        r9: guest.r9,
1360        r10: guest.r10,
1361        r11: guest.r11,
1362        r12: guest.r12,
1363        r13: guest.r13,
1364        r14: guest.r14,
1365        r15: guest.r15,
1366        rip: guest.rip,
1367        rflags: guest.rflags,
1368        cr0: guest.cr0,
1369        cr3: guest.cr3,
1370        cr4: guest.cr4,
1371        efer: guest.efer,
1372    }
1373}
1374
1375/// Names the access type encoded in an EPT-violation qualification.
1376///
1377/// Bits 2:0 are read/write/execute; bit 8 tells whether the fault came from a
1378/// guest-page-table walk (the GPA is then a page-table entry address, not the
1379/// faulting linear address).
1380pub(crate) fn ept_access_name(qualification: u64) -> &'static str {
1381    let access = match qualification & 0x7 {
1382        0b001 => "read",
1383        0b010 => "write",
1384        0b100 => "execute",
1385        _ => "read/write",
1386    };
1387    if qualification & (1 << 8) != 0 {
1388        "page-table walk"
1389    } else {
1390        access
1391    }
1392}
1393
1394fn event_from_exit(exit: &ExitInfo, vcpu_id: u64, guest_rax: u64) -> VmmExitEvent {
1395    let class = exit.class();
1396    let mut event = VmmExitEvent {
1397        abi_version: strat9_abi::vmm::VMM_ABI_VERSION,
1398        vcpu_id,
1399        gpa: exit.guest_physical_address,
1400        flags: 0,
1401        ..VmmExitEvent::default()
1402    };
1403    match class {
1404        ExitClass::IoPort => {
1405            let qualification = exit.qualification;
1406            event.kind = exit_kind::IO_PORT;
1407            event.port = ((qualification >> 16) & 0xFFFF) as u32;
1408            event.size = ((qualification & 0x7) + 1) as u32;
1409            // Bit 3: 0 = OUT, 1 = IN. For an OUT the policy needs the data the
1410            // guest wrote, otherwise every debug-port byte reads as zero.
1411            let direction_in = (qualification >> 3) & 1 != 0;
1412            event.flags = u32::from(direction_in);
1413            if !direction_in {
1414                let width = u64::from(event.size.min(8));
1415                let mask = if width == 8 {
1416                    u64::MAX
1417                } else {
1418                    (1u64 << (width * 8)) - 1
1419                };
1420                event.value = guest_rax & mask;
1421            }
1422        }
1423        ExitClass::Halt => {
1424            event.kind = exit_kind::HALT;
1425        }
1426        ExitClass::EptViolation => {
1427            event.kind = exit_kind::TRANSLATION;
1428            // Bits 2:0 of the EPT qualification: read/write/execute.
1429            event.flags = (exit.qualification & 0x7) as u32;
1430        }
1431        ExitClass::ExceptionOrNmi => {
1432            event.kind = exit_kind::EXCEPTION;
1433            event.flags = exit.interrupt_info;
1434        }
1435        ExitClass::PreemptionTimer => {
1436            event.kind = exit_kind::PREEMPTION_TIMER;
1437        }
1438        _ => {
1439            event.kind = exit_kind::OTHER;
1440            event.flags = exit.raw_reason;
1441        }
1442    }
1443    // A policy-driven I/O replay must advance the guest RIP itself: the
1444    // hardware leaves GUEST_RIP at the faulting instruction for port exits.
1445    event.instruction_length = exit.instruction_length;
1446    event
1447}
1448
1449/// Runs a vCPU until the next "policy" exit and queues the corresponding event
1450/// in the world's queue.
1451///
1452/// Exits that are purely hostile to throughput (external interrupt, interrupt
1453/// window, APIC, preemption timer) are resumed immediately by the kernel; all
1454/// the others are reported back to policy.
1455///
1456/// # Timing
1457///
1458/// Every guest entry is bracketed by two time-stamp counter reads. The delta is
1459/// recorded in the world's cumulative timing aggregates, per exit class: the
1460/// decoded reason for exits that reach policy, the functional class for exits
1461/// replayed by the kernel. Because the pair spans the guest entry and the exit
1462/// delivery, the delta measures the entry/exit cost **on the CPU that runs the
1463/// vCPU** only for single-instruction exits (I/O port, MSR access, second-level
1464/// violation), where the guest time is negligible; for asynchronous exits
1465/// (external interrupt, preemption timer, halt) it also contains the guest time
1466/// slice that preceded the exit, and must not be read as the exit latency.
1467/// Device-model replay latency is measured separately around the replay.
1468///
1469/// The sliding window of the rate meters is advanced once per call: one call is
1470/// one time slice.
1471pub fn run_vcpu(vcpu_id: u64, caps: &HwCaps) -> Result<(), RunError> {
1472    if crate::s9vm::active_cpu_count() == 0 {
1473        return Err(RunError::HardwareNotReady);
1474    }
1475    // 1. Takes the hardware context and the registers out of the registry,
1476    //    without holding the lock during execution.
1477    let (
1478        world_id,
1479        hardware,
1480        mut regs,
1481        pointer,
1482        pending_nmi,
1483        mut machine,
1484        mut apic,
1485        mut stats,
1486        mut timing,
1487        mut handler_timing,
1488        mut pending_console_input,
1489        mut pending_frames,
1490        mut console_output,
1491        mut network_output,
1492        mut network_output_bytes,
1493    ) = {
1494        let mut worlds = WORLDS.lock();
1495        let world = vcpu_world_mut(&mut worlds, vcpu_id).ok_or(RunError::UnknownVcpu)?;
1496        let slot = world
1497            .vcpus
1498            .iter_mut()
1499            .find(|slot| slot.id == vcpu_id)
1500            .ok_or(RunError::UnknownVcpu)?;
1501        let memory = world.memory.as_ref().ok_or(RunError::NoMemory)?;
1502        let pointer = memory.second_level_pointer(caps);
1503        let hardware = slot.hardware.take();
1504        let pending_nmi = core::mem::replace(&mut slot.pending_nmi, false);
1505        let apic_id = slot.apic_id;
1506        // The device model and the local APIC stay out of the registry while
1507        // the guest runs: the exit handler updates them without taking the
1508        // registry lock, which a running guest must never wait on.
1509        let machine = core::mem::replace(&mut world.machine, Machine::new());
1510        let apic = core::mem::replace(&mut slot.apic, LocalApic::new(apic_id));
1511        let stats = core::mem::replace(&mut world.stats, WorldStats::default());
1512        // The timing aggregates follow the same take/put pattern as `stats`:
1513        // the running vCPU updates them without ever taking the registry lock.
1514        let timing = core::mem::replace(&mut world.timing, WorldTiming::default());
1515        let handler_timing =
1516            core::mem::replace(&mut world.handler_timing, ExitLatencyHistogram::default());
1517        let pending_console_input = core::mem::take(&mut world.pending_console_input);
1518        let pending_frames = core::mem::take(&mut world.pending_frames);
1519        let console_output = core::mem::take(&mut world.console_output);
1520        let network_output = core::mem::take(&mut world.network_output);
1521        let network_output_bytes = core::mem::replace(&mut world.network_output_bytes, 0);
1522        (
1523            world.record.id,
1524            hardware,
1525            slot.regs,
1526            pointer,
1527            pending_nmi,
1528            machine,
1529            apic,
1530            stats,
1531            timing,
1532            handler_timing,
1533            pending_console_input,
1534            pending_frames,
1535            console_output,
1536            network_output,
1537            network_output_bytes,
1538        )
1539    };
1540    // One sliding-window slot per invocation: the rate meters measure exits per
1541    // time slice, and a "slice" is one `run_vcpu` call, whether or not the
1542    // guest actually entered (hardware setup failures included).
1543    timing.advance_window();
1544    // True when this call resumes a vCPU the guest already ran on: the control
1545    // block then holds the architectural state the guest produced (descriptor
1546    // tables, segments, MSRs) and it must not be reset by the ABI rebuild.
1547    let mut resumed = false;
1548    let mut hardware = match hardware {
1549        Some(existing) => {
1550            resumed = existing.entered();
1551            existing
1552        }
1553        None => HwVcpu::new(caps, pointer)?,
1554    };
1555
1556    // 2. Builds and validates the guest state.
1557    let mut guest = GuestState::from_abi_regs(&regs);
1558    let fixed = FixedBits::new(
1559        caps.cr0_fixed0,
1560        caps.cr0_fixed1,
1561        caps.cr4_fixed0,
1562        caps.cr4_fixed1,
1563    );
1564    guest
1565        .validate(&fixed, caps.unrestricted_guest)
1566        .map_err(|error| {
1567            // A rejected state would otherwise only surface as
1568            // `InvalidGuestState` in the caller: name the failing check and the
1569            // state fields, so a hardware run is diagnosable from the serial
1570            // log alone.
1571            log::warn!(
1572                "[s9vm] vcpu {}: invalid guest state ({:?}): cr0={:#x} cr3={:#x} cr4={:#x} \
1573                 efer={:#x} rip={:#x} rsp={:#x} rflags={:#x}",
1574                vcpu_id,
1575                error,
1576                regs.cr0,
1577                regs.cr3,
1578                regs.cr4,
1579                regs.efer,
1580                regs.rip,
1581                regs.rsp,
1582                regs.rflags
1583            );
1584            RunError::InvalidGuestState
1585        })?;
1586
1587    // 3. Loads the control block, configures and executes.
1588    // SAFETY: VT-x is active on this CPU (checked above); the control block
1589    // and the host stack belong to this vCPU, which is not currently running
1590    // (context taken out of the registry).
1591    let mut result = Ok(());
1592    stats.runs += 1;
1593    unsafe {
1594        // Drop any cached second-level translation for this world before the
1595        // next entry: a world can be torn down and its EPT root frame reused,
1596        // and stale translations tagged by the same EPTP would expose frames
1597        // that now belong to another world. The RUN always executes with VT-x
1598        // active on this CPU, which INVEPT requires.
1599        if caps.invept {
1600            crate::s9vm::control::invalidate_second_level(hardware.second_level_pointer());
1601        }
1602        let _ = hardware.clear();
1603        if let Err(error) = hardware.load() {
1604            result = Err(RunError::Hardware(error));
1605        } else if let Err(error) = hardware.configure_host() {
1606            result = Err(RunError::Hardware(error));
1607        } else if resumed {
1608            // The guest may have loaded its own GDT/IDT and segments since the
1609            // previous entry; the processor saved them in the control block on
1610            // the last exit. Import them before the ABI rebuild writes the boot
1611            // defaults back: a policy round trip must be transparent for the
1612            // guest, otherwise the first interrupt after it cannot be
1613            // delivered (zero IDTR limit → triple fault).
1614            match hardware.refresh_system_state() {
1615                Ok(()) => guest.import_system_state(hardware.guest()),
1616                Err(error) => result = Err(RunError::Hardware(error)),
1617            }
1618        }
1619        if result.is_ok() {
1620            if let Err(error) = hardware.configure(caps, &guest) {
1621                result = Err(RunError::Hardware(error));
1622            }
1623        }
1624        if result.is_ok() && pending_nmi {
1625            // The NMI takes priority over a pending external interrupt.
1626            if let Err(error) = hardware.inject_nmi() {
1627                result = Err(RunError::Hardware(error));
1628            }
1629        }
1630        if result.is_ok() {
1631            // Queued console input and network frames entered the world
1632            // while the vCPU was not running (they cannot be touched during
1633            // execution): hand them to the device model now, then service the
1634            // receive queues against the guest memory.
1635            if !pending_console_input.is_empty() {
1636                machine
1637                    .devices_mut()
1638                    .console
1639                    .push_input(&pending_console_input);
1640                pending_console_input.clear();
1641            }
1642            if !pending_frames.is_empty() {
1643                for frame in &pending_frames {
1644                    machine.push_network_frame(frame);
1645                }
1646                pending_frames.clear();
1647            }
1648            machine.service_devices(&mut hardware);
1649            // Interrupt-window exiting is control-block state and survives a
1650            // RUN, while `window_armed` below only tracks the current one: a
1651            // previous RUN that ended on a policy exit can leave the window
1652            // armed. An interruptible guest would then exit with
1653            // `InterruptWindow` after every entry and eventually be reported as
1654            // an exit storm. Start every RUN from a known, disarmed state.
1655            let _ = hardware.set_interrupt_window_exiting(caps, false);
1656            // Re-arm external-interrupt exiting in case a previous RUN left it
1657            // disabled: every host IRQ must exit so it is serviced in the STI
1658            // window and never delivered through the guest IDT.
1659            let _ = hardware.set_external_interrupt_exiting(caps, true);
1660            let mut resumed = 0u32;
1661            // True while interrupt-window exiting is armed in the control
1662            // block: the guest has a pending vector but interrupts disabled.
1663            let mut window_armed = false;
1664            loop {
1665                // Interrupt delivery. The local APIC is the only source: the
1666                // highest-priority deliverable vector is injected when the
1667                // guest is interruptible; otherwise the interrupt window is
1668                // armed so that the vector is delivered as soon as the guest
1669                // becomes ready. The window control is disarmed as soon as it
1670                // is no longer needed, otherwise the processor would exit
1671                // after every single instruction in the guest.
1672                let pending = apic.pending_vector();
1673                let mut interruptible = hardware.guest().rflags & RFLAGS_IF != 0;
1674                if interruptible && pending.is_some() {
1675                    // RFLAGS.IF alone is not enough: blocking by STI or by
1676                    // MOV SS suppresses VM-entry interruption delivery, and the
1677                    // vector would be discarded after being taken out of the
1678                    // APIC. Read the interruptibility state before injecting.
1679                    match hardware.interruptibility() {
1680                        Ok(state) => interruptible = interrupt_deliverable(true, state),
1681                        Err(error) => {
1682                            result = Err(RunError::Hardware(error));
1683                            break;
1684                        }
1685                    }
1686                }
1687                match interrupt_action(pending.is_some(), interruptible, window_armed) {
1688                    InterruptAction::Inject => {
1689                        if let Some(vector) = pending {
1690                            if let Err(error) = hardware.inject_interrupt(vector) {
1691                                result = Err(RunError::Hardware(error));
1692                                break;
1693                            }
1694                            // The vector moves to the in-service register: the
1695                            // processor delivers it at the next entry.
1696                            let _ = apic.service();
1697                            stats.injected_interrupts += 1;
1698                        }
1699                        if window_armed {
1700                            match hardware.set_interrupt_window_exiting(caps, false) {
1701                                Ok(_) => window_armed = false,
1702                                Err(error) => {
1703                                    result = Err(RunError::Hardware(error));
1704                                    break;
1705                                }
1706                            }
1707                        }
1708                    }
1709                    InterruptAction::ArmWindow => {
1710                        match hardware.set_interrupt_window_exiting(caps, true) {
1711                            Ok(armed) => {
1712                                if armed {
1713                                    stats.windows_armed += 1;
1714                                }
1715                                window_armed = armed;
1716                            }
1717                            Err(error) => {
1718                                result = Err(RunError::Hardware(error));
1719                                break;
1720                            }
1721                        }
1722                    }
1723                    InterruptAction::DisarmWindow => {
1724                        match hardware.set_interrupt_window_exiting(caps, false) {
1725                            Ok(_) => window_armed = false,
1726                            Err(error) => {
1727                                result = Err(RunError::Hardware(error));
1728                                break;
1729                            }
1730                        }
1731                    }
1732                    InterruptAction::None => {}
1733                }
1734                // Bracket the guest entry with two time-stamp counter reads.
1735                // The delta is the wall-clock time spent between the host and
1736                // the guest: guest execution plus the hardware entry and exit
1737                // sequences. See the function documentation for what it means
1738                // per class.
1739                let entry_tsc = core::arch::x86_64::_rdtsc();
1740                let run_result = hardware.run();
1741                let exit_tsc = core::arch::x86_64::_rdtsc();
1742                let exit_cycles = exit_tsc.saturating_sub(entry_tsc);
1743                // Advances the emulated local APIC timer by the time the guest
1744                // spent running (one-shot/periodic) and publishes the current
1745                // time stamp for the TSC-deadline mode. An expiry raises the
1746                // LVT vector in the APIC; the injection loop below (and at the
1747                // next iteration) delivers it through the interrupt-window
1748                // path. The guest TSC offset is zero, so host time stamps are
1749                // the guest's.
1750                //
1751                // APIC timer counts are bus ticks, not TSC cycles: the
1752                // conversion uses the published host frequency when it is
1753                // known (0 disables the scaling and keeps the raw-cycle
1754                // approximation, documented in the timer model).
1755                let tsc_hz = crate::s9vm::tsc::get()
1756                    .map(|frequency| frequency.hz())
1757                    .unwrap_or(0);
1758                apic.advance_tsc(exit_cycles, tsc_hz);
1759                apic.set_tsc(exit_tsc);
1760                // Legacy time base: the 8254 counts down and raises IRQ0, the
1761                // CMOS RTC advances by whole seconds. Same "advance on exit"
1762                // model as the local APIC timer, documented in those models.
1763                machine.advance_time(&mut apic, exit_cycles, tsc_hz);
1764                match run_result {
1765                    Ok(exit) => {
1766                        let class = exit.class();
1767                        // A triple fault or an entry-state rejection is a
1768                        // guest crash: policy only receives an `other` event
1769                        // without the registers, so name the state here. The
1770                        // guest-physical-address field of such an exit is a
1771                        // leftover of the previous exit and must not be read.
1772                        if matches!(class, ExitClass::TripleFault | ExitClass::EntryFailure) {
1773                            let guest = hardware.guest();
1774                            log::error!(
1775                                "[s9vm] vcpu {}: guest {} rip={:#x} rsp={:#x} rflags={:#x} \
1776                                 cr0={:#x} cr3={:#x} cr4={:#x} efer={:#x} info={:#x}",
1777                                vcpu_id,
1778                                if class == ExitClass::TripleFault {
1779                                    "triple fault"
1780                                } else {
1781                                    "entry failure"
1782                                },
1783                                guest.rip,
1784                                guest.rsp,
1785                                guest.rflags,
1786                                guest.cr0,
1787                                guest.cr3,
1788                                guest.cr4,
1789                                guest.efer,
1790                                exit.interrupt_info
1791                            );
1792                        }
1793                        // Kernel fast path: accesses to the modeled devices
1794                        // are replayed in place, so the guest never observes
1795                        // the exit and policy is not involved.
1796                        if matches!(
1797                            class,
1798                            ExitClass::IoPort
1799                                | ExitClass::Msr
1800                                | ExitClass::EptViolation
1801                                | ExitClass::Cpuid
1802                        ) {
1803                            // Replay latency: handler cost only, without the
1804                            // guest time contained in `exit_cycles`.
1805                            let handler_tsc = core::arch::x86_64::_rdtsc();
1806                            let handled = machine.handle(&mut hardware, &mut apic, &exit);
1807                            let handler_cycles =
1808                                core::arch::x86_64::_rdtsc().saturating_sub(handler_tsc);
1809                            match handled {
1810                                Ok(true) => {
1811                                    timing.record(class, exit_cycles);
1812                                    handler_timing.record(handler_cycles);
1813                                    // An emulated MSR write can change guest
1814                                    // state fields the control block caches
1815                                    // (EFER, PAT, FS/GS base, SYSENTER): push
1816                                    // them back before the next entry.
1817                                    if class == ExitClass::Msr {
1818                                        // SAFETY: the control block is loaded
1819                                        // and the guest is not running (we are
1820                                        // in the exit handler).
1821                                        let _ = hardware.sync_msr_state();
1822                                    }
1823                                    if resumed >= MAX_RESUMED_EXITS {
1824                                        log::warn!(
1825                                            "[s9vm] vcpu {}: exit storm after {} replayed \
1826                                             exits (class {:?}, rip {:#x}, pending_irq {:?})",
1827                                            vcpu_id,
1828                                            resumed,
1829                                            class,
1830                                            hardware.guest().rip,
1831                                            apic.pending_vector()
1832                                        );
1833                                        result = Err(RunError::ExitStorm);
1834                                        break;
1835                                    }
1836                                    resumed += 1;
1837                                    stats.emulated_exits += 1;
1838                                    match class {
1839                                        ExitClass::IoPort => stats.emulated_io += 1,
1840                                        ExitClass::EptViolation => stats.emulated_mmio += 1,
1841                                        ExitClass::Msr => stats.emulated_msr += 1,
1842                                        _ => {}
1843                                    }
1844                                    // Frames transmitted by the guest are
1845                                    // queued for the network front-end. The
1846                                    // queue is bounded: a slow consumer loses
1847                                    // the oldest frames instead of growing
1848                                    // kernel memory without limit.
1849                                    let frames = machine.drain_network_frames();
1850                                    if !frames.is_empty() {
1851                                        log::info!(
1852                                            "[s9vm] net: {} octets transmitted",
1853                                            frames.iter().map(|frame| frame.len()).sum::<usize>()
1854                                        );
1855                                        for frame in frames {
1856                                            if frame.len() > MAX_FRAME_SIZE {
1857                                                continue;
1858                                            }
1859                                            if network_output.len() >= MAX_NETWORK_OUTPUT_FRAMES
1860                                                || network_output_bytes + frame.len()
1861                                                    > MAX_NETWORK_OUTPUT_BYTES
1862                                            {
1863                                                let dropped = network_output.remove(0);
1864                                                network_output_bytes = network_output_bytes
1865                                                    .saturating_sub(dropped.len());
1866                                            }
1867                                            network_output_bytes += frame.len();
1868                                            network_output.push(frame);
1869                                        }
1870                                    }
1871                                    // The console device model collects the
1872                                    // bytes the guest wrote; the kernel only
1873                                    // routes them to its own log for now.
1874                                    let output = machine.drain_console();
1875                                    if !output.is_empty() {
1876                                        log::info!(
1877                                            "[s9vm] console: {}",
1878                                            core::str::from_utf8(&output)
1879                                                .unwrap_or("<binary data>")
1880                                        );
1881                                        push_console_output(&mut console_output, &output);
1882                                    }
1883                                    // Legacy COM1 output (a kernel that uses the
1884                                    // 8250 instead of virtio-console): same
1885                                    // routing, tagged so both are visible.
1886                                    let serial = machine.drain_serial();
1887                                    if !serial.is_empty() {
1888                                        log::info!(
1889                                            "[s9vm] serial: {}",
1890                                            core::str::from_utf8(&serial)
1891                                                .unwrap_or("<binary data>")
1892                                        );
1893                                        push_console_output(&mut console_output, &serial);
1894                                    }
1895                                    continue;
1896                                }
1897                                Ok(false) | Err(_) => {}
1898                            }
1899                        }
1900                        // Exits that are not replayed by the kernel: the
1901                        // decoded reason is recorded so that guest entry
1902                        // failures remain distinguishable from ordinary exits.
1903                        timing.record_exit(exit.reason, exit_cycles);
1904                        // A host interrupt that arrives while the guest runs is
1905                        // exited but cannot be delivered with host interrupts
1906                        // disabled. Open a one-instruction STI window so the
1907                        // host services it; the vector never reaches the guest
1908                        // IDT and the LAPIC ISR is acknowledged normally.
1909                        if class == ExitClass::ExternalInterrupt {
1910                            // The host services the pending IRQ in a short STI
1911                            // window; the vector is never delivered into the
1912                            // guest.
1913                            crate::s9vm::vcpu::service_pending_host_interrupts();
1914                            continue;
1915                        }
1916                        if is_resumable(class) && resumed < MAX_RESUMED_EXITS {
1917                            resumed += 1;
1918                            continue;
1919                        }
1920                        if is_resumable(class) {
1921                            log::warn!(
1922                                "[s9vm] vcpu {}: exit storm after {} resumable exits \
1923                                 (class {:?}, rip {:#x}, pending_irq {:?})",
1924                                vcpu_id,
1925                                resumed,
1926                                class,
1927                                hardware.guest().rip,
1928                                apic.pending_vector()
1929                            );
1930                            result = Err(RunError::ExitStorm);
1931                        } else {
1932                            stats.policy_exits += 1;
1933                            if class == ExitClass::PreemptionTimer {
1934                                stats.timer_exits += 1;
1935                            }
1936                            // An EPT violation that reaches policy means the
1937                            // guest touched a GPA the world does not map and
1938                            // that no device model claims. Name the address,
1939                            // the access type and the guest context: without
1940                            // them the only visible symptom is a replayed
1941                            // instruction or a later entry failure.
1942                            if class == ExitClass::EptViolation {
1943                                log::warn!(
1944                                    "[s9vm] vcpu {}: EPT violation gpa={:#x} qual={:#x} \
1945                                     access={} rip={:#x} cr3={:#x} rsp={:#x}",
1946                                    vcpu_id,
1947                                    exit.guest_physical_address,
1948                                    exit.qualification,
1949                                    ept_access_name(exit.qualification),
1950                                    hardware.guest().rip,
1951                                    hardware.guest().cr3,
1952                                    hardware.guest().rsp
1953                                );
1954                            }
1955                            let event = event_from_exit(&exit, vcpu_id, hardware.guest().rax);
1956                            let _ = push_exit(world_id, event);
1957                        }
1958                        break;
1959                    }
1960                    Err(error) => {
1961                        // A VM-entry failure ("VMfail") carries a hardware
1962                        // instruction-error code; dump the guest-state fields
1963                        // too, they are the only way to find the invalid one.
1964                        if let VcpuError::VmFail(code) = error {
1965                            log::error!(
1966                                "[s9vm] vcpu {}: VM entry failed (instruction error {:#x}): {}",
1967                                vcpu_id,
1968                                code,
1969                                hardware.guest_diagnostics()
1970                            );
1971                        }
1972                        result = Err(RunError::Hardware(error));
1973                        break;
1974                    }
1975                }
1976            }
1977        }
1978    }
1979
1980    // The VMCS must not stay current on this CPU after the RUN: the vCPU can be
1981    // resumed on another CPU, and a current VMCS blocks VMPTRLD/VMCLEAR there.
1982    if caps.invept {
1983        unsafe {
1984            crate::s9vm::control::invalidate_second_level(hardware.second_level_pointer());
1985        }
1986    }
1987    let _ = unsafe { hardware.clear() };
1988
1989    // 4. Reloads the registers from the post-execution guest state and puts
1990    //    the hardware context back into the registry if the world still
1991    //    exists.
1992    regs = regs_from_guest(hardware.guest(), &regs);
1993    let mut worlds = WORLDS.lock();
1994    if let Some(world) = worlds.get_mut(&world_id) {
1995        world.machine = machine;
1996        world.stats = stats;
1997        world.timing = timing;
1998        world.handler_timing = handler_timing;
1999        world.console_output = console_output;
2000        world.pending_console_input = pending_console_input;
2001        world.pending_frames = pending_frames;
2002        world.network_output = network_output;
2003        world.network_output_bytes = network_output_bytes;
2004        if let Some(slot) = world.vcpus.iter_mut().find(|slot| slot.id == vcpu_id) {
2005            slot.regs = regs;
2006            slot.hardware = Some(hardware);
2007            slot.apic = apic;
2008        }
2009    }
2010    result
2011}
2012
2013/// Appends bytes to the bounded console-output queue of a world.
2014fn push_console_output(queue: &mut Vec<u8>, bytes: &[u8]) {
2015    queue.extend_from_slice(bytes);
2016    if queue.len() > MAX_CONSOLE_OUTPUT {
2017        let excess = queue.len() - MAX_CONSOLE_OUTPUT;
2018        queue.drain(..excess);
2019    }
2020}
2021
2022/// Queues console input for a world.
2023///
2024/// The bytes are delivered to the guest's receive queue at the next `RUN`;
2025/// this is the entry point of a console scheme.
2026pub fn push_console_input(world_id: u64, bytes: &[u8]) -> Result<usize, ()> {
2027    let mut worlds = WORLDS.lock();
2028    let world = worlds.get_mut(&world_id).ok_or(())?;
2029    let room = MAX_CONSOLE_PENDING.saturating_sub(world.pending_console_input.len());
2030    let count = core::cmp::min(room, bytes.len());
2031    world
2032        .pending_console_input
2033        .extend_from_slice(&bytes[..count]);
2034    Ok(count)
2035}
2036
2037/// Takes the console input queued for a world.
2038///
2039/// A DOS world has no virtio console: its runner turns these host bytes into
2040/// PS/2 scancodes and types them into the guest keyboard, so `vm send <id>`
2041/// drives the DOS prompt of a live session.
2042pub fn take_console_input(world_id: u64) -> Vec<u8> {
2043    let mut worlds = WORLDS.lock();
2044    match worlds.get_mut(&world_id) {
2045        Some(world) => core::mem::take(&mut world.pending_console_input),
2046        None => Vec::new(),
2047    }
2048}
2049
2050/// Replaces the console-output snapshot of a world.
2051///
2052/// A DOS world has no virtio console, so its runner publishes the current VGA
2053/// text here: a following `vm console <id>` then shows the screen.
2054pub fn set_console_output(world_id: u64, bytes: &[u8]) -> Result<(), ()> {
2055    let mut worlds = WORLDS.lock();
2056    let world = worlds.get_mut(&world_id).ok_or(())?;
2057    world.console_output.clear();
2058    push_console_output(&mut world.console_output, bytes);
2059    Ok(())
2060}
2061
2062/// Takes the device model out of a world.
2063///
2064/// The DOS session runner keeps it while the guest runs, so the 8259/8254/8042
2065/// and the block device keep their state between two shell commands.
2066pub fn take_machine(world_id: u64) -> Option<Machine> {
2067    let mut worlds = WORLDS.lock();
2068    let world = worlds.get_mut(&world_id)?;
2069    Some(core::mem::replace(&mut world.machine, Machine::new()))
2070}
2071
2072/// Puts the device model back into its world. Returns `false` if it vanished.
2073pub fn store_machine(world_id: u64, machine: Machine) -> bool {
2074    let mut worlds = WORLDS.lock();
2075    match worlds.get_mut(&world_id) {
2076        Some(world) => {
2077            world.machine = machine;
2078            true
2079        }
2080        None => false,
2081    }
2082}
2083
2084/// Drains console output of a world into `out`.
2085///
2086/// Returns the number of bytes copied (0 when nothing is pending).
2087pub fn read_console_output(world_id: u64, out: &mut [u8]) -> Result<usize, ()> {
2088    let mut worlds = WORLDS.lock();
2089    let world = worlds.get_mut(&world_id).ok_or(())?;
2090    let count = core::cmp::min(out.len(), world.console_output.len());
2091    out[..count].copy_from_slice(&world.console_output[..count]);
2092    world.console_output.drain(..count);
2093    Ok(count)
2094}
2095
2096/// Writes the guest boot-information page of a world at `gpa`.
2097///
2098/// The page describes the memory ranges reserved for the world and the virtual
2099/// devices of its machine (MMIO base, I/O APIC line, device-specific value).
2100/// `gpa` must be page aligned and mapped in the world.
2101pub fn write_boot_info(world_id: u64, gpa: u64) -> Result<(), VmError> {
2102    use crate::s9vm::{bootinfo, emulate};
2103    if gpa % PAGE_SIZE != 0 {
2104        return Err(VmError::Map(MapError::InvalidRange));
2105    }
2106    let mut worlds = WORLDS.lock();
2107    let world = worlds.get_mut(&world_id).ok_or(VmError::Unknown)?;
2108    let memory = world
2109        .memory
2110        .as_ref()
2111        .ok_or(VmError::Map(MapError::NotMapped))?;
2112    let mut info = bootinfo::BootInfo::new();
2113    for region in memory.regions() {
2114        info.add_memory(region.gpa, region.len, bootinfo::memory_kind::RAM);
2115    }
2116    info.flags = bootinfo::flags::COMPLETE;
2117    let devices = world.machine.devices();
2118    if info.add_device(
2119        bootinfo::device_kind::CONSOLE,
2120        emulate::CONSOLE_IRQ_LINE as u32,
2121        emulate::CONSOLE_BASE,
2122        0,
2123    ) {
2124        info.flags |= bootinfo::flags::HAS_CONSOLE;
2125    }
2126    if info.add_device(
2127        bootinfo::device_kind::BLOCK,
2128        emulate::BLK_IRQ_LINE as u32,
2129        emulate::BLK_BASE,
2130        devices.blk.sectors(),
2131    ) {
2132        info.flags |= bootinfo::flags::HAS_BLOCK;
2133    }
2134    if info.add_device(
2135        bootinfo::device_kind::NETWORK,
2136        emulate::NET_IRQ_LINE as u32,
2137        emulate::NET_BASE,
2138        0,
2139    ) {
2140        info.flags |= bootinfo::flags::HAS_NETWORK;
2141    }
2142    let mut page = [0u8; bootinfo::SIZE];
2143    info.encode(&mut page);
2144    let hpa = memory
2145        .translate(gpa)
2146        .ok_or(VmError::Map(MapError::NotMapped))?;
2147    // SAFETY: `hpa` belongs to a frame reserved for this world and is mapped by
2148    // the HHDM; `SIZE` bytes stay inside the page.
2149    unsafe {
2150        core::ptr::copy_nonoverlapping(
2151            page.as_ptr(),
2152            crate::memory::phys_to_virt(hpa) as *mut u8,
2153            bootinfo::SIZE,
2154        );
2155    }
2156    Ok(())
2157}
2158
2159/// Conventional guest-physical address of the firmware table image.
2160///
2161/// ACPI-compatible guests search for the `RSD PTR ` signature on 16-byte
2162/// boundaries in the extended BIOS data area and in the
2163/// `0x000E_0000..=0x000F_FFFF` window, so placing the image there makes it
2164/// discoverable without extending the boot-information page.
2165pub const ACPI_GPA: u64 = 0x000E_0000;
2166
2167/// Writes the firmware description tables of a world at `base_gpa`.
2168///
2169/// The image is built from the world's vCPU APIC identifiers (one MADT Local
2170/// APIC entry each) and placed in guest memory. If the range is not mapped
2171/// yet, it is mapped read-only; if it already belongs to guest RAM (a firmware
2172/// region mapped by the loader, for instance), the tables are written into the
2173/// existing pages. `base_gpa` must be 16-byte aligned and the image must stay
2174/// inside the guest-physical address space.
2175pub fn write_acpi(world_id: u64, caps: &HwCaps, base_gpa: u64) -> Result<(), VmError> {
2176    use crate::s9vm::acpi::{AcpiBuilder, IMAGE_ALIGN, MAX_IMAGE_LEN};
2177
2178    if base_gpa % IMAGE_ALIGN != 0 {
2179        return Err(VmError::Map(MapError::InvalidRange));
2180    }
2181    if base_gpa
2182        .checked_add(MAX_IMAGE_LEN as u64)
2183        .map_or(true, |end| end > MAX_GPA)
2184    {
2185        return Err(VmError::Map(MapError::InvalidRange));
2186    }
2187
2188    // 1. APIC identifiers of the world's vCPUs (the MADT describes them).
2189    let apic_ids: Vec<u8> = {
2190        let worlds = WORLDS.lock();
2191        let world = worlds.get(&world_id).ok_or(VmError::Unknown)?;
2192        if world.vcpus.is_empty() {
2193            return Err(VmError::Map(MapError::InvalidRange));
2194        }
2195        world.vcpus.iter().map(|slot| slot.apic_id as u8).collect()
2196    };
2197
2198    // 2. Builds the image outside the registry lock.
2199    let builder = AcpiBuilder::new(base_gpa, &apic_ids);
2200    let layout = builder
2201        .layout()
2202        .map_err(|_| VmError::Map(MapError::InvalidRange))?;
2203    let mut image = alloc::vec![0u8; layout.total_len];
2204    builder
2205        .encode(&mut image)
2206        .map_err(|_| VmError::Map(MapError::InvalidRange))?;
2207    let len = image.len();
2208    let page_len = ((len as u64 + PAGE_SIZE - 1) / PAGE_SIZE) * PAGE_SIZE;
2209
2210    // 3. Maps the window when it is not already backed by guest memory. An
2211    //    overlap is not an error: the range may already be covered by a larger
2212    //    reserved region, in which case the copy below simply uses it.
2213    let already_mapped = {
2214        let worlds = WORLDS.lock();
2215        match worlds
2216            .get(&world_id)
2217            .and_then(|world| world.memory.as_ref())
2218        {
2219            Some(memory) => (0..page_len)
2220                .step_by(PAGE_SIZE as usize)
2221                .all(|offset| memory.translate(base_gpa + offset as u64).is_some()),
2222            None => return Err(VmError::Map(MapError::NotMapped)),
2223        }
2224    };
2225    if !already_mapped {
2226        if let Err(error) = map_memory(world_id, caps, base_gpa, page_len, 1, 0) {
2227            if error != VmError::Map(MapError::Overlap) {
2228                return Err(error);
2229            }
2230        }
2231    }
2232
2233    // 4. Copies the tables page by page through the HHDM.
2234    let mut worlds = WORLDS.lock();
2235    let world = worlds.get_mut(&world_id).ok_or(VmError::Unknown)?;
2236    let memory = world
2237        .memory
2238        .as_ref()
2239        .ok_or(VmError::Map(MapError::NotMapped))?;
2240    let mut copied = 0usize;
2241    while copied < len {
2242        let page_gpa = base_gpa + ((copied / PAGE_SIZE as usize) * PAGE_SIZE as usize) as u64;
2243        let page_offset = copied % PAGE_SIZE as usize;
2244        let count = core::cmp::min(PAGE_SIZE as usize - page_offset, len - copied);
2245        let hpa = memory
2246            .translate(page_gpa)
2247            .ok_or(VmError::Map(MapError::NotMapped))?;
2248        // SAFETY: the page belongs to this world and is mapped by the HHDM;
2249        // `page_offset + count <= PAGE_SIZE`.
2250        unsafe {
2251            core::ptr::copy_nonoverlapping(
2252                image[copied..].as_ptr(),
2253                (crate::memory::phys_to_virt(hpa) as *mut u8).add(page_offset),
2254                count,
2255            );
2256        }
2257        copied += count;
2258    }
2259    drop(worlds);
2260
2261    log::info!(
2262        "[s9vm] firmware tables at {:#x}: {} byte(s), {} vCPU(s)",
2263        base_gpa,
2264        len,
2265        apic_ids.len()
2266    );
2267    Ok(())
2268}
2269
2270/// Peeks at the oldest pending exit event of a world, without consuming it.
2271///
2272/// The exit queue is owned by the policy; this accessor only feeds diagnostics
2273/// (`/dev/vmm/<id>/exits`) and never changes the queue.
2274pub fn peek_exit(world_id: u64) -> Result<VmmExitEvent, ()> {
2275    WORLDS
2276        .lock()
2277        .get(&world_id)
2278        .ok_or(())?
2279        .exits
2280        .peek()
2281        .map_err(|_| ())
2282}
2283
2284/// Pops one frame transmitted by the guest and queued for the network
2285/// front-end. Returns `Ok(None)` when the queue is empty.
2286pub fn read_network_frame(world_id: u64) -> Result<Option<Vec<u8>>, ()> {
2287    let mut worlds = WORLDS.lock();
2288    let world = worlds.get_mut(&world_id).ok_or(())?;
2289    if world.network_output.is_empty() {
2290        return Ok(None);
2291    }
2292    let frame = world.network_output.remove(0);
2293    world.network_output_bytes = world.network_output_bytes.saturating_sub(frame.len());
2294    Ok(Some(frame))
2295}
2296
2297/// Capacity of the world's block device, in 512-byte sectors.
2298pub fn disk_sectors(world_id: u64) -> Option<u64> {
2299    WORLDS
2300        .lock()
2301        .get(&world_id)
2302        .map(|world| world.machine.devices().blk.sectors())
2303}
2304
2305/// Reads sectors from the world's block device into `out`.
2306///
2307/// Returns the number of bytes copied, clamped to the disk capacity and to the
2308/// length of `out`.
2309pub fn read_disk(world_id: u64, sector: u64, out: &mut [u8]) -> Result<usize, ()> {
2310    let mut worlds = WORLDS.lock();
2311    let world = worlds.get_mut(&world_id).ok_or(())?;
2312    let disk = world.machine.devices_mut().blk.disk_mut();
2313    let offset = sector
2314        .checked_mul(512)
2315        .and_then(|offset| usize::try_from(offset).ok())
2316        .ok_or(())?;
2317    if offset >= disk.len() {
2318        return Ok(0);
2319    }
2320    let count = core::cmp::min(out.len(), disk.len() - offset);
2321    out[..count].copy_from_slice(&disk[offset..offset + count]);
2322    Ok(count)
2323}
2324
2325/// Writes sectors to the world's block device from `data`.
2326///
2327/// Returns the number of bytes written, clamped to the disk capacity and to
2328/// the length of `data`.
2329pub fn write_disk(world_id: u64, sector: u64, data: &[u8]) -> Result<usize, ()> {
2330    let mut worlds = WORLDS.lock();
2331    let world = worlds.get_mut(&world_id).ok_or(())?;
2332    let disk = world.machine.devices_mut().blk.disk_mut();
2333    let offset = sector
2334        .checked_mul(512)
2335        .and_then(|offset| usize::try_from(offset).ok())
2336        .ok_or(())?;
2337    if offset >= disk.len() {
2338        return Ok(0);
2339    }
2340    let count = core::cmp::min(data.len(), disk.len() - offset);
2341    disk[offset..offset + count].copy_from_slice(&data[..count]);
2342    Ok(count)
2343}
2344
2345/// Errors of [`load_disk`].
2346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2347pub enum DiskError {
2348    /// The world does not exist (or is being destroyed).
2349    Unknown,
2350    /// Empty or non-sector-multiple image length.
2351    InvalidLength,
2352    /// Image larger than [`VMM_DISK_MAX_BYTES`].
2353    TooLarge,
2354}
2355
2356/// Replaces the contents of a world's block device with a disk image.
2357///
2358/// `bytes` must be a non-empty multiple of [`VMM_DISK_SECTOR_SIZE`] and at
2359/// most [`VMM_DISK_MAX_BYTES`]. The image is copied from sector 0, the device
2360/// is **never shrunk**, and the capacity after the call is at least
2361/// `max(current, VMM_DISK_DEFAULT_BYTES, image length)`. Bytes past the image
2362/// are zero, so a shorter image fully replaces the previous content; when the
2363/// device has to grow it is rebuilt zeroed (read-only mode preserved), which
2364/// resets its virtio transport state. Meant to be called before the guest
2365/// boots. Returns the resulting capacity in 512-byte sectors.
2366pub fn load_disk(world_id: u64, bytes: &[u8]) -> Result<u64, DiskError> {
2367    if bytes.is_empty() || bytes.len() as u64 % VMM_DISK_SECTOR_SIZE != 0 {
2368        return Err(DiskError::InvalidLength);
2369    }
2370    if bytes.len() as u64 > VMM_DISK_MAX_BYTES {
2371        return Err(DiskError::TooLarge);
2372    }
2373    let mut worlds = WORLDS.lock();
2374    let world = worlds.get_mut(&world_id).ok_or(DiskError::Unknown)?;
2375    if world.closing {
2376        return Err(DiskError::Unknown);
2377    }
2378    let blk = &mut world.machine.devices_mut().blk;
2379    let current = blk.sectors() * VMM_DISK_SECTOR_SIZE;
2380    // Grow-only: never shrink, and leave at least the documented default
2381    // capacity so a small image still yields a stable 256-sector device.
2382    let target = current.max(VMM_DISK_DEFAULT_BYTES).max(bytes.len() as u64);
2383    if target == current {
2384        // In-place replacement keeps the virtio transport state.
2385        let disk = blk.disk_mut();
2386        disk.fill(0);
2387        disk[..bytes.len()].copy_from_slice(bytes);
2388    } else {
2389        // Growth rebuilds the device zeroed; preserve the access mode.
2390        let read_only = blk.read_only();
2391        let mut fresh = if read_only {
2392            VirtioBlk::new_read_only(target as usize)
2393        } else {
2394            VirtioBlk::new(target as usize)
2395        };
2396        fresh.disk_mut()[..bytes.len()].copy_from_slice(bytes);
2397        *blk = fresh;
2398    }
2399    Ok(target / VMM_DISK_SECTOR_SIZE)
2400}
2401
2402/// Diagnostic snapshot of one logical vCPU.
2403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2404pub struct VcpuSnapshot {
2405    /// Opaque vCPU identifier.
2406    pub id: u64,
2407    /// Guest APIC identifier.
2408    pub apic_id: u32,
2409    /// `true` when a hardware context has been created (at least one `RUN`).
2410    pub hardware_ready: bool,
2411    /// `true` while a `RUN` request is pending or executing.
2412    pub executing: bool,
2413    /// `true` while the vCPU task is inside guest execution (VM entry/exits).
2414    pub in_guest: bool,
2415    /// Number of `RUN`s completed by this vCPU task.
2416    pub runs: u64,
2417    /// `true` when an NMI is pending delivery.
2418    pub pending_nmi: bool,
2419}
2420
2421/// Diagnostic snapshot of every vCPU of a world.
2422pub fn vcpu_snapshots(world_id: u64) -> Option<Vec<VcpuSnapshot>> {
2423    let worlds = WORLDS.lock();
2424    let world = worlds.get(&world_id)?;
2425    Some(
2426        world
2427            .vcpus
2428            .iter()
2429            .map(|slot| VcpuSnapshot {
2430                id: slot.id,
2431                apic_id: slot.apic_id,
2432                hardware_ready: slot.hardware.is_some(),
2433                executing: slot.run_requested || slot.run_in_flight,
2434                in_guest: slot.in_guest,
2435                runs: slot.runs,
2436                pending_nmi: slot.pending_nmi,
2437            })
2438            .collect(),
2439    )
2440}
2441
2442/// Writes the guest boot-parameter block at `gpa`.
2443///
2444/// The 1024-byte block (`s9vm::bootparams`) is the hand-off structure a real
2445/// operating-system guest expects: a physical memory map derived from the
2446/// world's mapped regions, the ACPI RSDP address, the console device and the
2447/// boot flags. `gpa` must be page aligned and already mapped in the world; the
2448/// block is copied through the HHDM like the boot-information page.
2449///
2450/// Region classification: write-back RAM that does not overlap a device window
2451/// is `USABLE`; anything mapped with a non-default memory type or overlapping
2452/// the console/block/network/APIC windows is `MMIO`; the firmware window
2453/// (`ACPI_GPA..ACPI_GPA + acpi::MAX_IMAGE_LEN`) is `ACPI_RECLAIMABLE`. Adjacent
2454/// ranges of the same kind are merged; if more than the block capacity remain,
2455/// the map is truncated (logged) rather than refusing to boot the guest.
2456pub fn write_boot_params(world_id: u64, gpa: u64) -> Result<(), VmError> {
2457    use crate::s9vm::{acpi, bootparams, emulate};
2458
2459    if gpa % PAGE_SIZE != 0 {
2460        return Err(VmError::Map(MapError::InvalidRange));
2461    }
2462    let acpi_end = ACPI_GPA.saturating_add(acpi::MAX_IMAGE_LEN as u64);
2463    let mut worlds = WORLDS.lock();
2464    let world = worlds.get_mut(&world_id).ok_or(VmError::Unknown)?;
2465    let memory = world
2466        .memory
2467        .as_ref()
2468        .ok_or(VmError::Map(MapError::NotMapped))?;
2469
2470    let mut params = bootparams::BootParams::new();
2471    params.set_rsdp(ACPI_GPA);
2472    params.set_console(emulate::CONSOLE_BASE, emulate::CONSOLE_IRQ_LINE as u32);
2473    params
2474        .set_flags(
2475            bootparams::flags::CONSOLE_PRESENT
2476                | bootparams::flags::BLOCK_PRESENT
2477                | bootparams::flags::NETWORK_PRESENT,
2478        )
2479        .map_err(|_| VmError::Map(MapError::InvalidRange))?;
2480
2481    // Initrd/module ranges and the command line are authoritative in the
2482    // world registry: `SYS_VMM_LOAD_MODULE` and `SYS_VMM_SET_CMDLINE` fill
2483    // them before this block is written.
2484    for module in &world.modules {
2485        params
2486            .add_module(module.base, module.len)
2487            .map_err(|_| VmError::Map(MapError::InvalidRange))?;
2488    }
2489    params
2490        .set_cmdline(&world.cmdline[..world.cmdline_len])
2491        .map_err(|_| VmError::Map(MapError::InvalidRange))?;
2492
2493    // Builds the map from the world's own reservations, merging neighbours of
2494    // the same kind so that a fragmented map still fits in the fixed block.
2495    let mut pending: Option<(u64, u64, u32)> = None;
2496    let mut truncated = false;
2497    for region in memory.regions() {
2498        let kind = classify_region(region, acpi_end);
2499        match pending {
2500            Some((base, len, current)) if current == kind && base + len == region.gpa => {
2501                pending = Some((base, len + region.len, current));
2502            }
2503            Some((base, len, current)) => {
2504                if params.add_memory(base, len, current).is_err() {
2505                    truncated = true;
2506                }
2507                pending = Some((region.gpa, region.len, kind));
2508            }
2509            None => pending = Some((region.gpa, region.len, kind)),
2510        }
2511    }
2512    if let Some((base, len, kind)) = pending {
2513        if params.add_memory(base, len, kind).is_err() {
2514            truncated = true;
2515        }
2516    }
2517
2518    let mut page = [0u8; bootparams::SIZE];
2519    params.encode(&mut page);
2520    let hpa = memory
2521        .translate(gpa)
2522        .ok_or(VmError::Map(MapError::NotMapped))?;
2523    // SAFETY: `hpa` belongs to a frame reserved for this world, is mapped by
2524    // the HHDM, and `SIZE` bytes stay inside one 4 KiB page.
2525    unsafe {
2526        core::ptr::copy_nonoverlapping(
2527            page.as_ptr(),
2528            crate::memory::phys_to_virt(hpa) as *mut u8,
2529            bootparams::SIZE,
2530        );
2531    }
2532    // Read the device flags back from guest memory: a guest that reports a
2533    // device as "not advertised" can then be distinguished from a wrong
2534    // boot-parameter block on the writer side.
2535    let mut flags_readback = [0u8; 4];
2536    unsafe {
2537        core::ptr::copy_nonoverlapping(
2538            (crate::memory::phys_to_virt(hpa) as *const u8).add(bootparams::OFF_FLAGS),
2539            flags_readback.as_mut_ptr(),
2540            flags_readback.len(),
2541        );
2542    }
2543    let flags_readback = u32::from_le_bytes(flags_readback);
2544    drop(worlds);
2545    if truncated {
2546        log::warn!(
2547            "[s9vm] boot params at {:#x}: memory map truncated to {} entries",
2548            gpa,
2549            bootparams::MAX_MEMORY_ENTRIES
2550        );
2551    }
2552    log::info!(
2553        "[s9vm] boot params at {:#x}: flags {:#x} (readback {:#x}), {} memory range(s), \
2554         {} module(s), cmdline {} byte(s), rsdp {:#x}",
2555        gpa,
2556        params.flags(),
2557        flags_readback,
2558        params.memory_count(),
2559        params.module_count(),
2560        params.cmdline_len(),
2561        ACPI_GPA
2562    );
2563    Ok(())
2564}
2565
2566/// Classifies one world region for the guest boot-parameter memory map.
2567fn classify_region(region: &crate::s9vm::memmap::Region, acpi_end: u64) -> u32 {
2568    use crate::s9vm::{bootparams::memory_kind, emulate};
2569
2570    let end = region.end();
2571    fn overlaps(start: u64, end: u64, other: u64, other_end: u64) -> bool {
2572        start < other_end && other < end
2573    }
2574    // Device windows and MMIO-typed mappings are not ordinary RAM.
2575    let device = [
2576        (emulate::APIC_BASE, emulate::APIC_BASE + 0x1000),
2577        (emulate::IOAPIC_BASE, emulate::IOAPIC_BASE + 0x1000),
2578        (emulate::CONSOLE_BASE, emulate::CONSOLE_BASE + 0x1000),
2579        (emulate::BLK_BASE, emulate::BLK_BASE + 0x1000),
2580        (emulate::NET_BASE, emulate::NET_BASE + 0x1000),
2581    ];
2582    if region.memtype != 0
2583        || device
2584            .iter()
2585            .any(|(start, end_device)| overlaps(region.gpa, end, *start, *end_device))
2586    {
2587        return memory_kind::MMIO;
2588    }
2589    // The firmware table image is reclaimable once the guest has parsed it.
2590    if overlaps(region.gpa, end, ACPI_GPA, acpi_end) {
2591        return memory_kind::ACPI_RECLAIMABLE;
2592    }
2593    memory_kind::USABLE
2594}
2595
2596/// Queues a frame for the network device of a world.
2597///
2598/// The frame is handed to the guest's receive queue at the next `RUN`; this is
2599/// the entry point a network scheme will use.
2600pub fn push_network_frame(world_id: u64, frame: &[u8]) -> Result<(), ()> {
2601    let mut worlds = WORLDS.lock();
2602    let world = worlds.get_mut(&world_id).ok_or(())?;
2603    if frame.len() > MAX_FRAME_SIZE || world.pending_frames.len() >= MAX_PENDING_FRAMES {
2604        return Err(());
2605    }
2606    world.pending_frames.push(frame.to_vec());
2607    Ok(())
2608}
2609
2610/// Queues an event in a world's queue.
2611pub fn push_exit(world_id: u64, event: VmmExitEvent) -> Result<(), ()> {
2612    let mut worlds = WORLDS.lock();
2613    let world = worlds.get_mut(&world_id).ok_or(())?;
2614    world.exits.push(event).map_err(|_| ())
2615}
2616
2617/// Dequeues the next event of a world.
2618pub fn pop_exit(world_id: u64) -> Result<VmmExitEvent, ()> {
2619    let mut worlds = WORLDS.lock();
2620    let world = worlds.get_mut(&world_id).ok_or(())?;
2621    world.exits.pop().map_err(|_| ())
2622}
2623
2624/// Cumulative execution counters of a world.
2625pub fn stats(world_id: u64) -> Option<WorldStats> {
2626    WORLDS.lock().get(&world_id).map(|world| world.stats)
2627}
2628
2629/// Cumulative execution counters of every world.
2630pub fn total_stats() -> WorldStats {
2631    let worlds = WORLDS.lock();
2632    let mut total = WorldStats::default();
2633    for world in worlds.values() {
2634        total.add(&world.stats);
2635    }
2636    total
2637}
2638
2639/// Upper bound of the bucket that contains the `p`-th sample of the union of
2640/// every per-class histogram, in cycles.
2641///
2642/// The merged distribution is never materialised: the populations are summed
2643/// bucket by bucket across the classes, which keeps the accessor allocation
2644/// free. This is the same conservative semantics as
2645/// `ExitLatencyHistogram::percentile`.
2646fn merged_percentile(timing: &WorldTiming, p: u8, count: u64) -> u64 {
2647    if count == 0 {
2648        return 0;
2649    }
2650    let clamped = if p > 100 { 100 } else { p } as u64;
2651    let scaled = clamped.saturating_mul(count);
2652    let mut rank = scaled / 100;
2653    if scaled % 100 != 0 || rank == 0 {
2654        rank = rank.saturating_add(1);
2655    }
2656    let mut cumulative = 0u64;
2657    for bucket in 0..EXIT_LATENCY_BUCKETS {
2658        let mut population = 0u64;
2659        for index in 0..TIMING_CLASS_COUNT {
2660            if let Some(class) = WorldTiming::class_at(index) {
2661                population = population.saturating_add(timing.latency(class).bucket_count(bucket));
2662            }
2663        }
2664        cumulative = cumulative.saturating_add(population);
2665        if cumulative >= rank {
2666            return ExitLatencyHistogram::bucket_upper_bound(bucket);
2667        }
2668    }
2669    // Defensive: the populations sum to `count`, so the loop always returns.
2670    0
2671}
2672
2673/// Builds a compact snapshot from the two per-world aggregates.
2674fn timing_snapshot(timing: &WorldTiming, handler: &ExitLatencyHistogram) -> WorldTimingSnapshot {
2675    let mut snapshot = WorldTimingSnapshot::default();
2676    let mut sum = 0u64;
2677    let mut min = u64::MAX;
2678    let mut max = 0u64;
2679    for index in 0..TIMING_CLASS_COUNT {
2680        let Some(class) = WorldTiming::class_at(index) else {
2681            continue;
2682        };
2683        let histogram = timing.latency(class);
2684        snapshot.per_class[index] = histogram.count();
2685        snapshot.exits = snapshot.exits.saturating_add(histogram.count());
2686        sum = sum.saturating_add(histogram.sum());
2687        if let Some(value) = histogram.min() {
2688            if value < min {
2689                min = value;
2690            }
2691        }
2692        if let Some(value) = histogram.max() {
2693            if value > max {
2694                max = value;
2695            }
2696        }
2697    }
2698    if snapshot.exits != 0 {
2699        snapshot.mean_cycles = sum / snapshot.exits;
2700        snapshot.min_cycles = min;
2701        snapshot.max_cycles = max;
2702        snapshot.p95_cycles = merged_percentile(timing, 95, snapshot.exits);
2703    }
2704    snapshot.handler_samples = handler.count();
2705    snapshot.handler_mean_cycles = handler.mean().unwrap_or(0);
2706    snapshot.handler_p95_cycles = handler.percentile(95).unwrap_or(0);
2707    snapshot.window = timing.total_rate().window();
2708    snapshot.peak_window = timing.total_rate().peak_window();
2709    snapshot
2710}
2711
2712/// Read-only timing snapshot of a world.
2713///
2714/// Returns `None` when the world does not exist. The aggregates are taken out
2715/// of the registry while a vCPU runs (the execution path must never take the
2716/// registry lock), so a snapshot taken during execution reports the state of
2717/// the last completed time slice; the in-flight samples are put back when
2718/// `run_vcpu` returns.
2719pub fn timing(world_id: u64) -> Option<WorldTimingSnapshot> {
2720    let worlds = WORLDS.lock();
2721    let world = worlds.get(&world_id)?;
2722    Some(timing_snapshot(&world.timing, &world.handler_timing))
2723}
2724
2725/// Returns the second-level translation pointer (EPTP) of a world.
2726///
2727/// The value is the pointer the control block uses to walk the guest physical
2728/// address space; it is the world's real translation table, not a mirror. It
2729/// stays valid as long as the world exists and its guest memory has not been
2730/// destroyed (the tables are freed by `destroy`), so the caller must not cache
2731/// it beyond the world's lifetime. The registry lock is taken briefly for the
2732/// lookup and never across guest execution.
2733///
2734/// Returns [`VmError::Unknown`] when the world does not exist, and
2735/// [`VmError::Map`] with [`MapError::NotMapped`] when the world has no guest
2736/// memory yet.
2737pub fn second_level_pointer(world_id: u64, caps: &HwCaps) -> Result<u64, VmError> {
2738    let worlds = WORLDS.lock();
2739    let world = worlds.get(&world_id).ok_or(VmError::Unknown)?;
2740    let memory = world
2741        .memory
2742        .as_ref()
2743        .ok_or(VmError::Map(MapError::NotMapped))?;
2744    Ok(memory.second_level_pointer(caps))
2745}
2746
2747/// Number of pending events for a world.
2748pub fn exit_count(world_id: u64) -> Option<usize> {
2749    WORLDS.lock().get(&world_id).map(|world| world.exits.len())
2750}
2751
2752// ============================================================================
2753// Device translation (IOMMU)
2754// ============================================================================
2755
2756/// Validates the shape of an IOMMU map/unmap request.
2757fn validate_iommu_range(iova: u64, len: u64, require_2m: bool) -> Result<(), IommuError> {
2758    if len == 0
2759        || len > IOMMU_MAX_MAP_BYTES
2760        || len % IOMMU_PAGE_SIZE != 0
2761        || iova % IOMMU_PAGE_SIZE != 0
2762    {
2763        return Err(IommuError::InvalidRange);
2764    }
2765    if iova.checked_add(len).map_or(true, |end| end > MAX_GPA) {
2766        return Err(IommuError::InvalidRange);
2767    }
2768    if require_2m && (iova % IOMMU_LARGE_PAGE_SIZE != 0 || len % IOMMU_LARGE_PAGE_SIZE != 0) {
2769        return Err(IommuError::InvalidRange);
2770    }
2771    Ok(())
2772}
2773
2774/// Returns the IOMMU domain of a world, allocating it on first use.
2775///
2776/// One domain per world: every device assigned to the world shares the same
2777/// address space, so a mapping installed for one device is visible to the
2778/// others (the device set is trusted to be co-operating; isolation is between
2779/// worlds, not inside one).
2780fn iommu_domain(world: &mut World) -> Result<DomainId, IommuError> {
2781    if world.closing {
2782        return Err(IommuError::UnknownDomain);
2783    }
2784    match world.iommu_domain {
2785        Some(domain) => Ok(domain),
2786        None => {
2787            let domain = world.iommu.create_domain()?;
2788            world.iommu_domain = Some(domain);
2789            Ok(domain)
2790        }
2791    }
2792}
2793
2794// ----------------------------------------------------------------------------
2795// Host VT-d mirroring (best effort, software model stays authoritative)
2796// ----------------------------------------------------------------------------
2797
2798/// One host-side mirror segment, collected while the registry lock is held.
2799///
2800/// The collection is bounded by the model quota (`MAX_ENTRIES_PER_DOMAIN`), so
2801/// the vector cannot grow without bound.
2802struct HostIommuSegment {
2803    iova: u64,
2804    phys: u64,
2805    len: u64,
2806    kind: MappingKind,
2807}
2808
2809/// Host IOMMU domains, one per `(world, PCI function)`.
2810///
2811/// The registry lock and this lock are **never** held together: the table is
2812/// only used to find or park an `Arc`, and the hardware IOMMU layer (which has
2813/// its own locks) is called after it has been released.
2814static IOMMU_HOST_DOMAINS: SpinLock<BTreeMap<(u64, u32), Arc<HardwareIommuDomain>>> =
2815    SpinLock::new(BTreeMap::new());
2816
2817/// One-shot note when the host backend is not ready (feature disabled, no
2818/// DMAR, or activation not validated). The software model keeps working.
2819static IOMMU_BACKEND_NOTED: AtomicBool = AtomicBool::new(false);
2820
2821/// Records (once) that host mirroring is disabled.
2822fn note_iommu_backend_unavailable() {
2823    if !IOMMU_BACKEND_NOTED.swap(true, Ordering::Relaxed) {
2824        log::info!(
2825            "[s9vm] iommu: host VT-d backend not ready; host mirroring disabled, \
2826             software model only"
2827        );
2828    }
2829}
2830
2831/// True when the authoritative host backend is ready for mirroring.
2832fn iommu_host_ready() -> bool {
2833    crate::arch::iommu::backend().is_ready()
2834}
2835
2836/// Translates the model permissions into VT-d DMA rights.
2837///
2838/// `Perms::read`/`write` describe what the **device** may do with the mapped
2839/// memory: read becomes `DmaProt::READ`, write becomes `DmaProt::WRITE`.
2840/// Execute has no meaning for a DMA translation and is ignored. A mapping with
2841/// neither read nor write (execute-only) becomes `DmaProt::NONE`; the hardware
2842/// leaf is installed but the device cannot access it.
2843fn iommu_dma_prot(perms: MmuPerms) -> DmaProt {
2844    let mut bits = 0u8;
2845    if perms.read {
2846        bits |= DmaProt::READ.bits();
2847    }
2848    if perms.write {
2849        bits |= DmaProt::WRITE.bits();
2850    }
2851    match DmaProt::from_bits(bits) {
2852        Some(prot) => prot,
2853        None => DmaProt::NONE,
2854    }
2855}
2856
2857/// Returns (creating it on first use) the host VT-d domain of one PCI
2858/// function assigned to a world.
2859///
2860/// Each successful acquisition takes one logical reference on the hardware
2861/// domain; it is released by [`release_host_iommu_domains`] at world teardown.
2862fn host_iommu_domain(world_id: u64, sbdf: Sbdf) -> Option<Arc<HardwareIommuDomain>> {
2863    let key = (world_id, sbdf.to_u32());
2864    if let Some(domain) = IOMMU_HOST_DOMAINS.lock().get(&key) {
2865        return Some(Arc::clone(domain));
2866    }
2867    let domain = match crate::hardware::iommu::domain_for_owned(sbdf, None, FaultPolicy::Log) {
2868        Ok(domain) => domain,
2869        Err(error) => {
2870            log::warn!(
2871                "[s9vm] iommu: host domain for world={} {} unavailable: {:?}",
2872                world_id,
2873                sbdf,
2874                error
2875            );
2876            return None;
2877        }
2878    };
2879    let mut map = IOMMU_HOST_DOMAINS.lock();
2880    if let Some(existing) = map.get(&key) {
2881        let existing = Arc::clone(existing);
2882        drop(map);
2883        // Another request created the domain first: drop our extra logical
2884        // reference and use the registered one.
2885        let _ = crate::hardware::iommu::release_domain(&domain);
2886        return Some(existing);
2887    }
2888    map.insert(key, Arc::clone(&domain));
2889    Some(domain)
2890}
2891
2892/// Mirrors model segments into the host VT-d backend.
2893///
2894/// Called **without** the world registry lock. Best effort: a missing/not-ready
2895/// backend disables mirroring with a one-time log; a hardware failure is
2896/// logged with the world, device, IOVA and keeps the software model semantics
2897/// (the syscall still succeeds).
2898fn mirror_host_map(world_id: u64, device: u32, segments: &[HostIommuSegment], perms: MmuPerms) {
2899    if segments.is_empty() {
2900        return;
2901    }
2902    if !iommu_host_ready() {
2903        note_iommu_backend_unavailable();
2904        return;
2905    }
2906    let sbdf = Sbdf::from_u32(device);
2907    let Some(domain) = host_iommu_domain(world_id, sbdf) else {
2908        return;
2909    };
2910    let prot = iommu_dma_prot(perms);
2911    let backend = crate::arch::iommu::backend();
2912    // One hardware mapping per model leaf: the granularity must stay exactly
2913    // aligned with the software model so a later (possibly partial) unmap can
2914    // never leave a wider hardware mapping installed than the model allows.
2915    for segment in segments {
2916        match domain.map_kind(segment.iova, segment.phys, segment.len, prot, segment.kind) {
2917            Ok(()) => {}
2918            Err(crate::hardware::iommu::IommuError::BackendNotReady) => {
2919                note_iommu_backend_unavailable();
2920                return;
2921            }
2922            Err(error) => log::warn!(
2923                "[s9vm] iommu: host map failed world={} device={} iova={:#x} \
2924                 len={:#x} kind={:?}: {:?}",
2925                world_id,
2926                sbdf,
2927                segment.iova,
2928                segment.len,
2929                segment.kind,
2930                error
2931            ),
2932        }
2933    }
2934    // One invalidation for the whole batch (the per-leaf backend calls may
2935    // already flush when translation is active).
2936    backend.invalidate_domain(domain.id());
2937}
2938
2939/// Removes a range from the host mirror of one device.
2940///
2941/// Called **without** the world registry lock; best effort like
2942/// [`mirror_host_map`]. When no host domain exists for the pair the call is a
2943/// no-op (the mirror was never installed or the backend was not ready).
2944fn mirror_host_unmap(world_id: u64, device: u32, iova: u64, len: u64) {
2945    if !iommu_host_ready() {
2946        return;
2947    }
2948    let sbdf = Sbdf::from_u32(device);
2949    let key = (world_id, sbdf.to_u32());
2950    let domain = match IOMMU_HOST_DOMAINS.lock().get(&key) {
2951        Some(domain) => Arc::clone(domain),
2952        None => return,
2953    };
2954    let backend = crate::arch::iommu::backend();
2955    match domain.unmap(iova, len) {
2956        Ok(_pages) => backend.invalidate_domain(domain.id()),
2957        Err(crate::hardware::iommu::IommuError::NotMapped) => {
2958            // The mirror may be partial after an earlier best-effort failure;
2959            // the software model remains authoritative.
2960            log::debug!(
2961                "[s9vm] iommu: host unmap found no mirror world={} device={} \
2962                 iova={:#x} len={:#x}",
2963                world_id,
2964                sbdf,
2965                iova,
2966                len
2967            );
2968        }
2969        Err(error) => log::warn!(
2970            "[s9vm] iommu: host unmap failed world={} device={} iova={:#x} \
2971             len={:#x}: {:?}",
2972            world_id,
2973            sbdf,
2974            iova,
2975            len,
2976            error
2977        ),
2978    }
2979}
2980
2981/// Releases every host VT-d domain owned by a world.
2982///
2983/// Called from `destroy_inner` after the world has been removed from the
2984/// registry and **without** the registry lock. The domains are torn down first
2985/// (their mappings are cleared and unmapped from the hardware shadow tables),
2986/// then their logical reference is dropped.
2987fn release_host_iommu_domains(world_id: u64) {
2988    let domains: Vec<Arc<HardwareIommuDomain>> = {
2989        let mut map = IOMMU_HOST_DOMAINS.lock();
2990        let keys: Vec<(u64, u32)> = map
2991            .keys()
2992            .filter(|(world, _)| *world == world_id)
2993            .copied()
2994            .collect();
2995        keys.into_iter()
2996            .filter_map(|key| map.remove(&key))
2997            .collect()
2998    };
2999    for domain in domains {
3000        if !crate::hardware::iommu::release_domain(&domain) {
3001            // A lingering logical reference would keep the hardware domain
3002            // alive: force the teardown rather than leaking a translation
3003            // domain for a destroyed world.
3004            log::warn!(
3005                "[s9vm] iommu: world {} host domain {} still referenced; \
3006                 forcing teardown",
3007                world_id,
3008                domain.id().raw()
3009            );
3010            let _ = crate::hardware::iommu::teardown(domain.id());
3011        }
3012    }
3013}
3014
3015/// Maps an IOVA range of a world to the host frames backing its guest memory.
3016///
3017/// Contract:
3018/// - `iova`/`len` are 4 KiB aligned and `len <= IOMMU_MAX_MAP_BYTES`; with
3019///   `require_2m` both are 2 MiB aligned and every 2 MiB block must be backed
3020///   by a physically contiguous, 2 MiB-aligned host range.
3021/// - Every IOVA page must be backed by the world's guest memory
3022///   (`WorldMemory::translate`); an unmapped GPA returns
3023///   [`IommuError::NotMapped`] and nothing is installed.
3024/// - The device is bound to the world domain (idempotent when already bound).
3025/// - All-or-nothing: on any error the leaves installed by this call are
3026///   removed before returning.
3027///
3028/// When the host VT-d backend is ready (`arch::iommu::backend().is_ready()`),
3029/// the same leaves are mirrored into the host shadow tables **after** the
3030/// registry lock is released: one `hardware::iommu::Domain` per
3031/// `(world, PCI function)`, `map_kind` with 4 KiB / 2 MiB matching the model
3032/// leaf and `DmaProt` derived from `perms`, followed by a domain invalidation.
3033/// The mirror is best effort: a missing/not-ready backend disables it with a
3034/// one-time log, and a hardware failure is logged with world/device/IOVA while
3035/// the software model (authoritative) and the syscall result are unchanged.
3036/// Mappings created before the backend becomes ready are not retroactively
3037/// mirrored.
3038///
3039/// Returns the number of 4 KiB pages covered. The host physical addresses are
3040/// never returned to the caller.
3041pub fn iommu_map(
3042    world_id: u64,
3043    iova: u64,
3044    len: u64,
3045    perms: MmuPerms,
3046    require_2m: bool,
3047    device: u32,
3048) -> Result<u64, IommuError> {
3049    validate_iommu_range(iova, len, require_2m)?;
3050    let pages = len / IOMMU_PAGE_SIZE;
3051    // Host mirror segments are collected under the registry lock (the model
3052    // quota bounds their number) and installed after it is released, so the
3053    // hardware IOMMU layer is never called with the registry lock held.
3054    let mirror_capacity =
3055        core::cmp::min(pages, crate::s9vm::iommu::MAX_ENTRIES_PER_DOMAIN as u64) as usize;
3056    let mut mirror: Vec<HostIommuSegment> = Vec::with_capacity(mirror_capacity);
3057    {
3058        let mut worlds = WORLDS.lock();
3059        let world = worlds.get_mut(&world_id).ok_or(IommuError::UnknownDomain)?;
3060        let domain = iommu_domain(world)?;
3061        let memory = world.memory.as_ref().ok_or(IommuError::NotMapped)?;
3062
3063        if require_2m {
3064            let leaves = len / IOMMU_LARGE_PAGE_SIZE;
3065            let mut done = 0u64;
3066            for leaf in 0..leaves {
3067                let base = iova + leaf * IOMMU_LARGE_PAGE_SIZE;
3068                let hpa = match memory.translate(base) {
3069                    Some(hpa) => hpa,
3070                    None => {
3071                        if done > 0 {
3072                            let _ =
3073                                world
3074                                    .iommu
3075                                    .unmap_2m(domain, iova, done * IOMMU_LARGE_PAGE_SIZE);
3076                        }
3077                        return Err(IommuError::NotMapped);
3078                    }
3079                };
3080                if hpa % IOMMU_LARGE_PAGE_SIZE != 0 {
3081                    if done > 0 {
3082                        let _ = world
3083                            .iommu
3084                            .unmap_2m(domain, iova, done * IOMMU_LARGE_PAGE_SIZE);
3085                    }
3086                    return Err(IommuError::InvalidRange);
3087                }
3088                // A 2 MiB leaf needs a physically contiguous block: verify
3089                // every 4 KiB page of the block maps to the expected
3090                // contiguous HPA.
3091                let block_pages = IOMMU_LARGE_PAGE_SIZE / IOMMU_PAGE_SIZE;
3092                for sub in 1..block_pages {
3093                    let gpa = base + sub * IOMMU_PAGE_SIZE;
3094                    if memory.translate(gpa) != Some(hpa + sub * IOMMU_PAGE_SIZE) {
3095                        if done > 0 {
3096                            let _ =
3097                                world
3098                                    .iommu
3099                                    .unmap_2m(domain, iova, done * IOMMU_LARGE_PAGE_SIZE);
3100                        }
3101                        return Err(IommuError::NotMapped);
3102                    }
3103                }
3104                if let Err(error) =
3105                    world
3106                        .iommu
3107                        .map_2m(domain, base, hpa, IOMMU_LARGE_PAGE_SIZE, perms)
3108                {
3109                    if done > 0 {
3110                        let _ = world
3111                            .iommu
3112                            .unmap_2m(domain, iova, done * IOMMU_LARGE_PAGE_SIZE);
3113                    }
3114                    return Err(error);
3115                }
3116                mirror.push(HostIommuSegment {
3117                    iova: base,
3118                    phys: hpa,
3119                    len: IOMMU_LARGE_PAGE_SIZE,
3120                    kind: MappingKind::Page2M,
3121                });
3122                done += 1;
3123            }
3124        } else {
3125            let mut done = 0u64;
3126            for page in 0..pages {
3127                let gpa = iova + page * IOMMU_PAGE_SIZE;
3128                let hpa = match memory.translate(gpa) {
3129                    Some(hpa) => hpa,
3130                    None => {
3131                        if done > 0 {
3132                            let _ = world.iommu.unmap(domain, iova, done * IOMMU_PAGE_SIZE);
3133                        }
3134                        return Err(IommuError::NotMapped);
3135                    }
3136                };
3137                if let Err(error) = world.iommu.map(domain, gpa, hpa, IOMMU_PAGE_SIZE, perms) {
3138                    if done > 0 {
3139                        let _ = world.iommu.unmap(domain, iova, done * IOMMU_PAGE_SIZE);
3140                    }
3141                    return Err(error);
3142                }
3143                mirror.push(HostIommuSegment {
3144                    iova: gpa,
3145                    phys: hpa,
3146                    len: IOMMU_PAGE_SIZE,
3147                    kind: MappingKind::Page4K,
3148                });
3149                done += 1;
3150            }
3151        }
3152
3153        // Bind the device to the world domain. Binding twice to the same
3154        // domain is idempotent; any other failure rolls the mapping back.
3155        match world.iommu.bind_device(domain, DeviceId(device)) {
3156            Ok(()) | Err(IommuError::AlreadyBound) => {}
3157            Err(error) => {
3158                if require_2m {
3159                    let _ = world.iommu.unmap_2m(domain, iova, len);
3160                } else {
3161                    let _ = world.iommu.unmap(domain, iova, len);
3162                }
3163                return Err(error);
3164            }
3165        }
3166    }
3167    // Registry lock released: mirror into the host VT-d backend, best effort.
3168    mirror_host_map(world_id, device, &mirror, perms);
3169    Ok(pages)
3170}
3171
3172/// Removes an IOVA range of a world from its device translation domain.
3173///
3174/// The range must have been installed by [`iommu_map`] with the same leaf
3175/// size. When the domain becomes empty the device is unbound. Returns the
3176/// number of 4 KiB pages removed.
3177///
3178/// The software model is updated under the registry lock; the host VT-d
3179/// mirror is removed afterwards, without the lock, best effort.
3180pub fn iommu_unmap(
3181    world_id: u64,
3182    iova: u64,
3183    len: u64,
3184    require_2m: bool,
3185    device: u32,
3186) -> Result<u64, IommuError> {
3187    validate_iommu_range(iova, len, require_2m)?;
3188    let pages = {
3189        let mut worlds = WORLDS.lock();
3190        let world = worlds.get_mut(&world_id).ok_or(IommuError::UnknownDomain)?;
3191        if world.closing {
3192            return Err(IommuError::UnknownDomain);
3193        }
3194        let domain = world.iommu_domain.ok_or(IommuError::NotMapped)?;
3195        let pages = if require_2m {
3196            world.iommu.unmap_2m(domain, iova, len)?
3197        } else {
3198            world.iommu.unmap(domain, iova, len)?
3199        };
3200        if world.iommu.mapped_entries(domain) == Some(0) {
3201            let _ = world.iommu.unbind_device(DeviceId(device));
3202        }
3203        pages
3204    };
3205    mirror_host_unmap(world_id, device, iova, len);
3206    Ok(pages)
3207}
3208
3209/// Translates one device-visible address of a world.
3210///
3211/// This is a **kernel-side** diagnostic/device-model accessor: the host
3212/// physical address is never exposed through the syscall ABI.
3213pub fn iommu_translate(world_id: u64, iova: u64) -> Option<u64> {
3214    let mut worlds = WORLDS.lock();
3215    let world = worlds.get_mut(&world_id)?;
3216    if world.closing {
3217        return None;
3218    }
3219    let domain = world.iommu_domain?;
3220    world.iommu.translate(domain, iova)
3221}
3222
3223/// Number of leaves installed in the device translation domain of a world.
3224pub fn iommu_mapped_entries(world_id: u64) -> Option<usize> {
3225    let worlds = WORLDS.lock();
3226    let world = worlds.get(&world_id)?;
3227    world.iommu.mapped_entries(world.iommu_domain?)
3228}
3229
3230/// Next vCPU identifier (global, never 0).
3231static NEXT_VCPU: AtomicU64 = AtomicU64::new(1);
3232
3233/// Creates a logical vCPU in a world and the kernel task that drives it.
3234pub fn create_vcpu(world_id: u64, apic_id: u32) -> Result<u64, VcpuRegistryError> {
3235    // 1. Registers the vCPU without holding the lock during task creation.
3236    let id = {
3237        let mut worlds = WORLDS.lock();
3238        let world = worlds
3239            .get_mut(&world_id)
3240            .ok_or(VcpuRegistryError::WorldUnknown)?;
3241        if world.closing {
3242            return Err(VcpuRegistryError::WorldUnknown);
3243        }
3244        if world.vcpus.len() >= MAX_VCPUS_PER_WORLD {
3245            return Err(VcpuRegistryError::Limit);
3246        }
3247        let id = NEXT_VCPU.fetch_add(1, Ordering::AcqRel);
3248        world.vcpus.push(new_vcpu_slot(id, apic_id));
3249        world.record.vcpu_count = world.vcpus.len() as u32;
3250        id
3251    };
3252    // 2. Creates the vCPU's kernel task (ADR-4 model).
3253    //
3254    // Diagnostics: this path can be called from any task context (including a
3255    // userspace syscall), and a silently dropped kernel task used to be
3256    // indistinguishable from a hang. The three log lines below tell an operator
3257    // exactly where a stuck `SYS_VMM_CREATE_VCPU` stopped.
3258    log::info!("[s9vm] create_vcpu {}: spawning the vCPU kernel task", id);
3259    let task = match kthread::spawn("s9vm-vcpu", move || vcpu_task_main(world_id, id)) {
3260        Ok(task) => task,
3261        Err(_) => {
3262            log::warn!("[s9vm] create_vcpu {}: kernel task spawn failed", id);
3263            let _ = remove_vcpu(id);
3264            return Err(VcpuRegistryError::Thread);
3265        }
3266    };
3267    log::info!(
3268        "[s9vm] create_vcpu {}: kernel task {} spawned",
3269        id,
3270        task.as_u64()
3271    );
3272    // 3. Publishes the task identifier if the vCPU still exists.
3273    {
3274        let mut worlds = WORLDS.lock();
3275        if let Some((world, index)) = locate_slot(&mut worlds, id) {
3276            world.vcpus[index].task = Some(task);
3277        }
3278    }
3279    log::info!("[s9vm] create_vcpu {}: registered", id);
3280    Ok(id)
3281}
3282
3283/// Registers a logical vCPU **without** spawning a kernel task.
3284///
3285/// The slot exists in the registry (so `write_acpi` can describe it, its
3286/// register block can be read and `destroy` has nothing to join), but
3287/// `request_run` is refused: there is no task to wake. Callers that use it
3288/// drive the vCPU with a direct `Vcpu` loop, which keeps the in-kernel
3289/// selftests independent from the scheduler.
3290pub fn create_vcpu_detached(world_id: u64, apic_id: u32) -> Result<u64, VcpuRegistryError> {
3291    let mut worlds = WORLDS.lock();
3292    let world = worlds
3293        .get_mut(&world_id)
3294        .ok_or(VcpuRegistryError::WorldUnknown)?;
3295    if world.closing {
3296        return Err(VcpuRegistryError::WorldUnknown);
3297    }
3298    if world.vcpus.len() >= MAX_VCPUS_PER_WORLD {
3299        return Err(VcpuRegistryError::Limit);
3300    }
3301    let id = NEXT_VCPU.fetch_add(1, Ordering::AcqRel);
3302    world.vcpus.push(new_vcpu_slot(id, apic_id));
3303    world.record.vcpu_count = world.vcpus.len() as u32;
3304    Ok(id)
3305}
3306
3307/// Destroys a logical vCPU. Returns `false` if it is unknown.
3308///
3309/// The kernel task is stopped and joined before the entry is removed: the
3310/// hardware context (control block, host stack, EPT) is never freed during a
3311/// guest entry.
3312pub fn destroy_vcpu(vcpu_id: u64) -> bool {
3313    let (run_wait, done_wait, has_task) = {
3314        let mut worlds = WORLDS.lock();
3315        let Some((world, index)) = locate_slot(&mut worlds, vcpu_id) else {
3316            return false;
3317        };
3318        let slot = &mut world.vcpus[index];
3319        if slot.shutdown {
3320            return false;
3321        }
3322        slot.shutdown = true;
3323        (
3324            Arc::clone(&slot.run_wait),
3325            Arc::clone(&slot.done_wait),
3326            slot.task.is_some(),
3327        )
3328    };
3329    run_wait.wake_all();
3330    done_wait.wake_all();
3331    if has_task {
3332        wait_vcpu_exited(vcpu_id);
3333    }
3334    remove_vcpu(vcpu_id)
3335}
3336
3337/// Body of a vCPU's kernel task: waits for `RUN` requests, runs the guest
3338/// until the next policy exit, publishes the event then waits again.
3339fn vcpu_task_main(world_id: u64, vcpu_id: u64) {
3340    let _ = world_id;
3341    loop {
3342        // Wake-ups: RUN request or shutdown.
3343        let run_wait = {
3344            let mut worlds = WORLDS.lock();
3345            let Some((world, index)) = locate_slot(&mut worlds, vcpu_id) else {
3346                return;
3347            };
3348            let slot = &world.vcpus[index];
3349            if slot.shutdown {
3350                break;
3351            }
3352            Arc::clone(&slot.run_wait)
3353        };
3354        let run = run_wait.wait_until(|| {
3355            let mut worlds = WORLDS.lock();
3356            match locate_slot(&mut worlds, vcpu_id) {
3357                Some((world, index)) => {
3358                    let slot = &mut world.vcpus[index];
3359                    if slot.shutdown {
3360                        Some(false)
3361                    } else if slot.run_requested {
3362                        slot.run_requested = false;
3363                        Some(true)
3364                    } else {
3365                        None
3366                    }
3367                }
3368                None => Some(false),
3369            }
3370        });
3371        if !run {
3372            break;
3373        }
3374
3375        {
3376            let mut worlds = WORLDS.lock();
3377            if let Some((world, index)) = locate_slot(&mut worlds, vcpu_id) {
3378                world.vcpus[index].in_guest = true;
3379            }
3380        }
3381        let result = execute_one_run(vcpu_id);
3382        // Diagnostics: one line per RUN tells an operator whether the vCPU
3383        // task executed at all (a missing line means the task never ran; an
3384        // error here is the reason the guest stopped).
3385        match &result {
3386            Ok(()) => log::info!("[s9vm] vcpu task {}: run executed", vcpu_id),
3387            Err(RunError::NoMemory) => log::info!(
3388                "[s9vm] vcpu task {}: run skipped (the world has no guest memory)",
3389                vcpu_id
3390            ),
3391            Err(error) => log::warn!("[s9vm] vcpu task {}: run failed ({:?})", vcpu_id, error),
3392        }
3393
3394        let done_wait = {
3395            let mut worlds = WORLDS.lock();
3396            let Some((world, index)) = locate_slot(&mut worlds, vcpu_id) else {
3397                return;
3398            };
3399            let slot = &mut world.vcpus[index];
3400            slot.in_guest = false;
3401            slot.runs = slot.runs.saturating_add(1);
3402            slot.run_done = true;
3403            slot.run_in_flight = false;
3404            slot.run_result = Some(result);
3405            Arc::clone(&slot.done_wait)
3406        };
3407        done_wait.wake_all();
3408    }
3409    cleanup_vcpu(vcpu_id);
3410}
3411
3412/// Executes a `RUN` (at most one guest entry) in the vCPU task.
3413fn execute_one_run(vcpu_id: u64) -> Result<(), RunError> {
3414    if crate::s9vm::active_cpu_count() == 0 {
3415        return Err(RunError::HardwareNotReady);
3416    }
3417    let caps = crate::s9vm::detect().ok_or(RunError::HardwareNotReady)?;
3418    // Pin the task to this CPU for the whole RUN. The VMCS is loaded (VMPTRLD)
3419    // on one CPU and cleared (VMCLEAR) at the end of the RUN on that same CPU.
3420    // The STI window opened by `service_pending_host_interrupts` lets the
3421    // timer interrupt run; without this guard it could preempt and migrate the
3422    // task, leaving the VMCS active on the old CPU and skipping the final
3423    // VMCLEAR there. The guard also makes the per-CPU activation check below
3424    // race-free. Interrupts stay masked outside the STI window, so this does
3425    // not lengthen the time other tasks wait on this CPU.
3426    let _pin = crate::sync::preempt::PreemptGuard::new();
3427    // VT-x activation is **per CPU**: the vCPU kernel task can be scheduled on
3428    // a CPU that has never executed `VMXON` (activation at boot only enables
3429    // the boot CPU). Running a guest there would execute VMX instructions
3430    // without a VMXON root and fault the kernel, so the task activates the
3431    // current CPU first (the activation is idempotent and cheap once done).
3432    // `VMXON` expects interrupts disabled.
3433    let activated =
3434        crate::s9vm::activation_region(crate::arch::x86_64::percpu::current_cpu_index()).is_some();
3435    if !activated {
3436        let result = crate::sync::with_irqs_disabled(|_| crate::s9vm::activate_current_cpu());
3437        if result.is_err() {
3438            log::warn!(
3439                "[s9vm] vcpu task: cannot activate VT-x on cpu {}",
3440                crate::arch::x86_64::percpu::current_cpu_index()
3441            );
3442            return Err(RunError::HardwareNotReady);
3443        }
3444    }
3445    // Host interrupts stay disabled during the guest entry: guest time is
3446    // bounded by the next exit (P0). VMX preemption (timer) will come with the
3447    // full preemption model.
3448    crate::sync::with_irqs_disabled(|_| run_vcpu(vcpu_id, &caps))
3449}
3450
3451/// Unloads the hardware context and signals the vCPU task's exit.
3452fn cleanup_vcpu(vcpu_id: u64) {
3453    let hardware = {
3454        let mut worlds = WORLDS.lock();
3455        match locate_slot(&mut worlds, vcpu_id) {
3456            Some((world, index)) => world.vcpus[index].hardware.take(),
3457            None => None,
3458        }
3459    };
3460    if let Some(mut hardware) = hardware {
3461        if crate::s9vm::active_cpu_count() > 0 {
3462            // SAFETY: no guest is running on this vCPU anymore.
3463            unsafe {
3464                let _ = hardware.clear();
3465            }
3466        }
3467    }
3468    let done_wait = {
3469        let mut worlds = WORLDS.lock();
3470        match locate_slot(&mut worlds, vcpu_id) {
3471            Some((world, index)) => {
3472                let slot = &mut world.vcpus[index];
3473                slot.exited = true;
3474                Arc::clone(&slot.done_wait)
3475            }
3476            None => return,
3477        }
3478    };
3479    done_wait.wake_all();
3480}
3481
3482/// Posts a `RUN` request without waiting for the vCPU task.
3483///
3484/// The request is marked in the slot, the vCPU kernel task is woken, and the
3485/// call returns immediately. The caller must collect completion with
3486/// [`wait_run_complete`] (or observe the exit queue). Only one `RUN` may be in
3487/// flight per vCPU; a second request before completion returns
3488/// [`RunError::Busy`].
3489///
3490/// This is the kernel-internal primitive used by the SMP selftest to queue two
3491/// vCPUs back-to-back and measure real overlap; it has no ABI/syscall surface.
3492pub fn request_run_async(vcpu_id: u64) -> Result<(), RunError> {
3493    let run_wait = {
3494        let mut worlds = WORLDS.lock();
3495        let Some((world, index)) = locate_slot(&mut worlds, vcpu_id) else {
3496            return Err(RunError::UnknownVcpu);
3497        };
3498        if world.closing {
3499            return Err(RunError::UnknownVcpu);
3500        }
3501        if world.paused {
3502            return Err(RunError::Paused);
3503        }
3504        let slot = &mut world.vcpus[index];
3505        if slot.shutdown || slot.task.is_none() {
3506            return Err(RunError::UnknownVcpu);
3507        }
3508        if slot.run_in_flight || slot.run_requested {
3509            return Err(RunError::Busy);
3510        }
3511        slot.run_in_flight = true;
3512        slot.run_requested = true;
3513        slot.run_done = false;
3514        slot.run_result = None;
3515        Arc::clone(&slot.run_wait)
3516    };
3517    run_wait.wake_one();
3518    Ok(())
3519}
3520
3521/// Waits, at most `timeout_ns`, for a previously posted `RUN` to complete.
3522///
3523/// Returns the result published by the vCPU task (`Ok` or a `RunError`), or
3524/// [`RunError::Timeout`] when the task did not finish within the budget. The
3525/// timed-out request stays in flight; the caller must not post another `RUN`
3526/// until it completes.
3527pub fn wait_run_complete(vcpu_id: u64, timeout_ns: u64) -> Result<(), RunError> {
3528    let budget_ticks = (timeout_ns / crate::arch::timer::NS_PER_TICK).max(1);
3529    let deadline = ticks().saturating_add(budget_ticks);
3530    loop {
3531        {
3532            let mut worlds = WORLDS.lock();
3533            match locate_slot(&mut worlds, vcpu_id) {
3534                Some((world, index)) => {
3535                    let slot = &mut world.vcpus[index];
3536                    if slot.run_done {
3537                        return slot.run_result.take().unwrap_or(Ok(()));
3538                    }
3539                }
3540                None => return Err(RunError::UnknownVcpu),
3541            }
3542        }
3543        if ticks() >= deadline {
3544            return Err(RunError::Timeout);
3545        }
3546        sleep_current_task_ticks(1);
3547    }
3548}
3549
3550/// Diagnostic state of the last `RUN` of a vCPU.
3551///
3552/// Returns `(done, in_flight, result)`. The result is `Some` as soon as the
3553/// vCPU task published the outcome of the run, so a caller that observes a
3554/// missing exit can distinguish "the run failed" from "the task never ran":
3555/// without it the only visible symptom is a timeout.
3556pub fn run_completion(vcpu_id: u64) -> Option<(bool, bool, Option<Result<(), RunError>>)> {
3557    let mut worlds = WORLDS.lock();
3558    let (world, index) = locate_slot(&mut worlds, vcpu_id)?;
3559    let slot = &world.vcpus[index];
3560    Some((slot.run_done, slot.run_in_flight, slot.run_result))
3561}
3562
3563/// Requests execution of a vCPU and **blocks** the caller until the end of
3564/// that `RUN` (at most one policy exit).
3565///
3566/// Only one `RUN` can be in flight per vCPU; a second concurrent call receives
3567/// [`RunError::Busy`].
3568pub fn request_run(vcpu_id: u64) -> Result<(), RunError> {
3569    request_run_inner(vcpu_id, None)
3570}
3571
3572/// Requests execution of a vCPU and waits at most `timeout_ns` for the end of
3573/// that `RUN`.
3574///
3575/// Returns [`RunError::Timeout`] if the vCPU task did not complete the request
3576/// within the budget. The request stays queued (`run_in_flight`), so a late
3577/// completion still clears the slot; the caller must treat the timeout as a
3578/// defect and must not issue another `RUN` before it completes.
3579pub fn request_run_timeout(vcpu_id: u64, timeout_ns: u64) -> Result<(), RunError> {
3580    request_run_async(vcpu_id)?;
3581    wait_run_complete(vcpu_id, timeout_ns)
3582}
3583
3584fn request_run_inner(vcpu_id: u64, timeout_ns: Option<u64>) -> Result<(), RunError> {
3585    let (run_wait, done_wait) = {
3586        let mut worlds = WORLDS.lock();
3587        let Some((world, index)) = locate_slot(&mut worlds, vcpu_id) else {
3588            return Err(RunError::UnknownVcpu);
3589        };
3590        if world.closing {
3591            return Err(RunError::UnknownVcpu);
3592        }
3593        if world.paused {
3594            return Err(RunError::Paused);
3595        }
3596        let slot = &mut world.vcpus[index];
3597        if slot.shutdown || slot.task.is_none() {
3598            return Err(RunError::UnknownVcpu);
3599        }
3600        if slot.run_in_flight || slot.run_requested {
3601            return Err(RunError::Busy);
3602        }
3603        slot.run_in_flight = true;
3604        slot.run_requested = true;
3605        slot.run_done = false;
3606        slot.run_result = None;
3607        (Arc::clone(&slot.run_wait), Arc::clone(&slot.done_wait))
3608    };
3609    run_wait.wake_one();
3610
3611    if let Some(timeout_ns) = timeout_ns {
3612        let budget_ticks = (timeout_ns / crate::arch::timer::NS_PER_TICK).max(1);
3613        let deadline = ticks().saturating_add(budget_ticks);
3614        loop {
3615            {
3616                let mut worlds = WORLDS.lock();
3617                match locate_slot(&mut worlds, vcpu_id) {
3618                    Some((world, index)) => {
3619                        let slot = &mut world.vcpus[index];
3620                        if slot.run_done {
3621                            return slot.run_result.take().unwrap_or(Ok(()));
3622                        }
3623                    }
3624                    None => return Err(RunError::UnknownVcpu),
3625                }
3626            }
3627            if ticks() >= deadline {
3628                return Err(RunError::Timeout);
3629            }
3630            sleep_current_task_ticks(1);
3631        }
3632    }
3633
3634    done_wait
3635        .wait_until(|| {
3636            let mut worlds = WORLDS.lock();
3637            match locate_slot(&mut worlds, vcpu_id) {
3638                Some((world, index)) => {
3639                    let slot = &mut world.vcpus[index];
3640                    if slot.run_done {
3641                        Some(slot.run_result.take())
3642                    } else {
3643                        None
3644                    }
3645                }
3646                None => Some(Some(Err(RunError::UnknownVcpu))),
3647            }
3648        })
3649        .unwrap_or(Err(RunError::UnknownVcpu))
3650}
3651
3652/// Waits until at least one exit event is available in the vCPU's world, or
3653/// until the timeout expires.
3654///
3655/// `timeout_ns = 0` tests immediately (no wait). Returns `true` if an event is
3656/// pending, `false` on timeout.
3657pub fn wait_exit(vcpu_id: u64, timeout_ns: u64) -> Result<bool, VcpuRegistryError> {
3658    let world_id = {
3659        let mut worlds = WORLDS.lock();
3660        let Some((world, index)) = locate_slot(&mut worlds, vcpu_id) else {
3661            return Err(VcpuRegistryError::Unknown);
3662        };
3663        if world.closing || world.vcpus[index].shutdown {
3664            return Err(VcpuRegistryError::Unknown);
3665        }
3666        world.record.id
3667    };
3668    if exit_count(world_id).unwrap_or(0) > 0 {
3669        return Ok(true);
3670    }
3671    if timeout_ns == 0 {
3672        return Ok(false);
3673    }
3674    let budget_ticks = (timeout_ns / crate::arch::timer::NS_PER_TICK).max(1);
3675    let deadline = ticks().saturating_add(budget_ticks);
3676    loop {
3677        if exit_count(world_id).unwrap_or(0) > 0 {
3678            return Ok(true);
3679        }
3680        if ticks() >= deadline {
3681            return Ok(false);
3682        }
3683        sleep_current_task_ticks(1);
3684    }
3685}
3686
3687/// Completes an exit that the policy emulated: writes the result value to
3688/// the guest `RAX` and adds `advance` bytes to the guest `RIP`.
3689///
3690/// `advance` is 0 for exits that already advanced `RIP` (I/O instructions);
3691/// it is the instruction length for exits that must be retried or skipped
3692/// after emulation (EPT violations, MMIO). Only the software register block is
3693/// updated: the next `RUN` rebuilds the guest state from it.
3694pub fn complete_exit(vcpu_id: u64, value: u64, advance: u64) -> Result<(), VcpuRegistryError> {
3695    let mut worlds = WORLDS.lock();
3696    let world = vcpu_world_mut(&mut worlds, vcpu_id).ok_or(VcpuRegistryError::Unknown)?;
3697    let slot = world
3698        .vcpus
3699        .iter_mut()
3700        .find(|slot| slot.id == vcpu_id)
3701        .ok_or(VcpuRegistryError::Unknown)?;
3702    slot.regs.rax = value;
3703    slot.regs.rip = slot.regs.rip.wrapping_add(advance);
3704    Ok(())
3705}
3706
3707/// Schedules the injection of an external interrupt into a vCPU.
3708///
3709/// The injection is deferred: the vector is remembered and written into the
3710/// "VM-entry interruption information" field at the next `run_vcpu`. Returns
3711/// `Unknown` if the vCPU does not exist.
3712pub fn inject_irq(vcpu_id: u64, vector: u8) -> Result<(), VcpuRegistryError> {
3713    let mut worlds = WORLDS.lock();
3714    let world = vcpu_world_mut(&mut worlds, vcpu_id).ok_or(VcpuRegistryError::Unknown)?;
3715    let slot = world
3716        .vcpus
3717        .iter_mut()
3718        .find(|slot| slot.id == vcpu_id)
3719        .ok_or(VcpuRegistryError::Unknown)?;
3720    // The local APIC is the single delivery path: the vector waits in the IRR
3721    // until the guest is interruptible (the execution loop injects it and
3722    // arms the interrupt window when needed).
3723    slot.apic.inject(vector);
3724    Ok(())
3725}
3726
3727/// Schedules the injection of an NMI into a vCPU (delivered at the next
3728/// `RUN`).
3729pub fn inject_nmi(vcpu_id: u64) -> Result<(), VcpuRegistryError> {
3730    let mut worlds = WORLDS.lock();
3731    let world = vcpu_world_mut(&mut worlds, vcpu_id).ok_or(VcpuRegistryError::Unknown)?;
3732    let slot = world
3733        .vcpus
3734        .iter_mut()
3735        .find(|slot| slot.id == vcpu_id)
3736        .ok_or(VcpuRegistryError::Unknown)?;
3737    slot.pending_nmi = true;
3738    Ok(())
3739}
3740
3741/// Pauses a world (`RUN` refused until resumed).
3742pub fn pause(world_id: u64) -> Result<(), VmError> {
3743    let mut worlds = WORLDS.lock();
3744    let world = worlds.get_mut(&world_id).ok_or(VmError::Unknown)?;
3745    if world.closing {
3746        return Err(VmError::Unknown);
3747    }
3748    world.paused = true;
3749    world.record.state = strat9_abi::vmm::state::PAUSED;
3750    Ok(())
3751}
3752
3753/// Resumes a paused world.
3754pub fn resume(world_id: u64) -> Result<(), VmError> {
3755    let mut worlds = WORLDS.lock();
3756    let world = worlds.get_mut(&world_id).ok_or(VmError::Unknown)?;
3757    if world.closing {
3758        return Err(VmError::Unknown);
3759    }
3760    world.paused = false;
3761    world.record.state = strat9_abi::vmm::state::RUNNING;
3762    Ok(())
3763}
3764
3765/// True if the world is paused.
3766pub fn is_paused(world_id: u64) -> bool {
3767    WORLDS
3768        .lock()
3769        .get(&world_id)
3770        .map(|world| world.paused)
3771        .unwrap_or(false)
3772}
3773
3774/// Pending deliverable interrupt vector for a vCPU, if any.
3775pub fn pending_irq(vcpu_id: u64) -> Option<u8> {
3776    let mut worlds = WORLDS.lock();
3777    let world = vcpu_world_mut(&mut worlds, vcpu_id)?;
3778    world
3779        .vcpus
3780        .iter()
3781        .find(|slot| slot.id == vcpu_id)
3782        .and_then(|slot| slot.apic.pending_vector())
3783}
3784
3785/// Finds the world owning a vCPU (excluding closing worlds).
3786fn vcpu_world_mut(worlds: &mut WorldMap, vcpu_id: u64) -> Option<&mut World> {
3787    worlds
3788        .values_mut()
3789        .find(|world| !world.closing && world.vcpus.iter().any(|slot| slot.id == vcpu_id))
3790        .map(Box::as_mut)
3791}
3792
3793/// Writes a vCPU's register block.
3794pub fn set_vcpu_regs(
3795    vcpu_id: u64,
3796    regs: &strat9_abi::vmm::VmmRegs,
3797) -> Result<(), VcpuRegistryError> {
3798    if regs.abi_version != strat9_abi::vmm::VMM_ABI_VERSION {
3799        return Err(VcpuRegistryError::BadAbiVersion);
3800    }
3801    let mut worlds = WORLDS.lock();
3802    let world = vcpu_world_mut(&mut worlds, vcpu_id).ok_or(VcpuRegistryError::Unknown)?;
3803    let slot = world
3804        .vcpus
3805        .iter_mut()
3806        .find(|slot| slot.id == vcpu_id)
3807        .ok_or(VcpuRegistryError::Unknown)?;
3808    slot.regs = *regs;
3809    Ok(())
3810}
3811
3812/// Reads a vCPU's register block.
3813pub fn get_vcpu_regs(vcpu_id: u64) -> Option<strat9_abi::vmm::VmmRegs> {
3814    let worlds = WORLDS.lock();
3815    for world in worlds.values() {
3816        if let Some(slot) = world.vcpus.iter().find(|slot| slot.id == vcpu_id) {
3817            return Some(slot.regs);
3818        }
3819    }
3820    None
3821}
3822
3823/// Number of logical vCPUs of a world.
3824pub fn vcpu_count(world_id: u64) -> Option<u32> {
3825    WORLDS
3826        .lock()
3827        .get(&world_id)
3828        .map(|world| world.vcpus.len() as u32)
3829}
3830
3831/// Sets the guest CPU description (CPUID policy) of a world.
3832///
3833/// The policy belongs to the world, not to a vCPU: the device model and the
3834/// CPUID replay live in the world's `Machine`, so every vCPU of the world
3835/// observes the same CPU. Returns `false` when the world does not exist.
3836pub fn set_cpuid_policy(world_id: u64, policy: crate::s9vm::cpuid::CpuidPolicy) -> bool {
3837    let mut worlds = WORLDS.lock();
3838    match worlds.get_mut(&world_id) {
3839        Some(world) => {
3840            world.machine.set_cpuid_policy(policy);
3841            true
3842        }
3843        None => false,
3844    }
3845}
3846
3847/// Current guest CPU description (CPUID policy) of a world.
3848pub fn cpuid_policy(world_id: u64) -> Option<crate::s9vm::cpuid::CpuidPolicy> {
3849    WORLDS
3850        .lock()
3851        .get(&world_id)
3852        .map(|world| world.machine.cpuid_policy())
3853}
3854
3855/// Diagnostic detail for a world: mapped pages and translation of a GPA.
3856pub fn debug_translate(id: u64, gpa: u64) -> Option<u64> {
3857    let memory_ref = {
3858        let worlds = WORLDS.lock();
3859        let world = worlds.get(&id)?;
3860        // A reference cannot be handed out beyond the lock: the translation is
3861        // copied before it is released.
3862        world
3863            .memory
3864            .as_ref()
3865            .and_then(|memory| memory.translate(gpa))
3866    };
3867    memory_ref
3868}
3869
3870/// Frees all entries (tests and kernel shutdown).
3871pub fn clear() {
3872    let worlds: WorldMap = {
3873        let mut guard = WORLDS.lock();
3874        core::mem::take(&mut *guard)
3875    };
3876    for (_, world) in worlds {
3877        if let Some(memory) = world.memory {
3878            memory.destroy();
3879        }
3880    }
3881}