1pub mod android;
8pub mod fdt;
9pub mod pstore;
10pub mod serial;
11
12pub mod sys;
13
14use std::collections::BTreeMap;
15use std::error::Error as StdError;
16use std::fs::File;
17use std::io;
18use std::ops::Deref;
19use std::path::PathBuf;
20use std::str::FromStr;
21use std::sync::mpsc;
22use std::sync::mpsc::SendError;
23use std::sync::Arc;
24
25use acpi_tables::sdt::SDT;
26use base::syslog;
27use base::AsRawDescriptors;
28use base::FileGetLen;
29use base::FileReadWriteAtVolatile;
30use base::RecvTube;
31use base::SendTube;
32use base::Tube;
33use devices::virtio::VirtioDevice;
34use devices::BarRange;
35use devices::Bus;
36use devices::BusDevice;
37use devices::BusDeviceObj;
38use devices::BusError;
39use devices::BusResumeDevice;
40use devices::FwCfgParameters;
41use devices::GpeScope;
42use devices::HotPlugBus;
43use devices::IrqChip;
44use devices::IrqEventSource;
45use devices::PciAddress;
46use devices::PciBus;
47use devices::PciDevice;
48use devices::PciDeviceError;
49use devices::PciInterruptPin;
50use devices::PciRoot;
51use devices::PciRootCommand;
52use devices::PreferredIrq;
53#[cfg(any(target_os = "android", target_os = "linux"))]
54use devices::ProxyDevice;
55use devices::SerialHardware;
56use devices::SerialParameters;
57pub use fdt::apply_device_tree_overlays;
58pub use fdt::DtbOverlay;
59#[cfg(feature = "gdb")]
60use gdbstub::arch::Arch;
61use hypervisor::MemCacheType;
62use hypervisor::Vm;
63#[cfg(windows)]
64use jail::FakeMinijailStub as Minijail;
65#[cfg(any(target_os = "android", target_os = "linux"))]
66use minijail::Minijail;
67use remain::sorted;
68use resources::SystemAllocator;
69use resources::SystemAllocatorConfig;
70use serde::de::Visitor;
71use serde::Deserialize;
72use serde::Serialize;
73use serde_keyvalue::FromKeyValues;
74pub use serial::add_serial_devices;
75pub use serial::get_serial_cmdline;
76pub use serial::set_default_serial_parameters;
77pub use serial::GetSerialCmdlineError;
78pub use serial::SERIAL_ADDR;
79use sync::Condvar;
80use sync::Mutex;
81#[cfg(any(target_os = "android", target_os = "linux"))]
82pub use sys::linux::PlatformBusResources;
83use thiserror::Error;
84use uuid::Uuid;
85use vm_control::BatControl;
86use vm_control::BatteryType;
87use vm_control::PmResource;
88use vm_memory::GuestAddress;
89use vm_memory::GuestMemory;
90use vm_memory::GuestMemoryError;
91use vm_memory::MemoryRegionInformation;
92use vm_memory::MemoryRegionOptions;
93
94cfg_if::cfg_if! {
95 if #[cfg(target_arch = "aarch64")] {
96 pub use devices::IrqChipAArch64 as IrqChipArch;
97 #[cfg(feature = "gdb")]
98 pub use gdbstub_arch::aarch64::AArch64 as GdbArch;
99 pub use hypervisor::CpuConfigAArch64 as CpuConfigArch;
100 pub use hypervisor::Hypervisor as HypervisorArch;
101 pub use hypervisor::VcpuAArch64 as VcpuArch;
102 pub use hypervisor::VcpuInitAArch64 as VcpuInitArch;
103 pub use hypervisor::VmAArch64 as VmArch;
104 } else if #[cfg(target_arch = "riscv64")] {
105 pub use devices::IrqChipRiscv64 as IrqChipArch;
106 #[cfg(feature = "gdb")]
107 pub use gdbstub_arch::riscv::Riscv64 as GdbArch;
108 pub use hypervisor::CpuConfigRiscv64 as CpuConfigArch;
109 pub use hypervisor::Hypervisor as HypervisorArch;
110 pub use hypervisor::VcpuInitRiscv64 as VcpuInitArch;
111 pub use hypervisor::VcpuRiscv64 as VcpuArch;
112 pub use hypervisor::VmRiscv64 as VmArch;
113 } else if #[cfg(target_arch = "x86_64")] {
114 pub use devices::IrqChipX86_64 as IrqChipArch;
115 #[cfg(feature = "gdb")]
116 pub use gdbstub_arch::x86::X86_64_SSE as GdbArch;
117 pub use hypervisor::CpuConfigX86_64 as CpuConfigArch;
118 pub use hypervisor::HypervisorX86_64 as HypervisorArch;
119 pub use hypervisor::VcpuInitX86_64 as VcpuInitArch;
120 pub use hypervisor::VcpuX86_64 as VcpuArch;
121 pub use hypervisor::VmX86_64 as VmArch;
122 }
123}
124
125pub enum VmImage {
126 Kernel(File),
127 Bios(File),
128}
129
130#[derive(Clone, Debug, Deserialize, Serialize, FromKeyValues, PartialEq, Eq)]
131#[serde(deny_unknown_fields, rename_all = "kebab-case")]
132pub struct Pstore {
133 pub path: PathBuf,
134 pub size: u32,
135}
136
137#[derive(Clone, Copy, Debug, Serialize, Deserialize, FromKeyValues)]
138#[serde(deny_unknown_fields, rename_all = "kebab-case")]
139pub enum FdtPosition {
140 Start,
142 End,
144 AfterPayload,
146}
147
148#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
150pub struct CpuSet(Vec<usize>);
151
152impl CpuSet {
153 pub fn new<I: IntoIterator<Item = usize>>(cpus: I) -> Self {
154 CpuSet(cpus.into_iter().collect())
155 }
156
157 pub fn iter(&self) -> std::slice::Iter<'_, usize> {
158 self.0.iter()
159 }
160}
161
162impl FromIterator<usize> for CpuSet {
163 fn from_iter<T>(iter: T) -> Self
164 where
165 T: IntoIterator<Item = usize>,
166 {
167 CpuSet::new(iter)
168 }
169}
170
171#[cfg(target_arch = "aarch64")]
172fn sve_auto_default() -> bool {
173 true
174}
175
176#[cfg(target_arch = "aarch64")]
178#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
179#[serde(deny_unknown_fields, rename_all = "kebab-case")]
180pub struct SveConfig {
181 #[serde(default = "sve_auto_default")]
183 pub auto: bool,
184}
185
186#[cfg(target_arch = "aarch64")]
187impl Default for SveConfig {
188 fn default() -> Self {
189 SveConfig {
190 auto: sve_auto_default(),
191 }
192 }
193}
194
195#[cfg(all(target_os = "android", target_arch = "aarch64"))]
199#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize, FromKeyValues)]
200#[serde(deny_unknown_fields, rename_all = "kebab-case")]
201pub struct FfaConfig {
202 #[serde(default)]
204 pub auto: bool,
205}
206
207fn parse_cpu_range(s: &str, cpuset: &mut Vec<usize>) -> Result<(), String> {
208 fn parse_cpu(s: &str) -> Result<usize, String> {
209 s.parse()
210 .map_err(|_| format!("invalid CPU index {s} - index must be a non-negative integer"))
211 }
212
213 let (first_cpu, last_cpu) = match s.split_once('-') {
214 Some((first_cpu, last_cpu)) => {
215 let first_cpu = parse_cpu(first_cpu)?;
216 let last_cpu = parse_cpu(last_cpu)?;
217
218 if last_cpu < first_cpu {
219 return Err(format!(
220 "invalid CPU range {s} - ranges must be from low to high"
221 ));
222 }
223 (first_cpu, last_cpu)
224 }
225 None => {
226 let cpu = parse_cpu(s)?;
227 (cpu, cpu)
228 }
229 };
230
231 cpuset.extend(first_cpu..=last_cpu);
232
233 Ok(())
234}
235
236impl FromStr for CpuSet {
237 type Err = String;
238
239 fn from_str(s: &str) -> Result<Self, Self::Err> {
240 let mut cpuset = Vec::new();
241 for part in s.split(',') {
242 parse_cpu_range(part, &mut cpuset)?;
243 }
244 Ok(CpuSet::new(cpuset))
245 }
246}
247
248impl Deref for CpuSet {
249 type Target = Vec<usize>;
250
251 fn deref(&self) -> &Self::Target {
252 &self.0
253 }
254}
255
256impl IntoIterator for CpuSet {
257 type Item = usize;
258 type IntoIter = std::vec::IntoIter<Self::Item>;
259
260 fn into_iter(self) -> Self::IntoIter {
261 self.0.into_iter()
262 }
263}
264
265#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
267pub enum DevicePowerManagerConfig {
268 PkvmHvc,
270}
271
272impl FromStr for DevicePowerManagerConfig {
273 type Err = String;
274
275 fn from_str(s: &str) -> Result<Self, Self::Err> {
276 match s {
277 "pkvm-hvc" => Ok(Self::PkvmHvc),
278 _ => Err(format!("DevicePowerManagerConfig '{s}' not supported")),
279 }
280 }
281}
282
283impl<'de> Deserialize<'de> for CpuSet {
286 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
287 where
288 D: serde::Deserializer<'de>,
289 {
290 struct CpuSetVisitor;
291 impl<'de> Visitor<'de> for CpuSetVisitor {
292 type Value = CpuSet;
293
294 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
295 formatter.write_str("CpuSet")
296 }
297
298 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
299 where
300 A: serde::de::SeqAccess<'de>,
301 {
302 #[derive(Deserialize)]
303 #[serde(untagged)]
304 enum CpuSetValue<'a> {
305 Single(usize),
306 Range(&'a str),
307 }
308
309 let mut cpus = Vec::new();
310 while let Some(cpuset) = seq.next_element::<CpuSetValue>()? {
311 match cpuset {
312 CpuSetValue::Single(cpu) => cpus.push(cpu),
313 CpuSetValue::Range(range) => {
314 parse_cpu_range(range, &mut cpus).map_err(serde::de::Error::custom)?;
315 }
316 }
317 }
318
319 Ok(CpuSet::new(cpus))
320 }
321 }
322
323 deserializer.deserialize_seq(CpuSetVisitor)
324 }
325}
326
327impl Serialize for CpuSet {
329 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
330 where
331 S: serde::Serializer,
332 {
333 use serde::ser::SerializeSeq;
334
335 let mut seq = serializer.serialize_seq(None)?;
336
337 let mut serialize_range = |start: usize, end: usize| -> Result<(), S::Error> {
339 if start == end {
340 seq.serialize_element(&start)?;
341 } else {
342 seq.serialize_element(&format!("{start}-{end}"))?;
343 }
344
345 Ok(())
346 };
347
348 let mut range = None;
350 for core in &self.0 {
351 range = match range {
352 None => Some((core, core)),
353 Some((start, end)) if *end == *core - 1 => Some((start, core)),
354 Some((start, end)) => {
355 serialize_range(*start, *end)?;
356 Some((core, core))
357 }
358 };
359 }
360
361 if let Some((start, end)) = range {
362 serialize_range(*start, *end)?;
363 }
364
365 seq.end()
366 }
367}
368
369#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
371pub enum VcpuAffinity {
372 Global(CpuSet),
374 PerVcpu(BTreeMap<usize, CpuSet>),
379}
380
381#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, FromKeyValues)]
383pub struct MemoryRegionConfig {
384 pub start: u64,
385 pub size: Option<u64>,
386}
387
388#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, FromKeyValues)]
390pub struct PciConfig {
391 #[cfg(target_arch = "aarch64")]
393 pub cam: Option<MemoryRegionConfig>,
394 #[cfg(target_arch = "x86_64")]
396 pub ecam: Option<MemoryRegionConfig>,
397 pub mem: Option<MemoryRegionConfig>,
399}
400
401#[sorted]
404pub struct VmComponents {
405 #[cfg(all(target_arch = "x86_64", unix))]
406 pub ac_adapter: bool,
407 pub acpi_sdts: Vec<SDT>,
408 pub android_fstab: Option<File>,
409 pub boot_cpu: usize,
410 pub bootorder_fw_cfg_blob: Vec<u8>,
411 #[cfg(target_arch = "x86_64")]
412 pub break_linux_pci_config_io: bool,
413
414 pub delay_rt: bool,
415 pub dev_pm: Option<DevicePowerManagerConfig>,
416 pub dynamic_power_coefficient: BTreeMap<usize, u32>,
417 pub extra_kernel_params: Vec<String>,
418 #[cfg(target_arch = "x86_64")]
419 pub force_s2idle: bool,
420 pub fw_cfg_enable: bool,
421 pub fw_cfg_parameters: Vec<FwCfgParameters>,
422 pub host_cpu_topology: bool,
423 pub hugepages: bool,
424 pub hv_cfg: hypervisor::Config,
425 pub initrd_image: Option<File>,
426 pub itmt: bool,
427 pub memory_size: u64,
428 pub no_i8042: bool,
429 pub no_rtc: bool,
430 pub no_smt: bool,
431 #[cfg(all(
432 target_arch = "aarch64",
433 any(target_os = "android", target_os = "linux")
434 ))]
435 pub normalized_cpu_ipc_ratios: BTreeMap<usize, u32>,
436 pub pci_config: PciConfig,
437 pub pflash_block_size: u32,
438 pub pflash_image: Option<File>,
439 pub pstore: Option<Pstore>,
440 pub pvm_fw: Option<File>,
443 pub rt_cpus: CpuSet,
444 #[cfg(target_arch = "x86_64")]
445 pub smbios: SmbiosOptions,
446 pub smccc_trng: bool,
447 #[cfg(target_arch = "aarch64")]
448 pub sve_config: SveConfig,
449 pub swiotlb: Option<u64>,
450 pub vcpu_affinity: Option<VcpuAffinity>,
451 pub vcpu_capacity: BTreeMap<usize, u32>,
453 pub vcpu_clusters: Vec<CpuSet>,
455 pub vcpu_count: usize,
456 #[cfg(all(
457 target_arch = "aarch64",
458 any(target_os = "android", target_os = "linux")
459 ))]
460 pub vcpu_domain_paths: BTreeMap<usize, PathBuf>,
461 #[cfg(all(
462 target_arch = "aarch64",
463 any(target_os = "android", target_os = "linux")
464 ))]
465 pub vcpu_domains: BTreeMap<usize, u32>,
466 #[cfg(all(
467 target_arch = "aarch64",
468 any(target_os = "android", target_os = "linux")
469 ))]
470 pub vcpu_frequencies: BTreeMap<usize, Vec<u32>>,
473 #[cfg(any(target_os = "android", target_os = "linux"))]
474 pub vfio_platform_pm: bool,
475 #[cfg(all(
476 target_arch = "aarch64",
477 any(target_os = "android", target_os = "linux")
478 ))]
479 pub virt_cpufreq_v2: bool,
480 pub vm_image: VmImage,
481}
482
483#[sorted]
485pub struct RunnableLinuxVm<V: VmArch, Vcpu: VcpuArch> {
486 pub bat_control: Option<BatControl>,
487 pub delay_rt: bool,
488 pub devices_thread: Option<std::thread::JoinHandle<()>>,
489 pub hotplug_bus: BTreeMap<u8, Arc<Mutex<dyn HotPlugBus>>>,
490 pub hypercall_bus: Arc<Bus>,
491 pub io_bus: Arc<Bus>,
492 pub irq_chip: Box<dyn IrqChipArch>,
493 pub mmio_bus: Arc<Bus>,
494 pub no_smt: bool,
495 pub pid_debug_label_map: BTreeMap<u32, String>,
496 #[cfg(any(target_os = "android", target_os = "linux"))]
497 pub platform_devices: Vec<Arc<Mutex<dyn BusDevice>>>,
498 pub pm: Option<Arc<Mutex<dyn PmResource + Send>>>,
499 pub resume_notify_devices: Vec<Arc<Mutex<dyn BusResumeDevice>>>,
501 pub root_config: Arc<Mutex<PciRoot>>,
502 pub rt_cpus: CpuSet,
503 pub suspend_tube: (Arc<Mutex<SendTube>>, RecvTube),
504 pub vcpu_affinity: Option<VcpuAffinity>,
505 pub vcpu_count: usize,
506 pub vcpu_init: Vec<VcpuInitArch>,
507 pub vcpus: Option<Vec<Vcpu>>,
510 pub vm: V,
511 pub vm_request_tubes: Vec<Tube>,
512}
513
514pub struct VirtioDeviceStub {
516 pub dev: Box<dyn VirtioDevice>,
517 pub jail: Option<Minijail>,
518}
519
520pub trait LinuxArch {
523 type Error: StdError;
524 type ArchMemoryLayout;
525
526 fn arch_memory_layout(
529 components: &VmComponents,
530 ) -> std::result::Result<Self::ArchMemoryLayout, Self::Error>;
531
532 fn guest_memory_layout(
539 components: &VmComponents,
540 arch_memory_layout: &Self::ArchMemoryLayout,
541 hypervisor: &impl hypervisor::Hypervisor,
542 ) -> std::result::Result<Vec<(GuestAddress, u64, MemoryRegionOptions)>, Self::Error>;
543
544 fn get_system_allocator_config<V: Vm>(
554 vm: &V,
555 arch_memory_layout: &Self::ArchMemoryLayout,
556 ) -> SystemAllocatorConfig;
557
558 fn build_vm<V, Vcpu>(
579 components: VmComponents,
580 arch_memory_layout: &Self::ArchMemoryLayout,
581 vm_evt_wrtube: &SendTube,
582 system_allocator: &mut SystemAllocator,
583 serial_parameters: &BTreeMap<(SerialHardware, u8), SerialParameters>,
584 serial_jail: Option<Minijail>,
585 battery: (Option<BatteryType>, Option<Minijail>),
586 vm: V,
587 ramoops_region: Option<pstore::RamoopsRegion>,
588 devices: Vec<(Box<dyn BusDeviceObj>, Option<Minijail>)>,
589 irq_chip: &mut dyn IrqChipArch,
590 vcpu_ids: &mut Vec<usize>,
591 dump_device_tree_blob: Option<PathBuf>,
592 debugcon_jail: Option<Minijail>,
593 #[cfg(target_arch = "x86_64")] pflash_jail: Option<Minijail>,
594 #[cfg(target_arch = "x86_64")] fw_cfg_jail: Option<Minijail>,
595 #[cfg(feature = "swap")] swap_controller: &mut Option<swap::SwapController>,
596 guest_suspended_cvar: Option<Arc<(Mutex<bool>, Condvar)>>,
597 device_tree_overlays: Vec<DtbOverlay>,
598 fdt_position: Option<FdtPosition>,
599 no_pmu: bool,
600 ) -> std::result::Result<RunnableLinuxVm<V, Vcpu>, Self::Error>
601 where
602 V: VmArch,
603 Vcpu: VcpuArch;
604
605 fn configure_vcpu<V: Vm>(
618 vm: &V,
619 hypervisor: &dyn HypervisorArch,
620 irq_chip: &mut dyn IrqChipArch,
621 vcpu: &mut dyn VcpuArch,
622 vcpu_init: VcpuInitArch,
623 vcpu_id: usize,
624 num_vcpus: usize,
625 cpu_config: Option<CpuConfigArch>,
626 ) -> Result<(), Self::Error>;
627
628 fn register_pci_device<V: VmArch, Vcpu: VcpuArch>(
630 linux: &mut RunnableLinuxVm<V, Vcpu>,
631 device: Box<dyn PciDevice>,
632 #[cfg(any(target_os = "android", target_os = "linux"))] minijail: Option<Minijail>,
633 resources: &mut SystemAllocator,
634 hp_control_tube: &mpsc::Sender<PciRootCommand>,
635 #[cfg(feature = "swap")] swap_controller: &mut Option<swap::SwapController>,
636 ) -> Result<PciAddress, Self::Error>;
637
638 fn get_host_cpu_frequencies_khz() -> Result<BTreeMap<usize, Vec<u32>>, Self::Error>;
640
641 fn get_host_cpu_max_freq_khz() -> Result<BTreeMap<usize, u32>, Self::Error>;
643
644 fn get_host_cpu_capacity() -> Result<BTreeMap<usize, u32>, Self::Error>;
646
647 fn get_host_cpu_clusters() -> Result<Vec<CpuSet>, Self::Error>;
649}
650
651#[cfg(feature = "gdb")]
652pub trait GdbOps<T: VcpuArch> {
653 type Error: StdError;
654
655 fn read_registers(vcpu: &T) -> Result<<GdbArch as Arch>::Registers, Self::Error>;
657
658 fn write_registers(vcpu: &T, regs: &<GdbArch as Arch>::Registers) -> Result<(), Self::Error>;
660
661 fn read_memory(
663 vcpu: &T,
664 guest_mem: &GuestMemory,
665 vaddr: GuestAddress,
666 len: usize,
667 ) -> Result<Vec<u8>, Self::Error>;
668
669 fn write_memory(
671 vcpu: &T,
672 guest_mem: &GuestMemory,
673 vaddr: GuestAddress,
674 buf: &[u8],
675 ) -> Result<(), Self::Error>;
676
677 fn read_register(vcpu: &T, reg_id: <GdbArch as Arch>::RegId) -> Result<Vec<u8>, Self::Error>;
681
682 fn write_register(
684 vcpu: &T,
685 reg_id: <GdbArch as Arch>::RegId,
686 data: &[u8],
687 ) -> Result<(), Self::Error>;
688
689 fn enable_singlestep(vcpu: &T) -> Result<(), Self::Error>;
691
692 fn get_max_hw_breakpoints(vcpu: &T) -> Result<usize, Self::Error>;
694
695 fn set_hw_breakpoints(vcpu: &T, breakpoints: &[GuestAddress]) -> Result<(), Self::Error>;
697}
698
699#[sorted]
701#[derive(Error, Debug)]
702pub enum DeviceRegistrationError {
703 #[error("no more addresses are available")]
705 AddrsExhausted,
706 #[error("Allocating device addresses: {0}")]
708 AllocateDeviceAddrs(PciDeviceError),
709 #[error("Allocating IO addresses: {0}")]
711 AllocateIoAddrs(PciDeviceError),
712 #[error("Allocating IO resource: {0}")]
714 AllocateIoResource(resources::Error),
715 #[error("Allocating IRQ number")]
717 AllocateIrq,
718 #[cfg(any(target_os = "android", target_os = "linux"))]
720 #[error("Allocating IRQ resource: {0}")]
721 AllocateIrqResource(devices::vfio::VfioError),
722 #[error("failed to attach the device to its power domain: {0}")]
723 AttachDevicePowerDomain(anyhow::Error),
724 #[error("pci topology is broken")]
726 BrokenPciTopology,
727 #[cfg(any(target_os = "android", target_os = "linux"))]
729 #[error("failed to clone jail: {0}")]
730 CloneJail(minijail::Error),
731 #[error("unable to add device to kernel command line: {0}")]
733 Cmdline(kernel_cmdline::Error),
734 #[error("failed to configure window size: {0}")]
736 ConfigureWindowSize(PciDeviceError),
737 #[error("failed to create pipe: {0}")]
739 CreatePipe(base::Error),
740 #[error("failed to create pci root: {0}")]
742 CreateRoot(anyhow::Error),
743 #[error("failed to create serial device: {0}")]
745 CreateSerialDevice(devices::SerialError),
746 #[error("failed to create tube: {0}")]
748 CreateTube(base::TubeError),
749 #[error("failed to clone event: {0}")]
751 EventClone(base::Error),
752 #[error("failed to create event: {0}")]
754 EventCreate(base::Error),
755 #[error("failed to generate ACPI content")]
757 GenerateAcpi,
758 #[error("no more IRQs are available")]
760 IrqsExhausted,
761 #[error("cannot match VFIO device to DT node due to a missing symbol")]
763 MissingDeviceTreeSymbol,
764 #[error("missing required serial device {0}")]
766 MissingRequiredSerialDevice(u8),
767 #[error("failed to add to mmio bus: {0}")]
769 MmioInsert(BusError),
770 #[error("failed to insert device into PCI root: {0}")]
772 PciRootAddDevice(PciDeviceError),
773 #[cfg(any(target_os = "android", target_os = "linux"))]
774 #[error("failed to create proxy device: {0}")]
776 ProxyDeviceCreation(devices::ProxyError),
777 #[cfg(any(target_os = "android", target_os = "linux"))]
778 #[error("failed to register battery device to VM: {0}")]
780 RegisterBattery(devices::BatteryError),
781 #[error("failed to register PCI device to pci root bus")]
783 RegisterDevice(SendError<PciRootCommand>),
784 #[error("could not register PCI device capabilities: {0}")]
786 RegisterDeviceCapabilities(PciDeviceError),
787 #[error("failed to register ioevent to VM: {0}")]
789 RegisterIoevent(base::Error),
790 #[error("failed to register irq event to VM: {0}")]
792 RegisterIrqfd(base::Error),
793 #[error("Setting up VFIO platform IRQ: {0}")]
795 SetupVfioPlatformIrq(anyhow::Error),
796}
797
798pub fn configure_pci_device<V: VmArch, Vcpu: VcpuArch>(
800 linux: &mut RunnableLinuxVm<V, Vcpu>,
801 mut device: Box<dyn PciDevice>,
802 #[cfg(any(target_os = "android", target_os = "linux"))] jail: Option<Minijail>,
803 resources: &mut SystemAllocator,
804 hp_control_tube: &mpsc::Sender<PciRootCommand>,
805 #[cfg(feature = "swap")] swap_controller: &mut Option<swap::SwapController>,
806) -> Result<PciAddress, DeviceRegistrationError> {
807 let pci_address = device
809 .allocate_address(resources)
810 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
811
812 let mmio_ranges = device
814 .allocate_io_bars(resources)
815 .map_err(DeviceRegistrationError::AllocateIoAddrs)?;
816
817 let device_ranges = device
819 .allocate_device_bars(resources)
820 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
821
822 if let Some(pci_bus) = device.get_new_pci_bus() {
824 hp_control_tube
825 .send(PciRootCommand::AddBridge(pci_bus))
826 .map_err(DeviceRegistrationError::RegisterDevice)?;
827 let bar_ranges = Vec::new();
828 device
829 .configure_bridge_window(resources, &bar_ranges)
830 .map_err(DeviceRegistrationError::ConfigureWindowSize)?;
831 }
832
833 let intx_event = devices::IrqLevelEvent::new().map_err(DeviceRegistrationError::EventCreate)?;
835
836 if let PreferredIrq::Fixed { pin, gsi } = device.preferred_irq() {
837 resources.reserve_irq(gsi);
838
839 device.assign_irq(
840 intx_event
841 .try_clone()
842 .map_err(DeviceRegistrationError::EventClone)?,
843 pin,
844 gsi,
845 );
846
847 linux
848 .irq_chip
849 .as_irq_chip_mut()
850 .register_level_irq_event(gsi, &intx_event, IrqEventSource::from_device(&device))
851 .map_err(DeviceRegistrationError::RegisterIrqfd)?;
852 }
853
854 let mut keep_rds = device.keep_rds();
855 syslog::push_descriptors(&mut keep_rds);
856 cros_tracing::push_descriptors!(&mut keep_rds);
857 metrics::push_descriptors(&mut keep_rds);
858
859 device
860 .register_device_capabilities()
861 .map_err(DeviceRegistrationError::RegisterDeviceCapabilities)?;
862
863 #[cfg(any(target_os = "android", target_os = "linux"))]
864 let arced_dev: Arc<Mutex<dyn BusDevice>> = if let Some(jail) = jail {
865 let proxy = ProxyDevice::new(
866 device,
867 jail,
868 keep_rds,
869 #[cfg(feature = "swap")]
870 swap_controller,
871 )
872 .map_err(DeviceRegistrationError::ProxyDeviceCreation)?;
873 linux
874 .pid_debug_label_map
875 .insert(proxy.pid() as u32, proxy.debug_label());
876 Arc::new(Mutex::new(proxy))
877 } else {
878 device.on_sandboxed();
879 Arc::new(Mutex::new(device))
880 };
881
882 #[cfg(windows)]
883 let arced_dev = {
884 device.on_sandboxed();
885 Arc::new(Mutex::new(device))
886 };
887
888 #[cfg(any(target_os = "android", target_os = "linux"))]
889 hp_control_tube
890 .send(PciRootCommand::Add(pci_address, arced_dev.clone()))
891 .map_err(DeviceRegistrationError::RegisterDevice)?;
892
893 for range in &mmio_ranges {
894 linux
895 .mmio_bus
896 .insert(arced_dev.clone(), range.addr, range.size)
897 .map_err(DeviceRegistrationError::MmioInsert)?;
898 }
899
900 for range in &device_ranges {
901 linux
902 .mmio_bus
903 .insert(arced_dev.clone(), range.addr, range.size)
904 .map_err(DeviceRegistrationError::MmioInsert)?;
905 }
906
907 Ok(pci_address)
908}
909
910fn generate_pci_topology(
912 parent_bus: Arc<Mutex<PciBus>>,
913 resources: &mut SystemAllocator,
914 io_ranges: &mut BTreeMap<usize, Vec<BarRange>>,
915 device_ranges: &mut BTreeMap<usize, Vec<BarRange>>,
916 device_addrs: &[PciAddress],
917 devices: &mut Vec<(Box<dyn PciDevice>, Option<Minijail>)>,
918) -> Result<(Vec<BarRange>, u8), DeviceRegistrationError> {
919 let mut bar_ranges = Vec::new();
920 let bus_num = parent_bus.lock().get_bus_num();
921 let mut subordinate_bus = bus_num;
922 for (dev_idx, addr) in device_addrs.iter().enumerate() {
923 if addr.bus == bus_num {
925 if let Some(child_bus) = devices[dev_idx].0.get_new_pci_bus() {
928 let (child_bar_ranges, child_sub_bus) = generate_pci_topology(
929 child_bus.clone(),
930 resources,
931 io_ranges,
932 device_ranges,
933 device_addrs,
934 devices,
935 )?;
936 let device = &mut devices[dev_idx].0;
937 parent_bus
938 .lock()
939 .add_child_bus(child_bus.clone())
940 .map_err(|_| DeviceRegistrationError::BrokenPciTopology)?;
941 let bridge_window = device
942 .configure_bridge_window(resources, &child_bar_ranges)
943 .map_err(DeviceRegistrationError::ConfigureWindowSize)?;
944 bar_ranges.extend(bridge_window);
945
946 let ranges = device
947 .allocate_io_bars(resources)
948 .map_err(DeviceRegistrationError::AllocateIoAddrs)?;
949 io_ranges.insert(dev_idx, ranges.clone());
950 bar_ranges.extend(ranges);
951
952 let ranges = device
953 .allocate_device_bars(resources)
954 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
955 device_ranges.insert(dev_idx, ranges.clone());
956 bar_ranges.extend(ranges);
957
958 device.set_subordinate_bus(child_sub_bus);
959
960 subordinate_bus = std::cmp::max(subordinate_bus, child_sub_bus);
961 }
962 }
963 }
964
965 for (dev_idx, addr) in device_addrs.iter().enumerate() {
966 if addr.bus == bus_num {
967 let device = &mut devices[dev_idx].0;
968 if device.get_new_pci_bus().is_none() {
970 let ranges = device
971 .allocate_io_bars(resources)
972 .map_err(DeviceRegistrationError::AllocateIoAddrs)?;
973 io_ranges.insert(dev_idx, ranges.clone());
974 bar_ranges.extend(ranges);
975
976 let ranges = device
977 .allocate_device_bars(resources)
978 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
979 device_ranges.insert(dev_idx, ranges.clone());
980 bar_ranges.extend(ranges);
981 }
982 }
983 }
984 Ok((bar_ranges, subordinate_bus))
985}
986
987pub fn assign_pci_addresses(
989 devices: &mut [(Box<dyn BusDeviceObj>, Option<Minijail>)],
990 resources: &mut SystemAllocator,
991) -> Result<(), DeviceRegistrationError> {
992 for pci_device in devices
994 .iter_mut()
995 .filter_map(|(device, _jail)| device.as_pci_device_mut())
996 .filter(|pci_device| pci_device.preferred_address().is_some())
997 {
998 let _ = pci_device
999 .allocate_address(resources)
1000 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
1001 }
1002
1003 for pci_device in devices
1005 .iter_mut()
1006 .filter_map(|(device, _jail)| device.as_pci_device_mut())
1007 .filter(|pci_device| pci_device.preferred_address().is_none())
1008 {
1009 let _ = pci_device
1010 .allocate_address(resources)
1011 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
1012 }
1013
1014 Ok(())
1015}
1016
1017pub fn generate_pci_root(
1019 mut devices: Vec<(Box<dyn PciDevice>, Option<Minijail>)>,
1020 irq_chip: &mut dyn IrqChip,
1021 mmio_bus: Arc<Bus>,
1022 mmio_base: GuestAddress,
1023 mmio_register_bit_num: usize,
1024 io_bus: Arc<Bus>,
1025 resources: &mut SystemAllocator,
1026 vm: &mut impl Vm,
1027 max_irqs: usize,
1028 vcfg_base: Option<u64>,
1029 #[cfg(feature = "swap")] swap_controller: &mut Option<swap::SwapController>,
1030) -> Result<
1031 (
1032 PciRoot,
1033 Vec<(PciAddress, u32, PciInterruptPin)>,
1034 BTreeMap<u32, String>,
1035 BTreeMap<PciAddress, Vec<u8>>,
1036 BTreeMap<PciAddress, Vec<u8>>,
1037 ),
1038 DeviceRegistrationError,
1039> {
1040 let mut device_addrs = Vec::new();
1041
1042 for (device, _jail) in devices.iter_mut() {
1043 let address = device
1044 .allocate_address(resources)
1045 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
1046 device_addrs.push(address);
1047 }
1048
1049 let mut device_ranges = BTreeMap::new();
1050 let mut io_ranges = BTreeMap::new();
1051 let root_bus = Arc::new(Mutex::new(PciBus::new(0, 0, false)));
1052
1053 generate_pci_topology(
1054 root_bus.clone(),
1055 resources,
1056 &mut io_ranges,
1057 &mut device_ranges,
1058 &device_addrs,
1059 &mut devices,
1060 )?;
1061
1062 let mut root = PciRoot::new(
1063 vm,
1064 Arc::downgrade(&mmio_bus),
1065 mmio_base,
1066 mmio_register_bit_num,
1067 Arc::downgrade(&io_bus),
1068 root_bus,
1069 )
1070 .map_err(DeviceRegistrationError::CreateRoot)?;
1071 #[cfg_attr(windows, allow(unused_mut))]
1072 let mut pid_labels = BTreeMap::new();
1073
1074 let mut pci_irqs = Vec::new();
1076 let mut irqs: Vec<u32> = Vec::new();
1077
1078 let mut dev_pin_irq = BTreeMap::new();
1080
1081 for (dev_idx, (device, _jail)) in devices.iter_mut().enumerate() {
1082 let pci_address = device_addrs[dev_idx];
1083
1084 let irq = match device.preferred_irq() {
1085 PreferredIrq::Fixed { pin, gsi } => {
1086 resources.reserve_irq(gsi);
1088 Some((pin, gsi))
1089 }
1090 PreferredIrq::Any => {
1091 let pin = match pci_address.func % 4 {
1098 0 => PciInterruptPin::IntA,
1099 1 => PciInterruptPin::IntB,
1100 2 => PciInterruptPin::IntC,
1101 _ => PciInterruptPin::IntD,
1102 };
1103
1104 let pin_key = (pci_address.bus, pci_address.dev, pin);
1108 let irq_num = if let Some(irq_num) = dev_pin_irq.get(&pin_key) {
1109 *irq_num
1110 } else {
1111 let irq_num = if irqs.len() < max_irqs {
1114 let irq_num = resources
1115 .allocate_irq()
1116 .ok_or(DeviceRegistrationError::AllocateIrq)?;
1117 irqs.push(irq_num);
1118 irq_num
1119 } else {
1120 irqs[dev_idx % max_irqs]
1123 };
1124
1125 dev_pin_irq.insert(pin_key, irq_num);
1126 irq_num
1127 };
1128 Some((pin, irq_num))
1129 }
1130 PreferredIrq::None => {
1131 None
1133 }
1134 };
1135
1136 if let Some((pin, gsi)) = irq {
1137 let intx_event =
1138 devices::IrqLevelEvent::new().map_err(DeviceRegistrationError::EventCreate)?;
1139
1140 device.assign_irq(
1141 intx_event
1142 .try_clone()
1143 .map_err(DeviceRegistrationError::EventClone)?,
1144 pin,
1145 gsi,
1146 );
1147
1148 irq_chip
1149 .register_level_irq_event(gsi, &intx_event, IrqEventSource::from_device(device))
1150 .map_err(DeviceRegistrationError::RegisterIrqfd)?;
1151
1152 pci_irqs.push((pci_address, gsi, pin));
1153 }
1154 }
1155
1156 let devices = {
1161 let (sandboxed, non_sandboxed): (Vec<_>, Vec<_>) = devices
1162 .into_iter()
1163 .enumerate()
1164 .partition(|(_, (_, jail))| jail.is_some());
1165 sandboxed.into_iter().chain(non_sandboxed)
1166 };
1167
1168 let mut amls = BTreeMap::new();
1169 let mut gpe_scope_amls = BTreeMap::new();
1170 for (dev_idx, dev_value) in devices {
1171 #[cfg(any(target_os = "android", target_os = "linux"))]
1172 let (mut device, jail) = dev_value;
1173 #[cfg(windows)]
1174 let (mut device, _) = dev_value;
1175 let address = device_addrs[dev_idx];
1176
1177 let mut keep_rds = device.keep_rds();
1178 syslog::push_descriptors(&mut keep_rds);
1179 cros_tracing::push_descriptors!(&mut keep_rds);
1180 metrics::push_descriptors(&mut keep_rds);
1181 keep_rds.append(&mut vm.get_memory().as_raw_descriptors());
1182
1183 let ranges = io_ranges.remove(&dev_idx).unwrap_or_default();
1184 let device_ranges = device_ranges.remove(&dev_idx).unwrap_or_default();
1185 device
1186 .register_device_capabilities()
1187 .map_err(DeviceRegistrationError::RegisterDeviceCapabilities)?;
1188
1189 if let Some(vcfg_base) = vcfg_base {
1190 let (methods, shm) = device.generate_acpi_methods();
1191 if !methods.is_empty() {
1192 amls.insert(address, methods);
1193 }
1194 if let Some((offset, mmap)) = shm {
1195 let _ = vm.add_memory_region(
1196 GuestAddress(vcfg_base + offset as u64),
1197 Box::new(mmap),
1198 false,
1199 false,
1200 MemCacheType::CacheCoherent,
1201 );
1202 }
1203 }
1204 let gpe_nr = device.set_gpe(resources);
1205
1206 #[cfg(any(target_os = "android", target_os = "linux"))]
1207 let arced_dev: Arc<Mutex<dyn BusDevice>> = if let Some(jail) = jail {
1208 let proxy = ProxyDevice::new(
1209 device,
1210 jail,
1211 keep_rds,
1212 #[cfg(feature = "swap")]
1213 swap_controller,
1214 )
1215 .map_err(DeviceRegistrationError::ProxyDeviceCreation)?;
1216 pid_labels.insert(proxy.pid() as u32, proxy.debug_label());
1217 Arc::new(Mutex::new(proxy))
1218 } else {
1219 device.on_sandboxed();
1220 Arc::new(Mutex::new(device))
1221 };
1222 #[cfg(windows)]
1223 let arced_dev = {
1224 device.on_sandboxed();
1225 Arc::new(Mutex::new(device))
1226 };
1227 root.add_device(address, arced_dev.clone(), vm)
1228 .map_err(DeviceRegistrationError::PciRootAddDevice)?;
1229 for range in &ranges {
1230 mmio_bus
1231 .insert(arced_dev.clone(), range.addr, range.size)
1232 .map_err(DeviceRegistrationError::MmioInsert)?;
1233 }
1234
1235 for range in &device_ranges {
1236 mmio_bus
1237 .insert(arced_dev.clone(), range.addr, range.size)
1238 .map_err(DeviceRegistrationError::MmioInsert)?;
1239 }
1240
1241 if let Some(gpe_nr) = gpe_nr {
1242 if let Some(acpi_path) = root.acpi_path(&address) {
1243 let mut gpe_aml = Vec::new();
1244
1245 GpeScope {}.cast_to_aml_bytes(
1246 &mut gpe_aml,
1247 gpe_nr,
1248 format!("\\{acpi_path}").as_str(),
1249 );
1250 if !gpe_aml.is_empty() {
1251 gpe_scope_amls.insert(address, gpe_aml);
1252 }
1253 }
1254 }
1255 }
1256
1257 Ok((root, pci_irqs, pid_labels, amls, gpe_scope_amls))
1258}
1259
1260#[sorted]
1262#[derive(Error, Debug)]
1263pub enum LoadImageError {
1264 #[error("Alignment not a power of two: {0}")]
1265 BadAlignment(u64),
1266 #[error("Getting image size failed: {0}")]
1267 GetLen(io::Error),
1268 #[error("GuestMemory get slice failed: {0}")]
1269 GuestMemorySlice(GuestMemoryError),
1270 #[error("Image size too large: {0}")]
1271 ImageSizeTooLarge(u64),
1272 #[error("No suitable memory region found")]
1273 NoSuitableMemoryRegion,
1274 #[error("Reading image into memory failed: {0}")]
1275 ReadToMemory(io::Error),
1276 #[error("Cannot load zero-sized image")]
1277 ZeroSizedImage,
1278}
1279
1280pub fn load_image<F>(
1291 guest_mem: &GuestMemory,
1292 image: &mut F,
1293 guest_addr: GuestAddress,
1294 max_size: u64,
1295) -> Result<u32, LoadImageError>
1296where
1297 F: FileReadWriteAtVolatile + FileGetLen,
1298{
1299 let size = image.get_len().map_err(LoadImageError::GetLen)?;
1300
1301 if size > u32::MAX as u64 || size > max_size {
1302 return Err(LoadImageError::ImageSizeTooLarge(size));
1303 }
1304
1305 let size = size as u32;
1307
1308 let guest_slice = guest_mem
1309 .get_slice_at_addr(guest_addr, size as usize)
1310 .map_err(LoadImageError::GuestMemorySlice)?;
1311 image
1312 .read_exact_at_volatile(guest_slice, 0)
1313 .map_err(LoadImageError::ReadToMemory)?;
1314
1315 Ok(size)
1316}
1317
1318pub fn load_image_high<F>(
1333 guest_mem: &GuestMemory,
1334 image: &mut F,
1335 min_guest_addr: GuestAddress,
1336 max_guest_addr: GuestAddress,
1337 region_filter: Option<fn(&MemoryRegionInformation) -> bool>,
1338 align: u64,
1339) -> Result<(GuestAddress, u32), LoadImageError>
1340where
1341 F: FileReadWriteAtVolatile + FileGetLen,
1342{
1343 if !align.is_power_of_two() {
1344 return Err(LoadImageError::BadAlignment(align));
1345 }
1346
1347 let max_size = max_guest_addr.offset_from(min_guest_addr) & !(align - 1);
1348 let size = image.get_len().map_err(LoadImageError::GetLen)?;
1349
1350 if size == 0 {
1351 return Err(LoadImageError::ZeroSizedImage);
1352 }
1353
1354 if size > u32::MAX as u64 || size > max_size {
1355 return Err(LoadImageError::ImageSizeTooLarge(size));
1356 }
1357
1358 let mut regions: Vec<_> = guest_mem
1361 .regions()
1362 .filter(region_filter.unwrap_or(|_| true))
1363 .collect();
1364 regions.sort_unstable_by(|a, b| a.guest_addr.cmp(&b.guest_addr));
1365
1366 let guest_addr = regions
1369 .into_iter()
1370 .rev()
1371 .filter_map(|r| {
1372 let rgn_max_addr = r
1374 .guest_addr
1375 .checked_add((r.size as u64).checked_sub(1)?)?
1376 .min(max_guest_addr);
1377 let rgn_start_aligned = r.guest_addr.align(align)?;
1379 let image_addr = rgn_max_addr.checked_sub(size - 1)? & !(align - 1);
1381
1382 if image_addr >= rgn_start_aligned {
1384 Some(image_addr)
1385 } else {
1386 None
1387 }
1388 })
1389 .find(|&addr| addr >= min_guest_addr)
1390 .ok_or(LoadImageError::NoSuitableMemoryRegion)?;
1391
1392 let size = size as u32;
1394
1395 let guest_slice = guest_mem
1396 .get_slice_at_addr(guest_addr, size as usize)
1397 .map_err(LoadImageError::GuestMemorySlice)?;
1398 image
1399 .read_exact_at_volatile(guest_slice, 0)
1400 .map_err(LoadImageError::ReadToMemory)?;
1401
1402 Ok((guest_addr, size))
1403}
1404
1405#[derive(Clone, Debug, Default, Serialize, Deserialize, FromKeyValues, PartialEq, Eq)]
1407#[serde(deny_unknown_fields, rename_all = "kebab-case")]
1408pub struct SmbiosOptions {
1409 pub bios_vendor: Option<String>,
1411
1412 pub bios_version: Option<String>,
1414
1415 pub manufacturer: Option<String>,
1417
1418 pub product_name: Option<String>,
1420
1421 pub serial_number: Option<String>,
1423
1424 pub uuid: Option<Uuid>,
1426
1427 #[serde(default)]
1429 pub oem_strings: Vec<String>,
1430}
1431
1432#[cfg(test)]
1433mod tests {
1434 use serde_keyvalue::from_key_values;
1435 use tempfile::tempfile;
1436
1437 use super::*;
1438
1439 #[test]
1440 fn parse_pstore() {
1441 let res: Pstore = from_key_values("path=/some/path,size=16384").unwrap();
1442 assert_eq!(
1443 res,
1444 Pstore {
1445 path: "/some/path".into(),
1446 size: 16384,
1447 }
1448 );
1449
1450 let res = from_key_values::<Pstore>("path=/some/path");
1451 assert!(res.is_err());
1452
1453 let res = from_key_values::<Pstore>("size=16384");
1454 assert!(res.is_err());
1455
1456 let res = from_key_values::<Pstore>("");
1457 assert!(res.is_err());
1458 }
1459
1460 #[test]
1461 fn deserialize_cpuset_serde_kv() {
1462 let res: CpuSet = from_key_values("[0,4,7]").unwrap();
1463 assert_eq!(res, CpuSet::new(vec![0, 4, 7]));
1464
1465 let res: CpuSet = from_key_values("[9-12]").unwrap();
1466 assert_eq!(res, CpuSet::new(vec![9, 10, 11, 12]));
1467
1468 let res: CpuSet = from_key_values("[0,4,7,9-12,15]").unwrap();
1469 assert_eq!(res, CpuSet::new(vec![0, 4, 7, 9, 10, 11, 12, 15]));
1470 }
1471
1472 #[test]
1473 fn deserialize_serialize_cpuset_json() {
1474 let json_str = "[0,4,7]";
1475 let cpuset = CpuSet::new(vec![0, 4, 7]);
1476 let res: CpuSet = serde_json::from_str(json_str).unwrap();
1477 assert_eq!(res, cpuset);
1478 assert_eq!(serde_json::to_string(&cpuset).unwrap(), json_str);
1479
1480 let json_str = r#"["9-12"]"#;
1481 let cpuset = CpuSet::new(vec![9, 10, 11, 12]);
1482 let res: CpuSet = serde_json::from_str(json_str).unwrap();
1483 assert_eq!(res, cpuset);
1484 assert_eq!(serde_json::to_string(&cpuset).unwrap(), json_str);
1485
1486 let json_str = r#"[0,4,7,"9-12",15]"#;
1487 let cpuset = CpuSet::new(vec![0, 4, 7, 9, 10, 11, 12, 15]);
1488 let res: CpuSet = serde_json::from_str(json_str).unwrap();
1489 assert_eq!(res, cpuset);
1490 assert_eq!(serde_json::to_string(&cpuset).unwrap(), json_str);
1491 }
1492
1493 #[test]
1494 fn load_image_high_max_4g() {
1495 let mem = GuestMemory::new(&[
1496 (GuestAddress(0x0000_0000), 0x4000_0000), (GuestAddress(0x8000_0000), 0x4000_0000), ])
1499 .unwrap();
1500
1501 const TEST_IMAGE_SIZE: u64 = 1234;
1502 let mut test_image = tempfile().unwrap();
1503 test_image.set_len(TEST_IMAGE_SIZE).unwrap();
1504
1505 const TEST_ALIGN: u64 = 0x8000;
1506 let (addr, size) = load_image_high(
1507 &mem,
1508 &mut test_image,
1509 GuestAddress(0x8000),
1510 GuestAddress(0xFFFF_FFFF), None,
1512 TEST_ALIGN,
1513 )
1514 .unwrap();
1515
1516 assert_eq!(addr, GuestAddress(0xBFFF_8000));
1517 assert_eq!(addr.offset() % TEST_ALIGN, 0);
1518 assert_eq!(size, TEST_IMAGE_SIZE as u32);
1519 }
1520}