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;
61pub use hypervisor::CpuConfigArch;
62pub use hypervisor::HypervisorArch;
63use hypervisor::MemCacheType;
64pub use hypervisor::VcpuArch;
65pub use hypervisor::VcpuInitArch;
66use hypervisor::Vm;
67pub use hypervisor::VmArch;
68#[cfg(windows)]
69use jail::FakeMinijailStub as Minijail;
70#[cfg(any(target_os = "android", target_os = "linux"))]
71use minijail::Minijail;
72use remain::sorted;
73use resources::SystemAllocator;
74use resources::SystemAllocatorConfig;
75use serde::de::Visitor;
76use serde::Deserialize;
77use serde::Serialize;
78use serde_keyvalue::FromKeyValues;
79pub use serial::add_serial_devices;
80pub use serial::get_serial_cmdline;
81pub use serial::set_default_serial_parameters;
82pub use serial::GetSerialCmdlineError;
83pub use serial::SERIAL_ADDR;
84use sync::Condvar;
85use sync::Mutex;
86use thiserror::Error;
87use uuid::Uuid;
88use vm_control::BatControl;
89use vm_control::BatteryType;
90use vm_control::PmResource;
91use vm_memory::GuestAddress;
92use vm_memory::GuestMemory;
93use vm_memory::GuestMemoryError;
94use vm_memory::MemoryRegionInformation;
95use vm_memory::MemoryRegionOptions;
96
97cfg_if::cfg_if! {
98 if #[cfg(target_arch = "aarch64")] {
99 pub use devices::IrqChipAArch64 as IrqChipArch;
100 #[cfg(feature = "gdb")]
101 pub use gdbstub_arch::aarch64::AArch64 as GdbArch;
102 } else if #[cfg(target_arch = "riscv64")] {
103 pub use devices::IrqChipRiscv64 as IrqChipArch;
104 #[cfg(feature = "gdb")]
105 pub use gdbstub_arch::riscv::Riscv64 as GdbArch;
106 } else if #[cfg(target_arch = "x86_64")] {
107 pub use devices::IrqChipX86_64 as IrqChipArch;
108 #[cfg(feature = "gdb")]
109 pub use gdbstub_arch::x86::X86_64_SSE as GdbArch;
110 }
111}
112
113pub enum VmImage {
114 Kernel(File),
115 Bios(File),
116}
117
118#[derive(Clone, Debug, Deserialize, Serialize, FromKeyValues, PartialEq, Eq)]
119#[serde(deny_unknown_fields, rename_all = "kebab-case")]
120pub struct Pstore {
121 pub path: PathBuf,
122 pub size: u32,
123}
124
125#[derive(Clone, Copy, Debug, Serialize, Deserialize, FromKeyValues)]
126#[serde(deny_unknown_fields, rename_all = "kebab-case")]
127pub enum FdtPosition {
128 Start,
130 End,
132 AfterPayload,
134}
135
136#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
138pub struct CpuSet(Vec<usize>);
139
140impl CpuSet {
141 pub fn new<I: IntoIterator<Item = usize>>(cpus: I) -> Self {
142 CpuSet(cpus.into_iter().collect())
143 }
144
145 pub fn iter(&self) -> std::slice::Iter<'_, usize> {
146 self.0.iter()
147 }
148}
149
150impl FromIterator<usize> for CpuSet {
151 fn from_iter<T>(iter: T) -> Self
152 where
153 T: IntoIterator<Item = usize>,
154 {
155 CpuSet::new(iter)
156 }
157}
158
159#[cfg(target_arch = "aarch64")]
160fn mte_auto_default() -> bool {
161 true
162}
163
164#[cfg(target_arch = "aarch64")]
166#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
167#[serde(deny_unknown_fields, rename_all = "kebab-case")]
168pub struct MteConfig {
169 #[serde(default = "mte_auto_default")]
171 pub auto: bool,
172}
173
174#[cfg(target_arch = "aarch64")]
175impl Default for MteConfig {
176 fn default() -> Self {
177 MteConfig {
178 auto: mte_auto_default(),
179 }
180 }
181}
182
183#[cfg(target_arch = "aarch64")]
184fn sve_auto_default() -> bool {
185 true
186}
187
188#[cfg(target_arch = "aarch64")]
190#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
191#[serde(deny_unknown_fields, rename_all = "kebab-case")]
192pub struct SveConfig {
193 #[serde(default = "sve_auto_default")]
195 pub auto: bool,
196}
197
198#[cfg(target_arch = "aarch64")]
199impl Default for SveConfig {
200 fn default() -> Self {
201 SveConfig {
202 auto: sve_auto_default(),
203 }
204 }
205}
206
207#[cfg(all(target_os = "android", target_arch = "aarch64"))]
211#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize, FromKeyValues)]
212#[serde(deny_unknown_fields, rename_all = "kebab-case")]
213pub struct FfaConfig {
214 #[serde(default)]
216 pub auto: bool,
217}
218
219fn parse_cpu_range(s: &str, cpuset: &mut Vec<usize>) -> Result<(), String> {
220 fn parse_cpu(s: &str) -> Result<usize, String> {
221 s.parse()
222 .map_err(|_| format!("invalid CPU index {s} - index must be a non-negative integer"))
223 }
224
225 let (first_cpu, last_cpu) = match s.split_once('-') {
226 Some((first_cpu, last_cpu)) => {
227 let first_cpu = parse_cpu(first_cpu)?;
228 let last_cpu = parse_cpu(last_cpu)?;
229
230 if last_cpu < first_cpu {
231 return Err(format!(
232 "invalid CPU range {s} - ranges must be from low to high"
233 ));
234 }
235 (first_cpu, last_cpu)
236 }
237 None => {
238 let cpu = parse_cpu(s)?;
239 (cpu, cpu)
240 }
241 };
242
243 cpuset.extend(first_cpu..=last_cpu);
244
245 Ok(())
246}
247
248impl FromStr for CpuSet {
249 type Err = String;
250
251 fn from_str(s: &str) -> Result<Self, Self::Err> {
252 let mut cpuset = Vec::new();
253 for part in s.split(',') {
254 parse_cpu_range(part, &mut cpuset)?;
255 }
256 Ok(CpuSet::new(cpuset))
257 }
258}
259
260impl Deref for CpuSet {
261 type Target = Vec<usize>;
262
263 fn deref(&self) -> &Self::Target {
264 &self.0
265 }
266}
267
268impl IntoIterator for CpuSet {
269 type Item = usize;
270 type IntoIter = std::vec::IntoIter<Self::Item>;
271
272 fn into_iter(self) -> Self::IntoIter {
273 self.0.into_iter()
274 }
275}
276
277#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
279pub enum DevicePowerManagerConfig {
280 PkvmHvc,
283}
284
285impl FromStr for DevicePowerManagerConfig {
286 type Err = String;
287
288 fn from_str(s: &str) -> Result<Self, Self::Err> {
289 match s {
290 "pkvm-hvc" => Ok(Self::PkvmHvc),
291 _ => Err(format!("DevicePowerManagerConfig '{s}' not supported")),
292 }
293 }
294}
295
296impl<'de> Deserialize<'de> for CpuSet {
299 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
300 where
301 D: serde::Deserializer<'de>,
302 {
303 struct CpuSetVisitor;
304 impl<'de> Visitor<'de> for CpuSetVisitor {
305 type Value = CpuSet;
306
307 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
308 formatter.write_str("CpuSet")
309 }
310
311 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
312 where
313 A: serde::de::SeqAccess<'de>,
314 {
315 #[derive(Deserialize)]
316 #[serde(untagged)]
317 enum CpuSetValue<'a> {
318 Single(usize),
319 Range(&'a str),
320 }
321
322 let mut cpus = Vec::new();
323 while let Some(cpuset) = seq.next_element::<CpuSetValue>()? {
324 match cpuset {
325 CpuSetValue::Single(cpu) => cpus.push(cpu),
326 CpuSetValue::Range(range) => {
327 parse_cpu_range(range, &mut cpus).map_err(serde::de::Error::custom)?;
328 }
329 }
330 }
331
332 Ok(CpuSet::new(cpus))
333 }
334 }
335
336 deserializer.deserialize_seq(CpuSetVisitor)
337 }
338}
339
340impl Serialize for CpuSet {
342 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
343 where
344 S: serde::Serializer,
345 {
346 use serde::ser::SerializeSeq;
347
348 let mut seq = serializer.serialize_seq(None)?;
349
350 let mut serialize_range = |start: usize, end: usize| -> Result<(), S::Error> {
352 if start == end {
353 seq.serialize_element(&start)?;
354 } else {
355 seq.serialize_element(&format!("{start}-{end}"))?;
356 }
357
358 Ok(())
359 };
360
361 let mut range = None;
363 for core in &self.0 {
364 range = match range {
365 None => Some((core, core)),
366 Some((start, end)) if *end == *core - 1 => Some((start, core)),
367 Some((start, end)) => {
368 serialize_range(*start, *end)?;
369 Some((core, core))
370 }
371 };
372 }
373
374 if let Some((start, end)) = range {
375 serialize_range(*start, *end)?;
376 }
377
378 seq.end()
379 }
380}
381
382#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
384pub enum VcpuAffinity {
385 Global(CpuSet),
387 PerVcpu(BTreeMap<usize, CpuSet>),
392}
393
394#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, FromKeyValues)]
396pub struct MemoryRegionConfig {
397 pub start: u64,
398 pub size: Option<u64>,
399}
400
401#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, FromKeyValues)]
403pub struct PciConfig {
404 #[cfg(target_arch = "aarch64")]
406 pub cam: Option<MemoryRegionConfig>,
407 #[cfg(target_arch = "x86_64")]
409 pub ecam: Option<MemoryRegionConfig>,
410 pub mem: Option<MemoryRegionConfig>,
412}
413
414pub const DEFAULT_CPU_CAPACITY: u32 = 1024;
415
416#[sorted]
417#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
418pub struct VcpuProperties {
419 pub capacity: Option<u32>,
420 pub dynamic_power_coefficient: Option<u32>,
421 pub frequencies: Vec<u32>,
422 #[cfg(all(
423 target_arch = "aarch64",
424 any(target_os = "android", target_os = "linux")
425 ))]
426 pub normalized_cpu_ipc_ratio: Option<u32>,
427 #[cfg(all(
428 target_arch = "aarch64",
429 any(target_os = "android", target_os = "linux")
430 ))]
431 pub vcpu_domain: Option<u32>,
432 #[cfg(all(
433 target_arch = "aarch64",
434 any(target_os = "android", target_os = "linux")
435 ))]
436 pub vcpu_domain_path: Option<PathBuf>,
437}
438
439pub fn derive_vcpu_properties(
441 vcpu_count: usize,
442 vcpu_capacity: &std::collections::BTreeMap<usize, u32>,
443 dynamic_power_coefficient: &std::collections::BTreeMap<usize, u32>,
444 vcpu_frequencies: &std::collections::BTreeMap<usize, Vec<u32>>,
445 #[cfg(all(
446 target_arch = "aarch64",
447 any(target_os = "android", target_os = "linux")
448 ))]
449 normalized_cpu_ipc_ratio: &std::collections::BTreeMap<usize, u32>,
450 #[cfg(all(
451 target_arch = "aarch64",
452 any(target_os = "android", target_os = "linux")
453 ))]
454 vcpu_domain: &std::collections::BTreeMap<usize, u32>,
455 #[cfg(all(
456 target_arch = "aarch64",
457 any(target_os = "android", target_os = "linux")
458 ))]
459 vcpu_domain_path: &std::collections::BTreeMap<usize, std::path::PathBuf>,
460) -> std::collections::BTreeMap<usize, VcpuProperties> {
461 let mut vcpu_properties = std::collections::BTreeMap::new();
462 for vcpu_id in 0..vcpu_count {
463 let vcpu_prop_capacity = vcpu_capacity.get(&vcpu_id).copied();
464
465 vcpu_properties.insert(
466 vcpu_id,
467 VcpuProperties {
468 capacity: vcpu_prop_capacity,
469 frequencies: vcpu_frequencies.get(&vcpu_id).cloned().unwrap_or_default(),
470 dynamic_power_coefficient: dynamic_power_coefficient.get(&vcpu_id).copied(),
471 #[cfg(all(
472 target_arch = "aarch64",
473 any(target_os = "android", target_os = "linux")
474 ))]
475 normalized_cpu_ipc_ratio: normalized_cpu_ipc_ratio.get(&vcpu_id).copied(),
476 #[cfg(all(
477 target_arch = "aarch64",
478 any(target_os = "android", target_os = "linux")
479 ))]
480 vcpu_domain: vcpu_domain.get(&vcpu_id).copied(),
481 #[cfg(all(
482 target_arch = "aarch64",
483 any(target_os = "android", target_os = "linux")
484 ))]
485 vcpu_domain_path: vcpu_domain_path.get(&vcpu_id).cloned(),
486 },
487 );
488 }
489 vcpu_properties
490}
491
492#[sorted]
495pub struct VmComponents {
496 pub acpi_sdts: Vec<SDT>,
497 pub android_fstab: Option<File>,
498 pub boot_cpu: usize,
499 pub bootorder_fw_cfg_blob: Vec<u8>,
500 #[cfg(target_arch = "x86_64")]
501 pub break_linux_pci_config_io: bool,
502
503 pub delay_rt: bool,
504 pub dev_pm: Option<DevicePowerManagerConfig>,
505 pub extra_kernel_params: Vec<String>,
506 #[cfg(target_arch = "x86_64")]
507 pub force_s2idle: bool,
508 pub fw_cfg_enable: bool,
509 pub fw_cfg_parameters: Vec<FwCfgParameters>,
510 pub host_cpu_topology: bool,
511 pub hugepages: bool,
512 pub hv_cfg: hypervisor::Config,
513 pub initrd_image: Option<File>,
514 pub itmt: bool,
515 pub memory_size: u64,
516 #[cfg(target_arch = "aarch64")]
517 pub nested: hypervisor::NestedMode,
518 pub no_i8042: bool,
519 pub no_rtc: bool,
520 pub no_smt: bool,
521
522 pub pci_config: PciConfig,
523 pub pflash_block_size: u32,
524 pub pflash_image: Option<File>,
525 pub pstore: Option<Pstore>,
526 pub pvm_fw: Option<File>,
529 pub rt_cpus: CpuSet,
530 #[cfg(target_arch = "x86_64")]
531 pub smbios: SmbiosOptions,
532 pub smccc_trng: bool,
533 #[cfg(target_arch = "aarch64")]
534 pub sve_config: SveConfig,
535 pub swiotlb: Option<u64>,
536 pub vcpu_affinity: Option<VcpuAffinity>,
537 pub vcpu_clusters: Vec<CpuSet>,
539 pub vcpu_properties: BTreeMap<usize, VcpuProperties>,
540 #[cfg(any(target_os = "android", target_os = "linux"))]
541 pub vfio_platform_pm: bool,
542 #[cfg(all(
543 target_arch = "aarch64",
544 any(target_os = "android", target_os = "linux")
545 ))]
546 pub virt_cpufreq_v2: bool,
547 pub vm_image: VmImage,
548}
549
550#[sorted]
552pub struct RunnableLinuxVm {
553 pub bat_control: Option<BatControl>,
554 pub delay_rt: bool,
555 pub devices_thread: Option<std::thread::JoinHandle<()>>,
556 pub hotplug_bus: BTreeMap<u8, Arc<Mutex<dyn HotPlugBus>>>,
557 pub hypercall_bus: Arc<Bus>,
558 pub io_bus: Arc<Bus>,
559 pub irq_chip: Arc<dyn IrqChipArch>,
560 pub mmio_bus: Arc<Bus>,
561 pub no_smt: bool,
562 pub pid_debug_label_map: BTreeMap<u32, String>,
563 #[cfg(any(target_os = "android", target_os = "linux"))]
564 pub platform_devices: Vec<Arc<Mutex<dyn BusDevice>>>,
565 pub pm: Option<Arc<Mutex<dyn PmResource + Send>>>,
566 pub resume_notify_devices: Vec<Arc<Mutex<dyn BusResumeDevice>>>,
568 pub root_config: Arc<Mutex<PciRoot>>,
569 pub rt_cpus: CpuSet,
570 pub suspend_tube: (Arc<Mutex<SendTube>>, RecvTube),
571 pub vcpu_affinity: Option<VcpuAffinity>,
572 pub vcpu_count: usize,
573 pub vcpu_init: Vec<VcpuInitArch>,
574 pub vcpus: Option<Vec<Arc<dyn VcpuArch>>>,
577 pub vm: Arc<dyn VmArch>,
578 pub vm_request_tubes: Vec<Tube>,
579}
580
581pub struct VirtioDeviceStub {
583 pub dev: Box<dyn VirtioDevice>,
584 pub jail: Option<Minijail>,
585}
586
587pub trait LinuxArch {
590 type Error: StdError;
591 type ArchMemoryLayout;
592
593 fn arch_memory_layout(
596 components: &VmComponents,
597 ) -> std::result::Result<Self::ArchMemoryLayout, Self::Error>;
598
599 fn guest_memory_layout(
606 components: &VmComponents,
607 arch_memory_layout: &Self::ArchMemoryLayout,
608 hypervisor: &impl hypervisor::Hypervisor,
609 ) -> std::result::Result<Vec<(GuestAddress, u64, MemoryRegionOptions)>, Self::Error>;
610
611 fn get_system_allocator_config(
621 vm: &dyn Vm,
622 arch_memory_layout: &Self::ArchMemoryLayout,
623 ) -> SystemAllocatorConfig;
624
625 fn build_vm(
646 components: VmComponents,
647 arch_memory_layout: &Self::ArchMemoryLayout,
648 vm_evt_wrtube: &SendTube,
649 system_allocator: &mut SystemAllocator,
650 serial_parameters: &BTreeMap<(SerialHardware, u8), SerialParameters>,
651 serial_jail: Option<Minijail>,
652 battery: (Option<BatteryType>, Option<Minijail>),
653 vm: Arc<dyn VmArch>,
654 ramoops_region: Option<pstore::RamoopsRegion>,
655 devices: Vec<(Box<dyn BusDeviceObj>, Option<Minijail>)>,
656 irq_chip: Arc<dyn IrqChipArch>,
657 vcpu_ids: &mut Vec<usize>,
658 dump_device_tree_blob: Option<PathBuf>,
659 debugcon_jail: Option<Minijail>,
660 #[cfg(target_arch = "x86_64")] pflash_jail: Option<Minijail>,
661 #[cfg(target_arch = "x86_64")] fw_cfg_jail: Option<Minijail>,
662 #[cfg(feature = "swap")] swap_controller: &mut Option<swap::SwapController>,
663 guest_suspended_cvar: Option<Arc<(Mutex<bool>, Condvar)>>,
664 device_tree_overlays: Vec<DtbOverlay>,
665 fdt_position: Option<FdtPosition>,
666 no_pmu: bool,
667 ) -> std::result::Result<RunnableLinuxVm, Self::Error>;
668
669 fn configure_vcpu(
682 vm: &dyn Vm,
683 hypervisor: &dyn HypervisorArch,
684 irq_chip: &dyn IrqChipArch,
685 vcpu: &dyn VcpuArch,
686 vcpu_init: VcpuInitArch,
687 vcpu_id: usize,
688 num_vcpus: usize,
689 cpu_config: Option<CpuConfigArch>,
690 ) -> Result<(), Self::Error>;
691
692 fn register_pci_device(
694 linux: &mut RunnableLinuxVm,
695 device: Box<dyn PciDevice>,
696 #[cfg(any(target_os = "android", target_os = "linux"))] minijail: Option<Minijail>,
697 resources: &mut SystemAllocator,
698 hp_control_tube: &mpsc::Sender<PciRootCommand>,
699 #[cfg(feature = "swap")] swap_controller: &mut Option<swap::SwapController>,
700 ) -> Result<PciAddress, Self::Error>;
701
702 fn get_host_cpu_frequencies_khz() -> Result<BTreeMap<usize, Vec<u32>>, Self::Error>;
704
705 fn get_host_cpu_max_freq_khz() -> Result<BTreeMap<usize, u32>, Self::Error>;
707
708 fn get_host_cpu_capacity() -> Result<BTreeMap<usize, u32>, Self::Error>;
710
711 fn get_host_cpu_clusters() -> Result<Vec<CpuSet>, Self::Error>;
713}
714
715#[cfg(feature = "gdb")]
716pub trait GdbOps {
717 type Error: StdError;
718
719 fn read_registers(vcpu: &dyn VcpuArch) -> Result<<GdbArch as Arch>::Registers, Self::Error>;
721
722 fn write_registers(
724 vcpu: &dyn VcpuArch,
725 regs: &<GdbArch as Arch>::Registers,
726 ) -> Result<(), Self::Error>;
727
728 fn read_memory(
730 vcpu: &dyn VcpuArch,
731 guest_mem: &GuestMemory,
732 vaddr: GuestAddress,
733 len: usize,
734 ) -> Result<Vec<u8>, Self::Error>;
735
736 fn write_memory(
738 vcpu: &dyn VcpuArch,
739 guest_mem: &GuestMemory,
740 vaddr: GuestAddress,
741 buf: &[u8],
742 ) -> Result<(), Self::Error>;
743
744 fn read_register(
748 vcpu: &dyn VcpuArch,
749 reg_id: <GdbArch as Arch>::RegId,
750 ) -> Result<Vec<u8>, Self::Error>;
751
752 fn write_register(
754 vcpu: &dyn VcpuArch,
755 reg_id: <GdbArch as Arch>::RegId,
756 data: &[u8],
757 ) -> Result<(), Self::Error>;
758
759 fn enable_singlestep(vcpu: &dyn VcpuArch) -> Result<(), Self::Error>;
761
762 fn get_max_hw_breakpoints(vcpu: &dyn VcpuArch) -> Result<usize, Self::Error>;
764
765 fn set_hw_breakpoints(
767 vcpu: &dyn VcpuArch,
768 breakpoints: &[GuestAddress],
769 ) -> Result<(), Self::Error>;
770}
771
772#[sorted]
774#[derive(Error, Debug)]
775pub enum DeviceRegistrationError {
776 #[error("no more addresses are available")]
778 AddrsExhausted,
779 #[error("Allocating device addresses: {0}")]
781 AllocateDeviceAddrs(PciDeviceError),
782 #[error("Allocating IO addresses: {0}")]
784 AllocateIoAddrs(PciDeviceError),
785 #[error("Allocating IO resource: {0}")]
787 AllocateIoResource(resources::Error),
788 #[error("Allocating IRQ number")]
790 AllocateIrq,
791 #[cfg(any(target_os = "android", target_os = "linux"))]
793 #[error("Allocating IRQ resource: {0}")]
794 AllocateIrqResource(devices::vfio::VfioError),
795 #[error("failed to attach the device to its power domain: {0}")]
796 AttachDevicePowerDomain(anyhow::Error),
797 #[error("pci topology is broken")]
799 BrokenPciTopology,
800 #[cfg(any(target_os = "android", target_os = "linux"))]
802 #[error("failed to clone jail: {0}")]
803 CloneJail(minijail::Error),
804 #[error("unable to add device to kernel command line: {0}")]
806 Cmdline(kernel_cmdline::Error),
807 #[error("failed to configure window size: {0}")]
809 ConfigureWindowSize(PciDeviceError),
810 #[error("failed to create pipe: {0}")]
812 CreatePipe(base::Error),
813 #[error("failed to create pci root: {0}")]
815 CreateRoot(anyhow::Error),
816 #[error("failed to create serial device: {0}")]
818 CreateSerialDevice(devices::SerialError),
819 #[error("failed to create tube: {0}")]
821 CreateTube(base::TubeError),
822 #[error("failed to clone event: {0}")]
824 EventClone(base::Error),
825 #[error("failed to create event: {0}")]
827 EventCreate(base::Error),
828 #[error("failed to generate ACPI content")]
830 GenerateAcpi,
831 #[error("no more IRQs are available")]
833 IrqsExhausted,
834 #[error("cannot match VFIO device to DT node due to a missing symbol")]
836 MissingDeviceTreeSymbol,
837 #[error("missing required serial device {0}")]
839 MissingRequiredSerialDevice(u8),
840 #[error("failed to add to mmio bus: {0}")]
842 MmioInsert(BusError),
843 #[error("failed to insert device into PCI root: {0}")]
845 PciRootAddDevice(PciDeviceError),
846 #[cfg(any(target_os = "android", target_os = "linux"))]
847 #[error("failed to create proxy device: {0}")]
849 ProxyDeviceCreation(devices::ProxyError),
850 #[cfg(any(target_os = "android", target_os = "linux"))]
851 #[error("failed to register battery device to VM: {0}")]
853 RegisterBattery(devices::BatteryError),
854 #[error("failed to register PCI device to pci root bus")]
856 RegisterDevice(SendError<PciRootCommand>),
857 #[error("could not register PCI device capabilities: {0}")]
859 RegisterDeviceCapabilities(PciDeviceError),
860 #[error("failed to register ioevent to VM: {0}")]
862 RegisterIoevent(base::Error),
863 #[error("failed to register irq event to VM: {0}")]
865 RegisterIrqfd(base::Error),
866 #[error("Setting up VFIO platform IRQ: {0}")]
868 SetupVfioPlatformIrq(anyhow::Error),
869}
870
871pub fn configure_pci_device(
873 linux: &mut RunnableLinuxVm,
874 mut device: Box<dyn PciDevice>,
875 #[cfg(any(target_os = "android", target_os = "linux"))] jail: Option<Minijail>,
876 resources: &mut SystemAllocator,
877 hp_control_tube: &mpsc::Sender<PciRootCommand>,
878 #[cfg(feature = "swap")] swap_controller: &mut Option<swap::SwapController>,
879) -> Result<PciAddress, DeviceRegistrationError> {
880 let pci_address = device
882 .allocate_address(resources)
883 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
884
885 let mmio_ranges = device
887 .allocate_io_bars(resources)
888 .map_err(DeviceRegistrationError::AllocateIoAddrs)?;
889
890 let device_ranges = device
892 .allocate_device_bars(resources)
893 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
894
895 if let Some(pci_bus) = device.get_new_pci_bus() {
897 hp_control_tube
898 .send(PciRootCommand::AddBridge(pci_bus))
899 .map_err(DeviceRegistrationError::RegisterDevice)?;
900 let bar_ranges = Vec::new();
901 device
902 .configure_bridge_window(resources, &bar_ranges)
903 .map_err(DeviceRegistrationError::ConfigureWindowSize)?;
904 }
905
906 let intx_event = devices::IrqLevelEvent::new().map_err(DeviceRegistrationError::EventCreate)?;
908
909 if let PreferredIrq::Fixed { pin, gsi } = device.preferred_irq() {
910 resources.reserve_irq(gsi);
911
912 device.assign_irq(
913 intx_event
914 .try_clone()
915 .map_err(DeviceRegistrationError::EventClone)?,
916 pin,
917 gsi,
918 );
919
920 linux
921 .irq_chip
922 .register_level_irq_event(gsi, &intx_event, IrqEventSource::from_device(&device))
923 .map_err(DeviceRegistrationError::RegisterIrqfd)?;
924 }
925
926 let mut keep_rds = device.keep_rds();
927 syslog::push_descriptors(&mut keep_rds);
928 cros_tracing::push_descriptors!(&mut keep_rds);
929 metrics::push_descriptors(&mut keep_rds);
930
931 device
932 .register_device_capabilities()
933 .map_err(DeviceRegistrationError::RegisterDeviceCapabilities)?;
934
935 #[cfg(any(target_os = "android", target_os = "linux"))]
936 let arced_dev: Arc<Mutex<dyn BusDevice>> = if let Some(jail) = jail {
937 let proxy = ProxyDevice::new(
938 device,
939 jail,
940 keep_rds,
941 #[cfg(feature = "swap")]
942 swap_controller,
943 )
944 .map_err(DeviceRegistrationError::ProxyDeviceCreation)?;
945 linux
946 .pid_debug_label_map
947 .insert(proxy.pid() as u32, proxy.debug_label());
948 Arc::new(Mutex::new(proxy))
949 } else {
950 device.on_sandboxed();
951 Arc::new(Mutex::new(device))
952 };
953
954 #[cfg(windows)]
955 let arced_dev = {
956 device.on_sandboxed();
957 Arc::new(Mutex::new(device))
958 };
959
960 #[cfg(any(target_os = "android", target_os = "linux"))]
961 hp_control_tube
962 .send(PciRootCommand::Add(pci_address, arced_dev.clone()))
963 .map_err(DeviceRegistrationError::RegisterDevice)?;
964
965 for range in &mmio_ranges {
966 linux
967 .mmio_bus
968 .insert(arced_dev.clone(), range.addr, range.size)
969 .map_err(DeviceRegistrationError::MmioInsert)?;
970 }
971
972 for range in &device_ranges {
973 linux
974 .mmio_bus
975 .insert(arced_dev.clone(), range.addr, range.size)
976 .map_err(DeviceRegistrationError::MmioInsert)?;
977 }
978
979 Ok(pci_address)
980}
981
982fn generate_pci_topology(
984 parent_bus: Arc<Mutex<PciBus>>,
985 resources: &mut SystemAllocator,
986 io_ranges: &mut BTreeMap<usize, Vec<BarRange>>,
987 device_ranges: &mut BTreeMap<usize, Vec<BarRange>>,
988 device_addrs: &[PciAddress],
989 devices: &mut Vec<(Box<dyn PciDevice>, Option<Minijail>)>,
990) -> Result<(Vec<BarRange>, u8), DeviceRegistrationError> {
991 let mut bar_ranges = Vec::new();
992 let bus_num = parent_bus.lock().get_bus_num();
993 let mut subordinate_bus = bus_num;
994 for (dev_idx, addr) in device_addrs.iter().enumerate() {
995 if addr.bus == bus_num {
997 if let Some(child_bus) = devices[dev_idx].0.get_new_pci_bus() {
1000 let (child_bar_ranges, child_sub_bus) = generate_pci_topology(
1001 child_bus.clone(),
1002 resources,
1003 io_ranges,
1004 device_ranges,
1005 device_addrs,
1006 devices,
1007 )?;
1008 let device = &mut devices[dev_idx].0;
1009 parent_bus
1010 .lock()
1011 .add_child_bus(child_bus.clone())
1012 .map_err(|_| DeviceRegistrationError::BrokenPciTopology)?;
1013 let bridge_window = device
1014 .configure_bridge_window(resources, &child_bar_ranges)
1015 .map_err(DeviceRegistrationError::ConfigureWindowSize)?;
1016 bar_ranges.extend(bridge_window);
1017
1018 let ranges = device
1019 .allocate_io_bars(resources)
1020 .map_err(DeviceRegistrationError::AllocateIoAddrs)?;
1021 io_ranges.insert(dev_idx, ranges.clone());
1022 bar_ranges.extend(ranges);
1023
1024 let ranges = device
1025 .allocate_device_bars(resources)
1026 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
1027 device_ranges.insert(dev_idx, ranges.clone());
1028 bar_ranges.extend(ranges);
1029
1030 device.set_subordinate_bus(child_sub_bus);
1031
1032 subordinate_bus = std::cmp::max(subordinate_bus, child_sub_bus);
1033 }
1034 }
1035 }
1036
1037 for (dev_idx, addr) in device_addrs.iter().enumerate() {
1038 if addr.bus == bus_num {
1039 let device = &mut devices[dev_idx].0;
1040 if device.get_new_pci_bus().is_none() {
1042 let ranges = device
1043 .allocate_io_bars(resources)
1044 .map_err(DeviceRegistrationError::AllocateIoAddrs)?;
1045 io_ranges.insert(dev_idx, ranges.clone());
1046 bar_ranges.extend(ranges);
1047
1048 let ranges = device
1049 .allocate_device_bars(resources)
1050 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
1051 device_ranges.insert(dev_idx, ranges.clone());
1052 bar_ranges.extend(ranges);
1053 }
1054 }
1055 }
1056 Ok((bar_ranges, subordinate_bus))
1057}
1058
1059pub fn assign_pci_addresses(
1061 devices: &mut [(Box<dyn BusDeviceObj>, Option<Minijail>)],
1062 resources: &mut SystemAllocator,
1063) -> Result<(), DeviceRegistrationError> {
1064 for pci_device in devices
1066 .iter_mut()
1067 .filter_map(|(device, _jail)| device.as_pci_device_mut())
1068 .filter(|pci_device| pci_device.preferred_address().is_some())
1069 {
1070 let _ = pci_device
1071 .allocate_address(resources)
1072 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
1073 }
1074
1075 for pci_device in devices
1077 .iter_mut()
1078 .filter_map(|(device, _jail)| device.as_pci_device_mut())
1079 .filter(|pci_device| pci_device.preferred_address().is_none())
1080 {
1081 let _ = pci_device
1082 .allocate_address(resources)
1083 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
1084 }
1085
1086 Ok(())
1087}
1088
1089pub fn generate_pci_root(
1091 mut devices: Vec<(Box<dyn PciDevice>, Option<Minijail>)>,
1092 irq_chip: &dyn IrqChip,
1093 mmio_bus: Arc<Bus>,
1094 mmio_base: GuestAddress,
1095 mmio_register_bit_num: usize,
1096 io_bus: Arc<Bus>,
1097 resources: &mut SystemAllocator,
1098 mut vm: &dyn Vm,
1099 max_irqs: usize,
1100 vcfg_base: Option<u64>,
1101 #[cfg(feature = "swap")] swap_controller: &mut Option<swap::SwapController>,
1102) -> Result<
1103 (
1104 PciRoot,
1105 Vec<(PciAddress, u32, PciInterruptPin)>,
1106 BTreeMap<u32, String>,
1107 BTreeMap<PciAddress, Vec<u8>>,
1108 BTreeMap<PciAddress, Vec<u8>>,
1109 ),
1110 DeviceRegistrationError,
1111> {
1112 let mut device_addrs = Vec::new();
1113
1114 for (device, _jail) in devices.iter_mut() {
1115 let address = device
1116 .allocate_address(resources)
1117 .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
1118 device_addrs.push(address);
1119 }
1120
1121 let mut device_ranges = BTreeMap::new();
1122 let mut io_ranges = BTreeMap::new();
1123 let root_bus = Arc::new(Mutex::new(PciBus::new(0, 0, false)));
1124
1125 generate_pci_topology(
1126 root_bus.clone(),
1127 resources,
1128 &mut io_ranges,
1129 &mut device_ranges,
1130 &device_addrs,
1131 &mut devices,
1132 )?;
1133
1134 let mut root = PciRoot::new(
1135 vm,
1136 Arc::downgrade(&mmio_bus),
1137 mmio_base,
1138 mmio_register_bit_num,
1139 Arc::downgrade(&io_bus),
1140 root_bus,
1141 )
1142 .map_err(DeviceRegistrationError::CreateRoot)?;
1143 #[cfg_attr(windows, allow(unused_mut))]
1144 let mut pid_labels = BTreeMap::new();
1145
1146 let mut pci_irqs = Vec::new();
1148 let mut irqs: Vec<u32> = Vec::new();
1149
1150 let mut dev_pin_irq = BTreeMap::new();
1152
1153 for (dev_idx, (device, _jail)) in devices.iter_mut().enumerate() {
1154 let pci_address = device_addrs[dev_idx];
1155
1156 let irq = match device.preferred_irq() {
1157 PreferredIrq::Fixed { pin, gsi } => {
1158 resources.reserve_irq(gsi);
1160 Some((pin, gsi))
1161 }
1162 PreferredIrq::Any => {
1163 let pin = match pci_address.func % 4 {
1170 0 => PciInterruptPin::IntA,
1171 1 => PciInterruptPin::IntB,
1172 2 => PciInterruptPin::IntC,
1173 _ => PciInterruptPin::IntD,
1174 };
1175
1176 let pin_key = (pci_address.bus, pci_address.dev, pin);
1180 let irq_num = if let Some(irq_num) = dev_pin_irq.get(&pin_key) {
1181 *irq_num
1182 } else {
1183 let irq_num = if irqs.len() < max_irqs {
1186 let irq_num = resources
1187 .allocate_irq()
1188 .ok_or(DeviceRegistrationError::AllocateIrq)?;
1189 irqs.push(irq_num);
1190 irq_num
1191 } else {
1192 irqs[dev_idx % max_irqs]
1195 };
1196
1197 dev_pin_irq.insert(pin_key, irq_num);
1198 irq_num
1199 };
1200 Some((pin, irq_num))
1201 }
1202 PreferredIrq::None => {
1203 None
1205 }
1206 };
1207
1208 if let Some((pin, gsi)) = irq {
1209 let intx_event =
1210 devices::IrqLevelEvent::new().map_err(DeviceRegistrationError::EventCreate)?;
1211
1212 device.assign_irq(
1213 intx_event
1214 .try_clone()
1215 .map_err(DeviceRegistrationError::EventClone)?,
1216 pin,
1217 gsi,
1218 );
1219
1220 irq_chip
1221 .register_level_irq_event(gsi, &intx_event, IrqEventSource::from_device(device))
1222 .map_err(DeviceRegistrationError::RegisterIrqfd)?;
1223
1224 pci_irqs.push((pci_address, gsi, pin));
1225 }
1226 }
1227
1228 let devices = {
1233 let (sandboxed, non_sandboxed): (Vec<_>, Vec<_>) = devices
1234 .into_iter()
1235 .enumerate()
1236 .partition(|(_, (_, jail))| jail.is_some());
1237 sandboxed.into_iter().chain(non_sandboxed)
1238 };
1239
1240 let mut amls = BTreeMap::new();
1241 let mut gpe_scope_amls = BTreeMap::new();
1242 for (dev_idx, dev_value) in devices {
1243 #[cfg(any(target_os = "android", target_os = "linux"))]
1244 let (mut device, jail) = dev_value;
1245 #[cfg(windows)]
1246 let (mut device, _) = dev_value;
1247 let address = device_addrs[dev_idx];
1248
1249 let mut keep_rds = device.keep_rds();
1250 syslog::push_descriptors(&mut keep_rds);
1251 cros_tracing::push_descriptors!(&mut keep_rds);
1252 metrics::push_descriptors(&mut keep_rds);
1253 keep_rds.append(&mut vm.get_memory().as_raw_descriptors());
1254
1255 let ranges = io_ranges.remove(&dev_idx).unwrap_or_default();
1256 let device_ranges = device_ranges.remove(&dev_idx).unwrap_or_default();
1257 device
1258 .register_device_capabilities()
1259 .map_err(DeviceRegistrationError::RegisterDeviceCapabilities)?;
1260
1261 if let Some(vcfg_base) = vcfg_base {
1262 let (methods, shm) = device.generate_acpi_methods();
1263 if !methods.is_empty() {
1264 amls.insert(address, methods);
1265 }
1266 if let Some((offset, mmap)) = shm {
1267 let _ = vm.add_memory_region(
1268 GuestAddress(vcfg_base + offset as u64),
1269 Box::new(mmap),
1270 false,
1271 false,
1272 MemCacheType::CacheCoherent,
1273 );
1274 }
1275 }
1276 let gpe_nr = device.set_gpe(resources);
1277
1278 #[cfg(any(target_os = "android", target_os = "linux"))]
1279 let arced_dev: Arc<Mutex<dyn BusDevice>> = if let Some(jail) = jail {
1280 let proxy = ProxyDevice::new(
1281 device,
1282 jail,
1283 keep_rds,
1284 #[cfg(feature = "swap")]
1285 swap_controller,
1286 )
1287 .map_err(DeviceRegistrationError::ProxyDeviceCreation)?;
1288 pid_labels.insert(proxy.pid() as u32, proxy.debug_label());
1289 Arc::new(Mutex::new(proxy))
1290 } else {
1291 device.on_sandboxed();
1292 Arc::new(Mutex::new(device))
1293 };
1294 #[cfg(windows)]
1295 let arced_dev = {
1296 device.on_sandboxed();
1297 Arc::new(Mutex::new(device))
1298 };
1299 root.add_device(address, arced_dev.clone(), &mut vm)
1300 .map_err(DeviceRegistrationError::PciRootAddDevice)?;
1301 for range in &ranges {
1302 mmio_bus
1303 .insert(arced_dev.clone(), range.addr, range.size)
1304 .map_err(DeviceRegistrationError::MmioInsert)?;
1305 }
1306
1307 for range in &device_ranges {
1308 mmio_bus
1309 .insert(arced_dev.clone(), range.addr, range.size)
1310 .map_err(DeviceRegistrationError::MmioInsert)?;
1311 }
1312
1313 if let Some(gpe_nr) = gpe_nr {
1314 if let Some(acpi_path) = root.acpi_path(&address) {
1315 let mut gpe_aml = Vec::new();
1316
1317 GpeScope {}.cast_to_aml_bytes(
1318 &mut gpe_aml,
1319 gpe_nr,
1320 format!("\\{acpi_path}").as_str(),
1321 );
1322 if !gpe_aml.is_empty() {
1323 gpe_scope_amls.insert(address, gpe_aml);
1324 }
1325 }
1326 }
1327 }
1328
1329 Ok((root, pci_irqs, pid_labels, amls, gpe_scope_amls))
1330}
1331
1332#[sorted]
1334#[derive(Error, Debug)]
1335pub enum LoadImageError {
1336 #[error("Alignment not a power of two: {0}")]
1337 BadAlignment(u64),
1338 #[error("Getting image size failed: {0}")]
1339 GetLen(io::Error),
1340 #[error("GuestMemory get slice failed: {0}")]
1341 GuestMemorySlice(GuestMemoryError),
1342 #[error("Image size too large: {0}")]
1343 ImageSizeTooLarge(u64),
1344 #[error("No suitable memory region found")]
1345 NoSuitableMemoryRegion,
1346 #[error("Reading image into memory failed: {0}")]
1347 ReadToMemory(io::Error),
1348 #[error("Cannot load zero-sized image")]
1349 ZeroSizedImage,
1350}
1351
1352pub fn load_image<F>(
1363 guest_mem: &GuestMemory,
1364 image: &mut F,
1365 guest_addr: GuestAddress,
1366 max_size: u64,
1367) -> Result<u32, LoadImageError>
1368where
1369 F: FileReadWriteAtVolatile + FileGetLen,
1370{
1371 let size = image.get_len().map_err(LoadImageError::GetLen)?;
1372
1373 if size > u32::MAX as u64 || size > max_size {
1374 return Err(LoadImageError::ImageSizeTooLarge(size));
1375 }
1376
1377 let size = size as u32;
1379
1380 let guest_slice = guest_mem
1381 .get_slice_at_addr(guest_addr, size as usize)
1382 .map_err(LoadImageError::GuestMemorySlice)?;
1383 image
1384 .read_exact_at_volatile(guest_slice, 0)
1385 .map_err(LoadImageError::ReadToMemory)?;
1386
1387 Ok(size)
1388}
1389
1390pub fn load_image_high<F>(
1405 guest_mem: &GuestMemory,
1406 image: &mut F,
1407 min_guest_addr: GuestAddress,
1408 max_guest_addr: GuestAddress,
1409 region_filter: Option<fn(&MemoryRegionInformation) -> bool>,
1410 align: u64,
1411) -> Result<(GuestAddress, u32), LoadImageError>
1412where
1413 F: FileReadWriteAtVolatile + FileGetLen,
1414{
1415 if !align.is_power_of_two() {
1416 return Err(LoadImageError::BadAlignment(align));
1417 }
1418
1419 let max_size = max_guest_addr.offset_from(min_guest_addr) & !(align - 1);
1420 let size = image.get_len().map_err(LoadImageError::GetLen)?;
1421
1422 if size == 0 {
1423 return Err(LoadImageError::ZeroSizedImage);
1424 }
1425
1426 if size > u32::MAX as u64 || size > max_size {
1427 return Err(LoadImageError::ImageSizeTooLarge(size));
1428 }
1429
1430 let mut regions: Vec<_> = guest_mem
1433 .regions()
1434 .filter(region_filter.unwrap_or(|_| true))
1435 .collect();
1436 regions.sort_unstable_by(|a, b| a.guest_addr.cmp(&b.guest_addr));
1437
1438 let guest_addr = regions
1441 .into_iter()
1442 .rev()
1443 .filter_map(|r| {
1444 let rgn_max_addr = r
1446 .guest_addr
1447 .checked_add((r.size as u64).checked_sub(1)?)?
1448 .min(max_guest_addr);
1449 let rgn_start_aligned = r.guest_addr.align(align)?;
1451 let image_addr = rgn_max_addr.checked_sub(size - 1)? & !(align - 1);
1453
1454 if image_addr >= rgn_start_aligned {
1456 Some(image_addr)
1457 } else {
1458 None
1459 }
1460 })
1461 .find(|&addr| addr >= min_guest_addr)
1462 .ok_or(LoadImageError::NoSuitableMemoryRegion)?;
1463
1464 let size = size as u32;
1466
1467 let guest_slice = guest_mem
1468 .get_slice_at_addr(guest_addr, size as usize)
1469 .map_err(LoadImageError::GuestMemorySlice)?;
1470 image
1471 .read_exact_at_volatile(guest_slice, 0)
1472 .map_err(LoadImageError::ReadToMemory)?;
1473
1474 Ok((guest_addr, size))
1475}
1476
1477#[derive(Clone, Debug, Default, Serialize, Deserialize, FromKeyValues, PartialEq, Eq)]
1479#[serde(deny_unknown_fields, rename_all = "kebab-case")]
1480pub struct SmbiosOptions {
1481 pub bios_vendor: Option<String>,
1483
1484 pub bios_version: Option<String>,
1486
1487 pub manufacturer: Option<String>,
1489
1490 pub product_name: Option<String>,
1492
1493 pub serial_number: Option<String>,
1495
1496 pub uuid: Option<Uuid>,
1498
1499 #[serde(default)]
1501 pub oem_strings: Vec<String>,
1502}
1503
1504#[cfg(test)]
1505mod tests {
1506 use serde_keyvalue::from_key_values;
1507 use tempfile::tempfile;
1508
1509 use super::*;
1510
1511 #[test]
1512 fn parse_pstore() {
1513 let res: Pstore = from_key_values("path=/some/path,size=16384").unwrap();
1514 assert_eq!(
1515 res,
1516 Pstore {
1517 path: "/some/path".into(),
1518 size: 16384,
1519 }
1520 );
1521
1522 let res = from_key_values::<Pstore>("path=/some/path");
1523 assert!(res.is_err());
1524
1525 let res = from_key_values::<Pstore>("size=16384");
1526 assert!(res.is_err());
1527
1528 let res = from_key_values::<Pstore>("");
1529 assert!(res.is_err());
1530 }
1531
1532 #[test]
1533 fn deserialize_cpuset_serde_kv() {
1534 let res: CpuSet = from_key_values("[0,4,7]").unwrap();
1535 assert_eq!(res, CpuSet::new(vec![0, 4, 7]));
1536
1537 let res: CpuSet = from_key_values("[9-12]").unwrap();
1538 assert_eq!(res, CpuSet::new(vec![9, 10, 11, 12]));
1539
1540 let res: CpuSet = from_key_values("[0,4,7,9-12,15]").unwrap();
1541 assert_eq!(res, CpuSet::new(vec![0, 4, 7, 9, 10, 11, 12, 15]));
1542 }
1543
1544 #[test]
1545 fn deserialize_serialize_cpuset_json() {
1546 let json_str = "[0,4,7]";
1547 let cpuset = CpuSet::new(vec![0, 4, 7]);
1548 let res: CpuSet = serde_json::from_str(json_str).unwrap();
1549 assert_eq!(res, cpuset);
1550 assert_eq!(serde_json::to_string(&cpuset).unwrap(), json_str);
1551
1552 let json_str = r#"["9-12"]"#;
1553 let cpuset = CpuSet::new(vec![9, 10, 11, 12]);
1554 let res: CpuSet = serde_json::from_str(json_str).unwrap();
1555 assert_eq!(res, cpuset);
1556 assert_eq!(serde_json::to_string(&cpuset).unwrap(), json_str);
1557
1558 let json_str = r#"[0,4,7,"9-12",15]"#;
1559 let cpuset = CpuSet::new(vec![0, 4, 7, 9, 10, 11, 12, 15]);
1560 let res: CpuSet = serde_json::from_str(json_str).unwrap();
1561 assert_eq!(res, cpuset);
1562 assert_eq!(serde_json::to_string(&cpuset).unwrap(), json_str);
1563 }
1564
1565 #[test]
1566 fn load_image_high_max_4g() {
1567 let mem = GuestMemory::new(&[
1568 (GuestAddress(0x0000_0000), 0x4000_0000), (GuestAddress(0x8000_0000), 0x4000_0000), ])
1571 .unwrap();
1572
1573 const TEST_IMAGE_SIZE: u64 = 1234;
1574 let mut test_image = tempfile().unwrap();
1575 test_image.set_len(TEST_IMAGE_SIZE).unwrap();
1576
1577 const TEST_ALIGN: u64 = 0x8000;
1578 let (addr, size) = load_image_high(
1579 &mem,
1580 &mut test_image,
1581 GuestAddress(0x8000),
1582 GuestAddress(0xFFFF_FFFF), None,
1584 TEST_ALIGN,
1585 )
1586 .unwrap();
1587
1588 assert_eq!(addr, GuestAddress(0xBFFF_8000));
1589 assert_eq!(addr.offset() % TEST_ALIGN, 0);
1590 assert_eq!(size, TEST_IMAGE_SIZE as u32);
1591 }
1592}