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
542                & (VIRTIO_CONFIG_S_FAILED | VIRTIO_CONFIG_S_NEEDS_RESET) as u8
543                == 0
544    }
545
546    fn is_device_suspended(&self) -> bool {
547        (self.common_config.driver_status & VIRTIO_CONFIG_S_SUSPEND as u8) != 0
548    }
549
550    /// Determines if the driver has requested the device reset itself
551    fn is_reset_requested(&self) -> bool {
552        self.common_config.driver_status == DEVICE_RESET as u8
553    }
554
555    fn add_settings_pci_capabilities(
556        &mut self,
557        settings_bar: u8,
558    ) -> std::result::Result<(), PciDeviceError> {
559        // Add pointers to the different configuration structures from the PCI capabilities.
560        let common_cap = VirtioPciCap::new(
561            PciCapabilityType::CommonConfig,
562            settings_bar,
563            COMMON_CONFIG_BAR_OFFSET as u32,
564            COMMON_CONFIG_SIZE as u32,
565        );
566        self.config_regs
567            .add_capability(&common_cap, None)
568            .map_err(PciDeviceError::CapabilitiesSetup)?;
569
570        let isr_cap = VirtioPciCap::new(
571            PciCapabilityType::IsrConfig,
572            settings_bar,
573            ISR_CONFIG_BAR_OFFSET as u32,
574            ISR_CONFIG_SIZE as u32,
575        );
576        self.config_regs
577            .add_capability(&isr_cap, None)
578            .map_err(PciDeviceError::CapabilitiesSetup)?;
579
580        // TODO(dgreid) - set based on device's configuration size?
581        let device_cap = VirtioPciCap::new(
582            PciCapabilityType::DeviceConfig,
583            settings_bar,
584            DEVICE_CONFIG_BAR_OFFSET as u32,
585            DEVICE_CONFIG_SIZE as u32,
586        );
587        self.config_regs
588            .add_capability(&device_cap, None)
589            .map_err(PciDeviceError::CapabilitiesSetup)?;
590
591        let notify_cap = VirtioPciNotifyCap::new(
592            PciCapabilityType::NotifyConfig,
593            settings_bar,
594            NOTIFICATION_BAR_OFFSET as u32,
595            NOTIFICATION_SIZE as u32,
596            Le32::from(NOTIFY_OFF_MULTIPLIER),
597        );
598        self.config_regs
599            .add_capability(&notify_cap, None)
600            .map_err(PciDeviceError::CapabilitiesSetup)?;
601
602        //TODO(dgreid) - How will the configuration_cap work?
603        let configuration_cap = VirtioPciCap::new(PciCapabilityType::PciConfig, 0, 0, 0);
604        self.config_regs
605            .add_capability(&configuration_cap, None)
606            .map_err(PciDeviceError::CapabilitiesSetup)?;
607
608        let msix_cap = MsixCap::new(
609            settings_bar,
610            self.msix_config.lock().num_vectors(),
611            MSIX_TABLE_BAR_OFFSET as u32,
612            settings_bar,
613            MSIX_PBA_BAR_OFFSET as u32,
614        );
615        self.config_regs
616            .add_capability(&msix_cap, Some(Box::new(self.msix_config.clone())))
617            .map_err(PciDeviceError::CapabilitiesSetup)?;
618
619        self.config_regs
620            .add_capability(&PciPmCap::new(), Some(Box::new(self.pm_config.clone())))
621            .map_err(PciDeviceError::CapabilitiesSetup)?;
622
623        self.settings_bar = settings_bar as PciBarIndex;
624        Ok(())
625    }
626
627    /// Activates the underlying `VirtioDevice`. `assign_irq` has to be called first.
628    fn activate(&mut self) -> anyhow::Result<()> {
629        let interrupt = Interrupt::new(
630            self.interrupt_evt
631                .as_ref()
632                .ok_or_else(|| anyhow!("{} interrupt_evt is none", self.debug_label()))?
633                .try_clone()
634                .with_context(|| format!("{} failed to clone interrupt_evt", self.debug_label()))?,
635            Some(self.msix_config.clone()),
636            self.common_config.msix_config,
637            #[cfg(target_arch = "x86_64")]
638            Some((
639                PmWakeupEvent::new(self.vm_control_tube.clone(), self.pm_config.clone()),
640                MetricEventType::VirtioWakeup {
641                    virtio_id: self.device.device_type().into(),
642                },
643            )),
644        );
645        self.interrupt = Some(interrupt.clone());
646        self.interrupt_resample_worker = interrupt.spawn_resample_thread();
647
648        let bar0 = self.config_regs.get_bar_addr(self.settings_bar);
649        let notify_base = bar0 + NOTIFICATION_BAR_OFFSET;
650
651        // Use ready queues and their events.
652        let queues = match self
653            .queues
654            .iter_mut()
655            .enumerate()
656            .zip(self.queue_evts.iter_mut())
657            .filter(|((_, q), _)| q.ready())
658            .map(|((queue_index, queue), evt)| {
659                if !evt.ioevent_registered {
660                    self.ioevent_vm_memory_client
661                        .register_io_event(
662                            evt.event.try_clone().context("failed to clone Event")?,
663                            notify_base + queue_index as u64 * u64::from(NOTIFY_OFF_MULTIPLIER),
664                            Datamatch::AnyLength,
665                        )
666                        .context("failed to register ioevent")?;
667                    evt.ioevent_registered = true;
668                }
669                let queue_evt = evt.event.try_clone().context("failed to clone queue_evt")?;
670                Ok((
671                    queue_index,
672                    queue
673                        .activate(&self.mem, queue_evt, interrupt.clone())
674                        .context("failed to activate queue")?,
675                ))
676            })
677            .collect::<anyhow::Result<BTreeMap<usize, Queue>>>()
678        {
679            Ok(queues) => queues,
680            Err(e) => {
681                error!("{} failed to activate queues: {:#}", self.debug_label(), e);
682                self.common_config.driver_status |= VIRTIO_CONFIG_S_NEEDS_RESET as u8;
683                interrupt.signal_config_changed();
684                return Ok(());
685            }
686        };
687
688        if let Err(e) = self
689            .device
690            .activate(self.mem.clone(), interrupt.clone(), queues)
691        {
692            error!("{} activate failed: {:#}", self.debug_label(), e);
693            self.common_config.driver_status |= VIRTIO_CONFIG_S_NEEDS_RESET as u8;
694            interrupt.signal_config_changed();
695        } else {
696            self.device_activated = true;
697        }
698
699        Ok(())
700    }
701
702    fn unregister_ioevents(&mut self) -> anyhow::Result<()> {
703        let bar0 = self.config_regs.get_bar_addr(self.settings_bar);
704        let notify_base = bar0 + NOTIFICATION_BAR_OFFSET;
705
706        for (queue_index, evt) in self.queue_evts.iter_mut().enumerate() {
707            if evt.ioevent_registered {
708                self.ioevent_vm_memory_client
709                    .unregister_io_event(
710                        evt.event.try_clone().context("failed to clone Event")?,
711                        notify_base + queue_index as u64 * u64::from(NOTIFY_OFF_MULTIPLIER),
712                        Datamatch::AnyLength,
713                    )
714                    .context("failed to unregister ioevent")?;
715                evt.ioevent_registered = false;
716            }
717        }
718        Ok(())
719    }
720
721    pub fn virtio_device(&self) -> &dyn VirtioDevice {
722        self.device.as_ref()
723    }
724
725    pub fn pci_address(&self) -> Option<PciAddress> {
726        self.pci_address
727    }
728
729    #[cfg(target_arch = "x86_64")]
730    fn handle_pm_status_change(&mut self, status: &PmStatusChange) {
731        if let Some(interrupt) = self.interrupt.as_mut() {
732            interrupt.set_wakeup_event_active(status.to == PciDevicePower::D3)
733        }
734    }
735
736    #[cfg(not(target_arch = "x86_64"))]
737    fn handle_pm_status_change(&mut self, _status: &PmStatusChange) {}
738}
739
740impl PciDevice for VirtioPciDevice {
741    fn debug_label(&self) -> String {
742        format!("pci{}", self.device.debug_label())
743    }
744
745    fn preferred_address(&self) -> Option<PciAddress> {
746        self.preferred_address
747    }
748
749    fn allocate_address(
750        &mut self,
751        resources: &mut SystemAllocator,
752    ) -> std::result::Result<PciAddress, PciDeviceError> {
753        if self.pci_address.is_none() {
754            if let Some(address) = self.preferred_address {
755                if !resources.reserve_pci(address, self.debug_label()) {
756                    return Err(PciDeviceError::PciAllocationFailed);
757                }
758                self.pci_address = Some(address);
759            } else {
760                self.pci_address = resources.allocate_pci(0, self.debug_label());
761            }
762            self.msix_config
763                .lock()
764                .set_pci_address(self.pci_address.unwrap());
765        }
766        self.pci_address.ok_or(PciDeviceError::PciAllocationFailed)
767    }
768
769    fn keep_rds(&self) -> Vec<RawDescriptor> {
770        let mut rds = self.device.keep_rds();
771        rds.extend(
772            self.queue_evts
773                .iter()
774                .map(|qe| qe.event.as_raw_descriptor()),
775        );
776        if let Some(interrupt_evt) = &self.interrupt_evt {
777            rds.extend(interrupt_evt.as_raw_descriptors());
778        }
779        let descriptor = self.msix_config.lock().get_msi_socket();
780        rds.push(descriptor);
781        if let Some(iommu) = &self.iommu {
782            rds.append(&mut iommu.lock().as_raw_descriptors());
783        }
784        rds.push(self.ioevent_vm_memory_client.as_raw_descriptor());
785        rds.push(self.vm_control_tube.lock().as_raw_descriptor());
786        rds
787    }
788
789    fn assign_irq(&mut self, irq_evt: IrqLevelEvent, pin: PciInterruptPin, irq_num: u32) {
790        self.interrupt_evt = Some(irq_evt);
791        if !self.disable_intx {
792            self.config_regs.set_irq(irq_num as u8, pin);
793        }
794    }
795
796    fn allocate_io_bars(
797        &mut self,
798        resources: &mut SystemAllocator,
799    ) -> std::result::Result<Vec<BarRange>, PciDeviceError> {
800        let device_type = self.device.device_type();
801        allocate_io_bars(
802            self,
803            |size: u64, alloc: Alloc, alloc_option: &AllocOptions| {
804                resources
805                    .allocate_mmio(
806                        size,
807                        alloc,
808                        format!("virtio-{device_type}-cap_bar"),
809                        alloc_option,
810                    )
811                    .map_err(|e| PciDeviceError::IoAllocationFailed(size, e))
812            },
813        )
814    }
815
816    fn allocate_device_bars(
817        &mut self,
818        resources: &mut SystemAllocator,
819    ) -> std::result::Result<Vec<BarRange>, PciDeviceError> {
820        let device_type = self.device.device_type();
821        allocate_device_bars(
822            self,
823            |size: u64, alloc: Alloc, alloc_option: &AllocOptions| {
824                resources
825                    .allocate_mmio(
826                        size,
827                        alloc,
828                        format!("virtio-{device_type}-custom_bar"),
829                        alloc_option,
830                    )
831                    .map_err(|e| PciDeviceError::IoAllocationFailed(size, e))
832            },
833        )
834    }
835
836    fn destroy_device(&mut self) {
837        if let Err(e) = self.unregister_ioevents() {
838            error!("error destroying {}: {:?}", &self.debug_label(), &e);
839        }
840    }
841
842    fn get_bar_configuration(&self, bar_num: usize) -> Option<PciBarConfiguration> {
843        self.config_regs.get_bar_configuration(bar_num)
844    }
845
846    fn register_device_capabilities(&mut self) -> std::result::Result<(), PciDeviceError> {
847        let mut caps = self.device.get_device_caps();
848        if let Some(region) = self.device.get_shared_memory_region() {
849            caps.push(Box::new(VirtioPciShmCap::new(
850                PciCapabilityType::SharedMemoryConfig,
851                SHMEM_BAR_NUM as u8,
852                0,
853                region.length,
854                region.id,
855            )));
856        }
857
858        for cap in caps {
859            self.config_regs
860                .add_capability(&*cap, None)
861                .map_err(PciDeviceError::CapabilitiesSetup)?;
862        }
863
864        Ok(())
865    }
866
867    fn read_config_register(&self, reg_idx: usize) -> u32 {
868        self.config_regs.read_reg(reg_idx)
869    }
870
871    fn write_config_register(&mut self, reg_idx: usize, offset: u64, data: &[u8]) {
872        if let Some(res) = self.config_regs.write_reg(reg_idx, offset, data) {
873            if let Some(msix_behavior) = <dyn Any>::downcast_ref::<MsixStatus>(&*res) {
874                self.device.control_notify(*msix_behavior);
875            } else if let Some(status) = <dyn Any>::downcast_ref::<PmStatusChange>(&*res) {
876                self.handle_pm_status_change(status);
877            }
878        }
879    }
880
881    fn setup_pci_config_mapping(
882        &mut self,
883        shmem: &SharedMemory,
884        base: usize,
885        len: usize,
886    ) -> std::result::Result<bool, PciDeviceError> {
887        self.config_regs
888            .setup_mapping(shmem, base, len)
889            .map(|_| true)
890            .map_err(PciDeviceError::MmioSetup)
891    }
892
893    fn read_bar(&mut self, bar_index: usize, offset: u64, data: &mut [u8]) {
894        if bar_index == self.settings_bar {
895            match offset {
896                COMMON_CONFIG_BAR_OFFSET..=COMMON_CONFIG_LAST => self.common_config.read(
897                    offset - COMMON_CONFIG_BAR_OFFSET,
898                    data,
899                    &mut self.queues,
900                    self.device.as_mut(),
901                ),
902                ISR_CONFIG_BAR_OFFSET..=ISR_CONFIG_LAST => {
903                    if let Some(v) = data.get_mut(0) {
904                        // Reading this register resets it to 0.
905                        *v = if let Some(interrupt) = &self.interrupt {
906                            interrupt.read_and_reset_interrupt_status()
907                        } else {
908                            0
909                        };
910                    }
911                }
912                DEVICE_CONFIG_BAR_OFFSET..=DEVICE_CONFIG_LAST => {
913                    self.device
914                        .read_config(offset - DEVICE_CONFIG_BAR_OFFSET, data);
915                }
916                NOTIFICATION_BAR_OFFSET..=NOTIFICATION_LAST => {
917                    // Handled with ioevents.
918                }
919                MSIX_TABLE_BAR_OFFSET..=MSIX_TABLE_LAST => {
920                    self.msix_config
921                        .lock()
922                        .read_msix_table(offset - MSIX_TABLE_BAR_OFFSET, data);
923                }
924                MSIX_PBA_BAR_OFFSET..=MSIX_PBA_LAST => {
925                    self.msix_config
926                        .lock()
927                        .read_pba_entries(offset - MSIX_PBA_BAR_OFFSET, data);
928                }
929                _ => (),
930            }
931        }
932    }
933
934    fn write_bar(&mut self, bar_index: usize, offset: u64, data: &[u8]) {
935        let was_suspended = self.is_device_suspended();
936        let was_reset_requested = self.is_reset_requested();
937
938        if bar_index == self.settings_bar {
939            match offset {
940                COMMON_CONFIG_BAR_OFFSET..=COMMON_CONFIG_LAST => {
941                    let msix_vectors = self.msix_config.lock().num_vectors();
942                    self.common_config.write(
943                        offset - COMMON_CONFIG_BAR_OFFSET,
944                        data,
945                        &mut self.queues,
946                        self.device.as_mut(),
947                        msix_vectors,
948                    )
949                }
950                ISR_CONFIG_BAR_OFFSET..=ISR_CONFIG_LAST => {
951                    if let Some(v) = data.first() {
952                        if let Some(interrupt) = &self.interrupt {
953                            interrupt.clear_interrupt_status_bits(*v);
954                        }
955                    }
956                }
957                DEVICE_CONFIG_BAR_OFFSET..=DEVICE_CONFIG_LAST => {
958                    self.device
959                        .write_config(offset - DEVICE_CONFIG_BAR_OFFSET, data);
960                }
961                NOTIFICATION_BAR_OFFSET..=NOTIFICATION_LAST => {
962                    // Notifications are normally handled with ioevents inside the hypervisor and
963                    // do not reach write_bar(). However, if the ioevent registration hasn't
964                    // finished yet, it is possible for a write to the notification region to make
965                    // it through as a normal MMIO exit and end up here. To handle that case,
966                    // provide a fallback that looks up the corresponding queue for the offset and
967                    // triggers its event, which is equivalent to what the ioevent would do.
968                    let queue_index = (offset - NOTIFICATION_BAR_OFFSET) as usize
969                        / NOTIFY_OFF_MULTIPLIER as usize;
970                    trace!("write_bar notification fallback for queue {}", queue_index);
971                    if let Some(evt) = self.queue_evts.get(queue_index) {
972                        let _ = evt.event.signal();
973                    }
974                }
975                MSIX_TABLE_BAR_OFFSET..=MSIX_TABLE_LAST => {
976                    let behavior = self
977                        .msix_config
978                        .lock()
979                        .write_msix_table(offset - MSIX_TABLE_BAR_OFFSET, data);
980                    self.device.control_notify(behavior);
981                }
982                MSIX_PBA_BAR_OFFSET..=MSIX_PBA_LAST => {
983                    self.msix_config
984                        .lock()
985                        .write_pba_entries(offset - MSIX_PBA_BAR_OFFSET, data);
986                }
987                _ => (),
988            }
989        }
990
991        if !self.device_activated && self.is_driver_ready() {
992            if let Err(e) = self.activate() {
993                error!("failed to activate device: {:#}", e);
994            }
995        }
996
997        let is_suspended = self.is_device_suspended();
998        if is_suspended != was_suspended {
999            if let Some(interrupt) = self.interrupt.as_mut() {
1000                interrupt.set_suspended(is_suspended);
1001            }
1002        }
1003
1004        // Device has been reset by the driver. Only reset on the transition to 0 or to retry a
1005        // failed device reset.
1006        if self.is_reset_requested() && (!was_reset_requested || self.device_activated) {
1007            let result = if self.device_activated {
1008                self.device.reset()
1009            } else {
1010                Ok(())
1011            };
1012            if let Err(e) = result {
1013                error!("failed to reset {} device: {:#}", self.debug_label(), e);
1014            } else {
1015                self.device_activated = false;
1016                // reset queues
1017                self.queues.iter_mut().for_each(QueueConfig::reset);
1018                // select queue 0 by default
1019                self.common_config.queue_select = 0;
1020                if let Err(e) = self.unregister_ioevents() {
1021                    error!("failed to unregister ioevents: {:#}", e);
1022                }
1023                if let Some(interrupt_resample_worker) = self.interrupt_resample_worker.take() {
1024                    interrupt_resample_worker.stop();
1025                }
1026                // reset interrupt
1027                self.interrupt = None;
1028            }
1029        }
1030    }
1031
1032    fn on_device_sandboxed(&mut self) {
1033        self.device.on_device_sandboxed();
1034    }
1035
1036    #[cfg(target_arch = "x86_64")]
1037    fn generate_acpi(&mut self, sdts: &mut Vec<SDT>) -> anyhow::Result<()> {
1038        self.device.generate_acpi(
1039            self.pci_address.expect("pci_address must be assigned"),
1040            sdts,
1041        )
1042    }
1043
1044    fn as_virtio_pci_device(&self) -> Option<&VirtioPciDevice> {
1045        Some(self)
1046    }
1047}
1048
1049fn allocate_io_bars<F>(
1050    virtio_pci_device: &mut VirtioPciDevice,
1051    mut alloc_fn: F,
1052) -> std::result::Result<Vec<BarRange>, PciDeviceError>
1053where
1054    F: FnMut(u64, Alloc, &AllocOptions) -> std::result::Result<u64, PciDeviceError>,
1055{
1056    let address = virtio_pci_device
1057        .pci_address
1058        .expect("allocate_address must be called prior to allocate_io_bars");
1059    // Allocate one bar for the structures pointed to by the capability structures.
1060    let settings_config_addr = alloc_fn(
1061        CAPABILITY_BAR_SIZE,
1062        Alloc::PciBar {
1063            bus: address.bus,
1064            dev: address.dev,
1065            func: address.func,
1066            bar: 0,
1067        },
1068        AllocOptions::new()
1069            .max_address(u32::MAX.into())
1070            .align(CAPABILITY_BAR_SIZE),
1071    )?;
1072    let config = PciBarConfiguration::new(
1073        CAPABILITIES_BAR_NUM,
1074        CAPABILITY_BAR_SIZE,
1075        PciBarRegionType::Memory32BitRegion,
1076        PciBarPrefetchable::NotPrefetchable,
1077    )
1078    .set_address(settings_config_addr);
1079    let settings_bar = virtio_pci_device
1080        .config_regs
1081        .add_pci_bar(config)
1082        .map_err(|e| PciDeviceError::IoRegistrationFailed(settings_config_addr, e))?
1083        as u8;
1084    // Once the BARs are allocated, the capabilities can be added to the PCI configuration.
1085    virtio_pci_device.add_settings_pci_capabilities(settings_bar)?;
1086
1087    Ok(vec![BarRange {
1088        addr: settings_config_addr,
1089        size: CAPABILITY_BAR_SIZE,
1090        prefetchable: false,
1091    }])
1092}
1093
1094fn allocate_device_bars<F>(
1095    virtio_pci_device: &mut VirtioPciDevice,
1096    mut alloc_fn: F,
1097) -> std::result::Result<Vec<BarRange>, PciDeviceError>
1098where
1099    F: FnMut(u64, Alloc, &AllocOptions) -> std::result::Result<u64, PciDeviceError>,
1100{
1101    let address = virtio_pci_device
1102        .pci_address
1103        .expect("allocate_address must be called prior to allocate_device_bars");
1104
1105    let configs = virtio_pci_device.device.get_device_bars(address);
1106    let configs = if !configs.is_empty() {
1107        configs
1108    } else {
1109        let region = match virtio_pci_device.device.get_shared_memory_region() {
1110            None => return Ok(Vec::new()),
1111            Some(r) => r,
1112        };
1113        let config = PciBarConfiguration::new(
1114            SHMEM_BAR_NUM,
1115            region
1116                .length
1117                .checked_next_power_of_two()
1118                .expect("bar too large"),
1119            PciBarRegionType::Memory64BitRegion,
1120            PciBarPrefetchable::Prefetchable,
1121        );
1122
1123        let alloc = Alloc::PciBar {
1124            bus: address.bus,
1125            dev: address.dev,
1126            func: address.func,
1127            bar: config.bar_index() as u8,
1128        };
1129
1130        let vm_memory_client = virtio_pci_device
1131            .shared_memory_vm_memory_client
1132            .take()
1133            .expect("missing shared_memory_tube");
1134
1135        // See comment VmMemoryRequest::execute
1136        let can_prepare = !virtio_pci_device
1137            .device
1138            .expose_shmem_descriptors_with_viommu();
1139        let prepare_type = if can_prepare {
1140            virtio_pci_device.device.get_shared_memory_prepare_type()
1141        } else {
1142            SharedMemoryPrepareType::DynamicPerMapping
1143        };
1144
1145        let vm_requester = Box::new(VmRequester::new(vm_memory_client, alloc, prepare_type));
1146        virtio_pci_device
1147            .device
1148            .set_shared_memory_mapper(vm_requester);
1149
1150        vec![config]
1151    };
1152    let mut ranges = vec![];
1153    for config in configs {
1154        let device_addr = alloc_fn(
1155            config.size(),
1156            Alloc::PciBar {
1157                bus: address.bus,
1158                dev: address.dev,
1159                func: address.func,
1160                bar: config.bar_index() as u8,
1161            },
1162            AllocOptions::new()
1163                .prefetchable(config.is_prefetchable())
1164                .align(config.size()),
1165        )?;
1166        let config = config.set_address(device_addr);
1167        let _device_bar = virtio_pci_device
1168            .config_regs
1169            .add_pci_bar(config)
1170            .map_err(|e| PciDeviceError::IoRegistrationFailed(device_addr, e))?;
1171        ranges.push(BarRange {
1172            addr: device_addr,
1173            size: config.size(),
1174            prefetchable: false,
1175        });
1176    }
1177
1178    if virtio_pci_device
1179        .device
1180        .get_shared_memory_region()
1181        .is_some()
1182    {
1183        let shmem_region = AddressRange::from_start_and_size(ranges[0].addr, ranges[0].size)
1184            .expect("invalid shmem region");
1185        virtio_pci_device
1186            .device
1187            .set_shared_memory_region(shmem_region);
1188    }
1189
1190    Ok(ranges)
1191}
1192
1193#[cfg(feature = "pci-hotplug")]
1194impl HotPluggable for VirtioPciDevice {
1195    /// Sets PciAddress to pci_addr
1196    fn set_pci_address(&mut self, pci_addr: PciAddress) -> std::result::Result<(), PciDeviceError> {
1197        self.pci_address = Some(pci_addr);
1198        self.msix_config
1199            .lock()
1200            .set_pci_address(self.pci_address.unwrap());
1201        Ok(())
1202    }
1203
1204    /// Configures IO BAR layout without memory alloc.
1205    fn configure_io_bars(&mut self) -> std::result::Result<(), PciDeviceError> {
1206        let mut simple_allocator = SimpleAllocator::new(0);
1207        allocate_io_bars(self, |size, _, _| simple_allocator.alloc(size, size)).map(|_| ())
1208    }
1209
1210    /// Configure device BAR layout without memory alloc.
1211    fn configure_device_bars(&mut self) -> std::result::Result<(), PciDeviceError> {
1212        // For device BAR, the space for CAPABILITY_BAR_SIZE should be skipped.
1213        let mut simple_allocator = SimpleAllocator::new(CAPABILITY_BAR_SIZE);
1214        allocate_device_bars(self, |size, _, _| simple_allocator.alloc(size, size)).map(|_| ())
1215    }
1216}
1217
1218#[cfg(feature = "pci-hotplug")]
1219/// A simple allocator that can allocate non-overlapping aligned intervals.
1220///
1221/// The addresses allocated are not exclusively reserved for the device, and cannot be used for a
1222/// static device. The allocated placeholder address describes the layout of PCI BAR for hotplugged
1223/// devices. Actual memory allocation is handled by PCI BAR reprogramming initiated by guest OS.
1224struct SimpleAllocator {
1225    current_address: u64,
1226}
1227
1228#[cfg(feature = "pci-hotplug")]
1229impl SimpleAllocator {
1230    /// Constructs SimpleAllocator. Address will start at or after base_address.
1231    fn new(base_address: u64) -> Self {
1232        Self {
1233            current_address: base_address,
1234        }
1235    }
1236
1237    /// Allocate memory with size and align. Returns the start of address.
1238    fn alloc(&mut self, size: u64, align: u64) -> std::result::Result<u64, PciDeviceError> {
1239        if align > 0 {
1240            // aligns current_address upward to align.
1241            self.current_address = self.current_address.next_multiple_of(align);
1242        }
1243        let start_address = self.current_address;
1244        self.current_address += size;
1245        Ok(start_address)
1246    }
1247}
1248
1249impl Suspendable for VirtioPciDevice {
1250    fn sleep(&mut self) -> anyhow::Result<()> {
1251        // If the device is already asleep, we should not request it to sleep again.
1252        if self.sleep_state.is_some() {
1253            return Ok(());
1254        }
1255
1256        if let Some(queues) = self.device.virtio_sleep()? {
1257            anyhow::ensure!(
1258                self.device_activated,
1259                format!(
1260                    "unactivated device {} returned queues on sleep",
1261                    self.debug_label()
1262                ),
1263            );
1264            self.sleep_state = Some(SleepState::Active {
1265                activated_queues: queues,
1266            });
1267        } else {
1268            anyhow::ensure!(
1269                !self.device_activated,
1270                format!(
1271                    "activated device {} didn't return queues on sleep",
1272                    self.debug_label()
1273                ),
1274            );
1275            self.sleep_state = Some(SleepState::Inactive);
1276        }
1277        Ok(())
1278    }
1279
1280    fn wake(&mut self) -> anyhow::Result<()> {
1281        match self.sleep_state.take() {
1282            None => {
1283                // If the device is already awake, we should not request it to wake again.
1284            }
1285            Some(SleepState::Inactive) => {
1286                self.device.virtio_wake(None).with_context(|| {
1287                    format!(
1288                        "virtio_wake failed for {}, can't recover",
1289                        self.debug_label(),
1290                    )
1291                })?;
1292            }
1293            Some(SleepState::Active { activated_queues }) => {
1294                self.device
1295                    .virtio_wake(Some((
1296                        self.mem.clone(),
1297                        self.interrupt
1298                            .clone()
1299                            .expect("interrupt missing for already active queues"),
1300                        activated_queues,
1301                    )))
1302                    .with_context(|| {
1303                        format!(
1304                            "virtio_wake failed for {}, can't recover",
1305                            self.debug_label(),
1306                        )
1307                    })?;
1308            }
1309        };
1310        Ok(())
1311    }
1312
1313    fn snapshot(&mut self) -> anyhow::Result<AnySnapshot> {
1314        if self.iommu.is_some() {
1315            return Err(anyhow!("Cannot snapshot if iommu is present."));
1316        }
1317
1318        AnySnapshot::to_any(VirtioPciDeviceSnapshot {
1319            config_regs: self.config_regs.snapshot()?,
1320            inner_device: self.device.virtio_snapshot()?,
1321            device_activated: self.device_activated,
1322            interrupt: self.interrupt.as_ref().map(|i| i.snapshot()),
1323            msix_config: self.msix_config.lock().snapshot()?,
1324            common_config: self.common_config,
1325            queues: self
1326                .queues
1327                .iter()
1328                .map(|q| q.snapshot())
1329                .collect::<anyhow::Result<Vec<_>>>()?,
1330            activated_queues: match &self.sleep_state {
1331                None => {
1332                    anyhow::bail!("tried snapshotting while awake")
1333                }
1334                Some(SleepState::Inactive) => None,
1335                Some(SleepState::Active { activated_queues }) => {
1336                    let mut serialized_queues = Vec::new();
1337                    for (index, queue) in activated_queues.iter() {
1338                        serialized_queues.push((*index, queue.snapshot()?));
1339                    }
1340                    Some(serialized_queues)
1341                }
1342            },
1343        })
1344        .context("failed to serialize VirtioPciDeviceSnapshot")
1345    }
1346
1347    fn restore(&mut self, data: AnySnapshot) -> anyhow::Result<()> {
1348        // Restoring from an activated state is more complex and low priority, so just fail for
1349        // now. We'll need to reset the device before restoring, e.g. must call
1350        // self.unregister_ioevents().
1351        anyhow::ensure!(
1352            !self.device_activated,
1353            "tried to restore after virtio device activated. not supported yet"
1354        );
1355
1356        let deser: VirtioPciDeviceSnapshot = AnySnapshot::from_any(data)?;
1357
1358        self.config_regs.restore(deser.config_regs)?;
1359        self.device_activated = deser.device_activated;
1360
1361        self.msix_config.lock().restore(deser.msix_config)?;
1362        self.common_config = deser.common_config;
1363
1364        // Restore the interrupt. This must be done after restoring the MSI-X configuration, but
1365        // before restoring the queues.
1366        if let Some(deser_interrupt) = deser.interrupt {
1367            let interrupt = Interrupt::new_from_snapshot(
1368                self.interrupt_evt
1369                    .as_ref()
1370                    .ok_or_else(|| anyhow!("{} interrupt_evt is none", self.debug_label()))?
1371                    .try_clone()
1372                    .with_context(|| {
1373                        format!("{} failed to clone interrupt_evt", self.debug_label())
1374                    })?,
1375                Some(self.msix_config.clone()),
1376                self.common_config.msix_config,
1377                deser_interrupt,
1378                #[cfg(target_arch = "x86_64")]
1379                Some((
1380                    PmWakeupEvent::new(self.vm_control_tube.clone(), self.pm_config.clone()),
1381                    MetricEventType::VirtioWakeup {
1382                        virtio_id: self.device.device_type().into(),
1383                    },
1384                )),
1385            );
1386            self.interrupt_resample_worker = interrupt.spawn_resample_thread();
1387            self.interrupt = Some(interrupt);
1388        }
1389
1390        assert_eq!(
1391            self.queues.len(),
1392            deser.queues.len(),
1393            "device must have the same number of queues"
1394        );
1395        for (q, s) in self.queues.iter_mut().zip(deser.queues.into_iter()) {
1396            q.restore(s)?;
1397        }
1398
1399        // Verify we are asleep and inactive.
1400        match &self.sleep_state {
1401            None => {
1402                anyhow::bail!("tried restoring while awake")
1403            }
1404            Some(SleepState::Inactive) => {}
1405            Some(SleepState::Active { .. }) => {
1406                anyhow::bail!("tried to restore after virtio device activated. not supported yet")
1407            }
1408        };
1409        // Restore `sleep_state`.
1410        if let Some(activated_queues_snapshot) = deser.activated_queues {
1411            let interrupt = self
1412                .interrupt
1413                .as_ref()
1414                .context("tried to restore active queues without an interrupt")?;
1415            let mut activated_queues = BTreeMap::new();
1416            for (index, queue_snapshot) in activated_queues_snapshot {
1417                let queue_config = self
1418                    .queues
1419                    .get(index)
1420                    .with_context(|| format!("missing queue config for activated queue {index}"))?;
1421                let queue_evt = self
1422                    .queue_evts
1423                    .get(index)
1424                    .with_context(|| format!("missing queue event for activated queue {index}"))?
1425                    .event
1426                    .try_clone()
1427                    .context("failed to clone queue event")?;
1428                activated_queues.insert(
1429                    index,
1430                    Queue::restore(
1431                        queue_config,
1432                        queue_snapshot,
1433                        &self.mem,
1434                        queue_evt,
1435                        interrupt.clone(),
1436                    )?,
1437                );
1438            }
1439
1440            // Restore the activated queues.
1441            self.sleep_state = Some(SleepState::Active { activated_queues });
1442        } else {
1443            self.sleep_state = Some(SleepState::Inactive);
1444        }
1445
1446        // Call register_io_events for the activated queue events.
1447        let bar0 = self.config_regs.get_bar_addr(self.settings_bar);
1448        let notify_base = bar0 + NOTIFICATION_BAR_OFFSET;
1449        self.queues
1450            .iter()
1451            .enumerate()
1452            .zip(self.queue_evts.iter_mut())
1453            .filter(|((_, q), _)| q.ready())
1454            .try_for_each(|((queue_index, _queue), evt)| {
1455                if !evt.ioevent_registered {
1456                    self.ioevent_vm_memory_client
1457                        .register_io_event(
1458                            evt.event.try_clone().context("failed to clone Event")?,
1459                            notify_base + queue_index as u64 * u64::from(NOTIFY_OFF_MULTIPLIER),
1460                            Datamatch::AnyLength,
1461                        )
1462                        .context("failed to register ioevent")?;
1463                    evt.ioevent_registered = true;
1464                }
1465                Ok::<(), anyhow::Error>(())
1466            })?;
1467
1468        // There might be data in the queue that wasn't drained by the device
1469        // at the time it was snapshotted. In this case, the doorbell should
1470        // still be signaled. If it is not, the driver may never re-trigger the
1471        // doorbell, and the device will stall. So here, we explicitly signal
1472        // every doorbell. Spurious doorbells are safe (devices will check their
1473        // queue, realize nothing is there, and go back to sleep.)
1474        self.queue_evts.iter_mut().try_for_each(|queue_event| {
1475            queue_event
1476                .event
1477                .signal()
1478                .context("failed to wake doorbell")
1479        })?;
1480
1481        self.device.virtio_restore(deser.inner_device)?;
1482
1483        Ok(())
1484    }
1485}
1486
1487struct VmRequester {
1488    vm_memory_client: VmMemoryClient,
1489    alloc: Alloc,
1490    mappings: BTreeMap<u64, VmMemoryRegionId>,
1491    prepare_type: SharedMemoryPrepareType,
1492    prepared: bool,
1493}
1494
1495impl VmRequester {
1496    fn new(
1497        vm_memory_client: VmMemoryClient,
1498        alloc: Alloc,
1499        prepare_type: SharedMemoryPrepareType,
1500    ) -> Self {
1501        Self {
1502            vm_memory_client,
1503            alloc,
1504            mappings: BTreeMap::new(),
1505            prepare_type,
1506            prepared: false,
1507        }
1508    }
1509}
1510
1511impl SharedMemoryMapper for VmRequester {
1512    fn add_mapping(
1513        &mut self,
1514        source: VmMemorySource,
1515        offset: u64,
1516        prot: Protection,
1517        cache: MemCacheType,
1518    ) -> anyhow::Result<()> {
1519        if !self.prepared {
1520            if let SharedMemoryPrepareType::SingleMappingOnFirst {
1521                cache_type: prepare_cache_type,
1522                force,
1523            } = self.prepare_type
1524            {
1525                debug!(
1526                    "lazy prepare_shared_memory_region with {:?} (force={})",
1527                    prepare_cache_type, force
1528                );
1529                self.vm_memory_client
1530                    .prepare_shared_memory_region(self.alloc, prepare_cache_type, force)
1531                    .context("lazy prepare_shared_memory_region failed")?;
1532            }
1533            self.prepared = true;
1534        }
1535
1536        // devices must implement VirtioDevice::get_shared_memory_prepare_type(), returning
1537        // SharedMemoryPrepareType::SingleMappingOnFirst with MemCacheType::CacheNonCoherent in
1538        // order to add any mapping that requests MemCacheType::CacheNonCoherent.
1539        if cache == MemCacheType::CacheNonCoherent {
1540            if let SharedMemoryPrepareType::SingleMappingOnFirst {
1541                cache_type: MemCacheType::CacheCoherent,
1542                ..
1543            } = self.prepare_type
1544            {
1545                error!("invalid request to map with CacheNonCoherent for device with prepared CacheCoherent memory");
1546                return Err(anyhow!("invalid MemCacheType"));
1547            }
1548        }
1549
1550        let id = self
1551            .vm_memory_client
1552            .register_memory(
1553                source,
1554                VmMemoryDestination::ExistingAllocation {
1555                    allocation: self.alloc,
1556                    offset,
1557                },
1558                prot,
1559                cache,
1560            )
1561            .context("register_memory failed")?;
1562
1563        self.mappings.insert(offset, id);
1564        Ok(())
1565    }
1566
1567    fn remove_mapping(&mut self, offset: u64) -> anyhow::Result<()> {
1568        let id = self.mappings.remove(&offset).context("invalid offset")?;
1569        self.vm_memory_client
1570            .unregister_memory(id)
1571            .context("unregister_memory failed")
1572    }
1573
1574    fn as_raw_descriptor(&self) -> Option<RawDescriptor> {
1575        Some(self.vm_memory_client.as_raw_descriptor())
1576    }
1577}
1578
1579#[cfg(test)]
1580mod tests {
1581    use std::thread;
1582
1583    use vm_control::VmMemoryRequest;
1584    use vm_control::VmMemoryResponse;
1585    use vm_memory::GuestAddress;
1586
1587    use super::*;
1588
1589    /// A device with one queue. If `fail_activate` is set, the next activation fails.
1590    struct TestDevice {
1591        fail_activate: bool,
1592    }
1593
1594    impl VirtioDevice for TestDevice {
1595        fn keep_rds(&self) -> Vec<RawDescriptor> {
1596            Vec::new()
1597        }
1598
1599        fn device_type(&self) -> DeviceType {
1600            DeviceType::Block
1601        }
1602
1603        fn queue_max_sizes(&self) -> &[u16] {
1604            &[16]
1605        }
1606
1607        fn activate(
1608            &mut self,
1609            _mem: GuestMemory,
1610            _interrupt: Interrupt,
1611            _queues: BTreeMap<usize, Queue>,
1612        ) -> anyhow::Result<()> {
1613            if std::mem::take(&mut self.fail_activate) {
1614                return Err(anyhow!("test activation failure"));
1615            }
1616            Ok(())
1617        }
1618    }
1619
1620    #[test]
1621    fn needs_reset_prevents_activation() {
1622        let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap();
1623        let mut device = VirtioPciDevice::new(
1624            mem,
1625            Box::new(TestDevice {
1626                fail_activate: false,
1627            }),
1628            Tube::pair().unwrap().0,
1629            false,
1630            None,
1631            VmMemoryClient::new(Tube::pair().unwrap().0),
1632            Tube::pair().unwrap().0,
1633        )
1634        .unwrap();
1635        device.common_config.driver_status = (VIRTIO_CONFIG_S_ACKNOWLEDGE
1636            | VIRTIO_CONFIG_S_DRIVER
1637            | VIRTIO_CONFIG_S_DRIVER_OK
1638            | VIRTIO_CONFIG_S_FEATURES_OK) as u8;
1639        assert!(device.is_driver_ready());
1640
1641        // Queue activation failed; later BAR writes must not retry it.
1642        device.common_config.driver_status |= VIRTIO_CONFIG_S_NEEDS_RESET as u8;
1643        assert!(!device.is_driver_ready());
1644    }
1645
1646    #[test]
1647    fn reset_after_device_activation_failure() {
1648        // Common configuration register offsets.
1649        const STATUS: u64 = COMMON_CONFIG_BAR_OFFSET + 0x14;
1650        const QUEUE_ENABLE: u64 = COMMON_CONFIG_BAR_OFFSET + 0x1c;
1651        const QUEUE_DESC: u64 = COMMON_CONFIG_BAR_OFFSET + 0x20;
1652        const QUEUE_AVAIL: u64 = COMMON_CONFIG_BAR_OFFSET + 0x28;
1653        const QUEUE_USED: u64 = COMMON_CONFIG_BAR_OFFSET + 0x30;
1654
1655        let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap();
1656        let (ioevent_tube, ioevent_server) = Tube::pair().unwrap();
1657        // Acknowledge ioevent requests and record whether each registered or unregistered.
1658        let ioevent_server = thread::spawn(move || {
1659            let mut registrations = Vec::new();
1660            while let Ok(request) = ioevent_server.recv::<VmMemoryRequest>() {
1661                match request {
1662                    VmMemoryRequest::IoEventRaw(request) => registrations.push(request.register),
1663                    _ => panic!("unexpected VmMemoryRequest"),
1664                }
1665                ioevent_server.send(&VmMemoryResponse::Ok).unwrap();
1666            }
1667            registrations
1668        });
1669        let mut device = VirtioPciDevice::new(
1670            mem,
1671            Box::new(TestDevice {
1672                fail_activate: true,
1673            }),
1674            Tube::pair().unwrap().0,
1675            false,
1676            None,
1677            VmMemoryClient::new(ioevent_tube),
1678            Tube::pair().unwrap().0,
1679        )
1680        .unwrap();
1681        device.assign_irq(IrqLevelEvent::new().unwrap(), PciInterruptPin::IntA, 0);
1682        let bar = device.settings_bar;
1683        let features_ok = (VIRTIO_CONFIG_S_ACKNOWLEDGE
1684            | VIRTIO_CONFIG_S_DRIVER
1685            | VIRTIO_CONFIG_S_FEATURES_OK) as u8;
1686        let ready = features_ok | VIRTIO_CONFIG_S_DRIVER_OK as u8;
1687        let configure_queue = |device: &mut VirtioPciDevice| {
1688            device.write_bar(bar, STATUS, &[features_ok]);
1689            device.write_bar(bar, QUEUE_DESC, &0u64.to_le_bytes());
1690            device.write_bar(bar, QUEUE_AVAIL, &0x200u64.to_le_bytes());
1691            device.write_bar(bar, QUEUE_USED, &0x400u64.to_le_bytes());
1692            device.write_bar(bar, QUEUE_ENABLE, &1u16.to_le_bytes());
1693        };
1694
1695        // The queue activates but the device fails to.
1696        configure_queue(&mut device);
1697        device.write_bar(bar, STATUS, &[ready]);
1698        assert!(!device.device_activated);
1699        assert_ne!(
1700            device.common_config.driver_status & VIRTIO_CONFIG_S_NEEDS_RESET as u8,
1701            0
1702        );
1703        assert!(device.interrupt.is_some());
1704
1705        // Reset must clean up the queue, its ioevent and the interrupt even though the device
1706        // never activated.
1707        device.write_bar(bar, STATUS, &[0]);
1708        assert!(!device.queues[0].ready());
1709        assert!(!device.queue_evts[0].ioevent_registered);
1710        assert!(device.interrupt.is_none());
1711        assert!(device.interrupt_resample_worker.is_none());
1712
1713        // The driver can configure the queue again and activate the device.
1714        configure_queue(&mut device);
1715        device.write_bar(bar, STATUS, &[ready]);
1716        assert!(device.device_activated);
1717        assert_eq!(device.common_config.driver_status, ready);
1718
1719        drop(device);
1720        assert_eq!(ioevent_server.join().unwrap(), [true, false, true]);
1721    }
1722
1723    #[cfg(feature = "pci-hotplug")]
1724    #[test]
1725    fn allocate_aligned_address() {
1726        let mut simple_allocator = super::SimpleAllocator::new(0);
1727        // start at 0, aligned to 0x80. Interval end at 0x20.
1728        assert_eq!(simple_allocator.alloc(0x20, 0x80).unwrap(), 0);
1729        // 0x20 => start at 0x40. Interval end at 0x80.
1730        assert_eq!(simple_allocator.alloc(0x40, 0x40).unwrap(), 0x40);
1731        // 0x80 => start at 0x80, Interval end at 0x108.
1732        assert_eq!(simple_allocator.alloc(0x88, 0x80).unwrap(), 0x80);
1733        // 0x108 => start at 0x180. Interval end at 0x1b0.
1734        assert_eq!(simple_allocator.alloc(0x30, 0x80).unwrap(), 0x180);
1735    }
1736
1737    #[test]
1738    fn vm_requester_propagates_force_prepare_and_checks_cache_type() {
1739        let (client_tube, server_tube) = Tube::pair().unwrap();
1740        let alloc = Alloc::PciBar {
1741            bus: 0,
1742            dev: 1,
1743            func: 0,
1744            bar: 4,
1745        };
1746        let mut requester = VmRequester::new(
1747            VmMemoryClient::new(client_tube),
1748            alloc,
1749            SharedMemoryPrepareType::SingleMappingOnFirst {
1750                cache_type: MemCacheType::CacheCoherent,
1751                force: true,
1752            },
1753        );
1754
1755        let server = thread::spawn(move || {
1756            match server_tube.recv::<VmMemoryRequest>().unwrap() {
1757                VmMemoryRequest::PrepareSharedMemoryRegion {
1758                    alloc: req_alloc,
1759                    cache,
1760                    force,
1761                } => {
1762                    assert_eq!(req_alloc, alloc);
1763                    assert_eq!(cache, MemCacheType::CacheCoherent);
1764                    assert!(force);
1765                }
1766                other => panic!(
1767                    "expected PrepareSharedMemoryRegion, got {:?}",
1768                    std::mem::discriminant(&other)
1769                ),
1770            }
1771            server_tube.send(&VmMemoryResponse::Ok).unwrap();
1772
1773            match server_tube.recv::<VmMemoryRequest>().unwrap() {
1774                VmMemoryRequest::RegisterMemory { .. } => {}
1775                other => panic!(
1776                    "expected RegisterMemory, got {:?}",
1777                    std::mem::discriminant(&other)
1778                ),
1779            }
1780            server_tube
1781                .send(&VmMemoryResponse::RegisterMemory {
1782                    region_id: VmMemoryRegionId(GuestAddress(0x1000)),
1783                    slot: 7,
1784                })
1785                .unwrap();
1786        });
1787
1788        let shm = SharedMemory::new("test_blob", 4096).unwrap();
1789        requester
1790            .add_mapping(
1791                VmMemorySource::SharedMemory(shm),
1792                0,
1793                Protection::read_write(),
1794                MemCacheType::CacheCoherent,
1795            )
1796            .unwrap();
1797
1798        server.join().unwrap();
1799
1800        // Subsequent CacheNonCoherent mapping on a CacheCoherent-prepared region must still fail
1801        // even when force=true.
1802        let shm_nc = SharedMemory::new("test_blob_nc", 4096).unwrap();
1803        assert!(requester
1804            .add_mapping(
1805                VmMemorySource::SharedMemory(shm_nc),
1806                4096,
1807                Protection::read_write(),
1808                MemCacheType::CacheNonCoherent,
1809            )
1810            .is_err());
1811    }
1812}