crosvm/crosvm/
config.rs

1// Copyright 2022 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#[cfg(target_arch = "x86_64")]
6use std::arch::x86_64::__cpuid;
7#[cfg(target_arch = "x86_64")]
8use std::arch::x86_64::__cpuid_count;
9use std::collections::BTreeMap;
10use std::path::PathBuf;
11use std::str::FromStr;
12
13use arch::set_default_serial_parameters;
14use arch::CpuSet;
15use arch::DevicePowerManagerConfig;
16use arch::FdtPosition;
17#[cfg(all(target_os = "android", target_arch = "aarch64"))]
18use arch::FfaConfig;
19#[cfg(target_arch = "aarch64")]
20use arch::MteConfig;
21use arch::PciConfig;
22use arch::Pstore;
23#[cfg(target_arch = "x86_64")]
24use arch::SmbiosOptions;
25#[cfg(target_arch = "aarch64")]
26use arch::SveConfig;
27use arch::VcpuAffinity;
28use base::debug;
29use base::pagesize;
30use cros_async::ExecutorKind;
31#[cfg(all(windows, feature = "audio"))]
32use device_virtio_snd::vhost_user::sys::windows::SndSplitConfig;
33use devices::serial_device::SerialHardware;
34use devices::serial_device::SerialParameters;
35#[cfg(any(feature = "video-decoder", feature = "video-encoder"))]
36use devices::virtio::device_constants::video::VideoDeviceConfig;
37#[cfg(feature = "gpu")]
38use devices::virtio::gpu::GpuParameters;
39#[cfg(all(windows, feature = "gpu"))]
40use devices::virtio::vhost_user_backend::gpu::sys::windows::GpuBackendConfig;
41#[cfg(all(windows, feature = "gpu"))]
42use devices::virtio::vhost_user_backend::gpu::sys::windows::GpuVmmConfig;
43#[cfg(all(windows, feature = "gpu"))]
44use devices::virtio::vhost_user_backend::gpu::sys::windows::InputEventSplitConfig;
45#[cfg(all(windows, feature = "gpu"))]
46use devices::virtio::vhost_user_backend::gpu::sys::windows::WindowProcedureThreadSplitConfig;
47use devices::virtio::DeviceType;
48use devices::FwCfgParameters;
49use devices::PciAddress;
50use devices::PflashParameters;
51use devices::StubPciParameters;
52#[cfg(target_arch = "x86_64")]
53use hypervisor::CpuHybridType;
54#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
55use hypervisor::NestedMode;
56use hypervisor::ProtectionType;
57#[cfg(target_arch = "aarch64")]
58pub use hypervisor::ToggleMode;
59use jail::JailConfig;
60use resources::AddressRange;
61use serde::Deserialize;
62use serde::Serialize;
63use serde_keyvalue::FromKeyValues;
64use vm_control::BatteryType;
65use vm_memory::FileBackedMappingParameters;
66#[cfg(target_arch = "x86_64")]
67use x86_64::check_host_hybrid_support;
68#[cfg(target_arch = "x86_64")]
69use x86_64::CpuIdCall;
70
71use super::any_device_module::AnyVirtioDeviceModule;
72pub(crate) use super::sys::HypervisorKind;
73
74cfg_if::cfg_if! {
75    if #[cfg(any(target_os = "android", target_os = "linux"))] {
76        #[cfg(feature = "gpu")]
77        use crate::crosvm::sys::GpuRenderServerParameters;
78
79        #[cfg(target_arch = "aarch64")]
80        static VHOST_SCMI_PATH: &str = "/dev/vhost-scmi";
81    } else if #[cfg(windows)] {
82        use base::{Event, Tube};
83    }
84}
85
86// by default, if enabled, the balloon WS features will use 4 bins.
87#[cfg(feature = "balloon")]
88const VIRTIO_BALLOON_WS_DEFAULT_NUM_BINS: u8 = 4;
89
90/// Indicates the location and kind of executable kernel for a VM.
91#[allow(dead_code)]
92#[derive(Debug, Serialize, Deserialize)]
93pub enum Executable {
94    /// An executable intended to be run as a BIOS directly.
95    Bios(PathBuf),
96    /// A elf linux kernel, loaded and executed by crosvm.
97    Kernel(PathBuf),
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, FromKeyValues)]
101#[serde(deny_unknown_fields, rename_all = "kebab-case")]
102pub enum IrqChipKind {
103    /// All interrupt controllers are emulated in the kernel.
104    #[serde(rename_all = "kebab-case")]
105    Kernel {
106        /// Whether to setup a virtual ITS controller (for MSI interrupt support) if the hypervisor
107        /// supports it. Will eventually be enabled by default.
108        #[cfg(target_arch = "aarch64")]
109        #[serde(default)]
110        allow_vgic_its: bool,
111    },
112    /// APIC is emulated in the kernel.  All other interrupt controllers are in userspace.
113    Split,
114    /// All interrupt controllers are emulated in userspace.
115    Userspace,
116}
117
118impl Default for IrqChipKind {
119    fn default() -> Self {
120        IrqChipKind::Kernel {
121            #[cfg(target_arch = "aarch64")]
122            allow_vgic_its: false,
123        }
124    }
125}
126
127/// The core types in hybrid architecture.
128#[cfg(target_arch = "x86_64")]
129#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
130#[serde(deny_unknown_fields, rename_all = "kebab-case")]
131pub struct CpuCoreType {
132    /// Intel Atom.
133    pub atom: CpuSet,
134    /// Intel Core.
135    pub core: CpuSet,
136}
137
138#[derive(Debug, Default, PartialEq, Eq, Deserialize, Serialize, FromKeyValues)]
139#[serde(deny_unknown_fields, rename_all = "kebab-case")]
140pub struct CpuOptions {
141    /// Number of CPU cores.
142    #[serde(default)]
143    pub num_cores: Option<usize>,
144    /// Vector of CPU ids to be grouped into the same cluster.
145    #[serde(default)]
146    pub clusters: Vec<CpuSet>,
147    /// Core Type of CPUs.
148    #[cfg(target_arch = "x86_64")]
149    pub core_types: Option<CpuCoreType>,
150    /// Select which CPU to boot from.
151    #[serde(default)]
152    pub boot_cpu: Option<usize>,
153    /// Vector of CPU ids to be grouped into the same freq domain.
154    #[serde(default)]
155    pub freq_domains: Vec<CpuSet>,
156    /// Memory Tagging Extension.
157    #[cfg(target_arch = "aarch64")]
158    pub mte: Option<MteConfig>,
159    /// Scalable Vector Extension.
160    #[cfg(target_arch = "aarch64")]
161    pub sve: Option<SveConfig>,
162}
163
164/// Nested virtualization configuration.
165#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
166#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, FromKeyValues)]
167#[serde(deny_unknown_fields, rename_all = "kebab-case")]
168pub struct NestedConfig {
169    /// Nested virtualization exposure policy.
170    #[serde(default)]
171    pub mode: NestedMode,
172}
173
174/// Device tree overlay configuration.
175#[derive(Debug, Default, Serialize, Deserialize, FromKeyValues)]
176#[serde(deny_unknown_fields, rename_all = "kebab-case")]
177pub struct DtboOption {
178    /// Overlay file to apply to the base device tree.
179    pub path: PathBuf,
180    /// Labels of nodes to include in the final device tree.
181    #[serde(default)]
182    pub select_symbols: Option<Vec<String>>,
183    /// Whether to only apply device tree nodes which belong to a VFIO device.
184    #[serde(default)]
185    pub filter: bool,
186}
187
188#[derive(Debug, Default, Deserialize, Serialize, FromKeyValues, PartialEq, Eq)]
189#[serde(deny_unknown_fields, rename_all = "kebab-case")]
190pub struct MemOptions {
191    /// Amount of guest memory in MiB.
192    #[serde(default)]
193    pub size: Option<u64>,
194}
195
196#[derive(Serialize, Deserialize, FromKeyValues)]
197#[serde(deny_unknown_fields, rename_all = "kebab-case")]
198pub struct VhostUserFrontendOption {
199    /// Device type
200    #[serde(rename = "type")]
201    pub type_: devices::virtio::DeviceType,
202
203    /// Path to the vhost-user backend socket to connect to
204    pub socket: PathBuf,
205
206    /// Maximum number of entries per queue (default: 32768)
207    pub max_queue_size: Option<u16>,
208
209    /// Preferred PCI address
210    pub pci_address: Option<PciAddress>,
211}
212
213pub const DEFAULT_TOUCH_DEVICE_HEIGHT: u32 = 1024;
214pub const DEFAULT_TOUCH_DEVICE_WIDTH: u32 = 1280;
215
216#[derive(Serialize, Deserialize, Debug, FromKeyValues)]
217#[serde(deny_unknown_fields, rename_all = "kebab-case")]
218pub struct TouchDeviceOption {
219    pub path: PathBuf,
220    pub width: Option<u32>,
221    pub height: Option<u32>,
222    pub name: Option<String>,
223}
224
225/// Try to parse a colon-separated touch device option.
226///
227/// The expected format is "PATH:WIDTH:HEIGHT:NAME", with all fields except PATH being optional.
228fn parse_touch_device_option_legacy(s: &str) -> Option<TouchDeviceOption> {
229    let mut it = s.split(':');
230    let path = PathBuf::from(it.next()?.to_owned());
231    let width = if let Some(width) = it.next() {
232        Some(width.trim().parse().ok()?)
233    } else {
234        None
235    };
236    let height = if let Some(height) = it.next() {
237        Some(height.trim().parse().ok()?)
238    } else {
239        None
240    };
241    let name = it.next().map(|name| name.trim().to_string());
242    if it.next().is_some() {
243        return None;
244    }
245
246    Some(TouchDeviceOption {
247        path,
248        width,
249        height,
250        name,
251    })
252}
253
254/// Parse virtio-input touch device options from a string.
255///
256/// This function only exists to enable the use of the deprecated colon-separated form
257/// ("PATH:WIDTH:HEIGHT:NAME"); once the deprecation period is over, this function should be removed
258/// in favor of using the derived `FromKeyValues` function directly.
259pub fn parse_touch_device_option(s: &str) -> Result<TouchDeviceOption, String> {
260    if s.contains(':') {
261        if let Some(touch_spec) = parse_touch_device_option_legacy(s) {
262            log::warn!(
263                "colon-separated touch device options are deprecated; \
264                please use --input instead"
265            );
266            return Ok(touch_spec);
267        }
268    }
269
270    from_key_values::<TouchDeviceOption>(s)
271}
272
273/// virtio-input device configuration
274#[derive(Serialize, Deserialize, Debug, FromKeyValues, Eq, PartialEq)]
275#[serde(deny_unknown_fields, rename_all = "kebab-case")]
276pub enum InputDeviceOption {
277    Evdev {
278        path: PathBuf,
279    },
280    Keyboard {
281        path: PathBuf,
282    },
283    Mouse {
284        path: PathBuf,
285    },
286    MultiTouch {
287        path: PathBuf,
288        width: Option<u32>,
289        height: Option<u32>,
290        name: Option<String>,
291    },
292    Rotary {
293        path: PathBuf,
294    },
295    SingleTouch {
296        path: PathBuf,
297        width: Option<u32>,
298        height: Option<u32>,
299        name: Option<String>,
300    },
301    Switches {
302        path: PathBuf,
303    },
304    Trackpad {
305        path: PathBuf,
306        width: Option<u32>,
307        height: Option<u32>,
308        name: Option<String>,
309    },
310    MultiTouchTrackpad {
311        path: PathBuf,
312        width: Option<u32>,
313        height: Option<u32>,
314        name: Option<String>,
315    },
316    #[serde(rename_all = "kebab-case")]
317    Custom {
318        path: PathBuf,
319        config_path: PathBuf,
320    },
321}
322
323fn parse_hex_or_decimal(maybe_hex_string: &str) -> Result<u64, String> {
324    // Parse string starting with 0x as hex and others as numbers.
325    if let Some(hex_string) = maybe_hex_string.strip_prefix("0x") {
326        u64::from_str_radix(hex_string, 16)
327    } else if let Some(hex_string) = maybe_hex_string.strip_prefix("0X") {
328        u64::from_str_radix(hex_string, 16)
329    } else {
330        u64::from_str(maybe_hex_string)
331    }
332    .map_err(|e| format!("invalid numeric value {maybe_hex_string}: {e}"))
333}
334
335pub fn parse_mmio_address_range(s: &str) -> Result<Vec<AddressRange>, String> {
336    s.split(',')
337        .map(|s| {
338            let r: Vec<&str> = s.split('-').collect();
339            if r.len() != 2 {
340                return Err(invalid_value_err(s, "invalid range"));
341            }
342            let parse = |s: &str| -> Result<u64, String> {
343                match parse_hex_or_decimal(s) {
344                    Ok(v) => Ok(v),
345                    Err(_) => Err(invalid_value_err(s, "expected u64 value")),
346                }
347            };
348            Ok(AddressRange {
349                start: parse(r[0])?,
350                end: parse(r[1])?,
351            })
352        })
353        .collect()
354}
355
356pub fn validate_serial_parameters(params: &SerialParameters) -> Result<(), String> {
357    if params.stdin && params.input.is_some() {
358        return Err("Cannot specify both stdin and input options".to_string());
359    }
360    if params.num < 1 {
361        return Err(invalid_value_err(
362            params.num.to_string(),
363            "Serial port num must be at least 1",
364        ));
365    }
366
367    if params.hardware == SerialHardware::Serial && params.num > 4 {
368        return Err(invalid_value_err(
369            format!("{}", params.num),
370            "Serial port num must be 4 or less",
371        ));
372    }
373
374    if params.pci_address.is_some() && params.hardware != SerialHardware::VirtioConsole {
375        return Err(invalid_value_err(
376            params.pci_address.unwrap().to_string(),
377            "Providing serial PCI address is only supported for virtio-console hardware type",
378        ));
379    }
380
381    if let Some(sizes) = &params.max_queue_sizes {
382        if params.hardware != SerialHardware::VirtioConsole {
383            return Err(invalid_value_err(
384                format!("{sizes:?}"),
385                "max-queue-sizes is only supported for virtio-console hardware type",
386            ));
387        }
388        if sizes.len() != 2 || !sizes.iter().all(|s| s.is_power_of_two()) {
389            return Err(invalid_value_err(
390                format!("{sizes:?}"),
391                "max-queue-sizes must have 2 power-of-two entries",
392            ));
393        }
394    }
395
396    Ok(())
397}
398
399pub fn parse_serial_options(s: &str) -> Result<SerialParameters, String> {
400    let params: SerialParameters = from_key_values(s)?;
401
402    validate_serial_parameters(&params)?;
403
404    Ok(params)
405}
406
407pub fn parse_bus_id_addr(v: &str) -> Result<(u8, u8, u16, u16), String> {
408    debug!("parse_bus_id_addr: {}", v);
409    let mut ids = v.split(':');
410    let errorre = move |item| move |e| format!("{item}: {e}");
411    match (ids.next(), ids.next(), ids.next(), ids.next()) {
412        (Some(bus_id), Some(addr), Some(vid), Some(pid)) => {
413            let bus_id = bus_id.parse::<u8>().map_err(errorre("bus_id"))?;
414            let addr = addr.parse::<u8>().map_err(errorre("addr"))?;
415            let vid = u16::from_str_radix(vid, 16).map_err(errorre("vid"))?;
416            let pid = u16::from_str_radix(pid, 16).map_err(errorre("pid"))?;
417            Ok((bus_id, addr, vid, pid))
418        }
419        _ => Err(String::from("BUS_ID:ADDR:BUS_NUM:DEV_NUM")),
420    }
421}
422
423pub fn invalid_value_err<T: AsRef<str>, S: ToString>(value: T, expected: S) -> String {
424    format!("invalid value {}: {}", value.as_ref(), expected.to_string())
425}
426
427#[derive(Debug, Serialize, Deserialize, FromKeyValues)]
428#[serde(deny_unknown_fields, rename_all = "kebab-case")]
429pub struct BatteryConfig {
430    #[serde(rename = "type", default)]
431    pub type_: BatteryType,
432}
433
434pub fn parse_cpu_btreemap_u32(s: &str) -> Result<BTreeMap<usize, u32>, String> {
435    let mut parsed_btreemap: BTreeMap<usize, u32> = BTreeMap::default();
436    for cpu_pair in s.split(',') {
437        let assignment: Vec<&str> = cpu_pair.split('=').collect();
438        if assignment.len() != 2 {
439            return Err(invalid_value_err(
440                cpu_pair,
441                "Invalid CPU pair syntax, missing '='",
442            ));
443        }
444        let cpu = assignment[0].parse().map_err(|_| {
445            invalid_value_err(assignment[0], "CPU index must be a non-negative integer")
446        })?;
447        let val = assignment[1].parse().map_err(|_| {
448            invalid_value_err(assignment[1], "CPU property must be a non-negative integer")
449        })?;
450        if parsed_btreemap.insert(cpu, val).is_some() {
451            return Err(invalid_value_err(cpu_pair, "CPU index must be unique"));
452        }
453    }
454    Ok(parsed_btreemap)
455}
456
457#[cfg(all(
458    target_arch = "aarch64",
459    any(target_os = "android", target_os = "linux")
460))]
461pub fn parse_cpu_frequencies(s: &str) -> Result<BTreeMap<usize, Vec<u32>>, String> {
462    let mut cpu_frequencies: BTreeMap<usize, Vec<u32>> = BTreeMap::default();
463    for cpufreq_assigns in s.split(';') {
464        let assignment: Vec<&str> = cpufreq_assigns.split('=').collect();
465        if assignment.len() != 2 {
466            return Err(invalid_value_err(
467                cpufreq_assigns,
468                "invalid CPU freq syntax",
469            ));
470        }
471        let cpu = assignment[0].parse().map_err(|_| {
472            invalid_value_err(assignment[0], "CPU index must be a non-negative integer")
473        })?;
474        let freqs = assignment[1]
475            .split(',')
476            .map(|x| x.parse::<u32>().unwrap())
477            .collect::<Vec<_>>();
478        if cpu_frequencies.insert(cpu, freqs).is_some() {
479            return Err(invalid_value_err(
480                cpufreq_assigns,
481                "CPU index must be unique",
482            ));
483        }
484    }
485    Ok(cpu_frequencies)
486}
487
488pub fn from_key_values<'a, T: Deserialize<'a>>(value: &'a str) -> Result<T, String> {
489    serde_keyvalue::from_key_values(value).map_err(|e| e.to_string())
490}
491
492/// Parse a list of guest to host CPU mappings.
493///
494/// Each mapping consists of a single guest CPU index mapped to one or more host CPUs in the form
495/// accepted by `CpuSet::from_str`:
496///
497///  `<GUEST-CPU>=<HOST-CPU-SET>[:<GUEST-CPU>=<HOST-CPU-SET>[:...]]`
498pub fn parse_cpu_affinity(s: &str) -> Result<VcpuAffinity, String> {
499    if s.contains('=') {
500        let mut affinity_map = BTreeMap::new();
501        for cpu_pair in s.split(':') {
502            let assignment: Vec<&str> = cpu_pair.split('=').collect();
503            if assignment.len() != 2 {
504                return Err(invalid_value_err(
505                    cpu_pair,
506                    "invalid VCPU assignment syntax",
507                ));
508            }
509            let guest_cpu = assignment[0].parse().map_err(|_| {
510                invalid_value_err(assignment[0], "CPU index must be a non-negative integer")
511            })?;
512            let host_cpu_set = CpuSet::from_str(assignment[1])?;
513            if affinity_map.insert(guest_cpu, host_cpu_set).is_some() {
514                return Err(invalid_value_err(cpu_pair, "VCPU index must be unique"));
515            }
516        }
517        Ok(VcpuAffinity::PerVcpu(affinity_map))
518    } else {
519        Ok(VcpuAffinity::Global(CpuSet::from_str(s)?))
520    }
521}
522
523pub fn parse_pflash_parameters(s: &str) -> Result<PflashParameters, String> {
524    let pflash_parameters: PflashParameters = from_key_values(s)?;
525
526    Ok(pflash_parameters)
527}
528
529// BTreeMaps serialize fine, as long as their keys are trivial types. A tuple does not
530// work, hence the need to convert to/from a vector form.
531mod serde_serial_params {
532    use std::iter::FromIterator;
533
534    use serde::Deserializer;
535    use serde::Serializer;
536
537    use super::*;
538
539    pub fn serialize<S>(
540        params: &BTreeMap<(SerialHardware, u8), SerialParameters>,
541        ser: S,
542    ) -> Result<S::Ok, S::Error>
543    where
544        S: Serializer,
545    {
546        let v: Vec<(&(SerialHardware, u8), &SerialParameters)> = params.iter().collect();
547        serde::Serialize::serialize(&v, ser)
548    }
549
550    pub fn deserialize<'a, D>(
551        de: D,
552    ) -> Result<BTreeMap<(SerialHardware, u8), SerialParameters>, D::Error>
553    where
554        D: Deserializer<'a>,
555    {
556        let params: Vec<((SerialHardware, u8), SerialParameters)> =
557            serde::Deserialize::deserialize(de)?;
558        Ok(BTreeMap::from_iter(params))
559    }
560}
561
562/// Aggregate of all configurable options for a running VM.
563#[derive(Serialize, Deserialize)]
564#[remain::sorted]
565pub struct Config {
566    pub acpi_tables: Vec<PathBuf>,
567    #[cfg(feature = "android_display")]
568    pub android_display_service: Option<String>,
569    pub android_fstab: Option<PathBuf>,
570    pub async_executor: Option<ExecutorKind>,
571    #[cfg(feature = "balloon")]
572    pub balloon: bool,
573    #[cfg(feature = "balloon")]
574    pub balloon_bias: i64,
575    #[cfg(feature = "balloon")]
576    pub balloon_control: Option<PathBuf>,
577    #[cfg(feature = "balloon")]
578    pub balloon_page_reporting: bool,
579    #[cfg(feature = "balloon")]
580    pub balloon_ws_num_bins: u8,
581    #[cfg(feature = "balloon")]
582    pub balloon_ws_reporting: bool,
583    pub battery_config: Option<BatteryConfig>,
584    #[cfg(windows)]
585    pub block_control_tube: Vec<Tube>,
586    #[cfg(windows)]
587    pub block_vhost_user_tube: Vec<Tube>,
588    #[cfg(any(target_os = "android", target_os = "linux"))]
589    pub boost_uclamp: bool,
590    pub boot_cpu: usize,
591    #[cfg(target_arch = "x86_64")]
592    pub break_linux_pci_config_io: bool,
593    #[cfg(windows)]
594    pub broker_shutdown_event: Option<Event>,
595    #[cfg(target_arch = "x86_64")]
596    pub bus_lock_ratelimit: u64,
597    #[cfg(any(target_os = "android", target_os = "linux"))]
598    pub coiommu_param: Option<devices::CoIommuParameters>,
599    pub core_scheduling: bool,
600    pub cpu_capacity: BTreeMap<usize, u32>, // CPU index -> capacity
601    pub cpu_clusters: Vec<CpuSet>,
602    pub cpu_freq_domains: Vec<CpuSet>,
603    #[cfg(all(
604        target_arch = "aarch64",
605        any(target_os = "android", target_os = "linux")
606    ))]
607    pub cpu_frequencies_khz: BTreeMap<usize, Vec<u32>>, // CPU index -> frequencies
608    #[cfg(all(
609        target_arch = "aarch64",
610        any(target_os = "android", target_os = "linux")
611    ))]
612    pub cpu_ipc_ratio: BTreeMap<usize, u32>, // CPU index -> IPC Ratio
613    #[cfg(feature = "crash-report")]
614    pub crash_pipe_name: Option<String>,
615    #[cfg(feature = "crash-report")]
616    pub crash_report_uuid: Option<String>,
617    pub delay_rt: bool,
618    pub dev_pm: Option<DevicePowerManagerConfig>,
619    pub device_tree_overlay: Vec<DtboOption>,
620    pub disable_virtio_intx: bool,
621    // Disks that run as an automatically setup vhost-user backend.
622    #[cfg(windows)]
623    pub disks_auto_vhost_user: Vec<device_virtio_block::DiskOption>,
624    pub display_input_height: Option<u32>,
625    pub display_input_width: Option<u32>,
626    pub display_window_keyboard: bool,
627    pub display_window_mouse: bool,
628    pub dump_device_tree_blob: Option<PathBuf>,
629    pub dynamic_power_coefficient: BTreeMap<usize, u32>,
630    pub enable_fw_cfg: bool,
631    pub enable_hwp: bool,
632    pub executable_path: Option<Executable>,
633    #[cfg(windows)]
634    pub exit_stats: bool,
635    pub fdt_position: Option<FdtPosition>,
636    #[cfg(all(target_os = "android", target_arch = "aarch64"))]
637    pub ffa: Option<FfaConfig>,
638    pub file_backed_mappings_mmio: Vec<FileBackedMappingParameters>,
639    pub file_backed_mappings_ram: Vec<FileBackedMappingParameters>,
640    pub force_calibrated_tsc_leaf: bool,
641    pub force_disable_readonly_mem: bool,
642    pub force_s2idle: bool,
643    pub fw_cfg_parameters: Vec<FwCfgParameters>,
644    #[cfg(feature = "gdb")]
645    pub gdb: Option<u32>,
646    #[cfg(all(windows, feature = "gpu"))]
647    pub gpu_backend_config: Option<GpuBackendConfig>,
648    #[cfg(all(unix, feature = "gpu"))]
649    pub gpu_cgroup_path: Option<PathBuf>,
650    #[cfg(feature = "gpu")]
651    pub gpu_parameters: Option<GpuParameters>,
652    #[cfg(all(unix, feature = "gpu"))]
653    pub gpu_render_server_parameters: Option<GpuRenderServerParameters>,
654    #[cfg(all(unix, feature = "gpu"))]
655    pub gpu_server_cgroup_path: Option<PathBuf>,
656    #[cfg(all(windows, feature = "gpu"))]
657    pub gpu_vmm_config: Option<GpuVmmConfig>,
658    pub host_cpu_topology: bool,
659    #[cfg(windows)]
660    pub host_guid: Option<String>,
661    pub hugepages: bool,
662    pub hypervisor: Option<HypervisorKind>,
663    #[cfg(feature = "balloon")]
664    pub init_memory: Option<u64>,
665    pub initrd_path: Option<PathBuf>,
666    #[cfg(all(windows, feature = "gpu"))]
667    pub input_event_split_config: Option<InputEventSplitConfig>,
668    pub irq_chip: Option<IrqChipKind>,
669    pub itmt: bool,
670    pub jail_config: Option<JailConfig>,
671    #[cfg(windows)]
672    pub kernel_log_file: Option<String>,
673    #[cfg(any(target_os = "android", target_os = "linux"))]
674    pub lock_guest_memory: bool,
675    #[cfg(windows)]
676    pub log_file: Option<String>,
677    #[cfg(windows)]
678    pub logs_directory: Option<String>,
679    #[cfg(all(feature = "media", feature = "video-decoder"))]
680    pub media_decoder: Vec<VideoDeviceConfig>,
681    pub memory: Option<u64>,
682    pub memory_file: Option<PathBuf>,
683    pub mmio_address_ranges: Vec<AddressRange>,
684    #[cfg(target_arch = "aarch64")]
685    pub mte: ToggleMode,
686    pub name: Option<String>,
687    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
688    pub nested: NestedConfig,
689    #[cfg(windows)]
690    pub net_vhost_user_tube: Option<Tube>,
691    pub no_i8042: bool,
692    pub no_pmu: bool,
693    pub no_rtc: bool,
694    pub no_smt: bool,
695    pub params: Vec<String>,
696    pub pci_config: PciConfig,
697    #[cfg(feature = "pci-hotplug")]
698    pub pci_hotplug_slots: Option<u8>,
699    pub per_vm_core_scheduling: bool,
700    pub pflash_parameters: Option<PflashParameters>,
701    #[cfg(feature = "process-invariants")]
702    pub process_invariants_data_handle: Option<u64>,
703    #[cfg(feature = "process-invariants")]
704    pub process_invariants_data_size: Option<usize>,
705    #[cfg(windows)]
706    pub product_channel: Option<String>,
707    #[cfg(windows)]
708    pub product_name: Option<String>,
709    #[cfg(windows)]
710    pub product_version: Option<String>,
711    pub protection_type: ProtectionType,
712    pub pstore: Option<Pstore>,
713    #[cfg(feature = "pvclock")]
714    pub pvclock: bool,
715    /// Must be `Some` iff `protection_type == ProtectionType::UnprotectedWithFirmware`.
716    pub pvm_fw: Option<PathBuf>,
717    pub restore_path: Option<PathBuf>,
718    pub rt_cpus: CpuSet,
719    /// Note: virtio-console devices are present both in the serial_parameters field and in the
720    /// virtio_device_modules field. They are only present in serial_parameters so that they get
721    /// included in the get_serial_cmdline flow.
722    #[serde(with = "serde_serial_params")]
723    pub serial_parameters: BTreeMap<(SerialHardware, u8), SerialParameters>,
724    #[cfg(windows)]
725    pub service_pipe_name: Option<String>,
726    #[cfg(feature = "media")]
727    pub simple_media_device: bool,
728    #[cfg(any(feature = "slirp-ring-capture", feature = "slirp-debug"))]
729    pub slirp_capture_file: Option<String>,
730    #[cfg(target_arch = "x86_64")]
731    pub smbios: SmbiosOptions,
732    pub smccc_trng: bool,
733    #[cfg(all(windows, feature = "audio"))]
734    pub snd_split_configs: Vec<SndSplitConfig>,
735    pub socket_path: Option<PathBuf>,
736    #[cfg(feature = "audio")]
737    pub sound: Option<PathBuf>,
738    pub stub_pci_devices: Vec<StubPciParameters>,
739    pub suspended: bool,
740    pub suspended_vcpus: bool,
741    #[cfg(target_arch = "aarch64")]
742    pub sve: Option<SveConfig>,
743    pub swap_dir: Option<PathBuf>,
744    pub swiotlb: Option<u64>,
745    #[cfg(target_os = "android")]
746    pub task_profiles: Vec<String>,
747    #[cfg(any(target_os = "android", target_os = "linux"))]
748    pub unmap_guest_memory_on_fork: bool,
749    pub usb: bool,
750    #[cfg(any(target_os = "android", target_os = "linux"))]
751    #[cfg(feature = "media")]
752    pub v4l2_proxy: Vec<PathBuf>,
753    pub vcpu_affinity: Option<VcpuAffinity>,
754    pub vcpu_cgroup_path: Option<PathBuf>,
755    pub vcpu_count: Option<usize>,
756    #[cfg(target_arch = "x86_64")]
757    pub vcpu_hybrid_type: BTreeMap<usize, CpuHybridType>, // CPU index -> hybrid type
758    #[cfg(any(target_os = "android", target_os = "linux"))]
759    pub vfio: Vec<super::sys::config::VfioOption>,
760    #[cfg(any(target_os = "android", target_os = "linux"))]
761    pub vfio_isolate_hotplug: bool,
762    #[cfg(any(target_os = "android", target_os = "linux"))]
763    pub vfio_platform_pm: bool,
764    #[cfg(any(target_os = "android", target_os = "linux"))]
765    #[cfg(target_arch = "aarch64")]
766    pub vhost_scmi: bool,
767    #[cfg(any(target_os = "android", target_os = "linux"))]
768    #[cfg(target_arch = "aarch64")]
769    pub vhost_scmi_device: PathBuf,
770    pub vhost_user: Vec<VhostUserFrontendOption>,
771    pub vhost_user_connect_timeout_ms: Option<u64>,
772    #[cfg(feature = "video-decoder")]
773    pub video_dec: Vec<VideoDeviceConfig>,
774    #[cfg(feature = "video-encoder")]
775    pub video_enc: Vec<VideoDeviceConfig>,
776    #[cfg(all(
777        target_arch = "aarch64",
778        any(target_os = "android", target_os = "linux")
779    ))]
780    pub virt_cpufreq: bool,
781    pub virt_cpufreq_v2: bool,
782    #[serde(default)]
783    pub virtio_device_modules: Vec<AnyVirtioDeviceModule>,
784    pub virtio_input: Vec<InputDeviceOption>,
785    pub wayland_socket_paths: BTreeMap<String, PathBuf>,
786    #[cfg(all(windows, feature = "gpu"))]
787    pub window_procedure_thread_split_config: Option<WindowProcedureThreadSplitConfig>,
788    pub x_display: Option<String>,
789}
790
791impl Default for Config {
792    fn default() -> Config {
793        Config {
794            acpi_tables: Vec::new(),
795            #[cfg(feature = "android_display")]
796            android_display_service: None,
797            android_fstab: None,
798            async_executor: None,
799            #[cfg(feature = "balloon")]
800            balloon: true,
801            #[cfg(feature = "balloon")]
802            balloon_bias: 0,
803            #[cfg(feature = "balloon")]
804            balloon_control: None,
805            #[cfg(feature = "balloon")]
806            balloon_page_reporting: false,
807            #[cfg(feature = "balloon")]
808            balloon_ws_num_bins: VIRTIO_BALLOON_WS_DEFAULT_NUM_BINS,
809            #[cfg(feature = "balloon")]
810            balloon_ws_reporting: false,
811            battery_config: None,
812            boot_cpu: 0,
813            #[cfg(windows)]
814            block_control_tube: Vec::new(),
815            #[cfg(windows)]
816            block_vhost_user_tube: Vec::new(),
817            #[cfg(target_arch = "x86_64")]
818            break_linux_pci_config_io: false,
819            #[cfg(windows)]
820            broker_shutdown_event: None,
821            #[cfg(target_arch = "x86_64")]
822            bus_lock_ratelimit: 0,
823            #[cfg(any(target_os = "android", target_os = "linux"))]
824            coiommu_param: None,
825            core_scheduling: true,
826            #[cfg(feature = "crash-report")]
827            crash_pipe_name: None,
828            #[cfg(feature = "crash-report")]
829            crash_report_uuid: None,
830            cpu_capacity: BTreeMap::new(),
831            cpu_clusters: Vec::new(),
832            #[cfg(all(
833                target_arch = "aarch64",
834                any(target_os = "android", target_os = "linux")
835            ))]
836            cpu_frequencies_khz: BTreeMap::new(),
837            cpu_freq_domains: Vec::new(),
838            #[cfg(all(
839                target_arch = "aarch64",
840                any(target_os = "android", target_os = "linux")
841            ))]
842            cpu_ipc_ratio: BTreeMap::new(),
843            delay_rt: false,
844            device_tree_overlay: Vec::new(),
845            dev_pm: None,
846            #[cfg(windows)]
847            disks_auto_vhost_user: Vec::new(),
848            disable_virtio_intx: false,
849            display_input_height: None,
850            display_input_width: None,
851            display_window_keyboard: false,
852            display_window_mouse: false,
853            dump_device_tree_blob: None,
854            dynamic_power_coefficient: BTreeMap::new(),
855            enable_fw_cfg: false,
856            enable_hwp: false,
857            executable_path: None,
858            #[cfg(windows)]
859            exit_stats: false,
860            fdt_position: None,
861            #[cfg(all(target_os = "android", target_arch = "aarch64"))]
862            ffa: None,
863            file_backed_mappings_mmio: Vec::new(),
864            file_backed_mappings_ram: Vec::new(),
865            force_calibrated_tsc_leaf: false,
866            force_disable_readonly_mem: false,
867            force_s2idle: false,
868            fw_cfg_parameters: Vec::new(),
869            #[cfg(feature = "gdb")]
870            gdb: None,
871            #[cfg(all(windows, feature = "gpu"))]
872            gpu_backend_config: None,
873            #[cfg(feature = "gpu")]
874            gpu_parameters: None,
875            #[cfg(all(unix, feature = "gpu"))]
876            gpu_render_server_parameters: None,
877            #[cfg(all(unix, feature = "gpu"))]
878            gpu_cgroup_path: None,
879            #[cfg(all(unix, feature = "gpu"))]
880            gpu_server_cgroup_path: None,
881            #[cfg(all(windows, feature = "gpu"))]
882            gpu_vmm_config: None,
883            host_cpu_topology: false,
884            #[cfg(windows)]
885            host_guid: None,
886            #[cfg(windows)]
887            product_version: None,
888            #[cfg(windows)]
889            product_channel: None,
890            hugepages: false,
891            hypervisor: None,
892            #[cfg(feature = "balloon")]
893            init_memory: None,
894            initrd_path: None,
895            #[cfg(all(windows, feature = "gpu"))]
896            input_event_split_config: None,
897            irq_chip: None,
898            itmt: false,
899            jail_config: if !cfg!(feature = "default-no-sandbox") {
900                Some(Default::default())
901            } else {
902                None
903            },
904            #[cfg(windows)]
905            kernel_log_file: None,
906            #[cfg(any(target_os = "android", target_os = "linux"))]
907            lock_guest_memory: false,
908            #[cfg(windows)]
909            log_file: None,
910            #[cfg(windows)]
911            logs_directory: None,
912            #[cfg(any(target_os = "android", target_os = "linux"))]
913            boost_uclamp: false,
914            #[cfg(all(feature = "media", feature = "video-decoder"))]
915            media_decoder: Default::default(),
916            memory: None,
917            memory_file: None,
918            mmio_address_ranges: Vec::new(),
919            #[cfg(target_arch = "aarch64")]
920            mte: ToggleMode::Off,
921            name: None,
922            #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
923            nested: NestedConfig::default(),
924            #[cfg(windows)]
925            net_vhost_user_tube: None,
926            no_i8042: false,
927            no_pmu: false,
928            no_rtc: false,
929            no_smt: false,
930            params: Vec::new(),
931            pci_config: Default::default(),
932            #[cfg(feature = "pci-hotplug")]
933            pci_hotplug_slots: None,
934            per_vm_core_scheduling: false,
935            pflash_parameters: None,
936            #[cfg(feature = "process-invariants")]
937            process_invariants_data_handle: None,
938            #[cfg(feature = "process-invariants")]
939            process_invariants_data_size: None,
940            #[cfg(windows)]
941            product_name: None,
942            protection_type: ProtectionType::Unprotected,
943            pstore: None,
944            #[cfg(feature = "pvclock")]
945            pvclock: false,
946            pvm_fw: None,
947            restore_path: None,
948            rt_cpus: Default::default(),
949            serial_parameters: BTreeMap::new(),
950            #[cfg(windows)]
951            service_pipe_name: None,
952            #[cfg(feature = "media")]
953            simple_media_device: Default::default(),
954            #[cfg(any(feature = "slirp-ring-capture", feature = "slirp-debug"))]
955            slirp_capture_file: None,
956            #[cfg(target_arch = "x86_64")]
957            smbios: SmbiosOptions::default(),
958            smccc_trng: false,
959            #[cfg(all(windows, feature = "audio"))]
960            snd_split_configs: Vec::new(),
961            socket_path: None,
962            #[cfg(feature = "audio")]
963            sound: None,
964            stub_pci_devices: Vec::new(),
965            suspended: false,
966            suspended_vcpus: false,
967            #[cfg(target_arch = "aarch64")]
968            sve: None,
969            swap_dir: None,
970            swiotlb: None,
971            #[cfg(target_os = "android")]
972            task_profiles: Vec::new(),
973            #[cfg(any(target_os = "android", target_os = "linux"))]
974            unmap_guest_memory_on_fork: false,
975            usb: true,
976            vcpu_affinity: None,
977            vcpu_cgroup_path: None,
978            vcpu_count: None,
979            #[cfg(target_arch = "x86_64")]
980            vcpu_hybrid_type: BTreeMap::new(),
981            #[cfg(any(target_os = "android", target_os = "linux"))]
982            vfio: Vec::new(),
983            #[cfg(any(target_os = "android", target_os = "linux"))]
984            vfio_isolate_hotplug: false,
985            #[cfg(any(target_os = "android", target_os = "linux"))]
986            vfio_platform_pm: false,
987            #[cfg(any(target_os = "android", target_os = "linux"))]
988            #[cfg(target_arch = "aarch64")]
989            vhost_scmi: false,
990            #[cfg(any(target_os = "android", target_os = "linux"))]
991            #[cfg(target_arch = "aarch64")]
992            vhost_scmi_device: PathBuf::from(VHOST_SCMI_PATH),
993            vhost_user: Vec::new(),
994            vhost_user_connect_timeout_ms: None,
995            #[cfg(feature = "video-decoder")]
996            video_dec: Vec::new(),
997            #[cfg(feature = "video-encoder")]
998            video_enc: Vec::new(),
999            #[cfg(all(
1000                target_arch = "aarch64",
1001                any(target_os = "android", target_os = "linux")
1002            ))]
1003            virt_cpufreq: false,
1004            virt_cpufreq_v2: false,
1005            virtio_device_modules: Vec::new(),
1006            virtio_input: Vec::new(),
1007            #[cfg(any(target_os = "android", target_os = "linux"))]
1008            #[cfg(feature = "media")]
1009            v4l2_proxy: Vec::new(),
1010            wayland_socket_paths: BTreeMap::new(),
1011            #[cfg(windows)]
1012            window_procedure_thread_split_config: None,
1013            x_display: None,
1014        }
1015    }
1016}
1017
1018pub fn validate_config(cfg: &mut Config) -> std::result::Result<(), String> {
1019    if cfg.executable_path.is_none() {
1020        return Err("Executable is not specified".to_string());
1021    }
1022
1023    #[cfg(feature = "gpu")]
1024    {
1025        crate::crosvm::gpu_config::validate_gpu_config(cfg)?;
1026    }
1027    #[cfg(feature = "gdb")]
1028    if cfg.gdb.is_some() && cfg.vcpu_count.unwrap_or(1) != 1 {
1029        return Err("`gdb` requires the number of vCPU to be 1".to_string());
1030    }
1031    if cfg.host_cpu_topology {
1032        if cfg.no_smt {
1033            return Err(
1034                "`host-cpu-topology` cannot be set at the same time as `no_smt`, since \
1035                the smt of the Guest is the same as that of the Host when \
1036                `host-cpu-topology` is set."
1037                    .to_string(),
1038            );
1039        }
1040
1041        let pcpu_count =
1042            base::number_of_online_cores().expect("Could not read number of online cores");
1043        if let Some(vcpu_count) = cfg.vcpu_count {
1044            if pcpu_count != vcpu_count {
1045                return Err(format!(
1046                    "`host-cpu-topology` requires the count of vCPUs({vcpu_count}) to equal the \
1047                            count of online CPUs({pcpu_count}) on host."
1048                ));
1049            }
1050        } else {
1051            cfg.vcpu_count = Some(pcpu_count);
1052        }
1053
1054        match &cfg.vcpu_affinity {
1055            None => {
1056                let vcpu_count = cfg.vcpu_count.unwrap();
1057                let max_cores = base::number_of_logical_cores()
1058                    .expect("Could not read number of logical cores");
1059                let affinity_map =
1060                    default_vcpu_affinity_map(vcpu_count, max_cores, base::is_cpu_online);
1061                cfg.vcpu_affinity = Some(VcpuAffinity::PerVcpu(affinity_map));
1062            }
1063            _ => {
1064                return Err(
1065                    "`host-cpu-topology` requires not to set `cpu-affinity` at the same time"
1066                        .to_string(),
1067                );
1068            }
1069        }
1070
1071        if !cfg.cpu_capacity.is_empty() {
1072            return Err(
1073                "`host-cpu-topology` requires not to set `cpu-capacity` at the same time"
1074                    .to_string(),
1075            );
1076        }
1077
1078        if !cfg.cpu_clusters.is_empty() {
1079            return Err(
1080                "`host-cpu-topology` requires not to set `cpu clusters` at the same time"
1081                    .to_string(),
1082            );
1083        }
1084    }
1085
1086    if cfg.boot_cpu >= cfg.vcpu_count.unwrap_or(1) {
1087        log::warn!("boot_cpu selection cannot be higher than vCPUs available, defaulting to 0");
1088        cfg.boot_cpu = 0;
1089    }
1090
1091    #[cfg(all(
1092        target_arch = "aarch64",
1093        any(target_os = "android", target_os = "linux")
1094    ))]
1095    if !cfg.cpu_frequencies_khz.is_empty() {
1096        if !cfg.virt_cpufreq_v2 {
1097            return Err("`cpu-frequencies` requires `virt-cpufreq-upstream`".to_string());
1098        }
1099
1100        if cfg.host_cpu_topology {
1101            return Err(
1102                "`host-cpu-topology` cannot be used with 'cpu-frequencies` at the same time"
1103                    .to_string(),
1104            );
1105        }
1106    }
1107
1108    #[cfg(all(
1109        target_arch = "aarch64",
1110        any(target_os = "android", target_os = "linux")
1111    ))]
1112    if cfg.virt_cpufreq {
1113        if !cfg.host_cpu_topology && (cfg.vcpu_affinity.is_none() || cfg.cpu_capacity.is_empty()) {
1114            return Err("`virt-cpufreq` requires 'host-cpu-topology' enabled or \
1115                       have vcpu_affinity and cpu_capacity configured"
1116                .to_string());
1117        }
1118    }
1119    #[cfg(target_arch = "x86_64")]
1120    if !cfg.vcpu_hybrid_type.is_empty() {
1121        if cfg.host_cpu_topology {
1122            return Err("`core-types` cannot be set with `host-cpu-topology`.".to_string());
1123        }
1124        check_host_hybrid_support(&CpuIdCall::new(__cpuid_count, __cpuid))
1125            .map_err(|e| format!("the cpu doesn't support `core-types`: {e}"))?;
1126        if cfg.vcpu_hybrid_type.len() != cfg.vcpu_count.unwrap_or(1) {
1127            return Err("`core-types` must be set for all virtual CPUs".to_string());
1128        }
1129        for cpu_id in 0..cfg.vcpu_count.unwrap_or(1) {
1130            if !cfg.vcpu_hybrid_type.contains_key(&cpu_id) {
1131                return Err("`core-types` must be set for all virtual CPUs".to_string());
1132            }
1133        }
1134    }
1135    #[cfg(target_arch = "x86_64")]
1136    if cfg.enable_hwp && !cfg.host_cpu_topology {
1137        return Err("setting `enable-hwp` requires `host-cpu-topology` is set.".to_string());
1138    }
1139    #[cfg(target_arch = "x86_64")]
1140    if cfg.itmt {
1141        use std::collections::BTreeSet;
1142        // ITMT only works on the case each vCPU is 1:1 mapping to a pCPU.
1143        // `host-cpu-topology` has already set this 1:1 mapping. If no
1144        // `host-cpu-topology`, we need check the cpu affinity setting.
1145        if !cfg.host_cpu_topology {
1146            // only VcpuAffinity::PerVcpu supports setting cpu affinity
1147            // for each vCPU.
1148            if let Some(VcpuAffinity::PerVcpu(v)) = &cfg.vcpu_affinity {
1149                // ITMT allows more pCPUs than vCPUs.
1150                if v.len() != cfg.vcpu_count.unwrap_or(1) {
1151                    return Err("`itmt` requires affinity to be set for every vCPU.".to_string());
1152                }
1153
1154                let mut pcpu_set = BTreeSet::new();
1155                for cpus in v.values() {
1156                    if cpus.len() != 1 {
1157                        return Err(
1158                            "`itmt` requires affinity to be set 1 pCPU for 1 vCPU.".to_owned()
1159                        );
1160                    }
1161                    // Ensure that each vCPU corresponds to a different pCPU to avoid pCPU sharing,
1162                    // otherwise it will seriously affect the ITMT scheduling optimization effect.
1163                    if !pcpu_set.insert(cpus[0]) {
1164                        return Err(
1165                            "`cpu_host` requires affinity to be set different pVPU for each vCPU."
1166                                .to_owned(),
1167                        );
1168                    }
1169                }
1170            } else {
1171                return Err("`itmt` requires affinity to be set for every vCPU.".to_string());
1172            }
1173        }
1174        if !cfg.enable_hwp {
1175            return Err("setting `itmt` requires `enable-hwp` is set.".to_string());
1176        }
1177    }
1178
1179    #[cfg(feature = "balloon")]
1180    {
1181        if !cfg.balloon && cfg.balloon_control.is_some() {
1182            return Err("'balloon-control' requires enabled balloon".to_string());
1183        }
1184
1185        if !cfg.balloon && cfg.balloon_page_reporting {
1186            return Err("'balloon_page_reporting' requires enabled balloon".to_string());
1187        }
1188    }
1189
1190    // TODO(b/253386409): Vmm-swap only support sandboxed devices until vmm-swap use
1191    // `devices::Suspendable` to suspend devices.
1192    #[cfg(feature = "swap")]
1193    if cfg.swap_dir.is_some() && cfg.jail_config.is_none() {
1194        return Err("'swap' and 'disable-sandbox' are mutually exclusive".to_string());
1195    }
1196
1197    set_default_serial_parameters(
1198        &mut cfg.serial_parameters,
1199        cfg.vhost_user
1200            .iter()
1201            .any(|opt| opt.type_ == DeviceType::Console),
1202    );
1203
1204    for mapping in cfg
1205        .file_backed_mappings_mmio
1206        .iter_mut()
1207        .chain(cfg.file_backed_mappings_ram.iter_mut())
1208    {
1209        validate_file_backed_mapping(mapping)?;
1210    }
1211
1212    // Validate platform specific things
1213    super::sys::config::validate_config(cfg)
1214}
1215
1216fn default_vcpu_affinity_map(
1217    vcpu_count: usize,
1218    max_cores: usize,
1219    is_cpu_online: impl Fn(usize) -> bool,
1220) -> BTreeMap<usize, CpuSet> {
1221    let mut affinity_map = BTreeMap::new();
1222    let mut vcpu_id = 0;
1223    for cpu_id in 0..max_cores {
1224        if is_cpu_online(cpu_id) {
1225            affinity_map.insert(vcpu_id, CpuSet::new([cpu_id]));
1226            vcpu_id += 1;
1227        }
1228        if vcpu_id >= vcpu_count {
1229            // Exit early if we've allocated all the vcpu's.
1230            break;
1231        }
1232    }
1233    affinity_map
1234}
1235
1236fn validate_file_backed_mapping(mapping: &mut FileBackedMappingParameters) -> Result<(), String> {
1237    let pagesize_mask = pagesize() as u64 - 1;
1238    let aligned_address = mapping.address & !pagesize_mask;
1239    let aligned_size =
1240        ((mapping.address + mapping.size + pagesize_mask) & !pagesize_mask) - aligned_address;
1241
1242    if mapping.align {
1243        mapping.address = aligned_address;
1244        mapping.size = aligned_size;
1245    } else if aligned_address != mapping.address || aligned_size != mapping.size {
1246        return Err(
1247            "--file-backed-mapping addr and size parameters must be page size aligned".to_string(),
1248        );
1249    }
1250
1251    Ok(())
1252}
1253
1254#[cfg(test)]
1255#[allow(clippy::needless_update)]
1256mod tests {
1257    use argh::FromArgs;
1258    use devices::PciClassCode;
1259    use devices::StubPciParameters;
1260    #[cfg(target_arch = "x86_64")]
1261    use uuid::uuid;
1262
1263    use super::*;
1264
1265    fn config_from_args(args: &[&str]) -> Config {
1266        crate::crosvm::cmdline::RunCommand::from_args(&[], args)
1267            .unwrap()
1268            .try_into()
1269            .unwrap()
1270    }
1271
1272    #[test]
1273    fn parse_cpu_opts() {
1274        let res: CpuOptions = from_key_values("").unwrap();
1275        assert_eq!(res, CpuOptions::default());
1276
1277        // num_cores
1278        let res: CpuOptions = from_key_values("12").unwrap();
1279        assert_eq!(
1280            res,
1281            CpuOptions {
1282                num_cores: Some(12),
1283                ..Default::default()
1284            }
1285        );
1286
1287        let res: CpuOptions = from_key_values("num-cores=16").unwrap();
1288        assert_eq!(
1289            res,
1290            CpuOptions {
1291                num_cores: Some(16),
1292                ..Default::default()
1293            }
1294        );
1295
1296        // clusters
1297        let res: CpuOptions = from_key_values("clusters=[[0],[1],[2],[3]]").unwrap();
1298        assert_eq!(
1299            res,
1300            CpuOptions {
1301                clusters: vec![
1302                    CpuSet::new([0]),
1303                    CpuSet::new([1]),
1304                    CpuSet::new([2]),
1305                    CpuSet::new([3])
1306                ],
1307                ..Default::default()
1308            }
1309        );
1310
1311        let res: CpuOptions = from_key_values("clusters=[[0-3]]").unwrap();
1312        assert_eq!(
1313            res,
1314            CpuOptions {
1315                clusters: vec![CpuSet::new([0, 1, 2, 3])],
1316                ..Default::default()
1317            }
1318        );
1319
1320        let res: CpuOptions = from_key_values("clusters=[[0,2],[1,3],[4-7,12]]").unwrap();
1321        assert_eq!(
1322            res,
1323            CpuOptions {
1324                clusters: vec![
1325                    CpuSet::new([0, 2]),
1326                    CpuSet::new([1, 3]),
1327                    CpuSet::new([4, 5, 6, 7, 12])
1328                ],
1329                ..Default::default()
1330            }
1331        );
1332
1333        #[cfg(target_arch = "x86_64")]
1334        {
1335            let res: CpuOptions = from_key_values("core-types=[atom=[1,3-7],core=[0,2]]").unwrap();
1336            assert_eq!(
1337                res,
1338                CpuOptions {
1339                    core_types: Some(CpuCoreType {
1340                        atom: CpuSet::new([1, 3, 4, 5, 6, 7]),
1341                        core: CpuSet::new([0, 2])
1342                    }),
1343                    ..Default::default()
1344                }
1345            );
1346        }
1347
1348        // All together
1349        let res: CpuOptions = from_key_values("16,clusters=[[0],[4-6],[7]]").unwrap();
1350        assert_eq!(
1351            res,
1352            CpuOptions {
1353                num_cores: Some(16),
1354                clusters: vec![CpuSet::new([0]), CpuSet::new([4, 5, 6]), CpuSet::new([7])],
1355                ..Default::default()
1356            }
1357        );
1358
1359        let res: CpuOptions = from_key_values("clusters=[[0-7],[30-31]],num-cores=32").unwrap();
1360        assert_eq!(
1361            res,
1362            CpuOptions {
1363                num_cores: Some(32),
1364                clusters: vec![CpuSet::new([0, 1, 2, 3, 4, 5, 6, 7]), CpuSet::new([30, 31])],
1365                ..Default::default()
1366            }
1367        );
1368    }
1369
1370    #[test]
1371    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
1372    fn parse_nested_config() {
1373        for (arg, mode) in [
1374            ("off", NestedMode::Off),
1375            ("auto", NestedMode::Auto),
1376            ("on", NestedMode::On),
1377            ("mode=off", NestedMode::Off),
1378            ("mode=auto", NestedMode::Auto),
1379            ("mode=on", NestedMode::On),
1380        ] {
1381            assert_eq!(
1382                from_key_values::<NestedConfig>(arg).unwrap(),
1383                NestedConfig { mode }
1384            );
1385        }
1386        #[cfg(target_arch = "x86_64")]
1387        assert_eq!(NestedConfig::default().mode, NestedMode::Auto);
1388        #[cfg(target_arch = "aarch64")]
1389        assert_eq!(NestedConfig::default().mode, NestedMode::Off);
1390
1391        from_key_values::<NestedConfig>("maybe").unwrap_err();
1392        from_key_values::<NestedConfig>("mode=maybe").unwrap_err();
1393        from_key_values::<NestedConfig>("bogus=true").unwrap_err();
1394    }
1395
1396    #[test]
1397    #[cfg(target_arch = "aarch64")]
1398    fn parse_cpu_mte_config() {
1399        assert_eq!(
1400            from_key_values::<CpuOptions>("mte=[auto=true]")
1401                .unwrap()
1402                .mte,
1403            Some(MteConfig { auto: true })
1404        );
1405        assert_eq!(
1406            from_key_values::<CpuOptions>("mte=[auto=false]")
1407                .unwrap()
1408                .mte,
1409            Some(MteConfig { auto: false })
1410        );
1411    }
1412
1413    #[test]
1414    fn parse_cpu_set_single() {
1415        assert_eq!(
1416            CpuSet::from_str("123").expect("parse failed"),
1417            CpuSet::new([123])
1418        );
1419    }
1420
1421    #[test]
1422    fn parse_cpu_set_list() {
1423        assert_eq!(
1424            CpuSet::from_str("0,1,2,3").expect("parse failed"),
1425            CpuSet::new([0, 1, 2, 3])
1426        );
1427    }
1428
1429    #[test]
1430    fn parse_cpu_set_range() {
1431        assert_eq!(
1432            CpuSet::from_str("0-3").expect("parse failed"),
1433            CpuSet::new([0, 1, 2, 3])
1434        );
1435    }
1436
1437    #[test]
1438    fn parse_cpu_set_list_of_ranges() {
1439        assert_eq!(
1440            CpuSet::from_str("3-4,7-9,18").expect("parse failed"),
1441            CpuSet::new([3, 4, 7, 8, 9, 18])
1442        );
1443    }
1444
1445    #[test]
1446    fn parse_cpu_set_repeated() {
1447        // For now, allow duplicates - they will be handled gracefully by the vec to cpu_set_t
1448        // conversion.
1449        assert_eq!(
1450            CpuSet::from_str("1,1,1").expect("parse failed"),
1451            CpuSet::new([1, 1, 1])
1452        );
1453    }
1454
1455    #[test]
1456    fn parse_cpu_set_negative() {
1457        // Negative CPU numbers are not allowed.
1458        CpuSet::from_str("-3").expect_err("parse should have failed");
1459    }
1460
1461    #[test]
1462    fn parse_cpu_set_reverse_range() {
1463        // Ranges must be from low to high.
1464        CpuSet::from_str("5-2").expect_err("parse should have failed");
1465    }
1466
1467    #[test]
1468    fn parse_cpu_set_open_range() {
1469        CpuSet::from_str("3-").expect_err("parse should have failed");
1470    }
1471
1472    #[test]
1473    fn parse_cpu_set_extra_comma() {
1474        CpuSet::from_str("0,1,2,").expect_err("parse should have failed");
1475    }
1476
1477    #[test]
1478    fn parse_cpu_affinity_global() {
1479        assert_eq!(
1480            parse_cpu_affinity("0,5-7,9").expect("parse failed"),
1481            VcpuAffinity::Global(CpuSet::new([0, 5, 6, 7, 9])),
1482        );
1483    }
1484
1485    #[test]
1486    fn parse_cpu_affinity_per_vcpu_one_to_one() {
1487        let mut expected_map = BTreeMap::new();
1488        expected_map.insert(0, CpuSet::new([0]));
1489        expected_map.insert(1, CpuSet::new([1]));
1490        expected_map.insert(2, CpuSet::new([2]));
1491        expected_map.insert(3, CpuSet::new([3]));
1492        assert_eq!(
1493            parse_cpu_affinity("0=0:1=1:2=2:3=3").expect("parse failed"),
1494            VcpuAffinity::PerVcpu(expected_map),
1495        );
1496    }
1497
1498    #[test]
1499    fn parse_cpu_affinity_per_vcpu_sets() {
1500        let mut expected_map = BTreeMap::new();
1501        expected_map.insert(0, CpuSet::new([0, 1, 2]));
1502        expected_map.insert(1, CpuSet::new([3, 4, 5]));
1503        expected_map.insert(2, CpuSet::new([6, 7, 8]));
1504        assert_eq!(
1505            parse_cpu_affinity("0=0,1,2:1=3-5:2=6,7-8").expect("parse failed"),
1506            VcpuAffinity::PerVcpu(expected_map),
1507        );
1508    }
1509
1510    #[test]
1511    fn parse_mem_opts() {
1512        let res: MemOptions = from_key_values("").unwrap();
1513        assert_eq!(res.size, None);
1514
1515        let res: MemOptions = from_key_values("1024").unwrap();
1516        assert_eq!(res.size, Some(1024));
1517
1518        let res: MemOptions = from_key_values("size=0x4000").unwrap();
1519        assert_eq!(res.size, Some(16384));
1520    }
1521
1522    #[test]
1523    fn parse_serial_vaild() {
1524        parse_serial_options("type=syslog,num=1,console=true,stdin=true")
1525            .expect("parse should have succeded");
1526    }
1527
1528    #[test]
1529    fn parse_serial_virtio_console_vaild() {
1530        parse_serial_options("type=syslog,num=5,console=true,stdin=true,hardware=virtio-console")
1531            .expect("parse should have succeded");
1532    }
1533
1534    #[test]
1535    fn parse_serial_valid_no_num() {
1536        parse_serial_options("type=syslog").expect("parse should have succeded");
1537    }
1538
1539    #[test]
1540    fn parse_serial_equals_in_value() {
1541        let parsed = parse_serial_options("type=syslog,path=foo=bar==.log")
1542            .expect("parse should have succeded");
1543        assert_eq!(parsed.path, Some(PathBuf::from("foo=bar==.log")));
1544    }
1545
1546    #[test]
1547    fn parse_serial_invalid_type() {
1548        parse_serial_options("type=wormhole,num=1").expect_err("parse should have failed");
1549    }
1550
1551    #[test]
1552    fn parse_serial_invalid_num_upper() {
1553        parse_serial_options("type=syslog,num=5").expect_err("parse should have failed");
1554    }
1555
1556    #[test]
1557    fn parse_serial_invalid_num_lower() {
1558        parse_serial_options("type=syslog,num=0").expect_err("parse should have failed");
1559    }
1560
1561    #[test]
1562    fn parse_serial_virtio_console_invalid_num_lower() {
1563        parse_serial_options("type=syslog,hardware=virtio-console,num=0")
1564            .expect_err("parse should have failed");
1565    }
1566
1567    #[test]
1568    fn parse_serial_max_queue_sizes_validation() {
1569        let parsed =
1570            parse_serial_options("type=sink,hardware=virtio-console,max-queue-sizes=[128,256]")
1571                .expect("parse should have succeeded");
1572        assert_eq!(parsed.max_queue_sizes, Some(vec![128, 256]));
1573
1574        parse_serial_options("type=sink,hardware=serial,max-queue-sizes=[128,256]")
1575            .expect_err("expected max-queue-sizes error for serial hardware");
1576        parse_serial_options("type=sink,hardware=virtio-console,max-queue-sizes=[128]")
1577            .expect_err("expected max-queue-sizes length error");
1578        parse_serial_options("type=sink,hardware=virtio-console,max-queue-sizes=[0,256]")
1579            .expect_err("expected max-queue-sizes power-of-two error for 0");
1580        parse_serial_options("type=sink,hardware=virtio-console,max-queue-sizes=[3,256]")
1581            .expect_err("expected max-queue-sizes power-of-two error for 3");
1582    }
1583
1584    #[test]
1585    fn parse_serial_invalid_num_string() {
1586        parse_serial_options("type=syslog,num=number3").expect_err("parse should have failed");
1587    }
1588
1589    #[test]
1590    fn parse_serial_invalid_option() {
1591        parse_serial_options("type=syslog,speed=lightspeed").expect_err("parse should have failed");
1592    }
1593
1594    #[test]
1595    fn parse_serial_invalid_two_stdin() {
1596        assert!(TryInto::<Config>::try_into(
1597            crate::crosvm::cmdline::RunCommand::from_args(
1598                &[],
1599                &[
1600                    "--serial",
1601                    "num=1,type=stdout,stdin=true",
1602                    "--serial",
1603                    "num=2,type=stdout,stdin=true"
1604                ]
1605            )
1606            .unwrap()
1607        )
1608        .is_err())
1609    }
1610
1611    #[test]
1612    fn parse_serial_pci_address_valid_for_virtio() {
1613        let parsed =
1614            parse_serial_options("type=syslog,hardware=virtio-console,pci-address=00:0e.0")
1615                .expect("parse should have succeded");
1616        assert_eq!(
1617            parsed.pci_address,
1618            Some(PciAddress {
1619                bus: 0,
1620                dev: 14,
1621                func: 0
1622            })
1623        );
1624    }
1625
1626    #[test]
1627    fn parse_serial_pci_address_valid_for_legacy_virtio() {
1628        let parsed =
1629            parse_serial_options("type=syslog,hardware=legacy-virtio-console,pci-address=00:0e.0")
1630                .expect("parse should have succeded");
1631        assert_eq!(
1632            parsed.pci_address,
1633            Some(PciAddress {
1634                bus: 0,
1635                dev: 14,
1636                func: 0
1637            })
1638        );
1639    }
1640
1641    #[test]
1642    fn parse_serial_pci_address_failed_for_serial() {
1643        parse_serial_options("type=syslog,hardware=serial,pci-address=00:0e.0")
1644            .expect_err("expected pci-address error for serial hardware");
1645    }
1646
1647    #[test]
1648    fn parse_serial_pci_address_failed_for_debugcon() {
1649        parse_serial_options("type=syslog,hardware=debugcon,pci-address=00:0e.0")
1650            .expect_err("expected pci-address error for debugcon hardware");
1651    }
1652
1653    #[test]
1654    fn parse_battery_valid() {
1655        let bat_config: BatteryConfig = from_key_values("type=goldfish").unwrap();
1656        assert_eq!(bat_config.type_, BatteryType::Goldfish);
1657    }
1658
1659    #[test]
1660    fn parse_battery_valid_no_type() {
1661        let bat_config: BatteryConfig = from_key_values("").unwrap();
1662        assert_eq!(bat_config.type_, BatteryType::Goldfish);
1663    }
1664
1665    #[test]
1666    fn parse_battery_invalid_parameter() {
1667        from_key_values::<BatteryConfig>("tyep=goldfish").expect_err("parse should have failed");
1668    }
1669
1670    #[test]
1671    fn parse_battery_invalid_type_value() {
1672        from_key_values::<BatteryConfig>("type=xxx").expect_err("parse should have failed");
1673    }
1674
1675    #[test]
1676    fn parse_irqchip_kernel() {
1677        let cfg = TryInto::<Config>::try_into(
1678            crate::crosvm::cmdline::RunCommand::from_args(
1679                &[],
1680                &["--irqchip", "kernel", "/dev/null"],
1681            )
1682            .unwrap(),
1683        )
1684        .unwrap();
1685
1686        assert_eq!(
1687            cfg.irq_chip,
1688            Some(IrqChipKind::Kernel {
1689                #[cfg(target_arch = "aarch64")]
1690                allow_vgic_its: false
1691            })
1692        );
1693    }
1694
1695    #[test]
1696    #[cfg(target_arch = "aarch64")]
1697    fn parse_irqchip_kernel_with_its() {
1698        let cfg = TryInto::<Config>::try_into(
1699            crate::crosvm::cmdline::RunCommand::from_args(
1700                &[],
1701                &["--irqchip", "kernel[allow-vgic-its]", "/dev/null"],
1702            )
1703            .unwrap(),
1704        )
1705        .unwrap();
1706
1707        assert_eq!(
1708            cfg.irq_chip,
1709            Some(IrqChipKind::Kernel {
1710                allow_vgic_its: true
1711            })
1712        );
1713    }
1714
1715    #[test]
1716    fn parse_irqchip_split() {
1717        let cfg = TryInto::<Config>::try_into(
1718            crate::crosvm::cmdline::RunCommand::from_args(
1719                &[],
1720                &["--irqchip", "split", "/dev/null"],
1721            )
1722            .unwrap(),
1723        )
1724        .unwrap();
1725
1726        assert_eq!(cfg.irq_chip, Some(IrqChipKind::Split));
1727    }
1728
1729    #[test]
1730    fn parse_irqchip_userspace() {
1731        let cfg = TryInto::<Config>::try_into(
1732            crate::crosvm::cmdline::RunCommand::from_args(
1733                &[],
1734                &["--irqchip", "userspace", "/dev/null"],
1735            )
1736            .unwrap(),
1737        )
1738        .unwrap();
1739
1740        assert_eq!(cfg.irq_chip, Some(IrqChipKind::Userspace));
1741    }
1742
1743    #[test]
1744    fn parse_stub_pci() {
1745        let params = from_key_values::<StubPciParameters>("0000:01:02.3,vendor=0xfffe,device=0xfffd,class=0xffc1c2,subsystem_vendor=0xfffc,subsystem_device=0xfffb,revision=0xa").unwrap();
1746        assert_eq!(params.address.bus, 1);
1747        assert_eq!(params.address.dev, 2);
1748        assert_eq!(params.address.func, 3);
1749        assert_eq!(params.vendor, 0xfffe);
1750        assert_eq!(params.device, 0xfffd);
1751        assert_eq!(params.class.class as u8, PciClassCode::Other as u8);
1752        assert_eq!(params.class.subclass, 0xc1);
1753        assert_eq!(params.class.programming_interface, 0xc2);
1754        assert_eq!(params.subsystem_vendor, 0xfffc);
1755        assert_eq!(params.subsystem_device, 0xfffb);
1756        assert_eq!(params.revision, 0xa);
1757    }
1758
1759    #[test]
1760    fn parse_file_backed_mapping_valid() {
1761        let params = from_key_values::<FileBackedMappingParameters>(
1762            "addr=0x1000,size=0x2000,path=/dev/mem,offset=0x3000,rw,sync",
1763        )
1764        .unwrap();
1765        assert_eq!(params.address, 0x1000);
1766        assert_eq!(params.size, 0x2000);
1767        assert_eq!(params.path, PathBuf::from("/dev/mem"));
1768        assert_eq!(params.offset, 0x3000);
1769        assert!(params.writable);
1770        assert!(params.sync);
1771    }
1772
1773    #[test]
1774    fn parse_file_backed_mapping_incomplete() {
1775        assert!(
1776            from_key_values::<FileBackedMappingParameters>("addr=0x1000,size=0x2000")
1777                .unwrap_err()
1778                .contains("missing field `path`")
1779        );
1780        assert!(
1781            from_key_values::<FileBackedMappingParameters>("size=0x2000,path=/dev/mem")
1782                .unwrap_err()
1783                .contains("missing field `addr`")
1784        );
1785        assert!(
1786            from_key_values::<FileBackedMappingParameters>("addr=0x1000,path=/dev/mem")
1787                .unwrap_err()
1788                .contains("missing field `size`")
1789        );
1790    }
1791
1792    #[test]
1793    fn parse_file_backed_mapping_unaligned_addr() {
1794        let mut params =
1795            from_key_values::<FileBackedMappingParameters>("addr=0x1001,size=0x2000,path=/dev/mem")
1796                .unwrap();
1797        assert!(validate_file_backed_mapping(&mut params)
1798            .unwrap_err()
1799            .contains("aligned"));
1800    }
1801    #[test]
1802    fn parse_file_backed_mapping_unaligned_size() {
1803        let mut params =
1804            from_key_values::<FileBackedMappingParameters>("addr=0x1000,size=0x2001,path=/dev/mem")
1805                .unwrap();
1806        assert!(validate_file_backed_mapping(&mut params)
1807            .unwrap_err()
1808            .contains("aligned"));
1809    }
1810
1811    #[test]
1812    fn parse_file_backed_mapping_align() {
1813        let addr = pagesize() as u64 * 3 + 42;
1814        let size = pagesize() as u64 - 0xf;
1815        let mut params = from_key_values::<FileBackedMappingParameters>(&format!(
1816            "addr={addr},size={size},path=/dev/mem,align",
1817        ))
1818        .unwrap();
1819        assert_eq!(params.address, addr);
1820        assert_eq!(params.size, size);
1821        validate_file_backed_mapping(&mut params).unwrap();
1822        assert_eq!(params.address, pagesize() as u64 * 3);
1823        assert_eq!(params.size, pagesize() as u64 * 2);
1824    }
1825
1826    #[test]
1827    fn parse_fw_cfg_valid_path() {
1828        let cfg = TryInto::<Config>::try_into(
1829            crate::crosvm::cmdline::RunCommand::from_args(
1830                &[],
1831                &["--fw-cfg", "name=bar,path=data.bin", "/dev/null"],
1832            )
1833            .unwrap(),
1834        )
1835        .unwrap();
1836
1837        assert_eq!(cfg.fw_cfg_parameters.len(), 1);
1838        assert_eq!(cfg.fw_cfg_parameters[0].name, "bar".to_string());
1839        assert_eq!(cfg.fw_cfg_parameters[0].string, None);
1840        assert_eq!(cfg.fw_cfg_parameters[0].path, Some("data.bin".into()));
1841    }
1842
1843    #[test]
1844    fn parse_fw_cfg_valid_string() {
1845        let cfg = TryInto::<Config>::try_into(
1846            crate::crosvm::cmdline::RunCommand::from_args(
1847                &[],
1848                &["--fw-cfg", "name=bar,string=foo", "/dev/null"],
1849            )
1850            .unwrap(),
1851        )
1852        .unwrap();
1853
1854        assert_eq!(cfg.fw_cfg_parameters.len(), 1);
1855        assert_eq!(cfg.fw_cfg_parameters[0].name, "bar".to_string());
1856        assert_eq!(cfg.fw_cfg_parameters[0].string, Some("foo".to_string()));
1857        assert_eq!(cfg.fw_cfg_parameters[0].path, None);
1858    }
1859
1860    #[test]
1861    fn parse_dtbo() {
1862        let cfg: Config = crate::crosvm::cmdline::RunCommand::from_args(
1863            &[],
1864            &[
1865                "--device-tree-overlay",
1866                "/path/to/dtbo1",
1867                "--device-tree-overlay",
1868                "/path/to/dtbo2",
1869                "/dev/null",
1870            ],
1871        )
1872        .unwrap()
1873        .try_into()
1874        .unwrap();
1875
1876        assert_eq!(cfg.device_tree_overlay.len(), 2);
1877        for (opt, p) in cfg
1878            .device_tree_overlay
1879            .into_iter()
1880            .zip(["/path/to/dtbo1", "/path/to/dtbo2"])
1881        {
1882            assert_eq!(opt.path, PathBuf::from(p));
1883            assert!(opt.select_symbols.is_none());
1884        }
1885    }
1886
1887    #[test]
1888    #[cfg(any(target_os = "android", target_os = "linux"))]
1889    fn parse_dtbo_filtered() {
1890        let cfg: Config = crate::crosvm::cmdline::RunCommand::from_args(
1891            &[],
1892            &[
1893                "--vfio",
1894                "/path/to/dev",
1895                "--device-tree-overlay",
1896                "/path/to/dtbo1,select-symbols=[mydev]",
1897                "--device-tree-overlay",
1898                "/path/to/dtbo2,select-symbols=[mydev]",
1899                "/dev/null",
1900            ],
1901        )
1902        .unwrap()
1903        .try_into()
1904        .unwrap();
1905
1906        assert_eq!(cfg.device_tree_overlay.len(), 2);
1907        for (opt, p) in cfg
1908            .device_tree_overlay
1909            .into_iter()
1910            .zip(["/path/to/dtbo1", "/path/to/dtbo2"])
1911        {
1912            assert_eq!(opt.path, PathBuf::from(p));
1913            assert_eq!(opt.select_symbols, Some(vec!["mydev".to_string()]));
1914        }
1915    }
1916
1917    #[test]
1918    #[cfg(any(target_os = "android", target_os = "linux"))]
1919    fn parse_dtbo_legacy_filter() {
1920        let cfg: Config = crate::crosvm::cmdline::RunCommand::from_args(
1921            &[],
1922            &[
1923                "--vfio",
1924                "/path/to/dev,dt-symbol=mydev",
1925                "--device-tree-overlay",
1926                "/path/to/dtbo1,filter",
1927                "/dev/null",
1928            ],
1929        )
1930        .unwrap()
1931        .try_into()
1932        .unwrap();
1933
1934        assert_eq!(cfg.device_tree_overlay.len(), 1);
1935        let opt = cfg.device_tree_overlay.first().unwrap();
1936        assert_eq!(opt.path, PathBuf::from("/path/to/dtbo1"));
1937        assert_eq!(opt.select_symbols, Some(vec!["mydev".to_string()]));
1938    }
1939
1940    #[test]
1941    #[cfg(any(target_os = "android", target_os = "linux"))]
1942    fn parse_dtbo_filter_and_select_symbols() {
1943        let cfg: Config = crate::crosvm::cmdline::RunCommand::from_args(
1944            &[],
1945            &[
1946                "--vfio",
1947                "/path/to/dev,dt-symbol=mydev",
1948                "--device-tree-overlay",
1949                "/path/to/dtbo1,filter,select-symbols=[otherdev]",
1950                "/dev/null",
1951            ],
1952        )
1953        .unwrap()
1954        .try_into()
1955        .unwrap();
1956
1957        assert_eq!(cfg.device_tree_overlay.len(), 1);
1958        let opt = cfg.device_tree_overlay.first().unwrap();
1959        assert_eq!(opt.path, PathBuf::from("/path/to/dtbo1"));
1960        assert_eq!(
1961            opt.select_symbols,
1962            Some(vec!["otherdev".to_string(), "mydev".to_string()])
1963        );
1964    }
1965
1966    #[test]
1967    fn parse_fw_cfg_invalid_no_name() {
1968        assert!(
1969            crate::crosvm::cmdline::RunCommand::from_args(&[], &["--fw-cfg", "string=foo",])
1970                .is_err()
1971        );
1972    }
1973
1974    #[cfg(any(feature = "video-decoder", feature = "video-encoder"))]
1975    #[test]
1976    fn parse_video() {
1977        use devices::virtio::device_constants::video::VideoBackendType;
1978
1979        #[cfg(feature = "libvda")]
1980        {
1981            let params: VideoDeviceConfig = from_key_values("libvda").unwrap();
1982            assert_eq!(params.backend, VideoBackendType::Libvda);
1983
1984            let params: VideoDeviceConfig = from_key_values("libvda-vd").unwrap();
1985            assert_eq!(params.backend, VideoBackendType::LibvdaVd);
1986        }
1987
1988        #[cfg(feature = "ffmpeg")]
1989        {
1990            let params: VideoDeviceConfig = from_key_values("ffmpeg").unwrap();
1991            assert_eq!(params.backend, VideoBackendType::Ffmpeg);
1992        }
1993
1994        #[cfg(feature = "vaapi")]
1995        {
1996            let params: VideoDeviceConfig = from_key_values("vaapi").unwrap();
1997            assert_eq!(params.backend, VideoBackendType::Vaapi);
1998        }
1999    }
2000
2001    #[test]
2002    fn parse_vhost_user_option_all_device_types() {
2003        fn test_device_type(type_string: &str, type_: DeviceType) {
2004            let vhost_user_arg = format!("{type_string},socket=sock");
2005
2006            let cfg = TryInto::<Config>::try_into(
2007                crate::crosvm::cmdline::RunCommand::from_args(
2008                    &[],
2009                    &["--vhost-user", &vhost_user_arg, "/dev/null"],
2010                )
2011                .unwrap(),
2012            )
2013            .unwrap();
2014
2015            assert_eq!(cfg.vhost_user.len(), 1);
2016            let vu = &cfg.vhost_user[0];
2017            assert_eq!(vu.type_, type_);
2018        }
2019
2020        test_device_type("net", DeviceType::Net);
2021        test_device_type("block", DeviceType::Block);
2022        test_device_type("console", DeviceType::Console);
2023        test_device_type("rng", DeviceType::Rng);
2024        test_device_type("balloon", DeviceType::Balloon);
2025        test_device_type("scsi", DeviceType::Scsi);
2026        test_device_type("9p", DeviceType::P9);
2027        test_device_type("gpu", DeviceType::Gpu);
2028        test_device_type("input", DeviceType::Input);
2029        test_device_type("vsock", DeviceType::Vsock);
2030        test_device_type("iommu", DeviceType::Iommu);
2031        test_device_type("sound", DeviceType::Sound);
2032        test_device_type("fs", DeviceType::Fs);
2033        test_device_type("pmem", DeviceType::Pmem);
2034        test_device_type("mac80211-hwsim", DeviceType::Mac80211HwSim);
2035        test_device_type("video-encoder", DeviceType::VideoEncoder);
2036        test_device_type("video-decoder", DeviceType::VideoDecoder);
2037        test_device_type("scmi", DeviceType::Scmi);
2038        test_device_type("wl", DeviceType::Wl);
2039        test_device_type("tpm", DeviceType::Tpm);
2040        test_device_type("pvclock", DeviceType::Pvclock);
2041    }
2042
2043    #[cfg(target_arch = "x86_64")]
2044    #[test]
2045    fn parse_smbios_uuid() {
2046        let opt: SmbiosOptions =
2047            from_key_values("uuid=12e474af-2cc1-49d1-b0e5-d03a3e03ca03").unwrap();
2048        assert_eq!(
2049            opt.uuid,
2050            Some(uuid!("12e474af-2cc1-49d1-b0e5-d03a3e03ca03"))
2051        );
2052
2053        from_key_values::<SmbiosOptions>("uuid=zzzz").expect_err("expected error parsing uuid");
2054    }
2055
2056    #[test]
2057    fn parse_touch_legacy() {
2058        let cfg = TryInto::<Config>::try_into(
2059            crate::crosvm::cmdline::RunCommand::from_args(
2060                &[],
2061                &["--multi-touch", "my_socket:867:5309", "bzImage"],
2062            )
2063            .unwrap(),
2064        )
2065        .unwrap();
2066
2067        assert_eq!(cfg.virtio_input.len(), 1);
2068        let multi_touch = cfg
2069            .virtio_input
2070            .iter()
2071            .find(|input| matches!(input, InputDeviceOption::MultiTouch { .. }))
2072            .unwrap();
2073        assert_eq!(
2074            *multi_touch,
2075            InputDeviceOption::MultiTouch {
2076                path: PathBuf::from("my_socket"),
2077                width: Some(867),
2078                height: Some(5309),
2079                name: None
2080            }
2081        );
2082    }
2083
2084    #[test]
2085    fn parse_touch() {
2086        let cfg = TryInto::<Config>::try_into(
2087            crate::crosvm::cmdline::RunCommand::from_args(
2088                &[],
2089                &["--multi-touch", r"C:\path,width=867,height=5309", "bzImage"],
2090            )
2091            .unwrap(),
2092        )
2093        .unwrap();
2094
2095        assert_eq!(cfg.virtio_input.len(), 1);
2096        let multi_touch = cfg
2097            .virtio_input
2098            .iter()
2099            .find(|input| matches!(input, InputDeviceOption::MultiTouch { .. }))
2100            .unwrap();
2101        assert_eq!(
2102            *multi_touch,
2103            InputDeviceOption::MultiTouch {
2104                path: PathBuf::from(r"C:\path"),
2105                width: Some(867),
2106                height: Some(5309),
2107                name: None
2108            }
2109        );
2110    }
2111
2112    #[test]
2113    fn single_touch_spec_and_track_pad_spec_default_size() {
2114        let config: Config = crate::crosvm::cmdline::RunCommand::from_args(
2115            &[],
2116            &[
2117                "--single-touch",
2118                "/dev/single-touch-test",
2119                "--trackpad",
2120                "/dev/single-touch-test",
2121                "/dev/null",
2122            ],
2123        )
2124        .unwrap()
2125        .try_into()
2126        .unwrap();
2127
2128        let single_touch = config
2129            .virtio_input
2130            .iter()
2131            .find(|input| matches!(input, InputDeviceOption::SingleTouch { .. }))
2132            .unwrap();
2133        let trackpad = config
2134            .virtio_input
2135            .iter()
2136            .find(|input| matches!(input, InputDeviceOption::Trackpad { .. }))
2137            .unwrap();
2138
2139        assert_eq!(
2140            *single_touch,
2141            InputDeviceOption::SingleTouch {
2142                path: PathBuf::from("/dev/single-touch-test"),
2143                width: None,
2144                height: None,
2145                name: None
2146            }
2147        );
2148        assert_eq!(
2149            *trackpad,
2150            InputDeviceOption::Trackpad {
2151                path: PathBuf::from("/dev/single-touch-test"),
2152                width: None,
2153                height: None,
2154                name: None
2155            }
2156        );
2157    }
2158
2159    #[cfg(feature = "gpu")]
2160    #[test]
2161    fn single_touch_spec_default_size_from_gpu() {
2162        let config: Config = crate::crosvm::cmdline::RunCommand::from_args(
2163            &[],
2164            &[
2165                "--single-touch",
2166                "/dev/single-touch-test",
2167                "--gpu",
2168                "width=1024,height=768",
2169                "/dev/null",
2170            ],
2171        )
2172        .unwrap()
2173        .try_into()
2174        .unwrap();
2175
2176        let single_touch = config
2177            .virtio_input
2178            .iter()
2179            .find(|input| matches!(input, InputDeviceOption::SingleTouch { .. }))
2180            .unwrap();
2181        assert_eq!(
2182            *single_touch,
2183            InputDeviceOption::SingleTouch {
2184                path: PathBuf::from("/dev/single-touch-test"),
2185                width: None,
2186                height: None,
2187                name: None
2188            }
2189        );
2190
2191        assert_eq!(config.display_input_width, Some(1024));
2192        assert_eq!(config.display_input_height, Some(768));
2193    }
2194
2195    #[test]
2196    fn single_touch_spec_and_track_pad_spec_with_size() {
2197        let config: Config = crate::crosvm::cmdline::RunCommand::from_args(
2198            &[],
2199            &[
2200                "--single-touch",
2201                "/dev/single-touch-test:12345:54321",
2202                "--trackpad",
2203                "/dev/single-touch-test:5678:9876",
2204                "/dev/null",
2205            ],
2206        )
2207        .unwrap()
2208        .try_into()
2209        .unwrap();
2210
2211        let single_touch = config
2212            .virtio_input
2213            .iter()
2214            .find(|input| matches!(input, InputDeviceOption::SingleTouch { .. }))
2215            .unwrap();
2216        let trackpad = config
2217            .virtio_input
2218            .iter()
2219            .find(|input| matches!(input, InputDeviceOption::Trackpad { .. }))
2220            .unwrap();
2221
2222        assert_eq!(
2223            *single_touch,
2224            InputDeviceOption::SingleTouch {
2225                path: PathBuf::from("/dev/single-touch-test"),
2226                width: Some(12345),
2227                height: Some(54321),
2228                name: None
2229            }
2230        );
2231        assert_eq!(
2232            *trackpad,
2233            InputDeviceOption::Trackpad {
2234                path: PathBuf::from("/dev/single-touch-test"),
2235                width: Some(5678),
2236                height: Some(9876),
2237                name: None
2238            }
2239        );
2240    }
2241
2242    #[cfg(feature = "gpu")]
2243    #[test]
2244    fn single_touch_spec_with_size_independent_from_gpu() {
2245        let config: Config = crate::crosvm::cmdline::RunCommand::from_args(
2246            &[],
2247            &[
2248                "--single-touch",
2249                "/dev/single-touch-test:12345:54321",
2250                "--gpu",
2251                "width=1024,height=768",
2252                "/dev/null",
2253            ],
2254        )
2255        .unwrap()
2256        .try_into()
2257        .unwrap();
2258
2259        let single_touch = config
2260            .virtio_input
2261            .iter()
2262            .find(|input| matches!(input, InputDeviceOption::SingleTouch { .. }))
2263            .unwrap();
2264
2265        assert_eq!(
2266            *single_touch,
2267            InputDeviceOption::SingleTouch {
2268                path: PathBuf::from("/dev/single-touch-test"),
2269                width: Some(12345),
2270                height: Some(54321),
2271                name: None
2272            }
2273        );
2274
2275        assert_eq!(config.display_input_width, Some(1024));
2276        assert_eq!(config.display_input_height, Some(768));
2277    }
2278
2279    #[test]
2280    fn virtio_switches() {
2281        let config: Config = crate::crosvm::cmdline::RunCommand::from_args(
2282            &[],
2283            &["--switches", "/dev/switches-test", "/dev/null"],
2284        )
2285        .unwrap()
2286        .try_into()
2287        .unwrap();
2288
2289        let switches = config
2290            .virtio_input
2291            .iter()
2292            .find(|input| matches!(input, InputDeviceOption::Switches { .. }))
2293            .unwrap();
2294
2295        assert_eq!(
2296            *switches,
2297            InputDeviceOption::Switches {
2298                path: PathBuf::from("/dev/switches-test")
2299            }
2300        );
2301    }
2302
2303    #[test]
2304    fn virtio_rotary() {
2305        let config: Config = crate::crosvm::cmdline::RunCommand::from_args(
2306            &[],
2307            &["--rotary", "/dev/rotary-test", "/dev/null"],
2308        )
2309        .unwrap()
2310        .try_into()
2311        .unwrap();
2312
2313        let rotary = config
2314            .virtio_input
2315            .iter()
2316            .find(|input| matches!(input, InputDeviceOption::Rotary { .. }))
2317            .unwrap();
2318
2319        assert_eq!(
2320            *rotary,
2321            InputDeviceOption::Rotary {
2322                path: PathBuf::from("/dev/rotary-test")
2323            }
2324        );
2325    }
2326
2327    #[cfg(target_arch = "aarch64")]
2328    #[test]
2329    fn parse_pci_cam() {
2330        assert_eq!(
2331            config_from_args(&["--pci", "cam=[start=0x123]", "/dev/null"]).pci_config,
2332            PciConfig {
2333                cam: Some(arch::MemoryRegionConfig {
2334                    start: 0x123,
2335                    size: None,
2336                }),
2337                ..PciConfig::default()
2338            }
2339        );
2340        assert_eq!(
2341            config_from_args(&["--pci", "cam=[start=0x123,size=0x456]", "/dev/null"]).pci_config,
2342            PciConfig {
2343                cam: Some(arch::MemoryRegionConfig {
2344                    start: 0x123,
2345                    size: Some(0x456),
2346                }),
2347                ..PciConfig::default()
2348            },
2349        );
2350    }
2351
2352    #[cfg(target_arch = "x86_64")]
2353    #[test]
2354    fn parse_pci_ecam() {
2355        assert_eq!(
2356            config_from_args(&["--pci", "ecam=[start=0x123]", "/dev/null"]).pci_config,
2357            PciConfig {
2358                ecam: Some(arch::MemoryRegionConfig {
2359                    start: 0x123,
2360                    size: None,
2361                }),
2362                ..PciConfig::default()
2363            }
2364        );
2365        assert_eq!(
2366            config_from_args(&["--pci", "ecam=[start=0x123,size=0x456]", "/dev/null"]).pci_config,
2367            PciConfig {
2368                ecam: Some(arch::MemoryRegionConfig {
2369                    start: 0x123,
2370                    size: Some(0x456),
2371                }),
2372                ..PciConfig::default()
2373            },
2374        );
2375    }
2376
2377    #[test]
2378    fn parse_pci_mem() {
2379        assert_eq!(
2380            config_from_args(&["--pci", "mem=[start=0x123]", "/dev/null"]).pci_config,
2381            PciConfig {
2382                mem: Some(arch::MemoryRegionConfig {
2383                    start: 0x123,
2384                    size: None,
2385                }),
2386                ..PciConfig::default()
2387            }
2388        );
2389        assert_eq!(
2390            config_from_args(&["--pci", "mem=[start=0x123,size=0x456]", "/dev/null"]).pci_config,
2391            PciConfig {
2392                mem: Some(arch::MemoryRegionConfig {
2393                    start: 0x123,
2394                    size: Some(0x456),
2395                }),
2396                ..PciConfig::default()
2397            },
2398        );
2399    }
2400
2401    #[test]
2402    fn test_default_vcpu_affinity_map() {
2403        // Simple 1:1 mapping of vcpu:cpu.
2404        let affinity = default_vcpu_affinity_map(4, 4, |_| true);
2405        assert_eq!(affinity.len(), 4);
2406        assert_eq!(affinity.get(&0), Some(&CpuSet::new([0])));
2407        assert_eq!(affinity.get(&1), Some(&CpuSet::new([1])));
2408        assert_eq!(affinity.get(&2), Some(&CpuSet::new([2])));
2409        assert_eq!(affinity.get(&3), Some(&CpuSet::new([3])));
2410
2411        // cpu 1 is offline, so skip it when assigning vcpu's.
2412        let affinity = default_vcpu_affinity_map(3, 4, |id| id != 1);
2413        assert_eq!(affinity.len(), 3);
2414        assert_eq!(affinity.get(&0), Some(&CpuSet::new([0])));
2415        assert_eq!(affinity.get(&1), Some(&CpuSet::new([2])));
2416        assert_eq!(affinity.get(&2), Some(&CpuSet::new([3])));
2417    }
2418}