devices/virtio/
virtio_pci_device.rs

1// Copyright 2018 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::any::Any;
6use std::collections::BTreeMap;
7use std::sync::Arc;
8
9#[cfg(target_arch = "x86_64")]
10use acpi_tables::sdt::SDT;
11use anyhow::anyhow;
12use anyhow::Context;
13use base::debug;
14use base::error;
15use base::trace;
16use base::AsRawDescriptor;
17use base::AsRawDescriptors;
18use base::Event;
19use base::Protection;
20use base::RawDescriptor;
21use base::Result;
22use base::SharedMemory;
23use base::Tube;
24use base::WorkerThread;
25use data_model::Le32;
26use hypervisor::Datamatch;
27use hypervisor::MemCacheType;
28use libc::ERANGE;
29#[cfg(target_arch = "x86_64")]
30use metrics::MetricEventType;
31use resources::AddressRange;
32use resources::Alloc;
33use resources::AllocOptions;
34use resources::SystemAllocator;
35use serde::Deserialize;
36use serde::Serialize;
37use snapshot::AnySnapshot;
38use sync::Mutex;
39use virtio_sys::virtio_config::VIRTIO_CONFIG_S_ACKNOWLEDGE;
40use virtio_sys::virtio_config::VIRTIO_CONFIG_S_DRIVER;
41use virtio_sys::virtio_config::VIRTIO_CONFIG_S_DRIVER_OK;
42use virtio_sys::virtio_config::VIRTIO_CONFIG_S_FAILED;
43use virtio_sys::virtio_config::VIRTIO_CONFIG_S_FEATURES_OK;
44use virtio_sys::virtio_config::VIRTIO_CONFIG_S_NEEDS_RESET;
45use virtio_sys::virtio_config::VIRTIO_CONFIG_S_SUSPEND;
46use vm_control::api::VmMemoryClient;
47use vm_control::PciId;
48use vm_control::VmMemoryDestination;
49use vm_control::VmMemoryRegionId;
50use vm_control::VmMemorySource;
51use vm_memory::GuestMemory;
52use zerocopy::FromBytes;
53use zerocopy::Immutable;
54use zerocopy::IntoBytes;
55use zerocopy::KnownLayout;
56
57use self::virtio_pci_common_config::VirtioPciCommonConfig;
58use super::*;
59#[cfg(target_arch = "x86_64")]
60use crate::acpi::PmWakeupEvent;
61#[cfg(target_arch = "x86_64")]
62use crate::pci::pm::PciDevicePower;
63use crate::pci::pm::PciPmCap;
64use crate::pci::pm::PmConfig;
65use crate::pci::pm::PmStatusChange;
66use crate::pci::BarRange;
67use crate::pci::MsixCap;
68use crate::pci::MsixConfig;
69use crate::pci::MsixStatus;
70use crate::pci::PciAddress;
71use crate::pci::PciBarConfiguration;
72use crate::pci::PciBarIndex;
73use crate::pci::PciBarPrefetchable;
74use crate::pci::PciBarRegionType;
75use crate::pci::PciBaseSystemPeripheralSubclass;
76use crate::pci::PciCapability;
77use crate::pci::PciCapabilityID;
78use crate::pci::PciClassCode;
79use crate::pci::PciConfiguration;
80use crate::pci::PciDevice;
81use crate::pci::PciDeviceError;
82use crate::pci::PciDisplaySubclass;
83use crate::pci::PciHeaderType;
84use crate::pci::PciInputDeviceSubclass;
85use crate::pci::PciInterruptPin;
86use crate::pci::PciMassStorageSubclass;
87use crate::pci::PciMultimediaSubclass;
88use crate::pci::PciNetworkControllerSubclass;
89use crate::pci::PciSimpleCommunicationControllerSubclass;
90use crate::pci::PciSubclass;
91use crate::pci::PciWirelessControllerSubclass;
92use crate::virtio::ipc_memory_mapper::IpcMemoryMapper;
93#[cfg(feature = "pci-hotplug")]
94use crate::HotPluggable;
95use crate::IrqLevelEvent;
96use crate::Suspendable;
97
98#[repr(u8)]
99#[derive(Debug, Copy, Clone, enumn::N)]
100pub enum PciCapabilityType {
101    CommonConfig = 1,
102    NotifyConfig = 2,
103    IsrConfig = 3,
104    DeviceConfig = 4,
105    PciConfig = 5,
106    // Doorbell, Notification and SharedMemory are Virtio Vhost User related PCI
107    // capabilities. Specified in 5.7.7.4 here
108    // https://stefanha.github.io/virtio/vhost-user-slave.html#x1-2830007.
109    DoorbellConfig = 6,
110    NotificationConfig = 7,
111    SharedMemoryConfig = 8,
112}
113
114#[allow(dead_code)]
115#[repr(C)]
116#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)]
117pub struct VirtioPciCap {
118    // cap_vndr and cap_next are autofilled based on id() in pci configuration
119    pub cap_vndr: u8, // Generic PCI field: PCI_CAP_ID_VNDR
120    pub cap_next: u8, // Generic PCI field: next ptr
121    pub cap_len: u8,  // Generic PCI field: capability length
122    pub cfg_type: u8, // Identifies the structure.
123    pub bar: u8,      // Where to find it.
124    id: u8,           // Multiple capabilities of the same type
125    padding: [u8; 2], // Pad to full dword.
126    pub offset: Le32, // Offset within bar.
127    pub length: Le32, // Length of the structure, in bytes.
128}
129
130impl PciCapability for VirtioPciCap {
131    fn bytes(&self) -> &[u8] {
132        self.as_bytes()
133    }
134
135    fn id(&self) -> PciCapabilityID {
136        PciCapabilityID::VendorSpecific
137    }
138
139    fn writable_bits(&self) -> Vec<u32> {
140        vec![0u32; 4]
141    }
142}
143
144impl VirtioPciCap {
145    pub fn new(cfg_type: PciCapabilityType, bar: u8, offset: u32, length: u32) -> Self {
146        VirtioPciCap {
147            cap_vndr: 0,
148            cap_next: 0,
149            cap_len: std::mem::size_of::<VirtioPciCap>() as u8,
150            cfg_type: cfg_type as u8,
151            bar,
152            id: 0,
153            padding: [0; 2],
154            offset: Le32::from(offset),
155            length: Le32::from(length),
156        }
157    }
158
159    pub fn set_cap_len(&mut self, cap_len: u8) {
160        self.cap_len = cap_len;
161    }
162}
163
164#[allow(dead_code)]
165#[repr(C)]
166#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)]
167pub struct VirtioPciNotifyCap {
168    cap: VirtioPciCap,
169    notify_off_multiplier: Le32,
170}
171
172impl PciCapability for VirtioPciNotifyCap {
173    fn bytes(&self) -> &[u8] {
174        self.as_bytes()
175    }
176
177    fn id(&self) -> PciCapabilityID {
178        PciCapabilityID::VendorSpecific
179    }
180
181    fn writable_bits(&self) -> Vec<u32> {
182        vec![0u32; 5]
183    }
184}
185
186impl VirtioPciNotifyCap {
187    pub fn new(
188        cfg_type: PciCapabilityType,
189        bar: u8,
190        offset: u32,
191        length: u32,
192        multiplier: Le32,
193    ) -> Self {
194        VirtioPciNotifyCap {
195            cap: VirtioPciCap {
196                cap_vndr: 0,
197                cap_next: 0,
198                cap_len: std::mem::size_of::<VirtioPciNotifyCap>() as u8,
199                cfg_type: cfg_type as u8,
200                bar,
201                id: 0,
202                padding: [0; 2],
203                offset: Le32::from(offset),
204                length: Le32::from(length),
205            },
206            notify_off_multiplier: multiplier,
207        }
208    }
209}
210
211#[repr(C)]
212#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)]
213pub struct VirtioPciShmCap {
214    cap: VirtioPciCap,
215    offset_hi: Le32, // Most sig 32 bits of offset
216    length_hi: Le32, // Most sig 32 bits of length
217}
218
219impl PciCapability for VirtioPciShmCap {
220    fn bytes(&self) -> &[u8] {
221        self.as_bytes()
222    }
223
224    fn id(&self) -> PciCapabilityID {
225        PciCapabilityID::VendorSpecific
226    }
227
228    fn writable_bits(&self) -> Vec<u32> {
229        vec![0u32; 6]
230    }
231}
232
233impl VirtioPciShmCap {
234    pub fn new(cfg_type: PciCapabilityType, bar: u8, offset: u64, length: u64, shmid: u8) -> Self {
235        VirtioPciShmCap {
236            cap: VirtioPciCap {
237                cap_vndr: 0,
238                cap_next: 0,
239                cap_len: std::mem::size_of::<VirtioPciShmCap>() as u8,
240                cfg_type: cfg_type as u8,
241                bar,
242                id: shmid,
243                padding: [0; 2],
244                offset: Le32::from(offset as u32),
245                length: Le32::from(length as u32),
246            },
247            offset_hi: Le32::from((offset >> 32) as u32),
248            length_hi: Le32::from((length >> 32) as u32),
249        }
250    }
251}
252
253// Allocate one bar for the structs pointed to by the capability structures.
254const COMMON_CONFIG_BAR_OFFSET: u64 = 0x0000;
255const COMMON_CONFIG_SIZE: u64 = 56;
256const COMMON_CONFIG_LAST: u64 = COMMON_CONFIG_BAR_OFFSET + COMMON_CONFIG_SIZE - 1;
257const ISR_CONFIG_BAR_OFFSET: u64 = 0x1000;
258const ISR_CONFIG_SIZE: u64 = 1;
259const ISR_CONFIG_LAST: u64 = ISR_CONFIG_BAR_OFFSET + ISR_CONFIG_SIZE - 1;
260const DEVICE_CONFIG_BAR_OFFSET: u64 = 0x2000;
261const DEVICE_CONFIG_SIZE: u64 = 0x1000;
262const DEVICE_CONFIG_LAST: u64 = DEVICE_CONFIG_BAR_OFFSET + DEVICE_CONFIG_SIZE - 1;
263const NOTIFICATION_BAR_OFFSET: u64 = 0x3000;
264const NOTIFICATION_SIZE: u64 = 0x1000;
265const NOTIFICATION_LAST: u64 = NOTIFICATION_BAR_OFFSET + NOTIFICATION_SIZE - 1;
266const MSIX_TABLE_BAR_OFFSET: u64 = 0x6000;
267const MSIX_TABLE_SIZE: u64 = 0x1000;
268const MSIX_TABLE_LAST: u64 = MSIX_TABLE_BAR_OFFSET + MSIX_TABLE_SIZE - 1;
269const MSIX_PBA_BAR_OFFSET: u64 = 0x7000;
270const MSIX_PBA_SIZE: u64 = 0x1000;
271const MSIX_PBA_LAST: u64 = MSIX_PBA_BAR_OFFSET + MSIX_PBA_SIZE - 1;
272const CAPABILITY_BAR_SIZE: u64 = 0x8000;
273
274const NOTIFY_OFF_MULTIPLIER: u32 = 4; // A dword per notification address.
275
276const VIRTIO_PCI_VENDOR_ID: u16 = 0x1af4;
277const VIRTIO_PCI_DEVICE_ID_BASE: u16 = 0x1040; // Add to device type to get device ID.
278const VIRTIO_PCI_REVISION_ID: u8 = 1;
279
280const CAPABILITIES_BAR_NUM: usize = 0;
281const SHMEM_BAR_NUM: usize = 2;
282
283struct QueueEvent {
284    event: Event,
285    ioevent_registered: bool,
286}
287
288/// Implements the
289/// [PCI](http://docs.oasis-open.org/virtio/virtio/v1.0/cs04/virtio-v1.0-cs04.html#x1-650001)
290/// transport for virtio devices.
291pub struct VirtioPciDevice {
292    config_regs: PciConfiguration,
293    preferred_address: Option<PciAddress>,
294    pci_address: Option<PciAddress>,
295
296    device: Box<dyn VirtioDevice>,
297    device_activated: bool,
298    disable_intx: bool,
299
300    interrupt: Option<Interrupt>,
301    interrupt_evt: Option<IrqLevelEvent>,
302    interrupt_resample_worker: Option<WorkerThread<()>>,
303
304    queues: Vec<QueueConfig>,
305    queue_evts: Vec<QueueEvent>,
306    mem: GuestMemory,
307    settings_bar: PciBarIndex,
308    msix_config: Arc<Mutex<MsixConfig>>,
309    pm_config: Arc<Mutex<PmConfig>>,
310    common_config: VirtioPciCommonConfig,
311
312    iommu: Option<Arc<Mutex<IpcMemoryMapper>>>,
313
314    // API client that is present if the device has shared memory regions, and
315    // is used to map/unmap files into the shared memory region.
316    shared_memory_vm_memory_client: Option<VmMemoryClient>,
317
318    // API client for registration of ioevents when PCI BAR reprogramming is detected.
319    ioevent_vm_memory_client: VmMemoryClient,
320
321    // State only present while asleep.
322    sleep_state: Option<SleepState>,
323
324    vm_control_tube: Arc<Mutex<Tube>>,
325}
326
327enum SleepState {
328    // Asleep and device hasn't been activated yet by the guest.
329    Inactive,
330    // Asleep and device has been activated by the guest.
331    Active {
332        /// The queues returned from `VirtioDevice::virtio_sleep`.
333        /// Map is from queue index -> Queue.
334        activated_queues: BTreeMap<usize, Queue>,
335    },
336}
337
338#[derive(Serialize, Deserialize)]
339struct VirtioPciDeviceSnapshot {
340    config_regs: AnySnapshot,
341
342    inner_device: AnySnapshot,
343    device_activated: bool,
344
345    interrupt: Option<InterruptSnapshot>,
346    msix_config: AnySnapshot,
347    common_config: VirtioPciCommonConfig,
348
349    queues: Vec<AnySnapshot>,
350    activated_queues: Option<Vec<(usize, AnySnapshot)>>,
351}
352
353impl VirtioPciDevice {
354    /// Constructs a new PCI transport for the given virtio device.
355    pub fn new(
356        mem: GuestMemory,
357        device: Box<dyn VirtioDevice>,
358        msi_device_tube: Tube,
359        disable_intx: bool,
360        shared_memory_vm_memory_client: Option<VmMemoryClient>,
361        ioevent_vm_memory_client: VmMemoryClient,
362        vm_control_tube: Tube,
363    ) -> Result<Self> {
364        // shared_memory_vm_memory_client is required if there are shared memory regions.
365        assert_eq!(
366            device.get_shared_memory_region().is_none(),
367            shared_memory_vm_memory_client.is_none()
368        );
369
370        let mut queue_evts = Vec::new();
371        for _ in device.queue_max_sizes() {
372            queue_evts.push(QueueEvent {
373                event: Event::new()?,
374                ioevent_registered: false,
375            });
376        }
377        let queues = device
378            .queue_max_sizes()
379            .iter()
380            .map(|&s| QueueConfig::new(s, device.features()))
381            .collect();
382
383        let pci_device_id = VIRTIO_PCI_DEVICE_ID_BASE + u32::from(device.device_type()) as u16;
384
385        let (pci_device_class, pci_device_subclass) = match device.device_type() {
386            DeviceType::Net => (
387                PciClassCode::NetworkController,
388                &PciNetworkControllerSubclass::Other as &dyn PciSubclass,
389            ),
390            DeviceType::Block => (
391                PciClassCode::MassStorage,
392                &PciMassStorageSubclass::Other as &dyn PciSubclass,
393            ),
394            DeviceType::Console => (
395                PciClassCode::SimpleCommunicationController,
396                &PciSimpleCommunicationControllerSubclass::Other as &dyn PciSubclass,
397            ),
398            DeviceType::Rng => (
399                PciClassCode::BaseSystemPeripheral,
400                &PciBaseSystemPeripheralSubclass::Other as &dyn PciSubclass,
401            ),
402            DeviceType::Balloon => (
403                PciClassCode::BaseSystemPeripheral,
404                &PciBaseSystemPeripheralSubclass::Other as &dyn PciSubclass,
405            ),
406            DeviceType::Scsi => (
407                PciClassCode::MassStorage,
408                &PciMassStorageSubclass::Scsi as &dyn PciSubclass,
409            ),
410            DeviceType::P9 => (
411                PciClassCode::NetworkController,
412                &PciNetworkControllerSubclass::Other as &dyn PciSubclass,
413            ),
414            DeviceType::Gpu => (
415                PciClassCode::DisplayController,
416                &PciDisplaySubclass::Other as &dyn PciSubclass,
417            ),
418            DeviceType::Input => (
419                PciClassCode::InputDevice,
420                &PciInputDeviceSubclass::Other as &dyn PciSubclass,
421            ),
422            DeviceType::Vsock => (
423                PciClassCode::NetworkController,
424                &PciNetworkControllerSubclass::Other as &dyn PciSubclass,
425            ),
426            DeviceType::Iommu => (
427                PciClassCode::BaseSystemPeripheral,
428                &PciBaseSystemPeripheralSubclass::Iommu as &dyn PciSubclass,
429            ),
430            DeviceType::Sound => (
431                PciClassCode::MultimediaController,
432                &PciMultimediaSubclass::AudioController as &dyn PciSubclass,
433            ),
434            DeviceType::Fs => (
435                PciClassCode::MassStorage,
436                &PciMassStorageSubclass::Other as &dyn PciSubclass,
437            ),
438            DeviceType::Pmem => (
439                PciClassCode::MassStorage,
440                &PciMassStorageSubclass::NonVolatileMemory as &dyn PciSubclass,
441            ),
442            DeviceType::Mac80211HwSim => (
443                PciClassCode::WirelessController,
444                &PciWirelessControllerSubclass::Other as &dyn PciSubclass,
445            ),
446            DeviceType::VideoEncoder => (
447                PciClassCode::MultimediaController,
448                &PciMultimediaSubclass::VideoController as &dyn PciSubclass,
449            ),
450            DeviceType::VideoDecoder => (
451                PciClassCode::MultimediaController,
452                &PciMultimediaSubclass::VideoController as &dyn PciSubclass,
453            ),
454            DeviceType::Media => (
455                PciClassCode::MultimediaController,
456                &PciMultimediaSubclass::VideoController as &dyn PciSubclass,
457            ),
458            DeviceType::Scmi => (
459                PciClassCode::BaseSystemPeripheral,
460                &PciBaseSystemPeripheralSubclass::Other as &dyn PciSubclass,
461            ),
462            DeviceType::Wl => (
463                PciClassCode::DisplayController,
464                &PciDisplaySubclass::Other as &dyn PciSubclass,
465            ),
466            DeviceType::Tpm => (
467                PciClassCode::BaseSystemPeripheral,
468                &PciBaseSystemPeripheralSubclass::Other as &dyn PciSubclass,
469            ),
470            DeviceType::Pvclock => (
471                PciClassCode::BaseSystemPeripheral,
472                &PciBaseSystemPeripheralSubclass::Other as &dyn PciSubclass,
473            ),
474            DeviceType::VendorDevice(_) => (
475                PciClassCode::BaseSystemPeripheral,
476                &PciBaseSystemPeripheralSubclass::Other as &dyn PciSubclass,
477            ),
478        };
479
480        let num_interrupts = device.num_interrupts();
481
482        // One MSI-X vector per queue plus one for configuration changes.
483        let msix_num = u16::try_from(num_interrupts + 1).map_err(|_| base::Error::new(ERANGE))?;
484        let msix_config = Arc::new(Mutex::new(MsixConfig::new(
485            msix_num,
486            msi_device_tube,
487            PciId::new(VIRTIO_PCI_VENDOR_ID, pci_device_id).into(),
488            device.debug_label(),
489        )));
490
491        let config_regs = PciConfiguration::new(
492            VIRTIO_PCI_VENDOR_ID,
493            pci_device_id,
494            pci_device_class,
495            pci_device_subclass,
496            None,
497            PciHeaderType::Device,
498            VIRTIO_PCI_VENDOR_ID,
499            pci_device_id,
500            VIRTIO_PCI_REVISION_ID,
501        );
502
503        Ok(VirtioPciDevice {
504            config_regs,
505            preferred_address: device.pci_address(),
506            pci_address: None,
507            device,
508            device_activated: false,
509            disable_intx,
510            interrupt: None,
511            interrupt_evt: None,
512            interrupt_resample_worker: None,
513            queues,
514            queue_evts,
515            mem,
516            settings_bar: 0,
517            msix_config,
518            pm_config: Arc::new(Mutex::new(PmConfig::new(true))),
519            common_config: VirtioPciCommonConfig {
520                driver_status: 0,
521                config_generation: 0,
522                device_feature_select: 0,
523                driver_feature_select: 0,
524                queue_select: 0,
525                msix_config: VIRTIO_MSI_NO_VECTOR,
526            },
527            iommu: None,
528            shared_memory_vm_memory_client,
529            ioevent_vm_memory_client,
530            sleep_state: None,
531            vm_control_tube: Arc::new(Mutex::new(vm_control_tube)),
532        })
533    }
534
535    fn is_driver_ready(&self) -> bool {
536        let ready_bits = (VIRTIO_CONFIG_S_ACKNOWLEDGE
537            | VIRTIO_CONFIG_S_DRIVER
538            | VIRTIO_CONFIG_S_DRIVER_OK
539            | VIRTIO_CONFIG_S_FEATURES_OK) as u8;
540        (self.common_config.driver_status & ready_bits) == ready_bits
541            && self.common_config.driver_status & VIRTIO_CONFIG_S_FAILED as u8 == 0
542    }
543
544    fn is_device_suspended(&self) -> bool {
545        (self.common_config.driver_status & VIRTIO_CONFIG_S_SUSPEND as u8) != 0
546    }
547
548    /// Determines if the driver has requested the device reset itself
549    fn is_reset_requested(&self) -> bool {
550        self.common_config.driver_status == DEVICE_RESET as u8
551    }
552
553    fn add_settings_pci_capabilities(
554        &mut self,
555        settings_bar: u8,
556    ) -> std::result::Result<(), PciDeviceError> {
557        // Add pointers to the different configuration structures from the PCI capabilities.
558        let common_cap = VirtioPciCap::new(
559            PciCapabilityType::CommonConfig,
560            settings_bar,
561            COMMON_CONFIG_BAR_OFFSET as u32,
562            COMMON_CONFIG_SIZE as u32,
563        );
564        self.config_regs
565            .add_capability(&common_cap, None)
566            .map_err(PciDeviceError::CapabilitiesSetup)?;
567
568        let isr_cap = VirtioPciCap::new(
569            PciCapabilityType::IsrConfig,
570            settings_bar,
571            ISR_CONFIG_BAR_OFFSET as u32,
572            ISR_CONFIG_SIZE as u32,
573        );
574        self.config_regs
575            .add_capability(&isr_cap, None)
576            .map_err(PciDeviceError::CapabilitiesSetup)?;
577
578        // TODO(dgreid) - set based on device's configuration size?
579        let device_cap = VirtioPciCap::new(
580            PciCapabilityType::DeviceConfig,
581            settings_bar,
582            DEVICE_CONFIG_BAR_OFFSET as u32,
583            DEVICE_CONFIG_SIZE as u32,
584        );
585        self.config_regs
586            .add_capability(&device_cap, None)
587            .map_err(PciDeviceError::CapabilitiesSetup)?;
588
589        let notify_cap = VirtioPciNotifyCap::new(
590            PciCapabilityType::NotifyConfig,
591            settings_bar,
592            NOTIFICATION_BAR_OFFSET as u32,
593            NOTIFICATION_SIZE as u32,
594            Le32::from(NOTIFY_OFF_MULTIPLIER),
595        );
596        self.config_regs
597            .add_capability(&notify_cap, None)
598            .map_err(PciDeviceError::CapabilitiesSetup)?;
599
600        //TODO(dgreid) - How will the configuration_cap work?
601        let configuration_cap = VirtioPciCap::new(PciCapabilityType::PciConfig, 0, 0, 0);
602        self.config_regs
603            .add_capability(&configuration_cap, None)
604            .map_err(PciDeviceError::CapabilitiesSetup)?;
605
606        let msix_cap = MsixCap::new(
607            settings_bar,
608            self.msix_config.lock().num_vectors(),
609            MSIX_TABLE_BAR_OFFSET as u32,
610            settings_bar,
611            MSIX_PBA_BAR_OFFSET as u32,
612        );
613        self.config_regs
614            .add_capability(&msix_cap, Some(Box::new(self.msix_config.clone())))
615            .map_err(PciDeviceError::CapabilitiesSetup)?;
616
617        self.config_regs
618            .add_capability(&PciPmCap::new(), Some(Box::new(self.pm_config.clone())))
619            .map_err(PciDeviceError::CapabilitiesSetup)?;
620
621        self.settings_bar = settings_bar as PciBarIndex;
622        Ok(())
623    }
624
625    /// Activates the underlying `VirtioDevice`. `assign_irq` has to be called first.
626    fn activate(&mut self) -> anyhow::Result<()> {
627        let interrupt = Interrupt::new(
628            self.interrupt_evt
629                .as_ref()
630                .ok_or_else(|| anyhow!("{} interrupt_evt is none", self.debug_label()))?
631                .try_clone()
632                .with_context(|| format!("{} failed to clone interrupt_evt", self.debug_label()))?,
633            Some(self.msix_config.clone()),
634            self.common_config.msix_config,
635            #[cfg(target_arch = "x86_64")]
636            Some((
637                PmWakeupEvent::new(self.vm_control_tube.clone(), self.pm_config.clone()),
638                MetricEventType::VirtioWakeup {
639                    virtio_id: self.device.device_type().into(),
640                },
641            )),
642        );
643        self.interrupt = Some(interrupt.clone());
644        self.interrupt_resample_worker = interrupt.spawn_resample_thread();
645
646        let bar0 = self.config_regs.get_bar_addr(self.settings_bar);
647        let notify_base = bar0 + NOTIFICATION_BAR_OFFSET;
648
649        // Use ready queues and their events.
650        let queues = self
651            .queues
652            .iter_mut()
653            .enumerate()
654            .zip(self.queue_evts.iter_mut())
655            .filter(|((_, q), _)| q.ready())
656            .map(|((queue_index, queue), evt)| {
657                if !evt.ioevent_registered {
658                    self.ioevent_vm_memory_client
659                        .register_io_event(
660                            evt.event.try_clone().context("failed to clone Event")?,
661                            notify_base + queue_index as u64 * u64::from(NOTIFY_OFF_MULTIPLIER),
662                            Datamatch::AnyLength,
663                        )
664                        .context("failed to register ioevent")?;
665                    evt.ioevent_registered = true;
666                }
667                let queue_evt = evt.event.try_clone().context("failed to clone queue_evt")?;
668                Ok((
669                    queue_index,
670                    queue
671                        .activate(&self.mem, queue_evt, interrupt.clone())
672                        .context("failed to activate queue")?,
673                ))
674            })
675            .collect::<anyhow::Result<BTreeMap<usize, Queue>>>()?;
676
677        if let Err(e) = self.device.activate(self.mem.clone(), interrupt, queues) {
678            error!("{} activate failed: {:#}", self.debug_label(), e);
679            self.common_config.driver_status |= VIRTIO_CONFIG_S_NEEDS_RESET as u8;
680        } else {
681            self.device_activated = true;
682        }
683
684        Ok(())
685    }
686
687    fn unregister_ioevents(&mut self) -> anyhow::Result<()> {
688        let bar0 = self.config_regs.get_bar_addr(self.settings_bar);
689        let notify_base = bar0 + NOTIFICATION_BAR_OFFSET;
690
691        for (queue_index, evt) in self.queue_evts.iter_mut().enumerate() {
692            if evt.ioevent_registered {
693                self.ioevent_vm_memory_client
694                    .unregister_io_event(
695                        evt.event.try_clone().context("failed to clone Event")?,
696                        notify_base + queue_index as u64 * u64::from(NOTIFY_OFF_MULTIPLIER),
697                        Datamatch::AnyLength,
698                    )
699                    .context("failed to unregister ioevent")?;
700                evt.ioevent_registered = false;
701            }
702        }
703        Ok(())
704    }
705
706    pub fn virtio_device(&self) -> &dyn VirtioDevice {
707        self.device.as_ref()
708    }
709
710    pub fn pci_address(&self) -> Option<PciAddress> {
711        self.pci_address
712    }
713
714    #[cfg(target_arch = "x86_64")]
715    fn handle_pm_status_change(&mut self, status: &PmStatusChange) {
716        if let Some(interrupt) = self.interrupt.as_mut() {
717            interrupt.set_wakeup_event_active(status.to == PciDevicePower::D3)
718        }
719    }
720
721    #[cfg(not(target_arch = "x86_64"))]
722    fn handle_pm_status_change(&mut self, _status: &PmStatusChange) {}
723}
724
725impl PciDevice for VirtioPciDevice {
726    fn debug_label(&self) -> String {
727        format!("pci{}", self.device.debug_label())
728    }
729
730    fn preferred_address(&self) -> Option<PciAddress> {
731        self.preferred_address
732    }
733
734    fn allocate_address(
735        &mut self,
736        resources: &mut SystemAllocator,
737    ) -> std::result::Result<PciAddress, PciDeviceError> {
738        if self.pci_address.is_none() {
739            if let Some(address) = self.preferred_address {
740                if !resources.reserve_pci(address, self.debug_label()) {
741                    return Err(PciDeviceError::PciAllocationFailed);
742                }
743                self.pci_address = Some(address);
744            } else {
745                self.pci_address = resources.allocate_pci(0, self.debug_label());
746            }
747            self.msix_config
748                .lock()
749                .set_pci_address(self.pci_address.unwrap());
750        }
751        self.pci_address.ok_or(PciDeviceError::PciAllocationFailed)
752    }
753
754    fn keep_rds(&self) -> Vec<RawDescriptor> {
755        let mut rds = self.device.keep_rds();
756        rds.extend(
757            self.queue_evts
758                .iter()
759                .map(|qe| qe.event.as_raw_descriptor()),
760        );
761        if let Some(interrupt_evt) = &self.interrupt_evt {
762            rds.extend(interrupt_evt.as_raw_descriptors());
763        }
764        let descriptor = self.msix_config.lock().get_msi_socket();
765        rds.push(descriptor);
766        if let Some(iommu) = &self.iommu {
767            rds.append(&mut iommu.lock().as_raw_descriptors());
768        }
769        rds.push(self.ioevent_vm_memory_client.as_raw_descriptor());
770        rds.push(self.vm_control_tube.lock().as_raw_descriptor());
771        rds
772    }
773
774    fn assign_irq(&mut self, irq_evt: IrqLevelEvent, pin: PciInterruptPin, irq_num: u32) {
775        self.interrupt_evt = Some(irq_evt);
776        if !self.disable_intx {
777            self.config_regs.set_irq(irq_num as u8, pin);
778        }
779    }
780
781    fn allocate_io_bars(
782        &mut self,
783        resources: &mut SystemAllocator,
784    ) -> std::result::Result<Vec<BarRange>, PciDeviceError> {
785        let device_type = self.device.device_type();
786        allocate_io_bars(
787            self,
788            |size: u64, alloc: Alloc, alloc_option: &AllocOptions| {
789                resources
790                    .allocate_mmio(
791                        size,
792                        alloc,
793                        format!("virtio-{device_type}-cap_bar"),
794                        alloc_option,
795                    )
796                    .map_err(|e| PciDeviceError::IoAllocationFailed(size, e))
797            },
798        )
799    }
800
801    fn allocate_device_bars(
802        &mut self,
803        resources: &mut SystemAllocator,
804    ) -> std::result::Result<Vec<BarRange>, PciDeviceError> {
805        let device_type = self.device.device_type();
806        allocate_device_bars(
807            self,
808            |size: u64, alloc: Alloc, alloc_option: &AllocOptions| {
809                resources
810                    .allocate_mmio(
811                        size,
812                        alloc,
813                        format!("virtio-{device_type}-custom_bar"),
814                        alloc_option,
815                    )
816                    .map_err(|e| PciDeviceError::IoAllocationFailed(size, e))
817            },
818        )
819    }
820
821    fn destroy_device(&mut self) {
822        if let Err(e) = self.unregister_ioevents() {
823            error!("error destroying {}: {:?}", &self.debug_label(), &e);
824        }
825    }
826
827    fn get_bar_configuration(&self, bar_num: usize) -> Option<PciBarConfiguration> {
828        self.config_regs.get_bar_configuration(bar_num)
829    }
830
831    fn register_device_capabilities(&mut self) -> std::result::Result<(), PciDeviceError> {
832        let mut caps = self.device.get_device_caps();
833        if let Some(region) = self.device.get_shared_memory_region() {
834            caps.push(Box::new(VirtioPciShmCap::new(
835                PciCapabilityType::SharedMemoryConfig,
836                SHMEM_BAR_NUM as u8,
837                0,
838                region.length,
839                region.id,
840            )));
841        }
842
843        for cap in caps {
844            self.config_regs
845                .add_capability(&*cap, None)
846                .map_err(PciDeviceError::CapabilitiesSetup)?;
847        }
848
849        Ok(())
850    }
851
852    fn read_config_register(&self, reg_idx: usize) -> u32 {
853        self.config_regs.read_reg(reg_idx)
854    }
855
856    fn write_config_register(&mut self, reg_idx: usize, offset: u64, data: &[u8]) {
857        if let Some(res) = self.config_regs.write_reg(reg_idx, offset, data) {
858            if let Some(msix_behavior) = <dyn Any>::downcast_ref::<MsixStatus>(&*res) {
859                self.device.control_notify(*msix_behavior);
860            } else if let Some(status) = <dyn Any>::downcast_ref::<PmStatusChange>(&*res) {
861                self.handle_pm_status_change(status);
862            }
863        }
864    }
865
866    fn setup_pci_config_mapping(
867        &mut self,
868        shmem: &SharedMemory,
869        base: usize,
870        len: usize,
871    ) -> std::result::Result<bool, PciDeviceError> {
872        self.config_regs
873            .setup_mapping(shmem, base, len)
874            .map(|_| true)
875            .map_err(PciDeviceError::MmioSetup)
876    }
877
878    fn read_bar(&mut self, bar_index: usize, offset: u64, data: &mut [u8]) {
879        if bar_index == self.settings_bar {
880            match offset {
881                COMMON_CONFIG_BAR_OFFSET..=COMMON_CONFIG_LAST => self.common_config.read(
882                    offset - COMMON_CONFIG_BAR_OFFSET,
883                    data,
884                    &mut self.queues,
885                    self.device.as_mut(),
886                ),
887                ISR_CONFIG_BAR_OFFSET..=ISR_CONFIG_LAST => {
888                    if let Some(v) = data.get_mut(0) {
889                        // Reading this register resets it to 0.
890                        *v = if let Some(interrupt) = &self.interrupt {
891                            interrupt.read_and_reset_interrupt_status()
892                        } else {
893                            0
894                        };
895                    }
896                }
897                DEVICE_CONFIG_BAR_OFFSET..=DEVICE_CONFIG_LAST => {
898                    self.device
899                        .read_config(offset - DEVICE_CONFIG_BAR_OFFSET, data);
900                }
901                NOTIFICATION_BAR_OFFSET..=NOTIFICATION_LAST => {
902                    // Handled with ioevents.
903                }
904                MSIX_TABLE_BAR_OFFSET..=MSIX_TABLE_LAST => {
905                    self.msix_config
906                        .lock()
907                        .read_msix_table(offset - MSIX_TABLE_BAR_OFFSET, data);
908                }
909                MSIX_PBA_BAR_OFFSET..=MSIX_PBA_LAST => {
910                    self.msix_config
911                        .lock()
912                        .read_pba_entries(offset - MSIX_PBA_BAR_OFFSET, data);
913                }
914                _ => (),
915            }
916        }
917    }
918
919    fn write_bar(&mut self, bar_index: usize, offset: u64, data: &[u8]) {
920        let was_suspended = self.is_device_suspended();
921
922        if bar_index == self.settings_bar {
923            match offset {
924                COMMON_CONFIG_BAR_OFFSET..=COMMON_CONFIG_LAST => self.common_config.write(
925                    offset - COMMON_CONFIG_BAR_OFFSET,
926                    data,
927                    &mut self.queues,
928                    self.device.as_mut(),
929                ),
930                ISR_CONFIG_BAR_OFFSET..=ISR_CONFIG_LAST => {
931                    if let Some(v) = data.first() {
932                        if let Some(interrupt) = &self.interrupt {
933                            interrupt.clear_interrupt_status_bits(*v);
934                        }
935                    }
936                }
937                DEVICE_CONFIG_BAR_OFFSET..=DEVICE_CONFIG_LAST => {
938                    self.device
939                        .write_config(offset - DEVICE_CONFIG_BAR_OFFSET, data);
940                }
941                NOTIFICATION_BAR_OFFSET..=NOTIFICATION_LAST => {
942                    // Notifications are normally handled with ioevents inside the hypervisor and
943                    // do not reach write_bar(). However, if the ioevent registration hasn't
944                    // finished yet, it is possible for a write to the notification region to make
945                    // it through as a normal MMIO exit and end up here. To handle that case,
946                    // provide a fallback that looks up the corresponding queue for the offset and
947                    // triggers its event, which is equivalent to what the ioevent would do.
948                    let queue_index = (offset - NOTIFICATION_BAR_OFFSET) as usize
949                        / NOTIFY_OFF_MULTIPLIER as usize;
950                    trace!("write_bar notification fallback for queue {}", queue_index);
951                    if let Some(evt) = self.queue_evts.get(queue_index) {
952                        let _ = evt.event.signal();
953                    }
954                }
955                MSIX_TABLE_BAR_OFFSET..=MSIX_TABLE_LAST => {
956                    let behavior = self
957                        .msix_config
958                        .lock()
959                        .write_msix_table(offset - MSIX_TABLE_BAR_OFFSET, data);
960                    self.device.control_notify(behavior);
961                }
962                MSIX_PBA_BAR_OFFSET..=MSIX_PBA_LAST => {
963                    self.msix_config
964                        .lock()
965                        .write_pba_entries(offset - MSIX_PBA_BAR_OFFSET, data);
966                }
967                _ => (),
968            }
969        }
970
971        if !self.device_activated && self.is_driver_ready() {
972            if let Err(e) = self.activate() {
973                error!("failed to activate device: {:#}", e);
974            }
975        }
976
977        let is_suspended = self.is_device_suspended();
978        if is_suspended != was_suspended {
979            if let Some(interrupt) = self.interrupt.as_mut() {
980                interrupt.set_suspended(is_suspended);
981            }
982        }
983
984        // Device has been reset by the driver
985        if self.device_activated && self.is_reset_requested() {
986            if let Err(e) = self.device.reset() {
987                error!("failed to reset {} device: {:#}", self.debug_label(), e);
988            } else {
989                self.device_activated = false;
990                // reset queues
991                self.queues.iter_mut().for_each(QueueConfig::reset);
992                // select queue 0 by default
993                self.common_config.queue_select = 0;
994                if let Err(e) = self.unregister_ioevents() {
995                    error!("failed to unregister ioevents: {:#}", e);
996                }
997                if let Some(interrupt_resample_worker) = self.interrupt_resample_worker.take() {
998                    interrupt_resample_worker.stop();
999                }
1000            }
1001        }
1002    }
1003
1004    fn on_device_sandboxed(&mut self) {
1005        self.device.on_device_sandboxed();
1006    }
1007
1008    #[cfg(target_arch = "x86_64")]
1009    fn generate_acpi(&mut self, sdts: &mut Vec<SDT>) -> anyhow::Result<()> {
1010        self.device.generate_acpi(
1011            self.pci_address.expect("pci_address must be assigned"),
1012            sdts,
1013        )
1014    }
1015
1016    fn as_virtio_pci_device(&self) -> Option<&VirtioPciDevice> {
1017        Some(self)
1018    }
1019}
1020
1021fn allocate_io_bars<F>(
1022    virtio_pci_device: &mut VirtioPciDevice,
1023    mut alloc_fn: F,
1024) -> std::result::Result<Vec<BarRange>, PciDeviceError>
1025where
1026    F: FnMut(u64, Alloc, &AllocOptions) -> std::result::Result<u64, PciDeviceError>,
1027{
1028    let address = virtio_pci_device
1029        .pci_address
1030        .expect("allocate_address must be called prior to allocate_io_bars");
1031    // Allocate one bar for the structures pointed to by the capability structures.
1032    let settings_config_addr = alloc_fn(
1033        CAPABILITY_BAR_SIZE,
1034        Alloc::PciBar {
1035            bus: address.bus,
1036            dev: address.dev,
1037            func: address.func,
1038            bar: 0,
1039        },
1040        AllocOptions::new()
1041            .max_address(u32::MAX.into())
1042            .align(CAPABILITY_BAR_SIZE),
1043    )?;
1044    let config = PciBarConfiguration::new(
1045        CAPABILITIES_BAR_NUM,
1046        CAPABILITY_BAR_SIZE,
1047        PciBarRegionType::Memory32BitRegion,
1048        PciBarPrefetchable::NotPrefetchable,
1049    )
1050    .set_address(settings_config_addr);
1051    let settings_bar = virtio_pci_device
1052        .config_regs
1053        .add_pci_bar(config)
1054        .map_err(|e| PciDeviceError::IoRegistrationFailed(settings_config_addr, e))?
1055        as u8;
1056    // Once the BARs are allocated, the capabilities can be added to the PCI configuration.
1057    virtio_pci_device.add_settings_pci_capabilities(settings_bar)?;
1058
1059    Ok(vec![BarRange {
1060        addr: settings_config_addr,
1061        size: CAPABILITY_BAR_SIZE,
1062        prefetchable: false,
1063    }])
1064}
1065
1066fn allocate_device_bars<F>(
1067    virtio_pci_device: &mut VirtioPciDevice,
1068    mut alloc_fn: F,
1069) -> std::result::Result<Vec<BarRange>, PciDeviceError>
1070where
1071    F: FnMut(u64, Alloc, &AllocOptions) -> std::result::Result<u64, PciDeviceError>,
1072{
1073    let address = virtio_pci_device
1074        .pci_address
1075        .expect("allocate_address must be called prior to allocate_device_bars");
1076
1077    let configs = virtio_pci_device.device.get_device_bars(address);
1078    let configs = if !configs.is_empty() {
1079        configs
1080    } else {
1081        let region = match virtio_pci_device.device.get_shared_memory_region() {
1082            None => return Ok(Vec::new()),
1083            Some(r) => r,
1084        };
1085        let config = PciBarConfiguration::new(
1086            SHMEM_BAR_NUM,
1087            region
1088                .length
1089                .checked_next_power_of_two()
1090                .expect("bar too large"),
1091            PciBarRegionType::Memory64BitRegion,
1092            PciBarPrefetchable::Prefetchable,
1093        );
1094
1095        let alloc = Alloc::PciBar {
1096            bus: address.bus,
1097            dev: address.dev,
1098            func: address.func,
1099            bar: config.bar_index() as u8,
1100        };
1101
1102        let vm_memory_client = virtio_pci_device
1103            .shared_memory_vm_memory_client
1104            .take()
1105            .expect("missing shared_memory_tube");
1106
1107        // See comment VmMemoryRequest::execute
1108        let can_prepare = !virtio_pci_device
1109            .device
1110            .expose_shmem_descriptors_with_viommu();
1111        let prepare_type = if can_prepare {
1112            virtio_pci_device.device.get_shared_memory_prepare_type()
1113        } else {
1114            SharedMemoryPrepareType::DynamicPerMapping
1115        };
1116
1117        let vm_requester = Box::new(VmRequester::new(vm_memory_client, alloc, prepare_type));
1118        virtio_pci_device
1119            .device
1120            .set_shared_memory_mapper(vm_requester);
1121
1122        vec![config]
1123    };
1124    let mut ranges = vec![];
1125    for config in configs {
1126        let device_addr = alloc_fn(
1127            config.size(),
1128            Alloc::PciBar {
1129                bus: address.bus,
1130                dev: address.dev,
1131                func: address.func,
1132                bar: config.bar_index() as u8,
1133            },
1134            AllocOptions::new()
1135                .prefetchable(config.is_prefetchable())
1136                .align(config.size()),
1137        )?;
1138        let config = config.set_address(device_addr);
1139        let _device_bar = virtio_pci_device
1140            .config_regs
1141            .add_pci_bar(config)
1142            .map_err(|e| PciDeviceError::IoRegistrationFailed(device_addr, e))?;
1143        ranges.push(BarRange {
1144            addr: device_addr,
1145            size: config.size(),
1146            prefetchable: false,
1147        });
1148    }
1149
1150    if virtio_pci_device
1151        .device
1152        .get_shared_memory_region()
1153        .is_some()
1154    {
1155        let shmem_region = AddressRange::from_start_and_size(ranges[0].addr, ranges[0].size)
1156            .expect("invalid shmem region");
1157        virtio_pci_device
1158            .device
1159            .set_shared_memory_region(shmem_region);
1160    }
1161
1162    Ok(ranges)
1163}
1164
1165#[cfg(feature = "pci-hotplug")]
1166impl HotPluggable for VirtioPciDevice {
1167    /// Sets PciAddress to pci_addr
1168    fn set_pci_address(&mut self, pci_addr: PciAddress) -> std::result::Result<(), PciDeviceError> {
1169        self.pci_address = Some(pci_addr);
1170        self.msix_config
1171            .lock()
1172            .set_pci_address(self.pci_address.unwrap());
1173        Ok(())
1174    }
1175
1176    /// Configures IO BAR layout without memory alloc.
1177    fn configure_io_bars(&mut self) -> std::result::Result<(), PciDeviceError> {
1178        let mut simple_allocator = SimpleAllocator::new(0);
1179        allocate_io_bars(self, |size, _, _| simple_allocator.alloc(size, size)).map(|_| ())
1180    }
1181
1182    /// Configure device BAR layout without memory alloc.
1183    fn configure_device_bars(&mut self) -> std::result::Result<(), PciDeviceError> {
1184        // For device BAR, the space for CAPABILITY_BAR_SIZE should be skipped.
1185        let mut simple_allocator = SimpleAllocator::new(CAPABILITY_BAR_SIZE);
1186        allocate_device_bars(self, |size, _, _| simple_allocator.alloc(size, size)).map(|_| ())
1187    }
1188}
1189
1190#[cfg(feature = "pci-hotplug")]
1191/// A simple allocator that can allocate non-overlapping aligned intervals.
1192///
1193/// The addresses allocated are not exclusively reserved for the device, and cannot be used for a
1194/// static device. The allocated placeholder address describes the layout of PCI BAR for hotplugged
1195/// devices. Actual memory allocation is handled by PCI BAR reprogramming initiated by guest OS.
1196struct SimpleAllocator {
1197    current_address: u64,
1198}
1199
1200#[cfg(feature = "pci-hotplug")]
1201impl SimpleAllocator {
1202    /// Constructs SimpleAllocator. Address will start at or after base_address.
1203    fn new(base_address: u64) -> Self {
1204        Self {
1205            current_address: base_address,
1206        }
1207    }
1208
1209    /// Allocate memory with size and align. Returns the start of address.
1210    fn alloc(&mut self, size: u64, align: u64) -> std::result::Result<u64, PciDeviceError> {
1211        if align > 0 {
1212            // aligns current_address upward to align.
1213            self.current_address = self.current_address.next_multiple_of(align);
1214        }
1215        let start_address = self.current_address;
1216        self.current_address += size;
1217        Ok(start_address)
1218    }
1219}
1220
1221impl Suspendable for VirtioPciDevice {
1222    fn sleep(&mut self) -> anyhow::Result<()> {
1223        // If the device is already asleep, we should not request it to sleep again.
1224        if self.sleep_state.is_some() {
1225            return Ok(());
1226        }
1227
1228        if let Some(queues) = self.device.virtio_sleep()? {
1229            anyhow::ensure!(
1230                self.device_activated,
1231                format!(
1232                    "unactivated device {} returned queues on sleep",
1233                    self.debug_label()
1234                ),
1235            );
1236            self.sleep_state = Some(SleepState::Active {
1237                activated_queues: queues,
1238            });
1239        } else {
1240            anyhow::ensure!(
1241                !self.device_activated,
1242                format!(
1243                    "activated device {} didn't return queues on sleep",
1244                    self.debug_label()
1245                ),
1246            );
1247            self.sleep_state = Some(SleepState::Inactive);
1248        }
1249        Ok(())
1250    }
1251
1252    fn wake(&mut self) -> anyhow::Result<()> {
1253        match self.sleep_state.take() {
1254            None => {
1255                // If the device is already awake, we should not request it to wake again.
1256            }
1257            Some(SleepState::Inactive) => {
1258                self.device.virtio_wake(None).with_context(|| {
1259                    format!(
1260                        "virtio_wake failed for {}, can't recover",
1261                        self.debug_label(),
1262                    )
1263                })?;
1264            }
1265            Some(SleepState::Active { activated_queues }) => {
1266                self.device
1267                    .virtio_wake(Some((
1268                        self.mem.clone(),
1269                        self.interrupt
1270                            .clone()
1271                            .expect("interrupt missing for already active queues"),
1272                        activated_queues,
1273                    )))
1274                    .with_context(|| {
1275                        format!(
1276                            "virtio_wake failed for {}, can't recover",
1277                            self.debug_label(),
1278                        )
1279                    })?;
1280            }
1281        };
1282        Ok(())
1283    }
1284
1285    fn snapshot(&mut self) -> anyhow::Result<AnySnapshot> {
1286        if self.iommu.is_some() {
1287            return Err(anyhow!("Cannot snapshot if iommu is present."));
1288        }
1289
1290        AnySnapshot::to_any(VirtioPciDeviceSnapshot {
1291            config_regs: self.config_regs.snapshot()?,
1292            inner_device: self.device.virtio_snapshot()?,
1293            device_activated: self.device_activated,
1294            interrupt: self.interrupt.as_ref().map(|i| i.snapshot()),
1295            msix_config: self.msix_config.lock().snapshot()?,
1296            common_config: self.common_config,
1297            queues: self
1298                .queues
1299                .iter()
1300                .map(|q| q.snapshot())
1301                .collect::<anyhow::Result<Vec<_>>>()?,
1302            activated_queues: match &self.sleep_state {
1303                None => {
1304                    anyhow::bail!("tried snapshotting while awake")
1305                }
1306                Some(SleepState::Inactive) => None,
1307                Some(SleepState::Active { activated_queues }) => {
1308                    let mut serialized_queues = Vec::new();
1309                    for (index, queue) in activated_queues.iter() {
1310                        serialized_queues.push((*index, queue.snapshot()?));
1311                    }
1312                    Some(serialized_queues)
1313                }
1314            },
1315        })
1316        .context("failed to serialize VirtioPciDeviceSnapshot")
1317    }
1318
1319    fn restore(&mut self, data: AnySnapshot) -> anyhow::Result<()> {
1320        // Restoring from an activated state is more complex and low priority, so just fail for
1321        // now. We'll need to reset the device before restoring, e.g. must call
1322        // self.unregister_ioevents().
1323        anyhow::ensure!(
1324            !self.device_activated,
1325            "tried to restore after virtio device activated. not supported yet"
1326        );
1327
1328        let deser: VirtioPciDeviceSnapshot = AnySnapshot::from_any(data)?;
1329
1330        self.config_regs.restore(deser.config_regs)?;
1331        self.device_activated = deser.device_activated;
1332
1333        self.msix_config.lock().restore(deser.msix_config)?;
1334        self.common_config = deser.common_config;
1335
1336        // Restore the interrupt. This must be done after restoring the MSI-X configuration, but
1337        // before restoring the queues.
1338        if let Some(deser_interrupt) = deser.interrupt {
1339            let interrupt = Interrupt::new_from_snapshot(
1340                self.interrupt_evt
1341                    .as_ref()
1342                    .ok_or_else(|| anyhow!("{} interrupt_evt is none", self.debug_label()))?
1343                    .try_clone()
1344                    .with_context(|| {
1345                        format!("{} failed to clone interrupt_evt", self.debug_label())
1346                    })?,
1347                Some(self.msix_config.clone()),
1348                self.common_config.msix_config,
1349                deser_interrupt,
1350                #[cfg(target_arch = "x86_64")]
1351                Some((
1352                    PmWakeupEvent::new(self.vm_control_tube.clone(), self.pm_config.clone()),
1353                    MetricEventType::VirtioWakeup {
1354                        virtio_id: self.device.device_type().into(),
1355                    },
1356                )),
1357            );
1358            self.interrupt_resample_worker = interrupt.spawn_resample_thread();
1359            self.interrupt = Some(interrupt);
1360        }
1361
1362        assert_eq!(
1363            self.queues.len(),
1364            deser.queues.len(),
1365            "device must have the same number of queues"
1366        );
1367        for (q, s) in self.queues.iter_mut().zip(deser.queues.into_iter()) {
1368            q.restore(s)?;
1369        }
1370
1371        // Verify we are asleep and inactive.
1372        match &self.sleep_state {
1373            None => {
1374                anyhow::bail!("tried restoring while awake")
1375            }
1376            Some(SleepState::Inactive) => {}
1377            Some(SleepState::Active { .. }) => {
1378                anyhow::bail!("tried to restore after virtio device activated. not supported yet")
1379            }
1380        };
1381        // Restore `sleep_state`.
1382        if let Some(activated_queues_snapshot) = deser.activated_queues {
1383            let interrupt = self
1384                .interrupt
1385                .as_ref()
1386                .context("tried to restore active queues without an interrupt")?;
1387            let mut activated_queues = BTreeMap::new();
1388            for (index, queue_snapshot) in activated_queues_snapshot {
1389                let queue_config = self
1390                    .queues
1391                    .get(index)
1392                    .with_context(|| format!("missing queue config for activated queue {index}"))?;
1393                let queue_evt = self
1394                    .queue_evts
1395                    .get(index)
1396                    .with_context(|| format!("missing queue event for activated queue {index}"))?
1397                    .event
1398                    .try_clone()
1399                    .context("failed to clone queue event")?;
1400                activated_queues.insert(
1401                    index,
1402                    Queue::restore(
1403                        queue_config,
1404                        queue_snapshot,
1405                        &self.mem,
1406                        queue_evt,
1407                        interrupt.clone(),
1408                    )?,
1409                );
1410            }
1411
1412            // Restore the activated queues.
1413            self.sleep_state = Some(SleepState::Active { activated_queues });
1414        } else {
1415            self.sleep_state = Some(SleepState::Inactive);
1416        }
1417
1418        // Call register_io_events for the activated queue events.
1419        let bar0 = self.config_regs.get_bar_addr(self.settings_bar);
1420        let notify_base = bar0 + NOTIFICATION_BAR_OFFSET;
1421        self.queues
1422            .iter()
1423            .enumerate()
1424            .zip(self.queue_evts.iter_mut())
1425            .filter(|((_, q), _)| q.ready())
1426            .try_for_each(|((queue_index, _queue), evt)| {
1427                if !evt.ioevent_registered {
1428                    self.ioevent_vm_memory_client
1429                        .register_io_event(
1430                            evt.event.try_clone().context("failed to clone Event")?,
1431                            notify_base + queue_index as u64 * u64::from(NOTIFY_OFF_MULTIPLIER),
1432                            Datamatch::AnyLength,
1433                        )
1434                        .context("failed to register ioevent")?;
1435                    evt.ioevent_registered = true;
1436                }
1437                Ok::<(), anyhow::Error>(())
1438            })?;
1439
1440        // There might be data in the queue that wasn't drained by the device
1441        // at the time it was snapshotted. In this case, the doorbell should
1442        // still be signaled. If it is not, the driver may never re-trigger the
1443        // doorbell, and the device will stall. So here, we explicitly signal
1444        // every doorbell. Spurious doorbells are safe (devices will check their
1445        // queue, realize nothing is there, and go back to sleep.)
1446        self.queue_evts.iter_mut().try_for_each(|queue_event| {
1447            queue_event
1448                .event
1449                .signal()
1450                .context("failed to wake doorbell")
1451        })?;
1452
1453        self.device.virtio_restore(deser.inner_device)?;
1454
1455        Ok(())
1456    }
1457}
1458
1459struct VmRequester {
1460    vm_memory_client: VmMemoryClient,
1461    alloc: Alloc,
1462    mappings: BTreeMap<u64, VmMemoryRegionId>,
1463    prepare_type: SharedMemoryPrepareType,
1464    prepared: bool,
1465}
1466
1467impl VmRequester {
1468    fn new(
1469        vm_memory_client: VmMemoryClient,
1470        alloc: Alloc,
1471        prepare_type: SharedMemoryPrepareType,
1472    ) -> Self {
1473        Self {
1474            vm_memory_client,
1475            alloc,
1476            mappings: BTreeMap::new(),
1477            prepare_type,
1478            prepared: false,
1479        }
1480    }
1481}
1482
1483impl SharedMemoryMapper for VmRequester {
1484    fn add_mapping(
1485        &mut self,
1486        source: VmMemorySource,
1487        offset: u64,
1488        prot: Protection,
1489        cache: MemCacheType,
1490    ) -> anyhow::Result<()> {
1491        if !self.prepared {
1492            if let SharedMemoryPrepareType::SingleMappingOnFirst(prepare_cache_type) =
1493                self.prepare_type
1494            {
1495                debug!(
1496                    "lazy prepare_shared_memory_region with {:?}",
1497                    prepare_cache_type
1498                );
1499                self.vm_memory_client
1500                    .prepare_shared_memory_region(self.alloc, prepare_cache_type)
1501                    .context("lazy prepare_shared_memory_region failed")?;
1502            }
1503            self.prepared = true;
1504        }
1505
1506        // devices must implement VirtioDevice::get_shared_memory_prepare_type(), returning
1507        // SharedMemoryPrepareType::SingleMappingOnFirst(MemCacheType::CacheNonCoherent) in order to
1508        // add any mapping that requests MemCacheType::CacheNonCoherent.
1509        if cache == MemCacheType::CacheNonCoherent {
1510            if let SharedMemoryPrepareType::SingleMappingOnFirst(MemCacheType::CacheCoherent) =
1511                self.prepare_type
1512            {
1513                error!("invalid request to map with CacheNonCoherent for device with prepared CacheCoherent memory");
1514                return Err(anyhow!("invalid MemCacheType"));
1515            }
1516        }
1517
1518        let id = self
1519            .vm_memory_client
1520            .register_memory(
1521                source,
1522                VmMemoryDestination::ExistingAllocation {
1523                    allocation: self.alloc,
1524                    offset,
1525                },
1526                prot,
1527                cache,
1528            )
1529            .context("register_memory failed")?;
1530
1531        self.mappings.insert(offset, id);
1532        Ok(())
1533    }
1534
1535    fn remove_mapping(&mut self, offset: u64) -> anyhow::Result<()> {
1536        let id = self.mappings.remove(&offset).context("invalid offset")?;
1537        self.vm_memory_client
1538            .unregister_memory(id)
1539            .context("unregister_memory failed")
1540    }
1541
1542    fn as_raw_descriptor(&self) -> Option<RawDescriptor> {
1543        Some(self.vm_memory_client.as_raw_descriptor())
1544    }
1545}
1546
1547#[cfg(test)]
1548mod tests {
1549
1550    #[cfg(feature = "pci-hotplug")]
1551    #[test]
1552    fn allocate_aligned_address() {
1553        let mut simple_allocator = super::SimpleAllocator::new(0);
1554        // start at 0, aligned to 0x80. Interval end at 0x20.
1555        assert_eq!(simple_allocator.alloc(0x20, 0x80).unwrap(), 0);
1556        // 0x20 => start at 0x40. Interval end at 0x80.
1557        assert_eq!(simple_allocator.alloc(0x40, 0x40).unwrap(), 0x40);
1558        // 0x80 => start at 0x80, Interval end at 0x108.
1559        assert_eq!(simple_allocator.alloc(0x88, 0x80).unwrap(), 0x80);
1560        // 0x108 => start at 0x180. Interval end at 0x1b0.
1561        assert_eq!(simple_allocator.alloc(0x30, 0x80).unwrap(), 0x180);
1562    }
1563}