hypervisor/
x86_64.rs

1// Copyright 2020 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#[cfg(any(unix, feature = "haxm", feature = "whpx"))]
6use std::arch::x86_64::__cpuid;
7use std::arch::x86_64::_rdtsc;
8use std::arch::x86_64::CpuidResult;
9use std::collections::BTreeMap;
10use std::collections::HashSet;
11use std::sync::Arc;
12
13use anyhow::Context;
14use base::custom_serde::deserialize_seq_to_arr;
15use base::custom_serde::serialize_arr;
16use base::error;
17use base::warn;
18use base::Result;
19use bit_field::*;
20use libc::c_void;
21use serde::Deserialize;
22use serde::Serialize;
23use snapshot::AnySnapshot;
24use vm_memory::GuestAddress;
25
26use crate::Hypervisor;
27use crate::IrqRoute;
28use crate::IrqSource;
29use crate::IrqSourceChip;
30use crate::NestedMode;
31use crate::Vcpu;
32use crate::Vm;
33
34const MSR_F15H_PERF_CTL0: u32 = 0xc0010200;
35const MSR_F15H_PERF_CTL1: u32 = 0xc0010202;
36const MSR_F15H_PERF_CTL2: u32 = 0xc0010204;
37const MSR_F15H_PERF_CTL3: u32 = 0xc0010206;
38const MSR_F15H_PERF_CTL4: u32 = 0xc0010208;
39const MSR_F15H_PERF_CTL5: u32 = 0xc001020a;
40const MSR_F15H_PERF_CTR0: u32 = 0xc0010201;
41const MSR_F15H_PERF_CTR1: u32 = 0xc0010203;
42const MSR_F15H_PERF_CTR2: u32 = 0xc0010205;
43const MSR_F15H_PERF_CTR3: u32 = 0xc0010207;
44const MSR_F15H_PERF_CTR4: u32 = 0xc0010209;
45const MSR_F15H_PERF_CTR5: u32 = 0xc001020b;
46const MSR_IA32_PERF_CAPABILITIES: u32 = 0x00000345;
47
48/// A trait for managing cpuids for an x86_64 hypervisor and for checking its capabilities.
49pub trait HypervisorX86_64: Hypervisor {
50    /// Get the system supported CPUID values.
51    fn get_supported_cpuid(&self) -> Result<CpuId>;
52
53    /// Gets the list of supported MSRs.
54    fn get_msr_index_list(&self) -> Result<Vec<u32>>;
55}
56
57/// A wrapper for using a VM on x86_64 and getting/setting its state.
58pub trait VmX86_64: Vm {
59    /// Designates the vCPU with ID `vcpu_id` as the bootstrap processor (BSP).
60    ///
61    /// Must be called before any vCPU is created. Hypervisors that can't choose the boot vCPU
62    /// return `ENOTSUP`; for them the boot vCPU is always vCPU 0.
63    fn set_boot_cpu_id(&self, _vcpu_id: usize) -> Result<()> {
64        Err(base::Error::new(libc::ENOTSUP))
65    }
66
67    /// Gets the `HypervisorX86_64` that created this VM.
68    fn get_hypervisor(&self) -> &dyn HypervisorX86_64;
69
70    /// Create a Vcpu with the specified Vcpu ID.
71    fn create_vcpu(&self, id: usize) -> Result<Arc<dyn VcpuX86_64>>;
72
73    /// Sets the address of the three-page region in the VM's address space.
74    fn set_tss_addr(&self, addr: GuestAddress) -> Result<()>;
75
76    /// Sets the address of a one-page region in the VM's address space.
77    fn set_identity_map_addr(&self, addr: GuestAddress) -> Result<()>;
78
79    /// Load pVM firmware for the VM, creating a memslot for it as needed.
80    ///
81    /// Only works on protected VMs (i.e. those with vm_type == KVM_X86_PKVM_PROTECTED_VM).
82    fn load_protected_vm_firmware(&self, fw_addr: GuestAddress, fw_max_size: u64) -> Result<()>;
83}
84
85/// A wrapper around creating and using a VCPU on x86_64.
86pub trait VcpuX86_64: Vcpu {
87    /// Sets or clears the flag that requests the VCPU to exit when it becomes possible to inject
88    /// interrupts into the guest.
89    fn set_interrupt_window_requested(&self, requested: bool);
90
91    /// Checks if we can inject an interrupt into the VCPU.
92    fn ready_for_interrupt(&self) -> bool;
93
94    /// Injects interrupt vector `irq` into the VCPU.
95    ///
96    /// This function should only be called when [`Self::ready_for_interrupt`] returns true.
97    /// Otherwise the interrupt injection may fail or the next VCPU run may fail. However, if
98    /// [`Self::interrupt`] returns [`Ok`], the implementation must guarantee that the interrupt
99    /// isn't injected in an uninterruptible window (e.g. right after the mov ss instruction).
100    ///
101    /// The caller should avoid calling this function more than 1 time for one VMEXIT, because the
102    /// hypervisor may behave differently: some hypervisors(e.g. WHPX, KVM) will only try to inject
103    /// the last `irq` requested, while some other hypervisors(e.g. HAXM) may try to inject all
104    /// `irq`s requested.
105    fn interrupt(&self, irq: u8) -> Result<()>;
106
107    /// Injects a non-maskable interrupt into the VCPU.
108    fn inject_nmi(&self) -> Result<()>;
109
110    /// Gets the VCPU general purpose registers.
111    fn get_regs(&self) -> Result<Regs>;
112
113    /// Sets the VCPU general purpose registers.
114    fn set_regs(&self, regs: &Regs) -> Result<()>;
115
116    /// Gets the VCPU special registers.
117    fn get_sregs(&self) -> Result<Sregs>;
118
119    /// Sets the VCPU special registers.
120    fn set_sregs(&self, sregs: &Sregs) -> Result<()>;
121
122    /// Gets the VCPU FPU registers.
123    fn get_fpu(&self) -> Result<Fpu>;
124
125    /// Sets the VCPU FPU registers.
126    fn set_fpu(&self, fpu: &Fpu) -> Result<()>;
127
128    /// Gets the VCPU debug registers.
129    fn get_debugregs(&self) -> Result<DebugRegs>;
130
131    /// Sets the VCPU debug registers.
132    fn set_debugregs(&self, debugregs: &DebugRegs) -> Result<()>;
133
134    /// Gets the VCPU extended control registers.
135    fn get_xcrs(&self) -> Result<BTreeMap<u32, u64>>;
136
137    /// Sets a VCPU extended control register.
138    fn set_xcr(&self, xcr: u32, value: u64) -> Result<()>;
139
140    /// Gets the VCPU x87 FPU, MMX, XMM, YMM and MXCSR registers.
141    fn get_xsave(&self) -> Result<Xsave>;
142
143    /// Sets the VCPU x87 FPU, MMX, XMM, YMM and MXCSR registers.
144    fn set_xsave(&self, xsave: &Xsave) -> Result<()>;
145
146    /// Gets hypervisor specific state for this VCPU that must be
147    /// saved/restored for snapshotting.
148    /// This state is fetched after VCPUs are frozen and interrupts are flushed.
149    fn get_hypervisor_specific_state(&self) -> Result<AnySnapshot>;
150
151    /// Sets hypervisor specific state for this VCPU. Only used for
152    /// snapshotting.
153    fn set_hypervisor_specific_state(&self, data: AnySnapshot) -> Result<()>;
154
155    /// Gets a single model-specific register's value.
156    fn get_msr(&self, msr_index: u32) -> Result<u64>;
157
158    /// Gets the model-specific registers. Returns all the MSRs for the VCPU.
159    fn get_all_msrs(&self) -> Result<BTreeMap<u32, u64>>;
160
161    /// Sets a single model-specific register's value.
162    fn set_msr(&self, msr_index: u32, value: u64) -> Result<()>;
163
164    /// Sets up the data returned by the CPUID instruction.
165    fn set_cpuid(&self, cpuid: &CpuId) -> Result<()>;
166
167    /// Sets up debug registers and configure vcpu for handling guest debug events.
168    fn set_guest_debug(&self, addrs: &[GuestAddress], enable_singlestep: bool) -> Result<()>;
169
170    /// This function should be called after `Vcpu::run` returns `VcpuExit::Cpuid`, and `entry`
171    /// should represent the result of emulating the CPUID instruction. The `handle_cpuid` function
172    /// will then set the appropriate registers on the vcpu.
173    fn handle_cpuid(&self, entry: &CpuIdEntry) -> Result<()>;
174
175    /// Gets the guest->host TSC offset.
176    ///
177    /// The default implementation uses [`VcpuX86_64::get_msr()`] to read the guest TSC.
178    fn get_tsc_offset(&self) -> Result<u64> {
179        // SAFETY:
180        // Safe because _rdtsc takes no arguments
181        let host_before_tsc = unsafe { _rdtsc() };
182
183        // get guest TSC value from our hypervisor
184        let guest_tsc = self.get_msr(crate::MSR_IA32_TSC)?;
185
186        // SAFETY:
187        // Safe because _rdtsc takes no arguments
188        let host_after_tsc = unsafe { _rdtsc() };
189
190        // Average the before and after host tsc to get the best value
191        let host_tsc = ((host_before_tsc as u128 + host_after_tsc as u128) / 2) as u64;
192
193        Ok(guest_tsc.wrapping_sub(host_tsc))
194    }
195
196    /// Sets the guest->host TSC offset.
197    ///
198    /// The default implementation uses [`VcpuX86_64::set_tsc_value()`] to set the TSC value.
199    ///
200    /// It sets TSC_OFFSET (VMCS / CB field) by setting the TSC MSR to the current
201    /// host TSC value plus the desired offset. We rely on the fact that hypervisors
202    /// determine the value of TSC_OFFSET by computing TSC_OFFSET = `new_tsc_value - _rdtsc()` =
203    /// `_rdtsc() + offset - _rdtsc()` ~= `offset`. Note that the ~= is important: this is an
204    /// approximate operation, because the two _rdtsc() calls
205    /// are separated by at least a few ticks.
206    ///
207    /// Note: TSC_OFFSET, host TSC, guest TSC, and TSC MSR are all different
208    /// concepts.
209    /// * When a guest executes rdtsc, the value (guest TSC) returned is host_tsc * TSC_MULTIPLIER +
210    ///   TSC_OFFSET + TSC_ADJUST.
211    /// * The TSC MSR is a special MSR that when written to by the host, will cause TSC_OFFSET to be
212    ///   set accordingly by the hypervisor.
213    /// * When the guest *writes* to TSC MSR, it actually changes the TSC_ADJUST MSR *for the
214    ///   guest*. Generally this is only happens if the guest is trying to re-zero or synchronize
215    ///   TSCs.
216    fn set_tsc_offset(&self, offset: u64) -> Result<()> {
217        // SAFETY: _rdtsc takes no arguments.
218        let host_tsc = unsafe { _rdtsc() };
219        self.set_tsc_value(host_tsc.wrapping_add(offset))
220    }
221
222    /// Sets the guest TSC exactly to the provided value.
223    ///
224    /// The default implementation sets the guest's TSC by writing the value to the MSR directly.
225    ///
226    /// See [`VcpuX86_64::set_tsc_offset()`] for an explanation of how this value is actually read
227    /// by the guest after being set.
228    fn set_tsc_value(&self, value: u64) -> Result<()> {
229        self.set_msr(crate::MSR_IA32_TSC, value)
230    }
231
232    /// Some hypervisors require special handling to restore timekeeping when
233    /// a snapshot is restored. They are provided with a host TSC reference
234    /// moment, guaranteed to be the same across all Vcpus, and the Vcpu's TSC
235    /// offset at the moment it was snapshotted.
236    fn restore_timekeeping(&self, host_tsc_reference_moment: u64, tsc_offset: u64) -> Result<()>;
237
238    /// Snapshot vCPU state
239    fn snapshot(&self) -> anyhow::Result<VcpuSnapshot> {
240        Ok(VcpuSnapshot {
241            vcpu_id: self.id(),
242            regs: self.get_regs()?,
243            sregs: self.get_sregs()?,
244            debug_regs: self.get_debugregs()?,
245            xcrs: self.get_xcrs()?,
246            msrs: self.get_all_msrs()?,
247            xsave: self.get_xsave()?,
248            hypervisor_data: self.get_hypervisor_specific_state()?,
249            tsc_offset: self.get_tsc_offset()?,
250        })
251    }
252
253    fn restore(
254        &self,
255        snapshot: &VcpuSnapshot,
256        host_tsc_reference_moment: u64,
257    ) -> anyhow::Result<()> {
258        // List of MSRs that may fail to restore due to lack of support in the host kernel.
259        // Some hosts are may be running older kernels which do not support all MSRs, but
260        // get_all_msrs will still fetch the MSRs supported by the CPU. Trying to set those MSRs
261        // will result in failures, so they will throw a warning instead.
262        let msr_allowlist = HashSet::from([
263            MSR_F15H_PERF_CTL0,
264            MSR_F15H_PERF_CTL1,
265            MSR_F15H_PERF_CTL2,
266            MSR_F15H_PERF_CTL3,
267            MSR_F15H_PERF_CTL4,
268            MSR_F15H_PERF_CTL5,
269            MSR_F15H_PERF_CTR0,
270            MSR_F15H_PERF_CTR1,
271            MSR_F15H_PERF_CTR2,
272            MSR_F15H_PERF_CTR3,
273            MSR_F15H_PERF_CTR4,
274            MSR_F15H_PERF_CTR5,
275            MSR_IA32_PERF_CAPABILITIES,
276        ]);
277        assert_eq!(snapshot.vcpu_id, self.id());
278        self.set_regs(&snapshot.regs)?;
279        self.set_sregs(&snapshot.sregs)?;
280        self.set_debugregs(&snapshot.debug_regs)?;
281        for (xcr_index, value) in &snapshot.xcrs {
282            self.set_xcr(*xcr_index, *value)?;
283        }
284
285        for (msr_index, value) in snapshot.msrs.iter() {
286            if self.get_msr(*msr_index) == Ok(*value) {
287                continue; // no need to set MSR since the values are the same.
288            }
289            if let Err(e) = self.set_msr(*msr_index, *value) {
290                if msr_allowlist.contains(msr_index) {
291                    warn!(
292                        "Failed to set MSR. MSR might not be supported in this kernel. Err: {}",
293                        e
294                    );
295                } else {
296                    return Err(e).context(
297                        "Failed to set MSR. MSR might not be supported by the CPU or by the kernel,
298                         and was not allow-listed.",
299                    );
300                }
301            };
302        }
303        self.set_xsave(&snapshot.xsave)?;
304        self.set_hypervisor_specific_state(snapshot.hypervisor_data.clone())?;
305        self.restore_timekeeping(host_tsc_reference_moment, snapshot.tsc_offset)?;
306        Ok(())
307    }
308}
309
310/// x86 specific vCPU snapshot.
311#[derive(Clone, Debug, Serialize, Deserialize)]
312pub struct VcpuSnapshot {
313    pub vcpu_id: usize,
314    regs: Regs,
315    sregs: Sregs,
316    debug_regs: DebugRegs,
317    xcrs: BTreeMap<u32, u64>,
318    msrs: BTreeMap<u32, u64>,
319    xsave: Xsave,
320    hypervisor_data: AnySnapshot,
321    tsc_offset: u64,
322}
323
324// TSC MSR
325pub const MSR_IA32_TSC: u32 = 0x00000010;
326
327/// Gets host cpu max physical address bits.
328#[cfg(any(unix, feature = "haxm", feature = "whpx"))]
329pub(crate) fn host_phys_addr_bits() -> u8 {
330    // SAFETY: trivially safe
331    let highest_ext_function = unsafe { __cpuid(0x80000000) };
332    if highest_ext_function.eax >= 0x80000008 {
333        // SAFETY: trivially safe
334        let addr_size = unsafe { __cpuid(0x80000008) };
335        // Low 8 bits of 0x80000008 leaf: host physical address size in bits.
336        addr_size.eax as u8
337    } else {
338        36
339    }
340}
341
342/// Initial state for x86_64 VCPUs.
343#[derive(Clone, Default)]
344pub struct VcpuInitX86_64 {
345    /// General-purpose registers.
346    pub regs: Regs,
347
348    /// Special registers.
349    pub sregs: Sregs,
350
351    /// Floating-point registers.
352    pub fpu: Fpu,
353
354    /// Machine-specific registers.
355    pub msrs: BTreeMap<u32, u64>,
356}
357
358/// Hold the CPU feature configurations that are needed to setup a vCPU.
359#[derive(Clone, Debug, PartialEq, Eq)]
360pub struct CpuConfigX86_64 {
361    /// whether to force using a calibrated TSC leaf (0x15).
362    pub force_calibrated_tsc_leaf: bool,
363
364    /// whether enabling host cpu topology.
365    pub host_cpu_topology: bool,
366
367    /// whether expose HWP feature to the guest.
368    pub enable_hwp: bool,
369
370    /// Wheter diabling SMT (Simultaneous Multithreading).
371    pub no_smt: bool,
372
373    /// whether enabling ITMT scheduler
374    pub itmt: bool,
375
376    /// whether setting hybrid CPU type
377    pub hybrid_type: Option<CpuHybridType>,
378
379    /// how to expose nested virtualization to the guest.
380    pub nested: NestedMode,
381}
382
383impl CpuConfigX86_64 {
384    pub fn new(
385        force_calibrated_tsc_leaf: bool,
386        host_cpu_topology: bool,
387        enable_hwp: bool,
388        no_smt: bool,
389        itmt: bool,
390        hybrid_type: Option<CpuHybridType>,
391        nested: NestedMode,
392    ) -> Self {
393        CpuConfigX86_64 {
394            force_calibrated_tsc_leaf,
395            host_cpu_topology,
396            enable_hwp,
397            no_smt,
398            itmt,
399            hybrid_type,
400            nested,
401        }
402    }
403}
404
405/// A CpuId Entry contains supported feature information for the given processor.
406/// This can be modified by the hypervisor to pass additional information to the guest kernel
407/// about the hypervisor or vm. Information is returned in the eax, ebx, ecx and edx registers
408/// by the cpu for a given function and index/subfunction (passed into the cpu via the eax and ecx
409/// register respectively).
410#[repr(C)]
411#[derive(Clone, Copy, Debug, PartialEq, Eq)]
412pub struct CpuIdEntry {
413    pub function: u32,
414    pub index: u32,
415    // flags is needed for KVM.  We store it on CpuIdEntry to preserve the flags across
416    // get_supported_cpuids() -> kvm_cpuid2 -> CpuId -> kvm_cpuid2 -> set_cpuid().
417    pub flags: u32,
418    pub cpuid: CpuidResult,
419}
420
421/// A container for the list of cpu id entries for the hypervisor and underlying cpu.
422pub struct CpuId {
423    pub cpu_id_entries: Vec<CpuIdEntry>,
424}
425
426impl CpuId {
427    /// Constructs a new CpuId, with space allocated for `initial_capacity` CpuIdEntries.
428    pub fn new(initial_capacity: usize) -> Self {
429        CpuId {
430            cpu_id_entries: Vec::with_capacity(initial_capacity),
431        }
432    }
433}
434
435#[bitfield]
436#[derive(Clone, Copy, Debug, PartialEq, Eq)]
437pub enum DestinationMode {
438    Physical = 0,
439    Logical = 1,
440}
441
442#[bitfield]
443#[derive(Clone, Copy, Debug, PartialEq, Eq)]
444pub enum TriggerMode {
445    Edge = 0,
446    Level = 1,
447}
448
449#[bitfield]
450#[derive(Debug, Clone, Copy, PartialEq, Eq)]
451pub enum DeliveryMode {
452    Fixed = 0b000,
453    Lowest = 0b001,
454    SMI = 0b010,        // System management interrupt
455    RemoteRead = 0b011, // This is no longer supported by intel.
456    NMI = 0b100,        // Non maskable interrupt
457    Init = 0b101,
458    Startup = 0b110,
459    External = 0b111,
460}
461
462// These MSI structures are for Intel's implementation of MSI.  The PCI spec defines most of MSI,
463// but the Intel spec defines the format of messages for raising interrupts.  The PCI spec defines
464// three u32s -- the address, address_high, and data -- but Intel only makes use of the address and
465// data.  The Intel portion of the specification is in Volume 3 section 10.11.
466#[bitfield]
467#[derive(Clone, Copy, PartialEq, Eq)]
468pub struct MsiAddressMessage {
469    pub reserved: BitField2,
470    #[bits = 1]
471    pub destination_mode: DestinationMode,
472    pub redirection_hint: BitField1,
473    pub reserved_2: BitField8,
474    pub destination_id: BitField8,
475    // According to Intel's implementation of MSI, these bits must always be 0xfee.
476    pub always_0xfee: BitField12,
477}
478
479#[bitfield]
480#[derive(Clone, Copy, PartialEq, Eq)]
481pub struct MsiDataMessage {
482    pub vector: BitField8,
483    #[bits = 3]
484    pub delivery_mode: DeliveryMode,
485    pub reserved: BitField3,
486    #[bits = 1]
487    pub level: Level,
488    #[bits = 1]
489    pub trigger: TriggerMode,
490    pub reserved2: BitField16,
491}
492
493#[bitfield]
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
495pub enum DeliveryStatus {
496    Idle = 0,
497    Pending = 1,
498}
499
500/// The level of a level-triggered interrupt: asserted or deasserted.
501#[bitfield]
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub enum Level {
504    Deassert = 0,
505    Assert = 1,
506}
507
508/// Represents a IOAPIC redirection table entry.
509#[bitfield]
510#[derive(Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
511pub struct IoapicRedirectionTableEntry {
512    vector: BitField8,
513    #[bits = 3]
514    delivery_mode: DeliveryMode,
515    #[bits = 1]
516    dest_mode: DestinationMode,
517    #[bits = 1]
518    delivery_status: DeliveryStatus,
519    polarity: BitField1,
520    remote_irr: bool,
521    #[bits = 1]
522    trigger_mode: TriggerMode,
523    interrupt_mask: bool, // true iff interrupts are masked.
524    reserved: BitField39,
525    dest_id: BitField8,
526}
527
528/// Number of pins on the standard KVM/IOAPIC.
529pub const NUM_IOAPIC_PINS: usize = 24;
530
531/// Represents the state of the IOAPIC.
532#[repr(C)]
533#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
534pub struct IoapicState {
535    /// base_address is the memory base address for this IOAPIC. It cannot be changed.
536    pub base_address: u64,
537    /// ioregsel register. Used for selecting which entry of the redirect table to read/write.
538    pub ioregsel: u8,
539    /// ioapicid register. Bits 24 - 27 contain the APIC ID for this device.
540    pub ioapicid: u32,
541    /// current_interrupt_level_bitmap represents a bitmap of the state of all of the irq lines
542    pub current_interrupt_level_bitmap: u32,
543    /// redirect_table contains the irq settings for each irq line
544    #[serde(
545        serialize_with = "serialize_arr",
546        deserialize_with = "deserialize_seq_to_arr"
547    )]
548    pub redirect_table: [IoapicRedirectionTableEntry; NUM_IOAPIC_PINS],
549}
550
551impl Default for IoapicState {
552    fn default() -> IoapicState {
553        // SAFETY: trivially safe
554        unsafe { std::mem::zeroed() }
555    }
556}
557
558#[repr(C)]
559#[derive(Debug, Clone, Copy, PartialEq, Eq)]
560pub enum PicSelect {
561    Primary = 0,
562    Secondary = 1,
563}
564
565#[repr(C)]
566#[derive(enumn::N, Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
567pub enum PicInitState {
568    #[default]
569    Icw1 = 0,
570    Icw2 = 1,
571    Icw3 = 2,
572    Icw4 = 3,
573}
574
575/// Convenience implementation for converting from a u8
576impl From<u8> for PicInitState {
577    fn from(item: u8) -> Self {
578        PicInitState::n(item).unwrap_or_else(|| {
579            error!("Invalid PicInitState {}, setting to 0", item);
580            PicInitState::Icw1
581        })
582    }
583}
584
585/// Represents the state of the PIC.
586#[repr(C)]
587#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
588pub struct PicState {
589    /// Edge detection.
590    pub last_irr: u8,
591    /// Interrupt Request Register.
592    pub irr: u8,
593    /// Interrupt Mask Register.
594    pub imr: u8,
595    /// Interrupt Service Register.
596    pub isr: u8,
597    /// Highest priority, for priority rotation.
598    pub priority_add: u8,
599    pub irq_base: u8,
600    pub read_reg_select: bool,
601    pub poll: bool,
602    pub special_mask: bool,
603    pub init_state: PicInitState,
604    pub auto_eoi: bool,
605    pub rotate_on_auto_eoi: bool,
606    pub special_fully_nested_mode: bool,
607    /// PIC takes either 3 or 4 bytes of initialization command word during
608    /// initialization. use_4_byte_icw is true if 4 bytes of ICW are needed.
609    pub use_4_byte_icw: bool,
610    /// "Edge/Level Control Registers", for edge trigger selection.
611    /// When a particular bit is set, the corresponding IRQ is in level-triggered mode. Otherwise
612    /// it is in edge-triggered mode.
613    pub elcr: u8,
614    pub elcr_mask: u8,
615}
616
617/// The LapicState represents the state of an x86 CPU's Local APIC.
618/// The Local APIC consists of 64 128-bit registers, but only the first 32-bits of each register
619/// can be used, so this structure only stores the first 32-bits of each register.
620#[repr(C)]
621#[derive(Clone, Copy, Serialize, Deserialize)]
622pub struct LapicState {
623    #[serde(
624        serialize_with = "serialize_arr",
625        deserialize_with = "deserialize_seq_to_arr"
626    )]
627    pub regs: [LapicRegister; 64],
628}
629
630pub type LapicRegister = u32;
631
632// rust arrays longer than 32 need custom implementations of Debug
633impl std::fmt::Debug for LapicState {
634    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
635        self.regs[..].fmt(formatter)
636    }
637}
638
639// rust arrays longer than 32 need custom implementations of PartialEq
640impl PartialEq for LapicState {
641    fn eq(&self, other: &LapicState) -> bool {
642        self.regs[..] == other.regs[..]
643    }
644}
645
646// Lapic equality is reflexive, so we impl Eq
647impl Eq for LapicState {}
648
649// Local APIC ID register: index 2 (offset 0x20)
650pub const APIC_ID_REG: usize = 2;
651// Local APIC IRR registers: indices 32..=39 (offsets 0x200..0x270, vectors 0..=255)
652pub const APIC_IRR_START_REG: usize = 32;
653
654impl LapicState {
655    /// Returns the APIC ID from the LAPIC registers.
656    pub fn get_apic_id(&self) -> u32 {
657        (self.regs[APIC_ID_REG] >> 24) & 0xFF
658    }
659
660    /// Returns a list of all pending interrupt vectors set in the IRR (Interrupt Request Register).
661    pub fn get_pending_irr_vectors(&self) -> Vec<u8> {
662        let mut vectors = Vec::new();
663        for (i, &reg) in self.regs[APIC_IRR_START_REG..=APIC_IRR_START_REG + 7]
664            .iter()
665            .enumerate()
666        {
667            if reg != 0 {
668                for bit in 0..32 {
669                    if (reg & (1 << bit)) != 0 {
670                        vectors.push((i * 32 + bit) as u8);
671                    }
672                }
673            }
674        }
675        vectors
676    }
677}
678
679/// The PitState represents the state of the PIT (aka the Programmable Interval Timer).
680/// The state is simply the state of it's three channels.
681#[repr(C)]
682#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
683pub struct PitState {
684    pub channels: [PitChannelState; 3],
685    /// Hypervisor-specific flags for setting the pit state.
686    pub flags: u32,
687}
688
689/// The PitRWMode enum represents the access mode of a PIT channel.
690/// Reads and writes to the Pit happen over Port-mapped I/O, which happens one byte at a time,
691/// but the count values and latch values are two bytes. So the access mode controls which of the
692/// two bytes will be read when.
693#[repr(C)]
694#[derive(enumn::N, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
695pub enum PitRWMode {
696    /// None mode means that no access mode has been set.
697    None = 0,
698    /// Least mode means all reads/writes will read/write the least significant byte.
699    Least = 1,
700    /// Most mode means all reads/writes will read/write the most significant byte.
701    Most = 2,
702    /// Both mode means first the least significant byte will be read/written, then the
703    /// next read/write will read/write the most significant byte.
704    Both = 3,
705}
706
707/// Convenience implementation for converting from a u8
708impl From<u8> for PitRWMode {
709    fn from(item: u8) -> Self {
710        PitRWMode::n(item).unwrap_or_else(|| {
711            error!("Invalid PitRWMode value {}, setting to 0", item);
712            PitRWMode::None
713        })
714    }
715}
716
717/// The PitRWState enum represents the state of reading to or writing from a channel.
718/// This is related to the PitRWMode, it mainly gives more detail about the state of the channel
719/// with respect to PitRWMode::Both.
720#[repr(C)]
721#[derive(enumn::N, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
722pub enum PitRWState {
723    /// None mode means that no access mode has been set.
724    None = 0,
725    /// LSB means that the channel is in PitRWMode::Least access mode.
726    LSB = 1,
727    /// MSB means that the channel is in PitRWMode::Most access mode.
728    MSB = 2,
729    /// Word0 means that the channel is in PitRWMode::Both mode, and the least sginificant byte
730    /// has not been read/written yet.
731    Word0 = 3,
732    /// Word1 means that the channel is in PitRWMode::Both mode and the least significant byte
733    /// has already been read/written, and the next byte to be read/written will be the most
734    /// significant byte.
735    Word1 = 4,
736}
737
738/// Convenience implementation for converting from a u8
739impl From<u8> for PitRWState {
740    fn from(item: u8) -> Self {
741        PitRWState::n(item).unwrap_or_else(|| {
742            error!("Invalid PitRWState value {}, setting to 0", item);
743            PitRWState::None
744        })
745    }
746}
747
748/// The PitChannelState represents the state of one of the PIT's three counters.
749#[repr(C)]
750#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
751pub struct PitChannelState {
752    /// The starting value for the counter.
753    pub count: u32,
754    /// Stores the channel count from the last time the count was latched.
755    pub latched_count: u16,
756    /// Indicates the PitRWState state of reading the latch value.
757    pub count_latched: PitRWState,
758    /// Indicates whether ReadBack status has been latched.
759    pub status_latched: bool,
760    /// Stores the channel status from the last time the status was latched. The status contains
761    /// information about the access mode of this channel, but changing those bits in the status
762    /// will not change the behavior of the pit.
763    pub status: u8,
764    /// Indicates the PitRWState state of reading the counter.
765    pub read_state: PitRWState,
766    /// Indicates the PitRWState state of writing the counter.
767    pub write_state: PitRWState,
768    /// Stores the value with which the counter was initialized. Counters are 16-
769    /// bit values with an effective range of 1-65536 (65536 represented by 0).
770    pub reload_value: u16,
771    /// The command access mode of this channel.
772    pub rw_mode: PitRWMode,
773    /// The operation mode of this channel.
774    pub mode: u8,
775    /// Whether or not we are in bcd mode. Not supported by KVM or crosvm's PIT implementation.
776    pub bcd: bool,
777    /// Value of the gate input pin. This only applies to channel 2.
778    pub gate: bool,
779    /// Nanosecond timestamp of when the count value was loaded.
780    pub count_load_time: u64,
781}
782
783// Convenience constructors for IrqRoutes
784impl IrqRoute {
785    pub fn ioapic_irq_route(irq_num: u32) -> IrqRoute {
786        IrqRoute {
787            gsi: irq_num,
788            source: IrqSource::Irqchip {
789                chip: IrqSourceChip::Ioapic,
790                pin: irq_num,
791            },
792        }
793    }
794
795    pub fn pic_irq_route(id: IrqSourceChip, irq_num: u32) -> IrqRoute {
796        IrqRoute {
797            gsi: irq_num,
798            source: IrqSource::Irqchip {
799                chip: id,
800                pin: irq_num % 8,
801            },
802        }
803    }
804}
805
806/// State of a VCPU's general purpose registers.
807#[repr(C)]
808#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
809pub struct Regs {
810    pub rax: u64,
811    pub rbx: u64,
812    pub rcx: u64,
813    pub rdx: u64,
814    pub rsi: u64,
815    pub rdi: u64,
816    pub rsp: u64,
817    pub rbp: u64,
818    pub r8: u64,
819    pub r9: u64,
820    pub r10: u64,
821    pub r11: u64,
822    pub r12: u64,
823    pub r13: u64,
824    pub r14: u64,
825    pub r15: u64,
826    pub rip: u64,
827    pub rflags: u64,
828}
829
830impl Default for Regs {
831    fn default() -> Self {
832        Regs {
833            rax: 0,
834            rbx: 0,
835            rcx: 0,
836            rdx: 0,
837            rsi: 0,
838            rdi: 0,
839            rsp: 0,
840            rbp: 0,
841            r8: 0,
842            r9: 0,
843            r10: 0,
844            r11: 0,
845            r12: 0,
846            r13: 0,
847            r14: 0,
848            r15: 0,
849            rip: 0xfff0, // Reset vector.
850            rflags: 0x2, // Bit 1 (0x2) is always 1.
851        }
852    }
853}
854
855/// State of a memory segment.
856#[repr(C)]
857#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
858pub struct Segment {
859    pub base: u64,
860    /// Limit of the segment - always in bytes, regardless of granularity (`g`) field.
861    pub limit_bytes: u32,
862    pub selector: u16,
863    pub type_: u8,
864    pub present: u8,
865    pub dpl: u8,
866    pub db: u8,
867    pub s: u8,
868    pub l: u8,
869    pub g: u8,
870    pub avl: u8,
871}
872
873/// State of a global descriptor table or interrupt descriptor table.
874#[repr(C)]
875#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize)]
876pub struct DescriptorTable {
877    pub base: u64,
878    pub limit: u16,
879}
880
881/// State of a VCPU's special registers.
882#[repr(C)]
883#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
884pub struct Sregs {
885    pub cs: Segment,
886    pub ds: Segment,
887    pub es: Segment,
888    pub fs: Segment,
889    pub gs: Segment,
890    pub ss: Segment,
891    pub tr: Segment,
892    pub ldt: Segment,
893    pub gdt: DescriptorTable,
894    pub idt: DescriptorTable,
895    pub cr0: u64,
896    pub cr2: u64,
897    pub cr3: u64,
898    pub cr4: u64,
899    pub cr8: u64,
900    pub efer: u64,
901}
902
903impl Default for Sregs {
904    fn default() -> Self {
905        // Intel SDM Vol. 3A, 3.4.5.1 ("Code- and Data-Segment Descriptor Types")
906        const SEG_TYPE_DATA: u8 = 0b0000;
907        const SEG_TYPE_DATA_WRITABLE: u8 = 0b0010;
908
909        const SEG_TYPE_CODE: u8 = 0b1000;
910        const SEG_TYPE_CODE_READABLE: u8 = 0b0010;
911
912        const SEG_TYPE_ACCESSED: u8 = 0b0001;
913
914        // Intel SDM Vol. 3A, 3.4.5 ("Segment Descriptors")
915        const SEG_S_SYSTEM: u8 = 0; // System segment.
916        const SEG_S_CODE_OR_DATA: u8 = 1; // Data/code segment.
917
918        // 16-bit real-mode code segment (reset vector).
919        let code_seg = Segment {
920            base: 0xffff0000,
921            limit_bytes: 0xffff,
922            selector: 0xf000,
923            type_: SEG_TYPE_CODE | SEG_TYPE_CODE_READABLE | SEG_TYPE_ACCESSED, // 11
924            present: 1,
925            s: SEG_S_CODE_OR_DATA,
926            ..Default::default()
927        };
928
929        // 16-bit real-mode data segment.
930        let data_seg = Segment {
931            base: 0,
932            limit_bytes: 0xffff,
933            selector: 0,
934            type_: SEG_TYPE_DATA | SEG_TYPE_DATA_WRITABLE | SEG_TYPE_ACCESSED, // 3
935            present: 1,
936            s: SEG_S_CODE_OR_DATA,
937            ..Default::default()
938        };
939
940        // 16-bit TSS segment.
941        let task_seg = Segment {
942            base: 0,
943            limit_bytes: 0xffff,
944            selector: 0,
945            type_: SEG_TYPE_CODE | SEG_TYPE_CODE_READABLE | SEG_TYPE_ACCESSED, // 11
946            present: 1,
947            s: SEG_S_SYSTEM,
948            ..Default::default()
949        };
950
951        // Local descriptor table.
952        let ldt = Segment {
953            base: 0,
954            limit_bytes: 0xffff,
955            selector: 0,
956            type_: SEG_TYPE_DATA | SEG_TYPE_DATA_WRITABLE, // 2
957            present: 1,
958            s: SEG_S_SYSTEM,
959            ..Default::default()
960        };
961
962        // Global descriptor table.
963        let gdt = DescriptorTable {
964            base: 0,
965            limit: 0xffff,
966        };
967
968        // Interrupt descriptor table.
969        let idt = DescriptorTable {
970            base: 0,
971            limit: 0xffff,
972        };
973
974        let cr0 = (1 << 4) // CR0.ET (reserved, always 1)
975                | (1 << 30); // CR0.CD (cache disable)
976
977        Sregs {
978            cs: code_seg,
979            ds: data_seg,
980            es: data_seg,
981            fs: data_seg,
982            gs: data_seg,
983            ss: data_seg,
984            tr: task_seg,
985            ldt,
986            gdt,
987            idt,
988            cr0,
989            cr2: 0,
990            cr3: 0,
991            cr4: 0,
992            cr8: 0,
993            efer: 0,
994        }
995    }
996}
997
998/// x87 80-bit floating point value.
999#[repr(C)]
1000#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
1001pub struct FpuReg {
1002    /// 64-bit mantissa.
1003    pub significand: u64,
1004
1005    /// 15-bit biased exponent and sign bit.
1006    pub sign_exp: u16,
1007}
1008
1009impl FpuReg {
1010    /// Convert an array of 8x16-byte arrays to an array of 8 `FpuReg`.
1011    ///
1012    /// Ignores any data in the upper 6 bytes of each element; the values represent 80-bit FPU
1013    /// registers, so the upper 48 bits are unused.
1014    pub fn from_16byte_arrays(byte_arrays: &[[u8; 16]; 8]) -> [FpuReg; 8] {
1015        let mut regs = [FpuReg::default(); 8];
1016        for (dst, src) in regs.iter_mut().zip(byte_arrays.iter()) {
1017            let tbyte: [u8; 10] = src[0..10].try_into().unwrap();
1018            *dst = FpuReg::from(tbyte);
1019        }
1020        regs
1021    }
1022
1023    /// Convert an array of 8 `FpuReg` into 8x16-byte arrays.
1024    pub fn to_16byte_arrays(regs: &[FpuReg; 8]) -> [[u8; 16]; 8] {
1025        let mut byte_arrays = [[0u8; 16]; 8];
1026        for (dst, src) in byte_arrays.iter_mut().zip(regs.iter()) {
1027            *dst = (*src).into();
1028        }
1029        byte_arrays
1030    }
1031}
1032
1033impl From<[u8; 10]> for FpuReg {
1034    /// Construct a `FpuReg` from an 80-bit representation.
1035    fn from(value: [u8; 10]) -> FpuReg {
1036        // These array sub-slices can't fail, but there's no (safe) way to express that in Rust
1037        // without an `unwrap()`.
1038        let significand_bytes = value[0..8].try_into().unwrap();
1039        let significand = u64::from_le_bytes(significand_bytes);
1040        let sign_exp_bytes = value[8..10].try_into().unwrap();
1041        let sign_exp = u16::from_le_bytes(sign_exp_bytes);
1042        FpuReg {
1043            significand,
1044            sign_exp,
1045        }
1046    }
1047}
1048
1049impl From<FpuReg> for [u8; 10] {
1050    /// Convert an `FpuReg` into its 80-bit "TBYTE" representation.
1051    fn from(value: FpuReg) -> [u8; 10] {
1052        let mut bytes = [0u8; 10];
1053        bytes[0..8].copy_from_slice(&value.significand.to_le_bytes());
1054        bytes[8..10].copy_from_slice(&value.sign_exp.to_le_bytes());
1055        bytes
1056    }
1057}
1058
1059impl From<FpuReg> for [u8; 16] {
1060    /// Convert an `FpuReg` into its 80-bit representation plus 6 unused upper bytes.
1061    /// This is a convenience function for converting to hypervisor types.
1062    fn from(value: FpuReg) -> [u8; 16] {
1063        let mut bytes = [0u8; 16];
1064        bytes[0..8].copy_from_slice(&value.significand.to_le_bytes());
1065        bytes[8..10].copy_from_slice(&value.sign_exp.to_le_bytes());
1066        bytes
1067    }
1068}
1069
1070/// State of a VCPU's floating point unit.
1071#[repr(C)]
1072#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
1073pub struct Fpu {
1074    pub fpr: [FpuReg; 8],
1075    pub fcw: u16,
1076    pub fsw: u16,
1077    pub ftwx: u8,
1078    pub last_opcode: u16,
1079    pub last_ip: u64,
1080    pub last_dp: u64,
1081    pub xmm: [[u8; 16usize]; 16usize],
1082    pub mxcsr: u32,
1083}
1084
1085impl Default for Fpu {
1086    fn default() -> Self {
1087        Fpu {
1088            fpr: Default::default(),
1089            fcw: 0x37f, // Intel SDM Vol. 1, 13.6
1090            fsw: 0,
1091            ftwx: 0,
1092            last_opcode: 0,
1093            last_ip: 0,
1094            last_dp: 0,
1095            xmm: Default::default(),
1096            mxcsr: 0x1f80, // Intel SDM Vol. 1, 11.6.4
1097        }
1098    }
1099}
1100
1101/// State of a VCPU's debug registers.
1102#[repr(C)]
1103#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize)]
1104pub struct DebugRegs {
1105    pub db: [u64; 4usize],
1106    pub dr6: u64,
1107    pub dr7: u64,
1108}
1109
1110/// The hybrid type for intel hybrid CPU.
1111#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1112pub enum CpuHybridType {
1113    /// Intel Atom.
1114    Atom,
1115    /// Intel Core.
1116    Core,
1117}
1118
1119/// State of the VCPU's x87 FPU, MMX, XMM, YMM registers.
1120/// May contain more state depending on enabled extensions.
1121#[derive(Clone, Debug, Serialize, Deserialize)]
1122pub struct Xsave {
1123    data: Vec<u32>,
1124
1125    // Actual length in bytes. May be smaller than data if a non-u32 multiple of bytes is
1126    // requested.
1127    len: usize,
1128}
1129
1130impl Xsave {
1131    /// Create a new buffer to store Xsave data.
1132    ///
1133    /// # Argments
1134    /// * `len` size in bytes.
1135    pub fn new(len: usize) -> Self {
1136        Xsave {
1137            data: vec![0; len.div_ceil(4)],
1138            len,
1139        }
1140    }
1141
1142    pub fn as_ptr(&self) -> *const c_void {
1143        self.data.as_ptr() as *const c_void
1144    }
1145
1146    pub fn as_mut_ptr(&mut self) -> *mut c_void {
1147        self.data.as_mut_ptr() as *mut c_void
1148    }
1149
1150    /// Length in bytes of the XSAVE data.
1151    pub fn len(&self) -> usize {
1152        self.len
1153    }
1154
1155    /// Returns true is length of XSAVE data is zero
1156    pub fn is_empty(&self) -> bool {
1157        self.len() == 0
1158    }
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163    use super::*;
1164
1165    #[test]
1166    fn test_lapic_get_apic_id() {
1167        let mut lapic = LapicState { regs: [0; 64] };
1168        assert_eq!(lapic.get_apic_id(), 0);
1169
1170        // xAPIC mode: ID in bits 24..=31
1171        lapic.regs[APIC_ID_REG] = 0x05000000;
1172        assert_eq!(lapic.get_apic_id(), 5);
1173
1174        lapic.regs[APIC_ID_REG] = 0xFE000000;
1175        assert_eq!(lapic.get_apic_id(), 0xFE);
1176    }
1177
1178    #[test]
1179    fn test_lapic_get_pending_irr_vectors() {
1180        let mut lapic = LapicState { regs: [0; 64] };
1181        assert!(lapic.get_pending_irr_vectors().is_empty());
1182
1183        // Vector 0xEC (236): word 7 (regs[39]), bit 12 (236 - 224 = 12)
1184        lapic.regs[APIC_IRR_START_REG + 7] |= 1 << 12;
1185        // Vector 0x30 (48): word 1 (regs[33]), bit 16 (48 - 32 = 16)
1186        lapic.regs[APIC_IRR_START_REG + 1] |= 1 << 16;
1187
1188        let vectors = lapic.get_pending_irr_vectors();
1189        assert_eq!(vectors, vec![48, 236]);
1190    }
1191}