hypervisor/kvm/
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
5use std::arch::x86_64::CpuidResult;
6use std::collections::BTreeMap;
7use std::sync::Arc;
8
9use base::errno_result;
10use base::error;
11use base::ioctl;
12use base::ioctl_with_mut_ptr;
13use base::ioctl_with_mut_ref;
14use base::ioctl_with_ptr;
15use base::ioctl_with_ref;
16use base::ioctl_with_val;
17use base::AsRawDescriptor;
18use base::Error;
19use base::IoctlNr;
20use base::MappedRegion;
21use base::Result;
22use kvm_sys::*;
23use libc::E2BIG;
24use libc::EAGAIN;
25use libc::EINVAL;
26use libc::EIO;
27use libc::ENOMEM;
28use libc::ENXIO;
29use serde::Deserialize;
30use serde::Serialize;
31use snapshot::AnySnapshot;
32use vm_memory::GuestAddress;
33use zerocopy::FromZeros;
34
35use super::Config;
36use super::Kvm;
37use super::KvmCap;
38use super::KvmVcpu;
39use super::KvmVm;
40use crate::host_phys_addr_bits;
41use crate::ClockState;
42use crate::CpuId;
43use crate::CpuIdEntry;
44use crate::DebugRegs;
45use crate::DescriptorTable;
46use crate::DeviceKind;
47use crate::Fpu;
48use crate::FpuReg;
49use crate::HypervisorX86_64;
50use crate::IoapicRedirectionTableEntry;
51use crate::IoapicState;
52use crate::IrqSourceChip;
53use crate::LapicState;
54use crate::PicSelect;
55use crate::PicState;
56use crate::PitChannelState;
57use crate::PitState;
58use crate::ProtectionType;
59use crate::Regs;
60use crate::Segment;
61use crate::Sregs;
62use crate::VcpuExit;
63use crate::VcpuX86_64;
64use crate::VmCap;
65use crate::VmX86_64;
66use crate::Xsave;
67use crate::NUM_IOAPIC_PINS;
68
69const KVM_XSAVE_MAX_SIZE: usize = 4096;
70const MSR_IA32_APICBASE: u32 = 0x0000001b;
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct VcpuEvents {
74    pub exception: VcpuExceptionState,
75    pub interrupt: VcpuInterruptState,
76    pub nmi: VcpuNmiState,
77    pub sipi_vector: Option<u32>,
78    pub smi: VcpuSmiState,
79    pub triple_fault: VcpuTripleFaultState,
80    pub exception_payload: Option<u64>,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct VcpuExceptionState {
85    pub injected: bool,
86    pub nr: u8,
87    pub has_error_code: bool,
88    pub pending: Option<bool>,
89    pub error_code: u32,
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct VcpuInterruptState {
94    pub injected: bool,
95    pub nr: u8,
96    pub soft: bool,
97    pub shadow: Option<u8>,
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct VcpuNmiState {
102    pub injected: bool,
103    pub pending: Option<bool>,
104    pub masked: bool,
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct VcpuSmiState {
109    pub smm: Option<bool>,
110    pub pending: bool,
111    pub smm_inside_nmi: bool,
112    pub latched_init: u8,
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct VcpuTripleFaultState {
117    pub pending: Option<bool>,
118}
119
120pub fn get_cpuid_with_initial_capacity<T: AsRawDescriptor>(
121    descriptor: &T,
122    kind: IoctlNr,
123    initial_capacity: usize,
124) -> Result<CpuId> {
125    let mut entries: usize = initial_capacity;
126
127    loop {
128        let mut kvm_cpuid =
129            kvm_cpuid2::<[kvm_cpuid_entry2]>::new_box_zeroed_with_elems(entries).unwrap();
130        kvm_cpuid.nent = entries.try_into().unwrap();
131
132        let ret = {
133            // SAFETY:
134            // ioctl is unsafe. The kernel is trusted not to write beyond the bounds of the
135            // memory allocated for the struct. The limit is read from nent within kvm_cpuid2,
136            // which is set to the allocated size above.
137            unsafe { ioctl_with_mut_ref(descriptor, kind, &mut *kvm_cpuid) }
138        };
139        if ret < 0 {
140            let err = Error::last();
141            match err.errno() {
142                E2BIG => {
143                    // double the available memory for cpuid entries for kvm.
144                    if let Some(val) = entries.checked_mul(2) {
145                        entries = val;
146                    } else {
147                        return Err(err);
148                    }
149                }
150                _ => return Err(err),
151            }
152        } else {
153            return Ok(CpuId::from(&*kvm_cpuid));
154        }
155    }
156}
157
158impl Kvm {
159    pub fn get_cpuid(&self, kind: IoctlNr) -> Result<CpuId> {
160        const KVM_MAX_ENTRIES: usize = 256;
161        get_cpuid_with_initial_capacity(self, kind, KVM_MAX_ENTRIES)
162    }
163
164    pub fn get_vm_type(&self, protection_type: ProtectionType) -> Result<u32> {
165        if protection_type.isolates_memory() {
166            Ok(KVM_X86_PKVM_PROTECTED_VM)
167        } else {
168            Ok(KVM_X86_DEFAULT_VM)
169        }
170    }
171
172    /// Get the size of guest physical addresses in bits.
173    pub fn get_guest_phys_addr_bits(&self) -> u8 {
174        // Assume the guest physical address size is the same as the host.
175        host_phys_addr_bits()
176    }
177}
178
179impl HypervisorX86_64 for Kvm {
180    fn get_supported_cpuid(&self) -> Result<CpuId> {
181        self.get_cpuid(KVM_GET_SUPPORTED_CPUID)
182    }
183
184    fn get_msr_index_list(&self) -> Result<Vec<u32>> {
185        const MAX_KVM_MSR_ENTRIES: usize = 256;
186
187        let mut msr_list = kvm_msr_list::<[u32; MAX_KVM_MSR_ENTRIES]>::new_zeroed();
188        msr_list.nmsrs = MAX_KVM_MSR_ENTRIES as u32;
189
190        let ret = {
191            // SAFETY:
192            // ioctl is unsafe. The kernel is trusted not to write beyond the bounds of the memory
193            // allocated for the struct. The limit is read from nmsrs, which is set to the allocated
194            // size (MAX_KVM_MSR_ENTRIES) above.
195            unsafe { ioctl_with_mut_ref(self, KVM_GET_MSR_INDEX_LIST, &mut msr_list) }
196        };
197        if ret < 0 {
198            return errno_result();
199        }
200
201        let mut nmsrs = msr_list.nmsrs;
202        if nmsrs > MAX_KVM_MSR_ENTRIES as u32 {
203            nmsrs = MAX_KVM_MSR_ENTRIES as u32;
204        }
205
206        Ok(msr_list.indices[..nmsrs as usize].to_vec())
207    }
208}
209
210impl KvmVm {
211    /// Does platform specific initialization for the KvmVm.
212    pub fn init_arch(&self, _cfg: &Config) -> Result<()> {
213        Ok(())
214    }
215
216    /// Checks if a particular `VmCap` is available, or returns None if arch-independent
217    /// Vm.check_capability() should handle the check.
218    pub fn check_capability_arch(&self, c: VmCap) -> Option<bool> {
219        match c {
220            VmCap::PvClock => Some(true),
221            _ => None,
222        }
223    }
224
225    /// Returns the params to pass to KVM_CREATE_DEVICE for a `kind` device on this arch, or None to
226    /// let the arch-independent `KvmVm::create_device` handle it.
227    pub fn get_device_params_arch(&self, _kind: DeviceKind) -> Option<kvm_create_device> {
228        None
229    }
230
231    /// Arch-specific implementation of `Vm::get_pvclock`.
232    pub fn get_pvclock_arch(&self) -> Result<ClockState> {
233        let mut clock_data: kvm_clock_data = Default::default();
234        let ret =
235            // SAFETY:
236            // Safe because we know that our file is a VM fd, we know the kernel will only write correct
237            // amount of memory to our pointer, and we verify the return result.
238            unsafe { ioctl_with_mut_ref(self, KVM_GET_CLOCK, &mut clock_data) };
239        if ret == 0 {
240            Ok(ClockState::from(&clock_data))
241        } else {
242            errno_result()
243        }
244    }
245
246    /// Arch-specific implementation of `Vm::set_pvclock`.
247    pub fn set_pvclock_arch(&self, state: &ClockState) -> Result<()> {
248        let clock_data = kvm_clock_data::from(state);
249        // SAFETY:
250        // Safe because we know that our file is a VM fd, we know the kernel will only read correct
251        // amount of memory from our pointer, and we verify the return result.
252        let ret = unsafe { ioctl_with_ref(self, KVM_SET_CLOCK, &clock_data) };
253        if ret == 0 {
254            Ok(())
255        } else {
256            errno_result()
257        }
258    }
259
260    /// Signals an interrupt vector directly to a vCPU's Local APIC using MSI.
261    pub fn signal_msi_to_lapic(&self, apic_id: u32, vector: u8) -> Result<()> {
262        let msi = kvm_msi {
263            address_lo: 0xFEE0_0000 | ((apic_id & 0xFF) << 12),
264            address_hi: 0,
265            data: vector as u32,
266            flags: 0,
267            ..Default::default()
268        };
269        self.signal_msi(&msi)
270    }
271
272    /// Retrieves the state of given interrupt controller by issuing KVM_GET_IRQCHIP ioctl.
273    ///
274    /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
275    pub fn get_pic_state(&self, id: PicSelect) -> Result<kvm_pic_state> {
276        let mut irqchip_state = kvm_irqchip {
277            chip_id: id as u32,
278            ..Default::default()
279        };
280        let ret = {
281            // SAFETY:
282            // Safe because we know our file is a VM fd, we know the kernel will only write
283            // correct amount of memory to our pointer, and we verify the return result.
284            unsafe { ioctl_with_mut_ref(self, KVM_GET_IRQCHIP, &mut irqchip_state) }
285        };
286        if ret == 0 {
287            Ok(
288                // SAFETY:
289                // Safe as we know that we are retrieving data related to the
290                // PIC (primary or secondary) and not IOAPIC.
291                unsafe { irqchip_state.chip.pic },
292            )
293        } else {
294            errno_result()
295        }
296    }
297
298    /// Sets the state of given interrupt controller by issuing KVM_SET_IRQCHIP ioctl.
299    ///
300    /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
301    pub fn set_pic_state(&self, id: PicSelect, state: &kvm_pic_state) -> Result<()> {
302        let mut irqchip_state = kvm_irqchip {
303            chip_id: id as u32,
304            ..Default::default()
305        };
306        irqchip_state.chip.pic = *state;
307        // SAFETY:
308        // Safe because we know that our file is a VM fd, we know the kernel will only read
309        // correct amount of memory from our pointer, and we verify the return result.
310        let ret = unsafe { ioctl_with_ref(self, KVM_SET_IRQCHIP, &irqchip_state) };
311        if ret == 0 {
312            Ok(())
313        } else {
314            errno_result()
315        }
316    }
317
318    /// Retrieves the number of pins for emulated IO-APIC.
319    pub fn get_ioapic_num_pins(&self) -> Result<usize> {
320        Ok(NUM_IOAPIC_PINS)
321    }
322
323    /// Retrieves the state of IOAPIC by issuing KVM_GET_IRQCHIP ioctl.
324    ///
325    /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
326    pub fn get_ioapic_state(&self) -> Result<kvm_ioapic_state> {
327        let mut irqchip_state = kvm_irqchip {
328            chip_id: 2,
329            ..Default::default()
330        };
331        let ret = {
332            // SAFETY:
333            // Safe because we know our file is a VM fd, we know the kernel will only write
334            // correct amount of memory to our pointer, and we verify the return result.
335            unsafe { ioctl_with_mut_ref(self, KVM_GET_IRQCHIP, &mut irqchip_state) }
336        };
337        if ret == 0 {
338            Ok(
339                // SAFETY:
340                // Safe as we know that we are retrieving data related to the
341                // IOAPIC and not PIC.
342                unsafe { irqchip_state.chip.ioapic },
343            )
344        } else {
345            errno_result()
346        }
347    }
348
349    /// Sets the state of IOAPIC by issuing KVM_SET_IRQCHIP ioctl.
350    ///
351    /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
352    pub fn set_ioapic_state(&self, state: &kvm_ioapic_state) -> Result<()> {
353        let mut irqchip_state = kvm_irqchip {
354            chip_id: 2,
355            ..Default::default()
356        };
357        irqchip_state.chip.ioapic = *state;
358        // SAFETY:
359        // Safe because we know that our file is a VM fd, we know the kernel will only read
360        // correct amount of memory from our pointer, and we verify the return result.
361        let ret = unsafe { ioctl_with_ref(self, KVM_SET_IRQCHIP, &irqchip_state) };
362        if ret == 0 {
363            Ok(())
364        } else {
365            errno_result()
366        }
367    }
368
369    /// Creates a PIT as per the KVM_CREATE_PIT2 ioctl.
370    ///
371    /// Note that this call can only succeed after a call to `Vm::create_irq_chip`.
372    pub fn create_pit(&self) -> Result<()> {
373        let pit_config = kvm_pit_config::default();
374        // SAFETY:
375        // Safe because we know that our file is a VM fd, we know the kernel will only read the
376        // correct amount of memory from our pointer, and we verify the return result.
377        let ret = unsafe { ioctl_with_ref(self, KVM_CREATE_PIT2, &pit_config) };
378        if ret == 0 {
379            Ok(())
380        } else {
381            errno_result()
382        }
383    }
384
385    /// Retrieves the state of PIT by issuing KVM_GET_PIT2 ioctl.
386    ///
387    /// Note that this call can only succeed after a call to `Vm::create_pit`.
388    pub fn get_pit_state(&self) -> Result<kvm_pit_state2> {
389        let mut pit_state = Default::default();
390        // SAFETY:
391        // Safe because we know that our file is a VM fd, we know the kernel will only write
392        // correct amount of memory to our pointer, and we verify the return result.
393        let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_PIT2, &mut pit_state) };
394        if ret == 0 {
395            Ok(pit_state)
396        } else {
397            errno_result()
398        }
399    }
400
401    /// Sets the state of PIT by issuing KVM_SET_PIT2 ioctl.
402    ///
403    /// Note that this call can only succeed after a call to `Vm::create_pit`.
404    pub fn set_pit_state(&self, pit_state: &kvm_pit_state2) -> Result<()> {
405        // SAFETY:
406        // Safe because we know that our file is a VM fd, we know the kernel will only read
407        // correct amount of memory from our pointer, and we verify the return result.
408        let ret = unsafe { ioctl_with_ref(self, KVM_SET_PIT2, pit_state) };
409        if ret == 0 {
410            Ok(())
411        } else {
412            errno_result()
413        }
414    }
415
416    /// Set MSR_PLATFORM_INFO read access.
417    pub fn set_platform_info_read_access(&self, allow_read: bool) -> Result<()> {
418        let mut cap = kvm_enable_cap {
419            cap: KVM_CAP_MSR_PLATFORM_INFO,
420            ..Default::default()
421        };
422        cap.args[0] = allow_read as u64;
423
424        // SAFETY:
425        // Safe because we know that our file is a VM fd, we know that the
426        // kernel will only read correct amount of memory from our pointer, and
427        // we verify the return result.
428        let ret = unsafe { ioctl_with_ref(self, KVM_ENABLE_CAP, &cap) };
429        if ret < 0 {
430            errno_result()
431        } else {
432            Ok(())
433        }
434    }
435
436    /// Enable support for split-irqchip.
437    pub fn enable_split_irqchip(&self, ioapic_pins: usize) -> Result<()> {
438        let mut cap = kvm_enable_cap {
439            cap: KVM_CAP_SPLIT_IRQCHIP,
440            ..Default::default()
441        };
442        cap.args[0] = ioapic_pins as u64;
443        // SAFETY:
444        // safe becuase we allocated the struct and we know the kernel will read
445        // exactly the size of the struct
446        let ret = unsafe { ioctl_with_ref(self, KVM_ENABLE_CAP, &cap) };
447        if ret < 0 {
448            errno_result()
449        } else {
450            Ok(())
451        }
452    }
453
454    /// Get pKVM hypervisor details, e.g. the firmware size.
455    ///
456    /// Returns `Err` if not running under pKVM.
457    ///
458    /// Uses `KVM_ENABLE_CAP` internally, but it is only a getter, there should be no side effects
459    /// in KVM.
460    fn get_protected_vm_info(&self) -> Result<KvmProtectedVmInfo> {
461        let mut info = KvmProtectedVmInfo {
462            firmware_size: 0,
463            reserved: [0; 7],
464        };
465        // SAFETY:
466        // Safe because we allocated the struct and we know the kernel won't write beyond the end of
467        // the struct or keep a pointer to it.
468        unsafe {
469            self.enable_raw_capability(
470                KvmCap::X86ProtectedVm,
471                KVM_CAP_X86_PROTECTED_VM_FLAGS_INFO,
472                &[&mut info as *mut KvmProtectedVmInfo as u64, 0, 0, 0],
473            )
474        }?;
475        Ok(info)
476    }
477
478    fn set_protected_vm_firmware_gpa(&self, fw_addr: GuestAddress) -> Result<()> {
479        // SAFETY:
480        // Safe because none of the args are pointers.
481        unsafe {
482            self.enable_raw_capability(
483                KvmCap::X86ProtectedVm,
484                KVM_CAP_X86_PROTECTED_VM_FLAGS_SET_FW_GPA,
485                &[fw_addr.0, 0, 0, 0],
486            )
487        }
488    }
489}
490
491#[repr(C)]
492struct KvmProtectedVmInfo {
493    firmware_size: u64,
494    reserved: [u64; 7],
495}
496
497impl VmX86_64 for KvmVm {
498    /// Sets the bootstrap processor (BSP) vCPU ID.
499    ///
500    /// See the documentation on the KVM_SET_BOOT_CPU_ID ioctl.
501    fn set_boot_cpu_id(&self, vcpu_id: usize) -> Result<()> {
502        if !self.check_raw_capability(KvmCap::SetBootCpuId) {
503            return Err(Error::new(libc::ENOTSUP));
504        }
505        // SAFETY:
506        // Safe because we know that our file is a VM fd, the argument is a plain integer, and we
507        // verify the return result.
508        let ret = unsafe { ioctl_with_val(self, KVM_SET_BOOT_CPU_ID, vcpu_id as libc::c_ulong) };
509        if ret == 0 {
510            Ok(())
511        } else {
512            errno_result()
513        }
514    }
515
516    fn get_hypervisor(&self) -> &dyn HypervisorX86_64 {
517        &self.kvm
518    }
519
520    fn load_protected_vm_firmware(&self, fw_addr: GuestAddress, fw_max_size: u64) -> Result<()> {
521        let info = self.get_protected_vm_info()?;
522        if info.firmware_size == 0 {
523            Err(Error::new(EINVAL))
524        } else {
525            if info.firmware_size > fw_max_size {
526                return Err(Error::new(ENOMEM));
527            }
528            self.set_protected_vm_firmware_gpa(fw_addr)
529        }
530    }
531
532    fn create_vcpu(&self, id: usize) -> Result<Arc<dyn VcpuX86_64>> {
533        // create_vcpu is declared separately in VmAArch64 and VmX86, so it can return VcpuAArch64
534        // or VcpuX86.  But both use the same implementation in KvmVm::create_vcpu.
535        Ok(Arc::new(KvmVm::create_kvm_vcpu(self, id)?))
536    }
537
538    /// Sets the address of the three-page region in the VM's address space.
539    ///
540    /// See the documentation on the KVM_SET_TSS_ADDR ioctl.
541    fn set_tss_addr(&self, addr: GuestAddress) -> Result<()> {
542        // SAFETY:
543        // Safe because we know that our file is a VM fd and we verify the return result.
544        let ret = unsafe { ioctl_with_val(self, KVM_SET_TSS_ADDR, addr.offset()) };
545        if ret == 0 {
546            Ok(())
547        } else {
548            errno_result()
549        }
550    }
551
552    /// Sets the address of a one-page region in the VM's address space.
553    ///
554    /// See the documentation on the KVM_SET_IDENTITY_MAP_ADDR ioctl.
555    fn set_identity_map_addr(&self, addr: GuestAddress) -> Result<()> {
556        // SAFETY:
557        // Safe because we know that our file is a VM fd and we verify the return result.
558        let ret = unsafe { ioctl_with_ref(self, KVM_SET_IDENTITY_MAP_ADDR, &addr.offset()) };
559        if ret == 0 {
560            Ok(())
561        } else {
562            errno_result()
563        }
564    }
565}
566
567impl KvmVcpu {
568    /// Handles a `KVM_EXIT_SYSTEM_EVENT` with event type `KVM_SYSTEM_EVENT_RESET` with the given
569    /// event flags and returns the appropriate `VcpuExit` value for the run loop to handle.
570    pub fn system_event_reset(&self, _event_flags: u64) -> Result<VcpuExit> {
571        Ok(VcpuExit::SystemEventReset)
572    }
573
574    /// Gets the Xsave size by checking the extension KVM_CAP_XSAVE2.
575    ///
576    /// Size should always be >=0. If size is negative, an error occurred.
577    /// If size <= 4096, XSAVE2 is not supported by the CPU or the kernel. KVM_XSAVE_MAX_SIZE is
578    /// returned (4096).
579    /// Otherwise, the size will be returned.
580    fn xsave_size(&self) -> Result<usize> {
581        let size = {
582            // SAFETY:
583            // Safe because we know that our file is a valid VM fd
584            unsafe { ioctl_with_val(&self.vm, KVM_CHECK_EXTENSION, KVM_CAP_XSAVE2 as u64) }
585        };
586        if size < 0 {
587            return errno_result();
588        }
589        // Safe to unwrap since we already tested for negative values
590        let size: usize = size.try_into().unwrap();
591        Ok(size.max(KVM_XSAVE_MAX_SIZE))
592    }
593
594    #[inline]
595    pub(crate) fn handle_vm_exit_arch(&self, run: &mut kvm_run) -> Option<VcpuExit> {
596        match run.exit_reason {
597            KVM_EXIT_IO => Some(VcpuExit::Io),
598            KVM_EXIT_IOAPIC_EOI => {
599                // SAFETY:
600                // Safe because the exit_reason (which comes from the kernel) told us which
601                // union field to use.
602                let vector = unsafe { run.__bindgen_anon_1.eoi.vector };
603                Some(VcpuExit::IoapicEoi { vector })
604            }
605            KVM_EXIT_HLT => Some(VcpuExit::Hlt),
606            KVM_EXIT_SET_TPR => Some(VcpuExit::SetTpr),
607            KVM_EXIT_TPR_ACCESS => Some(VcpuExit::TprAccess),
608            KVM_EXIT_X86_BUS_LOCK => Some(VcpuExit::BusLock),
609            _ => None,
610        }
611    }
612}
613
614#[derive(Debug, Serialize, Deserialize)]
615struct HypervisorState {
616    interrupts: VcpuEvents,
617    nested_state: Vec<u8>,
618}
619
620impl VcpuX86_64 for KvmVcpu {
621    #[allow(clippy::cast_ptr_alignment)]
622    fn set_interrupt_window_requested(&self, requested: bool) {
623        // SAFETY:
624        // Safe because we know we mapped enough memory to hold the kvm_run struct because the
625        // kernel told us how large it was. The pointer is page aligned so casting to a different
626        // type is well defined, hence the clippy allow attribute.
627        let run = unsafe { &mut *(self.run_mmap.as_ptr() as *mut kvm_run) };
628        run.request_interrupt_window = requested.into();
629    }
630
631    #[allow(clippy::cast_ptr_alignment)]
632    fn ready_for_interrupt(&self) -> bool {
633        // SAFETY:
634        // Safe because we know we mapped enough memory to hold the kvm_run struct because the
635        // kernel told us how large it was. The pointer is page aligned so casting to a different
636        // type is well defined, hence the clippy allow attribute.
637        let run = unsafe { &mut *(self.run_mmap.as_ptr() as *mut kvm_run) };
638        run.ready_for_interrupt_injection != 0 && run.if_flag != 0
639    }
640
641    /// Use the KVM_INTERRUPT ioctl to inject the specified interrupt vector.
642    ///
643    /// While this ioctl exists on PPC and MIPS as well as x86, the semantics are different and
644    /// ChromeOS doesn't support PPC or MIPS.
645    fn interrupt(&self, irq: u8) -> Result<()> {
646        if !self.ready_for_interrupt() {
647            return Err(Error::new(EAGAIN));
648        }
649
650        let interrupt = kvm_interrupt { irq: irq.into() };
651        // SAFETY:
652        // safe becuase we allocated the struct and we know the kernel will read
653        // exactly the size of the struct
654        let ret = unsafe { ioctl_with_ref(self, KVM_INTERRUPT, &interrupt) };
655        if ret == 0 {
656            Ok(())
657        } else {
658            errno_result()
659        }
660    }
661
662    fn inject_nmi(&self) -> Result<()> {
663        // SAFETY:
664        // Safe because we know that our file is a VCPU fd.
665        let ret = unsafe { ioctl(self, KVM_NMI) };
666        if ret == 0 {
667            Ok(())
668        } else {
669            errno_result()
670        }
671    }
672
673    fn get_regs(&self) -> Result<Regs> {
674        let mut regs: kvm_regs = Default::default();
675        let ret = {
676            // SAFETY:
677            // Safe because we know that our file is a VCPU fd, we know the kernel will only read
678            // the correct amount of memory from our pointer, and we verify the return
679            // result.
680            unsafe { ioctl_with_mut_ref(self, KVM_GET_REGS, &mut regs) }
681        };
682        if ret == 0 {
683            Ok(Regs::from(&regs))
684        } else {
685            errno_result()
686        }
687    }
688
689    fn set_regs(&self, regs: &Regs) -> Result<()> {
690        let regs = kvm_regs::from(regs);
691        let ret = {
692            // SAFETY:
693            // Safe because we know that our file is a VCPU fd, we know the kernel will only read
694            // the correct amount of memory from our pointer, and we verify the return
695            // result.
696            unsafe { ioctl_with_ref(self, KVM_SET_REGS, &regs) }
697        };
698        if ret == 0 {
699            Ok(())
700        } else {
701            errno_result()
702        }
703    }
704
705    fn get_sregs(&self) -> Result<Sregs> {
706        let mut regs: kvm_sregs = Default::default();
707        let ret = {
708            // SAFETY:
709            // Safe because we know that our file is a VCPU fd, we know the kernel will only write
710            // the correct amount of memory to our pointer, and we verify the return
711            // result.
712            unsafe { ioctl_with_mut_ref(self, KVM_GET_SREGS, &mut regs) }
713        };
714        if ret == 0 {
715            Ok(Sregs::from(&regs))
716        } else {
717            errno_result()
718        }
719    }
720
721    fn set_sregs(&self, sregs: &Sregs) -> Result<()> {
722        // Get the current `kvm_sregs` so we can use its `apic_base` and `interrupt_bitmap`, which
723        // are not present in `Sregs`.
724        let mut kvm_sregs: kvm_sregs = Default::default();
725        // SAFETY:
726        // Safe because we know that our file is a VCPU fd, we know the kernel will only write the
727        // correct amount of memory to our pointer, and we verify the return result.
728        let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_SREGS, &mut kvm_sregs) };
729        if ret != 0 {
730            return errno_result();
731        }
732
733        kvm_sregs.cs = kvm_segment::from(&sregs.cs);
734        kvm_sregs.ds = kvm_segment::from(&sregs.ds);
735        kvm_sregs.es = kvm_segment::from(&sregs.es);
736        kvm_sregs.fs = kvm_segment::from(&sregs.fs);
737        kvm_sregs.gs = kvm_segment::from(&sregs.gs);
738        kvm_sregs.ss = kvm_segment::from(&sregs.ss);
739        kvm_sregs.tr = kvm_segment::from(&sregs.tr);
740        kvm_sregs.ldt = kvm_segment::from(&sregs.ldt);
741        kvm_sregs.gdt = kvm_dtable::from(&sregs.gdt);
742        kvm_sregs.idt = kvm_dtable::from(&sregs.idt);
743        kvm_sregs.cr0 = sregs.cr0;
744        kvm_sregs.cr2 = sregs.cr2;
745        kvm_sregs.cr3 = sregs.cr3;
746        kvm_sregs.cr4 = sregs.cr4;
747        kvm_sregs.cr8 = sregs.cr8;
748        kvm_sregs.efer = sregs.efer;
749
750        // SAFETY:
751        // Safe because we know that our file is a VCPU fd, we know the kernel will only read the
752        // correct amount of memory from our pointer, and we verify the return result.
753        let ret = unsafe { ioctl_with_ref(self, KVM_SET_SREGS, &kvm_sregs) };
754        if ret == 0 {
755            Ok(())
756        } else {
757            errno_result()
758        }
759    }
760
761    fn get_fpu(&self) -> Result<Fpu> {
762        let mut fpu: kvm_fpu = Default::default();
763        // SAFETY:
764        // Safe because we know that our file is a VCPU fd, we know the kernel will only write the
765        // correct amount of memory to our pointer, and we verify the return result.
766        let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_FPU, &mut fpu) };
767        if ret == 0 {
768            Ok(Fpu::from(&fpu))
769        } else {
770            errno_result()
771        }
772    }
773
774    fn set_fpu(&self, fpu: &Fpu) -> Result<()> {
775        let fpu = kvm_fpu::from(fpu);
776        let ret = {
777            // SAFETY:
778            // Here we trust the kernel not to read past the end of the kvm_fpu struct.
779            unsafe { ioctl_with_ref(self, KVM_SET_FPU, &fpu) }
780        };
781        if ret == 0 {
782            Ok(())
783        } else {
784            errno_result()
785        }
786    }
787
788    /// If the VM reports using XSave2, the function will call XSave2.
789    fn get_xsave(&self) -> Result<Xsave> {
790        let size = self.xsave_size()?;
791        let ioctl_nr = if size > KVM_XSAVE_MAX_SIZE {
792            KVM_GET_XSAVE2
793        } else {
794            KVM_GET_XSAVE
795        };
796        let mut xsave = Xsave::new(size);
797
798        // SAFETY:
799        // Safe because we know that our file is a VCPU fd, we know the kernel will only write the
800        // correct amount of memory to our pointer, and we verify the return result.
801        let ret = unsafe { ioctl_with_mut_ptr(self, ioctl_nr, xsave.as_mut_ptr()) };
802        if ret == 0 {
803            Ok(xsave)
804        } else {
805            errno_result()
806        }
807    }
808
809    fn set_xsave(&self, xsave: &Xsave) -> Result<()> {
810        let size = self.xsave_size()?;
811        // Ensure xsave is the same size as used in get_xsave.
812        // Return err if sizes don't match => not the same extensions are enabled for CPU.
813        if xsave.len() != size {
814            return Err(Error::new(EIO));
815        }
816
817        // SAFETY:
818        // Safe because we know that our file is a VCPU fd, we know the kernel will only write the
819        // correct amount of memory to our pointer, and we verify the return result.
820        // Because of the len check above, and because the layout of `struct kvm_xsave` is
821        // compatible with a slice of `u32`, we can pass the pointer to `xsave` directly.
822        let ret = unsafe { ioctl_with_ptr(self, KVM_SET_XSAVE, xsave.as_ptr()) };
823        if ret == 0 {
824            Ok(())
825        } else {
826            errno_result()
827        }
828    }
829
830    fn get_hypervisor_specific_state(&self) -> Result<AnySnapshot> {
831        let mut vcpu_evts: kvm_vcpu_events = Default::default();
832        // SAFETY:
833        // Safe because we know that our file is a VCPU fd, we know the kernel will only write
834        // the correct amount of memory to our pointer, and we verify the return
835        // result.
836        let ret = { unsafe { ioctl_with_mut_ref(self, KVM_GET_VCPU_EVENTS, &mut vcpu_evts) } };
837        if ret != 0 {
838            return errno_result();
839        }
840        let interrupts = VcpuEvents::from(&vcpu_evts);
841        let ret =
842            // SAFETY:
843            // Safe because we know that our file is a valid VM fd
844            unsafe { ioctl_with_val(&self.vm, KVM_CHECK_EXTENSION, KVM_CAP_NESTED_STATE as u64) };
845        if ret < 0 {
846            return errno_result();
847        }
848        // 0 == unsupported
849        let nested_state = if ret == 0 {
850            Vec::new()
851        } else {
852            let mut nested_state: Vec<u8> = vec![0; ret as usize];
853            let nested_state_ptr = nested_state.as_ptr() as *mut kvm_nested_state;
854            assert!(nested_state_ptr.is_aligned());
855            // SAFETY:
856            // Casting this vector to kvm_nested_state meets all the requirements mentioned at
857            // https://doc.rust-lang.org/std/ptr/index.html#pointer-to-reference-conversion
858            // The pointer is validated to be aligned, the value is non-null, can be dereferenced,
859            // the pointer points to kvm_nested_state, which holds zeroes and is valid.
860            // No other references to this point exist and no other operation happens. The memory
861            // is only accessed via the reference the lifetime of the reference
862            unsafe {
863                (*nested_state_ptr).size = ret as u32;
864            }
865            assert!(nested_state.as_ptr().is_aligned());
866            // SAFETY:
867            // Safe because we know out FD is a valid VCPU fd, and  we got the size
868            // of nested state from the KVM_CAP_NESTED_STATE call.
869            let ret = unsafe {
870                ioctl_with_mut_ptr(self, KVM_GET_NESTED_STATE, nested_state.as_mut_ptr())
871            };
872            if ret < 0 {
873                return errno_result();
874            }
875            nested_state
876        };
877        AnySnapshot::to_any(HypervisorState {
878            interrupts,
879            nested_state,
880        })
881        .map_err(|e| {
882            error!("failed to serialize hypervisor state: {:?}", e);
883            Error::new(EIO)
884        })
885    }
886
887    fn set_hypervisor_specific_state(&self, data: AnySnapshot) -> Result<()> {
888        let hypervisor_state = AnySnapshot::from_any::<HypervisorState>(data).map_err(|e| {
889            error!("failed to deserialize hypervisor_state: {:?}", e);
890            Error::new(EIO)
891        })?;
892        let vcpu_events = kvm_vcpu_events::from(&hypervisor_state.interrupts);
893        let ret = {
894            // SAFETY:
895            // Safe because we know that our file is a VCPU fd, we know the kernel will only read
896            // the correct amount of memory from our pointer, and we verify the return
897            // result.
898            unsafe { ioctl_with_ref(self, KVM_SET_VCPU_EVENTS, &vcpu_events) }
899        };
900        if ret != 0 {
901            return errno_result();
902        }
903        if hypervisor_state.nested_state.is_empty() {
904            return Ok(());
905        }
906        // SAFETY:
907        // Casting this vector to kvm_nested_state meets all the requirements mentioned at
908        // https://doc.rust-lang.org/std/ptr/index.html#pointer-to-reference-conversion
909        // The pointer is validated to be aligned, the value is non-null, can be dereferenced,
910        // the pointer points to Vec<u8>, which is initialized and a valid value.
911        // No other references to this point exist and no other operation happens. The memory
912        // is not modified by any operation. The pointer is dropped after validating that size is
913        // smaller than the vector length.
914        unsafe {
915            let vec_len = hypervisor_state.nested_state.len();
916            assert!(
917                (hypervisor_state.nested_state.as_ptr() as *const kvm_nested_state).is_aligned()
918            );
919            if (*(hypervisor_state.nested_state.as_ptr() as *const kvm_nested_state)).size
920                > vec_len as u32
921            {
922                error!("Invalued nested state data, size larger than vec allocated.");
923                return Err(Error::new(EINVAL));
924            }
925        }
926        // SAFETY:
927        // Safe because we know that our file is a VCPU fd, we know the kernel will only read
928        // the correct amount of memory from our pointer, and we verify the return
929        // result.
930        let ret = unsafe {
931            ioctl_with_ptr(
932                self,
933                KVM_SET_NESTED_STATE,
934                hypervisor_state.nested_state.as_ptr(),
935            )
936        };
937        if ret == 0 {
938            Ok(())
939        } else {
940            errno_result()
941        }
942    }
943
944    fn get_debugregs(&self) -> Result<DebugRegs> {
945        let mut regs: kvm_debugregs = Default::default();
946        // SAFETY:
947        // Safe because we know that our file is a VCPU fd, we know the kernel will only write the
948        // correct amount of memory to our pointer, and we verify the return result.
949        let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_DEBUGREGS, &mut regs) };
950        if ret == 0 {
951            Ok(DebugRegs::from(&regs))
952        } else {
953            errno_result()
954        }
955    }
956
957    fn set_debugregs(&self, dregs: &DebugRegs) -> Result<()> {
958        let dregs = kvm_debugregs::from(dregs);
959        let ret = {
960            // SAFETY:
961            // Here we trust the kernel not to read past the end of the kvm_debugregs struct.
962            unsafe { ioctl_with_ref(self, KVM_SET_DEBUGREGS, &dregs) }
963        };
964        if ret == 0 {
965            Ok(())
966        } else {
967            errno_result()
968        }
969    }
970
971    fn get_xcrs(&self) -> Result<BTreeMap<u32, u64>> {
972        let mut regs: kvm_xcrs = Default::default();
973        // SAFETY:
974        // Safe because we know that our file is a VCPU fd, we know the kernel will only write the
975        // correct amount of memory to our pointer, and we verify the return result.
976        let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_XCRS, &mut regs) };
977        if ret < 0 {
978            return errno_result();
979        }
980
981        Ok(regs
982            .xcrs
983            .iter()
984            .take(regs.nr_xcrs as usize)
985            .map(|kvm_xcr| (kvm_xcr.xcr, kvm_xcr.value))
986            .collect())
987    }
988
989    fn set_xcr(&self, xcr_index: u32, value: u64) -> Result<()> {
990        let mut kvm_xcr = kvm_xcrs {
991            nr_xcrs: 1,
992            ..Default::default()
993        };
994        kvm_xcr.xcrs[0].xcr = xcr_index;
995        kvm_xcr.xcrs[0].value = value;
996
997        let ret = {
998            // SAFETY:
999            // Here we trust the kernel not to read past the end of the kvm_xcrs struct.
1000            unsafe { ioctl_with_ref(self, KVM_SET_XCRS, &kvm_xcr) }
1001        };
1002        if ret == 0 {
1003            Ok(())
1004        } else {
1005            errno_result()
1006        }
1007    }
1008
1009    fn get_msr(&self, msr_index: u32) -> Result<u64> {
1010        let mut msrs = kvm_msrs::<[kvm_msr_entry; 1]>::new_zeroed();
1011        msrs.nmsrs = 1;
1012        msrs.entries[0].index = msr_index;
1013
1014        let ret = {
1015            // SAFETY:
1016            // Here we trust the kernel not to read or write past the end of the kvm_msrs struct.
1017            unsafe { ioctl_with_mut_ref(self, KVM_GET_MSRS, &mut msrs) }
1018        };
1019        if ret < 0 {
1020            return errno_result();
1021        }
1022
1023        // KVM_GET_MSRS returns the number of msr entries written.
1024        if ret != 1 {
1025            return Err(base::Error::new(libc::ENOENT));
1026        }
1027
1028        Ok(msrs.entries[0].data)
1029    }
1030
1031    fn get_all_msrs(&self) -> Result<BTreeMap<u32, u64>> {
1032        let msr_index_list = self.kvm.get_msr_index_list()?;
1033
1034        let mut kvm_msrs =
1035            kvm_msrs::<[kvm_msr_entry]>::new_box_zeroed_with_elems(msr_index_list.len()).unwrap();
1036        kvm_msrs.nmsrs = msr_index_list.len() as u32;
1037        kvm_msrs
1038            .entries
1039            .iter_mut()
1040            .zip(msr_index_list.iter())
1041            .for_each(|(msr_entry, msr_index)| msr_entry.index = *msr_index);
1042
1043        let ret = {
1044            // SAFETY:
1045            // Here we trust the kernel not to read or write past the end of the kvm_msrs struct.
1046            unsafe { ioctl_with_mut_ref(self, KVM_GET_MSRS, &mut *kvm_msrs) }
1047        };
1048        if ret < 0 {
1049            return errno_result();
1050        }
1051
1052        // KVM_GET_MSRS returns the number of msr entries written.
1053        let count = ret as usize;
1054        if count != msr_index_list.len() {
1055            error!(
1056                "failed to get all MSRs: requested {}, got {}",
1057                msr_index_list.len(),
1058                count,
1059            );
1060            return Err(base::Error::new(libc::EPERM));
1061        }
1062
1063        let msrs = BTreeMap::from_iter(
1064            kvm_msrs
1065                .entries
1066                .iter()
1067                .map(|kvm_msr| (kvm_msr.index, kvm_msr.data)),
1068        );
1069
1070        Ok(msrs)
1071    }
1072
1073    fn set_msr(&self, msr_index: u32, value: u64) -> Result<()> {
1074        let mut kvm_msrs = kvm_msrs::<[kvm_msr_entry; 1]>::new_zeroed();
1075        kvm_msrs.nmsrs = 1;
1076        kvm_msrs.entries[0].index = msr_index;
1077        kvm_msrs.entries[0].data = value;
1078
1079        let ret = {
1080            // SAFETY:
1081            // Here we trust the kernel not to read past the end of the kvm_msrs struct.
1082            unsafe { ioctl_with_ref(self, KVM_SET_MSRS, &kvm_msrs) }
1083        };
1084        if ret < 0 {
1085            return errno_result();
1086        }
1087
1088        // KVM_SET_MSRS returns the number of msr entries written.
1089        if ret != 1 {
1090            error!("failed to set MSR {:#x} to {:#x}", msr_index, value);
1091            return Err(base::Error::new(libc::EPERM));
1092        }
1093
1094        Ok(())
1095    }
1096
1097    fn set_cpuid(&self, cpuid: &CpuId) -> Result<()> {
1098        let cpuid = Box::<kvm_cpuid2<[kvm_cpuid_entry2]>>::from(cpuid);
1099        let ret = {
1100            // SAFETY:
1101            // Here we trust the kernel not to read past the end of the kvm_msrs struct.
1102            unsafe { ioctl_with_ref(self, KVM_SET_CPUID2, &*cpuid) }
1103        };
1104        if ret == 0 {
1105            Ok(())
1106        } else {
1107            errno_result()
1108        }
1109    }
1110
1111    fn set_guest_debug(&self, addrs: &[GuestAddress], enable_singlestep: bool) -> Result<()> {
1112        use kvm_sys::*;
1113        let mut dbg: kvm_guest_debug = Default::default();
1114
1115        if addrs.len() > 4 {
1116            error!(
1117                "Support 4 breakpoints at most but {} addresses are passed",
1118                addrs.len()
1119            );
1120            return Err(base::Error::new(libc::EINVAL));
1121        }
1122
1123        dbg.control = KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
1124        if enable_singlestep {
1125            dbg.control |= KVM_GUESTDBG_SINGLESTEP;
1126        }
1127
1128        // Set bits 9 and 10.
1129        // bit 9: GE (global exact breakpoint enable) flag.
1130        // bit 10: always 1.
1131        dbg.arch.debugreg[7] = 0x0600;
1132
1133        for (i, addr) in addrs.iter().enumerate() {
1134            dbg.arch.debugreg[i] = addr.0;
1135            // Set global breakpoint enable flag
1136            dbg.arch.debugreg[7] |= 2 << (i * 2);
1137        }
1138
1139        let ret = {
1140            // SAFETY:
1141            // Here we trust the kernel not to read past the end of the kvm_guest_debug struct.
1142            unsafe { ioctl_with_ref(self, KVM_SET_GUEST_DEBUG, &dbg) }
1143        };
1144        if ret == 0 {
1145            Ok(())
1146        } else {
1147            errno_result()
1148        }
1149    }
1150
1151    /// KVM does not support the VcpuExit::Cpuid exit type.
1152    fn handle_cpuid(&self, _entry: &CpuIdEntry) -> Result<()> {
1153        Err(Error::new(ENXIO))
1154    }
1155
1156    fn restore_timekeeping(&self, _host_tsc_reference_moment: u64, _tsc_offset: u64) -> Result<()> {
1157        // On KVM, the TSC MSR is restored as part of SET_MSRS, and no further action is required.
1158        Ok(())
1159    }
1160}
1161
1162impl KvmVcpu {
1163    /// X86 specific call to get the state of the "Local Advanced Programmable Interrupt
1164    /// Controller".
1165    ///
1166    /// See the documentation for KVM_GET_LAPIC.
1167    pub fn get_lapic(&self) -> Result<kvm_lapic_state> {
1168        let mut klapic: kvm_lapic_state = Default::default();
1169
1170        let ret = {
1171            // SAFETY:
1172            // The ioctl is unsafe unless you trust the kernel not to write past the end of the
1173            // local_apic struct.
1174            unsafe { ioctl_with_mut_ref(self, KVM_GET_LAPIC, &mut klapic) }
1175        };
1176        if ret < 0 {
1177            return errno_result();
1178        }
1179        Ok(klapic)
1180    }
1181
1182    /// X86 specific call to set the state of the "Local Advanced Programmable Interrupt
1183    /// Controller".
1184    ///
1185    /// See the documentation for KVM_SET_LAPIC.
1186    pub fn set_lapic(&self, klapic: &kvm_lapic_state) -> Result<()> {
1187        let ret = {
1188            // SAFETY:
1189            // The ioctl is safe because the kernel will only read from the klapic struct.
1190            unsafe { ioctl_with_ref(self, KVM_SET_LAPIC, klapic) }
1191        };
1192        if ret < 0 {
1193            return errno_result();
1194        }
1195        Ok(())
1196    }
1197
1198    /// X86 specific call to get the value of the APIC_BASE MSR.
1199    ///
1200    /// See the documentation for The kvm_run structure, and for KVM_GET_LAPIC.
1201    pub fn get_apic_base(&self) -> Result<u64> {
1202        self.get_msr(MSR_IA32_APICBASE)
1203    }
1204
1205    /// X86 specific call to set the value of the APIC_BASE MSR.
1206    ///
1207    /// See the documentation for The kvm_run structure, and for KVM_GET_LAPIC.
1208    pub fn set_apic_base(&self, apic_base: u64) -> Result<()> {
1209        self.set_msr(MSR_IA32_APICBASE, apic_base)
1210    }
1211
1212    /// Call to get pending interrupts acknowledged by the APIC but not yet injected into the CPU.
1213    ///
1214    /// See the documentation for KVM_GET_SREGS.
1215    pub fn get_interrupt_bitmap(&self) -> Result<[u64; 4usize]> {
1216        let mut regs: kvm_sregs = Default::default();
1217        // SAFETY:
1218        // Safe because we know that our file is a VCPU fd, we know the kernel will only write the
1219        // correct amount of memory to our pointer, and we verify the return result.
1220        let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_SREGS, &mut regs) };
1221        if ret >= 0 {
1222            Ok(regs.interrupt_bitmap)
1223        } else {
1224            errno_result()
1225        }
1226    }
1227
1228    /// Call to set pending interrupts acknowledged by the APIC but not yet injected into the CPU.
1229    ///
1230    /// See the documentation for KVM_GET_SREGS.
1231    pub fn set_interrupt_bitmap(&self, interrupt_bitmap: [u64; 4usize]) -> Result<()> {
1232        // Potentially racy code. Vcpu registers are set in a separate thread and this could result
1233        // in Sregs being modified from the Vcpu initialization thread and the Irq restoring
1234        // thread.
1235        let mut regs: kvm_sregs = Default::default();
1236        // SAFETY:
1237        // Safe because we know that our file is a VCPU fd, we know the kernel will only write the
1238        // correct amount of memory to our pointer, and we verify the return result.
1239        let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_SREGS, &mut regs) };
1240        if ret >= 0 {
1241            regs.interrupt_bitmap = interrupt_bitmap;
1242            // SAFETY:
1243            // Safe because we know that our file is a VCPU fd, we know the kernel will only read
1244            // the correct amount of memory from our pointer, and we verify the return
1245            // result.
1246            let ret = unsafe { ioctl_with_ref(self, KVM_SET_SREGS, &regs) };
1247            if ret >= 0 {
1248                Ok(())
1249            } else {
1250                errno_result()
1251            }
1252        } else {
1253            errno_result()
1254        }
1255    }
1256}
1257
1258impl<'a> From<&'a kvm_cpuid2<[kvm_cpuid_entry2]>> for CpuId {
1259    fn from(kvm_cpuid: &'a kvm_cpuid2<[kvm_cpuid_entry2]>) -> CpuId {
1260        let kvm_entries = &kvm_cpuid.entries[..kvm_cpuid.nent as usize];
1261        let mut cpu_id_entries = Vec::with_capacity(kvm_entries.len());
1262
1263        for entry in kvm_entries {
1264            let cpu_id_entry = CpuIdEntry {
1265                function: entry.function,
1266                index: entry.index,
1267                flags: entry.flags,
1268                cpuid: CpuidResult {
1269                    eax: entry.eax,
1270                    ebx: entry.ebx,
1271                    ecx: entry.ecx,
1272                    edx: entry.edx,
1273                },
1274            };
1275            cpu_id_entries.push(cpu_id_entry)
1276        }
1277        CpuId { cpu_id_entries }
1278    }
1279}
1280
1281impl From<&CpuId> for Box<kvm_cpuid2<[kvm_cpuid_entry2]>> {
1282    fn from(cpuid: &CpuId) -> Box<kvm_cpuid2<[kvm_cpuid_entry2]>> {
1283        let mut kvm =
1284            kvm_cpuid2::<[kvm_cpuid_entry2]>::new_box_zeroed_with_elems(cpuid.cpu_id_entries.len())
1285                .unwrap();
1286        kvm.nent = cpuid.cpu_id_entries.len().try_into().unwrap();
1287        for (i, &e) in cpuid.cpu_id_entries.iter().enumerate() {
1288            kvm.entries[i] = kvm_cpuid_entry2 {
1289                function: e.function,
1290                index: e.index,
1291                flags: e.flags,
1292                eax: e.cpuid.eax,
1293                ebx: e.cpuid.ebx,
1294                ecx: e.cpuid.ecx,
1295                edx: e.cpuid.edx,
1296                ..Default::default()
1297            };
1298        }
1299        kvm
1300    }
1301}
1302
1303impl From<&ClockState> for kvm_clock_data {
1304    fn from(state: &ClockState) -> Self {
1305        kvm_clock_data {
1306            clock: state.clock,
1307            ..Default::default()
1308        }
1309    }
1310}
1311
1312impl From<&kvm_clock_data> for ClockState {
1313    fn from(clock_data: &kvm_clock_data) -> Self {
1314        ClockState {
1315            clock: clock_data.clock,
1316        }
1317    }
1318}
1319
1320impl From<&kvm_pic_state> for PicState {
1321    fn from(item: &kvm_pic_state) -> Self {
1322        PicState {
1323            last_irr: item.last_irr,
1324            irr: item.irr,
1325            imr: item.imr,
1326            isr: item.isr,
1327            priority_add: item.priority_add,
1328            irq_base: item.irq_base,
1329            read_reg_select: item.read_reg_select != 0,
1330            poll: item.poll != 0,
1331            special_mask: item.special_mask != 0,
1332            init_state: item.init_state.into(),
1333            auto_eoi: item.auto_eoi != 0,
1334            rotate_on_auto_eoi: item.rotate_on_auto_eoi != 0,
1335            special_fully_nested_mode: item.special_fully_nested_mode != 0,
1336            use_4_byte_icw: item.init4 != 0,
1337            elcr: item.elcr,
1338            elcr_mask: item.elcr_mask,
1339        }
1340    }
1341}
1342
1343impl From<&PicState> for kvm_pic_state {
1344    fn from(item: &PicState) -> Self {
1345        kvm_pic_state {
1346            last_irr: item.last_irr,
1347            irr: item.irr,
1348            imr: item.imr,
1349            isr: item.isr,
1350            priority_add: item.priority_add,
1351            irq_base: item.irq_base,
1352            read_reg_select: item.read_reg_select as u8,
1353            poll: item.poll as u8,
1354            special_mask: item.special_mask as u8,
1355            init_state: item.init_state as u8,
1356            auto_eoi: item.auto_eoi as u8,
1357            rotate_on_auto_eoi: item.rotate_on_auto_eoi as u8,
1358            special_fully_nested_mode: item.special_fully_nested_mode as u8,
1359            init4: item.use_4_byte_icw as u8,
1360            elcr: item.elcr,
1361            elcr_mask: item.elcr_mask,
1362        }
1363    }
1364}
1365
1366impl From<&kvm_ioapic_state> for IoapicState {
1367    fn from(item: &kvm_ioapic_state) -> Self {
1368        let mut state = IoapicState {
1369            base_address: item.base_address,
1370            ioregsel: item.ioregsel as u8,
1371            ioapicid: item.id,
1372            current_interrupt_level_bitmap: item.irr,
1373            redirect_table: [IoapicRedirectionTableEntry::default(); NUM_IOAPIC_PINS],
1374        };
1375        for (in_state, out_state) in item.redirtbl.iter().zip(state.redirect_table.iter_mut()) {
1376            *out_state = in_state.into();
1377        }
1378        state
1379    }
1380}
1381
1382impl From<&IoapicRedirectionTableEntry> for kvm_ioapic_state__bindgen_ty_1 {
1383    fn from(item: &IoapicRedirectionTableEntry) -> Self {
1384        kvm_ioapic_state__bindgen_ty_1 {
1385            // IoapicRedirectionTableEntry layout matches the exact bit layout of a hardware
1386            // ioapic redirection table entry, so we can simply do a 64-bit copy
1387            bits: item.get(0, 64),
1388        }
1389    }
1390}
1391
1392impl From<&kvm_ioapic_state__bindgen_ty_1> for IoapicRedirectionTableEntry {
1393    fn from(item: &kvm_ioapic_state__bindgen_ty_1) -> Self {
1394        let mut entry = IoapicRedirectionTableEntry::default();
1395        // SAFETY:
1396        // Safe because the 64-bit layout of the IoapicRedirectionTableEntry matches the kvm_sys
1397        // table entry layout
1398        entry.set(0, 64, unsafe { item.bits });
1399        entry
1400    }
1401}
1402
1403impl From<&IoapicState> for kvm_ioapic_state {
1404    fn from(item: &IoapicState) -> Self {
1405        let mut state = kvm_ioapic_state {
1406            base_address: item.base_address,
1407            ioregsel: item.ioregsel as u32,
1408            id: item.ioapicid,
1409            irr: item.current_interrupt_level_bitmap,
1410            ..Default::default()
1411        };
1412        for (in_state, out_state) in item.redirect_table.iter().zip(state.redirtbl.iter_mut()) {
1413            *out_state = in_state.into();
1414        }
1415        state
1416    }
1417}
1418
1419impl From<&LapicState> for kvm_lapic_state {
1420    fn from(item: &LapicState) -> Self {
1421        let mut state = kvm_lapic_state::default();
1422        // There are 64 lapic registers
1423        for (reg, value) in item.regs.iter().enumerate() {
1424            // Each lapic register is 16 bytes, but only the first 4 are used
1425            let reg_offset = 16 * reg;
1426            let regs_slice = &mut state.regs[reg_offset..reg_offset + 4];
1427
1428            // to_le_bytes() produces an array of u8, not i8(c_char), so we can't directly use
1429            // copy_from_slice().
1430            for (i, v) in value.to_le_bytes().iter().enumerate() {
1431                regs_slice[i] = *v as i8;
1432            }
1433        }
1434        state
1435    }
1436}
1437
1438impl From<&kvm_lapic_state> for LapicState {
1439    fn from(item: &kvm_lapic_state) -> Self {
1440        let mut state = LapicState { regs: [0; 64] };
1441        // There are 64 lapic registers
1442        for reg in 0..64 {
1443            // Each lapic register is 16 bytes, but only the first 4 are used
1444            let reg_offset = 16 * reg;
1445
1446            // from_le_bytes() only works on arrays of u8, not i8(c_char).
1447            let reg_slice = &item.regs[reg_offset..reg_offset + 4];
1448            let mut bytes = [0u8; 4];
1449            for i in 0..4 {
1450                bytes[i] = reg_slice[i] as u8;
1451            }
1452            state.regs[reg] = u32::from_le_bytes(bytes);
1453        }
1454        state
1455    }
1456}
1457
1458impl From<&PitState> for kvm_pit_state2 {
1459    fn from(item: &PitState) -> Self {
1460        kvm_pit_state2 {
1461            channels: [
1462                kvm_pit_channel_state::from(&item.channels[0]),
1463                kvm_pit_channel_state::from(&item.channels[1]),
1464                kvm_pit_channel_state::from(&item.channels[2]),
1465            ],
1466            flags: item.flags,
1467            ..Default::default()
1468        }
1469    }
1470}
1471
1472impl From<&kvm_pit_state2> for PitState {
1473    fn from(item: &kvm_pit_state2) -> Self {
1474        PitState {
1475            channels: [
1476                PitChannelState::from(&item.channels[0]),
1477                PitChannelState::from(&item.channels[1]),
1478                PitChannelState::from(&item.channels[2]),
1479            ],
1480            flags: item.flags,
1481        }
1482    }
1483}
1484
1485impl From<&PitChannelState> for kvm_pit_channel_state {
1486    fn from(item: &PitChannelState) -> Self {
1487        kvm_pit_channel_state {
1488            count: item.count,
1489            latched_count: item.latched_count,
1490            count_latched: item.count_latched as u8,
1491            status_latched: item.status_latched as u8,
1492            status: item.status,
1493            read_state: item.read_state as u8,
1494            write_state: item.write_state as u8,
1495            // kvm's write_latch only stores the low byte of the reload value
1496            write_latch: item.reload_value as u8,
1497            rw_mode: item.rw_mode as u8,
1498            mode: item.mode,
1499            bcd: item.bcd as u8,
1500            gate: item.gate as u8,
1501            count_load_time: item.count_load_time as i64,
1502        }
1503    }
1504}
1505
1506impl From<&kvm_pit_channel_state> for PitChannelState {
1507    fn from(item: &kvm_pit_channel_state) -> Self {
1508        PitChannelState {
1509            count: item.count,
1510            latched_count: item.latched_count,
1511            count_latched: item.count_latched.into(),
1512            status_latched: item.status_latched != 0,
1513            status: item.status,
1514            read_state: item.read_state.into(),
1515            write_state: item.write_state.into(),
1516            // kvm's write_latch only stores the low byte of the reload value
1517            reload_value: item.write_latch as u16,
1518            rw_mode: item.rw_mode.into(),
1519            mode: item.mode,
1520            bcd: item.bcd != 0,
1521            gate: item.gate != 0,
1522            count_load_time: item.count_load_time as u64,
1523        }
1524    }
1525}
1526
1527// This function translates an IrqSrouceChip to the kvm u32 equivalent. It has a different
1528// implementation between x86_64 and aarch64 because the irqchip KVM constants are not defined on
1529// all architectures.
1530pub(super) fn chip_to_kvm_chip(chip: IrqSourceChip) -> u32 {
1531    match chip {
1532        IrqSourceChip::PicPrimary => KVM_IRQCHIP_PIC_MASTER,
1533        IrqSourceChip::PicSecondary => KVM_IRQCHIP_PIC_SLAVE,
1534        IrqSourceChip::Ioapic => KVM_IRQCHIP_IOAPIC,
1535        _ => {
1536            error!("Invalid IrqChipSource for X86 {:?}", chip);
1537            0
1538        }
1539    }
1540}
1541
1542impl From<&kvm_regs> for Regs {
1543    fn from(r: &kvm_regs) -> Self {
1544        Regs {
1545            rax: r.rax,
1546            rbx: r.rbx,
1547            rcx: r.rcx,
1548            rdx: r.rdx,
1549            rsi: r.rsi,
1550            rdi: r.rdi,
1551            rsp: r.rsp,
1552            rbp: r.rbp,
1553            r8: r.r8,
1554            r9: r.r9,
1555            r10: r.r10,
1556            r11: r.r11,
1557            r12: r.r12,
1558            r13: r.r13,
1559            r14: r.r14,
1560            r15: r.r15,
1561            rip: r.rip,
1562            rflags: r.rflags,
1563        }
1564    }
1565}
1566
1567impl From<&Regs> for kvm_regs {
1568    fn from(r: &Regs) -> Self {
1569        kvm_regs {
1570            rax: r.rax,
1571            rbx: r.rbx,
1572            rcx: r.rcx,
1573            rdx: r.rdx,
1574            rsi: r.rsi,
1575            rdi: r.rdi,
1576            rsp: r.rsp,
1577            rbp: r.rbp,
1578            r8: r.r8,
1579            r9: r.r9,
1580            r10: r.r10,
1581            r11: r.r11,
1582            r12: r.r12,
1583            r13: r.r13,
1584            r14: r.r14,
1585            r15: r.r15,
1586            rip: r.rip,
1587            rflags: r.rflags,
1588        }
1589    }
1590}
1591
1592impl From<&VcpuEvents> for kvm_vcpu_events {
1593    fn from(ve: &VcpuEvents) -> Self {
1594        let mut kvm_ve: kvm_vcpu_events = Default::default();
1595
1596        kvm_ve.exception.injected = ve.exception.injected as u8;
1597        kvm_ve.exception.nr = ve.exception.nr;
1598        kvm_ve.exception.has_error_code = ve.exception.has_error_code as u8;
1599        if let Some(pending) = ve.exception.pending {
1600            kvm_ve.exception.pending = pending as u8;
1601            if ve.exception_payload.is_some() {
1602                kvm_ve.exception_has_payload = true as u8;
1603            }
1604            kvm_ve.exception_payload = ve.exception_payload.unwrap_or(0);
1605            kvm_ve.flags |= KVM_VCPUEVENT_VALID_PAYLOAD;
1606        }
1607        kvm_ve.exception.error_code = ve.exception.error_code;
1608
1609        kvm_ve.interrupt.injected = ve.interrupt.injected as u8;
1610        kvm_ve.interrupt.nr = ve.interrupt.nr;
1611        kvm_ve.interrupt.soft = ve.interrupt.soft as u8;
1612        if let Some(shadow) = ve.interrupt.shadow {
1613            kvm_ve.interrupt.shadow = shadow;
1614            kvm_ve.flags |= KVM_VCPUEVENT_VALID_SHADOW;
1615        }
1616
1617        kvm_ve.nmi.injected = ve.nmi.injected as u8;
1618        if let Some(pending) = ve.nmi.pending {
1619            kvm_ve.nmi.pending = pending as u8;
1620            kvm_ve.flags |= KVM_VCPUEVENT_VALID_NMI_PENDING;
1621        }
1622        kvm_ve.nmi.masked = ve.nmi.masked as u8;
1623
1624        if let Some(sipi_vector) = ve.sipi_vector {
1625            kvm_ve.sipi_vector = sipi_vector;
1626            kvm_ve.flags |= KVM_VCPUEVENT_VALID_SIPI_VECTOR;
1627        }
1628
1629        if let Some(smm) = ve.smi.smm {
1630            kvm_ve.smi.smm = smm as u8;
1631            kvm_ve.flags |= KVM_VCPUEVENT_VALID_SMM;
1632        }
1633        kvm_ve.smi.pending = ve.smi.pending as u8;
1634        kvm_ve.smi.smm_inside_nmi = ve.smi.smm_inside_nmi as u8;
1635        kvm_ve.smi.latched_init = ve.smi.latched_init;
1636
1637        if let Some(pending) = ve.triple_fault.pending {
1638            kvm_ve.triple_fault.pending = pending as u8;
1639            kvm_ve.flags |= KVM_VCPUEVENT_VALID_TRIPLE_FAULT;
1640        }
1641        kvm_ve
1642    }
1643}
1644
1645impl From<&kvm_vcpu_events> for VcpuEvents {
1646    fn from(ve: &kvm_vcpu_events) -> Self {
1647        let exception = VcpuExceptionState {
1648            injected: ve.exception.injected != 0,
1649            nr: ve.exception.nr,
1650            has_error_code: ve.exception.has_error_code != 0,
1651            pending: if ve.flags & KVM_VCPUEVENT_VALID_PAYLOAD != 0 {
1652                Some(ve.exception.pending != 0)
1653            } else {
1654                None
1655            },
1656            error_code: ve.exception.error_code,
1657        };
1658
1659        let interrupt = VcpuInterruptState {
1660            injected: ve.interrupt.injected != 0,
1661            nr: ve.interrupt.nr,
1662            soft: ve.interrupt.soft != 0,
1663            shadow: if ve.flags & KVM_VCPUEVENT_VALID_SHADOW != 0 {
1664                Some(ve.interrupt.shadow)
1665            } else {
1666                None
1667            },
1668        };
1669
1670        let nmi = VcpuNmiState {
1671            injected: ve.nmi.injected != 0,
1672            pending: if ve.flags & KVM_VCPUEVENT_VALID_NMI_PENDING != 0 {
1673                Some(ve.nmi.pending != 0)
1674            } else {
1675                None
1676            },
1677            masked: ve.nmi.masked != 0,
1678        };
1679
1680        let sipi_vector = if ve.flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR != 0 {
1681            Some(ve.sipi_vector)
1682        } else {
1683            None
1684        };
1685
1686        let smi = VcpuSmiState {
1687            smm: if ve.flags & KVM_VCPUEVENT_VALID_SMM != 0 {
1688                Some(ve.smi.smm != 0)
1689            } else {
1690                None
1691            },
1692            pending: ve.smi.pending != 0,
1693            smm_inside_nmi: ve.smi.smm_inside_nmi != 0,
1694            latched_init: ve.smi.latched_init,
1695        };
1696
1697        let triple_fault = VcpuTripleFaultState {
1698            pending: if ve.flags & KVM_VCPUEVENT_VALID_TRIPLE_FAULT != 0 {
1699                Some(ve.triple_fault.pending != 0)
1700            } else {
1701                None
1702            },
1703        };
1704
1705        let exception_payload = if ve.flags & KVM_VCPUEVENT_VALID_PAYLOAD != 0 {
1706            Some(ve.exception_payload)
1707        } else {
1708            None
1709        };
1710
1711        VcpuEvents {
1712            exception,
1713            interrupt,
1714            nmi,
1715            sipi_vector,
1716            smi,
1717            triple_fault,
1718            exception_payload,
1719        }
1720    }
1721}
1722
1723impl From<&kvm_segment> for Segment {
1724    fn from(s: &kvm_segment) -> Self {
1725        Segment {
1726            base: s.base,
1727            limit_bytes: s.limit,
1728            selector: s.selector,
1729            type_: s.type_,
1730            present: s.present,
1731            dpl: s.dpl,
1732            db: s.db,
1733            s: s.s,
1734            l: s.l,
1735            g: s.g,
1736            avl: s.avl,
1737        }
1738    }
1739}
1740
1741impl From<&Segment> for kvm_segment {
1742    fn from(s: &Segment) -> Self {
1743        kvm_segment {
1744            base: s.base,
1745            limit: s.limit_bytes,
1746            selector: s.selector,
1747            type_: s.type_,
1748            present: s.present,
1749            dpl: s.dpl,
1750            db: s.db,
1751            s: s.s,
1752            l: s.l,
1753            g: s.g,
1754            avl: s.avl,
1755            unusable: match s.present {
1756                0 => 1,
1757                _ => 0,
1758            },
1759            ..Default::default()
1760        }
1761    }
1762}
1763
1764impl From<&kvm_dtable> for DescriptorTable {
1765    fn from(dt: &kvm_dtable) -> Self {
1766        DescriptorTable {
1767            base: dt.base,
1768            limit: dt.limit,
1769        }
1770    }
1771}
1772
1773impl From<&DescriptorTable> for kvm_dtable {
1774    fn from(dt: &DescriptorTable) -> Self {
1775        kvm_dtable {
1776            base: dt.base,
1777            limit: dt.limit,
1778            ..Default::default()
1779        }
1780    }
1781}
1782
1783impl From<&kvm_sregs> for Sregs {
1784    fn from(r: &kvm_sregs) -> Self {
1785        Sregs {
1786            cs: Segment::from(&r.cs),
1787            ds: Segment::from(&r.ds),
1788            es: Segment::from(&r.es),
1789            fs: Segment::from(&r.fs),
1790            gs: Segment::from(&r.gs),
1791            ss: Segment::from(&r.ss),
1792            tr: Segment::from(&r.tr),
1793            ldt: Segment::from(&r.ldt),
1794            gdt: DescriptorTable::from(&r.gdt),
1795            idt: DescriptorTable::from(&r.idt),
1796            cr0: r.cr0,
1797            cr2: r.cr2,
1798            cr3: r.cr3,
1799            cr4: r.cr4,
1800            cr8: r.cr8,
1801            efer: r.efer,
1802        }
1803    }
1804}
1805
1806impl From<&kvm_fpu> for Fpu {
1807    fn from(r: &kvm_fpu) -> Self {
1808        Fpu {
1809            fpr: FpuReg::from_16byte_arrays(&r.fpr),
1810            fcw: r.fcw,
1811            fsw: r.fsw,
1812            ftwx: r.ftwx,
1813            last_opcode: r.last_opcode,
1814            last_ip: r.last_ip,
1815            last_dp: r.last_dp,
1816            xmm: r.xmm,
1817            mxcsr: r.mxcsr,
1818        }
1819    }
1820}
1821
1822impl From<&Fpu> for kvm_fpu {
1823    fn from(r: &Fpu) -> Self {
1824        kvm_fpu {
1825            fpr: FpuReg::to_16byte_arrays(&r.fpr),
1826            fcw: r.fcw,
1827            fsw: r.fsw,
1828            ftwx: r.ftwx,
1829            last_opcode: r.last_opcode,
1830            last_ip: r.last_ip,
1831            last_dp: r.last_dp,
1832            xmm: r.xmm,
1833            mxcsr: r.mxcsr,
1834            ..Default::default()
1835        }
1836    }
1837}
1838
1839impl From<&kvm_debugregs> for DebugRegs {
1840    fn from(r: &kvm_debugregs) -> Self {
1841        DebugRegs {
1842            db: r.db,
1843            dr6: r.dr6,
1844            dr7: r.dr7,
1845        }
1846    }
1847}
1848
1849impl From<&DebugRegs> for kvm_debugregs {
1850    fn from(r: &DebugRegs) -> Self {
1851        kvm_debugregs {
1852            db: r.db,
1853            dr6: r.dr6,
1854            dr7: r.dr7,
1855            ..Default::default()
1856        }
1857    }
1858}
1859
1860#[cfg(test)]
1861mod tests {
1862    use super::*;
1863
1864    #[test]
1865    fn vcpu_event_to_from() {
1866        // All data is random.
1867        let mut kvm_ve: kvm_vcpu_events = Default::default();
1868        kvm_ve.exception.injected = 1;
1869        kvm_ve.exception.nr = 65;
1870        kvm_ve.exception.has_error_code = 1;
1871        kvm_ve.exception.error_code = 110;
1872        kvm_ve.exception.pending = 1;
1873
1874        kvm_ve.interrupt.injected = 1;
1875        kvm_ve.interrupt.nr = 100;
1876        kvm_ve.interrupt.soft = 1;
1877        kvm_ve.interrupt.shadow = 114;
1878
1879        kvm_ve.nmi.injected = 1;
1880        kvm_ve.nmi.pending = 1;
1881        kvm_ve.nmi.masked = 0;
1882
1883        kvm_ve.sipi_vector = 105;
1884
1885        kvm_ve.smi.smm = 1;
1886        kvm_ve.smi.pending = 1;
1887        kvm_ve.smi.smm_inside_nmi = 1;
1888        kvm_ve.smi.latched_init = 100;
1889
1890        kvm_ve.triple_fault.pending = 0;
1891
1892        kvm_ve.exception_payload = 33;
1893        kvm_ve.exception_has_payload = 1;
1894
1895        kvm_ve.flags = 0
1896            | KVM_VCPUEVENT_VALID_PAYLOAD
1897            | KVM_VCPUEVENT_VALID_SMM
1898            | KVM_VCPUEVENT_VALID_NMI_PENDING
1899            | KVM_VCPUEVENT_VALID_SIPI_VECTOR
1900            | KVM_VCPUEVENT_VALID_SHADOW;
1901
1902        let ve: VcpuEvents = VcpuEvents::from(&kvm_ve);
1903        assert_eq!(ve.exception.injected, true);
1904        assert_eq!(ve.exception.nr, 65);
1905        assert_eq!(ve.exception.has_error_code, true);
1906        assert_eq!(ve.exception.error_code, 110);
1907        assert_eq!(ve.exception.pending.unwrap(), true);
1908
1909        assert_eq!(ve.interrupt.injected, true);
1910        assert_eq!(ve.interrupt.nr, 100);
1911        assert_eq!(ve.interrupt.soft, true);
1912        assert_eq!(ve.interrupt.shadow.unwrap(), 114);
1913
1914        assert_eq!(ve.nmi.injected, true);
1915        assert_eq!(ve.nmi.pending.unwrap(), true);
1916        assert_eq!(ve.nmi.masked, false);
1917
1918        assert_eq!(ve.sipi_vector.unwrap(), 105);
1919
1920        assert_eq!(ve.smi.smm.unwrap(), true);
1921        assert_eq!(ve.smi.pending, true);
1922        assert_eq!(ve.smi.smm_inside_nmi, true);
1923        assert_eq!(ve.smi.latched_init, 100);
1924
1925        assert_eq!(ve.triple_fault.pending, None);
1926
1927        assert_eq!(ve.exception_payload.unwrap(), 33);
1928
1929        let kvm_ve_restored: kvm_vcpu_events = kvm_vcpu_events::from(&ve);
1930        assert_eq!(kvm_ve_restored.exception.injected, 1);
1931        assert_eq!(kvm_ve_restored.exception.nr, 65);
1932        assert_eq!(kvm_ve_restored.exception.has_error_code, 1);
1933        assert_eq!(kvm_ve_restored.exception.error_code, 110);
1934        assert_eq!(kvm_ve_restored.exception.pending, 1);
1935
1936        assert_eq!(kvm_ve_restored.interrupt.injected, 1);
1937        assert_eq!(kvm_ve_restored.interrupt.nr, 100);
1938        assert_eq!(kvm_ve_restored.interrupt.soft, 1);
1939        assert_eq!(kvm_ve_restored.interrupt.shadow, 114);
1940
1941        assert_eq!(kvm_ve_restored.nmi.injected, 1);
1942        assert_eq!(kvm_ve_restored.nmi.pending, 1);
1943        assert_eq!(kvm_ve_restored.nmi.masked, 0);
1944
1945        assert_eq!(kvm_ve_restored.sipi_vector, 105);
1946
1947        assert_eq!(kvm_ve_restored.smi.smm, 1);
1948        assert_eq!(kvm_ve_restored.smi.pending, 1);
1949        assert_eq!(kvm_ve_restored.smi.smm_inside_nmi, 1);
1950        assert_eq!(kvm_ve_restored.smi.latched_init, 100);
1951
1952        assert_eq!(kvm_ve_restored.triple_fault.pending, 0);
1953
1954        assert_eq!(kvm_ve_restored.exception_payload, 33);
1955        assert_eq!(kvm_ve_restored.exception_has_payload, 1);
1956    }
1957}