Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/uefi/src/proto/pci/enumeration.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / uefi / src / proto / pci / enumeration.rs` 331 lines ยท 11201 bytes Raw Blame History 1 // SPDX-License-Identifier: MIT OR Apache-2.0 2 3 //! PCI Bus device function and bridge enumeration. 4 5 use core::error; 6 use core::fmt::{Display, Formatter}; 7 use core::mem::{self, MaybeUninit}; 8 9 use alloc::collections::btree_map::BTreeMap; 10 use alloc::collections::btree_set::{self, BTreeSet}; 11 use alloc::fmt; 12 13 use crate::proto::device_path::build::{BuildError, DevicePathBuilder}; 14 use crate::proto::device_path::{self, DevicePath, DevicePathUtilitiesError, PoolDevicePath}; 15 16 use super::PciIoAddress; 17 use super::root_bridge::PciRootBridgeIo; 18 19 #[derive(Clone, Copy, Debug)] 20 #[repr(C)] 21 struct PciRegister0 { 22 vendor_id: u16, 23 device_id: u16, 24 } 25 26 #[derive(Clone, Copy, Debug)] 27 #[repr(C)] 28 struct PciRegister2 { 29 revision_id: u8, 30 prog_if: u8, 31 subclass: u8, 32 class: u8, 33 } 34 35 #[derive(Clone, Copy, Debug)] 36 #[repr(C)] 37 struct PciRegister3 { 38 cache_line_size: u8, 39 latency_timer: u8, 40 header_type: u8, 41 bist: u8, 42 } 43 44 #[derive(Clone, Copy, Debug)] 45 #[repr(C)] 46 struct PciHeader1Register6 { 47 primary_bus: u8, 48 secondary_bus: u8, 49 subordinate_bus: u8, 50 secondary_latency_timer: u8, 51 } 52 53 /// Read the 4byte pci register with the given `addr` and cast it into the given structured representation. 54 fn read_device_register_u32( 55 proto: &mut PciRootBridgeIo, 56 addr: PciIoAddress, 57 ) -> uefi::Result { 58 // SAFETY: The memory is valid. 59 unsafe { 60 let raw = proto.pci().read_one::(addr)?; 61 let reg: T = mem::transmute_copy(&raw); 62 Ok(reg) 63 } 64 } 65 66 // ########################################################################################## 67 68 /// Error type used by the device path construction of [`PciTree`]. 69 #[derive(Debug)] 70 pub enum PciDevicePathBuildError { 71 /// The given [`PciIoAddress`] was invalid or not path of the enumeration. 72 InvalidAddress, 73 /// Error while constructing the pci device DevicePath. 74 PathBuildError(BuildError), 75 /// Error while 76 DevicePathUtilitiesError(DevicePathUtilitiesError), 77 } 78 impl From for PciDevicePathBuildError { 79 fn from(value: BuildError) -> Self { 80 Self::PathBuildError(value) 81 } 82 } 83 impl From for PciDevicePathBuildError { 84 fn from(value: DevicePathUtilitiesError) -> Self { 85 Self::DevicePathUtilitiesError(value) 86 } 87 } 88 89 impl Display for PciDevicePathBuildError { 90 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 91 write!(f, "{self:?}") 92 } 93 } 94 95 impl error::Error for PciDevicePathBuildError { 96 fn source(&self) -> Option<&(dyn error::Error + 'static)> { 97 match self { 98 Self::PathBuildError(e) => Some(e), 99 Self::DevicePathUtilitiesError(e) => Some(e), 100 _ => None, 101 } 102 } 103 } 104 105 // ------------------------------------------------------------------------------------------ 106 107 /// Struct representing the tree structure of PCI devices. 108 /// 109 /// This allows iterating over all valid PCI device addresses in a tree, as well as querying 110 /// the tree topology. 111 #[derive(Debug)] 112 pub struct PciTree { 113 segment: u32, 114 devices: BTreeSet, 115 bus_anchors: BTreeMap, 116 } 117 impl PciTree { 118 pub(crate) const fn new(segment: u32) -> Self { 119 Self { 120 segment, 121 devices: BTreeSet::new(), 122 bus_anchors: BTreeMap::new(), 123 } 124 } 125 126 pub(crate) fn should_visit_bus(&self, bus: u8) -> bool { 127 !self.bus_anchors.contains_key(&bus) 128 } 129 130 pub(crate) fn push_device(&mut self, addr: PciIoAddress) { 131 self.devices.insert(addr); 132 } 133 134 /// Pushes a new bridge into the topology. 135 /// 136 /// Returns `false` if the bus is already in the topology and `true` 137 /// if the bridge was added to the topology. 138 pub(crate) fn push_bridge(&mut self, addr: PciIoAddress, child_bus: u8) -> bool { 139 match self.bus_anchors.contains_key(&child_bus) { 140 true => false, 141 false => { 142 self.bus_anchors.insert(child_bus, addr); 143 true 144 } 145 } 146 } 147 148 /// Iterate over all valid PCI device addresses in this tree structure. 149 pub fn iter(&self) -> btree_set::Iter<'_, PciIoAddress> { 150 self.devices.iter() 151 } 152 153 /// Get the segment number of this PCI tree. 154 #[must_use] 155 pub const fn segment_nr(&self) -> u32 { 156 self.segment 157 } 158 159 /// Query the address of the parent PCI bridge this `addr`'s bus is subordinate to. 160 #[must_use] 161 pub fn parent_for(&self, addr: PciIoAddress) -> Option { 162 self.bus_anchors.get(&addr.bus).cloned() 163 } 164 165 /// Iterate over all subsequent busses below the given `addr`. 166 /// This yields 0 results if `addr` doesn't point to a PCI bridge. 167 pub fn child_bus_of_iter(&self, addr: PciIoAddress) -> impl Iterator { 168 self.bus_anchors 169 .iter() 170 .filter(move |&(_, parent)| *parent == addr) 171 .map(|(bus, _)| bus) 172 .cloned() 173 } 174 175 /// Construct a device path for the given PCI `addr` and append it to the given `root_path`. 176 /// 177 /// # Arguments 178 /// - `root_path`: The [`DevicePath`] instance corresponding to the [`PciRootBridgeIo`] instance that 179 /// produced this [`PciTree`]. This path is prepended to the generated device paths. 180 /// - `addr`: [`PciIoAddress`] of the device 181 pub fn device_path( 182 &self, 183 root_path: &DevicePath, 184 addr: PciIoAddress, 185 ) -> Result { 186 use device_path::build; 187 188 if !self.devices.contains(&addr) { 189 return Err(PciDevicePathBuildError::InvalidAddress); 190 } 191 192 // A PCI [`DevicePath`] can have max. 255 PCI segments, each of which is 6 bytes in size. 193 // These are prepended by the given `root_path`. A construction buffer of 2048 bytes 194 // should thus suffice for all realistic scenarios. 195 let mut bfr = [MaybeUninit::uninit(); 2048]; 196 let mut builder = DevicePathBuilder::with_buf(&mut bfr); 197 for node in root_path.node_iter() { 198 builder = builder.push(&node)?; 199 } 200 201 // A pci device path is built by appending segments of `dev` and `fun` address byte pairs 202 // starting from a pci root bus to the specified address. Since the child <-> parent 203 // relationship is stored from child to parent, we start at the address and recurse back 204 // to the parent for path generation. 205 fn inner<'a>( 206 root: &PciTree, 207 mut builder: DevicePathBuilder<'a>, 208 addr: PciIoAddress, 209 ) -> Result, BuildError> { 210 if let Some(parent) = root.parent_for(addr) { 211 builder = inner(root, builder, parent)?; 212 } 213 builder.push(&build::hardware::Pci { 214 function: addr.fun, 215 device: addr.dev, 216 }) 217 } 218 219 builder = inner(self, builder, addr)?; 220 Ok(builder.finalize()?.to_pool()?) 221 } 222 } 223 impl IntoIterator for PciTree { 224 type Item = PciIoAddress; 225 type IntoIter = btree_set::IntoIter; 226 227 fn into_iter(self) -> Self::IntoIter { 228 self.devices.into_iter() 229 } 230 } 231 impl<'a> IntoIterator for &'a PciTree { 232 type Item = &'a PciIoAddress; 233 type IntoIter = btree_set::Iter<'a, PciIoAddress>; 234 235 fn into_iter(self) -> Self::IntoIter { 236 self.devices.iter() 237 } 238 } 239 240 // ########################################################################################## 241 // # Query Helpers (read from a device's configuration registers) 242 243 fn get_vendor_id(proto: &mut PciRootBridgeIo, addr: PciIoAddress) -> uefi::Result { 244 read_device_register_u32::(proto, addr.with_register(0)).map(|v| v.vendor_id) 245 } 246 247 fn get_classes(proto: &mut PciRootBridgeIo, addr: PciIoAddress) -> uefi::Result<(u8, u8)> { 248 let reg = read_device_register_u32::(proto, addr.with_register(2 * 4))?; 249 Ok((reg.class, reg.subclass)) 250 } 251 252 fn get_header_type(proto: &mut PciRootBridgeIo, addr: PciIoAddress) -> uefi::Result { 253 read_device_register_u32::(proto, addr.with_register(3 * 4)) 254 .map(|v| v.header_type) 255 } 256 257 fn get_secondary_bus_range( 258 proto: &mut PciRootBridgeIo, 259 addr: PciIoAddress, 260 ) -> uefi::Result<(u8, u8)> { 261 let reg = read_device_register_u32::(proto, addr.with_register(6 * 4))?; 262 Ok((reg.secondary_bus, reg.subordinate_bus)) 263 } 264 265 // ########################################################################################## 266 // # Recursive visitor implementation 267 268 fn visit_function( 269 proto: &mut PciRootBridgeIo, 270 addr: PciIoAddress, 271 tree: &mut PciTree, 272 ) -> uefi::Result<()> { 273 if get_vendor_id(proto, addr)? == 0xFFFF { 274 return Ok(()); // function doesn't exist - bail instantly 275 } 276 tree.push_device(addr); 277 let (base_class, sub_class) = get_classes(proto, addr)?; 278 let header_type = get_header_type(proto, addr)? & `0b01111111`; 279 if base_class == 0x6 && sub_class == 0x4 && header_type == 0x01 { 280 // This is a PCI-to-PCI bridge controller. The current `addr` is the address with which it's 281 // mounted in the PCI tree we are currently traversing. Now we query its header, where 282 // the bridge tells us a range of addresses [secondary;subordinate], with which the other 283 // side of the bridge is mounted into the PCI tree. 284 let (secondary_bus_nr, subordinate_bus_nr) = get_secondary_bus_range(proto, addr)?; 285 if secondary_bus_nr == 0 || subordinate_bus_nr < secondary_bus_nr { 286 // If the secondary bus number is the root number, or if the range is invalid - this hardware 287 // is so horribly broken that we refrain from touching it. It might explode - or worse! 288 return Ok(()); 289 } 290 for bus in secondary_bus_nr..=subordinate_bus_nr { 291 // Recurse into the bus namespaces on the other side of the bridge, if we haven't visited 292 // the subordinate bus through a more direct path already 293 if tree.push_bridge(addr, bus) { 294 visit_bus(proto, PciIoAddress::new(bus, 0, 0), tree)?; 295 } 296 } 297 } 298 Ok(()) 299 } 300 301 fn visit_device( 302 proto: &mut PciRootBridgeIo, 303 addr: PciIoAddress, 304 tree: &mut PciTree, 305 ) -> uefi::Result<()> { 306 if get_vendor_id(proto, addr)? == 0xFFFF { 307 return Ok(()); // device doesn't exist 308 } 309 visit_function(proto, addr.with_function(0), tree)?; 310 if get_header_type(proto, addr.with_function(0))? & 0x80 != 0 { 311 // This is a multi-function device - also try the remaining functions [1;7] 312 // These remaining functions can be sparsely populated - as long as function 0 exists. 313 for fun in 1..=7 { 314 visit_function(proto, addr.with_function(fun), tree)?; 315 } 316 } 317 318 Ok(()) 319 } 320 321 pub(crate) fn visit_bus( 322 proto: &mut PciRootBridgeIo, 323 addr: PciIoAddress, 324 tree: &mut PciTree, 325 ) -> uefi::Result<()> { 326 // Given a valid bus entry point - simply try all possible devices addresses 327 for dev in 0..32 { 328 visit_device(proto, addr.with_device(dev), tree)?; 329 } 330 Ok(()) 331 }