Skip to main content

strat9_kernel/syscall/
vmm.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 : handlers for the `SYS_VMM_*` syscalls (ABI block 560–589).
24//!
25//! P0 scope: management of the world registry (`CREATE`, `DESTROY`,
26//! `INFO`) and the execution surface driven by the injected exits. The
27//! appended P1 calls `LIST` (584) and `STATS` (585) expose the world registry
28//! and the cumulative engine counters without growing `VmmInfo`; `LOAD_IMAGE`
29//! (586) and `ACPI` (587) prepare a guest, and the per-vCPU introspection pair
30//! `VCPU_LIST` (588) / `VCPU_REGS` (589) publishes the vCPU snapshot and
31//! register block.
32//! The calls that depend on guest execution (`MAP_MEM`, `SET_REGS`, `RUN`,
33//! `INJECT_IRQ`, `EXIT_HANDLER`, `IRQ_WAIT`) are implemented by the vCPU
34//! layer; their ABI is frozen.
35//!
36//! Access control: `CREATE` requires silo administration; the other calls
37//! take a **capability handle** returned by `CREATE`
38//! (`ResourceType::Vmm`) or `CREATE_VCPU` (`ResourceType::Vcpu`). The handle
39//! is opaque to user space; internal identifiers are never accepted
40//! directly.
41
42use super::error::SyscallError;
43use crate::{
44    capability::{get_capability_manager, CapId, CapPermissions, ResourceType},
45    memory::{UserSliceRead, UserSliceWrite},
46    process::current_task_clone,
47    s9vm,
48    s9vm::{
49        cpuid::{self, CpuidPolicy},
50        iommu::IommuError,
51        memmap::MapError,
52        vm::{self, VmError},
53    },
54    silo,
55};
56use alloc::vec;
57use strat9_abi::vmm::{
58    iommu_flags, state, vcpu_flags, VmmCpuidPolicy, VmmImageInfo, VmmInfo, VmmIommuMap, VmmRegs,
59    VmmVcpuInfo, VmmWorldEntry, VmmWorldStats, VMM_ABI_VERSION, VMM_CMDLINE_MAX,
60    VMM_DISK_MAX_BYTES, VMM_DISK_SECTOR_SIZE, VMM_IOMMU_MAX_MAP_BYTES, VMM_LIST_MAX,
61    VMM_MODULE_MAX_BYTES, VMM_NAME_MAX, VMM_VCPU_LIST_MAX,
62};
63
64/// Maximum size of a structure read from user space.
65const MAX_STRUCT: usize = 192;
66
67/// Timeout applied to one `SYS_VMM_RUN` (10 s).
68///
69/// A guest that never reaches a policy exit (stuck vCPU task, pathological
70/// exit loop) must not block the caller forever: `RUN` returns
71/// [`SyscallError::TimedOut`] after this budget. The vCPU may still be busy at
72/// that point, so the caller must destroy the world rather than retry; the
73/// kernel logs the vCPU task state to help diagnose the defect.
74const RUN_TIMEOUT_NS: u64 = 10_000_000_000;
75
76/// Maximum size of a guest image accepted by `SYS_VMM_LOAD_IMAGE`.
77///
78/// The bytes are copied into a temporary kernel buffer before the loader parses
79/// them, so this bound also protects kernel memory.
80const MAX_IMAGE_BYTES: u64 = 16 * 1024 * 1024;
81
82/// Maximum number of entries written by one `SYS_VMM_LIST` call.
83///
84/// Mirrors [`VMM_LIST_MAX`] and the kernel world bound; clamping here keeps a
85/// single syscall bounded even if the caller passes a huge capacity.
86const MAX_LIST_ENTRIES: usize = VMM_LIST_MAX;
87
88/// Maximum number of entries written by one `SYS_VMM_VCPU_LIST` call.
89///
90/// Mirrors [`VMM_VCPU_LIST_MAX`] and the kernel per-world vCPU bound; clamping
91/// here keeps a single syscall bounded even if the caller passes a huge
92/// capacity.
93const MAX_VCPU_LIST_ENTRIES: usize = VMM_VCPU_LIST_MAX;
94
95// The ABI bound must mirror the engine bound: reporting more would need more
96// entries than a world can ever hold, and reporting fewer would truncate a
97// per-world listing.
98const _: () = assert!(VMM_VCPU_LIST_MAX == vm::MAX_VCPUS_PER_WORLD);
99
100/// Rights of a world creator: read, write, revoke.
101const VMM_OWNER: CapPermissions = CapPermissions {
102    read: true,
103    write: true,
104    execute: false,
105    grant: false,
106    revoke: true,
107};
108
109/// Rights of a vCPU: read, write, execute (`RUN`).
110const VCPU_OWNER: CapPermissions = CapPermissions {
111    read: true,
112    write: true,
113    execute: true,
114    grant: false,
115    revoke: true,
116};
117
118/// `CREATE` remains a silo administration operation: creating a world is
119/// not covered by an existing capability.
120fn require_control() -> Result<(), SyscallError> {
121    silo::require_silo_admin()
122}
123
124/// Installs a capability in the current task and returns its handle.
125fn install_handle(
126    resource_type: ResourceType,
127    resource: u64,
128    permissions: CapPermissions,
129) -> Result<u64, SyscallError> {
130    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
131    let capability =
132        get_capability_manager().create_capability(resource_type, resource as usize, permissions);
133    // SAFETY: the task's capability table is protected by the
134    // `CapabilityTable` API; the pattern is identical to the other kernel
135    // handle creations.
136    let id = unsafe { (&*task.process.capabilities.get()).insert(capability) };
137    Ok(id.as_u64())
138}
139
140/// Resolves a capability handle to an internal resource identifier.
141fn resolve_handle(
142    handle: u64,
143    expected: ResourceType,
144    required: CapPermissions,
145) -> Result<u64, SyscallError> {
146    if handle == 0 {
147        return Err(SyscallError::InvalidArgument);
148    }
149    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
150    // SAFETY: the table is internally synchronized.
151    let capabilities = unsafe { &*task.process.capabilities.get() };
152    let capability = capabilities
153        .get_with_permissions(CapId::from_raw(handle), required)
154        .ok_or(SyscallError::PermissionDenied)?;
155    if capability.resource_type != expected {
156        return Err(SyscallError::BadHandle);
157    }
158    Ok(capability.resource as u64)
159}
160
161/// Revokes a handle (removes the capability from the task and from the
162/// global registry).
163fn revoke_handle(handle: u64) {
164    let Some(task) = current_task_clone() else {
165        return;
166    };
167    // SAFETY: access under the protection of `CapabilityTable`; it is
168    // internally synchronized.
169    let capabilities = unsafe { &*task.process.capabilities.get() };
170    let _ = capabilities.remove(CapId::from_raw(handle));
171}
172
173/// Resolves a world handle (`ResourceType::Vmm`).
174fn vmm_world(handle: u64, required: CapPermissions) -> Result<u64, SyscallError> {
175    resolve_handle(handle, ResourceType::Vmm, required)
176}
177
178/// Resolves a vCPU handle (`ResourceType::Vcpu`).
179fn vcpu_target(handle: u64, required: CapPermissions) -> Result<u64, SyscallError> {
180    resolve_handle(handle, ResourceType::Vcpu, required)
181}
182
183fn read_struct<T: Copy>(ptr: u64) -> Result<T, SyscallError> {
184    if ptr == 0 {
185        return Err(SyscallError::Fault);
186    }
187    let size = core::mem::size_of::<T>();
188    let mut raw = [0u8; MAX_STRUCT];
189    if size == 0 || size > raw.len() {
190        return Err(SyscallError::InvalidArgument);
191    }
192    let slice = UserSliceRead::new(ptr, size)?;
193    if slice.copy_to(&mut raw[..size]) != size {
194        return Err(SyscallError::Fault);
195    }
196    // SAFETY: `raw[..size]` is fully initialized and `T: Copy`.
197    Ok(unsafe { core::ptr::read_unaligned(raw.as_ptr() as *const T) })
198}
199
200fn write_struct<T: Copy>(ptr: u64, value: &T) -> Result<(), SyscallError> {
201    if ptr == 0 {
202        return Err(SyscallError::Fault);
203    }
204    let size = core::mem::size_of::<T>();
205    let slice = UserSliceWrite::new(ptr, size)?;
206    // SAFETY: read of `size` bytes from a valid reference.
207    let bytes = unsafe { core::slice::from_raw_parts(value as *const T as *const u8, size) };
208    slice.copy_from(bytes);
209    Ok(())
210}
211
212/// SYS_VMM_CREATE (560): creates a virtual world.
213pub fn sys_vmm_create(name_ptr: u64, name_len: u64, silo_id: u64) -> Result<u64, SyscallError> {
214    require_control()?;
215    if !s9vm::detected() {
216        return Err(SyscallError::NotSupported);
217    }
218    if name_len == 0 || name_len > vm::NAME_MAX as u64 {
219        return Err(SyscallError::InvalidArgument);
220    }
221    if silo_id > u32::MAX as u64 {
222        return Err(SyscallError::InvalidArgument);
223    }
224    let mut name = [0u8; vm::NAME_MAX];
225    let slice = UserSliceRead::new(name_ptr, name_len as usize)?;
226    if slice.copy_to(&mut name[..name_len as usize]) != name_len as usize {
227        return Err(SyscallError::Fault);
228    }
229    let record =
230        vm::create(&name[..name_len as usize], silo_id as u32).ok_or(SyscallError::OutOfMemory)?;
231    match install_handle(ResourceType::Vmm, record.id, VMM_OWNER) {
232        Ok(handle) => Ok(handle),
233        Err(error) => {
234            let _ = vm::destroy(record.id);
235            Err(error)
236        }
237    }
238}
239
240/// SYS_VMM_DESTROY (561): destroys a world.
241pub fn sys_vmm_destroy(vmm_handle: u64) -> Result<u64, SyscallError> {
242    let required = CapPermissions {
243        revoke: true,
244        ..VMM_OWNER
245    };
246    let world = vmm_world(vmm_handle, required)?;
247    vm::destroy(world).ok_or(SyscallError::NotFound)?;
248    revoke_handle(vmm_handle);
249    Ok(0)
250}
251
252/// SYS_VMM_MAP_MEM (562): maps guest RAM into a world.
253///
254/// `perms`: bits 1 = read, 2 = write, 4 = execute (0 = read).
255/// `memtype`: 0 = write-back (the only type supported for now).
256pub fn sys_vmm_map_mem(
257    vmm_id: u64,
258    gpa: u64,
259    len: u64,
260    perms: u64,
261    memtype: u64,
262) -> Result<u64, SyscallError> {
263    let required = CapPermissions {
264        write: true,
265        ..CapPermissions::none()
266    };
267    let world = vmm_world(vmm_id, required)?;
268    let caps = s9vm::detect().ok_or(SyscallError::NotSupported)?;
269    if perms > 0b111 || memtype > 6 {
270        return Err(SyscallError::InvalidArgument);
271    }
272    if memtype != 0 && memtype != 6 {
273        return Err(SyscallError::NotSupported);
274    }
275    vm::map_memory(world, &caps, gpa, len, perms as u32, memtype as u8).map_err(map_vm_error)
276}
277
278/// SYS_VMM_SET_REGS (563): writes a vCPU's register block.
279pub fn sys_vmm_set_regs(vcpu_handle: u64, regs_ptr: u64) -> Result<u64, SyscallError> {
280    let required = CapPermissions {
281        write: true,
282        ..CapPermissions::none()
283    };
284    let vcpu = vcpu_target(vcpu_handle, required)?;
285    let regs: VmmRegs = read_struct(regs_ptr)?;
286    vm::set_vcpu_regs(vcpu, &regs).map_err(map_vcpu_error)?;
287    Ok(0)
288}
289
290/// SYS_VMM_GET_REGS (564): reads a vCPU's register block.
291pub fn sys_vmm_get_regs(vcpu_handle: u64, regs_ptr: u64) -> Result<u64, SyscallError> {
292    let required = CapPermissions {
293        read: true,
294        ..CapPermissions::none()
295    };
296    let vcpu = vcpu_target(vcpu_handle, required)?;
297    let regs = vm::get_vcpu_regs(vcpu).ok_or(SyscallError::NotFound)?;
298    write_struct(regs_ptr, &regs)?;
299    Ok(0)
300}
301
302/// SYS_VMM_CREATE_VCPU (570): creates a logical vCPU in a world.
303pub fn sys_vmm_create_vcpu(vmm_handle: u64, apic_id: u64) -> Result<u64, SyscallError> {
304    let required = CapPermissions {
305        write: true,
306        ..CapPermissions::none()
307    };
308    let world = vmm_world(vmm_handle, required)?;
309    if apic_id > u32::MAX as u64 {
310        return Err(SyscallError::InvalidArgument);
311    }
312    let vcpu = vm::create_vcpu(world, apic_id as u32).map_err(map_vcpu_error)?;
313    match install_handle(ResourceType::Vcpu, vcpu, VCPU_OWNER) {
314        Ok(handle) => Ok(handle),
315        Err(error) => {
316            let _ = vm::destroy_vcpu(vcpu);
317            Err(error)
318        }
319    }
320}
321
322/// SYS_VMM_DESTROY_VCPU (571): destroys a logical vCPU.
323pub fn sys_vmm_destroy_vcpu(vcpu_handle: u64) -> Result<u64, SyscallError> {
324    let required = CapPermissions {
325        revoke: true,
326        ..VCPU_OWNER
327    };
328    let vcpu = vcpu_target(vcpu_handle, required)?;
329    if !vm::destroy_vcpu(vcpu) {
330        return Err(SyscallError::NotFound);
331    }
332    revoke_handle(vcpu_handle);
333    Ok(0)
334}
335
336/// SYS_VMM_RUN (565): runs a vCPU until the next "policy" exit and pushes
337/// the event onto the world's queue.
338///
339/// The call is blocked until the exit event is queued **or** until
340/// [`RUN_TIMEOUT_NS`] expires. On timeout the vCPU task may still be busy, so
341/// the caller must destroy the world (the kernel log carries the vCPU task
342/// diagnostic); retrying `RUN` would just hit the same stuck task.
343pub fn sys_vmm_run(vcpu_handle: u64) -> Result<u64, SyscallError> {
344    let required = CapPermissions {
345        execute: true,
346        write: true,
347        ..CapPermissions::none()
348    };
349    let vcpu = vcpu_target(vcpu_handle, required)?;
350    vm::request_run_timeout(vcpu, RUN_TIMEOUT_NS).map_err(map_run_error)?;
351    Ok(0)
352}
353
354/// SYS_VMM_INJECT_IRQ (566): schedules the injection of an external
355/// interrupt into a vCPU; it will be delivered on the next guest entry.
356///
357/// `vector` must be a valid vector (0..=255). The injection is deferred:
358/// the vector is stored in the vCPU and written to the control block on the
359/// next `RUN`.
360pub fn sys_vmm_inject_irq(vcpu_handle: u64, vector: u64) -> Result<u64, SyscallError> {
361    let required = CapPermissions {
362        write: true,
363        ..CapPermissions::none()
364    };
365    let vcpu = vcpu_target(vcpu_handle, required)?;
366    if vector > u8::MAX as u64 {
367        return Err(SyscallError::InvalidArgument);
368    }
369    vm::inject_irq(vcpu, vector as u8).map_err(map_vcpu_error)?;
370    Ok(0)
371}
372
373/// SYS_VMM_EXIT_HANDLER (567): pops an exit event.
374///
375/// Returns 1 if an event was written, 0 if the queue is empty.
376pub fn sys_vmm_exit_handler(vmm_handle: u64, event_ptr: u64) -> Result<u64, SyscallError> {
377    let required = CapPermissions {
378        read: true,
379        ..CapPermissions::none()
380    };
381    let world = vmm_world(vmm_handle, required)?;
382    let event = match vm::pop_exit(world) {
383        Ok(event) => event,
384        Err(()) => return Ok(0),
385    };
386    write_struct(event_ptr, &event)?;
387    Ok(1)
388}
389
390/// SYS_VMM_IRQ_WAIT (568): waits for a vCPU exit event.
391///
392/// Returns 1 if an event is available, 0 if `timeout_ns` expires first
393/// (`timeout_ns = 0` tests immediately).
394pub fn sys_vmm_irq_wait(vcpu_handle: u64, timeout_ns: u64) -> Result<u64, SyscallError> {
395    let required = CapPermissions {
396        read: true,
397        ..CapPermissions::none()
398    };
399    let vcpu = vcpu_target(vcpu_handle, required)?;
400    let ready = vm::wait_exit(vcpu, timeout_ns).map_err(map_vcpu_error)?;
401    Ok(u64::from(ready))
402}
403
404/// SYS_VMM_SET_CPUID_POLICY (573): replaces the guest CPU description of a
405/// world.
406///
407/// `arg1` is the world capability handle (write permission required) and
408/// `arg2` a pointer to a [`VmmCpuidPolicy`]. The policy belongs to the world
409/// and applies from the next guest entry: every vCPU of the world then
410/// observes the same CPU. A feature bit the engine refuses (nested
411/// virtualization) is silently cleared, and a zero numeric field or feature
412/// mask keeps the engine default, so a caller can tune only what it cares
413/// about.
414pub fn sys_vmm_set_cpuid_policy(vmm_handle: u64, policy_ptr: u64) -> Result<u64, SyscallError> {
415    let required = CapPermissions {
416        write: true,
417        ..CapPermissions::none()
418    };
419    let world = vmm_world(vmm_handle, required)?;
420    let request: VmmCpuidPolicy = read_struct(policy_ptr)?;
421    if request.abi_version != VMM_ABI_VERSION {
422        return Err(SyscallError::InvalidArgument);
423    }
424    let policy = cpuid_policy_from_abi(&request)?;
425    if !vm::set_cpuid_policy(world, policy) {
426        return Err(SyscallError::NotFound);
427    }
428    Ok(0)
429}
430
431/// SYS_VMM_MAP_IOMMU (572): programs the device translation domain of a
432/// world.
433///
434/// `arg1` = VMM capability handle (write permission required),
435/// `arg2` = pointer to a [`VmmIommuMap`]. Exactly one of
436/// [`iommu_flags::MAP`] / [`iommu_flags::UNMAP`] must be set; `REQUIRE_2M`
437/// additionally enforces 2 MiB alignment on both the IOVA range and the
438/// backing host memory.
439///
440/// `MAP`: every IOVA page of the request is resolved through the world's
441/// guest memory; an address not backed by mapped guest RAM returns `ENOENT`
442/// and nothing is installed (all-or-nothing). The device is bound to the
443/// world domain. `UNMAP`: the range must have been installed with the same
444/// leaf size, otherwise `ENOENT`.
445///
446/// Never returns a host physical address: the translation is kernel-side
447/// only.
448///
449/// When the host VT-d backend is ready, the kernel also mirrors the mapping
450/// into the host shadow tables (best effort, after the world registry lock is
451/// released). Backend absence or a hardware programming failure is logged and
452/// does **not** change the syscall result: the software model is
453/// authoritative.
454pub fn sys_vmm_map_iommu(vmm_handle: u64, req_ptr: u64) -> Result<u64, SyscallError> {
455    let required = CapPermissions {
456        write: true,
457        ..CapPermissions::none()
458    };
459    let world = vmm_world(vmm_handle, required)?;
460    let request: VmmIommuMap = read_struct(req_ptr)?;
461    if request.abi_version != VMM_ABI_VERSION || request.reserved != 0 {
462        return Err(SyscallError::InvalidArgument);
463    }
464    if request.flags & !iommu_flags::ALL != 0 {
465        return Err(SyscallError::InvalidArgument);
466    }
467    let map = request.flags & iommu_flags::MAP != 0;
468    let unmap = request.flags & iommu_flags::UNMAP != 0;
469    // Exactly one operation; MAP|UNMAP or neither is a caller bug.
470    if map == unmap {
471        return Err(SyscallError::InvalidArgument);
472    }
473    let require_2m = request.flags & iommu_flags::REQUIRE_2M != 0;
474    if request.length == 0 || request.length > VMM_IOMMU_MAX_MAP_BYTES {
475        return Err(SyscallError::InvalidArgument);
476    }
477    if request.iova % 4096 != 0 || request.length % 4096 != 0 {
478        return Err(SyscallError::InvalidArgument);
479    }
480    if require_2m
481        && (request.iova % (2 * 1024 * 1024) != 0 || request.length % (2 * 1024 * 1024) != 0)
482    {
483        return Err(SyscallError::InvalidArgument);
484    }
485
486    if map {
487        // Permission bits 1 = read, 2 = write, 4 = execute; at least one bit
488        // and no reserved bit.
489        if request.perms == 0 || request.perms & !0x7 != 0 {
490            return Err(SyscallError::InvalidArgument);
491        }
492        let perms = crate::s9vm::mmu::Perms {
493            read: request.perms & 0x1 != 0,
494            write: request.perms & 0x2 != 0,
495            execute: request.perms & 0x4 != 0,
496        };
497        vm::iommu_map(
498            world,
499            request.iova,
500            request.length,
501            perms,
502            require_2m,
503            request.device,
504        )
505        .map_err(map_iommu_error)?;
506    } else {
507        vm::iommu_unmap(
508            world,
509            request.iova,
510            request.length,
511            require_2m,
512            request.device,
513        )
514        .map_err(map_iommu_error)?;
515    }
516    Ok(0)
517}
518
519/// Maps an IOMMU model error to the syscall ABI.
520///
521/// `InvalidRange`→`EINVAL`, `Overlap`→`EEXIST`, `NotMapped`→`ENOENT`,
522/// quota/domain exhaustion→`ENOMEM`, unknown world/domain→`EBADF`.
523fn map_iommu_error(error: IommuError) -> SyscallError {
524    match error {
525        IommuError::InvalidRange => SyscallError::InvalidArgument,
526        IommuError::Overlap => SyscallError::AlreadyExists,
527        IommuError::NotMapped => SyscallError::NotFound,
528        IommuError::QuotaExceeded | IommuError::TooManyDomains => SyscallError::OutOfMemory,
529        IommuError::UnknownDomain => SyscallError::BadHandle,
530        IommuError::AlreadyBound => SyscallError::AlreadyExists,
531    }
532}
533
534/// SYS_VMM_PAUSE (575): pauses a world.
535pub fn sys_vmm_pause(vmm_handle: u64) -> Result<u64, SyscallError> {
536    let required = CapPermissions {
537        write: true,
538        ..CapPermissions::none()
539    };
540    let world = vmm_world(vmm_handle, required)?;
541    vm::pause(world).map_err(map_vm_error)?;
542    Ok(0)
543}
544
545/// SYS_VMM_RESUME (576): resumes a paused world.
546pub fn sys_vmm_resume(vmm_handle: u64) -> Result<u64, SyscallError> {
547    let required = CapPermissions {
548        write: true,
549        ..CapPermissions::none()
550    };
551    let world = vmm_world(vmm_handle, required)?;
552    vm::resume(world).map_err(map_vm_error)?;
553    Ok(0)
554}
555
556/// SYS_VMM_INJECT_NMI (578): schedules an NMI for the next `RUN`.
557pub fn sys_vmm_inject_nmi(vcpu_handle: u64) -> Result<u64, SyscallError> {
558    let required = CapPermissions {
559        write: true,
560        ..CapPermissions::none()
561    };
562    let vcpu = vcpu_target(vcpu_handle, required)?;
563    vm::inject_nmi(vcpu).map_err(map_vcpu_error)?;
564    Ok(0)
565}
566
567/// SYS_VMM_DEBUG_DUMP (579): logs an engine snapshot.
568///
569/// Serializes a summary of the worlds and their vCPUs to the kernel output
570/// (serial / log), then returns 0. No data is copied to user space: this is a
571/// diagnostic tool.
572pub fn sys_vmm_debug_dump(_vmm_handle: u64) -> Result<u64, SyscallError> {
573    require_control()?;
574    crate::s9vm::vm::debug_dump();
575    Ok(0)
576}
577
578/// SYS_VMM_EXIT_COMPLETE (580): completes an exit emulated by the policy.
579///
580/// `value` is written to the guest `RAX` and `advance` bytes are added to the
581/// guest `RIP` (0 for I/O exits, instruction length for MMIO/EPT exits).
582pub fn sys_vmm_exit_complete(
583    vcpu_handle: u64,
584    value: u64,
585    advance: u64,
586) -> Result<u64, SyscallError> {
587    let required = CapPermissions {
588        write: true,
589        ..CapPermissions::none()
590    };
591    let vcpu = vcpu_target(vcpu_handle, required)?;
592    if advance > 15 {
593        // Longest x86 instruction is 15 bytes.
594        return Err(SyscallError::InvalidArgument);
595    }
596    vm::complete_exit(vcpu, value, advance).map_err(map_vcpu_error)?;
597    Ok(0)
598}
599
600/// Maximum bytes transferred by one console syscall.
601const MAX_CONSOLE_IO: u64 = 64 * 1024;
602
603/// SYS_VMM_CONSOLE_INPUT (581): queues bytes for the guest console.
604pub fn sys_vmm_console_input(vmm_handle: u64, buf_ptr: u64, len: u64) -> Result<u64, SyscallError> {
605    let world = vmm_world(vmm_handle, VMM_OWNER)?;
606    if len == 0 || len > MAX_CONSOLE_IO || buf_ptr == 0 {
607        return Err(SyscallError::InvalidArgument);
608    }
609    let mut bytes = alloc::vec![0u8; len as usize];
610    let slice = UserSliceRead::new(buf_ptr, len as usize)?;
611    if slice.copy_to(&mut bytes) != len as usize {
612        return Err(SyscallError::Fault);
613    }
614    let queued = vm::push_console_input(world, &bytes).map_err(|_| SyscallError::NotFound)?;
615    Ok(queued as u64)
616}
617
618/// SYS_VMM_CONSOLE_OUTPUT (582): drains console output bytes.
619pub fn sys_vmm_console_output(
620    vmm_handle: u64,
621    buf_ptr: u64,
622    len: u64,
623) -> Result<u64, SyscallError> {
624    let world = vmm_world(vmm_handle, VMM_OWNER)?;
625    if len == 0 || len > MAX_CONSOLE_IO || buf_ptr == 0 {
626        return Err(SyscallError::InvalidArgument);
627    }
628    let mut bytes = alloc::vec![0u8; len as usize];
629    let count = vm::read_console_output(world, &mut bytes).map_err(|_| SyscallError::NotFound)?;
630    if count > 0 {
631        let slice = UserSliceWrite::new(buf_ptr, count)?;
632        slice.copy_from(&bytes[..count]);
633    }
634    Ok(count as u64)
635}
636
637/// SYS_VMM_BOOT_INFO (583): writes the guest boot-information page.
638pub fn sys_vmm_boot_info(vmm_handle: u64, gpa: u64) -> Result<u64, SyscallError> {
639    let world = vmm_world(vmm_handle, VMM_OWNER)?;
640    vm::write_boot_info(world, gpa).map_err(|error| match error {
641        vm::VmError::Unknown => SyscallError::NotFound,
642        _ => SyscallError::InvalidArgument,
643    })?;
644    Ok(0)
645}
646
647/// Resolves the scope of a `SYS_VMM_LIST` call.
648///
649/// Returns `None` for a silo-administrator global listing (`handle == 0`),
650/// or `Some(silo_id)` when the caller holds a VMM capability: the listing is
651/// then restricted to the worlds owned by that world's silo. This keeps the
652/// call capability-gated while allowing a supervisor to enumerate its own
653/// worlds without knowing their opaque identifiers.
654fn list_scope(vmm_handle: u64) -> Result<Option<u32>, SyscallError> {
655    if vmm_handle == 0 {
656        require_control()?;
657        return Ok(None);
658    }
659    let required = CapPermissions {
660        read: true,
661        ..CapPermissions::none()
662    };
663    let world = vmm_world(vmm_handle, required)?;
664    let record = vm::get(world).ok_or(SyscallError::NotFound)?;
665    Ok(Some(record.silo_id))
666}
667
668/// SYS_VMM_LIST (584): enumerates worlds into a caller buffer.
669///
670/// Returns the total number of matching worlds. At most `capacity` entries
671/// are written, clamped to [`MAX_LIST_ENTRIES`]; the buffer range is
672/// overflow-checked before any copy. `capacity == 0` is a count query and
673/// accepts a null buffer.
674pub fn sys_vmm_list(vmm_handle: u64, entries_ptr: u64, capacity: u64) -> Result<u64, SyscallError> {
675    let scope = list_scope(vmm_handle)?;
676
677    let worlds: alloc::vec::Vec<vm::WorldRecord> = {
678        let all = vm::list();
679        match scope {
680            None => all,
681            Some(silo_id) => all
682                .into_iter()
683                .filter(|record| record.silo_id == silo_id)
684                .collect(),
685        }
686    };
687    let total = worlds.len();
688
689    if capacity == 0 {
690        // Count query: no buffer required, nothing is written.
691        return Ok(total as u64);
692    }
693    if entries_ptr == 0 {
694        return Err(SyscallError::Fault);
695    }
696
697    let requested = core::cmp::min(capacity, MAX_LIST_ENTRIES as u64) as usize;
698    let to_write = core::cmp::min(requested, total);
699    let entry_size = core::mem::size_of::<VmmWorldEntry>() as u64;
700
701    for (index, record) in worlds.iter().take(to_write).enumerate() {
702        // Bounded and overflow-checked: `index < MAX_LIST_ENTRIES` and
703        // `entry_size` is a small constant, but the base pointer is fully
704        // user-controlled.
705        let offset = (index as u64)
706            .checked_mul(entry_size)
707            .and_then(|delta| entries_ptr.checked_add(delta))
708            .ok_or(SyscallError::InvalidArgument)?;
709
710        let mut entry = VmmWorldEntry {
711            abi_version: VMM_ABI_VERSION,
712            state: record.state,
713            vmm_id: record.id,
714            silo_id: record.silo_id,
715            vcpu_count: record.vcpu_count,
716            mapped_pages: record.mapped_pages,
717            ..VmmWorldEntry::default()
718        };
719        let length = record.name_slice().len().min(VMM_NAME_MAX);
720        entry.name[..length].copy_from_slice(&record.name_slice()[..length]);
721        entry.name_len = length as u32;
722        write_struct(offset, &entry)?;
723    }
724
725    Ok(total as u64)
726}
727
728/// SYS_VMM_STATS (585): writes the cumulative counters of a world.
729///
730/// The capability check is the same as `INFO`: read access on the world
731/// handle. `exits_pending` is sampled atomically with respect to the event
732/// queue lock; the other counters are diagnostics and may be slightly stale.
733pub fn sys_vmm_stats(vmm_handle: u64, out_ptr: u64) -> Result<u64, SyscallError> {
734    let required = CapPermissions {
735        read: true,
736        ..CapPermissions::none()
737    };
738    let world = vmm_world(vmm_handle, required)?;
739    let record = vm::get(world).ok_or(SyscallError::NotFound)?;
740    let stats = vm::stats(world).ok_or(SyscallError::NotFound)?;
741    let exits_pending = vm::exit_count(world).ok_or(SyscallError::NotFound)?;
742    let paused = if vm::is_paused(world) { 1 } else { 0 };
743
744    let out = VmmWorldStats {
745        abi_version: VMM_ABI_VERSION,
746        paused,
747        vmm_id: record.id,
748        runs: stats.runs,
749        policy_exits: stats.policy_exits,
750        emulated_exits: stats.emulated_exits,
751        emulated_io: stats.emulated_io,
752        emulated_mmio: stats.emulated_mmio,
753        emulated_msr: stats.emulated_msr,
754        injected_interrupts: stats.injected_interrupts,
755        windows_armed: stats.windows_armed,
756        timer_exits: stats.timer_exits,
757        exits_pending: exits_pending as u64,
758    };
759    write_struct(out_ptr, &out)?;
760    Ok(0)
761}
762
763/// SYS_VMM_LOAD_IMAGE (586): loads an ELF64 guest image into a world.
764///
765/// The image bytes are copied out of the caller address space first, so a
766/// malformed pointer is rejected before any guest page is mapped. On success
767/// the relocated entry point and the loaded span are written to `out_ptr` as a
768/// [`VmmImageInfo`]; the caller sets the vCPU registers from it.
769pub fn sys_vmm_load_image(
770    vmm_handle: u64,
771    gpa: u64,
772    image_ptr: u64,
773    image_len: u64,
774    out_ptr: u64,
775) -> Result<u64, SyscallError> {
776    let required = CapPermissions {
777        write: true,
778        ..CapPermissions::none()
779    };
780    let world = vmm_world(vmm_handle, required)?;
781    let caps = s9vm::detect().ok_or(SyscallError::NotSupported)?;
782    if image_len == 0 || image_len > MAX_IMAGE_BYTES {
783        return Err(SyscallError::InvalidArgument);
784    }
785    if out_ptr == 0 {
786        return Err(SyscallError::Fault);
787    }
788    let slice = UserSliceRead::new(image_ptr, image_len as usize)?;
789    let mut image = vec![0u8; image_len as usize];
790    if slice.copy_to(&mut image) != image_len as usize {
791        return Err(SyscallError::Fault);
792    }
793    let loaded = vm::load_image(world, &caps, &image, gpa).map_err(map_vm_error)?;
794    let info = VmmImageInfo {
795        abi_version: VMM_ABI_VERSION,
796        entry: loaded.entry,
797        image_base: loaded.image_base,
798        span_min: loaded.span_min,
799        span_max: loaded.span_max,
800        ..VmmImageInfo::default()
801    };
802    write_struct(out_ptr, &info)?;
803    Ok(0)
804}
805
806/// SYS_VMM_ACPI (587): writes the firmware description tables of a world.
807///
808/// The tables describe the world's vCPUs and the I/O APIC and are placed at
809/// `gpa` (16-byte aligned, conventionally [`vm::ACPI_GPA`]). Returns 0.
810pub fn sys_vmm_acpi(vmm_handle: u64, gpa: u64) -> Result<u64, SyscallError> {
811    let required = CapPermissions {
812        write: true,
813        ..CapPermissions::none()
814    };
815    let world = vmm_world(vmm_handle, required)?;
816    let caps = s9vm::detect().ok_or(SyscallError::NotSupported)?;
817    vm::write_acpi(world, &caps, gpa).map_err(map_vm_error)?;
818    Ok(0)
819}
820
821/// SYS_VMM_BOOT_PARAMS (590): writes the guest boot-parameter block.
822///
823/// The block is built from the world's mapped regions and its device model and
824/// copied into guest memory at `gpa` (page aligned). Returns 0.
825pub fn sys_vmm_boot_params(vmm_handle: u64, gpa: u64) -> Result<u64, SyscallError> {
826    let required = CapPermissions {
827        write: true,
828        ..CapPermissions::none()
829    };
830    let world = vmm_world(vmm_handle, required)?;
831    vm::write_boot_params(world, gpa).map_err(map_vm_error)?;
832    Ok(0)
833}
834
835/// SYS_VMM_LOAD_MODULE (591): loads a module/initrd blob into a world.
836///
837/// The bytes are copied out of the caller address space first (so a malformed
838/// pointer is rejected before any guest page is mapped), validated against the
839/// 64 MiB bound, then mapped read/write at the page-aligned `gpa` and copied
840/// verbatim. The world records at most four ranges; the range is published by
841/// `SYS_VMM_BOOT_PARAMS`. Returns 0.
842pub fn sys_vmm_load_module(
843    vmm_handle: u64,
844    gpa: u64,
845    module_ptr: u64,
846    module_len: u64,
847) -> Result<u64, SyscallError> {
848    let required = CapPermissions {
849        write: true,
850        ..CapPermissions::none()
851    };
852    let world = vmm_world(vmm_handle, required)?;
853    let caps = s9vm::detect().ok_or(SyscallError::NotSupported)?;
854    if module_len == 0 || module_len > VMM_MODULE_MAX_BYTES as u64 {
855        return Err(SyscallError::InvalidArgument);
856    }
857    if gpa % crate::s9vm::mmu::PAGE_SIZE != 0 {
858        return Err(SyscallError::InvalidArgument);
859    }
860    let slice = UserSliceRead::new(module_ptr, module_len as usize)?;
861    let mut module = vec![0u8; module_len as usize];
862    if slice.copy_to(&mut module) != module_len as usize {
863        return Err(SyscallError::Fault);
864    }
865    vm::load_module(world, &caps, gpa, &module).map_err(map_vm_error)?;
866    Ok(0)
867}
868
869/// SYS_VMM_SET_CMDLINE (592): stores the guest kernel command line.
870///
871/// At most [`VMM_CMDLINE_MAX`] bytes are accepted; the command line is
872/// NUL-padded and not NUL-terminated. Returns the stored length, which is also
873/// what `SYS_VMM_BOOT_PARAMS` publishes to the guest.
874pub fn sys_vmm_set_cmdline(
875    vmm_handle: u64,
876    cmdline_ptr: u64,
877    cmdline_len: u64,
878) -> Result<u64, SyscallError> {
879    let required = CapPermissions {
880        write: true,
881        ..CapPermissions::none()
882    };
883    let world = vmm_world(vmm_handle, required)?;
884    if cmdline_len > VMM_CMDLINE_MAX as u64 {
885        return Err(SyscallError::InvalidArgument);
886    }
887    let mut cmdline = vec![0u8; cmdline_len as usize];
888    if cmdline_len != 0 {
889        let slice = UserSliceRead::new(cmdline_ptr, cmdline_len as usize)?;
890        if slice.copy_to(&mut cmdline) != cmdline_len as usize {
891            return Err(SyscallError::Fault);
892        }
893    }
894    let stored = vm::set_cmdline(world, &cmdline).map_err(map_vm_error)?;
895    Ok(stored as u64)
896}
897
898/// SYS_VMM_LOAD_DISK (593): replaces a world's block-device image.
899///
900/// `arg1` = VMM capability handle (write permission required),
901/// `arg2` = user pointer to the image bytes,
902/// `arg3` = image length: non-zero, a multiple of
903/// [`VMM_DISK_SECTOR_SIZE`], at most [`VMM_DISK_MAX_BYTES`].
904///
905/// The bytes are copied into a bounded kernel buffer, then
906/// [`vm::load_disk`] replaces the device content: image first, zero-fill after
907/// it, grow-only (never shrink), and at least
908/// [`strat9_abi::vmm::VMM_DISK_DEFAULT_BYTES`] of capacity. Intended to be
909/// called before the guest boots; when the device grows its virtio transport
910/// state is reset (the read-only mode is preserved). Returns 0.
911pub fn sys_vmm_load_disk(
912    vmm_handle: u64,
913    image_ptr: u64,
914    image_len: u64,
915) -> Result<u64, SyscallError> {
916    let required = CapPermissions {
917        write: true,
918        ..CapPermissions::none()
919    };
920    let world = vmm_world(vmm_handle, required)?;
921    if image_len == 0 || image_len % VMM_DISK_SECTOR_SIZE != 0 || image_len > VMM_DISK_MAX_BYTES {
922        return Err(SyscallError::InvalidArgument);
923    }
924    // Bounded by VMM_DISK_MAX_BYTES (16 MiB) by the check above.
925    let mut image = vec![0u8; image_len as usize];
926    let slice = UserSliceRead::new(image_ptr, image.as_slice().len())?;
927    if slice.copy_to(&mut image) != image.len() {
928        return Err(SyscallError::Fault);
929    }
930    vm::load_disk(world, &image).map_err(map_disk_error)?;
931    Ok(0)
932}
933
934/// Maps a [`vm::DiskError`] to the syscall ABI.
935fn map_disk_error(error: vm::DiskError) -> SyscallError {
936    match error {
937        vm::DiskError::Unknown => SyscallError::BadHandle,
938        vm::DiskError::InvalidLength | vm::DiskError::TooLarge => SyscallError::InvalidArgument,
939    }
940}
941
942/// SYS_VMM_VCPU_LIST (588): enumerates the vCPUs of a world into a caller
943/// buffer.
944///
945/// `handle == 0` lists every world and requires the silo administrator
946/// capability; a non-zero handle restricts the listing to that world and
947/// requires read access on the VMM capability. The [`VmmVcpuInfo`] entries are
948/// built from [`vm::vcpu_snapshots`] before any user copy, so the engine lock
949/// is never held while faulting user memory.
950///
951/// Returns the total number of matching vCPUs. At most `capacity` entries are
952/// written, clamped to [`MAX_VCPU_LIST_ENTRIES`]; the buffer range is
953/// overflow-checked before any copy. `capacity == 0` is a count query and
954/// accepts a null buffer.
955pub fn sys_vmm_vcpu_list(
956    vmm_handle: u64,
957    entries_ptr: u64,
958    capacity: u64,
959) -> Result<u64, SyscallError> {
960    let (worlds, single) = if vmm_handle == 0 {
961        require_control()?;
962        (vm::list(), false)
963    } else {
964        let required = CapPermissions {
965            read: true,
966            ..CapPermissions::none()
967        };
968        let world = vmm_world(vmm_handle, required)?;
969        let record = vm::get(world).ok_or(SyscallError::NotFound)?;
970        (alloc::vec![record], true)
971    };
972
973    // Snapshot every vCPU first: the engine lock is released before the user
974    // copy, which may fault.
975    let mut snapshots: alloc::vec::Vec<(u64, vm::VcpuSnapshot)> = alloc::vec::Vec::new();
976    for record in &worlds {
977        let Some(vcpus) = vm::vcpu_snapshots(record.id) else {
978            if single {
979                return Err(SyscallError::NotFound);
980            }
981            // The world disappeared between the enumeration and the
982            // snapshot: a global listing simply skips it.
983            continue;
984        };
985        for vcpu in vcpus {
986            snapshots.push((record.id, vcpu));
987        }
988    }
989    let total = snapshots.len();
990
991    if capacity == 0 {
992        // Count query: no buffer required, nothing is written.
993        return Ok(total as u64);
994    }
995    if entries_ptr == 0 {
996        return Err(SyscallError::Fault);
997    }
998
999    let requested = core::cmp::min(capacity, MAX_VCPU_LIST_ENTRIES as u64) as usize;
1000    let to_write = core::cmp::min(requested, total);
1001    let entry_size = core::mem::size_of::<VmmVcpuInfo>() as u64;
1002
1003    for (index, (vmm_id, snapshot)) in snapshots.iter().take(to_write).enumerate() {
1004        // Bounded and overflow-checked: `index < MAX_VCPU_LIST_ENTRIES` and
1005        // `entry_size` is a small constant, but the base pointer is fully
1006        // user-controlled.
1007        let offset = (index as u64)
1008            .checked_mul(entry_size)
1009            .and_then(|delta| entries_ptr.checked_add(delta))
1010            .ok_or(SyscallError::InvalidArgument)?;
1011
1012        let mut flags = 0u32;
1013        if snapshot.hardware_ready {
1014            flags |= vcpu_flags::HARDWARE_READY;
1015        }
1016        if snapshot.executing {
1017            flags |= vcpu_flags::EXECUTING;
1018        }
1019        if snapshot.pending_nmi {
1020            flags |= vcpu_flags::PENDING_NMI;
1021        }
1022        let entry = VmmVcpuInfo {
1023            abi_version: VMM_ABI_VERSION,
1024            flags,
1025            vmm_id: *vmm_id,
1026            vcpu_id: snapshot.id,
1027            apic_id: snapshot.apic_id,
1028            reserved: 0,
1029        };
1030        write_struct(offset, &entry)?;
1031    }
1032
1033    Ok(total as u64)
1034}
1035
1036/// SYS_VMM_VCPU_REGS (589): reads a vCPU's live register block.
1037///
1038/// Shares the handle/capability path and the copy helper of
1039/// [`sys_vmm_get_regs`] (564) instead of duplicating them; the distinct call
1040/// number keeps the vCPU introspection pair (`VCPU_LIST` / `VCPU_REGS`)
1041/// append-only.
1042pub fn sys_vmm_vcpu_regs(vcpu_handle: u64, regs_ptr: u64) -> Result<u64, SyscallError> {
1043    sys_vmm_get_regs(vcpu_handle, regs_ptr)
1044}
1045
1046/// SYS_VMM_INFO (569): snapshot of a world, or global summary if `vmm_id = 0`.
1047pub fn sys_vmm_info(vmm_handle: u64, out_ptr: u64) -> Result<u64, SyscallError> {
1048    let mut info = VmmInfo {
1049        abi_version: strat9_abi::vmm::VMM_ABI_VERSION,
1050        ..VmmInfo::default()
1051    };
1052    let vmm_id = if vmm_handle == 0 {
1053        require_control()?;
1054        0
1055    } else {
1056        let required = CapPermissions {
1057            read: true,
1058            ..CapPermissions::none()
1059        };
1060        vmm_world(vmm_handle, required)?
1061    };
1062    if vmm_id == 0 {
1063        // Global engine summary.
1064        info.state = if s9vm::detected() {
1065            state::RUNNING
1066        } else {
1067            state::STOPPED
1068        };
1069        info.vmm_id = 0;
1070        // The global summary aggregates every world: the vCPU count is the
1071        // number of vCPUs currently registered, not the number of worlds.
1072        let mut vcpus = 0u64;
1073        let mut pages = 0u64;
1074        for record in vm::list() {
1075            vcpus = vcpus.saturating_add(u64::from(record.vcpu_count));
1076            pages = pages.saturating_add(record.mapped_pages);
1077        }
1078        info.vcpu_count = vcpus.min(u64::from(u32::MAX)) as u32;
1079        info.mapped_pages = pages;
1080        let name = b"s9vm";
1081        info.name[..name.len()].copy_from_slice(name);
1082    } else {
1083        let record = vm::get(vmm_id).ok_or(SyscallError::NotFound)?;
1084        info.state = record.state;
1085        info.vmm_id = record.id;
1086        info.silo_id = record.silo_id;
1087        info.vcpu_count = record.vcpu_count;
1088        info.mapped_pages = record.mapped_pages;
1089        let length = record.name_slice().len();
1090        info.name[..length].copy_from_slice(record.name_slice());
1091    }
1092    write_struct(out_ptr, &info)?;
1093    Ok(0)
1094}
1095
1096/// Builds a vector of worlds for the shell command (diagnostic).
1097pub fn list_worlds() -> alloc::vec::Vec<vm::WorldRecord> {
1098    vm::list()
1099}
1100
1101/// Builds a `VmmInfo` for a world (diagnostic, without user copy).
1102pub fn world_info(vmm_id: u64) -> Option<VmmInfo> {
1103    let record = vm::get(vmm_id)?;
1104    let mut info = VmmInfo {
1105        abi_version: strat9_abi::vmm::VMM_ABI_VERSION,
1106        state: record.state,
1107        vmm_id: record.id,
1108        silo_id: record.silo_id,
1109        vcpu_count: record.vcpu_count,
1110        mapped_pages: record.mapped_pages,
1111        ..VmmInfo::default()
1112    };
1113    let length = record.name_slice().len();
1114    info.name[..length].copy_from_slice(record.name_slice());
1115    Some(info)
1116}
1117
1118/// Marks a world as running (used by the selftest and the shell). Returns
1119/// `false` if the world is unknown.
1120pub fn mark_running(vmm_id: u64) -> bool {
1121    vm::set_state(vmm_id, state::RUNNING)
1122}
1123
1124/// Marks a world as stopped.
1125pub fn mark_stopped(vmm_id: u64) -> bool {
1126    vm::set_state(vmm_id, state::STOPPED)
1127}
1128/// Converts an ABI CPU description into the engine model.
1129///
1130/// Reserved words must be zero and the ABI version must match. Everything else
1131/// is a tuning field: a zero value means "keep the engine default", so a caller
1132/// can change only the masks or topology it cares about. Leaf ranges are
1133/// bounded by the leaves the replay actually implements, and an out-of-range
1134/// value is rejected rather than clamped so a caller never believes it hid a
1135/// leaf that is in fact still answered.
1136fn cpuid_policy_from_abi(request: &VmmCpuidPolicy) -> Result<CpuidPolicy, SyscallError> {
1137    if request.flags != 0 || request.reserved != 0 {
1138        return Err(SyscallError::InvalidArgument);
1139    }
1140    if request.max_basic_leaf > cpuid::MAX_BASIC_LEAF {
1141        return Err(SyscallError::InvalidArgument);
1142    }
1143    if request.max_extended_leaf != 0
1144        && (request.max_extended_leaf < cpuid::LEAF_EXTENDED_FEATURES
1145            || request.max_extended_leaf > cpuid::MAX_EXTENDED_LEAF)
1146    {
1147        return Err(SyscallError::InvalidArgument);
1148    }
1149    if request.family > 0xFF
1150        || request.model > 0xFF
1151        || request.stepping > 0xFF
1152        || request.cores > 0xFF
1153        || request.threads > 0xFF
1154    {
1155        return Err(SyscallError::InvalidArgument);
1156    }
1157    let defaults = CpuidPolicy::new();
1158    Ok(CpuidPolicy {
1159        max_basic_leaf: defaulted(request.max_basic_leaf, defaults.max_basic_leaf),
1160        max_extended_leaf: defaulted(request.max_extended_leaf, defaults.max_extended_leaf),
1161        family: defaulted(request.family, defaults.family),
1162        model: defaulted(request.model, defaults.model),
1163        stepping: defaulted(request.stepping, defaults.stepping),
1164        cores: defaulted(request.cores, defaults.cores),
1165        threads: defaulted(request.threads, defaults.threads),
1166        leaf1_ecx: defaulted(request.leaf1_ecx, defaults.leaf1_ecx),
1167        leaf1_edx: defaulted(request.leaf1_edx, defaults.leaf1_edx),
1168        extended1_ecx: defaulted(request.extended1_ecx, defaults.extended1_ecx),
1169        extended1_edx: defaulted(request.extended1_edx, defaults.extended1_edx),
1170        // TSC leaves are not part of the ABI policy yet: a world publishes the
1171        // host frequency through the engine defaults. See the report of the
1172        // s9vm guest time-keeping task for the optional ABI extension.
1173        tsc_ratio_denominator: defaults.tsc_ratio_denominator,
1174        tsc_ratio_numerator: defaults.tsc_ratio_numerator,
1175        crystal_hz: defaults.crystal_hz,
1176        base_mhz: defaults.base_mhz,
1177    })
1178}
1179
1180/// A zero ABI field means "keep the engine default".
1181fn defaulted(value: u32, default: u32) -> u32 {
1182    if value == 0 {
1183        default
1184    } else {
1185        value
1186    }
1187}
1188
1189fn map_vm_error(error: VmError) -> SyscallError {
1190    match error {
1191        VmError::Unknown => SyscallError::NotFound,
1192        VmError::Map(MapError::InvalidRange) => SyscallError::InvalidArgument,
1193        VmError::Map(MapError::Overlap) => SyscallError::InvalidArgument,
1194        VmError::Map(MapError::QuotaExceeded) => SyscallError::OutOfMemory,
1195        VmError::Map(MapError::TooManyRegions) => SyscallError::OutOfMemory,
1196        VmError::Map(MapError::NotMapped) => SyscallError::NotFound,
1197        VmError::OutOfMemory => SyscallError::OutOfMemory,
1198        VmError::Translation(_) => SyscallError::NotSupported,
1199    }
1200}
1201fn map_vcpu_error(error: vm::VcpuRegistryError) -> SyscallError {
1202    match error {
1203        vm::VcpuRegistryError::WorldUnknown => SyscallError::NotFound,
1204        vm::VcpuRegistryError::Unknown => SyscallError::NotFound,
1205        vm::VcpuRegistryError::Limit => SyscallError::OutOfMemory,
1206        vm::VcpuRegistryError::BadAbiVersion => SyscallError::InvalidArgument,
1207        vm::VcpuRegistryError::Thread => SyscallError::OutOfMemory,
1208    }
1209}
1210fn map_run_error(error: vm::RunError) -> SyscallError {
1211    match error {
1212        vm::RunError::UnknownVcpu => SyscallError::NotFound,
1213        vm::RunError::NoMemory => SyscallError::Again,
1214        vm::RunError::InvalidGuestState => SyscallError::InvalidArgument,
1215        vm::RunError::HardwareNotReady => SyscallError::NotSupported,
1216        vm::RunError::Hardware(_) => SyscallError::IoError,
1217        vm::RunError::ExitStorm => SyscallError::Again,
1218        vm::RunError::Busy => SyscallError::Again,
1219        vm::RunError::Paused => SyscallError::Again,
1220        // The vCPU task did not finish within the `RUN` budget: report the
1221        // timeout (ETIMEDOUT) instead of retrying forever.
1222        vm::RunError::Timeout => SyscallError::TimedOut,
1223    }
1224}