arch/
lib.rs

1// Copyright 2018 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Virtual machine architecture support code.
6
7pub 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    /// At the start of RAM.
141    Start,
142    /// Near the end of RAM.
143    End,
144    /// After the payload, with some padding for alignment.
145    AfterPayload,
146}
147
148/// Set of CPU cores.
149#[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/// The SVE config for Vcpus.
177#[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    /// Detect if SVE is available and enable accordingly. `enable` is ignored if auto is true
182    #[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/// FFA config
196// For now this is limited to android, will be opened to other aarch64 based pVMs after
197// corresponding kernel APIs are upstreamed.
198#[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    /// Just enable FFA, don't care about the negotiated version.
203    #[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/// Selects the interface for guest-controlled power management of assigned devices.
266#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
267pub enum DevicePowerManagerConfig {
268    /// Uses the protected KVM hypercall interface.
269    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
283/// Deserializes a `CpuSet` from a sequence which elements can either be integers, or strings
284/// representing CPU ranges (e.g. `5-8`).
285impl<'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
327/// Serializes a `CpuSet` into a sequence of integers and strings representing CPU ranges.
328impl 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        // Factorize ranges into "a-b" strings.
338        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        // Current range.
349        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/// Mapping of guest VCPU threads to host CPU cores.
370#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
371pub enum VcpuAffinity {
372    /// All VCPU threads will be pinned to the same set of host CPU cores.
373    Global(CpuSet),
374    /// Each VCPU may be pinned to a set of host CPU cores.
375    /// The map key is a guest VCPU index, and the corresponding value is the set of
376    /// host CPU indices that the VCPU thread will be allowed to run on.
377    /// If a VCPU index is not present in the map, its affinity will not be set.
378    PerVcpu(BTreeMap<usize, CpuSet>),
379}
380
381/// Memory region with optional size.
382#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, FromKeyValues)]
383pub struct MemoryRegionConfig {
384    pub start: u64,
385    pub size: Option<u64>,
386}
387
388/// General PCI config.
389#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, FromKeyValues)]
390pub struct PciConfig {
391    /// region for PCI Configuration Access Mechanism
392    #[cfg(target_arch = "aarch64")]
393    pub cam: Option<MemoryRegionConfig>,
394    /// region for PCIe Enhanced Configuration Access Mechanism
395    #[cfg(target_arch = "x86_64")]
396    pub ecam: Option<MemoryRegionConfig>,
397    /// region for non-prefetchable PCI device memory below 4G
398    pub mem: Option<MemoryRegionConfig>,
399}
400
401/// Holds the pieces needed to build a VM. Passed to `build_vm` in the `LinuxArch` trait below to
402/// create a `RunnableLinuxVm`.
403#[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    /// A file to load as pVM firmware. Must be `Some` iff
441    /// `hv_cfg.protection_type == ProtectionType::UnprotectedWithFirmware`.
442    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    /// Map of vCPU ID->corresponding pCPU's capacity.
452    pub vcpu_capacity: BTreeMap<usize, u32>,
453    /// List of vCPU clusters, mapped from pCPU clusters.
454    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    /// Maps vcpu -> the corresponding pcpu's frequency, based on the vcpu:pcpu mapping in
471    /// vcpu_affinity
472    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/// Holds the elements needed to run a Linux VM. Created by `build_vm`.
484#[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    /// Devices to be notified before the system resumes from the S3 suspended state.
500    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    /// If vcpus is None, then it's the responsibility of the vcpu thread to create vcpus.
508    /// If it's Some, then `build_vm` already created the vcpus.
509    pub vcpus: Option<Vec<Vcpu>>,
510    pub vm: V,
511    pub vm_request_tubes: Vec<Tube>,
512}
513
514/// The device and optional jail.
515pub struct VirtioDeviceStub {
516    pub dev: Box<dyn VirtioDevice>,
517    pub jail: Option<Minijail>,
518}
519
520/// Trait which is implemented for each Linux Architecture in order to
521/// set up the memory, cpus, and system devices and to boot the kernel.
522pub trait LinuxArch {
523    type Error: StdError;
524    type ArchMemoryLayout;
525
526    /// Decide architecture specific memory layout details to be used by later stages of the VM
527    /// setup.
528    fn arch_memory_layout(
529        components: &VmComponents,
530    ) -> std::result::Result<Self::ArchMemoryLayout, Self::Error>;
531
532    /// Returns a Vec of the valid memory addresses as pairs of address and length. These should be
533    /// used to configure the `GuestMemory` structure for the platform.
534    ///
535    /// # Arguments
536    ///
537    /// * `components` - Parts used to determine the memory layout.
538    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    /// Gets the configuration for a new `SystemAllocator` that fits the given `Vm`'s memory layout.
545    ///
546    /// This is the per-architecture template for constructing the `SystemAllocator`. Platform
547    /// agnostic modifications may be made to this configuration, but the final `SystemAllocator`
548    /// will be at least as strict as this configuration.
549    ///
550    /// # Arguments
551    ///
552    /// * `vm` - The virtual machine to be used as a template for the `SystemAllocator`.
553    fn get_system_allocator_config<V: Vm>(
554        vm: &V,
555        arch_memory_layout: &Self::ArchMemoryLayout,
556    ) -> SystemAllocatorConfig;
557
558    /// Takes `VmComponents` and generates a `RunnableLinuxVm`.
559    ///
560    /// # Arguments
561    ///
562    /// * `components` - Parts to use to build the VM.
563    /// * `vm_evt_wrtube` - Tube used by sub-devices to request that crosvm exit because guest wants
564    ///   to stop/shut down or requested reset.
565    /// * `system_allocator` - Allocator created by this trait's implementation of
566    ///   `get_system_allocator_config`.
567    /// * `serial_parameters` - Definitions for how the serial devices should be configured.
568    /// * `serial_jail` - Jail used for serial devices created here.
569    /// * `battery` - Defines what battery device will be created.
570    /// * `vm` - A VM implementation to build upon.
571    /// * `ramoops_region` - Region allocated for ramoops.
572    /// * `devices` - The devices to be built into the VM.
573    /// * `irq_chip` - The IRQ chip implemention for the VM.
574    /// * `debugcon_jail` - Jail used for debugcon devices created here.
575    /// * `pflash_jail` - Jail used for pflash device created here.
576    /// * `fw_cfg_jail` - Jail used for fw_cfg device created here.
577    /// * `device_tree_overlays` - Device tree overlay binaries
578    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    /// Configures the vcpu and should be called once per vcpu from the vcpu's thread.
606    ///
607    /// # Arguments
608    ///
609    /// * `vm` - The virtual machine object.
610    /// * `hypervisor` - The `Hypervisor` that created the vcpu.
611    /// * `irq_chip` - The `IrqChip` associated with this vm.
612    /// * `vcpu` - The VCPU object to configure.
613    /// * `vcpu_init` - The data required to initialize VCPU registers and other state.
614    /// * `vcpu_id` - The id of the given `vcpu`.
615    /// * `num_vcpus` - Number of virtual CPUs the guest will have.
616    /// * `cpu_config` - CPU feature configurations.
617    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    /// Configures and add a pci device into vm
629    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    /// Returns frequency map for each of the host's logical cores.
639    fn get_host_cpu_frequencies_khz() -> Result<BTreeMap<usize, Vec<u32>>, Self::Error>;
640
641    /// Returns max-freq map of the host's logical cores.
642    fn get_host_cpu_max_freq_khz() -> Result<BTreeMap<usize, u32>, Self::Error>;
643
644    /// Returns capacity map of the host's logical cores.
645    fn get_host_cpu_capacity() -> Result<BTreeMap<usize, u32>, Self::Error>;
646
647    /// Returns cluster masks for each of the host's logical cores.
648    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    /// Reads vCPU's registers.
656    fn read_registers(vcpu: &T) -> Result<<GdbArch as Arch>::Registers, Self::Error>;
657
658    /// Writes vCPU's registers.
659    fn write_registers(vcpu: &T, regs: &<GdbArch as Arch>::Registers) -> Result<(), Self::Error>;
660
661    /// Reads bytes from the guest memory.
662    fn read_memory(
663        vcpu: &T,
664        guest_mem: &GuestMemory,
665        vaddr: GuestAddress,
666        len: usize,
667    ) -> Result<Vec<u8>, Self::Error>;
668
669    /// Writes bytes to the specified guest memory.
670    fn write_memory(
671        vcpu: &T,
672        guest_mem: &GuestMemory,
673        vaddr: GuestAddress,
674        buf: &[u8],
675    ) -> Result<(), Self::Error>;
676
677    /// Reads bytes from the guest register.
678    ///
679    /// Returns an empty vector if `reg_id` is valid but the register is not available.
680    fn read_register(vcpu: &T, reg_id: <GdbArch as Arch>::RegId) -> Result<Vec<u8>, Self::Error>;
681
682    /// Writes bytes to the specified guest register.
683    fn write_register(
684        vcpu: &T,
685        reg_id: <GdbArch as Arch>::RegId,
686        data: &[u8],
687    ) -> Result<(), Self::Error>;
688
689    /// Make the next vCPU's run single-step.
690    fn enable_singlestep(vcpu: &T) -> Result<(), Self::Error>;
691
692    /// Get maximum number of hardware breakpoints.
693    fn get_max_hw_breakpoints(vcpu: &T) -> Result<usize, Self::Error>;
694
695    /// Set hardware breakpoints at the given addresses.
696    fn set_hw_breakpoints(vcpu: &T, breakpoints: &[GuestAddress]) -> Result<(), Self::Error>;
697}
698
699/// Errors for device manager.
700#[sorted]
701#[derive(Error, Debug)]
702pub enum DeviceRegistrationError {
703    /// No more MMIO space available.
704    #[error("no more addresses are available")]
705    AddrsExhausted,
706    /// Could not allocate device address space for the device.
707    #[error("Allocating device addresses: {0}")]
708    AllocateDeviceAddrs(PciDeviceError),
709    /// Could not allocate IO space for the device.
710    #[error("Allocating IO addresses: {0}")]
711    AllocateIoAddrs(PciDeviceError),
712    /// Could not allocate MMIO or IO resource for the device.
713    #[error("Allocating IO resource: {0}")]
714    AllocateIoResource(resources::Error),
715    /// Could not allocate an IRQ number.
716    #[error("Allocating IRQ number")]
717    AllocateIrq,
718    /// Could not allocate IRQ resource for the device.
719    #[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    /// Broken pci topology
725    #[error("pci topology is broken")]
726    BrokenPciTopology,
727    /// Unable to clone a jail for the device.
728    #[cfg(any(target_os = "android", target_os = "linux"))]
729    #[error("failed to clone jail: {0}")]
730    CloneJail(minijail::Error),
731    /// Appending to kernel command line failed.
732    #[error("unable to add device to kernel command line: {0}")]
733    Cmdline(kernel_cmdline::Error),
734    /// Configure window size failed.
735    #[error("failed to configure window size: {0}")]
736    ConfigureWindowSize(PciDeviceError),
737    // Unable to create a pipe.
738    #[error("failed to create pipe: {0}")]
739    CreatePipe(base::Error),
740    // Unable to create a root.
741    #[error("failed to create pci root: {0}")]
742    CreateRoot(anyhow::Error),
743    // Unable to create serial device from serial parameters
744    #[error("failed to create serial device: {0}")]
745    CreateSerialDevice(devices::SerialError),
746    // Unable to create tube
747    #[error("failed to create tube: {0}")]
748    CreateTube(base::TubeError),
749    /// Could not clone an event.
750    #[error("failed to clone event: {0}")]
751    EventClone(base::Error),
752    /// Could not create an event.
753    #[error("failed to create event: {0}")]
754    EventCreate(base::Error),
755    /// Failed to generate ACPI content.
756    #[error("failed to generate ACPI content")]
757    GenerateAcpi,
758    /// No more IRQs are available.
759    #[error("no more IRQs are available")]
760    IrqsExhausted,
761    /// VFIO device is missing a DT symbol.
762    #[error("cannot match VFIO device to DT node due to a missing symbol")]
763    MissingDeviceTreeSymbol,
764    /// Missing a required serial device.
765    #[error("missing required serial device {0}")]
766    MissingRequiredSerialDevice(u8),
767    /// Could not add a device to the mmio bus.
768    #[error("failed to add to mmio bus: {0}")]
769    MmioInsert(BusError),
770    /// Failed to insert device into PCI root.
771    #[error("failed to insert device into PCI root: {0}")]
772    PciRootAddDevice(PciDeviceError),
773    #[cfg(any(target_os = "android", target_os = "linux"))]
774    /// Failed to initialize proxy device for jailed device.
775    #[error("failed to create proxy device: {0}")]
776    ProxyDeviceCreation(devices::ProxyError),
777    #[cfg(any(target_os = "android", target_os = "linux"))]
778    /// Failed to register battery device.
779    #[error("failed to register battery device to VM: {0}")]
780    RegisterBattery(devices::BatteryError),
781    /// Could not register PCI device to pci root bus
782    #[error("failed to register PCI device to pci root bus")]
783    RegisterDevice(SendError<PciRootCommand>),
784    /// Could not register PCI device capabilities.
785    #[error("could not register PCI device capabilities: {0}")]
786    RegisterDeviceCapabilities(PciDeviceError),
787    /// Failed to register ioevent with VM.
788    #[error("failed to register ioevent to VM: {0}")]
789    RegisterIoevent(base::Error),
790    /// Failed to register irq event with VM.
791    #[error("failed to register irq event to VM: {0}")]
792    RegisterIrqfd(base::Error),
793    /// Could not setup VFIO platform IRQ for the device.
794    #[error("Setting up VFIO platform IRQ: {0}")]
795    SetupVfioPlatformIrq(anyhow::Error),
796}
797
798/// Config a PCI device for used by this vm.
799pub 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    // Allocate PCI device address before allocating BARs.
808    let pci_address = device
809        .allocate_address(resources)
810        .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
811
812    // Allocate ranges that may need to be in the low MMIO region (MmioType::Low).
813    let mmio_ranges = device
814        .allocate_io_bars(resources)
815        .map_err(DeviceRegistrationError::AllocateIoAddrs)?;
816
817    // Allocate device ranges that may be in low or high MMIO after low-only ranges.
818    let device_ranges = device
819        .allocate_device_bars(resources)
820        .map_err(DeviceRegistrationError::AllocateDeviceAddrs)?;
821
822    // If device is a pcie bridge, add its pci bus to pci root
823    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    // Do not suggest INTx for hot-plug devices.
834    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
910// Generate pci topology starting from parent bus
911fn 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        // Only target for devices that located on this bus
924        if addr.bus == bus_num {
925            // If this device is a pci bridge (a.k.a., it has a pci bus structure),
926            // create its topology recursively
927            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            // Allocate MMIO for non-bridge devices
969            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
987/// Ensure all PCI devices have an assigned PCI address.
988pub fn assign_pci_addresses(
989    devices: &mut [(Box<dyn BusDeviceObj>, Option<Minijail>)],
990    resources: &mut SystemAllocator,
991) -> Result<(), DeviceRegistrationError> {
992    // First allocate devices with a preferred address.
993    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    // Then allocate addresses for the remaining devices.
1004    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
1017/// Creates a root PCI device for use by this Vm.
1018pub 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    // Allocate legacy INTx
1075    let mut pci_irqs = Vec::new();
1076    let mut irqs: Vec<u32> = Vec::new();
1077
1078    // Mapping of (bus, dev, pin) -> IRQ number.
1079    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                // The device reported a preferred IRQ, so use that rather than allocating one.
1087                resources.reserve_irq(gsi);
1088                Some((pin, gsi))
1089            }
1090            PreferredIrq::Any => {
1091                // The device did not provide a preferred IRQ but requested one, so allocate one.
1092
1093                // Choose a pin based on the slot's function number. Function 0 must always use
1094                // INTA# for single-function devices per the PCI spec, and we choose to use INTA#
1095                // for function 0 on multifunction devices and distribute the remaining functions
1096                // evenly across the other pins.
1097                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                // If an IRQ number has already been assigned for a different function with this
1105                // (bus, device, pin) combination, use it. Otherwise allocate a new one and insert
1106                // it into the map.
1107                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                    // If we have allocated fewer than `max_irqs` total, add a new irq to the `irqs`
1112                    // pool. Otherwise, share one of the existing `irqs`.
1113                    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                        // Pick one of the existing IRQs to share, using `dev_idx` to distribute IRQ
1121                        // sharing evenly across devices.
1122                        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                // The device does not want an INTx# IRQ.
1132                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    // To prevent issues where device's on_sandbox may spawn thread before all
1157    // sandboxed devices are sandboxed we partition iterator to go over sandboxed
1158    // first. This is needed on linux platforms. On windows, this is a no-op since
1159    // jails are always None, even for sandboxed devices.
1160    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/// Errors for image loading.
1261#[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
1280/// Load an image from a file into guest memory.
1281///
1282/// # Arguments
1283///
1284/// * `guest_mem` - The memory to be used by the guest.
1285/// * `guest_addr` - The starting address to load the image in the guest memory.
1286/// * `max_size` - The amount of space in bytes available in the guest memory for the image.
1287/// * `image` - The file containing the image to be loaded.
1288///
1289/// The size in bytes of the loaded image is returned.
1290pub 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    // This is safe due to the bounds check above.
1306    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
1318/// Load an image from a file into guest memory at the highest possible address.
1319///
1320/// # Arguments
1321///
1322/// * `guest_mem` - The memory to be used by the guest.
1323/// * `image` - The file containing the image to be loaded.
1324/// * `min_guest_addr` - The minimum address of the start of the image.
1325/// * `max_guest_addr` - The address to load the last byte of the image.
1326/// * `region_filter` - The optional filter function for determining if the given guest memory
1327///   region is suitable for loading the image into it.
1328/// * `align` - The minimum alignment of the start address of the image in bytes (must be a power of
1329///   two).
1330///
1331/// The guest address and size in bytes of the loaded image are returned.
1332pub 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    // Sort the list of guest memory regions by address so we can iterate over them in reverse order
1359    // (high to low).
1360    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    // Find the highest valid address inside a guest memory region that satisfies the requested
1367    // alignment and min/max address requirements while having enough space for the image.
1368    let guest_addr = regions
1369        .into_iter()
1370        .rev()
1371        .filter_map(|r| {
1372            // Highest address within this region.
1373            let rgn_max_addr = r
1374                .guest_addr
1375                .checked_add((r.size as u64).checked_sub(1)?)?
1376                .min(max_guest_addr);
1377            // Lowest aligned address within this region.
1378            let rgn_start_aligned = r.guest_addr.align(align)?;
1379            // Hypothetical address of the image if loaded at the end of the region.
1380            let image_addr = rgn_max_addr.checked_sub(size - 1)? & !(align - 1);
1381
1382            // Would the image fit within the region?
1383            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    // This is safe due to the bounds check above.
1393    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/// SMBIOS table configuration
1406#[derive(Clone, Debug, Default, Serialize, Deserialize, FromKeyValues, PartialEq, Eq)]
1407#[serde(deny_unknown_fields, rename_all = "kebab-case")]
1408pub struct SmbiosOptions {
1409    /// BIOS vendor name.
1410    pub bios_vendor: Option<String>,
1411
1412    /// BIOS version number (free-form string).
1413    pub bios_version: Option<String>,
1414
1415    /// System manufacturer name.
1416    pub manufacturer: Option<String>,
1417
1418    /// System product name.
1419    pub product_name: Option<String>,
1420
1421    /// System serial number (free-form string).
1422    pub serial_number: Option<String>,
1423
1424    /// System UUID.
1425    pub uuid: Option<Uuid>,
1426
1427    /// Additional OEM strings to add to SMBIOS table.
1428    #[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), // 0x00000000..0x40000000
1497            (GuestAddress(0x8000_0000), 0x4000_0000), // 0x80000000..0xC0000000
1498        ])
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), // max_guest_addr beyond highest guest memory region
1511            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}