1 // Copyright 2022, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //! Functions to scan the PCI bus for VirtIO devices.
16
17 use crate::memory::{MemoryTracker, MemoryTrackerError};
18 use alloc::boxed::Box;
19 use core::fmt;
20 use core::marker::PhantomData;
21 use fdtpci::PciInfo;
22 use log::debug;
23 use once_cell::race::OnceBox;
24 use virtio_drivers::{
25 device::{blk, socket},
26 transport::pci::{
27 bus::{BusDeviceIterator, PciRoot},
28 virtio_device_type, PciTransport,
29 },
30 Hal,
31 };
32
33 pub(super) static PCI_INFO: OnceBox<PciInfo> = OnceBox::new();
34
35 /// PCI errors.
36 #[derive(Debug, Clone)]
37 pub enum PciError {
38 /// Attempted to initialize the PCI more than once.
39 DuplicateInitialization,
40 /// Failed to map PCI CAM.
41 CamMapFailed(MemoryTrackerError),
42 /// Failed to map PCI BAR.
43 BarMapFailed(MemoryTrackerError),
44 }
45
46 impl fmt::Display for PciError {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result47 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48 match self {
49 Self::DuplicateInitialization => {
50 write!(f, "Attempted to initialize the PCI more than once.")
51 }
52 Self::CamMapFailed(e) => write!(f, "Failed to map PCI CAM: {e}"),
53 Self::BarMapFailed(e) => write!(f, "Failed to map PCI BAR: {e}"),
54 }
55 }
56 }
57
58 /// Prepares to use VirtIO PCI devices.
59 ///
60 /// In particular:
61 ///
62 /// 1. Maps the PCI CAM and BAR range in the page table and MMIO guard.
63 /// 2. Stores the `PciInfo` for the VirtIO HAL to use later.
64 /// 3. Creates and returns a `PciRoot`.
65 ///
66 /// This must only be called once; it will panic if it is called a second time.
initialize(pci_info: PciInfo, memory: &mut MemoryTracker) -> Result<PciRoot, PciError>67 pub fn initialize(pci_info: PciInfo, memory: &mut MemoryTracker) -> Result<PciRoot, PciError> {
68 PCI_INFO.set(Box::new(pci_info.clone())).map_err(|_| PciError::DuplicateInitialization)?;
69
70 memory.map_mmio_range(pci_info.cam_range.clone()).map_err(PciError::CamMapFailed)?;
71 let bar_range = pci_info.bar_range.start as usize..pci_info.bar_range.end as usize;
72 memory.map_mmio_range(bar_range).map_err(PciError::BarMapFailed)?;
73
74 // Safety: This is the only place where we call make_pci_root, and `PCI_INFO.set` above will
75 // panic if it is called a second time.
76 Ok(unsafe { pci_info.make_pci_root() })
77 }
78
79 /// Virtio Block device.
80 pub type VirtIOBlk<T> = blk::VirtIOBlk<T, PciTransport>;
81
82 /// Virtio Socket device.
83 ///
84 /// Spec: https://docs.oasis-open.org/virtio/virtio/v1.2/csd01/virtio-v1.2-csd01.html 5.10
85 pub type VirtIOSocket<T> = socket::VirtIOSocket<T, PciTransport>;
86
87 /// An iterator that iterates over the PCI transport for each device.
88 pub struct PciTransportIterator<'a, T: Hal> {
89 pci_root: &'a mut PciRoot,
90 bus: BusDeviceIterator,
91 _hal: PhantomData<T>,
92 }
93
94 impl<'a, T: Hal> PciTransportIterator<'a, T> {
95 /// Creates a new iterator.
new(pci_root: &'a mut PciRoot) -> Self96 pub fn new(pci_root: &'a mut PciRoot) -> Self {
97 let bus = pci_root.enumerate_bus(0);
98 Self { pci_root, bus, _hal: PhantomData }
99 }
100 }
101
102 impl<'a, T: Hal> Iterator for PciTransportIterator<'a, T> {
103 type Item = PciTransport;
104
next(&mut self) -> Option<Self::Item>105 fn next(&mut self) -> Option<Self::Item> {
106 loop {
107 let (device_function, info) = self.bus.next()?;
108 let (status, command) = self.pci_root.get_status_command(device_function);
109 debug!(
110 "Found PCI device {} at {}, status {:?} command {:?}",
111 info, device_function, status, command
112 );
113
114 let Some(virtio_type) = virtio_device_type(&info) else {
115 continue;
116 };
117 debug!(" VirtIO {:?}", virtio_type);
118
119 return PciTransport::new::<T>(self.pci_root, device_function).ok();
120 }
121 }
122 }
123