hypervisor/kvm/
mod.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(target_arch = "aarch64")]
6mod aarch64;
7#[cfg(target_arch = "riscv64")]
8mod riscv64;
9#[cfg(target_arch = "x86_64")]
10mod x86_64;
11
12mod cap;
13
14use std::cmp::Reverse;
15use std::collections::BTreeMap;
16use std::collections::BinaryHeap;
17use std::convert::TryFrom;
18use std::ffi::CString;
19use std::fs::File;
20use std::os::raw::c_ulong;
21use std::os::raw::c_void;
22use std::os::unix::prelude::OsStrExt;
23use std::path::Path;
24use std::sync::Arc;
25use std::sync::OnceLock;
26
27#[cfg(target_arch = "aarch64")]
28pub use aarch64::*;
29use base::errno_result;
30use base::error;
31use base::ioctl;
32use base::ioctl_with_mut_ref;
33use base::ioctl_with_ref;
34use base::ioctl_with_val;
35use base::pagesize;
36use base::AsRawDescriptor;
37use base::Error;
38use base::Event;
39use base::FromRawDescriptor;
40use base::MappedRegion;
41use base::MemoryMapping;
42use base::MemoryMappingBuilder;
43use base::MmapError;
44use base::Protection;
45use base::RawDescriptor;
46use base::Result;
47use base::SafeDescriptor;
48pub use cap::KvmCap;
49use cfg_if::cfg_if;
50use kvm_sys::*;
51use libc::open64;
52use libc::EFAULT;
53use libc::EINVAL;
54use libc::EIO;
55use libc::ENOENT;
56use libc::ENOSPC;
57use libc::ENOSYS;
58#[cfg(not(target_arch = "aarch64"))]
59use libc::ENOTSUP;
60use libc::EOVERFLOW;
61use libc::O_CLOEXEC;
62use libc::O_RDWR;
63#[cfg(target_arch = "riscv64")]
64use riscv64::*;
65use sync::Mutex;
66use vm_memory::GuestAddress;
67use vm_memory::GuestMemory;
68#[cfg(target_arch = "x86_64")]
69pub use x86_64::*;
70use zerocopy::FromZeros;
71
72use crate::BalloonEvent;
73use crate::ClockState;
74use crate::Config;
75use crate::Datamatch;
76use crate::DeviceKind;
77use crate::HypercallAbi;
78use crate::Hypervisor;
79use crate::HypervisorCap;
80use crate::HypervisorKind;
81use crate::IoEventAddress;
82use crate::IoOperation;
83use crate::IoParams;
84use crate::IrqRoute;
85use crate::IrqSource;
86use crate::MPState;
87use crate::MemCacheType;
88use crate::MemSlot;
89use crate::Vcpu;
90use crate::VcpuExit;
91use crate::VcpuSignalHandle;
92use crate::VcpuSignalHandleInner;
93use crate::Vm;
94use crate::VmCap;
95
96// Wrapper around KVM_SET_USER_MEMORY_REGION ioctl, which creates, modifies, or deletes a mapping
97// from guest physical to host user pages.
98//
99// SAFETY:
100// Safe when the guest regions are guaranteed not to overlap.
101unsafe fn set_user_memory_region(
102    kvm: &KvmVm,
103    slot: MemSlot,
104    read_only: bool,
105    log_dirty_pages: bool,
106    cache: MemCacheType,
107    guest_addr: u64,
108    memory_size: u64,
109    userspace_addr: *mut u8,
110) -> Result<()> {
111    let mut use_2_variant = false;
112    let mut flags = 0;
113    if read_only {
114        flags |= KVM_MEM_READONLY;
115    }
116    if log_dirty_pages {
117        flags |= KVM_MEM_LOG_DIRTY_PAGES;
118    }
119    if kvm.caps.user_noncoherent_dma && cache == MemCacheType::CacheNonCoherent {
120        flags |= KVM_MEM_NON_COHERENT_DMA;
121        use_2_variant = kvm.caps.user_memory_region2;
122    }
123
124    let untagged_userspace_addr = untagged_addr(userspace_addr as usize);
125    let ret = if use_2_variant {
126        let region2 = kvm_userspace_memory_region2 {
127            slot,
128            flags,
129            guest_phys_addr: guest_addr,
130            memory_size,
131            userspace_addr: untagged_userspace_addr as u64,
132            guest_memfd_offset: 0,
133            guest_memfd: 0,
134            ..Default::default()
135        };
136        ioctl_with_ref(&kvm.vm, KVM_SET_USER_MEMORY_REGION2, &region2)
137    } else {
138        let region = kvm_userspace_memory_region {
139            slot,
140            flags,
141            guest_phys_addr: guest_addr,
142            memory_size,
143            userspace_addr: (untagged_userspace_addr as u64),
144        };
145        ioctl_with_ref(&kvm.vm, KVM_SET_USER_MEMORY_REGION, &region)
146    };
147
148    if ret == 0 {
149        Ok(())
150    } else {
151        errno_result()
152    }
153}
154
155// https://github.com/torvalds/linux/blob/master/Documentation/virt/kvm/api.rst
156// On architectures that support a form of address tagging, userspace_addr must be an untagged
157// address.
158#[inline]
159fn untagged_addr(addr: usize) -> usize {
160    let tag_bits_mask: u64 = if cfg!(target_arch = "aarch64") {
161        0xFF00000000000000
162    } else {
163        0
164    };
165    addr & !tag_bits_mask as usize
166}
167
168/// Helper function to determine the size in bytes of a dirty log bitmap for the given memory region
169/// size.
170///
171/// # Arguments
172///
173/// * `size` - Number of bytes in the memory region being queried.
174pub fn dirty_log_bitmap_size(size: usize) -> usize {
175    let page_size = pagesize();
176    size.div_ceil(page_size).div_ceil(8)
177}
178
179pub struct Kvm {
180    kvm: SafeDescriptor,
181    vcpu_mmap_size: usize,
182}
183
184impl Kvm {
185    pub fn new_with_path(device_path: &Path) -> Result<Kvm> {
186        let c_path = CString::new(device_path.as_os_str().as_bytes()).unwrap();
187        // SAFETY:
188        // Open calls are safe because we give a nul-terminated string and verify the result.
189        let ret = unsafe { open64(c_path.as_ptr(), O_RDWR | O_CLOEXEC) };
190        if ret < 0 {
191            return errno_result();
192        }
193        // SAFETY:
194        // Safe because we verify that ret is valid and we own the fd.
195        let kvm = unsafe { SafeDescriptor::from_raw_descriptor(ret) };
196
197        // SAFETY:
198        // Safe because we know that the descriptor is valid and we verify the return result.
199        let version = unsafe { ioctl(&kvm, KVM_GET_API_VERSION) };
200        if version < 0 {
201            return errno_result();
202        }
203
204        // Per the kernel KVM API documentation: "Applications should refuse to run if
205        // KVM_GET_API_VERSION returns a value other than 12."
206        if version as u32 != KVM_API_VERSION {
207            error!(
208                "KVM_GET_API_VERSION: expected {}, got {}",
209                KVM_API_VERSION, version,
210            );
211            return Err(Error::new(ENOSYS));
212        }
213
214        // SAFETY:
215        // Safe because we know that our file is a KVM fd and we verify the return result.
216        let res = unsafe { ioctl(&kvm, KVM_GET_VCPU_MMAP_SIZE) };
217        if res <= 0 {
218            return errno_result();
219        }
220        let vcpu_mmap_size = res as usize;
221
222        Ok(Kvm {
223            kvm,
224            vcpu_mmap_size,
225        })
226    }
227
228    /// Opens `/dev/kvm` and returns a Kvm object on success.
229    pub fn new() -> Result<Kvm> {
230        Kvm::new_with_path(Path::new("/dev/kvm"))
231    }
232}
233
234impl AsRawDescriptor for Kvm {
235    fn as_raw_descriptor(&self) -> RawDescriptor {
236        self.kvm.as_raw_descriptor()
237    }
238}
239
240impl Hypervisor for Kvm {
241    fn try_clone(&self) -> Result<Self> {
242        Ok(Kvm {
243            kvm: self.kvm.try_clone()?,
244            vcpu_mmap_size: self.vcpu_mmap_size,
245        })
246    }
247
248    fn check_capability(&self, cap: HypervisorCap) -> bool {
249        if let Ok(kvm_cap) = KvmCap::try_from(cap) {
250            // SAFETY:
251            // this ioctl is safe because we know this kvm descriptor is valid,
252            // and we are copying over the kvm capability (u32) as a c_ulong value.
253            unsafe { ioctl_with_val(self, KVM_CHECK_EXTENSION, kvm_cap as c_ulong) == 1 }
254        } else {
255            // this capability cannot be converted on this platform, so return false
256            false
257        }
258    }
259}
260
261/// Storage for constant KVM driver caps
262#[derive(Clone, Default)]
263struct KvmVmCaps {
264    kvmclock_ctrl: bool,
265    user_noncoherent_dma: bool,
266    user_memory_region2: bool,
267    // This capability can't be detected until after the irqchip is configured, so we lazy
268    // initialize it when the first MSI is configured.
269    msi_devid: Arc<OnceLock<bool>>,
270}
271
272/// A wrapper around creating and using a KVM VM.
273pub struct KvmVm {
274    kvm: Kvm,
275    vm: SafeDescriptor,
276    guest_mem: GuestMemory,
277    mem_regions: Mutex<BTreeMap<MemSlot, Box<dyn MappedRegion>>>,
278    /// A min heap of MemSlot numbers that were used and then removed and can now be re-used
279    mem_slot_gaps: Mutex<BinaryHeap<Reverse<MemSlot>>>,
280    caps: KvmVmCaps,
281    force_disable_readonly_mem: bool,
282}
283
284impl KvmVm {
285    /// Constructs a new `KvmVm` using the given `Kvm` instance.
286    pub fn new(kvm: &Kvm, guest_mem: GuestMemory, cfg: Config) -> Result<KvmVm> {
287        // SAFETY:
288        // Safe because we know kvm is a real kvm fd as this module is the only one that can make
289        // Kvm objects.
290        let ret = unsafe {
291            ioctl_with_val(
292                kvm,
293                KVM_CREATE_VM,
294                kvm.get_vm_type(cfg.protection_type)? as c_ulong,
295            )
296        };
297        if ret < 0 {
298            return errno_result();
299        }
300        // SAFETY:
301        // Safe because we verify that ret is valid and we own the fd.
302        let vm_descriptor = unsafe { SafeDescriptor::from_raw_descriptor(ret) };
303        let mut vm = KvmVm {
304            kvm: kvm.try_clone()?,
305            vm: vm_descriptor,
306            guest_mem,
307            mem_regions: Default::default(),
308            mem_slot_gaps: Default::default(),
309            caps: Default::default(),
310            force_disable_readonly_mem: cfg.force_disable_readonly_mem,
311        };
312        vm.caps.kvmclock_ctrl = vm.check_raw_capability(KvmCap::KvmclockCtrl);
313        vm.caps.user_noncoherent_dma = vm.check_raw_capability(KvmCap::MemNoncoherentDma);
314        vm.caps.user_memory_region2 = vm.check_raw_capability(KvmCap::UserMemory2);
315
316        vm.init_arch(&cfg)?;
317
318        for region in vm.guest_mem.regions() {
319            // SAFETY:
320            // Safe because the guest regions are guaranteed not to overlap.
321            unsafe {
322                set_user_memory_region(
323                    &vm,
324                    region.index as MemSlot,
325                    false,
326                    false,
327                    MemCacheType::CacheCoherent,
328                    region.guest_addr.offset(),
329                    region.size as u64,
330                    region.host_addr as *mut u8,
331                )
332            }?;
333        }
334
335        Ok(vm)
336    }
337
338    pub fn create_kvm_vcpu(&self, id: usize) -> Result<KvmVcpu> {
339        // SAFETY:
340        // Safe because we know that our file is a VM fd and we verify the return result.
341        let fd = unsafe { ioctl_with_val(self, KVM_CREATE_VCPU, c_ulong::try_from(id).unwrap()) };
342        if fd < 0 {
343            return errno_result();
344        }
345
346        // SAFETY:
347        // Wrap the vcpu now in case the following ? returns early. This is safe because we verified
348        // the value of the fd and we own the fd.
349        let vcpu = unsafe { File::from_raw_descriptor(fd) };
350
351        // The VCPU mapping is held by an `Arc` inside `KvmVcpu`, and it can also be cloned by
352        // `signal_handle()` for use in `KvmVcpuSignalHandle`. The mapping will not be destroyed
353        // until all references are dropped, so it is safe to reference `kvm_run` fields via the
354        // `as_ptr()` function during either type's lifetime.
355        let run_mmap = MemoryMappingBuilder::new(self.kvm.vcpu_mmap_size)
356            .from_file(&vcpu)
357            .build()
358            .map_err(|_| Error::new(ENOSPC))?;
359
360        Ok(KvmVcpu {
361            #[cfg(target_arch = "x86_64")]
362            kvm: self.kvm.try_clone()?,
363            #[cfg(not(target_arch = "riscv64"))]
364            vm: self.vm.try_clone()?,
365            vcpu,
366            id,
367            cap_kvmclock_ctrl: self.caps.kvmclock_ctrl,
368            run_mmap: Arc::new(run_mmap),
369        })
370    }
371
372    /// Creates an in kernel interrupt controller.
373    ///
374    /// See the documentation on the KVM_CREATE_IRQCHIP ioctl.
375    pub fn create_irq_chip(&self) -> Result<()> {
376        // SAFETY:
377        // Safe because we know that our file is a VM fd and we verify the return result.
378        let ret = unsafe { ioctl(self, KVM_CREATE_IRQCHIP) };
379        if ret == 0 {
380            Ok(())
381        } else {
382            errno_result()
383        }
384    }
385
386    /// Sets the level on the given irq to 1 if `active` is true, and 0 otherwise.
387    pub fn set_irq_line(&self, irq: u32, active: bool) -> Result<()> {
388        let mut irq_level = kvm_irq_level::default();
389        irq_level.__bindgen_anon_1.irq = irq;
390        irq_level.level = active.into();
391
392        // SAFETY:
393        // Safe because we know that our file is a VM fd, we know the kernel will only read the
394        // correct amount of memory from our pointer, and we verify the return result.
395        let ret = unsafe { ioctl_with_ref(self, KVM_IRQ_LINE, &irq_level) };
396        if ret == 0 {
397            Ok(())
398        } else {
399            errno_result()
400        }
401    }
402
403    /// Registers an event that will, when signalled, trigger the `gsi` irq, and `resample_evt`
404    /// ( when not None ) will be triggered when the irqchip is resampled.
405    pub fn register_irqfd(
406        &self,
407        gsi: u32,
408        evt: &Event,
409        resample_evt: Option<&Event>,
410    ) -> Result<()> {
411        let mut irqfd = kvm_irqfd {
412            fd: evt.as_raw_descriptor() as u32,
413            gsi,
414            ..Default::default()
415        };
416
417        if let Some(r_evt) = resample_evt {
418            irqfd.flags = KVM_IRQFD_FLAG_RESAMPLE;
419            irqfd.resamplefd = r_evt.as_raw_descriptor() as u32;
420        }
421
422        // SAFETY:
423        // Safe because we know that our file is a VM fd, we know the kernel will only read the
424        // correct amount of memory from our pointer, and we verify the return result.
425        let ret = unsafe { ioctl_with_ref(self, KVM_IRQFD, &irqfd) };
426        if ret == 0 {
427            Ok(())
428        } else {
429            errno_result()
430        }
431    }
432
433    /// Unregisters an event that was previously registered with
434    /// `register_irqfd`.
435    ///
436    /// The `evt` and `gsi` pair must be the same as the ones passed into
437    /// `register_irqfd`.
438    pub fn unregister_irqfd(&self, gsi: u32, evt: &Event) -> Result<()> {
439        let irqfd = kvm_irqfd {
440            fd: evt.as_raw_descriptor() as u32,
441            gsi,
442            flags: KVM_IRQFD_FLAG_DEASSIGN,
443            ..Default::default()
444        };
445        // SAFETY:
446        // Safe because we know that our file is a VM fd, we know the kernel will only read the
447        // correct amount of memory from our pointer, and we verify the return result.
448        let ret = unsafe { ioctl_with_ref(self, KVM_IRQFD, &irqfd) };
449        if ret == 0 {
450            Ok(())
451        } else {
452            errno_result()
453        }
454    }
455
456    /// Sets the GSI routing table, replacing any table set with previous calls to
457    /// `set_gsi_routing`.
458    pub fn set_gsi_routing(&self, routes: &[IrqRoute]) -> Result<()> {
459        let mut irq_routing =
460            kvm_irq_routing::<[kvm_irq_routing_entry]>::new_box_zeroed_with_elems(routes.len())
461                .unwrap();
462        irq_routing.nr = routes.len() as u32;
463
464        let cap_msi_devid = *self
465            .caps
466            .msi_devid
467            .get_or_init(|| self.check_raw_capability(KvmCap::MsiDevid));
468
469        for (route, irq_route) in routes.iter().zip(irq_routing.entries.iter_mut()) {
470            *irq_route = to_kvm_irq_routing_entry(route, cap_msi_devid);
471        }
472
473        // TODO(b/315998194): Add safety comment
474        #[allow(clippy::undocumented_unsafe_blocks)]
475        let ret = unsafe { ioctl_with_ref(self, KVM_SET_GSI_ROUTING, &*irq_routing) };
476        if ret == 0 {
477            Ok(())
478        } else {
479            errno_result()
480        }
481    }
482
483    fn ioeventfd(
484        &self,
485        evt: Event,
486        addr: IoEventAddress,
487        datamatch: Datamatch,
488        deassign: bool,
489    ) -> Result<()> {
490        let (do_datamatch, datamatch_value, datamatch_len) = match datamatch {
491            Datamatch::AnyLength => (false, 0, 0),
492            Datamatch::U8(v) => match v {
493                Some(u) => (true, u as u64, 1),
494                None => (false, 0, 1),
495            },
496            Datamatch::U16(v) => match v {
497                Some(u) => (true, u as u64, 2),
498                None => (false, 0, 2),
499            },
500            Datamatch::U32(v) => match v {
501                Some(u) => (true, u as u64, 4),
502                None => (false, 0, 4),
503            },
504            Datamatch::U64(v) => match v {
505                Some(u) => (true, u, 8),
506                None => (false, 0, 8),
507            },
508        };
509        let mut flags = 0;
510        if deassign {
511            flags |= 1 << kvm_ioeventfd_flag_nr_deassign;
512        }
513        if do_datamatch {
514            flags |= 1 << kvm_ioeventfd_flag_nr_datamatch
515        }
516        if let IoEventAddress::Pio(_) = addr {
517            flags |= 1 << kvm_ioeventfd_flag_nr_pio;
518        }
519        let ioeventfd = kvm_ioeventfd {
520            datamatch: datamatch_value,
521            len: datamatch_len,
522            addr: match addr {
523                IoEventAddress::Pio(p) => p,
524                IoEventAddress::Mmio(m) => m,
525            },
526            fd: evt.as_raw_descriptor(),
527            flags,
528            ..Default::default()
529        };
530        // SAFETY:
531        // Safe because we know that our file is a VM fd, we know the kernel will only read the
532        // correct amount of memory from our pointer, and we verify the return result.
533        let ret = unsafe { ioctl_with_ref(self, KVM_IOEVENTFD, &ioeventfd) };
534        if ret == 0 {
535            Ok(())
536        } else {
537            errno_result()
538        }
539    }
540
541    /// Checks whether a particular KVM-specific capability is available for this VM.
542    pub fn check_raw_capability(&self, capability: KvmCap) -> bool {
543        // SAFETY:
544        // Safe because we know that our file is a KVM fd, and if the cap is invalid KVM assumes
545        // it's an unavailable extension and returns 0.
546        let ret = unsafe { ioctl_with_val(self, KVM_CHECK_EXTENSION, capability as c_ulong) };
547        match capability {
548            #[cfg(target_arch = "x86_64")]
549            KvmCap::BusLockDetect => {
550                if ret > 0 {
551                    ret as u32 & KVM_BUS_LOCK_DETECTION_EXIT == KVM_BUS_LOCK_DETECTION_EXIT
552                } else {
553                    false
554                }
555            }
556            _ => ret == 1,
557        }
558    }
559
560    // Currently only used on aarch64, but works on any architecture.
561    #[allow(dead_code)]
562    /// Enables a KVM-specific capability for this VM, with the given arguments.
563    ///
564    /// # Safety
565    /// This function is marked as unsafe because `args` may be interpreted as pointers for some
566    /// capabilities. The caller must ensure that any pointers passed in the `args` array are
567    /// allocated as the kernel expects, and that mutable pointers are owned.
568    unsafe fn enable_raw_capability(
569        &self,
570        capability: KvmCap,
571        flags: u32,
572        args: &[u64; 4],
573    ) -> Result<()> {
574        let kvm_cap = kvm_enable_cap {
575            cap: capability as u32,
576            args: *args,
577            flags,
578            ..Default::default()
579        };
580        // SAFETY:
581        // Safe because we allocated the struct and we know the kernel will read exactly the size of
582        // the struct, and because we assume the caller has allocated the args appropriately.
583        let ret = ioctl_with_ref(self, KVM_ENABLE_CAP, &kvm_cap);
584        if ret == 0 {
585            Ok(())
586        } else {
587            errno_result()
588        }
589    }
590
591    fn handle_inflate(&self, guest_address: GuestAddress, size: u64) -> Result<()> {
592        match self.guest_mem.remove_range(guest_address, size) {
593            Ok(_) => Ok(()),
594            Err(vm_memory::Error::MemoryAccess(_, MmapError::SystemCallFailed(e))) => Err(e),
595            Err(_) => Err(Error::new(EIO)),
596        }
597    }
598
599    fn handle_deflate(&self, _guest_address: GuestAddress, _size: u64) -> Result<()> {
600        // No-op, when the guest attempts to access the pages again, Linux/KVM will provide them.
601        Ok(())
602    }
603}
604
605impl Vm for KvmVm {
606    fn try_clone_descriptor(&self) -> Result<SafeDescriptor> {
607        self.vm.try_clone()
608    }
609
610    fn hypervisor_kind(&self) -> HypervisorKind {
611        HypervisorKind::Kvm
612    }
613
614    fn check_capability(&self, c: VmCap) -> bool {
615        if let Some(val) = self.check_capability_arch(c) {
616            return val;
617        }
618        match c {
619            #[cfg(target_arch = "aarch64")]
620            VmCap::ArmPmuV3 => self.check_raw_capability(KvmCap::ArmPmuV3),
621            VmCap::DirtyLog => true,
622            VmCap::PvClock => false,
623            VmCap::Protected => self.check_raw_capability(KvmCap::ArmProtectedVm),
624            VmCap::EarlyInitCpuid => false,
625            #[cfg(target_arch = "x86_64")]
626            VmCap::BusLockDetect => self.check_raw_capability(KvmCap::BusLockDetect),
627            VmCap::ReadOnlyMemoryRegion => {
628                !self.force_disable_readonly_mem && self.check_raw_capability(KvmCap::ReadonlyMem)
629            }
630            VmCap::MemNoncoherentDma => {
631                cfg!(feature = "noncoherent-dma")
632                    && self.check_raw_capability(KvmCap::MemNoncoherentDma)
633            }
634            #[cfg(target_arch = "aarch64")]
635            VmCap::Sve => self.check_raw_capability(KvmCap::Sve),
636            #[cfg(target_arch = "aarch64")]
637            VmCap::NestedVirt => self.check_raw_capability(KvmCap::El2),
638        }
639    }
640
641    fn enable_capability(&self, c: VmCap, _flags: u32) -> Result<bool> {
642        match c {
643            #[cfg(target_arch = "x86_64")]
644            VmCap::BusLockDetect => {
645                let args = [KVM_BUS_LOCK_DETECTION_EXIT as u64, 0, 0, 0];
646                Ok(
647                    // TODO(b/315998194): Add safety comment
648                    #[allow(clippy::undocumented_unsafe_blocks)]
649                    unsafe {
650                        self.enable_raw_capability(KvmCap::BusLockDetect, _flags, &args) == Ok(())
651                    },
652                )
653            }
654            _ => Ok(false),
655        }
656    }
657
658    fn get_guest_phys_addr_bits(&self) -> u8 {
659        self.kvm.get_guest_phys_addr_bits()
660    }
661
662    fn get_memory(&self) -> &GuestMemory {
663        &self.guest_mem
664    }
665
666    fn add_memory_region(
667        &self,
668        guest_addr: GuestAddress,
669        mem: Box<dyn MappedRegion>,
670        read_only: bool,
671        log_dirty_pages: bool,
672        cache: MemCacheType,
673    ) -> Result<MemSlot> {
674        let pgsz = pagesize() as u64;
675        // KVM require to set the user memory region with page size aligned size. Safe to extend
676        // the mem.size() to be page size aligned because the mmap will round up the size to be
677        // page size aligned if it is not.
678        let size = (mem.size() as u64).next_multiple_of(pgsz);
679        let end_addr = guest_addr
680            .checked_add(size)
681            .ok_or_else(|| Error::new(EOVERFLOW))?;
682        if self.guest_mem.range_overlap(guest_addr, end_addr) {
683            return Err(Error::new(ENOSPC));
684        }
685        let mut regions = self.mem_regions.lock();
686        let mut gaps = self.mem_slot_gaps.lock();
687        let slot = match gaps.pop() {
688            Some(gap) => gap.0,
689            None => (regions.len() + self.guest_mem.num_regions() as usize) as MemSlot,
690        };
691
692        // SAFETY:
693        // Safe because we check that the given guest address is valid and has no overlaps. We also
694        // know that the pointer and size are correct because the MemoryMapping interface ensures
695        // this. We take ownership of the memory mapping so that it won't be unmapped until the slot
696        // is removed.
697        let res = unsafe {
698            set_user_memory_region(
699                self,
700                slot,
701                read_only,
702                log_dirty_pages,
703                cache,
704                guest_addr.offset(),
705                size,
706                mem.as_ptr(),
707            )
708        };
709
710        if let Err(e) = res {
711            gaps.push(Reverse(slot));
712            return Err(e);
713        }
714        regions.insert(slot, mem);
715        Ok(slot)
716    }
717
718    fn enable_hypercalls(&self, nr: u64, count: usize) -> Result<()> {
719        cfg_if! {
720            if #[cfg(target_arch = "aarch64")] {
721                let base = u32::try_from(nr).unwrap();
722                let nr_functions = u32::try_from(count).unwrap();
723                self.enable_smccc_forwarding(base, nr_functions)
724            } else {
725                let _ = nr;
726                let _ = count;
727                Err(Error::new(ENOTSUP))
728            }
729        }
730    }
731
732    fn msync_memory_region(&self, slot: MemSlot, offset: usize, size: usize) -> Result<()> {
733        let mut regions = self.mem_regions.lock();
734        let mem = regions.get_mut(&slot).ok_or_else(|| Error::new(ENOENT))?;
735
736        mem.msync(offset, size).map_err(|err| match err {
737            MmapError::InvalidAddress => Error::new(EFAULT),
738            MmapError::NotPageAligned => Error::new(EINVAL),
739            MmapError::SystemCallFailed(e) => e,
740            _ => Error::new(EIO),
741        })
742    }
743
744    fn madvise_pageout_memory_region(
745        &self,
746        slot: MemSlot,
747        offset: usize,
748        size: usize,
749    ) -> Result<()> {
750        let mut regions = self.mem_regions.lock();
751        let mem = regions.get_mut(&slot).ok_or_else(|| Error::new(ENOENT))?;
752
753        mem.madvise(offset, size, libc::MADV_PAGEOUT)
754            .map_err(|err| match err {
755                MmapError::InvalidAddress => Error::new(EFAULT),
756                MmapError::NotPageAligned => Error::new(EINVAL),
757                MmapError::SystemCallFailed(e) => e,
758                _ => Error::new(EIO),
759            })
760    }
761
762    fn madvise_remove_memory_region(
763        &self,
764        slot: MemSlot,
765        offset: usize,
766        size: usize,
767    ) -> Result<()> {
768        let mut regions = self.mem_regions.lock();
769        let mem = regions.get_mut(&slot).ok_or_else(|| Error::new(ENOENT))?;
770
771        mem.madvise(offset, size, libc::MADV_REMOVE)
772            .map_err(|err| match err {
773                MmapError::InvalidAddress => Error::new(EFAULT),
774                MmapError::NotPageAligned => Error::new(EINVAL),
775                MmapError::SystemCallFailed(e) => e,
776                _ => Error::new(EIO),
777            })
778    }
779
780    fn remove_memory_region(&self, slot: MemSlot) -> Result<Box<dyn MappedRegion>> {
781        let mut regions = self.mem_regions.lock();
782        if !regions.contains_key(&slot) {
783            return Err(Error::new(ENOENT));
784        }
785        // SAFETY:
786        // Safe because the slot is checked against the list of memory slots.
787        unsafe {
788            set_user_memory_region(
789                self,
790                slot,
791                false,
792                false,
793                MemCacheType::CacheCoherent,
794                0,
795                0,
796                std::ptr::null_mut(),
797            )?;
798        }
799        self.mem_slot_gaps.lock().push(Reverse(slot));
800        // This remove will always succeed because of the contains_key check above.
801        Ok(regions.remove(&slot).unwrap())
802    }
803
804    fn create_device(&self, kind: DeviceKind) -> Result<SafeDescriptor> {
805        let mut device = if let Some(dev) = self.get_device_params_arch(kind) {
806            dev
807        } else {
808            match kind {
809                DeviceKind::Vfio => kvm_create_device {
810                    type_: kvm_device_type_KVM_DEV_TYPE_VFIO,
811                    fd: 0,
812                    flags: 0,
813                },
814
815                // ARM and risc-v have additional DeviceKinds, so it needs the catch-all pattern
816                #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
817                _ => return Err(Error::new(libc::ENXIO)),
818            }
819        };
820
821        // SAFETY:
822        // Safe because we know that our file is a VM fd, we know the kernel will only write correct
823        // amount of memory to our pointer, and we verify the return result.
824        let ret = unsafe { base::ioctl_with_mut_ref(self, KVM_CREATE_DEVICE, &mut device) };
825        if ret == 0 {
826            Ok(
827                // SAFETY:
828                // Safe because we verify that ret is valid and we own the fd.
829                unsafe { SafeDescriptor::from_raw_descriptor(device.fd as i32) },
830            )
831        } else {
832            errno_result()
833        }
834    }
835
836    fn get_dirty_log(&self, slot: MemSlot, dirty_log: &mut [u8]) -> Result<()> {
837        let regions = self.mem_regions.lock();
838        let mmap = regions.get(&slot).ok_or_else(|| Error::new(ENOENT))?;
839        // Ensures that there are as many bytes in dirty_log as there are pages in the mmap.
840        if dirty_log_bitmap_size(mmap.size()) > dirty_log.len() {
841            return Err(Error::new(EINVAL));
842        }
843
844        let mut dirty_log_kvm = kvm_dirty_log {
845            slot,
846            ..Default::default()
847        };
848        dirty_log_kvm.__bindgen_anon_1.dirty_bitmap = dirty_log.as_ptr() as *mut c_void;
849        // SAFETY:
850        // Safe because the `dirty_bitmap` pointer assigned above is guaranteed to be valid (because
851        // it's from a slice) and we checked that it will be large enough to hold the entire log.
852        let ret = unsafe { ioctl_with_ref(self, KVM_GET_DIRTY_LOG, &dirty_log_kvm) };
853        if ret == 0 {
854            Ok(())
855        } else {
856            errno_result()
857        }
858    }
859
860    fn register_ioevent(
861        &self,
862        evt: Event,
863        addr: IoEventAddress,
864        datamatch: Datamatch,
865    ) -> Result<()> {
866        self.ioeventfd(evt, addr, datamatch, false)
867    }
868
869    fn unregister_ioevent(
870        &self,
871        evt: Event,
872        addr: IoEventAddress,
873        datamatch: Datamatch,
874    ) -> Result<()> {
875        self.ioeventfd(evt, addr, datamatch, true)
876    }
877
878    fn handle_io_events(&self, _addr: IoEventAddress, _data: &[u8]) -> Result<()> {
879        // KVM delivers IO events in-kernel with ioeventfds, so this is a no-op
880        Ok(())
881    }
882
883    fn get_pvclock(&self) -> Result<ClockState> {
884        self.get_pvclock_arch()
885    }
886
887    fn set_pvclock(&self, state: &ClockState) -> Result<()> {
888        self.set_pvclock_arch(state)
889    }
890
891    fn add_fd_mapping(
892        &self,
893        slot: u32,
894        offset: usize,
895        size: usize,
896        fd: &dyn AsRawDescriptor,
897        fd_offset: u64,
898        prot: Protection,
899    ) -> Result<()> {
900        let mut regions = self.mem_regions.lock();
901        let region = regions.get_mut(&slot).ok_or_else(|| Error::new(EINVAL))?;
902
903        match region.add_fd_mapping(offset, size, fd, fd_offset, prot) {
904            Ok(()) => Ok(()),
905            Err(MmapError::SystemCallFailed(e)) => Err(e),
906            Err(_) => Err(Error::new(EIO)),
907        }
908    }
909
910    fn remove_mapping(&self, slot: u32, offset: usize, size: usize) -> Result<()> {
911        let mut regions = self.mem_regions.lock();
912        let region = regions.get_mut(&slot).ok_or_else(|| Error::new(EINVAL))?;
913
914        match region.remove_mapping(offset, size) {
915            Ok(()) => Ok(()),
916            Err(MmapError::SystemCallFailed(e)) => Err(e),
917            Err(_) => Err(Error::new(EIO)),
918        }
919    }
920
921    fn handle_balloon_event(&self, event: BalloonEvent) -> Result<()> {
922        match event {
923            BalloonEvent::Inflate(m) => self.handle_inflate(m.guest_address, m.size),
924            BalloonEvent::Deflate(m) => self.handle_deflate(m.guest_address, m.size),
925            BalloonEvent::BalloonTargetReached(_) => Ok(()),
926        }
927    }
928}
929
930impl AsRawDescriptor for KvmVm {
931    fn as_raw_descriptor(&self) -> RawDescriptor {
932        self.vm.as_raw_descriptor()
933    }
934}
935
936struct KvmVcpuSignalHandle {
937    run_mmap: Arc<MemoryMapping>,
938}
939
940impl VcpuSignalHandleInner for KvmVcpuSignalHandle {
941    fn signal_immediate_exit(&self) {
942        // SAFETY: we ensure `run_mmap` is a valid mapping of `kvm_run` at creation time, and the
943        // `Arc` ensures the mapping still exists while we hold a reference to it.
944        unsafe {
945            let run = self.run_mmap.as_ptr() as *mut kvm_run;
946            (*run).immediate_exit = 1;
947        }
948    }
949}
950
951/// A wrapper around using a KVM Vcpu.
952pub struct KvmVcpu {
953    #[cfg(target_arch = "x86_64")]
954    kvm: Kvm,
955    #[cfg(not(target_arch = "riscv64"))]
956    vm: SafeDescriptor,
957    vcpu: File,
958    id: usize,
959    cap_kvmclock_ctrl: bool,
960    run_mmap: Arc<MemoryMapping>,
961}
962
963impl Vcpu for KvmVcpu {
964    fn id(&self) -> usize {
965        self.id
966    }
967
968    #[allow(clippy::cast_ptr_alignment)]
969    fn set_immediate_exit(&self, exit: bool) {
970        // SAFETY:
971        // Safe because we know we mapped enough memory to hold the kvm_run struct because the
972        // kernel told us how large it was. The pointer is page aligned so casting to a different
973        // type is well defined, hence the clippy allow attribute.
974        let run = unsafe { &mut *(self.run_mmap.as_ptr() as *mut kvm_run) };
975        run.immediate_exit = exit.into();
976    }
977
978    fn signal_handle(&self) -> VcpuSignalHandle {
979        VcpuSignalHandle {
980            inner: Box::new(KvmVcpuSignalHandle {
981                run_mmap: self.run_mmap.clone(),
982            }),
983        }
984    }
985
986    fn on_suspend(&self) -> Result<()> {
987        // On KVM implementations that use a paravirtualized clock (e.g. x86), a flag must be set to
988        // indicate to the guest kernel that a vCPU was suspended. The guest kernel will use this
989        // flag to prevent the soft lockup detection from triggering when this vCPU resumes, which
990        // could happen days later in realtime.
991        if self.cap_kvmclock_ctrl {
992            // SAFETY:
993            // The ioctl is safe because it does not read or write memory in this process.
994            if unsafe { ioctl(self, KVM_KVMCLOCK_CTRL) } != 0 {
995                // Even if the host kernel supports the capability, it may not be configured by
996                // the guest - for example, when the guest kernel offlines a CPU.
997                if Error::last().errno() != libc::EINVAL {
998                    return errno_result();
999                }
1000            }
1001        }
1002
1003        Ok(())
1004    }
1005
1006    unsafe fn enable_raw_capability(&self, cap: u32, args: &[u64; 4]) -> Result<()> {
1007        let kvm_cap = kvm_enable_cap {
1008            cap,
1009            args: *args,
1010            ..Default::default()
1011        };
1012        // SAFETY:
1013        // Safe because we allocated the struct and we know the kernel will read exactly the size of
1014        // the struct, and because we assume the caller has allocated the args appropriately.
1015        let ret = ioctl_with_ref(self, KVM_ENABLE_CAP, &kvm_cap);
1016        if ret == 0 {
1017            Ok(())
1018        } else {
1019            errno_result()
1020        }
1021    }
1022
1023    #[allow(clippy::cast_ptr_alignment)]
1024    // The pointer is page aligned so casting to a different type is well defined, hence the clippy
1025    // allow attribute.
1026    fn run(&self) -> Result<VcpuExit> {
1027        // SAFETY:
1028        // Safe because we know that our file is a VCPU fd and we verify the return result.
1029        let ret = unsafe { ioctl(self, KVM_RUN) };
1030        if ret != 0 {
1031            return errno_result();
1032        }
1033
1034        // SAFETY:
1035        // Safe because we know we mapped enough memory to hold the kvm_run struct because the
1036        // kernel told us how large it was.
1037        let run = unsafe { &mut *(self.run_mmap.as_ptr() as *mut kvm_run) };
1038
1039        // Check for architecture-specific VM exit reasons first in case the architecture wants to
1040        // override the default handling.
1041        if let Some(vcpu_exit) = self.handle_vm_exit_arch(run) {
1042            return Ok(vcpu_exit);
1043        }
1044
1045        match run.exit_reason {
1046            KVM_EXIT_MMIO => Ok(VcpuExit::Mmio),
1047            KVM_EXIT_EXCEPTION => Ok(VcpuExit::Exception),
1048            KVM_EXIT_HYPERCALL => Ok(VcpuExit::Hypercall),
1049            KVM_EXIT_DEBUG => Ok(VcpuExit::Debug),
1050            KVM_EXIT_IRQ_WINDOW_OPEN => Ok(VcpuExit::IrqWindowOpen),
1051            KVM_EXIT_SHUTDOWN => Ok(VcpuExit::Shutdown(Ok(()))),
1052            KVM_EXIT_FAIL_ENTRY => {
1053                // SAFETY:
1054                // Safe because the exit_reason (which comes from the kernel) told us which
1055                // union field to use.
1056                let hardware_entry_failure_reason = unsafe {
1057                    run.__bindgen_anon_1
1058                        .fail_entry
1059                        .hardware_entry_failure_reason
1060                };
1061                Ok(VcpuExit::FailEntry {
1062                    hardware_entry_failure_reason,
1063                })
1064            }
1065            KVM_EXIT_INTR => Ok(VcpuExit::Intr),
1066            KVM_EXIT_INTERNAL_ERROR => Ok(VcpuExit::InternalError),
1067            KVM_EXIT_SYSTEM_EVENT => {
1068                // SAFETY:
1069                // Safe because we know the exit reason told us this union
1070                // field is valid
1071                let event_type = unsafe { run.__bindgen_anon_1.system_event.type_ };
1072                let event_flags =
1073                    // SAFETY:
1074                    // Safe because we know the exit reason told us this union
1075                    // field is valid
1076                    unsafe { run.__bindgen_anon_1.system_event.__bindgen_anon_1.flags };
1077                match event_type {
1078                    KVM_SYSTEM_EVENT_SHUTDOWN => Ok(VcpuExit::SystemEventShutdown),
1079                    KVM_SYSTEM_EVENT_RESET => self.system_event_reset(event_flags),
1080                    KVM_SYSTEM_EVENT_CRASH => Ok(VcpuExit::SystemEventCrash),
1081                    _ => {
1082                        error!(
1083                            "Unknown KVM system event {} with flags {}",
1084                            event_type, event_flags
1085                        );
1086                        Err(Error::new(EINVAL))
1087                    }
1088                }
1089            }
1090            r => panic!("unknown kvm exit reason: {r}"),
1091        }
1092    }
1093
1094    fn handle_mmio(&self, handle_fn: &mut dyn FnMut(IoParams) -> Result<()>) -> Result<()> {
1095        // SAFETY:
1096        // Safe because we know we mapped enough memory to hold the kvm_run struct because the
1097        // kernel told us how large it was.
1098        let run = unsafe { &mut *(self.run_mmap.as_ptr() as *mut kvm_run) };
1099        // Verify that the handler is called in the right context.
1100        assert!(run.exit_reason == KVM_EXIT_MMIO);
1101        // SAFETY:
1102        // Safe because the exit_reason (which comes from the kernel) told us which
1103        // union field to use.
1104        let mmio = unsafe { &mut run.__bindgen_anon_1.mmio };
1105        let address = mmio.phys_addr;
1106        let data = &mut mmio.data[..mmio.len as usize];
1107        if mmio.is_write != 0 {
1108            handle_fn(IoParams {
1109                address,
1110                operation: IoOperation::Write(data),
1111            })
1112        } else {
1113            handle_fn(IoParams {
1114                address,
1115                operation: IoOperation::Read(data),
1116            })
1117        }
1118    }
1119
1120    fn handle_io(&self, handle_fn: &mut dyn FnMut(IoParams)) -> Result<()> {
1121        // SAFETY:
1122        // Safe because we know we mapped enough memory to hold the kvm_run struct because the
1123        // kernel told us how large it was.
1124        let run = unsafe { &mut *(self.run_mmap.as_ptr() as *mut kvm_run) };
1125        // Verify that the handler is called in the right context.
1126        assert!(run.exit_reason == KVM_EXIT_IO);
1127        // SAFETY:
1128        // Safe because the exit_reason (which comes from the kernel) told us which
1129        // union field to use.
1130        let io = unsafe { run.__bindgen_anon_1.io };
1131        let address = u64::from(io.port);
1132        let size = usize::from(io.size);
1133        let count = io.count as usize;
1134        let data_len = count * size;
1135        let data_offset = io.data_offset as usize;
1136        assert!(data_offset + data_len <= self.run_mmap.size());
1137
1138        // SAFETY:
1139        // The data_offset is defined by the kernel to be some number of bytes into the kvm_run
1140        // structure, which we have fully mmap'd.
1141        let buffer: &mut [u8] = unsafe {
1142            std::slice::from_raw_parts_mut(
1143                (run as *mut kvm_run as *mut u8).add(data_offset),
1144                data_len,
1145            )
1146        };
1147        let data_chunks = buffer.chunks_mut(size);
1148
1149        if io.direction == KVM_EXIT_IO_IN as u8 {
1150            for data in data_chunks {
1151                handle_fn(IoParams {
1152                    address,
1153                    operation: IoOperation::Read(data),
1154                });
1155            }
1156        } else {
1157            debug_assert_eq!(io.direction, KVM_EXIT_IO_OUT as u8);
1158            for data in data_chunks {
1159                handle_fn(IoParams {
1160                    address,
1161                    operation: IoOperation::Write(data),
1162                });
1163            }
1164        }
1165
1166        Ok(())
1167    }
1168
1169    fn handle_hypercall(
1170        &self,
1171        handle_fn: &mut dyn FnMut(&mut HypercallAbi) -> anyhow::Result<()>,
1172    ) -> anyhow::Result<()> {
1173        cfg_if! {
1174            if #[cfg(target_arch = "aarch64")] {
1175                // Assume that all handled HVC/SMC calls follow the SMCCC.
1176                self.handle_smccc_call(handle_fn)
1177            } else {
1178                let _ = handle_fn;
1179                unimplemented!("KvmVcpu::handle_hypercall() not supported");
1180            }
1181        }
1182    }
1183}
1184
1185impl KvmVcpu {
1186    /// Gets the vcpu's current "multiprocessing state".
1187    ///
1188    /// See the documentation for KVM_GET_MP_STATE. This call can only succeed after
1189    /// a call to `Vm::create_irq_chip`.
1190    ///
1191    /// Note that KVM defines the call for both x86 and s390 but we do not expect anyone
1192    /// to run crosvm on s390.
1193    pub fn get_mp_state(&self) -> Result<kvm_mp_state> {
1194        // SAFETY: trivially safe
1195        let mut state: kvm_mp_state = unsafe { std::mem::zeroed() };
1196        let ret = {
1197            // SAFETY:
1198            // Safe because we know that our file is a VCPU fd, we know the kernel will only write
1199            // the correct amount of memory to our pointer, and we verify the return
1200            // result.
1201            unsafe { ioctl_with_mut_ref(self, KVM_GET_MP_STATE, &mut state) }
1202        };
1203        if ret < 0 {
1204            return errno_result();
1205        }
1206        Ok(state)
1207    }
1208
1209    /// Sets the vcpu's current "multiprocessing state".
1210    ///
1211    /// See the documentation for KVM_SET_MP_STATE. This call can only succeed after
1212    /// a call to `Vm::create_irq_chip`.
1213    ///
1214    /// Note that KVM defines the call for both x86 and s390 but we do not expect anyone
1215    /// to run crosvm on s390.
1216    pub fn set_mp_state(&self, state: &kvm_mp_state) -> Result<()> {
1217        let ret = {
1218            // SAFETY:
1219            // The ioctl is safe because the kernel will only read from the kvm_mp_state struct.
1220            unsafe { ioctl_with_ref(self, KVM_SET_MP_STATE, state) }
1221        };
1222        if ret < 0 {
1223            return errno_result();
1224        }
1225        Ok(())
1226    }
1227}
1228
1229impl AsRawDescriptor for KvmVcpu {
1230    fn as_raw_descriptor(&self) -> RawDescriptor {
1231        self.vcpu.as_raw_descriptor()
1232    }
1233}
1234
1235impl TryFrom<HypervisorCap> for KvmCap {
1236    type Error = Error;
1237
1238    fn try_from(cap: HypervisorCap) -> Result<KvmCap> {
1239        match cap {
1240            HypervisorCap::ImmediateExit => Ok(KvmCap::ImmediateExit),
1241            HypervisorCap::UserMemory => Ok(KvmCap::UserMemory),
1242            #[cfg(target_arch = "x86_64")]
1243            HypervisorCap::Xcrs => Ok(KvmCap::Xcrs),
1244            #[cfg(target_arch = "x86_64")]
1245            HypervisorCap::CalibratedTscLeafRequired => Err(Error::new(libc::EINVAL)),
1246            HypervisorCap::StaticSwiotlbAllocationRequired => Err(Error::new(libc::EINVAL)),
1247            HypervisorCap::HypervisorInitializedBootContext => Err(Error::new(libc::EINVAL)),
1248        }
1249    }
1250}
1251
1252fn to_kvm_irq_routing_entry(item: &IrqRoute, cap_msi_devid: bool) -> kvm_irq_routing_entry {
1253    match &item.source {
1254        IrqSource::Irqchip { chip, pin } => kvm_irq_routing_entry {
1255            gsi: item.gsi,
1256            type_: KVM_IRQ_ROUTING_IRQCHIP,
1257            u: kvm_irq_routing_entry__bindgen_ty_1 {
1258                irqchip: kvm_irq_routing_irqchip {
1259                    irqchip: chip_to_kvm_chip(*chip),
1260                    pin: *pin,
1261                },
1262            },
1263            ..Default::default()
1264        },
1265        IrqSource::Msi {
1266            address,
1267            data,
1268            #[cfg(target_arch = "aarch64")]
1269            pci_address,
1270        } => {
1271            // Even though we always pass the device ID along to this point, KVM docs say: "If this
1272            // capability is not available, userspace should never set the KVM_MSI_VALID_DEVID flag
1273            // as the ioctl might fail"
1274            let devid = if cap_msi_devid {
1275                #[cfg(not(target_arch = "aarch64"))]
1276                panic!("unexpected KVM_CAP_MSI_DEVID");
1277                #[cfg(target_arch = "aarch64")]
1278                Some(pci_address.to_u32())
1279            } else {
1280                None
1281            };
1282            kvm_irq_routing_entry {
1283                gsi: item.gsi,
1284                type_: KVM_IRQ_ROUTING_MSI,
1285                flags: if devid.is_some() {
1286                    KVM_MSI_VALID_DEVID
1287                } else {
1288                    0
1289                },
1290                u: kvm_irq_routing_entry__bindgen_ty_1 {
1291                    msi: kvm_irq_routing_msi {
1292                        address_lo: *address as u32,
1293                        address_hi: (*address >> 32) as u32,
1294                        data: *data,
1295                        __bindgen_anon_1: kvm_irq_routing_msi__bindgen_ty_1 {
1296                            devid: devid.unwrap_or_default(),
1297                        },
1298                    },
1299                },
1300                ..Default::default()
1301            }
1302        }
1303    }
1304}
1305
1306impl From<&kvm_mp_state> for MPState {
1307    fn from(item: &kvm_mp_state) -> Self {
1308        match item.mp_state {
1309            KVM_MP_STATE_RUNNABLE => MPState::Runnable,
1310            KVM_MP_STATE_UNINITIALIZED => MPState::Uninitialized,
1311            KVM_MP_STATE_INIT_RECEIVED => MPState::InitReceived,
1312            KVM_MP_STATE_HALTED => MPState::Halted,
1313            KVM_MP_STATE_SIPI_RECEIVED => MPState::SipiReceived,
1314            KVM_MP_STATE_STOPPED => MPState::Stopped,
1315            state => {
1316                error!(
1317                    "unrecognized kvm_mp_state {}, setting to KVM_MP_STATE_RUNNABLE",
1318                    state
1319                );
1320                MPState::Runnable
1321            }
1322        }
1323    }
1324}
1325
1326impl From<&MPState> for kvm_mp_state {
1327    fn from(item: &MPState) -> Self {
1328        kvm_mp_state {
1329            mp_state: match item {
1330                MPState::Runnable => KVM_MP_STATE_RUNNABLE,
1331                MPState::Uninitialized => KVM_MP_STATE_UNINITIALIZED,
1332                MPState::InitReceived => KVM_MP_STATE_INIT_RECEIVED,
1333                MPState::Halted => KVM_MP_STATE_HALTED,
1334                MPState::SipiReceived => KVM_MP_STATE_SIPI_RECEIVED,
1335                MPState::Stopped => KVM_MP_STATE_STOPPED,
1336            },
1337        }
1338    }
1339}