virt_mshv_vtl/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Implementation of the Underhill hypervisor backend, which uses
5//! `/dev/mshv_vtl` to interact with the Microsoft hypervisor while running in
6//! VTL2.
7
8#![cfg(all(guest_is_native, target_os = "linux"))]
9
10mod devmsr;
11
12cfg_if::cfg_if!(
13    if #[cfg(guest_arch = "x86_64")] {
14        mod cvm_cpuid;
15        pub use processor::snp::SnpBacked;
16        pub use processor::tdx::TdxBacked;
17        use crate::processor::HardwareIsolatedBacking;
18        pub use crate::processor::mshv::x64::HypervisorBackedX86 as HypervisorBacked;
19        use crate::processor::mshv::x64::HypervisorBackedX86Shared as HypervisorBackedShared;
20        use bitvec::prelude::BitArray;
21        use bitvec::prelude::Lsb0;
22        use devmsr::MsrDevice;
23        use hv1_emulator::hv::ProcessorVtlHv;
24        use processor::LapicState;
25        use processor::snp::SnpBackedShared;
26        use processor::tdx::TdxBackedShared;
27        use std::arch::x86_64::CpuidResult;
28        use virt::CpuidLeaf;
29        use virt::state::StateElement;
30        use virt::vp::MpState;
31        /// Bitarray type for representing IRR bits in a x86-64 APIC
32        /// Each bit represent the 256 possible vectors.
33        type IrrBitmap = BitArray<[u32; 8], Lsb0>;
34    } else if #[cfg(guest_arch = "aarch64")] {
35        pub use crate::processor::mshv::arm64::HypervisorBackedArm64 as HypervisorBacked;
36        use crate::processor::mshv::arm64::HypervisorBackedArm64Shared as HypervisorBackedShared;
37    }
38);
39
40mod processor;
41pub use processor::Backing;
42pub use processor::UhProcessor;
43
44use anyhow::Context as AnyhowContext;
45use bitfield_struct::bitfield;
46use bitvec::boxed::BitBox;
47use bitvec::vec::BitVec;
48use cvm_tracing::CVM_ALLOWED;
49use guestmem::GuestMemory;
50use guestmem::GuestMemoryBackingError;
51use hcl::GuestVtl;
52use hcl::ioctl::Hcl;
53use hcl::ioctl::SetVsmPartitionConfigError;
54use hv1_emulator::hv::GlobalHv;
55use hv1_emulator::message_queues::MessageQueues;
56use hv1_emulator::synic::GlobalSynic;
57use hv1_emulator::synic::SintProxied;
58use hv1_structs::VtlArray;
59use hvdef::GuestCrashCtl;
60use hvdef::HV_PAGE_SHIFT;
61use hvdef::HV_PAGE_SIZE;
62use hvdef::HV_PAGE_SIZE_USIZE;
63use hvdef::HvError;
64use hvdef::HvMapGpaFlags;
65use hvdef::HvPartitionPrivilege;
66use hvdef::HvRegisterName;
67use hvdef::HvRegisterVsmPartitionConfig;
68use hvdef::HvRegisterVsmPartitionStatus;
69use hvdef::Vtl;
70use hvdef::hypercall::HV_INTERCEPT_ACCESS_MASK_EXECUTE;
71use hvdef::hypercall::HV_INTERCEPT_ACCESS_MASK_NONE;
72use hvdef::hypercall::HV_INTERCEPT_ACCESS_MASK_READ_WRITE;
73use hvdef::hypercall::HV_INTERCEPT_ACCESS_MASK_WRITE;
74use hvdef::hypercall::HostVisibilityType;
75use hvdef::hypercall::HvGuestOsId;
76use hvdef::hypercall::HvInputVtl;
77use hvdef::hypercall::HvInterceptParameters;
78use hvdef::hypercall::HvInterceptType;
79use inspect::Inspect;
80use inspect::InspectMut;
81use memory_range::MemoryRange;
82use pal::unix::affinity;
83use pal::unix::affinity::CpuSet;
84use pal_async::driver::Driver;
85use pal_async::driver::SpawnDriver;
86use pal_uring::IdleControl;
87use parking_lot::Mutex;
88use parking_lot::RwLock;
89use processor::BackingSharedParams;
90use processor::SidecarExitReason;
91use sidecar_client::NewSidecarClientError;
92use std::collections::HashMap;
93use std::ops::RangeInclusive;
94use std::os::fd::AsRawFd;
95use std::sync::Arc;
96use std::sync::Weak;
97use std::sync::atomic::AtomicBool;
98use std::sync::atomic::AtomicU8;
99use std::sync::atomic::AtomicU32;
100use std::sync::atomic::AtomicU64;
101use std::sync::atomic::Ordering;
102use std::task::Waker;
103use thiserror::Error;
104use user_driver::DmaClient;
105use virt::IsolationType;
106use virt::PartitionCapabilities;
107use virt::VpIndex;
108use virt::X86Partition;
109use virt::irqcon::IoApicRouting;
110use virt::irqcon::MsiRequest;
111use virt::x86::apic_software_device::ApicSoftwareDevices;
112use virt_support_apic::LocalApicSet;
113use vm_topology::memory::MemoryLayout;
114use vm_topology::processor::ProcessorTopology;
115use vm_topology::processor::TargetVpInfo;
116use vmcore::monitor::MonitorPage;
117use vmcore::reference_time::GetReferenceTime;
118use vmcore::reference_time::ReferenceTimeResult;
119use vmcore::reference_time::ReferenceTimeSource;
120use vmcore::vmtime::VmTimeSource;
121use x86defs::snp::REG_TWEAK_BITMAP_OFFSET;
122use x86defs::snp::REG_TWEAK_BITMAP_SIZE;
123use x86defs::tdx::TdCallResult;
124use zerocopy::FromBytes;
125use zerocopy::FromZeros;
126use zerocopy::Immutable;
127use zerocopy::IntoBytes;
128use zerocopy::KnownLayout;
129
130/// General error returned by operations.
131#[derive(Error, Debug)]
132#[expect(missing_docs)]
133pub enum Error {
134    #[error("hcl error")]
135    Hcl(#[source] hcl::ioctl::Error),
136    #[error("failed to open sidecar client")]
137    Sidecar(#[source] NewSidecarClientError),
138    #[error("failed to install {0:?} intercept: {1:?}")]
139    InstallIntercept(HvInterceptType, HvError),
140    #[error("failed to query hypervisor register {0:#x?}")]
141    Register(HvRegisterName, #[source] HvError),
142    #[error("failed to set vsm partition config register")]
143    VsmPartitionConfig(#[source] SetVsmPartitionConfigError),
144    #[error("failed to create virtual device")]
145    NewDevice(#[source] virt::x86::apic_software_device::DeviceIdInUse),
146    #[error("failed to create cpuid tables for cvm")]
147    #[cfg(guest_arch = "x86_64")]
148    CvmCpuid(#[source] cvm_cpuid::CpuidResultsError),
149    #[error("failed to update hypercall msr")]
150    UpdateHypercallMsr,
151    #[error("failed to update reference tsc msr")]
152    UpdateReferenceTsc,
153    #[error("failed to map overlay page")]
154    MapOverlay(#[source] std::io::Error),
155    #[error("failed to allocate shared visibility pages for overlay")]
156    AllocateSharedVisOverlay(#[source] anyhow::Error),
157    #[error("failed to open msr device")]
158    OpenMsr(#[source] std::io::Error),
159    #[error("cpuid did not contain valid TSC frequency information")]
160    BadCpuidTsc,
161    #[error("failed to read tsc frequency")]
162    ReadTscFrequency(#[source] std::io::Error),
163    #[error(
164        "tsc frequency mismatch between hypervisor ({hv}) and hardware {hw}, exceeds allowed error {allowed_error}"
165    )]
166    TscFrequencyMismatch {
167        hv: u64,
168        hw: u64,
169        allowed_error: u64,
170    },
171    #[error("failed to set vsm partition config: {0:?}")]
172    FailedToSetL2Ctls(TdCallResult),
173    #[error("debugging is configured but the binary does not have the gdb feature")]
174    InvalidDebugConfiguration,
175    #[error("failed to allocate TLB flush page")]
176    AllocateTlbFlushPage(#[source] anyhow::Error),
177    #[error("host does not support required cpu capabilities")]
178    Capabilities(virt::PartitionCapabilitiesError),
179    #[error("failed to get register")]
180    GetReg(#[source] hcl::ioctl::register::GetRegError),
181    #[error("failed to set register")]
182    SetReg(#[source] hcl::ioctl::register::SetRegError),
183}
184
185/// Error revoking guest VSM.
186#[derive(Error, Debug)]
187#[expect(missing_docs)]
188pub enum RevokeGuestVsmError {
189    #[error("failed to set vsm config")]
190    SetGuestVsmConfig(#[source] hcl::ioctl::register::SetRegError),
191    #[error("VTL 1 is already enabled")]
192    Vtl1AlreadyEnabled,
193}
194
195/// Underhill partition.
196#[derive(Inspect)]
197pub struct UhPartition {
198    #[inspect(flatten)]
199    inner: Arc<UhPartitionInner>,
200    // TODO: remove this extra indirection by refactoring some traits.
201    #[inspect(skip)]
202    interrupt_targets: VtlArray<Arc<UhInterruptTarget>, 2>,
203}
204
205/// Underhill partition.
206#[derive(Inspect)]
207#[inspect(extra = "UhPartitionInner::inspect_extra")]
208struct UhPartitionInner {
209    #[inspect(skip)]
210    hcl: Hcl,
211    #[inspect(skip)] // inspected separately
212    vps: Vec<UhVpInner>,
213    irq_routes: virt::irqcon::IrqRoutes,
214    caps: PartitionCapabilities,
215    #[inspect(skip)] // handled in `inspect_extra`
216    enter_modes: Mutex<EnterModes>,
217    #[inspect(skip)]
218    enter_modes_atomic: AtomicU8,
219    #[cfg(guest_arch = "x86_64")]
220    cpuid: virt::CpuidLeafSet,
221    lower_vtl_memory_layout: MemoryLayout,
222    gm: VtlArray<GuestMemory, 2>,
223    vtl0_kernel_exec_gm: GuestMemory,
224    vtl0_user_exec_gm: GuestMemory,
225    #[cfg_attr(guest_arch = "aarch64", expect(dead_code))]
226    #[inspect(skip)]
227    crash_notification_send: mesh::Sender<VtlCrash>,
228    monitor_page: MonitorPage,
229    #[inspect(skip)]
230    allocated_monitor_page: Mutex<Option<user_driver::memory::MemoryBlock>>,
231    software_devices: Option<ApicSoftwareDevices>,
232    #[inspect(skip)]
233    vmtime: VmTimeSource,
234    isolation: IsolationType,
235    #[inspect(with = "inspect::AtomicMut")]
236    no_sidecar_hotplug: AtomicBool,
237    use_mmio_hypercalls: bool,
238    backing_shared: BackingShared,
239    intercept_debug_exceptions: bool,
240    #[cfg(guest_arch = "x86_64")]
241    // N.B For now, only one device vector table i.e. for VTL0 only
242    #[inspect(hex, with = "|x| inspect::iter_by_index(x.read().into_inner())")]
243    device_vector_table: RwLock<IrrBitmap>,
244    vmbus_relay: bool,
245}
246
247#[derive(Inspect)]
248#[inspect(untagged)]
249enum BackingShared {
250    Hypervisor(#[inspect(flatten)] HypervisorBackedShared),
251    #[cfg(guest_arch = "x86_64")]
252    Snp(#[inspect(flatten)] SnpBackedShared),
253    #[cfg(guest_arch = "x86_64")]
254    Tdx(#[inspect(flatten)] TdxBackedShared),
255}
256
257impl BackingShared {
258    fn new(
259        isolation: IsolationType,
260        partition_params: &UhPartitionNewParams<'_>,
261        backing_shared_params: BackingSharedParams<'_>,
262    ) -> Result<BackingShared, Error> {
263        Ok(match isolation {
264            IsolationType::None | IsolationType::Vbs => {
265                assert!(backing_shared_params.cvm_state.is_none());
266                BackingShared::Hypervisor(HypervisorBackedShared::new(
267                    partition_params,
268                    backing_shared_params,
269                )?)
270            }
271            #[cfg(guest_arch = "x86_64")]
272            IsolationType::Snp => BackingShared::Snp(SnpBackedShared::new(
273                partition_params,
274                backing_shared_params,
275            )?),
276            #[cfg(guest_arch = "x86_64")]
277            IsolationType::Tdx => BackingShared::Tdx(TdxBackedShared::new(
278                partition_params,
279                backing_shared_params,
280            )?),
281            #[cfg(not(guest_arch = "x86_64"))]
282            _ => unreachable!(),
283        })
284    }
285
286    fn cvm_state(&self) -> Option<&UhCvmPartitionState> {
287        match self {
288            BackingShared::Hypervisor(_) => None,
289            #[cfg(guest_arch = "x86_64")]
290            BackingShared::Snp(SnpBackedShared { cvm, .. })
291            | BackingShared::Tdx(TdxBackedShared { cvm, .. }) => Some(cvm),
292        }
293    }
294
295    fn untrusted_synic(&self) -> Option<&GlobalSynic> {
296        match self {
297            BackingShared::Hypervisor(_) => None,
298            #[cfg(guest_arch = "x86_64")]
299            BackingShared::Snp(_) => None,
300            #[cfg(guest_arch = "x86_64")]
301            BackingShared::Tdx(s) => s.untrusted_synic.as_ref(),
302        }
303    }
304}
305
306#[derive(InspectMut, Copy, Clone)]
307struct EnterModes {
308    #[inspect(mut)]
309    first: EnterMode,
310    #[inspect(mut)]
311    second: EnterMode,
312}
313
314impl Default for EnterModes {
315    fn default() -> Self {
316        Self {
317            first: EnterMode::Fast,
318            second: EnterMode::IdleToVtl0,
319        }
320    }
321}
322
323impl From<EnterModes> for hcl::protocol::EnterModes {
324    fn from(value: EnterModes) -> Self {
325        Self::new()
326            .with_first(value.first.into())
327            .with_second(value.second.into())
328    }
329}
330
331#[derive(InspectMut, Copy, Clone)]
332enum EnterMode {
333    Fast,
334    PlayIdle,
335    IdleToVtl0,
336}
337
338impl From<EnterMode> for hcl::protocol::EnterMode {
339    fn from(value: EnterMode) -> Self {
340        match value {
341            EnterMode::Fast => Self::FAST,
342            EnterMode::PlayIdle => Self::PLAY_IDLE,
343            EnterMode::IdleToVtl0 => Self::IDLE_TO_VTL0,
344        }
345    }
346}
347
348#[cfg(guest_arch = "x86_64")]
349#[derive(Inspect)]
350struct GuestVsmVpState {
351    /// The pending event that VTL 1 wants to inject into VTL 0. Injected on
352    /// next exit to VTL 0.
353    #[inspect(with = "|x| x.as_ref().map(inspect::AsDebug)")]
354    vtl0_exit_pending_event: Option<hvdef::HvX64PendingExceptionEvent>,
355    reg_intercept: SecureRegisterInterceptState,
356}
357
358#[cfg(guest_arch = "x86_64")]
359impl GuestVsmVpState {
360    fn new() -> Self {
361        GuestVsmVpState {
362            vtl0_exit_pending_event: None,
363            reg_intercept: Default::default(),
364        }
365    }
366}
367
368#[cfg(guest_arch = "x86_64")]
369#[derive(Inspect)]
370/// VP state for CVMs.
371struct UhCvmVpState {
372    // Allocation handle for direct overlays
373    #[inspect(debug)]
374    direct_overlay_handle: user_driver::memory::MemoryBlock,
375    /// Used in VTL 2 exit code to determine which VTL to exit to.
376    exit_vtl: GuestVtl,
377    /// Hypervisor enlightenment emulator state.
378    hv: VtlArray<ProcessorVtlHv, 2>,
379    /// LAPIC state.
380    lapics: VtlArray<LapicState, 2>,
381    /// Guest VSM state for this vp. Some when VTL 1 is enabled.
382    vtl1: Option<GuestVsmVpState>,
383}
384
385#[cfg(guest_arch = "x86_64")]
386impl UhCvmVpState {
387    /// Creates a new CVM VP state.
388    pub(crate) fn new(
389        cvm_partition: &UhCvmPartitionState,
390        inner: &UhPartitionInner,
391        vp_info: &TargetVpInfo,
392        overlay_pages_required: usize,
393    ) -> Result<Self, Error> {
394        let direct_overlay_handle = cvm_partition
395            .shared_dma_client
396            .allocate_dma_buffer(overlay_pages_required * HV_PAGE_SIZE as usize)
397            .map_err(Error::AllocateSharedVisOverlay)?;
398
399        let apic_base = virt::vp::Apic::at_reset(&inner.caps, vp_info).apic_base;
400        let lapics = VtlArray::from_fn(|vtl| {
401            let apic_set = &cvm_partition.lapic[vtl];
402
403            // The APIC is software-enabled after reset for secure VTLs, to
404            // maintain compatibility with released versions of secure kernel
405            let mut lapic = apic_set.add_apic(vp_info, vtl == Vtl::Vtl1);
406            // Initialize APIC base to match the reset VM state.
407            lapic.set_apic_base(apic_base).unwrap();
408            // Only the VTL 0 non-BSP LAPICs should be in the WaitForSipi state.
409            let activity = if vtl == Vtl::Vtl0 && !vp_info.base.is_bsp() {
410                MpState::WaitForSipi
411            } else {
412                MpState::Running
413            };
414            LapicState::new(lapic, activity)
415        });
416
417        let hv = VtlArray::from_fn(|vtl| cvm_partition.hv.add_vp(vp_info.base.vp_index, vtl));
418
419        Ok(Self {
420            direct_overlay_handle,
421            exit_vtl: GuestVtl::Vtl0,
422            hv,
423            lapics,
424            vtl1: None,
425        })
426    }
427}
428
429#[cfg(guest_arch = "x86_64")]
430#[derive(Inspect, Default)]
431#[inspect(hex)]
432/// Configuration of VTL 1 registration for intercepts on certain registers
433pub struct SecureRegisterInterceptState {
434    #[inspect(with = "|&x| u64::from(x)")]
435    intercept_control: hvdef::HvRegisterCrInterceptControl,
436    cr0_mask: u64,
437    cr4_mask: u64,
438    // Writes to X86X_IA32_MSR_MISC_ENABLE are dropped, so this is only used so
439    // that get_vp_register returns the correct value from a set_vp_register
440    ia32_misc_enable_mask: u64,
441}
442
443/// Information about a redirected interrupt for a specific vector.
444/// Stored per-processor, indexed by the redirected vector number in VTL2.
445#[derive(Clone, Inspect)]
446struct ProxyRedirectVectorInfo {
447    /// Device ID that owns this interrupt
448    device_id: u64,
449    /// Original interrupt vector from the device
450    original_vector: u32,
451}
452
453#[derive(Inspect)]
454/// Partition-wide state for CVMs.
455struct UhCvmPartitionState {
456    #[cfg(guest_arch = "x86_64")]
457    vps_per_socket: u32,
458    /// VPs that have locked their TLB.
459    #[inspect(
460        with = "|arr| inspect::iter_by_index(arr.iter()).map_value(|bb| inspect::iter_by_index(bb.iter().map(|v| *v)))"
461    )]
462    tlb_locked_vps: VtlArray<BitBox<AtomicU64>, 2>,
463    #[inspect(with = "inspect::iter_by_index")]
464    vps: Vec<UhCvmVpInner>,
465    shared_memory: GuestMemory,
466    #[cfg_attr(guest_arch = "aarch64", expect(dead_code))]
467    #[inspect(skip)]
468    isolated_memory_protector: Arc<dyn ProtectIsolatedMemory>,
469    /// The emulated local APIC set.
470    lapic: VtlArray<LocalApicSet, 2>,
471    /// The emulated hypervisor state.
472    hv: GlobalHv<2>,
473    /// Guest VSM state.
474    guest_vsm: RwLock<GuestVsmState<CvmVtl1State>>,
475    /// Dma client for shared visibility pages.
476    shared_dma_client: Arc<dyn DmaClient>,
477    /// Dma client for private visibility pages.
478    private_dma_client: Arc<dyn DmaClient>,
479    hide_isolation: bool,
480    proxy_interrupt_redirect: bool,
481}
482
483#[cfg_attr(guest_arch = "aarch64", expect(dead_code))]
484impl UhCvmPartitionState {
485    fn vp_inner(&self, vp_index: u32) -> &UhCvmVpInner {
486        &self.vps[vp_index as usize]
487    }
488
489    fn is_lower_vtl_startup_denied(&self) -> bool {
490        matches!(
491            *self.guest_vsm.read(),
492            GuestVsmState::Enabled {
493                vtl1: CvmVtl1State {
494                    deny_lower_vtl_startup: true,
495                    ..
496                }
497            }
498        )
499    }
500}
501
502#[derive(Inspect)]
503/// Per-vp state for CVMs.
504struct UhCvmVpInner {
505    /// The current status of TLB locks
506    tlb_lock_info: VtlArray<TlbLockInfo, 2>,
507    /// Whether EnableVpVtl for VTL 1 has been called on this VP.
508    vtl1_enable_called: Mutex<bool>,
509    /// Whether the VP has been started via the StartVp hypercall.
510    started: AtomicBool,
511    /// Start context for StartVp and EnableVpVtl calls.
512    #[inspect(with = "|arr| inspect::iter_by_index(arr.iter().map(|v| v.lock().is_some()))")]
513    hv_start_enable_vtl_vp: VtlArray<Mutex<Option<Box<VpStartEnableVtl>>>, 2>,
514    /// Tracking of proxy redirect interrupts mapped on this VP.
515    #[inspect(with = "|x| inspect::adhoc(|req| inspect::iter_by_key(&*x.lock()).inspect(req))")]
516    proxy_redirect_interrupts: Mutex<HashMap<u32, ProxyRedirectVectorInfo>>,
517}
518
519#[cfg_attr(guest_arch = "aarch64", expect(dead_code))]
520#[derive(Inspect)]
521#[inspect(tag = "guest_vsm_state")]
522/// Partition-wide state for guest vsm.
523enum GuestVsmState<T: Inspect> {
524    NotPlatformSupported,
525    NotGuestEnabled,
526    Enabled {
527        #[inspect(flatten)]
528        vtl1: T,
529    },
530}
531
532impl<T: Inspect> GuestVsmState<T> {
533    pub fn from_availability(guest_vsm_available: bool) -> Self {
534        if guest_vsm_available {
535            GuestVsmState::NotGuestEnabled
536        } else {
537            GuestVsmState::NotPlatformSupported
538        }
539    }
540}
541
542#[derive(Inspect)]
543struct CvmVtl1State {
544    /// Whether VTL 1 has been enabled on any vp
545    enabled_on_any_vp: bool,
546    /// Whether guest memory should be zeroed before it resets.
547    zero_memory_on_reset: bool,
548    /// Whether a vp can be started or reset by a lower vtl.
549    deny_lower_vtl_startup: bool,
550    /// Whether Mode-Based Execution Control should be enforced on lower VTLs.
551    pub mbec_enabled: bool,
552    /// Whether shadow supervisor stack is enabled.
553    pub shadow_supervisor_stack_enabled: bool,
554    #[inspect(with = "|bb| inspect::iter_by_index(bb.iter().map(|v| *v))")]
555    io_read_intercepts: BitBox<u64>,
556    #[inspect(with = "|bb| inspect::iter_by_index(bb.iter().map(|v| *v))")]
557    io_write_intercepts: BitBox<u64>,
558}
559
560#[cfg_attr(guest_arch = "aarch64", expect(dead_code))]
561impl CvmVtl1State {
562    fn new(mbec_enabled: bool) -> Self {
563        Self {
564            enabled_on_any_vp: false,
565            zero_memory_on_reset: false,
566            deny_lower_vtl_startup: false,
567            mbec_enabled,
568            shadow_supervisor_stack_enabled: false,
569            io_read_intercepts: BitVec::repeat(false, u16::MAX as usize + 1).into_boxed_bitslice(),
570            io_write_intercepts: BitVec::repeat(false, u16::MAX as usize + 1).into_boxed_bitslice(),
571        }
572    }
573}
574
575#[cfg_attr(guest_arch = "aarch64", expect(dead_code))]
576struct TscReferenceTimeSource {
577    tsc_scale: u64,
578}
579
580#[cfg_attr(guest_arch = "aarch64", expect(dead_code))]
581impl TscReferenceTimeSource {
582    fn new(tsc_frequency: u64) -> Self {
583        TscReferenceTimeSource {
584            tsc_scale: (((10_000_000_u128) << 64) / tsc_frequency as u128) as u64,
585        }
586    }
587}
588
589/// A time implementation based on TSC.
590impl GetReferenceTime for TscReferenceTimeSource {
591    fn now(&self) -> ReferenceTimeResult {
592        #[cfg(guest_arch = "x86_64")]
593        {
594            let tsc = safe_intrinsics::rdtsc();
595            let ref_time = ((self.tsc_scale as u128 * tsc as u128) >> 64) as u64;
596            ReferenceTimeResult {
597                ref_time,
598                system_time: None,
599            }
600        }
601
602        #[cfg(guest_arch = "aarch64")]
603        {
604            todo!("AARCH64_TODO");
605        }
606    }
607}
608
609impl virt::irqcon::ControlGic for UhPartitionInner {
610    fn set_spi_irq(&self, irq_id: u32, high: bool) {
611        if let Err(err) = self.hcl.request_interrupt(
612            hvdef::HvInterruptControl::new()
613                .with_arm64_asserted(high)
614                .with_interrupt_type(hvdef::HvInterruptType::HvArm64InterruptTypeFixed),
615            0,
616            irq_id,
617            GuestVtl::Vtl0,
618        ) {
619            tracelimit::warn_ratelimited!(
620                error = &err as &dyn std::error::Error,
621                irq = irq_id,
622                asserted = high,
623                "failed to request spi"
624            );
625        }
626    }
627}
628
629impl virt::Aarch64Partition for UhPartition {
630    fn control_gic(&self, vtl: Vtl) -> Arc<dyn virt::irqcon::ControlGic> {
631        debug_assert!(vtl == Vtl::Vtl0);
632        self.inner.clone()
633    }
634}
635
636/// A wrapper around [`UhProcessor`] that is [`Send`].
637///
638/// This is used to instantiate the processor object on the correct thread,
639/// since all lower VTL processor state accesses must occur from the same
640/// processor at VTL2.
641pub struct UhProcessorBox {
642    partition: Arc<UhPartitionInner>,
643    vp_info: TargetVpInfo,
644}
645
646impl UhProcessorBox {
647    /// Returns the VP index.
648    pub fn vp_index(&self) -> VpIndex {
649        self.vp_info.base.vp_index
650    }
651
652    /// Returns the base CPU that manages this processor, when it is a sidecar
653    /// VP.
654    pub fn sidecar_base_cpu(&self) -> Option<u32> {
655        self.partition
656            .hcl
657            .sidecar_base_cpu(self.vp_info.base.vp_index.index())
658    }
659
660    /// Returns the processor object, bound to this thread.
661    ///
662    /// If `control` is provided, then this must be called on the VP's
663    /// associated thread pool thread, and it will dispatch the VP directly.
664    /// Otherwise, the processor will control the processor via the sidecar
665    /// kernel.
666    pub fn bind_processor<'a, T: Backing>(
667        &'a mut self,
668        driver: &impl Driver,
669        control: Option<&'a mut IdleControl>,
670    ) -> Result<UhProcessor<'a, T>, Error> {
671        if let Some(control) = &control {
672            let vp_index = self.vp_info.base.vp_index;
673
674            let mut current = Default::default();
675            affinity::get_current_thread_affinity(&mut current).unwrap();
676            assert_eq!(&current, CpuSet::new().set(vp_index.index()));
677
678            self.partition
679                .hcl
680                .set_poll_file(
681                    self.partition.vp(vp_index).unwrap().cpu_index,
682                    control.ring_fd().as_raw_fd(),
683                )
684                .map_err(Error::Hcl)?;
685        }
686
687        UhProcessor::new(driver, &self.partition, self.vp_info, control)
688    }
689
690    /// Sets the sidecar remove reason for the processor to be due to a task
691    /// running with the given name.
692    ///
693    /// This is useful for diagnostics.
694    pub fn set_sidecar_exit_due_to_task(&self, task: Arc<str>) {
695        self.partition
696            .vp(self.vp_info.base.vp_index)
697            .unwrap()
698            .set_sidecar_exit_reason(SidecarExitReason::TaskRequest(task))
699    }
700}
701
702#[derive(Debug, Inspect)]
703struct UhVpInner {
704    /// 32 bits per VTL: top bits are VTL 1, bottom bits are VTL 0.
705    wake_reasons: AtomicU64,
706    #[inspect(skip)]
707    waker: RwLock<Option<Waker>>,
708    message_queues: VtlArray<MessageQueues, 2>,
709    #[inspect(skip)]
710    vp_info: TargetVpInfo,
711    /// The Linux kernel's CPU index for this VP. This should be used instead of VpIndex
712    /// when interacting with non-MSHV kernel interfaces.
713    cpu_index: u32,
714    sidecar_exit_reason: Mutex<Option<SidecarExitReason>>,
715}
716
717impl UhVpInner {
718    pub fn vp_index(&self) -> VpIndex {
719        self.vp_info.base.vp_index
720    }
721}
722
723#[cfg_attr(not(guest_arch = "x86_64"), expect(dead_code))]
724#[derive(Debug, Inspect)]
725/// Which operation is setting the initial vp context
726enum InitialVpContextOperation {
727    /// The VP is being started via the StartVp hypercall.
728    StartVp,
729    /// The VP is being started via the EnableVpVtl hypercall.
730    EnableVpVtl,
731}
732
733#[cfg_attr(not(guest_arch = "x86_64"), expect(dead_code))]
734#[derive(Debug, Inspect)]
735/// State for handling StartVp/EnableVpVtl hypercalls.
736struct VpStartEnableVtl {
737    /// Which operation, startvp or enablevpvtl, is setting the initial vp
738    /// context
739    operation: InitialVpContextOperation,
740    #[inspect(skip)]
741    context: hvdef::hypercall::InitialVpContextX64,
742}
743
744#[derive(Debug, Inspect)]
745struct TlbLockInfo {
746    /// The set of VPs that are waiting for this VP to release the TLB lock.
747    #[inspect(with = "|bb| inspect::iter_by_index(bb.iter().map(|v| *v))")]
748    blocked_vps: BitBox<AtomicU64>,
749    /// The set of VPs that are holding the TLB lock and preventing this VP
750    /// from proceeding.
751    #[inspect(with = "|bb| inspect::iter_by_index(bb.iter().map(|v| *v))")]
752    blocking_vps: BitBox<AtomicU64>,
753    /// The count of blocking VPs. This should always be equivalent to
754    /// `blocking_vps.count_ones()`, however it is accessible in a single
755    /// atomic operation while counting is not.
756    blocking_vp_count: AtomicU32,
757    /// Whether the VP is sleeping due to a TLB lock.
758    sleeping: AtomicBool,
759}
760
761#[cfg_attr(not(guest_arch = "x86_64"), expect(dead_code))]
762impl TlbLockInfo {
763    fn new(vp_count: usize) -> Self {
764        Self {
765            blocked_vps: BitVec::repeat(false, vp_count).into_boxed_bitslice(),
766            blocking_vps: BitVec::repeat(false, vp_count).into_boxed_bitslice(),
767            blocking_vp_count: AtomicU32::new(0),
768            sleeping: false.into(),
769        }
770    }
771}
772
773#[bitfield(u32)]
774#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
775struct WakeReason {
776    extint: bool,
777    message_queues: bool,
778    hv_start_enable_vtl_vp: bool,
779    intcon: bool,
780    update_proxy_irr_filter: bool,
781    #[bits(27)]
782    _reserved: u32,
783}
784
785impl WakeReason {
786    // Convenient constants.
787    const EXTINT: Self = Self::new().with_extint(true);
788    const MESSAGE_QUEUES: Self = Self::new().with_message_queues(true);
789    #[cfg(guest_arch = "x86_64")]
790    const HV_START_ENABLE_VP_VTL: Self = Self::new().with_hv_start_enable_vtl_vp(true); // StartVp/EnableVpVtl handling
791    const INTCON: Self = Self::new().with_intcon(true);
792    #[cfg(guest_arch = "x86_64")]
793    const UPDATE_PROXY_IRR_FILTER: Self = Self::new().with_update_proxy_irr_filter(true);
794}
795
796#[bitfield(u32)]
797#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
798struct ExitActivity {
799    pending_event: bool,
800    #[bits(31)]
801    _reserved: u32,
802}
803
804/// Immutable access to useful bits of Partition state.
805impl UhPartition {
806    /// Revokes guest VSM.
807    pub fn revoke_guest_vsm(&self) -> Result<(), RevokeGuestVsmError> {
808        fn revoke<T: Inspect>(vsm_state: &mut GuestVsmState<T>) -> Result<(), RevokeGuestVsmError> {
809            if matches!(vsm_state, GuestVsmState::Enabled { .. }) {
810                return Err(RevokeGuestVsmError::Vtl1AlreadyEnabled);
811            }
812            *vsm_state = GuestVsmState::NotPlatformSupported;
813            Ok(())
814        }
815
816        match &self.inner.backing_shared {
817            BackingShared::Hypervisor(s) => {
818                revoke(&mut *s.guest_vsm.write())?;
819                self.inner
820                    .hcl
821                    .set_guest_vsm_partition_config(false)
822                    .map_err(RevokeGuestVsmError::SetGuestVsmConfig)?;
823            }
824            #[cfg(guest_arch = "x86_64")]
825            BackingShared::Snp(SnpBackedShared { cvm, .. })
826            | BackingShared::Tdx(TdxBackedShared { cvm, .. }) => {
827                revoke(&mut *cvm.guest_vsm.write())?;
828            }
829        };
830
831        Ok(())
832    }
833
834    /// Returns the current hypervisor reference time, in 100ns units.
835    pub fn reference_time(&self) -> u64 {
836        if let Some(hv) = self.inner.hv() {
837            hv.ref_time_source().now().ref_time
838        } else {
839            self.inner
840                .hcl
841                .reference_time()
842                .expect("should not fail to get the reference time")
843        }
844    }
845}
846
847impl virt::Partition for UhPartition {
848    fn supports_reset(&self) -> Option<&dyn virt::ResetPartition<Error = Self::Error>> {
849        None
850    }
851
852    fn caps(&self) -> &PartitionCapabilities {
853        &self.inner.caps
854    }
855
856    fn request_msi(&self, vtl: Vtl, request: MsiRequest) {
857        self.inner
858            .request_msi(vtl.try_into().expect("higher vtl not configured"), request)
859    }
860
861    fn request_yield(&self, _vp_index: VpIndex) {
862        unimplemented!()
863    }
864}
865
866impl X86Partition for UhPartition {
867    fn ioapic_routing(&self) -> Arc<dyn IoApicRouting> {
868        self.inner.clone()
869    }
870
871    fn pulse_lint(&self, vp_index: VpIndex, vtl: Vtl, lint: u8) {
872        let vtl = GuestVtl::try_from(vtl).expect("higher vtl not configured");
873        if let Some(apic) = &self.inner.lapic(vtl) {
874            apic.lint(vp_index, lint.into(), |vp_index| {
875                self.inner
876                    .vp(vp_index)
877                    .unwrap()
878                    .wake(vtl, WakeReason::INTCON);
879            });
880        } else if lint == 0 {
881            self.inner
882                .vp(vp_index)
883                .unwrap()
884                .wake(vtl, WakeReason::EXTINT);
885        } else {
886            unimplemented!()
887        }
888    }
889}
890
891impl UhPartitionInner {
892    fn vp(&self, index: VpIndex) -> Option<&'_ UhVpInner> {
893        self.vps.get(index.index() as usize)
894    }
895
896    fn lapic(&self, vtl: GuestVtl) -> Option<&LocalApicSet> {
897        self.backing_shared.cvm_state().map(|x| &x.lapic[vtl])
898    }
899
900    fn hv(&self) -> Option<&GlobalHv<2>> {
901        self.backing_shared.cvm_state().map(|x| &x.hv)
902    }
903
904    /// For requester VP to issue `proxy_irr_blocked` update to other VPs
905    #[cfg(guest_arch = "x86_64")]
906    fn request_proxy_irr_filter_update(
907        &self,
908        vtl: GuestVtl,
909        device_vector: u8,
910        req_vp_index: VpIndex,
911    ) {
912        tracing::debug!(
913            ?vtl,
914            device_vector,
915            req_vp_index = req_vp_index.index(),
916            "request_proxy_irr_filter_update"
917        );
918
919        // Add given vector to partition global device vector table (VTL0 only for now)
920        {
921            let mut device_vector_table = self.device_vector_table.write();
922            device_vector_table.set(device_vector as usize, true);
923        }
924
925        // Wake all other VPs for their `proxy_irr_blocked` filter update
926        for vp in self.vps.iter() {
927            if vp.vp_index() != req_vp_index {
928                vp.wake(vtl, WakeReason::UPDATE_PROXY_IRR_FILTER);
929            }
930        }
931    }
932
933    /// Get current partition global device irr vectors (VTL0 for now)
934    #[cfg(guest_arch = "x86_64")]
935    fn fill_device_vectors(&self, _vtl: GuestVtl, irr_vectors: &mut IrrBitmap) {
936        let device_vector_table = self.device_vector_table.read();
937        for idx in device_vector_table.iter_ones() {
938            irr_vectors.set(idx, true);
939        }
940    }
941
942    fn inspect_extra(&self, resp: &mut inspect::Response<'_>) {
943        let mut wake_vps = false;
944        resp.field_mut(
945            "enter_modes",
946            &mut inspect::adhoc_mut(|req| {
947                let update = req.is_update();
948                {
949                    let mut modes = self.enter_modes.lock();
950                    modes.inspect_mut(req);
951                    if update {
952                        self.enter_modes_atomic.store(
953                            hcl::protocol::EnterModes::from(*modes).into(),
954                            Ordering::Relaxed,
955                        );
956                        wake_vps = true;
957                    }
958                }
959            }),
960        );
961
962        // Wake VPs to propagate updates.
963        if wake_vps {
964            for vp in self.vps.iter() {
965                vp.wake_vtl2();
966            }
967        }
968    }
969
970    // TODO VBS GUEST VSM: enable for aarch64
971    #[cfg_attr(guest_arch = "aarch64", expect(dead_code))]
972    fn vsm_status(
973        &self,
974    ) -> Result<HvRegisterVsmPartitionStatus, hcl::ioctl::register::GetRegError> {
975        // TODO: It might be possible to cache VsmPartitionStatus.
976        self.hcl.get_vsm_partition_status()
977    }
978}
979
980impl virt::Synic for UhPartition {
981    fn post_message(&self, vtl: Vtl, vp_index: VpIndex, sint: u8, typ: u32, payload: &[u8]) {
982        let vtl = GuestVtl::try_from(vtl).expect("higher vtl not configured");
983        let Some(vp) = self.inner.vp(vp_index) else {
984            tracelimit::warn_ratelimited!(
985                CVM_ALLOWED,
986                vp = vp_index.index(),
987                "invalid vp target for post_message"
988            );
989            return;
990        };
991
992        vp.post_message(
993            vtl,
994            sint,
995            &hvdef::HvMessage::new(hvdef::HvMessageType(typ), 0, payload),
996        );
997    }
998
999    fn new_guest_event_port(
1000        &self,
1001        vtl: Vtl,
1002        vp: u32,
1003        sint: u8,
1004        flag: u16,
1005    ) -> Box<dyn vmcore::synic::GuestEventPort> {
1006        let vtl = GuestVtl::try_from(vtl).expect("higher vtl not configured");
1007        Box::new(UhEventPort {
1008            partition: Arc::downgrade(&self.inner),
1009            params: Arc::new(Mutex::new(UhEventPortParams {
1010                vp: VpIndex::new(vp),
1011                sint,
1012                flag,
1013                vtl,
1014            })),
1015        })
1016    }
1017
1018    fn prefer_os_events(&self) -> bool {
1019        false
1020    }
1021
1022    fn monitor_support(&self) -> Option<&dyn virt::SynicMonitor> {
1023        Some(self)
1024    }
1025}
1026
1027impl virt::SynicMonitor for UhPartition {
1028    fn set_monitor_page(&self, vtl: Vtl, gpa: Option<u64>) -> anyhow::Result<()> {
1029        // Keep this locked the whole function to avoid racing with allocate_monitor_page.
1030        let mut allocated_block = self.inner.allocated_monitor_page.lock();
1031        let old_gpa = self.inner.monitor_page.set_gpa(gpa);
1032
1033        // Take ownership of any allocated monitor page so it will be freed on function exit.
1034        let allocated_page = allocated_block.take();
1035        if let Some(old_gpa) = old_gpa {
1036            let allocated_gpa = allocated_page
1037                .as_ref()
1038                .map(|b| b.pfns()[0] << HV_PAGE_SHIFT);
1039
1040            // Revert the old page's permissions, using the appropriate method depending on
1041            // whether it was allocated or guest-supplied.
1042            let result = if allocated_gpa == Some(old_gpa) {
1043                let vtl = GuestVtl::try_from(vtl).unwrap();
1044                self.unregister_cvm_dma_overlay_page(vtl, old_gpa >> HV_PAGE_SHIFT)
1045            } else {
1046                self.inner
1047                    .hcl
1048                    .modify_vtl_protection_mask(
1049                        MemoryRange::new(old_gpa..old_gpa + HV_PAGE_SIZE),
1050                        hvdef::HV_MAP_GPA_PERMISSIONS_ALL,
1051                        HvInputVtl::CURRENT_VTL,
1052                    )
1053                    .map_err(|err| anyhow::anyhow!(err))
1054            };
1055
1056            result
1057                .context("failed to unregister old monitor page")
1058                .inspect_err(|_| {
1059                    // Leave the page unset if returning a failure.
1060                    self.inner.monitor_page.set_gpa(None);
1061                })?;
1062
1063            tracing::debug!(old_gpa, "unregistered monitor page");
1064        }
1065
1066        if let Some(gpa) = gpa {
1067            // Disallow VTL0 from writing to the page, so we'll get an intercept. Note that read
1068            // permissions must be enabled or this doesn't work correctly.
1069            self.inner
1070                .hcl
1071                .modify_vtl_protection_mask(
1072                    MemoryRange::new(gpa..gpa + HV_PAGE_SIZE),
1073                    HvMapGpaFlags::new().with_readable(true),
1074                    HvInputVtl::CURRENT_VTL,
1075                )
1076                .context("failed to register monitor page")
1077                .inspect_err(|_| {
1078                    // Leave the page unset if returning a failure.
1079                    self.inner.monitor_page.set_gpa(None);
1080                })?;
1081
1082            tracing::debug!(gpa, "registered monitor page");
1083        }
1084
1085        Ok(())
1086    }
1087
1088    fn register_monitor(
1089        &self,
1090        monitor_id: vmcore::monitor::MonitorId,
1091        connection_id: u32,
1092    ) -> Box<dyn Sync + Send> {
1093        self.inner
1094            .monitor_page
1095            .register_monitor(monitor_id, connection_id)
1096    }
1097
1098    fn allocate_monitor_page(&self, vtl: Vtl) -> anyhow::Result<Option<u64>> {
1099        let vtl = GuestVtl::try_from(vtl).unwrap();
1100
1101        // Allocating a monitor page is only supported for CVMs.
1102        let Some(state) = self.inner.backing_shared.cvm_state() else {
1103            return Ok(None);
1104        };
1105
1106        let mut allocated_block = self.inner.allocated_monitor_page.lock();
1107        if let Some(block) = allocated_block.as_ref() {
1108            // An allocated monitor page is already in use; no need to change it.
1109            let gpa = block.pfns()[0] << HV_PAGE_SHIFT;
1110            assert_eq!(self.inner.monitor_page.gpa(), Some(gpa));
1111            return Ok(Some(gpa));
1112        }
1113
1114        let block = state
1115            .private_dma_client
1116            .allocate_dma_buffer(HV_PAGE_SIZE_USIZE)
1117            .context("failed to allocate monitor page")?;
1118
1119        let gpn = block.pfns()[0];
1120        *allocated_block = Some(block);
1121        let gpa = gpn << HV_PAGE_SHIFT;
1122        let old_gpa = self.inner.monitor_page.set_gpa(Some(gpa));
1123        if let Some(old_gpa) = old_gpa {
1124            // The old GPA is guaranteed not to be allocated, since that was checked above, so
1125            // revert its permissions using the method for guest-supplied memory.
1126            self.inner
1127                .hcl
1128                .modify_vtl_protection_mask(
1129                    MemoryRange::new(old_gpa..old_gpa + HV_PAGE_SIZE),
1130                    hvdef::HV_MAP_GPA_PERMISSIONS_ALL,
1131                    HvInputVtl::CURRENT_VTL,
1132                )
1133                .context("failed to unregister old monitor page")
1134                .inspect_err(|_| {
1135                    // Leave the page unset if returning a failure.
1136                    self.inner.monitor_page.set_gpa(None);
1137                })?;
1138
1139            tracing::debug!(old_gpa, "unregistered monitor page");
1140        }
1141
1142        // Disallow VTL0 from writing to the page, so we'll get an intercept. Note that read
1143        // permissions must be enabled or this doesn't work correctly.
1144        self.register_cvm_dma_overlay_page(vtl, gpn, HvMapGpaFlags::new().with_readable(true))
1145            .context("failed to unregister monitor page")
1146            .inspect_err(|_| {
1147                // Leave the page unset if returning a failure.
1148                self.inner.monitor_page.set_gpa(None);
1149            })?;
1150
1151        tracing::debug!(gpa, "registered allocated monitor page");
1152
1153        Ok(Some(gpa))
1154    }
1155}
1156
1157impl UhPartitionInner {
1158    #[cfg(guest_arch = "x86_64")]
1159    pub(crate) fn synic_interrupt(
1160        &self,
1161        vp_index: VpIndex,
1162        vtl: GuestVtl,
1163    ) -> impl '_ + hv1_emulator::RequestInterrupt {
1164        // TODO CVM: optimize for SNP with secure avic to avoid internal wake
1165        // and for TDX to avoid trip to user mode
1166        move |vector, auto_eoi| {
1167            self.lapic(vtl).unwrap().synic_interrupt(
1168                vp_index,
1169                vector as u8,
1170                auto_eoi,
1171                |vp_index| self.vp(vp_index).unwrap().wake(vtl, WakeReason::INTCON),
1172            );
1173        }
1174    }
1175
1176    #[cfg(guest_arch = "aarch64")]
1177    fn synic_interrupt(
1178        &self,
1179        _vp_index: VpIndex,
1180        _vtl: GuestVtl,
1181    ) -> impl '_ + hv1_emulator::RequestInterrupt {
1182        move |_, _| {}
1183    }
1184}
1185
1186#[derive(Debug)]
1187struct UhEventPort {
1188    partition: Weak<UhPartitionInner>,
1189    params: Arc<Mutex<UhEventPortParams>>,
1190}
1191
1192#[derive(Debug, Copy, Clone)]
1193struct UhEventPortParams {
1194    vp: VpIndex,
1195    sint: u8,
1196    flag: u16,
1197    vtl: GuestVtl,
1198}
1199
1200impl vmcore::synic::GuestEventPort for UhEventPort {
1201    fn interrupt(&self) -> vmcore::interrupt::Interrupt {
1202        let partition = self.partition.clone();
1203        let params = self.params.clone();
1204        vmcore::interrupt::Interrupt::from_fn(move || {
1205            let UhEventPortParams {
1206                vp,
1207                sint,
1208                flag,
1209                vtl,
1210            } = *params.lock();
1211            let Some(partition) = partition.upgrade() else {
1212                return;
1213            };
1214            tracing::trace!(vp = vp.index(), sint, flag, "signal_event");
1215            if let Some(hv) = partition.hv() {
1216                match hv.synic[vtl].signal_event(
1217                    vp,
1218                    sint,
1219                    flag,
1220                    &mut partition.synic_interrupt(vp, vtl),
1221                ) {
1222                    Ok(_) => {}
1223                    Err(SintProxied) => {
1224                        tracing::trace!(
1225                            vp = vp.index(),
1226                            sint,
1227                            flag,
1228                            "forwarding event to untrusted synic"
1229                        );
1230                        if let Some(synic) = partition.backing_shared.untrusted_synic() {
1231                            synic
1232                                .signal_event(
1233                                    vp,
1234                                    sint,
1235                                    flag,
1236                                    &mut partition.synic_interrupt(vp, vtl),
1237                                )
1238                                .ok();
1239                        } else {
1240                            partition.hcl.signal_event_direct(vp.index(), sint, flag)
1241                        }
1242                    }
1243                }
1244            } else {
1245                partition.hcl.signal_event_direct(vp.index(), sint, flag);
1246            }
1247        })
1248    }
1249
1250    fn set_target_vp(&mut self, vp: u32) -> Result<(), vmcore::synic::HypervisorError> {
1251        self.params.lock().vp = VpIndex::new(vp);
1252        Ok(())
1253    }
1254}
1255
1256impl virt::Hv1 for UhPartition {
1257    type Error = Error;
1258    type Device = virt::x86::apic_software_device::ApicSoftwareDevice;
1259
1260    fn reference_time_source(&self) -> Option<ReferenceTimeSource> {
1261        Some(if let Some(hv) = self.inner.hv() {
1262            hv.ref_time_source().clone()
1263        } else {
1264            ReferenceTimeSource::from(self.inner.clone() as Arc<_>)
1265        })
1266    }
1267
1268    fn new_virtual_device(
1269        &self,
1270    ) -> Option<&dyn virt::DeviceBuilder<Device = Self::Device, Error = Self::Error>> {
1271        self.inner.software_devices.is_some().then_some(self)
1272    }
1273}
1274
1275impl GetReferenceTime for UhPartitionInner {
1276    fn now(&self) -> ReferenceTimeResult {
1277        ReferenceTimeResult {
1278            ref_time: self.hcl.reference_time().unwrap(),
1279            system_time: None,
1280        }
1281    }
1282}
1283
1284impl virt::DeviceBuilder for UhPartition {
1285    fn build(&self, vtl: Vtl, device_id: u64) -> Result<Self::Device, Self::Error> {
1286        let vtl = GuestVtl::try_from(vtl).expect("higher vtl not configured");
1287        let device = self
1288            .inner
1289            .software_devices
1290            .as_ref()
1291            .expect("checked in new_virtual_device")
1292            .new_device(self.interrupt_targets[vtl].clone(), device_id)
1293            .map_err(Error::NewDevice)?;
1294
1295        Ok(device)
1296    }
1297}
1298
1299struct UhInterruptTarget {
1300    partition: Arc<UhPartitionInner>,
1301    vtl: GuestVtl,
1302}
1303
1304impl pci_core::msi::SignalMsi for UhInterruptTarget {
1305    fn signal_msi(&self, _rid: u32, address: u64, data: u32) {
1306        self.partition
1307            .request_msi(self.vtl, MsiRequest { address, data });
1308    }
1309}
1310
1311impl UhPartitionInner {
1312    fn request_msi(&self, vtl: GuestVtl, request: MsiRequest) {
1313        if let Some(lapic) = self.lapic(vtl) {
1314            tracing::trace!(?request, "interrupt");
1315            lapic.request_interrupt(request.address, request.data, |vp_index| {
1316                self.vp(vp_index).unwrap().wake(vtl, WakeReason::INTCON)
1317            });
1318        } else {
1319            let (address, data) = request.as_x86();
1320            if let Err(err) = self.hcl.request_interrupt(
1321                request.hv_x86_interrupt_control(),
1322                address.virt_destination().into(),
1323                data.vector().into(),
1324                vtl,
1325            ) {
1326                tracelimit::warn_ratelimited!(
1327                    CVM_ALLOWED,
1328                    error = &err as &dyn std::error::Error,
1329                    address = request.address,
1330                    data = request.data,
1331                    "failed to request msi"
1332                );
1333            }
1334        }
1335    }
1336}
1337
1338impl IoApicRouting for UhPartitionInner {
1339    fn set_irq_route(&self, irq: u8, request: Option<MsiRequest>) {
1340        self.irq_routes.set_irq_route(irq, request)
1341    }
1342
1343    // The IO-APIC is always hooked up to VTL0.
1344    fn assert_irq(&self, irq: u8) {
1345        self.irq_routes
1346            .assert_irq(irq, |request| self.request_msi(GuestVtl::Vtl0, request))
1347    }
1348}
1349
1350// xtask-fmt allow-target-arch cpu-intrinsic
1351#[cfg(target_arch = "x86_64")]
1352fn is_restore_partition_time_available() -> bool {
1353    let result =
1354        safe_intrinsics::cpuid(hvdef::HV_CPUID_FUNCTION_MS_HV_ENLIGHTENMENT_INFORMATION, 0);
1355    let enlightenment_info = hvdef::HvEnlightenmentInformation::from(
1356        result.eax as u128
1357            | (result.ebx as u128) << 32
1358            | (result.ecx as u128) << 64
1359            | (result.edx as u128) << 96,
1360    );
1361    enlightenment_info.restore_time_on_resume()
1362}
1363// xtask-fmt allow-target-arch cpu-intrinsic
1364#[cfg(not(target_arch = "x86_64"))]
1365fn is_restore_partition_time_available() -> bool {
1366    // Only available on x86_64 Hyper-V hypervisor.
1367    false
1368}
1369
1370/// Configure the [`hvdef::HvRegisterVsmPartitionConfig`] register with the
1371/// values used by underhill.
1372fn set_vtl2_vsm_partition_config(hcl: &Hcl) -> Result<(), Error> {
1373    // Read available capabilities to determine what to enable.
1374    let caps = hcl.get_vsm_capabilities().map_err(Error::GetReg)?;
1375    let hardware_isolated = hcl.isolation().is_hardware_isolated();
1376    let isolated = hcl.isolation().is_isolated();
1377    let config = HvRegisterVsmPartitionConfig::new()
1378        .with_default_vtl_protection_mask(0xF)
1379        .with_enable_vtl_protection(!hardware_isolated)
1380        .with_zero_memory_on_reset(!hardware_isolated)
1381        .with_intercept_cpuid_unimplemented(!hardware_isolated)
1382        .with_intercept_page(caps.intercept_page_available())
1383        .with_intercept_unrecoverable_exception(true)
1384        .with_intercept_not_present(caps.intercept_not_present_available() && !isolated)
1385        .with_intercept_acceptance(isolated)
1386        .with_intercept_enable_vtl_protection(isolated && !hardware_isolated)
1387        .with_intercept_system_reset(caps.intercept_system_reset_available())
1388        .with_intercept_restore_partition_time(is_restore_partition_time_available());
1389
1390    hcl.set_vtl2_vsm_partition_config(config)
1391        .map_err(Error::SetReg)
1392}
1393
1394/// Configuration parameters supplied to [`UhProtoPartition::new`].
1395///
1396/// These do not include runtime resources.
1397pub struct UhPartitionNewParams<'a> {
1398    /// The isolation type for the partition.
1399    pub isolation: IsolationType,
1400    /// Hide isolation from the guest. The guest will run as if it is not
1401    /// isolated.
1402    pub hide_isolation: bool,
1403    /// The memory layout for lower VTLs.
1404    pub lower_vtl_memory_layout: &'a MemoryLayout,
1405    /// The guest processor topology.
1406    pub topology: &'a ProcessorTopology,
1407    /// The unparsed CVM cpuid info.
1408    // TODO: move parsing up a layer.
1409    pub cvm_cpuid_info: Option<&'a [u8]>,
1410    /// The unparsed CVM secrets page.
1411    pub snp_secrets: Option<&'a [u8]>,
1412    /// The virtual top of memory for hardware-isolated VMs.
1413    ///
1414    /// Must be a power of two.
1415    pub vtom: Option<u64>,
1416    /// Handle synic messages and events.
1417    ///
1418    /// On TDX, this prevents the hypervisor from getting vmtdcall exits.
1419    pub handle_synic: bool,
1420    /// Do not hotplug sidecar VPs on their first exit. Just continue running
1421    /// the VP remotely.
1422    pub no_sidecar_hotplug: bool,
1423    /// Use MMIO access hypercalls.
1424    pub use_mmio_hypercalls: bool,
1425    /// Intercept guest debug exceptions to support gdbstub.
1426    pub intercept_debug_exceptions: bool,
1427    /// Disable proxy interrupt redirection.
1428    pub disable_proxy_redirect: bool,
1429    /// Disable lower VTL timer virtualization.
1430    pub disable_lower_vtl_timer_virt: bool,
1431}
1432
1433/// Parameters to [`UhProtoPartition::build`].
1434pub struct UhLateParams<'a> {
1435    /// Guest memory for lower VTLs.
1436    pub gm: VtlArray<GuestMemory, 2>,
1437    /// Guest memory for VTL 0 kernel execute access.
1438    pub vtl0_kernel_exec_gm: GuestMemory,
1439    /// Guest memory for VTL 0 user execute access.
1440    pub vtl0_user_exec_gm: GuestMemory,
1441    /// The CPUID leaves to expose to the guest.
1442    #[cfg(guest_arch = "x86_64")]
1443    pub cpuid: Vec<CpuidLeaf>,
1444    /// The mesh sender to use for crash notifications.
1445    // FUTURE: remove mesh dependency from this layer.
1446    pub crash_notification_send: mesh::Sender<VtlCrash>,
1447    /// The VM time source.
1448    pub vmtime: &'a VmTimeSource,
1449    /// Parameters for CVMs only.
1450    pub cvm_params: Option<CvmLateParams>,
1451    /// vmbus_relay is enabled and active for partition
1452    pub vmbus_relay: bool,
1453}
1454
1455/// CVM-only parameters to [`UhProtoPartition::build`].
1456pub struct CvmLateParams {
1457    /// Guest memory for untrusted devices, like overlay pages.
1458    pub shared_gm: GuestMemory,
1459    /// An object to call to change host visibility on guest memory.
1460    pub isolated_memory_protector: Arc<dyn ProtectIsolatedMemory>,
1461    /// Dma client for shared visibility pages.
1462    pub shared_dma_client: Arc<dyn DmaClient>,
1463    /// Allocator for private visibility pages.
1464    pub private_dma_client: Arc<dyn DmaClient>,
1465}
1466
1467/// Represents a GPN that is either in guest memory or was allocated by dma_client.
1468#[derive(Debug, Copy, Clone, PartialEq, Eq)]
1469pub enum GpnSource {
1470    /// The GPN is in regular guest RAM.
1471    GuestMemory,
1472    /// The GPN was allocated by dma_client and is not in guest RAM.
1473    Dma,
1474}
1475
1476/// Trait for CVM-related protections on guest memory.
1477pub trait ProtectIsolatedMemory: Send + Sync {
1478    /// Changes host visibility on guest memory.
1479    fn change_host_visibility(
1480        &self,
1481        vtl: GuestVtl,
1482        shared: bool,
1483        gpns: &[u64],
1484        tlb_access: &mut dyn TlbFlushLockAccess,
1485    ) -> Result<(), (HvError, usize)>;
1486
1487    /// Queries host visibility on guest memory.
1488    fn query_host_visibility(
1489        &self,
1490        gpns: &[u64],
1491        host_visibility: &mut [HostVisibilityType],
1492    ) -> Result<(), (HvError, usize)>;
1493
1494    /// Gets the default protections/permissions for VTL 0.
1495    fn default_vtl0_protections(&self) -> HvMapGpaFlags;
1496
1497    /// Changes the default protections/permissions for a VTL. For VBS-isolated
1498    /// VMs, the protections apply to all vtls lower than the specified one. For
1499    /// hardware-isolated VMs, they apply just to the given vtl.
1500    fn change_default_vtl_protections(
1501        &self,
1502        target_vtl: GuestVtl,
1503        protections: HvMapGpaFlags,
1504        tlb_access: &mut dyn TlbFlushLockAccess,
1505    ) -> Result<(), HvError>;
1506
1507    /// Changes the vtl protections on a range of guest memory.
1508    fn change_vtl_protections(
1509        &self,
1510        target_vtl: GuestVtl,
1511        gpns: &[u64],
1512        protections: HvMapGpaFlags,
1513        tlb_access: &mut dyn TlbFlushLockAccess,
1514    ) -> Result<(), (HvError, usize)>;
1515
1516    /// Registers a page as an overlay page by first validating it has the
1517    /// required permissions, optionally modifying them, then locking them.
1518    fn register_overlay_page(
1519        &self,
1520        vtl: GuestVtl,
1521        gpn: u64,
1522        gpn_source: GpnSource,
1523        check_perms: HvMapGpaFlags,
1524        new_perms: Option<HvMapGpaFlags>,
1525        tlb_access: &mut dyn TlbFlushLockAccess,
1526    ) -> Result<(), HvError>;
1527
1528    /// Unregisters an overlay page, removing its permission lock and restoring
1529    /// the previous permissions.
1530    fn unregister_overlay_page(
1531        &self,
1532        vtl: GuestVtl,
1533        gpn: u64,
1534        tlb_access: &mut dyn TlbFlushLockAccess,
1535    ) -> Result<(), HvError>;
1536
1537    /// Checks whether a page is currently registered as an overlay page.
1538    fn is_overlay_page(&self, vtl: GuestVtl, gpn: u64) -> bool;
1539
1540    /// Locks the permissions and mappings for a set of guest pages.
1541    fn lock_gpns(&self, vtl: GuestVtl, gpns: &[u64]) -> Result<(), GuestMemoryBackingError>;
1542
1543    /// Unlocks the permissions and mappings for a set of guest pages.
1544    ///
1545    /// Panics if asked to unlock a page that was not previously locked. The
1546    /// caller must ensure that the given slice has the same ordering as the
1547    /// one passed to `lock_gpns`.
1548    fn unlock_gpns(&self, vtl: GuestVtl, gpns: &[u64]);
1549
1550    /// Alerts the memory protector that vtl 1 is ready to set vtl protections
1551    /// on lower-vtl memory, and that these protections should be enforced.
1552    fn set_vtl1_protections_enabled(&self);
1553
1554    /// Whether VTL 1 is prepared to modify vtl protections on lower-vtl memory,
1555    /// and therefore whether these protections should be enforced.
1556    fn vtl1_protections_enabled(&self) -> bool;
1557}
1558
1559/// Trait for access to TLB flush and lock machinery.
1560pub trait TlbFlushLockAccess {
1561    /// Flush the entire TLB for all VPs for the given VTL.
1562    fn flush(&mut self, vtl: GuestVtl);
1563
1564    /// Flush the entire TLB for all VPs for all VTLs.
1565    fn flush_entire(&mut self);
1566
1567    /// Causes the specified VTL on the current VP to wait on all TLB locks.
1568    fn set_wait_for_tlb_locks(&mut self, vtl: GuestVtl);
1569}
1570
1571/// A partially built partition. Used to allow querying partition capabilities
1572/// before fully instantiating the partition.
1573pub struct UhProtoPartition<'a> {
1574    params: UhPartitionNewParams<'a>,
1575    hcl: Hcl,
1576    guest_vsm_available: bool,
1577    create_partition_available: bool,
1578    #[cfg(guest_arch = "x86_64")]
1579    cpuid: virt::CpuidLeafSet,
1580}
1581
1582impl<'a> UhProtoPartition<'a> {
1583    /// Creates a new prototype partition.
1584    ///
1585    /// `driver(cpu)` returns the driver to use for polling the sidecar device
1586    /// whose base CPU is `cpu`.
1587    pub fn new<T: SpawnDriver>(
1588        params: UhPartitionNewParams<'a>,
1589        driver: impl FnMut(u32) -> T,
1590    ) -> Result<Self, Error> {
1591        let hcl_isolation = match params.isolation {
1592            IsolationType::None => hcl::ioctl::IsolationType::None,
1593            IsolationType::Vbs => hcl::ioctl::IsolationType::Vbs,
1594            IsolationType::Snp => hcl::ioctl::IsolationType::Snp,
1595            IsolationType::Tdx => hcl::ioctl::IsolationType::Tdx,
1596        };
1597
1598        // Try to open the sidecar device, if it is present.
1599        let sidecar = sidecar_client::SidecarClient::new(driver).map_err(Error::Sidecar)?;
1600
1601        let hcl = Hcl::new(hcl_isolation, sidecar).map_err(Error::Hcl)?;
1602
1603        // Set the hypercalls that this process will use.
1604        let mut allowed_hypercalls = vec![
1605            hvdef::HypercallCode::HvCallGetVpRegisters,
1606            hvdef::HypercallCode::HvCallSetVpRegisters,
1607            hvdef::HypercallCode::HvCallInstallIntercept,
1608            hvdef::HypercallCode::HvCallTranslateVirtualAddress,
1609            hvdef::HypercallCode::HvCallPostMessageDirect,
1610            hvdef::HypercallCode::HvCallSignalEventDirect,
1611            hvdef::HypercallCode::HvCallModifyVtlProtectionMask,
1612            hvdef::HypercallCode::HvCallTranslateVirtualAddressEx,
1613            hvdef::HypercallCode::HvCallCheckSparseGpaPageVtlAccess,
1614            hvdef::HypercallCode::HvCallAssertVirtualInterrupt,
1615            hvdef::HypercallCode::HvCallGetVpIndexFromApicId,
1616            hvdef::HypercallCode::HvCallAcceptGpaPages,
1617            hvdef::HypercallCode::HvCallModifySparseGpaPageHostVisibility,
1618        ];
1619
1620        if params.isolation.is_hardware_isolated() {
1621            allowed_hypercalls.extend(vec![
1622                hvdef::HypercallCode::HvCallEnablePartitionVtl,
1623                hvdef::HypercallCode::HvCallRetargetDeviceInterrupt,
1624                hvdef::HypercallCode::HvCallEnableVpVtl,
1625            ]);
1626        }
1627
1628        if params.use_mmio_hypercalls {
1629            allowed_hypercalls.extend(vec![
1630                hvdef::HypercallCode::HvCallMemoryMappedIoRead,
1631                hvdef::HypercallCode::HvCallMemoryMappedIoWrite,
1632            ]);
1633        }
1634
1635        hcl.set_allowed_hypercalls(allowed_hypercalls.as_slice());
1636
1637        set_vtl2_vsm_partition_config(&hcl)?;
1638
1639        let privs = hcl
1640            .get_privileges_and_features_info()
1641            .map_err(Error::GetReg)?;
1642        let guest_vsm_available = Self::check_guest_vsm_support(privs, &hcl)?;
1643
1644        #[cfg(guest_arch = "x86_64")]
1645        let cpuid = match params.isolation {
1646            IsolationType::Snp => cvm_cpuid::CpuidResultsIsolationType::Snp {
1647                cpuid_pages: params.cvm_cpuid_info.unwrap(),
1648                vtom: params.vtom.unwrap(),
1649                access_vsm: guest_vsm_available,
1650            }
1651            .build()
1652            .map_err(Error::CvmCpuid)?,
1653
1654            IsolationType::Tdx => cvm_cpuid::CpuidResultsIsolationType::Tdx {
1655                topology: params.topology,
1656                vtom: params.vtom.unwrap(),
1657                access_vsm: guest_vsm_available,
1658            }
1659            .build()
1660            .map_err(Error::CvmCpuid)?,
1661            IsolationType::Vbs | IsolationType::None => Default::default(),
1662        };
1663
1664        Ok(UhProtoPartition {
1665            hcl,
1666            params,
1667            guest_vsm_available,
1668            create_partition_available: privs.create_partitions(),
1669            #[cfg(guest_arch = "x86_64")]
1670            cpuid,
1671        })
1672    }
1673
1674    /// Returns whether VSM support will be available to the guest.
1675    pub fn guest_vsm_available(&self) -> bool {
1676        self.guest_vsm_available
1677    }
1678
1679    /// Returns whether this partition has the create partitions hypercall
1680    /// available.
1681    pub fn create_partition_available(&self) -> bool {
1682        self.create_partition_available
1683    }
1684
1685    /// Returns a new Underhill partition.
1686    pub async fn build(
1687        self,
1688        late_params: UhLateParams<'_>,
1689    ) -> Result<(UhPartition, Vec<UhProcessorBox>), Error> {
1690        let Self {
1691            mut hcl,
1692            params,
1693            guest_vsm_available,
1694            create_partition_available: _,
1695            #[cfg(guest_arch = "x86_64")]
1696            cpuid,
1697        } = self;
1698        let isolation = params.isolation;
1699        let is_hardware_isolated = isolation.is_hardware_isolated();
1700
1701        // Intercept Debug Exceptions
1702        // On TDX because all OpenHCL TDs today have the debug policy bit set,
1703        // OpenHCL registers for the intercepts itself.
1704        // However, on non-TDX platforms hypervisor installs the
1705        // intercept on behalf of the guest.
1706        if params.intercept_debug_exceptions {
1707            if !cfg!(feature = "gdb") {
1708                return Err(Error::InvalidDebugConfiguration);
1709            }
1710
1711            cfg_if::cfg_if! {
1712                if #[cfg(guest_arch = "x86_64")] {
1713                    if isolation != IsolationType::Tdx {
1714                        let debug_exception_vector = 0x1;
1715                        hcl.register_intercept(
1716                            HvInterceptType::HvInterceptTypeException,
1717                            HV_INTERCEPT_ACCESS_MASK_EXECUTE,
1718                            HvInterceptParameters::new_exception(debug_exception_vector),
1719                        )
1720                        .map_err(|err| Error::InstallIntercept(HvInterceptType::HvInterceptTypeException, err))?;
1721                    }
1722                } else {
1723                    return Err(Error::InvalidDebugConfiguration);
1724                }
1725            }
1726        }
1727
1728        if !is_hardware_isolated {
1729            if cfg!(guest_arch = "x86_64") {
1730                hcl.register_intercept(
1731                    HvInterceptType::HvInterceptTypeX64Msr,
1732                    HV_INTERCEPT_ACCESS_MASK_READ_WRITE,
1733                    HvInterceptParameters::new_zeroed(),
1734                )
1735                .map_err(|err| {
1736                    Error::InstallIntercept(HvInterceptType::HvInterceptTypeX64Msr, err)
1737                })?;
1738
1739                hcl.register_intercept(
1740                    HvInterceptType::HvInterceptTypeX64ApicEoi,
1741                    HV_INTERCEPT_ACCESS_MASK_WRITE,
1742                    HvInterceptParameters::new_zeroed(),
1743                )
1744                .map_err(|err| {
1745                    Error::InstallIntercept(HvInterceptType::HvInterceptTypeX64ApicEoi, err)
1746                })?;
1747            } else {
1748                if false {
1749                    todo!("AARCH64_TODO");
1750                }
1751            }
1752        }
1753
1754        if isolation == IsolationType::Snp {
1755            // SNP VMs register for the #VC exception to support reflect-VC.
1756            hcl.register_intercept(
1757                HvInterceptType::HvInterceptTypeException,
1758                HV_INTERCEPT_ACCESS_MASK_EXECUTE,
1759                HvInterceptParameters::new_exception(
1760                    x86defs::Exception::SEV_VMM_COMMUNICATION.0 as u16,
1761                ),
1762            )
1763            .map_err(|err| {
1764                Error::InstallIntercept(HvInterceptType::HvInterceptTypeException, err)
1765            })?;
1766
1767            // Get the register tweak bitmap from secrets page.
1768            let mut bitmap = [0u8; 64];
1769            if let Some(secrets) = params.snp_secrets {
1770                bitmap.copy_from_slice(
1771                    &secrets
1772                        [REG_TWEAK_BITMAP_OFFSET..REG_TWEAK_BITMAP_OFFSET + REG_TWEAK_BITMAP_SIZE],
1773                );
1774            }
1775            hcl.set_snp_register_bitmap(bitmap);
1776        }
1777
1778        // Do per-VP HCL initialization.
1779        hcl.add_vps(
1780            params.topology.vp_count(),
1781            late_params
1782                .cvm_params
1783                .as_ref()
1784                .map(|x| &x.private_dma_client),
1785        )
1786        .map_err(Error::Hcl)?;
1787
1788        let vps: Vec<_> = params
1789            .topology
1790            .vps_arch()
1791            .map(|vp_info| {
1792                // TODO: determine CPU index, which in theory could be different
1793                // from the VP index, though this hasn't happened yet.
1794                let cpu_index = vp_info.base.vp_index.index();
1795                UhVpInner::new(cpu_index, vp_info)
1796            })
1797            .collect();
1798
1799        // Enable support for VPCI devices if the hypervisor supports it.
1800        #[cfg(guest_arch = "x86_64")]
1801        let software_devices = {
1802            let res = if !is_hardware_isolated {
1803                hcl.register_intercept(
1804                    HvInterceptType::HvInterceptTypeRetargetInterruptWithUnknownDeviceId,
1805                    HV_INTERCEPT_ACCESS_MASK_EXECUTE,
1806                    HvInterceptParameters::new_zeroed(),
1807                )
1808            } else {
1809                Ok(())
1810            };
1811            match res {
1812                Ok(()) => Some(ApicSoftwareDevices::new(
1813                    params.topology.vps_arch().map(|vp| vp.apic_id).collect(),
1814                )),
1815                Err(HvError::InvalidParameter | HvError::AccessDenied) => None,
1816                Err(err) => {
1817                    return Err(Error::InstallIntercept(
1818                        HvInterceptType::HvInterceptTypeRetargetInterruptWithUnknownDeviceId,
1819                        err,
1820                    ));
1821                }
1822            }
1823        };
1824
1825        #[cfg(guest_arch = "aarch64")]
1826        let software_devices = None;
1827
1828        #[cfg(guest_arch = "aarch64")]
1829        let caps = virt::aarch64::Aarch64PartitionCapabilities {};
1830
1831        #[cfg(guest_arch = "x86_64")]
1832        let cpuid = UhPartition::construct_cpuid_results(
1833            cpuid,
1834            &late_params.cpuid,
1835            params.topology,
1836            isolation,
1837            params.hide_isolation,
1838        );
1839
1840        #[cfg(guest_arch = "x86_64")]
1841        let caps = UhPartition::construct_capabilities(
1842            params.topology,
1843            &cpuid,
1844            isolation,
1845            params.hide_isolation,
1846        )
1847        .map_err(Error::Capabilities)?;
1848
1849        if params.handle_synic && !matches!(isolation, IsolationType::Tdx) {
1850            // The hypervisor will manage the untrusted SINTs (or the whole
1851            // synic for non-hardware-isolated VMs), but some event ports
1852            // and message ports are implemented here. Register an intercept
1853            // to handle HvSignalEvent and HvPostMessage hypercalls when the
1854            // hypervisor doesn't recognize the connection ID.
1855            //
1856            // TDX manages this locally instead of through the hypervisor.
1857            hcl.register_intercept(
1858                HvInterceptType::HvInterceptTypeUnknownSynicConnection,
1859                HV_INTERCEPT_ACCESS_MASK_EXECUTE,
1860                HvInterceptParameters::new_zeroed(),
1861            )
1862            .expect("registering synic intercept cannot fail");
1863        }
1864
1865        #[cfg(guest_arch = "x86_64")]
1866        let cvm_state = if is_hardware_isolated {
1867            let vsm_caps = hcl.get_vsm_capabilities().map_err(Error::GetReg)?;
1868            let proxy_interrupt_redirect_available =
1869                vsm_caps.proxy_interrupt_redirect_available() && !params.disable_proxy_redirect;
1870
1871            Some(Self::construct_cvm_state(
1872                &params,
1873                late_params.cvm_params.unwrap(),
1874                &caps,
1875                guest_vsm_available,
1876                proxy_interrupt_redirect_available,
1877            )?)
1878        } else {
1879            None
1880        };
1881        #[cfg(guest_arch = "aarch64")]
1882        let cvm_state = None;
1883
1884        let lower_vtl_timer_virt_available =
1885            hcl.supports_lower_vtl_timer_virt() && !params.disable_lower_vtl_timer_virt;
1886
1887        let backing_shared = BackingShared::new(
1888            isolation,
1889            &params,
1890            BackingSharedParams {
1891                cvm_state,
1892                #[cfg(guest_arch = "x86_64")]
1893                cpuid: &cpuid,
1894                hcl: &hcl,
1895                guest_vsm_available,
1896                lower_vtl_timer_virt_available,
1897            },
1898        )?;
1899
1900        let enter_modes = EnterModes::default();
1901
1902        let partition = Arc::new(UhPartitionInner {
1903            hcl,
1904            vps,
1905            irq_routes: Default::default(),
1906            caps,
1907            enter_modes: Mutex::new(enter_modes),
1908            enter_modes_atomic: u8::from(hcl::protocol::EnterModes::from(enter_modes)).into(),
1909            gm: late_params.gm,
1910            vtl0_kernel_exec_gm: late_params.vtl0_kernel_exec_gm,
1911            vtl0_user_exec_gm: late_params.vtl0_user_exec_gm,
1912            #[cfg(guest_arch = "x86_64")]
1913            cpuid,
1914            crash_notification_send: late_params.crash_notification_send,
1915            monitor_page: MonitorPage::new(),
1916            allocated_monitor_page: Mutex::new(None),
1917            software_devices,
1918            lower_vtl_memory_layout: params.lower_vtl_memory_layout.clone(),
1919            vmtime: late_params.vmtime.clone(),
1920            isolation,
1921            no_sidecar_hotplug: params.no_sidecar_hotplug.into(),
1922            use_mmio_hypercalls: params.use_mmio_hypercalls,
1923            backing_shared,
1924            #[cfg(guest_arch = "x86_64")]
1925            device_vector_table: RwLock::new(IrrBitmap::new(Default::default())),
1926            intercept_debug_exceptions: params.intercept_debug_exceptions,
1927            vmbus_relay: late_params.vmbus_relay,
1928        });
1929
1930        if cfg!(guest_arch = "x86_64") {
1931            // Intercept all IOs unless opted out.
1932            partition.manage_io_port_intercept_region(0, !0, true);
1933        }
1934
1935        let vps = params
1936            .topology
1937            .vps_arch()
1938            .map(|vp_info| UhProcessorBox {
1939                partition: partition.clone(),
1940                vp_info,
1941            })
1942            .collect();
1943
1944        Ok((
1945            UhPartition {
1946                inner: partition.clone(),
1947                interrupt_targets: VtlArray::from_fn(|vtl| {
1948                    Arc::new(UhInterruptTarget {
1949                        partition: partition.clone(),
1950                        vtl: vtl.try_into().unwrap(),
1951                    })
1952                }),
1953            },
1954            vps,
1955        ))
1956    }
1957}
1958
1959impl UhPartition {
1960    /// Gets the guest OS ID for VTL0.
1961    pub fn vtl0_guest_os_id(&self) -> Result<HvGuestOsId, hcl::ioctl::register::GetRegError> {
1962        // If Underhill is emulating the hypervisor interfaces, get this value
1963        // from the emulator. This happens when running under hardware isolation
1964        // or when configured for testing.
1965        let id = if let Some(hv) = self.inner.hv() {
1966            hv.guest_os_id(Vtl::Vtl0)
1967        } else {
1968            // Ask the hypervisor for this value.
1969            self.inner.hcl.get_guest_os_id(GuestVtl::Vtl0)?
1970        };
1971        Ok(id)
1972    }
1973
1974    /// Configures guest accesses to IO ports in `range` to go directly to the
1975    /// host.
1976    ///
1977    /// When the return value is dropped, the ports will be unregistered.
1978    pub fn register_host_io_port_fast_path(
1979        &self,
1980        range: RangeInclusive<u16>,
1981    ) -> HostIoPortFastPathHandle {
1982        // There is no way to provide a fast path for some hardware isolated
1983        // VM architectures. The devices that do use this facility are not
1984        // enabled on hardware isolated VMs.
1985        assert!(!self.inner.isolation.is_hardware_isolated());
1986
1987        self.inner
1988            .manage_io_port_intercept_region(*range.start(), *range.end(), false);
1989        HostIoPortFastPathHandle {
1990            inner: Arc::downgrade(&self.inner),
1991            begin: *range.start(),
1992            end: *range.end(),
1993        }
1994    }
1995
1996    /// Trigger the LINT1 interrupt vector on the LAPIC of the BSP.
1997    pub fn assert_debug_interrupt(&self, _vtl: u8) {
1998        #[cfg(guest_arch = "x86_64")]
1999        const LINT_INDEX_1: u8 = 1;
2000        #[cfg(guest_arch = "x86_64")]
2001        match self.inner.isolation {
2002            IsolationType::Snp => {
2003                tracing::error!(?_vtl, "Debug interrupts cannot be injected into SNP VMs",);
2004            }
2005            _ => {
2006                let bsp_index = VpIndex::new(0);
2007                self.pulse_lint(bsp_index, Vtl::try_from(_vtl).unwrap(), LINT_INDEX_1)
2008            }
2009        }
2010    }
2011
2012    /// Enables or disables the PM timer assist.
2013    pub fn set_pm_timer_assist(
2014        &self,
2015        port: Option<u16>,
2016    ) -> Result<(), hcl::ioctl::register::SetRegError> {
2017        self.inner.hcl.set_pm_timer_assist(port)
2018    }
2019
2020    /// Sets guest memory protections for a monitor page.
2021    fn register_cvm_dma_overlay_page(
2022        &self,
2023        vtl: GuestVtl,
2024        gpn: u64,
2025        new_perms: HvMapGpaFlags,
2026    ) -> anyhow::Result<()> {
2027        // How the monitor page is protected depends on the isolation type of the VM.
2028        match &self.inner.backing_shared {
2029            #[cfg(guest_arch = "x86_64")]
2030            BackingShared::Snp(snp_backed_shared) => snp_backed_shared
2031                .cvm
2032                .isolated_memory_protector
2033                .register_overlay_page(
2034                    vtl,
2035                    gpn,
2036                    // On a CVM, the monitor page is always DMA-allocated.
2037                    GpnSource::Dma,
2038                    HvMapGpaFlags::new(),
2039                    Some(new_perms),
2040                    &mut SnpBacked::tlb_flush_lock_access(
2041                        None,
2042                        self.inner.as_ref(),
2043                        snp_backed_shared,
2044                    ),
2045                )
2046                .map_err(|e| anyhow::anyhow!(e)),
2047            #[cfg(guest_arch = "x86_64")]
2048            BackingShared::Tdx(tdx_backed_shared) => tdx_backed_shared
2049                .cvm
2050                .isolated_memory_protector
2051                .register_overlay_page(
2052                    vtl,
2053                    gpn,
2054                    GpnSource::Dma,
2055                    HvMapGpaFlags::new(),
2056                    Some(new_perms),
2057                    &mut TdxBacked::tlb_flush_lock_access(
2058                        None,
2059                        self.inner.as_ref(),
2060                        tdx_backed_shared,
2061                    ),
2062                )
2063                .map_err(|e| anyhow::anyhow!(e)),
2064            BackingShared::Hypervisor(_) => {
2065                let _ = (vtl, gpn, new_perms);
2066                unreachable!()
2067            }
2068        }
2069    }
2070
2071    /// Reverts guest memory protections for a monitor page.
2072    fn unregister_cvm_dma_overlay_page(&self, vtl: GuestVtl, gpn: u64) -> anyhow::Result<()> {
2073        // How the monitor page is protected depends on the isolation type of the VM.
2074        match &self.inner.backing_shared {
2075            #[cfg(guest_arch = "x86_64")]
2076            BackingShared::Snp(snp_backed_shared) => snp_backed_shared
2077                .cvm
2078                .isolated_memory_protector
2079                .unregister_overlay_page(
2080                    vtl,
2081                    gpn,
2082                    &mut SnpBacked::tlb_flush_lock_access(
2083                        None,
2084                        self.inner.as_ref(),
2085                        snp_backed_shared,
2086                    ),
2087                )
2088                .map_err(|e| anyhow::anyhow!(e)),
2089            #[cfg(guest_arch = "x86_64")]
2090            BackingShared::Tdx(tdx_backed_shared) => tdx_backed_shared
2091                .cvm
2092                .isolated_memory_protector
2093                .unregister_overlay_page(
2094                    vtl,
2095                    gpn,
2096                    &mut TdxBacked::tlb_flush_lock_access(
2097                        None,
2098                        self.inner.as_ref(),
2099                        tdx_backed_shared,
2100                    ),
2101                )
2102                .map_err(|e| anyhow::anyhow!(e)),
2103            BackingShared::Hypervisor(_) => {
2104                let _ = (vtl, gpn);
2105                unreachable!()
2106            }
2107        }
2108    }
2109}
2110
2111impl UhProtoPartition<'_> {
2112    /// Whether Guest VSM is available to the guest. If so, for hardware CVMs,
2113    /// it is safe to expose Guest VSM support via cpuid.
2114    fn check_guest_vsm_support(privs: HvPartitionPrivilege, hcl: &Hcl) -> Result<bool, Error> {
2115        if !privs.access_vsm() {
2116            return Ok(false);
2117        }
2118
2119        let guest_vsm_config = hcl
2120            .get_guest_vsm_partition_config()
2121            .map_err(Error::GetReg)?;
2122        Ok(guest_vsm_config.maximum_vtl() >= u8::from(GuestVtl::Vtl1))
2123    }
2124
2125    #[cfg(guest_arch = "x86_64")]
2126    /// Constructs partition-wide CVM state.
2127    fn construct_cvm_state(
2128        params: &UhPartitionNewParams<'_>,
2129        late_params: CvmLateParams,
2130        caps: &PartitionCapabilities,
2131        guest_vsm_available: bool,
2132        proxy_interrupt_redirect_available: bool,
2133    ) -> Result<UhCvmPartitionState, Error> {
2134        use vmcore::reference_time::ReferenceTimeSource;
2135
2136        let vp_count = params.topology.vp_count() as usize;
2137        let vps = (0..vp_count)
2138            .map(|vp_index| UhCvmVpInner {
2139                tlb_lock_info: VtlArray::from_fn(|_| TlbLockInfo::new(vp_count)),
2140                vtl1_enable_called: Mutex::new(false),
2141                started: AtomicBool::new(vp_index == 0),
2142                hv_start_enable_vtl_vp: VtlArray::from_fn(|_| Mutex::new(None)),
2143                proxy_redirect_interrupts: Mutex::new(HashMap::new()),
2144            })
2145            .collect();
2146        let tlb_locked_vps =
2147            VtlArray::from_fn(|_| BitVec::repeat(false, vp_count).into_boxed_bitslice());
2148
2149        let lapic = VtlArray::from_fn(|_| {
2150            LocalApicSet::builder()
2151                .x2apic_capable(caps.x2apic)
2152                .hyperv_enlightenments(true)
2153                .build()
2154        });
2155
2156        let tsc_frequency = get_tsc_frequency(params.isolation)?;
2157        let ref_time = ReferenceTimeSource::new(TscReferenceTimeSource::new(tsc_frequency));
2158
2159        // If we're emulating the APIC, then we also must emulate the hypervisor
2160        // enlightenments, since the hypervisor can't support enlightenments
2161        // without also providing an APIC.
2162        //
2163        // Additionally, TDX provides hardware APIC emulation but we still need
2164        // to emulate the hypervisor enlightenments.
2165        let hv = GlobalHv::new(hv1_emulator::hv::GlobalHvParams {
2166            max_vp_count: params.topology.vp_count(),
2167            vendor: caps.vendor,
2168            tsc_frequency,
2169            ref_time,
2170            is_ref_time_backed_by_tsc: true,
2171        });
2172
2173        Ok(UhCvmPartitionState {
2174            vps_per_socket: params.topology.reserved_vps_per_socket(),
2175            tlb_locked_vps,
2176            vps,
2177            shared_memory: late_params.shared_gm,
2178            isolated_memory_protector: late_params.isolated_memory_protector,
2179            lapic,
2180            hv,
2181            guest_vsm: RwLock::new(GuestVsmState::from_availability(guest_vsm_available)),
2182            shared_dma_client: late_params.shared_dma_client,
2183            private_dma_client: late_params.private_dma_client,
2184            hide_isolation: params.hide_isolation,
2185            proxy_interrupt_redirect: proxy_interrupt_redirect_available,
2186        })
2187    }
2188}
2189
2190impl UhPartition {
2191    #[cfg(guest_arch = "x86_64")]
2192    /// Constructs the set of cpuid results to show to the guest
2193    fn construct_cpuid_results(
2194        cpuid: virt::CpuidLeafSet,
2195        initial_cpuid: &[CpuidLeaf],
2196        topology: &ProcessorTopology<vm_topology::processor::x86::X86Topology>,
2197        isolation: IsolationType,
2198        hide_isolation: bool,
2199    ) -> virt::CpuidLeafSet {
2200        let mut cpuid = cpuid.into_leaves();
2201        if isolation.is_hardware_isolated() {
2202            // Update the x2apic leaf based on the topology.
2203            let x2apic = match topology.apic_mode() {
2204                vm_topology::processor::x86::ApicMode::XApic => false,
2205                vm_topology::processor::x86::ApicMode::X2ApicSupported => true,
2206                vm_topology::processor::x86::ApicMode::X2ApicEnabled => true,
2207            };
2208            let ecx = x86defs::cpuid::VersionAndFeaturesEcx::new().with_x2_apic(x2apic);
2209            let ecx_mask = x86defs::cpuid::VersionAndFeaturesEcx::new().with_x2_apic(true);
2210            cpuid.push(
2211                CpuidLeaf::new(
2212                    x86defs::cpuid::CpuidFunction::VersionAndFeatures.0,
2213                    [0, 0, ecx.into(), 0],
2214                )
2215                .masked([0, 0, ecx_mask.into(), 0]),
2216            );
2217
2218            // Get the hypervisor version from the host. This is just for
2219            // reporting purposes, so it is safe even if the hypervisor is not
2220            // trusted.
2221            let hv_version = safe_intrinsics::cpuid(hvdef::HV_CPUID_FUNCTION_MS_HV_VERSION, 0);
2222
2223            // Perform final processing steps for synthetic leaves.
2224            hv1_emulator::cpuid::process_hv_cpuid_leaves(
2225                &mut cpuid,
2226                hide_isolation,
2227                [
2228                    hv_version.eax,
2229                    hv_version.ebx,
2230                    hv_version.ecx,
2231                    hv_version.edx,
2232                ],
2233            );
2234        }
2235        cpuid.extend(initial_cpuid);
2236        virt::CpuidLeafSet::new(cpuid)
2237    }
2238
2239    #[cfg(guest_arch = "x86_64")]
2240    /// Computes the partition capabilities
2241    fn construct_capabilities(
2242        topology: &ProcessorTopology,
2243        cpuid: &virt::CpuidLeafSet,
2244        isolation: IsolationType,
2245        hide_isolation: bool,
2246    ) -> Result<virt::x86::X86PartitionCapabilities, virt::x86::X86PartitionCapabilitiesError> {
2247        let mut native_cpuid_fn;
2248        let mut cvm_cpuid_fn;
2249
2250        // Determine the method to get cpuid results for the guest when
2251        // computing partition capabilities.
2252        let cpuid_fn: &mut dyn FnMut(u32, u32) -> [u32; 4] = if isolation.is_hardware_isolated() {
2253            // Use the filtered CPUID to determine capabilities.
2254            cvm_cpuid_fn = move |leaf, sub_leaf| cpuid.result(leaf, sub_leaf, &[0, 0, 0, 0]);
2255            &mut cvm_cpuid_fn
2256        } else {
2257            // Just use the native cpuid.
2258            native_cpuid_fn = |leaf, sub_leaf| {
2259                let CpuidResult { eax, ebx, ecx, edx } = safe_intrinsics::cpuid(leaf, sub_leaf);
2260                cpuid.result(leaf, sub_leaf, &[eax, ebx, ecx, edx])
2261            };
2262            &mut native_cpuid_fn
2263        };
2264
2265        // Compute and validate capabilities.
2266        let mut caps = virt::x86::X86PartitionCapabilities::from_cpuid(topology, cpuid_fn)?;
2267        match isolation {
2268            IsolationType::Tdx => {
2269                assert_eq!(caps.vtom.is_some(), !hide_isolation);
2270                // TDX 1.5 requires EFER.NXE to be set to 1, so set it at RESET/INIT.
2271                caps.nxe_forced_on = true;
2272            }
2273            IsolationType::Snp => {
2274                assert_eq!(caps.vtom.is_some(), !hide_isolation);
2275            }
2276            _ => {
2277                assert!(caps.vtom.is_none());
2278            }
2279        }
2280
2281        Ok(caps)
2282    }
2283}
2284
2285#[cfg(guest_arch = "x86_64")]
2286/// Gets the TSC frequency for the current platform.
2287fn get_tsc_frequency(isolation: IsolationType) -> Result<u64, Error> {
2288    // Always get the frequency from the hypervisor. It's believed that, as long
2289    // as the hypervisor is behaving, it will provide the most precise and accurate frequency.
2290    let msr = MsrDevice::new(0).map_err(Error::OpenMsr)?;
2291    let hv_frequency = msr
2292        .read_msr(hvdef::HV_X64_MSR_TSC_FREQUENCY)
2293        .map_err(Error::ReadTscFrequency)?;
2294
2295    // Get the hardware-advertised frequency and validate that the
2296    // hypervisor frequency is not too far off.
2297    let hw_info = match isolation {
2298        IsolationType::Tdx => {
2299            // TDX provides the TSC frequency via cpuid.
2300            let max_function =
2301                safe_intrinsics::cpuid(x86defs::cpuid::CpuidFunction::VendorAndMaxFunction.0, 0)
2302                    .eax;
2303
2304            if max_function < x86defs::cpuid::CpuidFunction::CoreCrystalClockInformation.0 {
2305                return Err(Error::BadCpuidTsc);
2306            }
2307            let result = safe_intrinsics::cpuid(
2308                x86defs::cpuid::CpuidFunction::CoreCrystalClockInformation.0,
2309                0,
2310            );
2311            let ratio_denom = result.eax;
2312            let ratio_num = result.ebx;
2313            let clock = result.ecx;
2314            if ratio_num == 0 || ratio_denom == 0 || clock == 0 {
2315                return Err(Error::BadCpuidTsc);
2316            }
2317            // TDX TSC is configurable in units of 25MHz, so allow up to 12.5MHz
2318            // error.
2319            let allowed_error = 12_500_000;
2320            Some((
2321                clock as u64 * ratio_num as u64 / ratio_denom as u64,
2322                allowed_error,
2323            ))
2324        }
2325        IsolationType::Snp => {
2326            // SNP currently does not provide the frequency.
2327            None
2328        }
2329        IsolationType::Vbs | IsolationType::None => None,
2330    };
2331
2332    if let Some((hw_frequency, allowed_error)) = hw_info {
2333        // Don't allow the frequencies to be different by more than the hardware
2334        // precision.
2335        let delta = hw_frequency.abs_diff(hv_frequency);
2336        if delta > allowed_error {
2337            return Err(Error::TscFrequencyMismatch {
2338                hv: hv_frequency,
2339                hw: hw_frequency,
2340                allowed_error,
2341            });
2342        }
2343    }
2344
2345    Ok(hv_frequency)
2346}
2347
2348impl UhPartitionInner {
2349    fn manage_io_port_intercept_region(&self, begin: u16, end: u16, active: bool) {
2350        if self.isolation.is_hardware_isolated() {
2351            return;
2352        }
2353
2354        static SKIP_RANGE: AtomicBool = AtomicBool::new(false);
2355
2356        let access_type_mask = if active {
2357            HV_INTERCEPT_ACCESS_MASK_READ_WRITE
2358        } else {
2359            HV_INTERCEPT_ACCESS_MASK_NONE
2360        };
2361
2362        // Try to register the whole range at once.
2363        if !SKIP_RANGE.load(Ordering::Relaxed) {
2364            match self.hcl.register_intercept(
2365                HvInterceptType::HvInterceptTypeX64IoPortRange,
2366                access_type_mask,
2367                HvInterceptParameters::new_io_port_range(begin..=end),
2368            ) {
2369                Ok(()) => return,
2370                Err(HvError::InvalidParameter) => {
2371                    // Probably a build that doesn't support range wrapping yet.
2372                    // Don't try again.
2373                    SKIP_RANGE.store(true, Ordering::Relaxed);
2374                    tracing::warn!(
2375                        CVM_ALLOWED,
2376                        "old hypervisor build; using slow path for intercept ranges"
2377                    );
2378                }
2379                Err(err) => {
2380                    panic!("io port range registration failure: {err:?}");
2381                }
2382            }
2383        }
2384
2385        // Fall back to registering one port at a time.
2386        for port in begin..=end {
2387            self.hcl
2388                .register_intercept(
2389                    HvInterceptType::HvInterceptTypeX64IoPort,
2390                    access_type_mask,
2391                    HvInterceptParameters::new_io_port(port),
2392                )
2393                .expect("registering io intercept cannot fail");
2394        }
2395    }
2396
2397    fn is_gpa_lower_vtl_ram(&self, gpa: u64) -> bool {
2398        // TODO: this probably should reflect changes to the memory map via PAM
2399        // registers. Right now this isn't an issue because the relevant region,
2400        // VGA, is handled on the host.
2401        self.lower_vtl_memory_layout
2402            .ram()
2403            .iter()
2404            .any(|m| m.range.contains_addr(gpa))
2405    }
2406
2407    fn is_gpa_mapped(&self, gpa: u64, write: bool) -> bool {
2408        // TODO: this probably should reflect changes to the memory map via PAM
2409        // registers. Right now this isn't an issue because the relevant region,
2410        // VGA, is handled on the host.
2411        if self.is_gpa_lower_vtl_ram(gpa) {
2412            // The monitor page is protected against lower VTL writes.
2413            !write || self.monitor_page.gpa() != Some(gpa & !(HV_PAGE_SIZE - 1))
2414        } else {
2415            false
2416        }
2417    }
2418}
2419
2420/// Handle returned by [`UhPartition::register_host_io_port_fast_path`].
2421///
2422/// When dropped, unregisters the IO ports so that they are no longer forwarded
2423/// to the host.
2424#[must_use]
2425pub struct HostIoPortFastPathHandle {
2426    inner: Weak<UhPartitionInner>,
2427    begin: u16,
2428    end: u16,
2429}
2430
2431impl Drop for HostIoPortFastPathHandle {
2432    fn drop(&mut self) {
2433        if let Some(inner) = self.inner.upgrade() {
2434            inner.manage_io_port_intercept_region(self.begin, self.end, true);
2435        }
2436    }
2437}
2438
2439/// The application level VTL crash data not suited for putting
2440/// on the wire.
2441///
2442/// FUTURE: move/remove this to standardize across virt backends.
2443#[derive(Copy, Clone, Debug)]
2444pub struct VtlCrash {
2445    /// The VP that crashed.
2446    pub vp_index: VpIndex,
2447    /// The VTL that crashed.
2448    pub last_vtl: GuestVtl,
2449    /// The crash control information.
2450    pub control: GuestCrashCtl,
2451    /// The crash parameters.
2452    pub parameters: [u64; 5],
2453}
2454
2455/// Validate that flags is a valid setting for VTL memory protection when
2456/// applied to VTL 1.
2457#[cfg_attr(guest_arch = "aarch64", expect(dead_code))]
2458fn validate_vtl_gpa_flags(
2459    flags: HvMapGpaFlags,
2460    mbec_enabled: bool,
2461    shadow_supervisor_stack_enabled: bool,
2462) -> bool {
2463    // Adjust is not allowed for VTL1.
2464    if flags.adjustable() {
2465        return false;
2466    }
2467
2468    // KX must equal UX unless MBEC is enabled. KX && !UX is invalid.
2469    if flags.kernel_executable() != flags.user_executable() {
2470        if (flags.kernel_executable() && !flags.user_executable()) || !mbec_enabled {
2471            return false;
2472        }
2473    }
2474
2475    // Read must be specified if anything else is specified.
2476    if flags.writable()
2477        || flags.kernel_executable()
2478        || flags.user_executable()
2479        || flags.supervisor_shadow_stack()
2480        || flags.paging_writability()
2481        || flags.verify_paging_writability()
2482    {
2483        if !flags.readable() {
2484            return false;
2485        }
2486    }
2487
2488    // Supervisor shadow stack protection is invalid if shadow stacks are disabled
2489    // or if execute is not specified.
2490    if flags.supervisor_shadow_stack()
2491        && ((!flags.kernel_executable() && !flags.user_executable())
2492            || shadow_supervisor_stack_enabled)
2493    {
2494        return false;
2495    }
2496
2497    true
2498}