xref: /cloud-hypervisor/hypervisor/src/vm.rs (revision eea9bcea38e0c5649f444c829f3a4f9c22aa486c)
1 // Copyright © 2019 Intel Corporation
2 //
3 // SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
4 //
5 // Copyright © 2020, Microsoft Corporation
6 //
7 // Copyright 2018-2019 CrowdStrike, Inc.
8 //
9 //
10 
11 #[cfg(target_arch = "aarch64")]
12 use crate::aarch64::VcpuInit;
13 #[cfg(target_arch = "aarch64")]
14 use crate::arch::aarch64::gic::{Vgic, VgicConfig};
15 #[cfg(feature = "tdx")]
16 use crate::arch::x86::CpuIdEntry;
17 use crate::cpu::Vcpu;
18 #[cfg(target_arch = "x86_64")]
19 use crate::ClockData;
20 use crate::UserMemoryRegion;
21 use crate::{IoEventAddress, IrqRoutingEntry};
22 use std::any::Any;
23 #[cfg(target_arch = "x86_64")]
24 use std::fs::File;
25 use std::sync::Arc;
26 #[cfg(target_arch = "aarch64")]
27 use std::sync::Mutex;
28 use thiserror::Error;
29 use vmm_sys_util::eventfd::EventFd;
30 
31 ///
32 /// I/O events data matches (32 or 64 bits).
33 ///
34 #[derive(Debug)]
35 pub enum DataMatch {
36     DataMatch32(u32),
37     DataMatch64(u64),
38 }
39 
40 impl From<DataMatch> for u64 {
41     fn from(dm: DataMatch) -> u64 {
42         match dm {
43             DataMatch::DataMatch32(dm) => dm.into(),
44             DataMatch::DataMatch64(dm) => dm,
45         }
46     }
47 }
48 
49 #[derive(Error, Debug)]
50 ///
51 /// Enum for VM error
52 pub enum HypervisorVmError {
53     ///
54     /// Create Vcpu error
55     ///
56     #[error("Failed to create Vcpu: {0}")]
57     CreateVcpu(#[source] anyhow::Error),
58     ///
59     /// Identity map address error
60     ///
61     #[error("Failed to set identity map address: {0}")]
62     SetIdentityMapAddress(#[source] anyhow::Error),
63     ///
64     /// TSS address error
65     ///
66     #[error("Failed to set TSS address: {0}")]
67     SetTssAddress(#[source] anyhow::Error),
68     ///
69     /// Create interrupt controller error
70     ///
71     #[error("Failed to create interrupt controller: {0}")]
72     CreateIrq(#[source] anyhow::Error),
73     ///
74     /// Register interrupt event error
75     ///
76     #[error("Failed to register interrupt event: {0}")]
77     RegisterIrqFd(#[source] anyhow::Error),
78     ///
79     /// Un register interrupt event error
80     ///
81     #[error("Failed to unregister interrupt event: {0}")]
82     UnregisterIrqFd(#[source] anyhow::Error),
83     ///
84     /// Register IO event error
85     ///
86     #[error("Failed to register IO event: {0}")]
87     RegisterIoEvent(#[source] anyhow::Error),
88     ///
89     /// Unregister IO event error
90     ///
91     #[error("Failed to unregister IO event: {0}")]
92     UnregisterIoEvent(#[source] anyhow::Error),
93     ///
94     /// Set GSI routing error
95     ///
96     #[error("Failed to set GSI routing: {0}")]
97     SetGsiRouting(#[source] anyhow::Error),
98     ///
99     /// Create user memory error
100     ///
101     #[error("Failed to create user memory: {0}")]
102     CreateUserMemory(#[source] anyhow::Error),
103     ///
104     /// Remove user memory region error
105     ///
106     #[error("Failed to remove user memory: {0}")]
107     RemoveUserMemory(#[source] anyhow::Error),
108     ///
109     /// Create device error
110     ///
111     #[error("Failed to set GSI routing: {0}")]
112     CreateDevice(#[source] anyhow::Error),
113     ///
114     /// Get preferred target error
115     ///
116     #[error("Failed to get preferred target: {0}")]
117     GetPreferredTarget(#[source] anyhow::Error),
118     ///
119     /// Enable split Irq error
120     ///
121     #[error("Failed to enable split Irq: {0}")]
122     EnableSplitIrq(#[source] anyhow::Error),
123     ///
124     /// Enable SGX attribute error
125     ///
126     #[error("Failed to enable SGX attribute: {0}")]
127     EnableSgxAttribute(#[source] anyhow::Error),
128     ///
129     /// Get clock error
130     ///
131     #[error("Failed to get clock: {0}")]
132     GetClock(#[source] anyhow::Error),
133     ///
134     /// Set clock error
135     ///
136     #[error("Failed to set clock: {0}")]
137     SetClock(#[source] anyhow::Error),
138     ///
139     /// Create passthrough device
140     ///
141     #[error("Failed to create passthrough device: {0}")]
142     CreatePassthroughDevice(#[source] anyhow::Error),
143     /// Write to Guest memory
144     ///
145     #[error("Failed to write to guest memory: {0}")]
146     GuestMemWrite(#[source] anyhow::Error),
147     ///
148     /// Read Guest memory
149     ///
150     #[error("Failed to read guest memory: {0}")]
151     GuestMemRead(#[source] anyhow::Error),
152     ///
153     /// Read from MMIO Bus
154     ///
155     #[error("Failed to read from MMIO Bus: {0}")]
156     MmioBusRead(#[source] anyhow::Error),
157     ///
158     /// Write to MMIO Bus
159     ///
160     #[error("Failed to write to MMIO Bus: {0}")]
161     MmioBusWrite(#[source] anyhow::Error),
162     ///
163     /// Read from IO Bus
164     ///
165     #[error("Failed to read from IO Bus: {0}")]
166     IoBusRead(#[source] anyhow::Error),
167     ///
168     /// Write to IO Bus
169     ///
170     #[error("Failed to write to IO Bus: {0}")]
171     IoBusWrite(#[source] anyhow::Error),
172     ///
173     /// Start dirty log error
174     ///
175     #[error("Failed to get dirty log: {0}")]
176     StartDirtyLog(#[source] anyhow::Error),
177     ///
178     /// Stop dirty log error
179     ///
180     #[error("Failed to get dirty log: {0}")]
181     StopDirtyLog(#[source] anyhow::Error),
182     ///
183     /// Get dirty log error
184     ///
185     #[error("Failed to get dirty log: {0}")]
186     GetDirtyLog(#[source] anyhow::Error),
187     ///
188     /// Assert virtual interrupt error
189     ///
190     #[error("Failed to assert virtual Interrupt: {0}")]
191     AsserttVirtualInterrupt(#[source] anyhow::Error),
192 
193     #[cfg(feature = "tdx")]
194     ///
195     /// Error initializing TDX on the VM
196     ///
197     #[error("Failed to initialize TDX: {0}")]
198     InitializeTdx(#[source] std::io::Error),
199     #[cfg(feature = "tdx")]
200     ///
201     /// Error finalizing the TDX configuration on the VM
202     ///
203     #[error("Failed to finalize TDX: {0}")]
204     FinalizeTdx(#[source] std::io::Error),
205     #[cfg(feature = "tdx")]
206     ///
207     /// Error initializing the TDX memory region
208     ///
209     #[error("Failed to initialize memory region TDX: {0}")]
210     InitMemRegionTdx(#[source] std::io::Error),
211     ///
212     /// Create Vgic error
213     ///
214     #[error("Failed to create Vgic: {0}")]
215     CreateVgic(#[source] anyhow::Error),
216 }
217 ///
218 /// Result type for returning from a function
219 ///
220 pub type Result<T> = std::result::Result<T, HypervisorVmError>;
221 
222 /// Configuration data for legacy interrupts.
223 ///
224 /// On x86 platforms, legacy interrupts means those interrupts routed through PICs or IOAPICs.
225 #[derive(Copy, Clone, Debug)]
226 pub struct LegacyIrqSourceConfig {
227     pub irqchip: u32,
228     pub pin: u32,
229 }
230 
231 /// Configuration data for MSI/MSI-X interrupts.
232 ///
233 /// On x86 platforms, these interrupts are vectors delivered directly to the LAPIC.
234 #[derive(Copy, Clone, Debug, Default)]
235 pub struct MsiIrqSourceConfig {
236     /// High address to delivery message signaled interrupt.
237     pub high_addr: u32,
238     /// Low address to delivery message signaled interrupt.
239     pub low_addr: u32,
240     /// Data to write to delivery message signaled interrupt.
241     pub data: u32,
242     /// Unique ID of the device to delivery message signaled interrupt.
243     pub devid: u32,
244 }
245 
246 /// Configuration data for an interrupt source.
247 #[derive(Copy, Clone, Debug)]
248 pub enum InterruptSourceConfig {
249     /// Configuration data for Legacy interrupts.
250     LegacyIrq(LegacyIrqSourceConfig),
251     /// Configuration data for PciMsi, PciMsix and generic MSI interrupts.
252     MsiIrq(MsiIrqSourceConfig),
253 }
254 
255 ///
256 /// Trait to represent a Vm
257 ///
258 /// This crate provides a hypervisor-agnostic interfaces for Vm
259 ///
260 pub trait Vm: Send + Sync + Any {
261     #[cfg(target_arch = "x86_64")]
262     /// Sets the address of the one-page region in the VM's address space.
263     fn set_identity_map_address(&self, address: u64) -> Result<()>;
264     #[cfg(target_arch = "x86_64")]
265     /// Sets the address of the three-page region in the VM's address space.
266     fn set_tss_address(&self, offset: usize) -> Result<()>;
267     /// Creates an in-kernel interrupt controller.
268     fn create_irq_chip(&self) -> Result<()>;
269     /// Registers an event that will, when signaled, trigger the `gsi` IRQ.
270     fn register_irqfd(&self, fd: &EventFd, gsi: u32) -> Result<()>;
271     /// Unregister an event that will, when signaled, trigger the `gsi` IRQ.
272     fn unregister_irqfd(&self, fd: &EventFd, gsi: u32) -> Result<()>;
273     /// Creates a new KVM vCPU file descriptor and maps the memory corresponding
274     fn create_vcpu(&self, id: u8, vm_ops: Option<Arc<dyn VmOps>>) -> Result<Arc<dyn Vcpu>>;
275     #[cfg(target_arch = "aarch64")]
276     fn create_vgic(&self, config: VgicConfig) -> Result<Arc<Mutex<dyn Vgic>>>;
277 
278     /// Registers an event to be signaled whenever a certain address is written to.
279     fn register_ioevent(
280         &self,
281         fd: &EventFd,
282         addr: &IoEventAddress,
283         datamatch: Option<DataMatch>,
284     ) -> Result<()>;
285     /// Unregister an event from a certain address it has been previously registered to.
286     fn unregister_ioevent(&self, fd: &EventFd, addr: &IoEventAddress) -> Result<()>;
287     // Construct a routing entry
288     fn make_routing_entry(&self, gsi: u32, config: &InterruptSourceConfig) -> IrqRoutingEntry;
289     /// Sets the GSI routing table entries, overwriting any previously set
290     fn set_gsi_routing(&self, entries: &[IrqRoutingEntry]) -> Result<()>;
291     /// Creates a memory region structure that can be used with {create/remove}_user_memory_region
292     fn make_user_memory_region(
293         &self,
294         slot: u32,
295         guest_phys_addr: u64,
296         memory_size: u64,
297         userspace_addr: u64,
298         readonly: bool,
299         log_dirty_pages: bool,
300     ) -> UserMemoryRegion;
301     /// Creates a guest physical memory slot.
302     fn create_user_memory_region(&self, user_memory_region: UserMemoryRegion) -> Result<()>;
303     /// Removes a guest physical memory slot.
304     fn remove_user_memory_region(&self, user_memory_region: UserMemoryRegion) -> Result<()>;
305     /// Returns the preferred CPU target type which can be emulated by KVM on underlying host.
306     #[cfg(target_arch = "aarch64")]
307     fn get_preferred_target(&self, kvi: &mut VcpuInit) -> Result<()>;
308     /// Enable split Irq capability
309     #[cfg(target_arch = "x86_64")]
310     fn enable_split_irq(&self) -> Result<()>;
311     #[cfg(target_arch = "x86_64")]
312     fn enable_sgx_attribute(&self, file: File) -> Result<()>;
313     /// Retrieve guest clock.
314     #[cfg(target_arch = "x86_64")]
315     fn get_clock(&self) -> Result<ClockData>;
316     /// Set guest clock.
317     #[cfg(target_arch = "x86_64")]
318     fn set_clock(&self, data: &ClockData) -> Result<()>;
319     /// Create a device that is used for passthrough
320     fn create_passthrough_device(&self) -> Result<vfio_ioctls::VfioDeviceFd>;
321     /// Start logging dirty pages
322     fn start_dirty_log(&self) -> Result<()>;
323     /// Stop logging dirty pages
324     fn stop_dirty_log(&self) -> Result<()>;
325     /// Get dirty pages bitmap
326     fn get_dirty_log(&self, slot: u32, base_gpa: u64, memory_size: u64) -> Result<Vec<u64>>;
327     #[cfg(feature = "tdx")]
328     /// Initalize TDX on this VM
329     fn tdx_init(&self, _cpuid: &[CpuIdEntry], _max_vcpus: u32) -> Result<()> {
330         unimplemented!()
331     }
332     #[cfg(feature = "tdx")]
333     /// Finalize the configuration of TDX on this VM
334     fn tdx_finalize(&self) -> Result<()> {
335         unimplemented!()
336     }
337     #[cfg(feature = "tdx")]
338     /// Initalize a TDX memory region for this VM
339     fn tdx_init_memory_region(
340         &self,
341         _host_address: u64,
342         _guest_address: u64,
343         _size: u64,
344         _measure: bool,
345     ) -> Result<()> {
346         unimplemented!()
347     }
348     /// Downcast to the underlying hypervisor VM type
349     fn as_any(&self) -> &dyn Any;
350 }
351 
352 pub trait VmOps: Send + Sync {
353     fn guest_mem_write(&self, gpa: u64, buf: &[u8]) -> Result<usize>;
354     fn guest_mem_read(&self, gpa: u64, buf: &mut [u8]) -> Result<usize>;
355     fn mmio_read(&self, gpa: u64, data: &mut [u8]) -> Result<()>;
356     fn mmio_write(&self, gpa: u64, data: &[u8]) -> Result<()>;
357     #[cfg(target_arch = "x86_64")]
358     fn pio_read(&self, port: u64, data: &mut [u8]) -> Result<()>;
359     #[cfg(target_arch = "x86_64")]
360     fn pio_write(&self, port: u64, data: &[u8]) -> Result<()>;
361 }
362