crosvm/crosvm/sys/linux/
pci_hotplug_helpers.rs

1// Copyright 2023 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//! Helper functions for PCI hotplug.
6
7#![deny(missing_docs)]
8
9use anyhow::Context;
10use anyhow::Result;
11use devices::HotPluggable;
12use devices::IntxParameter;
13use devices::NetResourceCarrier;
14use devices::PciDevice;
15use devices::VirtioPciDevice;
16use hypervisor::ProtectionType;
17use vm_memory::GuestMemory;
18
19use crate::crosvm::sys::linux::VirtioDeviceBuilder;
20
21/// Builds HotPlugPci from NetResourceCarrier and NetLocalParameters.
22pub fn build_hotplug_net_device(
23    net_carrier_device: NetResourceCarrier,
24    net_local_parameters: NetLocalParameters,
25) -> Result<Box<dyn HotPluggable>> {
26    let pci_address = net_carrier_device
27        .pci_address
28        .context("PCI address not allocated")?;
29    let virtio_device = net_carrier_device
30        .net_param
31        .create_virtio_device(net_local_parameters.protection_type)
32        .context("create virtio device")?;
33    let mut virtio_pci_device = VirtioPciDevice::new(
34        net_local_parameters.guest_memory,
35        virtio_device,
36        net_carrier_device.msi_device_tube,
37        true,
38        None,
39        net_carrier_device.ioevent_vm_memory_client,
40        net_carrier_device.vm_control_tube,
41    )
42    .context("create virtio PCI device")?;
43    virtio_pci_device
44        .set_pci_address(pci_address)
45        .context("set PCI address")?;
46    virtio_pci_device
47        .configure_io_bars()
48        .context("configure IO BAR")?;
49    virtio_pci_device
50        .configure_device_bars()
51        .context("configure device BAR")?;
52    let IntxParameter {
53        irq_evt,
54        irq_num,
55        pin,
56    } = net_carrier_device
57        .intx_parameter
58        .context("Missing INTx parameter.")?;
59    virtio_pci_device.assign_irq(irq_evt, pin, irq_num);
60    Ok(Box::new(virtio_pci_device))
61}
62
63/// Additional parameters required on the destination process to configure net VirtioPciDevice.
64pub struct NetLocalParameters {
65    guest_memory: GuestMemory,
66    protection_type: ProtectionType,
67}
68
69impl NetLocalParameters {
70    /// Constructs NetLocalParameters.
71    pub fn new(guest_memory: GuestMemory, protection_type: ProtectionType) -> Self {
72        Self {
73            guest_memory,
74            protection_type,
75        }
76    }
77}