diff --git a/crates/stela-boot-core/src/lib.rs b/crates/stela-boot-core/src/lib.rs index 70cc6123d5..2beae0cfab 100644 --- a/crates/stela-boot-core/src/lib.rs +++ b/crates/stela-boot-core/src/lib.rs @@ -95,6 +95,7 @@ pub mod paging_controls; pub mod panic_region; pub mod parking; pub mod passthrough; +pub mod pci_map; pub mod pe; pub mod pm_timer; pub mod poll_timer; @@ -131,6 +132,7 @@ pub mod tsc; pub mod uart; pub mod usb_legacy; pub mod vfct; +pub mod video_bios; #[cfg(target_arch = "x86_64")] pub mod vtd; pub mod work_status; diff --git a/crates/stela-boot-core/src/pci_map.rs b/crates/stela-boot-core/src/pci_map.rs new file mode 100644 index 0000000000..9b0f28871b --- /dev/null +++ b/crates/stela-boot-core/src/pci_map.rs @@ -0,0 +1,144 @@ +//! What the firmware's PCI bus driver knew of each function before it +//! exited, as Linux's EFI stub hands some of it over: the memory each BAR +//! decodes, each bridge's buses and non-prefetchable window, and a copy of +//! a display function's option ROM, which the firmware read from the ROM +//! BAR and keeps (`EFI_PCI_IO_PROTOCOL.RomImage`; Linux's stub copies it +//! into `setup_data` as `SETUP_PCI`, and `pci_dev::rom` holds it). +//! +//! The boot reads it once before the firmware's exit and the engine places +//! an expansion ROM BAR the firmware left unassigned with it +//! ([`rom_room`]): the firmware sized every BAR, which the engine cannot +//! do again on functions other drivers own. +use crate::video_bios::{bridge_window, place}; +use alloc::vec::Vec; +use core::ops::Range; + +/// One function as the firmware left it. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct Function { + pub segment: u16, + pub bus: u8, + pub device: u8, + pub function: u8, + /// A bridge's secondary and subordinate buses and register 0x20. + pub bridge: Option<(u8, u8, u32)>, + /// The memory each BAR decodes. + pub spans: Vec>, + /// Where the copy of its option ROM lies in memory the boot keeps. + pub rom: Option>, +} + +/// The most functions the map holds. +pub const MOST_FUNCTIONS: usize = 1024; +const MOST_SPANS: usize = 16; + +fn put(out: &mut Vec, bytes: &[u8]) { + out.extend_from_slice(bytes); +} + +/// The map as bytes, which [`decode`] reads back. +pub fn encode(functions: &[Function]) -> Vec { + let mut out = Vec::new(); + put( + &mut out, + &(functions.len().min(MOST_FUNCTIONS) as u32).to_le_bytes(), + ); + for function in functions.iter().take(MOST_FUNCTIONS) { + put(&mut out, &function.segment.to_le_bytes()); + put( + &mut out, + &[function.bus, function.device, function.function], + ); + let (secondary, subordinate, window) = function.bridge.unwrap_or_default(); + put( + &mut out, + &[u8::from(function.bridge.is_some()), secondary, subordinate], + ); + put(&mut out, &window.to_le_bytes()); + let spans = function.spans.len().min(MOST_SPANS); + put(&mut out, &[spans as u8]); + for span in function.spans.iter().take(spans) { + put(&mut out, &span.start.to_le_bytes()); + put(&mut out, &span.end.to_le_bytes()); + } + let rom = function.rom.clone().unwrap_or_default(); + put(&mut out, &rom.start.to_le_bytes()); + put(&mut out, &rom.end.to_le_bytes()); + } + out +} + +/// The map [`encode`] wrote, or `None` for bytes it did not write. +pub fn decode(bytes: &[u8]) -> Option> { + let mut at = 0usize; + let mut take = |count: usize| -> Option<&[u8]> { + let taken = bytes.get(at..at.checked_add(count)?)?; + at += count; + Some(taken) + }; + let u64_of = |bytes: &[u8]| u64::from_le_bytes(bytes.try_into().unwrap_or([0; 8])); + let count = u32::from_le_bytes(take(4)?.try_into().ok()?) as usize; + if count > MOST_FUNCTIONS { + return None; + } + let mut functions = Vec::new(); + for _ in 0..count { + let segment = u16::from_le_bytes(take(2)?.try_into().ok()?); + let place = take(3)?; + let (bus, device, function) = (place[0], place[1], place[2]); + let bridge = take(3)?; + let (is_bridge, secondary, subordinate) = (bridge[0] != 0, bridge[1], bridge[2]); + let window = u32::from_le_bytes(take(4)?.try_into().ok()?); + let spans_count = usize::from(take(1)?[0]); + if spans_count > MOST_SPANS { + return None; + } + let mut spans = Vec::new(); + for _ in 0..spans_count { + let start = u64_of(take(8)?); + let end = u64_of(take(8)?); + spans.push(start..end); + } + let start = u64_of(take(8)?); + let end = u64_of(take(8)?); + functions.push(Function { + segment, + bus, + device, + function, + bridge: is_bridge.then_some((secondary, subordinate, window)), + spans, + rom: (end > start).then_some(start..end), + }); + } + Some(functions) +} + +/// Where to place an expansion ROM BAR of `bytes` for the function at +/// `segment`/`bus`/`device`/`function`: the lowest place aligned to its +/// size in the non-prefetchable window of the bridge whose secondary bus is +/// the function's, clear of every BAR of every function below that bridge +/// and of every window of the bridges below it. `None` where no bridge is +/// above the function, its window is closed or holds no room. +pub fn rom_room(map: &[Function], segment: u16, bus: u8, bytes: u64) -> Option { + let (secondary, subordinate, window) = map.iter().find_map(|function| { + function + .bridge + .filter(|&(secondary, _, _)| function.segment == segment && secondary == bus) + })?; + let window = bridge_window(window)?; + let below = |function: &&Function| { + function.segment == segment && (secondary..=subordinate).contains(&function.bus) + }; + let mut used: Vec> = Vec::new(); + for function in map.iter().filter(below) { + used.extend(function.spans.iter().cloned()); + if let Some(window) = function.bridge.and_then(|(_, _, word)| bridge_window(word)) { + used.push(window); + } + } + place(&window, &used, bytes) +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-boot-core/src/pci_map/tests.rs b/crates/stela-boot-core/src/pci_map/tests.rs new file mode 100644 index 0000000000..8b8deef0a3 --- /dev/null +++ b/crates/stela-boot-core/src/pci_map/tests.rs @@ -0,0 +1,49 @@ +use super::*; +use alloc::vec; + +/// A root port at 00:01.1 forwarding bus 3 and the window 0xfc00_0000 to +/// 0xfcff_ffff; a GPU at 03:00.0 with its registers at the window's +/// bottom and its option ROM copied at 0x1000_0000; its audio function. +fn map() -> Vec { + vec![ + Function { + device: 1, + function: 1, + bridge: Some((3, 3, 0xfcf0_fc00)), + ..Function::default() + }, + Function { + bus: 3, + spans: vec![0xe000_0000..0xf000_0000, 0xfc00_0000..0xfc04_0000], + rom: Some(0x1000_0000..0x1001_0000), + ..Function::default() + }, + Function { + bus: 3, + function: 1, + spans: core::iter::once(0xfc06_0000..0xfc06_4000).collect(), + ..Function::default() + }, + ] +} + +#[test] +fn the_map_reads_back_as_written() { + let map = map(); + assert_eq!(decode(&encode(&map)).as_ref(), Some(&map)); + assert_eq!(decode(&encode(&map)[..10]), None); + assert_eq!(decode(&[]), None); +} + +#[test] +fn an_unassigned_rom_bar_goes_in_its_bridges_window_clear_of_every_bar() { + let map = map(); + // Between the registers and the audio function, else above both. + assert_eq!(rom_room(&map, 0, 3, 0x2_0000), Some(0xfc04_0000)); + assert_eq!(rom_room(&map, 0, 3, 0x4_0000), Some(0xfc08_0000)); + // No bridge above bus 0, and none on another segment. + assert_eq!(rom_room(&map, 0, 0, 0x2_0000), None); + assert_eq!(rom_room(&map, 1, 3, 0x2_0000), None); + // A window too small. + assert_eq!(rom_room(&map, 0, 3, 0x200_0000), None); +} diff --git a/crates/stela-boot-core/src/video_bios.rs b/crates/stela-boot-core/src/video_bios.rs new file mode 100644 index 0000000000..790592b56b --- /dev/null +++ b/crates/stela-boot-core/src/video_bios.rs @@ -0,0 +1,87 @@ +//! What the boot checks of a video BIOS image it gives a GPU's driver as +//! the function's platform ROM, and where it places an expansion ROM BAR +//! firmware left unassigned. +//! +//! amdgpu takes an image only when it is an ATOM BIOS (`check_atom_bios`); +//! a PCI expansion ROM names the device it is for in its PCI data +//! structure (PCI Firmware 3.0, 5.1.2). The ROM BAR is placed as Linux's +//! PCI core places an unassigned resource: aligned to its size, in the +//! upstream bridge's non-prefetchable window, clear of every BAR and window +//! decoded below that bridge (`pci_assign_resource`, `pbus_size_mem`). +use core::ops::Range; + +/// Whether `image` is an ATOM BIOS as `check_atom_bios` judges one of +/// `image.len()` bytes: the ROM signature, a header pointer at 0x48 and +/// "ATOM" (or "MOTA") four bytes after it. +pub fn atom(image: &[u8]) -> bool { + if image.len() < 0x49 || image[0] != 0x55 || image[1] != 0xaa { + return false; + } + let header = usize::from(u16::from_le_bytes([image[0x48], image[0x49]])); + if header == 0 { + return false; + } + let at = header + 4; + image + .get(at..at + 4) + .is_some_and(|word| word == b"ATOM" || word == b"MOTA") +} + +/// The vendor and device IDs the first image of expansion ROM `image` +/// names in its PCI data structure, if it has one. +pub fn names(image: &[u8]) -> Option<(u16, u16)> { + if image.get(..2)? != [0x55, 0xaa] { + return None; + } + let at = usize::from(u16::from_le_bytes([*image.get(0x18)?, *image.get(0x19)?])); + let data = image.get(at..at + 8)?; + if &data[..4] != b"PCIR" { + return None; + } + Some(( + u16::from_le_bytes([data[4], data[5]]), + u16::from_le_bytes([data[6], data[7]]), + )) +} + +/// The bytes an expansion ROM BAR decodes, from what it reads back after +/// all ones were written to its address bits (`pci_size`): `None` for a +/// function without one. +pub fn rom_size(read_back: u32) -> Option { + let mask = read_back & 0xffff_f800; + (mask != 0).then(|| (!mask).wrapping_add(1)) +} + +/// A bridge's non-prefetchable memory window, from its register 0x20 +/// (memory base and limit); `None` where it forwards none. +pub fn bridge_window(word: u32) -> Option> { + let base = u64::from(word & 0xfff0) << 16; + let limit = (u64::from(word >> 16 & 0xfff0) << 16) | 0xf_ffff; + (base <= limit).then(|| base..limit + 1) +} + +/// The lowest place for `bytes` (a power of two) aligned to its size in +/// `window` that overlaps none of `used`, as Linux places a resource it +/// assigns in its bridge's window. +pub fn place(window: &Range, used: &[Range], bytes: u64) -> Option { + if bytes == 0 || !bytes.is_power_of_two() { + return None; + } + let mut start = window.start.next_multiple_of(bytes); + while start.checked_add(bytes)? <= window.end { + let end = start + bytes; + match used + .iter() + .filter(|range| range.start < end && start < range.end) + .map(|range| range.end) + .max() + { + None => return Some(start), + Some(past) => start = past.next_multiple_of(bytes), + } + } + None +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-boot-core/src/video_bios/tests.rs b/crates/stela-boot-core/src/video_bios/tests.rs new file mode 100644 index 0000000000..59a22e7022 --- /dev/null +++ b/crates/stela-boot-core/src/video_bios/tests.rs @@ -0,0 +1,52 @@ +use super::*; +use alloc::{vec, vec::Vec}; + +/// A 64 KiB expansion ROM for `vendor:device` with an ATOM header. +pub(crate) fn rom(vendor: u16, device: u16) -> Vec { + let mut image = vec![0u8; 0x10000]; + image[0] = 0x55; + image[1] = 0xaa; + image[2] = 0x80; + image[0x18..0x1a].copy_from_slice(&0x200u16.to_le_bytes()); + image[0x200..0x204].copy_from_slice(b"PCIR"); + image[0x204..0x206].copy_from_slice(&vendor.to_le_bytes()); + image[0x206..0x208].copy_from_slice(&device.to_le_bytes()); + image[0x48..0x4a].copy_from_slice(&0x300u16.to_le_bytes()); + image[0x304..0x308].copy_from_slice(b"ATOM"); + image +} + +#[test] +fn an_atom_bios_is_known_as_amdgpu_knows_it() { + let image = rom(0x1002, 0x67df); + assert!(atom(&image)); + assert_eq!(names(&image), Some((0x1002, 0x67df))); + let mut legacy = image.clone(); + legacy[0x304..0x308].copy_from_slice(b"MOTA"); + assert!(atom(&legacy)); + let mut other = image.clone(); + other[0x304] = b'X'; + assert!(!atom(&other)); + assert!(!atom(&image[..0x40])); + let mut unsigned = image; + unsigned[1] = 0; + assert!(!atom(&unsigned)); + assert_eq!(names(&unsigned), None); +} + +#[test] +fn a_rom_bar_is_sized_and_placed_as_linux_places_it() { + assert_eq!(rom_size(0xfffe_0000), Some(0x2_0000)); + assert_eq!(rom_size(0xfffe_0001), Some(0x2_0000)); + assert_eq!(rom_size(0), None); + assert_eq!(bridge_window(0xfcf0_fc00), Some(0xfc00_0000..0xfd00_0000)); + assert_eq!(bridge_window(0x0000_fff0), None); + let window = 0xfc00_0000..0xfd00_0000; + // Registers at the bottom, the audio function above them. + let used = [0xfc00_0000..0xfc08_0000, 0xfc0a_0000..0xfc0a_4000]; + assert_eq!(place(&window, &used, 0x2_0000), Some(0xfc08_0000)); + assert_eq!(place(&window, &used, 0x4_0000), Some(0xfc0c_0000)); + // No room. + assert_eq!(place(&(0xfc00_0000..0xfc08_0000), &used, 0x2_0000), None); + assert_eq!(place(&window, &used, 0x3000), None); +} diff --git a/crates/stela-boot/src/engine/gpu.rs b/crates/stela-boot/src/engine/gpu.rs index 2728d9e0f9..32207dc908 100644 --- a/crates/stela-boot/src/engine/gpu.rs +++ b/crates/stela-boot/src/engine/gpu.rs @@ -185,14 +185,174 @@ pub(super) unsafe fn keep_video_bios_table(rsdp: u64, root: u64) { } } -/// The function's image in the kept VFCT table, as Linux takes it -/// (`amdgpu_acpi_vfct_bios`), or nothing; a refused image is said once. -fn platform_rom(adapter: &gpu::Adapter) -> &'static [u8] { - use stela_boot_core::vfct; +/// The video BIOS a hybrid laptop's `ATRM` handed out during the PCI +/// census (`stela_drivers::probe::gpu_methods::atrm`). +static ATRM: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + +/// Keeps what `ATRM` handed out for the claims, with a line. +pub(super) fn keep_atrm(atrm: Option) { + let Some(atrm) = atrm else { return }; + output::arguments(format_args!( + "GPU: ATRM at {} on {} handed out {} bytes of video BIOS\n", + atrm.path, + atrm.owner, + atrm.image.len() + )); + let previous = ATRM.swap(Box::into_raw(Box::new(atrm)), Ordering::AcqRel); + if !previous.is_null() { + // SAFETY: only this function stores, from `Box::into_raw`, and the + // claims read it only after the census that calls this once. + drop(unsafe { Box::from_raw(previous) }); + } +} + +/// The firmware's PCI map and the option ROMs it kept, for the claims. +struct FirmwareMap { + functions: Vec, + /// Each display function's option ROM, by its place in `functions`. + roms: Vec<(usize, Vec)>, +} + +static FIRMWARE_MAP: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + +/// Keeps the firmware's PCI map (`pci_io::firmware_map`) and copies of the +/// option ROMs it names. +/// +/// # Safety +/// `root` is the loader root that maps `region` and the copies it names, +/// pages the boot kept. Called once, before any claim. +pub(super) unsafe fn keep_pci_map(region: crate::handoff::Region, root: u64) { + if region.bytes == 0 { + return; + } + let map = { + // SAFETY: the caller's; the loader root maps the kept pages. + let _root = unsafe { super::storage::RestoreRoot::enter(root) }; + let read = |range: Range| -> Vec { + // SAFETY: as above: kept pages the boot wrote before its exit. + unsafe { + core::slice::from_raw_parts( + range.start as *const u8, + (range.end - range.start) as usize, + ) + } + .to_vec() + }; + let Some(functions) = stela_boot_core::pci_map::decode(&read( + region.physical..region.physical + region.bytes, + )) else { + output::arguments(format_args!("GPU: the firmware's PCI map is unreadable\n")); + return; + }; + let roms = functions + .iter() + .enumerate() + .filter_map(|(index, function)| Some((index, read(function.rom.clone()?)))) + .collect(); + FirmwareMap { functions, roms } + }; + FIRMWARE_MAP.store(Box::into_raw(Box::new(map)), Ordering::Release); +} + +fn firmware_map() -> Option<&'static FirmwareMap> { // SAFETY: stored once before any claim and never freed. - let Some(table) = (unsafe { VIDEO_BIOS_TABLE.load(Ordering::Acquire).as_ref() }) else { + unsafe { FIRMWARE_MAP.load(Ordering::Acquire).as_ref() } +} + +/// The function's platform ROM, a video BIOS image firmware publishes +/// apart from the function, which Linux keeps as `pci_dev::rom` and amdgpu +/// reads when the places it searches first hold none +/// (`amdgpu_read_platform_bios`). Linux's own places come in amdgpu's order, +/// those its ACPI support reads first, as Stela's Linux profile has none: +/// `ATRM` for a discrete GPU (`amdgpu_atrm_get_bios`), then the `VFCT` +/// image (`amdgpu_acpi_vfct_bios`), then the option ROM copy the firmware +/// kept (x86 Linux's `pci_dev::rom` from its EFI stub). One line says which. +fn platform_rom(adapter: &gpu::Adapter, integrated: bool) -> &'static [u8] { + let address = adapter.address; + if let Some(image) = atrm_image(adapter, integrated) { + return image; + } + if let Some(image) = vfct_image(adapter) { + return image; + } + let Some(map) = firmware_map() else { return &[]; }; + let Some((_, image)) = map.roms.iter().find(|(index, _)| { + let function = &map.functions[*index]; + ( + function.segment, + function.bus, + function.device, + function.function, + ) == ( + address.segment, + address.bus, + address.device, + address.function, + ) + }) else { + return &[]; + }; + output::arguments(format_args!( + "GPU {address}: video BIOS of {} bytes from the option ROM the firmware read, given to \ + Linux as its platform ROM\n", + image.len() + )); + image +} + +/// `ATRM`'s image for an AMD GPU amdgpu takes as discrete +/// (`amdgpu_get_bios_dgpu` asks `ATRM` first; its APU path never does): +/// one its table names and does not flag as an APU, or one it identifies by +/// discovery whose image names it, as only the probe tells those apart. +/// Only an ATOM BIOS, as `check_atom_bios` takes one. +fn atrm_image(adapter: &gpu::Adapter, integrated: bool) -> Option<&'static [u8]> { + use stela_boot_core::video_bios; + use stela_loader::host_firmware::recipes::AmdGpu; + if adapter.vendor != gpu::Vendor::Amd || integrated { + return None; + } + // Whether amdgpu takes it as discrete: yes for one its table names + // without the APU flag; unknown before the probe for a discovered one. + let discrete = match AmdGpu::of(adapter.device) { + AmdGpu::Named(..) => Some(true), + AmdGpu::Discovered => None, + AmdGpu::LeftToRadeon => return None, + }; + // SAFETY: stored once by the census before any claim and never freed. + let atrm = unsafe { ATRM.load(Ordering::Acquire).as_ref() }?; + let address = adapter.address; + let image = atrm.image.as_slice(); + let names_it = video_bios::names(image) == Some((0x1002, adapter.device)); + if !video_bios::atom(image) || (discrete.is_none() && !names_it) { + output::arguments(format_args!( + "GPU {address}: ATRM's {} bytes at {} are not taken: {}\n", + image.len(), + atrm.path, + if video_bios::atom(image) { + "the image names another device and amdgpu decides only at its probe whether this one is discrete" + } else { + "they are no ATOM BIOS" + } + )); + return None; + } + output::arguments(format_args!( + "GPU {address}: video BIOS of {} bytes from ATRM at {}, given to Linux as its platform \ + ROM\n", + image.len(), + atrm.path + )); + Some(image) +} + +/// The function's image in the kept VFCT table, as Linux takes it +/// (`amdgpu_acpi_vfct_bios`); a refused image is said once. +fn vfct_image(adapter: &gpu::Adapter) -> Option<&'static [u8]> { + use stela_boot_core::vfct; + // SAFETY: stored once before any claim and never freed. + let table = unsafe { VIDEO_BIOS_TABLE.load(Ordering::Acquire).as_ref() }?; let address = adapter.address; let function = vfct::Function { bus: address.bus, @@ -212,18 +372,109 @@ fn platform_rom(adapter: &gpu::Adapter) -> &'static [u8] { "GPU {address}: video BIOS of {} bytes from the ACPI VFCT table, given to Linux as its platform ROM\n", image.bytes.len() )); - &table[image.bytes] + Some(&table[image.bytes]) } - Err(vfct::Error::NoImage) => &[], + Err(vfct::Error::NoImage) => None, Err(error) => { output::arguments(format_args!( "GPU {address}: the ACPI VFCT table's image is refused ({error:?}); the driver looks for its video BIOS elsewhere\n" )); - &[] + None } } } +/// The expansion ROM BAR's register, its enable bit and its address bits. +const ROM_BAR: u16 = 0x30; +const ROM_ENABLE: u32 = 1; +const ROM_ADDRESS: u32 = 0xffff_f800; + +/// The function's expansion ROM BAR as Linux's PCI core leaves it for +/// `pci_map_rom`, decoding off: sized, and kept where firmware assigned it +/// inside the window above it, else placed in that window clear of every +/// BAR the firmware sized below it (`stela_boot_core::pci_map::rom_room`), +/// as Linux assigns an unassigned resource. The region for Linux's +/// `PCI_ROM_RESOURCE` and its reservation, or `None` with a line where the +/// function has no ROM BAR or no room is found; the BAR is then put back +/// as firmware left it. +fn expansion_rom( + services: &dyn NativeServices, + function: &mut Function, +) -> Option<(Region, owned::Resource)> { + use stela_boot_core::{pci_map::rom_room, video_bios::rom_size}; + /// Linux's `IORESOURCE_READONLY` and `IORESOURCE_SIZEALIGN`. + const RESOURCE_READONLY: u64 = 0x4000; + const RESOURCE_SIZEALIGN: u64 = 0x4_0000; + let address = function.address; + let config = function.config(); + let original = config.read32(ROM_BAR).ok()?; + // Sized with its decoding off, as `pci_read_bases` sizes it. + let read = config + .write32(ROM_BAR, ROM_ADDRESS) + .and_then(|()| config.read32(ROM_BAR)); + let put_back = |config: &mut OwnedConfig| config.write32(ROM_BAR, original & !ROM_ENABLE); + let Some(size) = read.ok().and_then(rom_size).map(u64::from) else { + let _ = put_back(config); + return None; + }; + // A ROM smaller than a page takes a page, aligned to it. + let span = size.max(PAGE); + let claim = |start: u64| { + services.bar_resource( + address, + Bar::Memory { + address: start, + size: span, + prefetchable: false, + wide: false, + }, + ) + }; + let assigned = u64::from(original & ROM_ADDRESS); + let region = |start: u64| Region { + start, + size, + flags: RESOURCE_MEMORY | RESOURCE_PREFETCHABLE | RESOURCE_READONLY | RESOURCE_SIZEALIGN, + }; + // Firmware's place, when it is one: aligned and not the all-ones the + // firmware's own sizing left. + if assigned != 0 + && assigned.is_multiple_of(span) + && assigned != u64::from(ROM_ADDRESS) & !(size - 1) + && let Ok(resource) = claim(assigned) + { + let _ = put_back(config); + output::arguments(format_args!( + "GPU {address}: its expansion ROM of {size} bytes stays where firmware placed it, at \ + {assigned:#x}\n" + )); + return Some((region(assigned), resource)); + } + let placed = firmware_map() + .and_then(|map| rom_room(&map.functions, address.segment, address.bus, span)) + .filter(|&start| start + span <= 1 << 32); + let found = placed.and_then(|start| { + let resource = claim(start).ok()?; + config.write32(ROM_BAR, start as u32).ok()?; + Some((region(start), resource)) + }); + match &found { + Some((region, _)) => output::arguments(format_args!( + "GPU {address}: its expansion ROM of {size} bytes, unassigned by firmware, placed at \ + {:#x} in the window above it, decoding off, as Linux assigns it\n", + region.start + )), + None => { + let _ = put_back(config); + output::arguments(format_args!( + "GPU {address}: its expansion ROM of {size} bytes has no place in the window above \ + it; its driver reads its video BIOS from the other places it searches\n" + )); + } + } + found +} + /// Who runs PE work on the boot CPU, once the PEs run. static HUB: AtomicPtr = AtomicPtr::new(ptr::null_mut()); static BOOT_PE: AtomicUsize = AtomicUsize::new(0); @@ -1182,7 +1433,7 @@ fn claim( // A mapping past the driver's mask is refused // (`function::Mappings`), not truncated. dma_limit: stack.kernel.dma_limit(adapter), - rom: platform_rom(adapter), + rom: platform_rom(adapter, (stack.kernel.integrated)(adapter)), ..Placement::default() }; let (mut bars, mut resources) = (Vec::new(), ManuallyDrop::new(Vec::new())); @@ -1365,6 +1616,12 @@ fn claim( if reset { resized_bars(address, &function, &mut placement, &mut bars); } + // After the reset, which clears what a ROM BAR held. + if let Some((region, resource)) = expansion_rom(services, &mut function) { + placement.rom_bar = region; + bars.push(region.start..region.start + region.size.max(PAGE)); + resources.push(resource); + } let mut views = ManuallyDrop::new(views); views .check(&mut function) diff --git a/crates/stela-boot/src/engine/start.rs b/crates/stela-boot/src/engine/start.rs index a0ff81a165..e5e6dcbf21 100644 --- a/crates/stela-boot/src/engine/start.rs +++ b/crates/stela-boot/src/engine/start.rs @@ -2935,6 +2935,8 @@ fn start_platform( // SAFETY: before any GPU claim, with the loader root that maps the // ACPI tables, as the remapping units' were read above. unsafe { super::gpu::keep_video_bios_table(handoff.rsdp, handoff.root) }; + // SAFETY: as above; the loader root maps the pages the boot kept. + unsafe { super::gpu::keep_pci_map(handoff.pci_map, handoff.root) }; // The IOAPICs are the operating system's after ExitBootServices, as // every OS takes them: firmware and SMM program no routes at runtime. if let Some(pci) = &contained_pci { diff --git a/crates/stela-boot/src/engine/storage.rs b/crates/stela-boot/src/engine/storage.rs index 63b5790731..f09e962985 100644 --- a/crates/stela-boot/src/engine/storage.rs +++ b/crates/stela-boot/src/engine/storage.rs @@ -2386,7 +2386,10 @@ pub unsafe fn open( core::mem::take(&mut devices.pcie_bluetooth), root, ), - gpus: core::mem::take(&mut devices.gpus), + gpus: { + super::gpu::keep_atrm(devices.atrm.take()); + core::mem::take(&mut devices.gpus) + }, gpu_companions: core::mem::take(&mut devices.gpu_companions), isa_bridges: core::mem::take(&mut devices.isa_bridges), usb, diff --git a/crates/stela-boot/src/handoff.rs b/crates/stela-boot/src/handoff.rs index c6039a9be1..0b7f6f65ec 100644 --- a/crates/stela-boot/src/handoff.rs +++ b/crates/stela-boot/src/handoff.rs @@ -98,6 +98,9 @@ pub struct Handoff { pub efi_reset: u64, /// The firmware's ACPI RSDP; zero without one. pub rsdp: u64, + /// The firmware's PCI map, with copies of the display functions' option + /// ROMs (`pci_io::firmware_map`); empty without one. + pub pci_map: Region, /// The `--wifi-key` file's bytes, read from the ESP; empty when /// `--wifi` names no network or the file could not be read. The engine /// parses and wipes them. diff --git a/crates/stela-boot/src/pci_io.rs b/crates/stela-boot/src/pci_io.rs index 0c474d6351..eeb45f79c2 100644 --- a/crates/stela-boot/src/pci_io.rs +++ b/crates/stela-boot/src/pci_io.rs @@ -755,3 +755,87 @@ pub(crate) fn xhci_legacy_capabilities() -> Vec<(Address, u64)> { } found } + +/// The firmware's map of every PCI function ([`stela_boot_core::pci_map`]): +/// each BAR's memory, each bridge's buses and window, and a copy of each +/// display function's option ROM the firmware keeps (`RomImage`), as +/// Linux's EFI stub copies it. The map and the copies are in pages the boot +/// keeps. An empty region where the firmware lists no PCI function. +pub(crate) fn firmware_map() -> crate::handoff::Region { + use stela_boot_core::pci_map::{self, Function, MOST_FUNCTIONS}; + let Ok(handles) = boot::find_handles::() else { + return crate::handoff::Region::default(); + }; + let mut functions = Vec::new(); + let mut roms = 0; + for handle in handles.into_iter().take(MOST_FUNCTIONS) { + let Ok(mut pci) = get_protocol::(handle) else { + continue; + }; + let (Ok(address), Ok(header)) = (pci.address(), pci.read_header()) else { + continue; + }; + let mut spans = Vec::new(); + for bar in 0..6 { + for region in pci.bar_regions(bar).unwrap_or_default() { + if region.resource_type == 0 && region.host == region.pci { + spans.push(region.host); + } + } + } + let bridge = (header[0x0e] & 0x7f == 1).then(|| { + ( + header[0x19], + header[0x1a], + u32::from_le_bytes([header[0x20], header[0x21], header[0x22], header[0x23]]), + ) + }); + let rom = if header[0x0b] == 3 && pci.rom_size != 0 && !pci.rom_image.is_null() { + copy_rom(&pci) + } else { + None + }; + roms += usize::from(rom.is_some()); + functions.push(Function { + segment: address.segment, + bus: address.bus, + device: address.device, + function: address.function, + bridge, + spans, + rom, + }); + } + let bytes = pci_map::encode(&functions); + let Ok(physical) = crate::firmware::pages(bytes.len().div_ceil(4096)) else { + return crate::handoff::Region::default(); + }; + // SAFETY: fresh reserved LOADER_DATA pages of at least this length, + // written only here; they are never freed or given to a guest. + unsafe { core::slice::from_raw_parts_mut(physical as *mut u8, bytes.len()) } + .copy_from_slice(&bytes); + crate::output::arguments(format_args!( + "PCI firmware map: {} functions, {roms} display option ROMs kept\n", + functions.len() + )); + crate::handoff::Region { + physical: physical as u64, + bytes: bytes.len() as u64, + } +} + +/// A copy of the option ROM the firmware read from `pci`'s ROM BAR, in +/// kept pages, of at most 16 MiB (a ROM BAR decodes no more). +fn copy_rom(pci: &PciIo) -> Option> { + let length = usize::try_from(pci.rom_size) + .ok() + .filter(|&length| length <= 16 << 20)?; + let physical = crate::firmware::pages(length.div_ceil(4096)).ok()?; + // SAFETY: the firmware's live RomImage of RomSize bytes during boot + // services, and fresh reserved LOADER_DATA pages of at least that + // length, written only here and never freed or given to a guest. + unsafe { + ptr::copy_nonoverlapping(pci.rom_image.cast::(), physical as *mut u8, length); + } + Some(physical as u64..physical as u64 + length as u64) +} diff --git a/crates/stela-boot/src/system.rs b/crates/stela-boot/src/system.rs index c285198b4b..01576c6ef9 100644 --- a/crates/stela-boot/src/system.rs +++ b/crates/stela-boot/src/system.rs @@ -901,6 +901,9 @@ fn load( boot_disk[..take].copy_from_slice(&location.as_bytes()[..take]); boot_disk_bytes = take; } + // Before the firmware's exit, while its PCI bus driver keeps what it + // sized and the option ROMs it read. + let pci_map = crate::pci_io::firmware_map(); let (device_skips, device_needs) = device_starts(&system); // Found now, through the firmware's own protocol; claimed as the first // act after the firmware's exit. @@ -1134,6 +1137,7 @@ fn load( power, efi_reset: runtime.reset, rsdp: storage::rsdp().unwrap_or(0), + pci_map, wifi_key: Region { physical: wifi_key.as_ptr() as u64, bytes: wifi_key.len() as u64, diff --git a/crates/stela-drivers/src/probe.rs b/crates/stela-drivers/src/probe.rs index c1123cebae..576e179656 100644 --- a/crates/stela-drivers/src/probe.rs +++ b/crates/stela-drivers/src/probe.rs @@ -788,6 +788,11 @@ pub struct Devices { /// PCI-to-ISA bridges as their configuration reads, which no driver /// here takes: a GPU's kernel driver names the chipset by them. pub isa_bridges: Vec, + /// A hybrid laptop's discrete GPU video BIOS, read through `ATRM` from + /// the first display function's ACPI companion that has it, as amdgpu + /// reads it (`gpu_methods::atrm`). + #[cfg(feature = "native-acpi")] + pub atrm: Option, /// Host keyboards and pointers: virtio-input devices, USB HID devices /// behind xHCI controllers, and the i8042 ports the ACPI namespace /// lists, each polled through [`InputDevice::poll`]. @@ -2349,6 +2354,11 @@ pub unsafe fn probe_observed( .push((address, class, d3cold::POWERED_OFF_PORT)); } } + // ATRM, read while the census's bridges name each function's companion. + #[cfg(feature = "native-acpi")] + if let Some(session) = services.and_then(|services| services.acpi()) { + devices.atrm = gpu_methods::atrm(session, &bridges, &devices.classes); + } attach_usb4_hosts(usb4_hosts, services, &bridges, handoff, &mut devices); // Each display controller's companion, once every bridge above it is // known. diff --git a/crates/stela-drivers/src/probe/gpu_methods.rs b/crates/stela-drivers/src/probe/gpu_methods.rs index cdcd12db55..7713da7834 100644 --- a/crates/stela-drivers/src/probe/gpu_methods.rs +++ b/crates/stela-drivers/src/probe/gpu_methods.rs @@ -1,24 +1,26 @@ -//! The ACPI methods of AMD's graphics interface that amdgpu calls where -//! Linux builds its ACPI support (`amdgpu_acpi.c`, `amdgpu_atpx_handler.c`), -//! which Stela's Linux profile does not: `ATPX` switches and powers a hybrid -//! laptop's discrete GPU, `ATRM` hands out its video BIOS, `ATIF` carries -//! the platform's display notifications and backlight, `ATCS` the PCIe link -//! requests. Each that the namespace holds is named once, with the -//! response amdgpu then gives without it. -use crate::platform::acpi::{Error, Session}; +//! The ACPI methods of AMD's graphics interface, which amdgpu calls where +//! Linux builds its ACPI support (`amdgpu_bios.c`, `amdgpu_atpx_handler.c`, +//! `amdgpu_acpi.c`). Stela's Linux profile does not build it, so the boot +//! calls the one a hybrid laptop's discrete GPU needs for its video BIOS, as +//! amdgpu calls it, and names the rest once: +//! +//! - `ATRM` hands out the discrete GPU's video BIOS in 4 KiB pieces +//! (`amdgpu_atrm_get_bios`); [`atrm`] reads it during the PCI census and +//! the claim gives it to Linux as the function's platform ROM. +//! - `ATPX`, `ATIF` and `ATCS` are not called: [`METHODS`] says what amdgpu +//! does without them. +use super::native::{Bridge, companion}; +use crate::bus::pci::Address; +use crate::platform::acpi::{Argument, Error, Handle, Session, Value}; use alloc::{string::String, vec::Vec}; -/// Each method, and what amdgpu does where it is not called. -pub const METHODS: [(&str, &str); 4] = [ +/// Each method the boot names once where the namespace holds it, and what +/// amdgpu does without it. +pub const METHODS: [(&str, &str); 3] = [ ( "ATPX", "the discrete GPU stays powered and the display mux stays as firmware set it", ), - ( - "ATRM", - "amdgpu reads the discrete GPU's video BIOS from the VFCT table, the GPU's ROM or its \ - registers instead", - ), ( "ATIF", "the platform's display notifications go unheard and amdgpu sets the backlight itself", @@ -43,5 +45,68 @@ pub fn find(session: &Session) -> Result, Error> { .collect()) } +/// `ATRM_BIOS_PAGE` and the 256 KiB `amdgpu_atrm_get_bios` reads at most. +const ATRM_PAGE: usize = 4096; +const ATRM_BYTES: usize = 256 * 1024; + +/// A video BIOS read through `ATRM`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Atrm { + /// The display function whose ACPI companion holds the method. + pub owner: Address, + /// The method's path. + pub path: String, + /// The pieces it returned, in order, up to the first short one. + pub image: Vec, +} + +/// `ATRM` as `amdgpu_atrm_get_bios` reads it: the first display function +/// of `displays` (class VGA or other display, in census order) whose ACPI +/// companion holds the method, called for each 4 KiB piece until one comes +/// back short or the call fails, at most 256 KiB. +pub(super) fn atrm( + session: &Session, + bridges: &[Bridge], + displays: &[(Address, [u8; 3])], +) -> Option { + let (owner, method) = displays + .iter() + .filter(|(_, class)| class[0] == 3 && matches!(class[1], 0 | 0x80)) + .find_map(|&(address, _)| { + let device = companion(session, address, bridges)?; + device.child("ATRM").ok()?; + Some((address, device)) + })?; + Some(Atrm { + owner, + path: method.path().unwrap_or_default(), + image: read_atrm(method), + }) +} + +/// The pieces `ATRM` under `device` returns, as [`atrm`] reads them. +pub fn read_atrm(device: Handle<'_>) -> Vec { + let mut image = Vec::new(); + while image.len() < ATRM_BYTES { + let offset = image.len() as u64; + let piece = match device.evaluate( + Some("ATRM"), + &[ + Argument::Integer(offset), + Argument::Integer(ATRM_PAGE as u64), + ], + ) { + Ok(Some(Value::Buffer(piece))) => piece, + _ => break, + }; + let length = piece.len().min(ATRM_PAGE); + image.extend_from_slice(&piece[..length]); + if length < ATRM_PAGE { + break; + } + } + image +} + #[cfg(test)] mod tests; diff --git a/crates/stela-drivers/src/probe/gpu_methods/tests.rs b/crates/stela-drivers/src/probe/gpu_methods/tests.rs index d5436b1364..af7f068b49 100644 --- a/crates/stela-drivers/src/probe/gpu_methods/tests.rs +++ b/crates/stela-drivers/src/probe/gpu_methods/tests.rs @@ -6,47 +6,148 @@ use crate::platform::acpi::{ }; use alloc::{vec, vec::Vec}; -/// A package with its one-byte length, which every object below fits. -fn package(op: &[u8], name: &[u8; 4], body: Vec) -> Vec { - let length = u8::try_from(body.len() + 5).unwrap(); - assert!(length < 0x40); - [op, &[length], name, &body].concat() -} -/// `Method (name, 0) { Return (Zero) }`. -fn method(name: &[u8; 4]) -> Vec { - package(&[0x14], name, vec![0, 0xa4, 0]) +/// A package: `op`, its length (which counts itself), then `body`. +fn package(op: &[u8], body: Vec) -> Vec { + let length = if body.len() + 1 < 0x40 { + vec![(body.len() + 1) as u8] + } else { + let total = body.len() + 2; + assert!(total < 1 << 12); + vec![0x40 | (total & 0xf) as u8, (total >> 4) as u8] + }; + [op.to_vec(), length, body].concat() } fn device(name: &[u8; 4], body: Vec>) -> Vec { - package(&[0x5b, 0x82], name, body.concat()) + package(&[0x5b, 0x82], [name.to_vec(), body.concat()].concat()) +} +fn method(name: &[u8; 4], arguments: u8, body: Vec>) -> Vec { + package( + &[0x14], + [name.to_vec(), vec![arguments], body.concat()].concat(), + ) +} +/// `Buffer (size) { bytes }`, the size as a word. +fn buffer(size: u16, bytes: &[u8]) -> Vec { + package( + &[0x11], + [vec![0x0b], size.to_le_bytes().to_vec(), bytes.to_vec()].concat(), + ) +} +fn ret(value: Vec) -> Vec { + [vec![0xa4], value].concat() +} +/// `If (predicate) { body }`. +fn when(predicate: Vec, body: Vec>) -> Vec { + package(&[0xa0], [predicate, body.concat()].concat()) +} +/// `LLess (Arg0, value)` and `LEqual (Arg0, value)`, the value as a word. +fn arg0_below(value: u16) -> Vec { + [vec![0x95, 0x68, 0x0b], value.to_le_bytes().to_vec()].concat() +} +fn arg0_is(value: u16) -> Vec { + [vec![0x93, 0x68, 0x0b], value.to_le_bytes().to_vec()].concat() +} + +/// `\_SB.PCI0` (a PCI host bridge) with `GFX0` at 00:02.0, whose `ATRM` +/// returns full pieces below 8 KiB and a short one there; `\_SB.IGPU`'s +/// `ATPX` supports power control and keeps its last power argument in +/// `PWRB`; `\_SB.IGPU` also has `ATIF`. +fn dsdt() -> Vec { + let atrm = method( + b"ATRM", + 2, + vec![ + when(arg0_below(0x2000), vec![ret(buffer(0x1000, &[0x55, 0xaa]))]), + ret(buffer(0x10, &[0x01])), + ], + ); + let gfx = device( + b"GFX0", + vec![ + [ + vec![0x08], + b"_ADR".to_vec(), + vec![0x0c], + 0x0002_0000u32.to_le_bytes().to_vec(), + ] + .concat(), + atrm, + ], + ); + let host = device( + b"PCI0", + vec![ + [ + vec![0x08], + b"_HID".to_vec(), + vec![0x0c], + 0x080a_d041u32.to_le_bytes().to_vec(), + ] + .concat(), + gfx, + ], + ); + let atpx = method( + b"ATPX", + 2, + vec![ + when(arg0_is(0), vec![ret(buffer(8, &[8, 0, 1, 0, 2, 0, 0, 0]))]), + when( + arg0_is(2), + vec![[vec![0x70, 0x69], b"PWRB".to_vec()].concat()], + ), + ret(buffer(2, &[0, 0])), + ], + ); + let igpu = device( + b"IGPU", + vec![ + [vec![0x08], b"PWRB".to_vec(), buffer(3, &[0, 0, 0])].concat(), + atpx, + method(b"ATIF", 2, vec![ret(buffer(2, &[0, 0]))]), + ], + ); + package(&[0x10], [b"\\_SB_".to_vec(), host, igpu].concat()) +} + +fn session() -> Session { + let services = dsdt_fixture(&dsdt()); + // SAFETY: the serialized fixture hands its whole provider to the one + // ACPICA session, which outlives every handle below. + unsafe { Session::start(services, Mode::InterpreterOnly) }.unwrap() } #[test] -fn each_method_is_found_once_at_its_first_device() { +fn each_unserved_method_is_found_once() { let _serial = TEST_SERIAL .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - // \_SB.GFX0 (the integrated GPU) with ATPX and ATIF, \_SB.DGPU with - // ATRM and a second ATIF; no ATCS. - let dsdt = [ - &[0x10][..], - &[0], // scope length, patched below - b"\\_SB_", - &device(b"GFX0", vec![method(b"ATPX"), method(b"ATIF")]), - &device(b"DGPU", vec![method(b"ATRM"), method(b"ATIF")]), - ] - .concat(); - let mut dsdt = dsdt; - let length = dsdt.len() - 1; - assert!(length < 0x40); - dsdt[1] = length as u8; - let services = dsdt_fixture(&dsdt); - // SAFETY: the serialized fixture hands its whole provider to the one - // ACPICA session, which outlives every handle below. - let session = unsafe { Session::start(services, Mode::InterpreterOnly) }.unwrap(); + let session = session(); let found = find(&session).unwrap(); let names: Vec<_> = found.iter().map(|(method, _)| *method).collect(); - assert_eq!(names, ["ATPX", "ATRM", "ATIF"]); - assert!(found[0].1.ends_with("GFX0"), "{found:?}"); - assert!(found[1].1.ends_with("DGPU"), "{found:?}"); - assert!(found[2].1.ends_with("GFX0"), "{found:?}"); + assert_eq!(names, ["ATPX", "ATIF"]); + assert!(found[0].1.ends_with("IGPU"), "{found:?}"); +} + +#[test] +fn atrm_is_read_in_pieces_up_to_the_first_short_one() { + let _serial = TEST_SERIAL + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let session = session(); + let gfx = Address { + segment: 0, + bus: 0, + device: 2, + function: 0, + }; + let audio = Address { function: 1, ..gfx }; + // Only a display function's companion is asked. + assert_eq!(atrm(&session, &[], &[(audio, [4, 3, 0])]), None); + let read = atrm(&session, &[], &[(audio, [4, 3, 0]), (gfx, [3, 0, 0])]).unwrap(); + assert_eq!(read.owner, gfx); + assert!(read.path.ends_with("GFX0"), "{}", read.path); + assert_eq!(read.image.len(), 2 * ATRM_PAGE + 0x10); + assert_eq!(read.image[..2], [0x55, 0xaa]); + assert_eq!(read.image[2 * ATRM_PAGE], 0x01); } diff --git a/crates/stela-linux/src/compat/kernel/pci_host.c b/crates/stela-linux/src/compat/kernel/pci_host.c index 600343ddb3..69c5e2eea6 100644 --- a/crates/stela-linux/src/compat/kernel/pci_host.c +++ b/crates/stela-linux/src/compat/kernel/pci_host.c @@ -374,6 +374,12 @@ struct pci_dev *stela_linux_pci_attach(const struct stela_linux_pci_function *fu dev->resource[i].end = region->start + region->size - 1; dev->resource[i].flags = region->flags; } + if (function->rom_bar.size) { + dev->resource[PCI_ROM_RESOURCE].start = function->rom_bar.start; + dev->resource[PCI_ROM_RESOURCE].end = + function->rom_bar.start + function->rom_bar.size - 1; + dev->resource[PCI_ROM_RESOURCE].flags = function->rom_bar.flags; + } /* The caller's image lasts only for the attach. */ host->function.rom = NULL; if (function->rom_length) { @@ -783,6 +789,22 @@ int main(void) assert(!stela_linux_pci_rom_map(copy, 1) && !stela_linux_pci_rom_mapped(rom)); function.rom = NULL; function.rom_length = 0; + /* An expansion ROM BAR the owner placed is PCI_ROM_RESOURCE, which + * pci_enable_rom turns on at its address and pci_disable_rom off. */ + function.rom_bar = (struct stela_linux_pci_region){ + 0xc0020000, 0x20000, IORESOURCE_MEM | IORESOURCE_READONLY}; + memcpy(&config[PCI_ROM_ADDRESS], "\x00\x00\x02\xc0", 4); + dev = stela_linux_pci_attach(&function, NULL); + assert(dev && pci_resource_start(dev, PCI_ROM_RESOURCE) == 0xc0020000); + assert(pci_resource_len(dev, PCI_ROM_RESOURCE) == 0x20000); + assert(!pci_enable_rom(dev)); + assert(!pci_read_config_dword(dev, PCI_ROM_ADDRESS, &value) && + value == (0xc0020000 | PCI_ROM_ADDRESS_ENABLE)); + pci_disable_rom(dev); + assert(!pci_read_config_dword(dev, PCI_ROM_ADDRESS, &value) && value == 0xc0020000); + stela_linux_pci_remove_device(dev); + function.rom_bar = (struct stela_linux_pci_region){0}; + memset(&config[PCI_ROM_ADDRESS], 0, 4); /* An atomic final put cannot destroy the host or callback context. */ function.release_context = test_release_context; dev = stela_linux_pci_attach(&function, NULL); diff --git a/crates/stela-linux/src/compat/stela/pci.h b/crates/stela-linux/src/compat/stela/pci.h index 0aa9fd4490..97034946fb 100644 --- a/crates/stela-linux/src/compat/stela/pci.h +++ b/crates/stela-linux/src/compat/stela/pci.h @@ -57,9 +57,14 @@ struct stela_linux_pci_function { * which the attach copies into pci_dev::rom: rom_length 0 for none. */ const void *rom; size_t rom_length; + /* The expansion ROM BAR where the owner placed it, decoding off, which + * the attach keeps as PCI_ROM_RESOURCE: size 0 for none. */ + struct stela_linux_pci_region rom_bar; }; -_Static_assert(sizeof(struct stela_linux_pci_function) == 256, "Linux PCI function ABI"); +_Static_assert(sizeof(struct stela_linux_pci_function) == 280, "Linux PCI function ABI"); +_Static_assert(__builtin_offsetof(struct stela_linux_pci_function, rom_bar) == 256, + "Linux PCI ROM BAR ABI"); _Static_assert(__builtin_offsetof(struct stela_linux_pci_function, release_context) == 224, "Linux PCI context release ABI"); diff --git a/crates/stela-linux/src/function.rs b/crates/stela-linux/src/function.rs index e294cf49e4..6bd7daf75d 100644 --- a/crates/stela-linux/src/function.rs +++ b/crates/stela-linux/src/function.rs @@ -101,6 +101,10 @@ pub struct Placement { /// apart from the function, which Linux keeps as `pci_dev::rom`. Empty /// for none. The attach copies it. pub rom: &'static [u8], + /// The function's expansion ROM BAR where its owner placed it, decoding + /// off, which Linux keeps as `PCI_ROM_RESOURCE` for `pci_map_rom`. Size + /// 0 for none. + pub rom_bar: Region, } /// A function's MSI capability (PCI Local Bus 3.0 6.8.1), one message at most. @@ -191,9 +195,11 @@ struct RawFunction { enroll: Option c_int>, rom: *const u8, rom_length: usize, + rom_bar: Region, } -const _: () = assert!(size_of::() == 256); +const _: () = assert!(size_of::() == 280); +const _: () = assert!(core::mem::offset_of!(RawFunction, rom_bar) == 256); const _: () = assert!(core::mem::offset_of!(RawFunction, rom_length) == 248); const _: () = assert!(core::mem::offset_of!(RawFunction, enroll) == 232); const _: () = assert!(core::mem::offset_of!(RawFunction, release_context) == 224); @@ -870,6 +876,7 @@ impl Attached { enroll: catalogued.then_some(enroll::), rom: placement.rom.as_ptr(), rom_length: placement.rom.len(), + rom_bar: placement.rom_bar, }; let mut error = 0; // SAFETY: caller's attach contract; C copies the table and returns a