interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / pci.rs

693 lines · 25345 bytes Raw Blame History
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//! PCI configuration space enumeration over an ECAM window.
17//!
18//! Finds functions by vendor and device id, reports each function's
19//! bus/device/function, requester id and header type, decodes memory BARs and
20//! reads or changes the Command register. Config access goes through the
21//! [`ConfigSpace`] trait so the walk is host-tested against a fake config
22//! space; [`EcamConfig`] is the real MMIO adapter over an
23//! [`EcamWindow`](crate::acpi::EcamWindow).
24//!
25//! Nothing here enables a device. Turning on memory decode or bus mastering is
26//! a decision for the device authority code, which calls [`update_command`].
27
28use crate::acpi::EcamWindow;
29
30/// Config offset of the vendor id (low 16 bits) and device id (high 16 bits).
31pub const REG_ID: u16 = 0x00;
32/// Config offset of the Command (low 16 bits) and Status (high 16 bits) registers.
33pub const REG_COMMAND: u16 = 0x04;
34/// Config offset of the revision id and class code dword.
35pub const REG_CLASS_REVISION: u16 = 0x08;
36/// Config offset of the dword holding the header type (bits 16..24).
37pub const REG_HEADER: u16 = 0x0c;
38/// Config offset of BAR0. BAR n sits at `REG_BAR0 + 4 * n`.
39pub const REG_BAR0: u16 = 0x10;
40
41/// Command register bit: respond to I/O space accesses.
42pub const COMMAND_IO_SPACE: u16 = 1 << 0;
43/// Command register bit: respond to memory space accesses (MMIO BARs).
44pub const COMMAND_MEMORY_SPACE: u16 = 1 << 1;
45/// Command register bit: allow the function to issue DMA (bus master).
46pub const COMMAND_BUS_MASTER: u16 = 1 << 2;
47
48/// Vendor id read back from an absent function.
49pub const VENDOR_NONE: u16 = 0xffff;
50/// Header type bit that marks function 0 as one of several functions.
51const HEADER_MULTI_FUNCTION: u8 = 0x80;
52/// Number of BARs in a type 0 (endpoint) header.
53pub const TYPE0_BAR_COUNT: u8 = 6;
54/// Number of BARs in a type 1 (bridge) header.
55pub const TYPE1_BAR_COUNT: u8 = 2;
56
57/// 32-bit PCI configuration space access, addressed by absolute bus number.
58///
59/// Only aligned dword accesses are used. Reads of an absent function return
60/// all ones, as ECAM does.
61pub trait ConfigSpace {
62 fn read32(&mut self, bdf: Bdf, offset: u16) -> u32;
63 fn write32(&mut self, bdf: Bdf, offset: u16, value: u32);
64}
65
66/// A bus/device/function address.
67#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
68pub struct Bdf {
69 pub bus: u8,
70 pub device: u8,
71 pub function: u8,
72}
73
74impl Bdf {
75 /// `None` when `device > 31` or `function > 7`.
76 pub const fn new(bus: u8, device: u8, function: u8) -> Option<Self> {
77 if device > 31 || function > 7 {
78 return None;
79 }
80 Some(Self {
81 bus,
82 device,
83 function,
84 })
85 }
86
87 /// PCI requester id: `bus << 8 | device << 3 | function`. This is the
88 /// input id that IORT maps to an SMMU stream id
89 /// (see [`IortSmmu::stream_id_for`](crate::acpi::IortSmmu::stream_id_for)).
90 pub const fn requester_id(self) -> u32 {
91 (self.bus as u32) << 8 | (self.device as u32) << 3 | self.function as u32
92 }
93}
94
95/// One present PCI function found by the walk.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub struct PciFunction {
98 pub bdf: Bdf,
99 pub vendor_id: u16,
100 pub device_id: u16,
101 /// Header layout (0 endpoint, 1 PCI bridge, 2 CardBus) without the
102 /// multi-function bit.
103 pub header_type: u8,
104 /// Set on function 0 of a multi-function device.
105 pub multi_function: bool,
106 /// Class code in bits 8..32, revision id in bits 0..8.
107 pub class_revision: u32,
108}
109
110impl PciFunction {
111 pub const fn requester_id(&self) -> u32 {
112 self.bdf.requester_id()
113 }
114
115 /// BARs this header layout has: 6 for type 0, 2 for type 1, none otherwise.
116 pub const fn bar_count(&self) -> u8 {
117 match self.header_type {
118 0 => TYPE0_BAR_COUNT,
119 1 => TYPE1_BAR_COUNT,
120 _ => 0,
121 }
122 }
123}
124
125/// Reads the identity of `bdf`, or `None` when no function answers there.
126pub fn read_function<C: ConfigSpace>(config: &mut C, bdf: Bdf) -> Option<PciFunction> {
127 let id = config.read32(bdf, REG_ID);
128 let vendor_id = id as u16;
129 // All ones is ECAM's answer for an absent function; vendor 0 is never valid.
130 if vendor_id == VENDOR_NONE || vendor_id == 0 {
131 return None;
132 }
133 let header = (config.read32(bdf, REG_HEADER) >> 16) as u8;
134 Some(PciFunction {
135 bdf,
136 vendor_id,
137 device_id: (id >> 16) as u16,
138 header_type: header & !HEADER_MULTI_FUNCTION,
139 multi_function: header & HEADER_MULTI_FUNCTION != 0,
140 class_revision: config.read32(bdf, REG_CLASS_REVISION),
141 })
142}
143
144/// Walks every present function on buses `start_bus..=end_bus` in bus,
145/// device, function order. Functions 1 to 7 are probed only when function 0
146/// exists and sets the multi-function bit. Allocates nothing.
147pub struct Functions<'a, C: ConfigSpace> {
148 config: &'a mut C,
149 end_bus: u8,
150 /// Next address to probe; `None` once the walk is finished.
151 next: Option<Bdf>,
152 /// Whether the current device's function 0 set the multi-function bit.
153 multi_function: bool,
154}
155
156impl<'a, C: ConfigSpace> Functions<'a, C> {
157 pub fn new(config: &'a mut C, start_bus: u8, end_bus: u8) -> Self {
158 let next = (start_bus <= end_bus).then_some(Bdf {
159 bus: start_bus,
160 device: 0,
161 function: 0,
162 });
163 Self {
164 config,
165 end_bus,
166 next,
167 multi_function: false,
168 }
169 }
170
171 /// Advance to the next device (function 0), or finish after the last bus.
172 fn next_device(&mut self, at: Bdf) {
173 self.next = if at.device < 31 {
174 Some(Bdf {
175 bus: at.bus,
176 device: at.device + 1,
177 function: 0,
178 })
179 } else if at.bus < self.end_bus {
180 Some(Bdf {
181 bus: at.bus + 1,
182 device: 0,
183 function: 0,
184 })
185 } else {
186 None
187 };
188 }
189}
190
191impl<C: ConfigSpace> Iterator for Functions<'_, C> {
192 type Item = PciFunction;
193
194 fn next(&mut self) -> Option<PciFunction> {
195 while let Some(at) = self.next {
196 let found = read_function(self.config, at);
197 if at.function == 0 {
198 self.multi_function = found.is_some_and(|f| f.multi_function);
199 }
200 if at.function < 7 && self.multi_function {
201 self.next = Some(Bdf {
202 function: at.function + 1,
203 ..at
204 });
205 } else {
206 self.next_device(at);
207 }
208 if found.is_some() {
209 return found;
210 }
211 }
212 None
213 }
214}
215
216/// Walks every present function on the buses of an ECAM window.
217pub fn functions_in<'a, C: ConfigSpace>(
218 config: &'a mut C,
219 window: &EcamWindow,
220) -> Functions<'a, C> {
221 Functions::new(config, window.start_bus, window.end_bus)
222}
223
224/// First function on buses `start_bus..=end_bus` with this vendor and device id.
225pub fn find_device<C: ConfigSpace>(
226 config: &mut C,
227 start_bus: u8,
228 end_bus: u8,
229 vendor_id: u16,
230 device_id: u16,
231) -> Option<PciFunction> {
232 Functions::new(config, start_bus, end_bus)
233 .find(|f| f.vendor_id == vendor_id && f.device_id == device_id)
234}
235
236/// A decoded Base Address Register.
237#[derive(Clone, Copy, Debug, PartialEq, Eq)]
238pub enum Bar {
239 /// 32-bit memory BAR.
240 Memory32 { base: u32, prefetchable: bool },
241 /// 64-bit memory BAR; it also uses the next BAR slot for the high half.
242 Memory64 { base: u64, prefetchable: bool },
243 /// I/O space BAR.
244 Io { base: u32 },
245}
246
247impl Bar {
248 /// Base address as a u64, whatever the BAR kind.
249 pub const fn base(&self) -> u64 {
250 match *self {
251 Bar::Memory32 { base, .. } => base as u64,
252 Bar::Memory64 { base, .. } => base,
253 Bar::Io { base } => base as u64,
254 }
255 }
256
257 /// Whether this BAR uses two slots.
258 pub const fn is_64bit(&self) -> bool {
259 matches!(self, Bar::Memory64 { .. })
260 }
261}
262
263/// Why a BAR could not be decoded.
264#[derive(Clone, Copy, Debug, PartialEq, Eq)]
265pub enum BarError {
266 /// The index is past the last BAR of this header type.
267 NoSuchBar,
268 /// A 64-bit BAR in the last slot has no slot for its high half.
269 MissingHighHalf,
270 /// The memory type field holds the reserved value 0b11 (or the legacy
271 /// below-1-MiB type 0b01, which PCI Express does not allow).
272 ReservedType,
273 /// The function did not answer (all ones).
274 Absent,
275}
276
277/// Memory BAR type field (bits 1..3).
278const BAR_IO: u32 = 1 << 0;
279const BAR_TYPE_MASK: u32 = 0b11 << 1;
280const BAR_TYPE_32: u32 = 0b00 << 1;
281const BAR_TYPE_64: u32 = 0b10 << 1;
282const BAR_PREFETCHABLE: u32 = 1 << 3;
283const BAR_MEMORY_BASE_MASK: u32 = !0xf;
284const BAR_IO_BASE_MASK: u32 = !0x3;
285
286/// Decodes a BAR from its low dword and, for a 64-bit memory BAR, the next
287/// dword. `high` is ignored for other kinds. Pure: no config access.
288pub fn decode_bar(low: u32, high: Option<u32>) -> Result<Bar, BarError> {
289 if low & BAR_IO != 0 {
290 return Ok(Bar::Io {
291 base: low & BAR_IO_BASE_MASK,
292 });
293 }
294 let prefetchable = low & BAR_PREFETCHABLE != 0;
295 match low & BAR_TYPE_MASK {
296 BAR_TYPE_32 => Ok(Bar::Memory32 {
297 base: low & BAR_MEMORY_BASE_MASK,
298 prefetchable,
299 }),
300 BAR_TYPE_64 => {
301 let high = high.ok_or(BarError::MissingHighHalf)?;
302 Ok(Bar::Memory64 {
303 base: u64::from(high) << 32 | u64::from(low & BAR_MEMORY_BASE_MASK),
304 prefetchable,
305 })
306 }
307 _ => Err(BarError::ReservedType),
308 }
309}
310
311/// Reads and decodes BAR `index` of `function`. A 64-bit BAR at `index`
312/// also reads slot `index + 1`; the caller skips that slot.
313pub fn read_bar<C: ConfigSpace>(
314 config: &mut C,
315 function: &PciFunction,
316 index: u8,
317) -> Result<Bar, BarError> {
318 if index >= function.bar_count() {
319 return Err(BarError::NoSuchBar);
320 }
321 let bdf = function.bdf;
322 let low = config.read32(bdf, bar_offset(index));
323 if low == u32::MAX {
324 return Err(BarError::Absent);
325 }
326 let high =
327 (index + 1 < function.bar_count()).then(|| config.read32(bdf, bar_offset(index + 1)));
328 decode_bar(low, high)
329}
330
331/// Size in bytes of memory BAR `index`, found by the standard probe: write
332/// all ones, read back the writable bits, restore the original value.
333///
334/// Memory and I/O decode are switched off for the duration so the device
335/// never decodes the all-ones address, then the Command register is put back
336/// exactly as it was. Returns `Ok(None)` for an unimplemented (size 0) BAR
337/// and `Err(NoSuchBar)` for an I/O BAR, which this kernel does not use.
338pub fn probe_bar_size<C: ConfigSpace>(
339 config: &mut C,
340 function: &PciFunction,
341 index: u8,
342) -> Result<Option<u64>, BarError> {
343 let bar = read_bar(config, function, index)?;
344 if let Bar::Io { .. } = bar {
345 return Err(BarError::NoSuchBar);
346 }
347 let bdf = function.bdf;
348 let command = read_command(config, bdf);
349 write_command(
350 config,
351 bdf,
352 command & !(COMMAND_MEMORY_SPACE | COMMAND_IO_SPACE),
353 );
354 let low_at = bar_offset(index);
355 let low = config.read32(bdf, low_at);
356 config.write32(bdf, low_at, u32::MAX);
357 let low_mask = config.read32(bdf, low_at) & BAR_MEMORY_BASE_MASK;
358 config.write32(bdf, low_at, low);
359 let mut mask = u64::from(low_mask) | 0xffff_ffff_0000_0000;
360 if bar.is_64bit() {
361 let high_at = bar_offset(index + 1);
362 let high = config.read32(bdf, high_at);
363 config.write32(bdf, high_at, u32::MAX);
364 let high_mask = config.read32(bdf, high_at);
365 config.write32(bdf, high_at, high);
366 mask = u64::from(high_mask) << 32 | u64::from(low_mask);
367 }
368 write_command(config, bdf, command);
369 if mask == 0 || (!bar.is_64bit() && low_mask == 0) {
370 return Ok(None);
371 }
372 // The lowest writable address bit is the size.
373 Ok(Some(mask.isolate_lowest_one()))
374}
375
376const fn bar_offset(index: u8) -> u16 {
377 REG_BAR0 + 4 * index as u16
378}
379
380/// Current Command register value of `bdf`.
381pub fn read_command<C: ConfigSpace>(config: &mut C, bdf: Bdf) -> u16 {
382 config.read32(bdf, REG_COMMAND) as u16
383}
384
385/// Writes the Command register. The upper half of the dword is the Status
386/// register, whose error bits clear when written with 1, so it is written as
387/// zero to leave them alone.
388fn write_command<C: ConfigSpace>(config: &mut C, bdf: Bdf, command: u16) {
389 config.write32(bdf, REG_COMMAND, u32::from(command));
390}
391
392/// Sets the Command bits in `set`, then clears those in `clear`, and returns
393/// the value written. Use [`COMMAND_MEMORY_SPACE`] and [`COMMAND_BUS_MASTER`]
394/// to grant or revoke MMIO decode and DMA. Status error bits are preserved.
395pub fn update_command<C: ConfigSpace>(config: &mut C, bdf: Bdf, set: u16, clear: u16) -> u16 {
396 let command = (read_command(config, bdf) | set) & !clear;
397 write_command(config, bdf, command);
398 command
399}
400
401/// Config space through a mapped ECAM window, with volatile dword accesses.
402pub struct EcamConfig {
403 window: EcamWindow,
404}
405
406impl EcamConfig {
407 /// # Safety
408 /// The whole ECAM range of `window` (1 MiB per bus from `window.base`)
409 /// must be mapped as device memory at the same virtual address for as
410 /// long as this value is used, and nothing else may drive those config
411 /// registers concurrently.
412 pub const unsafe fn new(window: EcamWindow) -> Self {
413 Self { window }
414 }
415
416 pub const fn window(&self) -> &EcamWindow {
417 &self.window
418 }
419}
420
421impl ConfigSpace for EcamConfig {
422 fn read32(&mut self, bdf: Bdf, offset: u16) -> u32 {
423 match self
424 .window
425 .config_address(bdf.bus, bdf.device, bdf.function, offset & !0x3)
426 {
427 // SAFETY: the address lies inside the window that `new` requires
428 // to be mapped, and is dword aligned.
429 Some(addr) => unsafe { core::ptr::read_volatile(addr as usize as *const u32) },
430 None => u32::MAX,
431 }
432 }
433
434 fn write32(&mut self, bdf: Bdf, offset: u16, value: u32) {
435 if let Some(addr) =
436 self.window
437 .config_address(bdf.bus, bdf.device, bdf.function, offset & !0x3)
438 {
439 // SAFETY: as for `read32`.
440 unsafe { core::ptr::write_volatile(addr as usize as *mut u32, value) }
441 }
442 }
443}
444
445#[cfg(test)]
446pub(crate) mod fake {
447 use super::*;
448 use std::collections::BTreeMap;
449
450 /// A config space holding a few functions. Each function has 64 dwords
451 /// of plain storage and optional BAR size masks that emulate the
452 /// read-only low bits of a BAR during size probing.
453 #[derive(Default)]
454 pub struct FakeConfig {
455 pub functions: BTreeMap<Bdf, [u32; 64]>,
456 /// (bdf, bar index) -> writable address bits of that BAR dword.
457 pub bar_masks: BTreeMap<(Bdf, u8), u32>,
458 pub reads: usize,
459 }
460
461 impl FakeConfig {
462 pub fn add(&mut self, bdf: Bdf, vendor: u16, device: u16, header: u8) -> &mut [u32; 64] {
463 let space = self.functions.entry(bdf).or_insert([0; 64]);
464 space[0] = u32::from(device) << 16 | u32::from(vendor);
465 space[3] = u32::from(header) << 16;
466 space
467 }
468 }
469
470 impl ConfigSpace for FakeConfig {
471 fn read32(&mut self, bdf: Bdf, offset: u16) -> u32 {
472 self.reads += 1;
473 self.functions
474 .get(&bdf)
475 .map_or(u32::MAX, |s| s[usize::from(offset / 4)])
476 }
477
478 fn write32(&mut self, bdf: Bdf, offset: u16, value: u32) {
479 let Some(space) = self.functions.get_mut(&bdf) else {
480 return;
481 };
482 let slot = usize::from(offset / 4);
483 let bar = offset
484 .checked_sub(REG_BAR0)
485 .map(|o| (o / 4) as u8)
486 .filter(|i| *i < TYPE0_BAR_COUNT);
487 let value = match bar.and_then(|i| self.bar_masks.get(&(bdf, i))) {
488 // Read-only low bits (type, prefetch) keep their value.
489 Some(mask) => (value & mask) | (space[slot] & !mask),
490 None => value,
491 };
492 space[slot] = if offset == REG_COMMAND {
493 // The Status half is write-1-to-clear: a 1 clears, a 0 keeps.
494 let status = (space[slot] >> 16) & !(value >> 16);
495 status << 16 | (value & 0xffff)
496 } else {
497 value
498 };
499 }
500 }
501}
502
503#[cfg(test)]
504mod tests {
505 use super::fake::FakeConfig;
506 use super::*;
507
508 fn bdf(bus: u8, device: u8, function: u8) -> Bdf {
509 Bdf::new(bus, device, function).unwrap()
510 }
511
512 #[test]
513 fn requester_id_packs_bus_device_function() {
514 assert_eq!(bdf(0, 0, 0).requester_id(), 0);
515 assert_eq!(bdf(0, 2, 0).requester_id(), 0x10);
516 assert_eq!(bdf(1, 3, 5).requester_id(), 0x11d);
517 assert_eq!(bdf(0xff, 31, 7).requester_id(), 0xffff);
518 assert_eq!(Bdf::new(0, 32, 0), None);
519 assert_eq!(Bdf::new(0, 0, 8), None);
520 }
521
522 #[test]
523 fn finds_device_by_vendor_and_device_id() {
524 let mut config = FakeConfig::default();
525 config.add(bdf(0, 0, 0), 0x1b36, 0x0008, 0);
526 config.add(bdf(0, 1, 0), 0x1af4, 0x1000, 0);
527 let edu = config.add(bdf(0, 3, 0), 0x1234, 0x11e8, 0);
528 edu[2] = 0x00ff_0010;
529 let found = find_device(&mut config, 0, 0, 0x1234, 0x11e8).unwrap();
530 assert_eq!(found.bdf, bdf(0, 3, 0));
531 assert_eq!(found.requester_id(), 0x18);
532 assert_eq!(found.header_type, 0);
533 assert!(!found.multi_function);
534 assert_eq!(found.class_revision, 0x00ff_0010);
535 assert_eq!(find_device(&mut config, 0, 0, 0x1234, 0x0001), None);
536 }
537
538 #[test]
539 fn walk_skips_functions_1_to_7_unless_multi_function() {
540 let mut config = FakeConfig::default();
541 // Single-function device: a stray function 2 must not be reported.
542 config.add(bdf(0, 1, 0), 0x1111, 0x0001, 0);
543 config.add(bdf(0, 1, 2), 0x1111, 0x0002, 0);
544 // Multi-function device with a hole at function 1.
545 config.add(bdf(0, 4, 0), 0x2222, 0x0001, 0x80);
546 config.add(bdf(0, 4, 2), 0x2222, 0x0002, 0);
547 config.add(bdf(0, 4, 7), 0x2222, 0x0003, 0);
548 // Absent function 0: the device is skipped entirely.
549 config.add(bdf(0, 6, 1), 0x3333, 0x0001, 0);
550 // Bridge on a later bus, reached only when the range covers it.
551 config.add(bdf(2, 0, 0), 0x4444, 0x0001, 0x01);
552 let found: Vec<_> = Functions::new(&mut config, 0, 2)
553 .map(|f| (f.bdf, f.device_id, f.header_type, f.multi_function))
554 .collect();
555 assert_eq!(
556 found,
557 [
558 (bdf(0, 1, 0), 1, 0, false),
559 (bdf(0, 4, 0), 1, 0, true),
560 (bdf(0, 4, 2), 2, 0, false),
561 (bdf(0, 4, 7), 3, 0, false),
562 (bdf(2, 0, 0), 1, 1, false),
563 ]
564 );
565 assert_eq!(Functions::new(&mut config, 0, 1).count(), 4);
566 }
567
568 #[test]
569 fn walk_covers_last_bus_and_device_without_overflow() {
570 let mut config = FakeConfig::default();
571 config.add(bdf(255, 31, 0), 0x5555, 0x0001, 0x80);
572 config.add(bdf(255, 31, 7), 0x5555, 0x0002, 0);
573 let found: Vec<_> = Functions::new(&mut config, 255, 255)
574 .map(|f| f.bdf)
575 .collect();
576 assert_eq!(found, [bdf(255, 31, 0), bdf(255, 31, 7)]);
577 // An empty range reads nothing.
578 config.reads = 0;
579 assert_eq!(Functions::new(&mut config, 5, 4).count(), 0);
580 assert_eq!(config.reads, 0);
581 }
582
583 #[test]
584 fn functions_in_uses_the_window_bus_range() {
585 let mut config = FakeConfig::default();
586 config.add(bdf(0x10, 0, 0), 0x1234, 0x11e8, 0);
587 config.add(bdf(0x20, 0, 0), 0x1234, 0x11e8, 0);
588 let window = EcamWindow {
589 base: 0x40_1000_0000,
590 segment: 0,
591 start_bus: 0x10,
592 end_bus: 0x1f,
593 };
594 let found: Vec<_> = functions_in(&mut config, &window).map(|f| f.bdf).collect();
595 assert_eq!(found, [bdf(0x10, 0, 0)]);
596 }
597
598 #[test]
599 fn decodes_32_and_64_bit_memory_bars_and_io_bars() {
600 assert_eq!(
601 decode_bar(0xfe00_0000, None),
602 Ok(Bar::Memory32 {
603 base: 0xfe00_0000,
604 prefetchable: false
605 })
606 );
607 assert_eq!(
608 decode_bar(0x1000_000c, Some(0x80)),
609 Ok(Bar::Memory64 {
610 base: 0x80_1000_0000,
611 prefetchable: true
612 })
613 );
614 assert_eq!(decode_bar(0xc001, None), Ok(Bar::Io { base: 0xc000 }));
615 assert_eq!(decode_bar(0x4, None), Err(BarError::MissingHighHalf));
616 assert_eq!(decode_bar(0x6, Some(0)), Err(BarError::ReservedType));
617 assert_eq!(decode_bar(0x2, None), Err(BarError::ReservedType));
618 }
619
620 #[test]
621 fn read_bar_respects_header_type_and_slots() {
622 let mut config = FakeConfig::default();
623 let space = config.add(bdf(0, 2, 0), 0x1234, 0x11e8, 0);
624 space[4] = 0x1000_0000; // BAR0, 32-bit
625 space[5] = 0x2000_0004; // BAR1, 64-bit low
626 space[6] = 0x0000_0001; // BAR2, high half of BAR1
627 space[9] = 0x0000_0004; // BAR5, 64-bit with no slot for the high half
628 let bridge = config.add(bdf(0, 3, 0), 0x1b36, 0x0001, 1);
629 bridge[4] = 0x3000_0000;
630 let f = read_function(&mut config, bdf(0, 2, 0)).unwrap();
631 let b = read_function(&mut config, bdf(0, 3, 0)).unwrap();
632 assert_eq!(read_bar(&mut config, &f, 0).unwrap().base(), 0x1000_0000);
633 let bar1 = read_bar(&mut config, &f, 1).unwrap();
634 assert!(bar1.is_64bit());
635 assert_eq!(bar1.base(), 0x1_2000_0000);
636 assert_eq!(read_bar(&mut config, &f, 5), Err(BarError::MissingHighHalf));
637 assert_eq!(read_bar(&mut config, &f, 6), Err(BarError::NoSuchBar));
638 assert_eq!(read_bar(&mut config, &b, 0).unwrap().base(), 0x3000_0000);
639 assert_eq!(read_bar(&mut config, &b, 2), Err(BarError::NoSuchBar));
640 }
641
642 #[test]
643 fn probes_bar_sizes_and_restores_state() {
644 let mut config = FakeConfig::default();
645 let at = bdf(0, 2, 0);
646 let space = config.add(at, 0x1234, 0x11e8, 0);
647 space[1] = u32::from(COMMAND_MEMORY_SPACE | COMMAND_BUS_MASTER);
648 space[4] = 0x1000_0000; // 1 MiB 32-bit BAR
649 space[5] = 0x0000_000c; // 16 KiB 64-bit prefetchable BAR
650 space[6] = 0x0000_0080;
651 config.bar_masks.insert((at, 0), 0xfff0_0000);
652 config.bar_masks.insert((at, 1), 0xffff_c000);
653 config.bar_masks.insert((at, 2), 0xffff_ffff);
654 config.bar_masks.insert((at, 3), 0);
655 let f = read_function(&mut config, at).unwrap();
656 assert_eq!(probe_bar_size(&mut config, &f, 0), Ok(Some(1 << 20)));
657 assert_eq!(probe_bar_size(&mut config, &f, 1), Ok(Some(16 << 10)));
658 assert_eq!(probe_bar_size(&mut config, &f, 3), Ok(None));
659 let space = config.functions[&at];
660 assert_eq!(space[4], 0x1000_0000);
661 assert_eq!(space[5], 0x0000_000c);
662 assert_eq!(space[6], 0x0000_0080);
663 assert_eq!(
664 space[1] as u16,
665 COMMAND_MEMORY_SPACE | COMMAND_BUS_MASTER,
666 "command restored"
667 );
668 }
669
670 #[test]
671 fn update_command_sets_and_clears_bits_without_touching_status() {
672 let mut config = FakeConfig::default();
673 let at = bdf(0, 2, 0);
674 let space = config.add(at, 0x1234, 0x11e8, 0);
675 // Status: a latched error bit (Received Master Abort, bit 13) and
676 // capabilities list (bit 4). Command: INTx disable (bit 10).
677 space[1] = (1 << 13 | 1 << 4) << 16 | 1 << 10;
678 let on = update_command(
679 &mut config,
680 at,
681 COMMAND_MEMORY_SPACE | COMMAND_BUS_MASTER,
682 0,
683 );
684 assert_eq!(on, 1 << 10 | COMMAND_MEMORY_SPACE | COMMAND_BUS_MASTER);
685 assert_eq!(read_command(&mut config, at), on);
686 let off = update_command(&mut config, at, 0, COMMAND_BUS_MASTER);
687 assert_eq!(off, 1 << 10 | COMMAND_MEMORY_SPACE);
688 assert_eq!(read_command(&mut config, at), off);
689 // The fake clears Status bits written with 1, as hardware does, so
690 // they survive only if the upper half was written as zero.
691 assert_eq!(config.functions[&at][1] >> 16, (1 << 13 | 1 << 4));
692 }
693}