aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / aienos-accel / src / pci.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Pure, read-only decoders for PCI configuration space. |
| 17 | //! |
| 18 | //! Every function in this module interprets a byte slice supplied by the |
| 19 | //! caller. Nothing here performs a PCI configuration read, a PCI configuration |
| 20 | //! write, or an MMIO access. The bytes come from firmware services, from the |
| 21 | //! Linux sysfs `config` file, or from a synthetic fixture; these decoders only |
| 22 | //! interpret them. |
| 23 | //! |
| 24 | //! Malformed input is rejected, never guessed at. A truncated slice, an |
| 25 | //! out-of-bounds offset, an invalid BAR encoding, a capability loop, and an |
| 26 | //! overlong capability chain each return an error. Absence of a capability is |
| 27 | //! not the same as an all-zero capability and is represented as `None`. |
| 28 | |
| 29 | pub const CONFIG_HEADER_SIZE: usize = 64; |
| 30 | pub const CONFIG_SPACE_SIZE: usize = 256; |
| 31 | pub const CONFIG_EXTENDED_SIZE: usize = 4096; |
| 32 | |
| 33 | /// Status register bit 4: the capability list is present. |
| 34 | pub const STATUS_CAPABILITIES_LIST: u16 = 0x0010; |
| 35 | |
| 36 | pub const CAP_ID_POWER_MANAGEMENT: u8 = 0x01; |
| 37 | pub const CAP_ID_MSI: u8 = 0x05; |
| 38 | pub const CAP_ID_VENDOR: u8 = 0x09; |
| 39 | pub const CAP_ID_PCIE: u8 = 0x10; |
| 40 | pub const CAP_ID_MSIX: u8 = 0x11; |
| 41 | |
| 42 | const MAX_CAPABILITIES: usize = 48; |
| 43 | const MAX_EXTENDED_CAPABILITIES: usize = 64; |
| 44 | const MAX_EXTENDED_WORDS: usize = 64; |
| 45 | |
| 46 | /// A rejection reason from a decoder. Distinct variants let a caller tell a |
| 47 | /// truncated read from a genuinely malformed value. |
| 48 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 49 | pub enum PciError { |
| 50 | /// The supplied slice is shorter than the structure being decoded. |
| 51 | Truncated, |
| 52 | /// An offset or capability pointer points outside the supplied slice. |
| 53 | OutOfBounds, |
| 54 | /// A BAR encoding is reserved or otherwise impossible. |
| 55 | InvalidBar, |
| 56 | /// A capability pointer revisited an offset already visited. |
| 57 | CapabilityLoop, |
| 58 | /// More capabilities than the bounded chain permits. |
| 59 | TooManyCapabilities, |
| 60 | /// The standard header is not a type 0 endpoint header. |
| 61 | InvalidHeaderType, |
| 62 | /// A capability decoder was handed a different capability id. |
| 63 | WrongCapability, |
| 64 | } |
| 65 | |
| 66 | fn add(base: usize, delta: usize) -> Result<usize, PciError> { |
| 67 | base.checked_add(delta).ok_or(PciError::OutOfBounds) |
| 68 | } |
| 69 | |
| 70 | fn read_u8(bytes: &[u8], offset: usize) -> Result<u8, PciError> { |
| 71 | bytes.get(offset).copied().ok_or(PciError::OutOfBounds) |
| 72 | } |
| 73 | |
| 74 | fn read_u16(bytes: &[u8], offset: usize) -> Result<u16, PciError> { |
| 75 | let end = add(offset, 2)?; |
| 76 | let slice = bytes.get(offset..end).ok_or(PciError::OutOfBounds)?; |
| 77 | Ok(u16::from_le_bytes([slice[0], slice[1]])) |
| 78 | } |
| 79 | |
| 80 | fn read_u32(bytes: &[u8], offset: usize) -> Result<u32, PciError> { |
| 81 | let end = add(offset, 4)?; |
| 82 | let slice = bytes.get(offset..end).ok_or(PciError::OutOfBounds)?; |
| 83 | Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) |
| 84 | } |
| 85 | |
| 86 | /// A decoded Base Address Register. `None` marks an unimplemented or a high |
| 87 | /// dword consumed by the preceding 64-bit BAR. |
| 88 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 89 | pub enum Bar { |
| 90 | None, |
| 91 | Memory(MemoryBar), |
| 92 | Io(IoBar), |
| 93 | } |
| 94 | |
| 95 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 96 | pub struct MemoryBar { |
| 97 | pub base: u64, |
| 98 | pub is_64_bit: bool, |
| 99 | pub prefetchable: bool, |
| 100 | pub size: BarSize, |
| 101 | } |
| 102 | |
| 103 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 104 | pub struct IoBar { |
| 105 | pub base: u32, |
| 106 | pub size: BarSize, |
| 107 | } |
| 108 | |
| 109 | /// A BAR size is only known when a size probe produced it. Probing requires |
| 110 | /// writing all ones to the BAR, so a read-only observation leaves it unknown. |
| 111 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 112 | pub enum BarSize { |
| 113 | Known(u64), |
| 114 | Unknown, |
| 115 | } |
| 116 | |
| 117 | /// A decoded type 0 PCI header (endpoint). |
| 118 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 119 | pub struct Header { |
| 120 | pub vendor_id: u16, |
| 121 | pub device_id: u16, |
| 122 | pub command: u16, |
| 123 | pub status: u16, |
| 124 | pub revision: u8, |
| 125 | pub prog_if: u8, |
| 126 | pub subclass: u8, |
| 127 | pub class_code: u8, |
| 128 | pub header_type: u8, |
| 129 | pub multifunction: bool, |
| 130 | pub bars: [Bar; 6], |
| 131 | pub subsystem_vendor_id: u16, |
| 132 | pub subsystem_id: u16, |
| 133 | pub capability_pointer: u8, |
| 134 | pub interrupt_line: u8, |
| 135 | pub interrupt_pin: u8, |
| 136 | } |
| 137 | |
| 138 | impl Header { |
| 139 | pub fn parse(bytes: &[u8]) -> Result<Self, PciError> { |
| 140 | if bytes.len() < CONFIG_HEADER_SIZE { |
| 141 | return Err(PciError::Truncated); |
| 142 | } |
| 143 | let header_type = read_u8(bytes, 0x0e)?; |
| 144 | if header_type & 0x7f != 0x00 { |
| 145 | return Err(PciError::InvalidHeaderType); |
| 146 | } |
| 147 | Ok(Self { |
| 148 | vendor_id: read_u16(bytes, 0x00)?, |
| 149 | device_id: read_u16(bytes, 0x02)?, |
| 150 | command: read_u16(bytes, 0x04)?, |
| 151 | status: read_u16(bytes, 0x06)?, |
| 152 | revision: read_u8(bytes, 0x08)?, |
| 153 | prog_if: read_u8(bytes, 0x09)?, |
| 154 | subclass: read_u8(bytes, 0x0a)?, |
| 155 | class_code: read_u8(bytes, 0x0b)?, |
| 156 | header_type, |
| 157 | multifunction: header_type & 0x80 != 0, |
| 158 | bars: decode_bars(bytes, 0x10)?, |
| 159 | subsystem_vendor_id: read_u16(bytes, 0x2c)?, |
| 160 | subsystem_id: read_u16(bytes, 0x2e)?, |
| 161 | capability_pointer: read_u8(bytes, 0x34)?, |
| 162 | interrupt_line: read_u8(bytes, 0x3c)?, |
| 163 | interrupt_pin: read_u8(bytes, 0x3d)?, |
| 164 | }) |
| 165 | } |
| 166 | |
| 167 | /// Memory decoding enabled (PCI command register bit 1). |
| 168 | pub fn memory_enabled(&self) -> bool { |
| 169 | self.command & 0x0002 != 0 |
| 170 | } |
| 171 | |
| 172 | pub fn has_capability_list(&self) -> bool { |
| 173 | self.status & STATUS_CAPABILITIES_LIST != 0 |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | /// Decode the six standard type 0 BAR slots starting at `offset`. |
| 178 | fn decode_bars(bytes: &[u8], offset: usize) -> Result<[Bar; 6], PciError> { |
| 179 | let mut bars = [Bar::None; 6]; |
| 180 | let mut index = 0usize; |
| 181 | while index < 6 { |
| 182 | let low_offset = offset.checked_add(index * 4).ok_or(PciError::OutOfBounds)?; |
| 183 | let low = read_u32(bytes, low_offset)?; |
| 184 | if low == 0 { |
| 185 | index += 1; |
| 186 | continue; |
| 187 | } |
| 188 | if low & 0x1 == 0x1 { |
| 189 | // IO BAR: bits [2:1] are reserved and must be zero. |
| 190 | if low & 0x6 != 0 { |
| 191 | return Err(PciError::InvalidBar); |
| 192 | } |
| 193 | bars[index] = Bar::Io(IoBar { |
| 194 | base: low & !0x3, |
| 195 | size: BarSize::Unknown, |
| 196 | }); |
| 197 | index += 1; |
| 198 | continue; |
| 199 | } |
| 200 | match (low >> 1) & 0x3 { |
| 201 | 0b00 => { |
| 202 | bars[index] = Bar::Memory(MemoryBar { |
| 203 | base: u64::from(low & !0xf), |
| 204 | is_64_bit: false, |
| 205 | prefetchable: low & 0x8 != 0, |
| 206 | size: BarSize::Unknown, |
| 207 | }); |
| 208 | index += 1; |
| 209 | } |
| 210 | 0b10 => { |
| 211 | // A 64-bit memory BAR consumes the next slot for its high |
| 212 | // dword. The last slot cannot start one. |
| 213 | if index + 1 >= 6 { |
| 214 | return Err(PciError::InvalidBar); |
| 215 | } |
| 216 | let high = read_u32(bytes, low_offset + 4)?; |
| 217 | bars[index] = Bar::Memory(MemoryBar { |
| 218 | base: (u64::from(high) << 32) | u64::from(low & !0xf), |
| 219 | is_64_bit: true, |
| 220 | prefetchable: low & 0x8 != 0, |
| 221 | size: BarSize::Unknown, |
| 222 | }); |
| 223 | index += 2; |
| 224 | } |
| 225 | // 0b01 and 0b11 are reserved encodings. |
| 226 | _ => return Err(PciError::InvalidBar), |
| 227 | } |
| 228 | } |
| 229 | Ok(bars) |
| 230 | } |
| 231 | |
| 232 | /// Decode a memory BAR size from the all-ones readback a size probe produces. |
| 233 | /// |
| 234 | /// This is a pure decoder for a probe result the caller already has. It does |
| 235 | /// not perform the probe: writing all ones to a BAR is a PCI configuration |
| 236 | /// write and lies outside AIENOS's read-only characterization boundary. A |
| 237 | /// non-power-of-two or out-of-range mask returns `None` rather than a size. |
| 238 | pub fn memory_bar_size(low: u32, high: u32, is_64_bit: bool) -> Option<u64> { |
| 239 | // A probe writes all ones; the device returns ones for every unimplemented |
| 240 | // bit, so size = !(readback & !0xf) + 1 within the BAR's address width. |
| 241 | if is_64_bit { |
| 242 | let mask = (u64::from(high) << 32) | u64::from(low & !0xf); |
| 243 | if mask == 0 || mask == u64::MAX { |
| 244 | return None; |
| 245 | } |
| 246 | let size = (!mask).checked_add(1)?; |
| 247 | if !size.is_power_of_two() || size > (1u64 << 46) { |
| 248 | return None; |
| 249 | } |
| 250 | Some(size) |
| 251 | } else { |
| 252 | let mask = low & !0xf; |
| 253 | if mask == 0 || mask == u32::MAX { |
| 254 | return None; |
| 255 | } |
| 256 | let size = u64::from((!mask).checked_add(1)?); |
| 257 | if !size.is_power_of_two() || size > (1u64 << 32) { |
| 258 | return None; |
| 259 | } |
| 260 | Some(size) |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// Decode an IO BAR size from an all-ones readback. See `memory_bar_size`. |
| 265 | pub fn io_bar_size(low: u32) -> Option<u64> { |
| 266 | let mask = low & !0x3; |
| 267 | if mask == 0 || mask == u32::MAX { |
| 268 | return None; |
| 269 | } |
| 270 | let size = u64::from((!mask).checked_add(1)?); |
| 271 | if !size.is_power_of_two() || size > (1u64 << 32) { |
| 272 | return None; |
| 273 | } |
| 274 | Some(size) |
| 275 | } |
| 276 | |
| 277 | /// One entry in the standard capability linked list. |
| 278 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 279 | pub struct Capability { |
| 280 | pub id: u8, |
| 281 | pub offset: u8, |
| 282 | pub next: u8, |
| 283 | } |
| 284 | |
| 285 | /// A bounded, loop-checked standard capability list. |
| 286 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 287 | pub struct CapabilityList { |
| 288 | entries: [Capability; MAX_CAPABILITIES], |
| 289 | len: usize, |
| 290 | } |
| 291 | |
| 292 | impl CapabilityList { |
| 293 | pub const fn empty() -> Self { |
| 294 | Self { |
| 295 | entries: [Capability { |
| 296 | id: 0, |
| 297 | offset: 0, |
| 298 | next: 0, |
| 299 | }; MAX_CAPABILITIES], |
| 300 | len: 0, |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | pub fn entries(&self) -> &[Capability] { |
| 305 | &self.entries[..self.len] |
| 306 | } |
| 307 | |
| 308 | pub fn find(&self, id: u8) -> Option<Capability> { |
| 309 | self.entries().iter().copied().find(|entry| entry.id == id) |
| 310 | } |
| 311 | |
| 312 | fn push(&mut self, entry: Capability) -> Result<(), PciError> { |
| 313 | if self.len == MAX_CAPABILITIES { |
| 314 | return Err(PciError::TooManyCapabilities); |
| 315 | } |
| 316 | self.entries[self.len] = entry; |
| 317 | self.len += 1; |
| 318 | Ok(()) |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | /// Walk the standard capability linked list in a 256-byte configuration space. |
| 323 | /// |
| 324 | /// Returns an empty list when the status register reports no capability list or |
| 325 | /// the capability pointer is zero. Rejects pointers below `0x40`, unaligned |
| 326 | /// pointers, offsets past the end, revisited offsets (loops), and chains |
| 327 | /// longer than the bound. |
| 328 | pub fn walk_capabilities(bytes: &[u8]) -> Result<CapabilityList, PciError> { |
| 329 | if bytes.len() < CONFIG_SPACE_SIZE { |
| 330 | return Err(PciError::Truncated); |
| 331 | } |
| 332 | let mut list = CapabilityList::empty(); |
| 333 | let status = read_u16(bytes, 0x06)?; |
| 334 | if status & STATUS_CAPABILITIES_LIST == 0 { |
| 335 | return Ok(list); |
| 336 | } |
| 337 | let mut offset = read_u8(bytes, 0x34)?; |
| 338 | let mut seen = [0u64; 4]; |
| 339 | while offset != 0 { |
| 340 | let index = usize::from(offset); |
| 341 | if index < 0x40 || !index.is_multiple_of(4) { |
| 342 | return Err(PciError::OutOfBounds); |
| 343 | } |
| 344 | if add(index, 2)? > CONFIG_SPACE_SIZE { |
| 345 | return Err(PciError::OutOfBounds); |
| 346 | } |
| 347 | let word = index / 64; |
| 348 | let bit = 1u64 << (index % 64); |
| 349 | if seen[word] & bit != 0 { |
| 350 | return Err(PciError::CapabilityLoop); |
| 351 | } |
| 352 | seen[word] |= bit; |
| 353 | let id = read_u8(bytes, index)?; |
| 354 | let next = read_u8(bytes, add(index, 1)?)?; |
| 355 | list.push(Capability { id, offset, next })?; |
| 356 | offset = next; |
| 357 | } |
| 358 | Ok(list) |
| 359 | } |
| 360 | |
| 361 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 362 | pub struct MsiCapability { |
| 363 | pub offset: u8, |
| 364 | pub enabled: bool, |
| 365 | pub capable_vectors: u16, |
| 366 | pub enabled_vectors: u16, |
| 367 | pub is_64_bit: bool, |
| 368 | pub maskable: bool, |
| 369 | pub address: u64, |
| 370 | pub data: u16, |
| 371 | } |
| 372 | |
| 373 | impl MsiCapability { |
| 374 | pub fn decode(bytes: &[u8], capability: Capability) -> Result<Self, PciError> { |
| 375 | if capability.id != CAP_ID_MSI { |
| 376 | return Err(PciError::WrongCapability); |
| 377 | } |
| 378 | let offset = usize::from(capability.offset); |
| 379 | let control = read_u16(bytes, add(offset, 2)?)?; |
| 380 | let is_64_bit = control & 0x0080 != 0; |
| 381 | let capable_vectors = 1u16 << ((control >> 1) & 0x7); |
| 382 | let enabled_vectors = 1u16 << ((control >> 4) & 0x7); |
| 383 | let address_low = read_u32(bytes, add(offset, 4)?)?; |
| 384 | let (address, data_offset) = if is_64_bit { |
| 385 | let address_high = read_u32(bytes, add(offset, 8)?)?; |
| 386 | ( |
| 387 | (u64::from(address_high) << 32) | u64::from(address_low), |
| 388 | add(offset, 12)?, |
| 389 | ) |
| 390 | } else { |
| 391 | (u64::from(address_low), add(offset, 8)?) |
| 392 | }; |
| 393 | Ok(Self { |
| 394 | offset: capability.offset, |
| 395 | enabled: control & 0x0001 != 0, |
| 396 | capable_vectors, |
| 397 | enabled_vectors, |
| 398 | is_64_bit, |
| 399 | maskable: control & 0x0100 != 0, |
| 400 | address, |
| 401 | data: read_u16(bytes, data_offset)?, |
| 402 | }) |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 407 | pub struct MsixCapability { |
| 408 | pub offset: u8, |
| 409 | pub enabled: bool, |
| 410 | pub function_masked: bool, |
| 411 | /// Number of table entries. The configuration field stores N-1. |
| 412 | pub vectors: u16, |
| 413 | pub table_bir: u8, |
| 414 | pub table_offset: u32, |
| 415 | pub pba_bir: u8, |
| 416 | pub pba_offset: u32, |
| 417 | } |
| 418 | |
| 419 | impl MsixCapability { |
| 420 | pub fn decode(bytes: &[u8], capability: Capability) -> Result<Self, PciError> { |
| 421 | if capability.id != CAP_ID_MSIX { |
| 422 | return Err(PciError::WrongCapability); |
| 423 | } |
| 424 | let offset = usize::from(capability.offset); |
| 425 | let control = read_u16(bytes, add(offset, 2)?)?; |
| 426 | let table = read_u32(bytes, add(offset, 4)?)?; |
| 427 | let pba = read_u32(bytes, add(offset, 8)?)?; |
| 428 | Ok(Self { |
| 429 | offset: capability.offset, |
| 430 | enabled: control & 0x8000 != 0, |
| 431 | function_masked: control & 0x4000 != 0, |
| 432 | vectors: (control & 0x07ff) + 1, |
| 433 | table_bir: (table & 0x0000_0007) as u8, |
| 434 | table_offset: table & !0x0000_0007, |
| 435 | pba_bir: (pba & 0x0000_0007) as u8, |
| 436 | pba_offset: pba & !0x0000_0007, |
| 437 | }) |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | /// PCI Express link speed encoding from the Link Capabilities register. |
| 442 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 443 | pub enum LinkSpeed { |
| 444 | Unknown, |
| 445 | Gen1, |
| 446 | Gen2, |
| 447 | Gen3, |
| 448 | Gen4, |
| 449 | Gen5, |
| 450 | Gen6, |
| 451 | } |
| 452 | |
| 453 | impl LinkSpeed { |
| 454 | pub fn from_encoding(encoding: u8) -> Self { |
| 455 | match encoding { |
| 456 | 1 => LinkSpeed::Gen1, |
| 457 | 2 => LinkSpeed::Gen2, |
| 458 | 3 => LinkSpeed::Gen3, |
| 459 | 4 => LinkSpeed::Gen4, |
| 460 | 5 => LinkSpeed::Gen5, |
| 461 | 6 => LinkSpeed::Gen6, |
| 462 | _ => LinkSpeed::Unknown, |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | pub fn gigatransfers(self) -> Option<u8> { |
| 467 | match self { |
| 468 | LinkSpeed::Unknown => None, |
| 469 | LinkSpeed::Gen1 => Some(2), |
| 470 | LinkSpeed::Gen2 => Some(5), |
| 471 | LinkSpeed::Gen3 => Some(8), |
| 472 | LinkSpeed::Gen4 => Some(16), |
| 473 | LinkSpeed::Gen5 => Some(32), |
| 474 | LinkSpeed::Gen6 => Some(64), |
| 475 | } |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 480 | pub struct PcieLink { |
| 481 | pub max_speed: LinkSpeed, |
| 482 | pub max_width: u8, |
| 483 | /// Raw supported-link-speeds bitmap from Link Capabilities 2, or 0 when the |
| 484 | /// function does not expose a second link capability register. |
| 485 | pub supported_speeds: u16, |
| 486 | pub current_speed: LinkSpeed, |
| 487 | pub current_width: u8, |
| 488 | pub downgraded: bool, |
| 489 | } |
| 490 | |
| 491 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 492 | pub struct PcieCapability { |
| 493 | pub offset: u8, |
| 494 | pub version: u8, |
| 495 | pub device_type: u8, |
| 496 | pub slot_implemented: bool, |
| 497 | /// Payload size in bytes derived from the device capabilities field. |
| 498 | pub max_payload_bytes: u16, |
| 499 | pub link: Option<PcieLink>, |
| 500 | } |
| 501 | |
| 502 | impl PcieCapability { |
| 503 | pub fn decode(bytes: &[u8], capability: Capability) -> Result<Self, PciError> { |
| 504 | if capability.id != CAP_ID_PCIE { |
| 505 | return Err(PciError::WrongCapability); |
| 506 | } |
| 507 | let offset = usize::from(capability.offset); |
| 508 | let cap = read_u16(bytes, add(offset, 2)?)?; |
| 509 | let device_type = ((cap >> 4) & 0x000f) as u8; |
| 510 | let device_caps = read_u32(bytes, add(offset, 4)?)?; |
| 511 | let max_payload_bytes = 128u16 << ((device_caps & 0x7) as u16); |
| 512 | // Root Complex Integrated Endpoints (8) and Event Collectors (9) do |
| 513 | // not implement the Link Capabilities register; every other type does. |
| 514 | let link = if matches!(device_type, 0x8 | 0x9) { |
| 515 | None |
| 516 | } else { |
| 517 | Some(decode_pcie_link(bytes, offset)?) |
| 518 | }; |
| 519 | Ok(Self { |
| 520 | offset: capability.offset, |
| 521 | version: (cap & 0x000f) as u8, |
| 522 | device_type, |
| 523 | slot_implemented: cap & 0x0100 != 0, |
| 524 | max_payload_bytes, |
| 525 | link, |
| 526 | }) |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | fn decode_pcie_link(bytes: &[u8], offset: usize) -> Result<PcieLink, PciError> { |
| 531 | let link_caps = read_u32(bytes, add(offset, 0x0c)?)?; |
| 532 | let link_status = read_u16(bytes, add(offset, 0x12)?)?; |
| 533 | let max_speed = LinkSpeed::from_encoding((link_caps & 0x000f) as u8); |
| 534 | let max_width = ((link_caps >> 4) & 0x003f) as u8; |
| 535 | let current_speed = LinkSpeed::from_encoding((link_status & 0x000f) as u8); |
| 536 | let current_width = ((link_status >> 4) & 0x003f) as u8; |
| 537 | let supported_speeds = if add(offset, 0x20)? <= bytes.len() { |
| 538 | (read_u32(bytes, add(offset, 0x1c)?)? & 0x0000_007f) as u16 |
| 539 | } else { |
| 540 | 0 |
| 541 | }; |
| 542 | let speed_downgraded = max_speed != LinkSpeed::Unknown |
| 543 | && current_speed != LinkSpeed::Unknown |
| 544 | && current_speed != max_speed; |
| 545 | Ok(PcieLink { |
| 546 | max_speed, |
| 547 | max_width, |
| 548 | supported_speeds, |
| 549 | current_speed, |
| 550 | current_width, |
| 551 | downgraded: speed_downgraded || current_width < max_width, |
| 552 | }) |
| 553 | } |
| 554 | |
| 555 | /// One extended capability header (PCI Express, configuration offset >= 0x100). |
| 556 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 557 | pub struct ExtendedCapability { |
| 558 | pub id: u16, |
| 559 | pub version: u8, |
| 560 | pub offset: u16, |
| 561 | } |
| 562 | |
| 563 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 564 | pub struct ExtendedCapabilityList { |
| 565 | entries: [ExtendedCapability; MAX_EXTENDED_CAPABILITIES], |
| 566 | len: usize, |
| 567 | } |
| 568 | |
| 569 | impl ExtendedCapabilityList { |
| 570 | pub const fn empty() -> Self { |
| 571 | Self { |
| 572 | entries: [ExtendedCapability { |
| 573 | id: 0, |
| 574 | version: 0, |
| 575 | offset: 0, |
| 576 | }; MAX_EXTENDED_CAPABILITIES], |
| 577 | len: 0, |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | pub fn entries(&self) -> &[ExtendedCapability] { |
| 582 | &self.entries[..self.len] |
| 583 | } |
| 584 | |
| 585 | pub fn find(&self, id: u16) -> Option<ExtendedCapability> { |
| 586 | self.entries().iter().copied().find(|entry| entry.id == id) |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | /// Walk the extended capability list starting at `0x100`. |
| 591 | /// |
| 592 | /// Returns an empty list when the slice stops at or before `0x100`, so a |
| 593 | /// 64-byte or 256-byte read yields no extended capabilities rather than an |
| 594 | /// error. Rejects out-of-bounds next pointers, revisited offsets, and chains |
| 595 | /// longer than the bound. |
| 596 | pub fn walk_extended_capabilities(bytes: &[u8]) -> Result<ExtendedCapabilityList, PciError> { |
| 597 | let mut list = ExtendedCapabilityList::empty(); |
| 598 | if add(CONFIG_SPACE_SIZE, 4)? > bytes.len() { |
| 599 | return Ok(list); |
| 600 | } |
| 601 | let mut offset = CONFIG_SPACE_SIZE; |
| 602 | let mut seen = [0u64; MAX_EXTENDED_WORDS]; |
| 603 | let mut count = 0usize; |
| 604 | while offset != 0 { |
| 605 | if !offset.is_multiple_of(4) || add(offset, 4)? > CONFIG_EXTENDED_SIZE { |
| 606 | return Err(PciError::OutOfBounds); |
| 607 | } |
| 608 | if add(offset, 4)? > bytes.len() { |
| 609 | return Err(PciError::OutOfBounds); |
| 610 | } |
| 611 | let word = offset / 64; |
| 612 | let bit = 1u64 << (offset % 64); |
| 613 | if seen[word] & bit != 0 { |
| 614 | return Err(PciError::CapabilityLoop); |
| 615 | } |
| 616 | seen[word] |= bit; |
| 617 | let header = read_u32(bytes, offset)?; |
| 618 | let id = (header & 0xffff) as u16; |
| 619 | let version = ((header >> 16) & 0x000f) as u8; |
| 620 | let next = ((header >> 20) & 0x0fff) as usize; |
| 621 | if count == MAX_EXTENDED_CAPABILITIES { |
| 622 | return Err(PciError::TooManyCapabilities); |
| 623 | } |
| 624 | list.entries[list.len] = ExtendedCapability { |
| 625 | id, |
| 626 | version, |
| 627 | offset: offset as u16, |
| 628 | }; |
| 629 | list.len += 1; |
| 630 | count += 1; |
| 631 | if id == 0xffff { |
| 632 | break; |
| 633 | } |
| 634 | offset = next; |
| 635 | } |
| 636 | Ok(list) |
| 637 | } |
| 638 | |
| 639 | /// A decoded type 1 PCI-to-PCI bridge header, enough to follow a firmware bus |
| 640 | /// window from a root bridge to a downstream device. |
| 641 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 642 | pub struct BridgeHeader { |
| 643 | pub vendor_id: u16, |
| 644 | pub device_id: u16, |
| 645 | pub class_code: u8, |
| 646 | pub subclass: u8, |
| 647 | pub secondary_bus: u8, |
| 648 | pub subordinate_bus: u8, |
| 649 | } |
| 650 | |
| 651 | impl BridgeHeader { |
| 652 | pub fn parse(bytes: &[u8]) -> Result<Self, PciError> { |
| 653 | if bytes.len() < CONFIG_HEADER_SIZE { |
| 654 | return Err(PciError::Truncated); |
| 655 | } |
| 656 | let header_type = read_u8(bytes, 0x0e)?; |
| 657 | if header_type & 0x7f != 0x01 { |
| 658 | return Err(PciError::InvalidHeaderType); |
| 659 | } |
| 660 | Ok(Self { |
| 661 | vendor_id: read_u16(bytes, 0x00)?, |
| 662 | device_id: read_u16(bytes, 0x02)?, |
| 663 | class_code: read_u8(bytes, 0x0b)?, |
| 664 | subclass: read_u8(bytes, 0x0a)?, |
| 665 | secondary_bus: read_u8(bytes, 0x19)?, |
| 666 | subordinate_bus: read_u8(bytes, 0x1a)?, |
| 667 | }) |
| 668 | } |
| 669 | |
| 670 | /// A usable bus window is one where the secondary bus is not zero and the |
| 671 | /// subordinate bus is at or above it. |
| 672 | pub fn has_bus_window(&self) -> bool { |
| 673 | self.secondary_bus != 0 && self.subordinate_bus >= self.secondary_bus |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | #[cfg(test)] |
| 678 | mod tests { |
| 679 | use super::*; |
| 680 | |
| 681 | fn base_header() -> [u8; CONFIG_SPACE_SIZE] { |
| 682 | let mut bytes = [0u8; CONFIG_SPACE_SIZE]; |
| 683 | bytes[0x00..0x02].copy_from_slice(&0x10deu16.to_le_bytes()); |
| 684 | bytes[0x02..0x04].copy_from_slice(&0x2e12u16.to_le_bytes()); |
| 685 | bytes[0x04..0x06].copy_from_slice(&0x0007u16.to_le_bytes()); |
| 686 | bytes[0x06..0x08].copy_from_slice(&0x0010u16.to_le_bytes()); |
| 687 | bytes[0x08] = 0xa1; |
| 688 | bytes[0x0b] = 0x03; |
| 689 | bytes |
| 690 | } |
| 691 | |
| 692 | #[test] |
| 693 | fn decodes_standard_header_and_64_bit_bar() { |
| 694 | let mut bytes = base_header(); |
| 695 | bytes[0x10..0x14].copy_from_slice(&0x2400_000cu32.to_le_bytes()); |
| 696 | bytes[0x14..0x18].copy_from_slice(&0x0000_0001u32.to_le_bytes()); |
| 697 | bytes[0x2c..0x2e].copy_from_slice(&0x10deu16.to_le_bytes()); |
| 698 | let header = Header::parse(&bytes).unwrap(); |
| 699 | assert_eq!(header.vendor_id, 0x10de); |
| 700 | assert_eq!(header.device_id, 0x2e12); |
| 701 | assert_eq!(header.class_code, 0x03); |
| 702 | assert!(header.memory_enabled()); |
| 703 | match header.bars[0] { |
| 704 | Bar::Memory(bar) => { |
| 705 | assert_eq!(bar.base, 0x0000_0001_2400_0000); |
| 706 | assert!(bar.is_64_bit); |
| 707 | assert!(bar.prefetchable); |
| 708 | } |
| 709 | other => panic!("expected memory bar, got {other:?}"), |
| 710 | } |
| 711 | assert_eq!(header.bars[1], Bar::None); |
| 712 | } |
| 713 | |
| 714 | #[test] |
| 715 | fn rejects_reserved_bar_encodings() { |
| 716 | let mut bytes = base_header(); |
| 717 | bytes[0x10..0x14].copy_from_slice(&0x0000_0006u32.to_le_bytes()); |
| 718 | assert!(Header::parse(&bytes).is_err()); |
| 719 | let mut bytes = base_header(); |
| 720 | bytes[0x24..0x28].copy_from_slice(&0x0000_000au32.to_le_bytes()); |
| 721 | assert!(Header::parse(&bytes).is_err()); |
| 722 | } |
| 723 | |
| 724 | #[test] |
| 725 | fn rejects_truncated_header_and_bridge_type() { |
| 726 | let bytes = [0u8; 16]; |
| 727 | assert_eq!(Header::parse(&bytes), Err(PciError::Truncated)); |
| 728 | let mut bytes = base_header(); |
| 729 | bytes[0x0e] = 0x01; |
| 730 | assert_eq!(Header::parse(&bytes), Err(PciError::InvalidHeaderType)); |
| 731 | } |
| 732 | |
| 733 | #[test] |
| 734 | fn rejects_capability_loop_and_out_of_bounds() { |
| 735 | let mut bytes = base_header(); |
| 736 | bytes[0x34] = 0x40; |
| 737 | bytes[0x40] = CAP_ID_MSI; |
| 738 | bytes[0x41] = 0x40; // points at itself |
| 739 | assert_eq!(walk_capabilities(&bytes), Err(PciError::CapabilityLoop)); |
| 740 | |
| 741 | let mut bytes = base_header(); |
| 742 | bytes[0x34] = 0xff; |
| 743 | assert_eq!(walk_capabilities(&bytes), Err(PciError::OutOfBounds)); |
| 744 | |
| 745 | let mut bytes = base_header(); |
| 746 | bytes[0x34] = 0x42; // unaligned |
| 747 | assert_eq!(walk_capabilities(&bytes), Err(PciError::OutOfBounds)); |
| 748 | |
| 749 | let truncated = [0u8; CONFIG_HEADER_SIZE]; |
| 750 | assert_eq!(walk_capabilities(&truncated), Err(PciError::Truncated)); |
| 751 | } |
| 752 | |
| 753 | #[test] |
| 754 | fn capability_list_absence_is_empty_not_error() { |
| 755 | let mut bytes = base_header(); |
| 756 | bytes[0x06..0x08].copy_from_slice(&0u16.to_le_bytes()); |
| 757 | assert!(walk_capabilities(&bytes).unwrap().entries().is_empty()); |
| 758 | let bytes = [0u8; CONFIG_SPACE_SIZE]; |
| 759 | assert!(walk_capabilities(&bytes).unwrap().entries().is_empty()); |
| 760 | } |
| 761 | |
| 762 | #[test] |
| 763 | fn decodes_msi_msix_and_pcie() { |
| 764 | let mut bytes = base_header(); |
| 765 | bytes[0x34] = 0x40; |
| 766 | // MSI at 0x40: id 0x05, next 0x50, control 0x0388 (64-bit, maskable). |
| 767 | bytes[0x40] = CAP_ID_MSI; |
| 768 | bytes[0x41] = 0x50; |
| 769 | bytes[0x42..0x44].copy_from_slice(&0x0388u16.to_le_bytes()); |
| 770 | bytes[0x44..0x48].copy_from_slice(&0xfee0_0000u32.to_le_bytes()); |
| 771 | bytes[0x4c..0x4e].copy_from_slice(&0x0041u16.to_le_bytes()); |
| 772 | // PCIe at 0x50: id 0x10, next 0x80, cap 0x0002, link caps/status. |
| 773 | bytes[0x50] = CAP_ID_PCIE; |
| 774 | bytes[0x51] = 0x80; |
| 775 | bytes[0x52..0x54].copy_from_slice(&0x0002u16.to_le_bytes()); |
| 776 | bytes[0x54..0x58].copy_from_slice(&0x0000_0003u32.to_le_bytes()); |
| 777 | bytes[0x5c..0x60].copy_from_slice(&0x0045_7901u32.to_le_bytes()); |
| 778 | bytes[0x62..0x64].copy_from_slice(&0x8010u16.to_le_bytes()); |
| 779 | // MSI-X at 0x80: id 0x11, next 0, control 0x8008, table, pba. |
| 780 | bytes[0x80] = CAP_ID_MSIX; |
| 781 | bytes[0x81] = 0x00; |
| 782 | bytes[0x82..0x84].copy_from_slice(&0x8008u16.to_le_bytes()); |
| 783 | bytes[0x84..0x88].copy_from_slice(&0x00b9_0000u32.to_le_bytes()); |
| 784 | bytes[0x88..0x8c].copy_from_slice(&0x00ba_0000u32.to_le_bytes()); |
| 785 | |
| 786 | let list = walk_capabilities(&bytes).unwrap(); |
| 787 | assert_eq!(list.entries().len(), 3); |
| 788 | let msi = MsiCapability::decode(&bytes, list.find(CAP_ID_MSI).unwrap()).unwrap(); |
| 789 | assert!(msi.is_64_bit && msi.maskable && !msi.enabled); |
| 790 | assert_eq!(msi.capable_vectors, 16); |
| 791 | assert_eq!(msi.data, 0x0041); |
| 792 | let pcie = PcieCapability::decode(&bytes, list.find(CAP_ID_PCIE).unwrap()).unwrap(); |
| 793 | let link = pcie.link.unwrap(); |
| 794 | assert_eq!(link.max_speed, LinkSpeed::Gen1); |
| 795 | assert_eq!(link.max_width, 16); |
| 796 | assert_eq!(link.current_width, 1); |
| 797 | assert!(link.downgraded); |
| 798 | assert_eq!(pcie.max_payload_bytes, 1024); |
| 799 | let msix = MsixCapability::decode(&bytes, list.find(CAP_ID_MSIX).unwrap()).unwrap(); |
| 800 | assert!(msix.enabled && !msix.function_masked); |
| 801 | assert_eq!(msix.vectors, 9); |
| 802 | assert_eq!(msix.table_bir, 0); |
| 803 | assert_eq!(msix.table_offset, 0x00b9_0000); |
| 804 | assert_eq!(msix.pba_offset, 0x00ba_0000); |
| 805 | |
| 806 | assert_eq!( |
| 807 | MsiCapability::decode(&bytes, list.find(CAP_ID_MSIX).unwrap()), |
| 808 | Err(PciError::WrongCapability) |
| 809 | ); |
| 810 | } |
| 811 | |
| 812 | #[test] |
| 813 | fn decodes_bridge_header_and_window() { |
| 814 | let mut bytes = base_header(); |
| 815 | bytes[0x0e] = 0x01; |
| 816 | bytes[0x19] = 0x01; |
| 817 | bytes[0x1a] = 0x0f; |
| 818 | let bridge = BridgeHeader::parse(&bytes).unwrap(); |
| 819 | assert_eq!(bridge.secondary_bus, 1); |
| 820 | assert_eq!(bridge.subordinate_bus, 0x0f); |
| 821 | assert!(bridge.has_bus_window()); |
| 822 | bytes[0x19] = 0x00; |
| 823 | assert!(!BridgeHeader::parse(&bytes).unwrap().has_bus_window()); |
| 824 | assert_eq!( |
| 825 | BridgeHeader::parse(&base_header()), |
| 826 | Err(PciError::InvalidHeaderType) |
| 827 | ); |
| 828 | } |
| 829 | |
| 830 | #[test] |
| 831 | fn walks_extended_capabilities_with_loop_and_bounds_checks() { |
| 832 | let mut bytes = [0u8; CONFIG_EXTENDED_SIZE]; |
| 833 | // Secondary PCI Express (0x19) at 0x100, then AER (0x01) at 0x12c. |
| 834 | let first = 0x19u32 | (1 << 16) | (0x12cu32 << 20); |
| 835 | bytes[0x100..0x104].copy_from_slice(&first.to_le_bytes()); |
| 836 | let second = 0x01u32 | (2 << 16); |
| 837 | bytes[0x12c..0x130].copy_from_slice(&second.to_le_bytes()); |
| 838 | let list = walk_extended_capabilities(&bytes).unwrap(); |
| 839 | assert_eq!(list.entries().len(), 2); |
| 840 | assert_eq!(list.find(0x19).unwrap().version, 1); |
| 841 | assert_eq!(list.find(0x01).unwrap().version, 2); |
| 842 | |
| 843 | // A loop: first entry next points at itself. |
| 844 | let mut bytes = [0u8; CONFIG_EXTENDED_SIZE]; |
| 845 | let looped = 0x19u32 | (0x100u32 << 20); |
| 846 | bytes[0x100..0x104].copy_from_slice(&looped.to_le_bytes()); |
| 847 | assert_eq!( |
| 848 | walk_extended_capabilities(&bytes), |
| 849 | Err(PciError::CapabilityLoop) |
| 850 | ); |
| 851 | |
| 852 | // A next pointer past the 4096-byte space is rejected. |
| 853 | let mut bytes = [0u8; CONFIG_EXTENDED_SIZE]; |
| 854 | let out = 0x19u32 | (0xfffu32 << 20); |
| 855 | bytes[0x100..0x104].copy_from_slice(&out.to_le_bytes()); |
| 856 | assert_eq!( |
| 857 | walk_extended_capabilities(&bytes), |
| 858 | Err(PciError::OutOfBounds) |
| 859 | ); |
| 860 | |
| 861 | // A slice at or below 0x100 has no extended capabilities. |
| 862 | assert!(walk_extended_capabilities(&[0u8; CONFIG_SPACE_SIZE]) |
| 863 | .unwrap() |
| 864 | .entries() |
| 865 | .is_empty()); |
| 866 | } |
| 867 | |
| 868 | #[test] |
| 869 | fn decodes_bar_sizes_with_bounds() { |
| 870 | assert_eq!( |
| 871 | memory_bar_size(0xf000_0004, 0xffff_ffff, true), |
| 872 | Some(0x1000_0000) |
| 873 | ); |
| 874 | assert_eq!(memory_bar_size(0xf000_0004, 0, false), Some(0x1000_0000)); |
| 875 | assert_eq!( |
| 876 | memory_bar_size(0x0000_0004, 0xffff_ffff, true), |
| 877 | Some(0x1_0000_0000) |
| 878 | ); |
| 879 | assert_eq!( |
| 880 | memory_bar_size(0xfff0_0004, 0xffff_ffff, true), |
| 881 | Some(0x10_0000) |
| 882 | ); |
| 883 | assert_eq!(memory_bar_size(0x2400_000c, 0, false), None); |
| 884 | assert_eq!(memory_bar_size(0x0000_0000, 0, false), None); |
| 885 | assert_eq!(memory_bar_size(0xffff_f004, 0, false), Some(0x1000)); |
| 886 | assert_eq!(memory_bar_size(0xf000_1004, 0xffff_ffff, true), None); |
| 887 | assert_eq!(io_bar_size(0xffff_f001), Some(0x1000)); |
| 888 | assert_eq!(io_bar_size(0x0000_0001), None); |
| 889 | } |
| 890 | } |