Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/patches/d723695f3f259b2d # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aienux#103 (code only) closed derived `d723695f3f259b2d` #103 Imported from GitHub aien-dev/aienux#103 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `a51db0b59e0d3b01882e051a2dff4e24843171eb` · Head `9e16f09ffb358690af5394f5a019dfd1bea78660` ### Apply it ``` git checkout -b patch-d723695f3f259b2d a51db0b59e0d3b01882e051a2dff4e24843171eb curl -fsSL https://interplane.io/drakestapleton/aienux/patches/d723695f3f259b2d.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aienux 103 9e16f09ffb358690af5394f5a019dfd1bea78660 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":103,"url":"https://github.com/aien-dev/aienux/pull/103","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:43Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml index 624baa4e..a525c99a 100644 --- a/crates/aienos-boot/Cargo.toml +++ b/crates/aienos-boot/Cargo.toml @@ -18,6 +18,7 @@ handoff = ["uefi-base", "dep:aienos-kernel", "dep:aienos-accel", "uefi/alloc"] # SEED-0A candidate: polled USB keyboard after firmware exit (ADR 0012). # Only the QEMU keyboard test enables it; hardware staging never does. usb-keyboard = ["handoff"] +debug-xhci-without-smmu = ["usb-keyboard"] [dependencies] uefi = { version = "0.41", default-features = false, optional = true } diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs index af7053d1..cc4aa797 100644 --- a/crates/aienos-boot/src/handoff.rs +++ b/crates/aienos-boot/src/handoff.rs @@ -33,12 +33,12 @@ use aienos_kernel::display::{FramebufferInfo, PixelOrder, Screen, ACCENT, FOREGR use aienos_kernel::fatal::{self, FaultInfo}; use aienos_kernel::mem::frame_allocator::PhysAddr; use aienos_kernel::mem::map_plan::{self, AddressRange, EfiMemoryDescriptor}; -use aienos_kernel::mem::pagetable::{FixedFramePool, PageTableBuilder, TableMemory}; +use aienos_kernel::mem::pagetable::{FixedFramePool, MapFlags, PageTableBuilder, TableMemory}; use aienos_kernel::report::ReportBuf; use aienos_kernel::sync::spinlock::SpinLock; use core::alloc::{GlobalAlloc, Layout}; use core::fmt::Write; -use core::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams}; use uefi::mem::memory_map::{MemoryMap, MemoryType}; use uefi::prelude::*; @@ -58,6 +58,44 @@ static POST_EXIT_HEAP: AtomicU64 = AtomicU64::new(0); static POST_EXIT_HEAP_USED: AtomicU64 = AtomicU64::new(0); static BOOT_SERVICES_LIVE: AtomicBool = AtomicBool::new(true); +#[cfg(feature = "usb-keyboard")] +#[repr(C)] +struct SmmuTables { + stream_table: [[u64; 8]; 4096], + command_queue: [[u64; 2]; 16], + event_queue: [[u64; 4]; 16], + context: [u64; 8], +} + +#[cfg(feature = "usb-keyboard")] +const STREAM_ENTRIES: u32 = 4096; + +// The linear stream table base must be aligned to its size (4096 * 64 bytes = +// 256 KiB) or QEMU truncates it before fetching the STE. COFF/PE cannot encode +// section alignment above 8192, so a 256 KiB-aligned static is unbuildable for +// aarch64-unknown-uefi; allocate the tables at runtime with an over-aligned +// Layout and hand out one shared pointer to every user instead. +#[cfg(feature = "usb-keyboard")] +const SMMU_TABLES_ALIGN: usize = 262144; + +#[cfg(feature = "usb-keyboard")] +static SMMU_TABLES_PTR: AtomicUsize = AtomicUsize::new(0); + +#[cfg(feature = "usb-keyboard")] +fn smmu_tables() -> *mut SmmuTables { + let existing = SMMU_TABLES_PTR.load(Ordering::Acquire); + if existing != 0 { + return existing as *mut SmmuTables; + } + let layout = Layout::from_size_align(core::mem::size_of::(), SMMU_TABLES_ALIGN) + .expect("smmu tables layout"); + let raw = unsafe { ALLOCATOR.alloc(layout) }; + assert!(!raw.is_null(), "smmu tables allocation failed"); + unsafe { core::ptr::write_bytes(raw, 0, layout.size()) }; + SMMU_TABLES_PTR.store(raw as usize, Ordering::Release); + raw.cast::() +} + struct BootHeap; unsafe impl GlobalAlloc for BootHeap { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { @@ -156,6 +194,75 @@ fn clean_table_pool(base: usize, bytes: usize) { let _ = (base, bytes); } +#[cfg(feature = "usb-keyboard")] +fn configure_smmu_for_xhci( + iort: Option<&acpi::IortSmmu>, + xhci: Option, + pool_base: usize, + frames_used: usize, +) -> Result { + let iort = iort.ok_or(aienos_kernel::smmu::Error::InvalidWindow)?; + let xhci = xhci.ok_or(aienos_kernel::smmu::Error::InvalidWindow)?; + let stream_id = xhci + .stream_id(iort) + .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?; + let (dma_base, dma_length) = xhci.dma_window(); + let remaining = PT_POOL_PAGES.saturating_sub(frames_used); + let next = pool_base + .checked_add( + frames_used + .checked_mul(4096) + .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?, + ) + .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?; + let frames = FixedFramePool::new(PhysAddr(next), remaining) + .ok_or(aienos_kernel::smmu::Error::InvalidWindow)?; + let mut page_table = PageTableBuilder::new(frames, PhysicalTableMemory) + .map_err(aienos_kernel::smmu::Error::PageTable)?; + page_table + .map( + dma_base as usize, + PhysAddr(dma_base as usize), + dma_length, + MapFlags::KERNEL_DATA, + ) + .map_err(aienos_kernel::smmu::Error::PageTable)?; + let dma_root = page_table.root().0; + let table_frames = page_table.frames_used().unwrap_or(0); + clean_table_pool(next, table_frames * 4096); + + let tables = smmu_tables(); + assert_eq!( + core::mem::size_of::<[[u64; 8]; STREAM_ENTRIES as usize]>(), + SMMU_TABLES_ALIGN, + "stream table must be exactly 256 KiB" + ); + assert_eq!(STREAM_ENTRIES.trailing_zeros(), 12, "LOG2SIZE must be 12"); + assert!(stream_id < STREAM_ENTRIES, "SID outside the stream table"); + assert_eq!( + tables as usize % SMMU_TABLES_ALIGN, + 0, + "SMMU stream table is not 256 KiB aligned" + ); + clean_table_pool(tables as usize, core::mem::size_of::()); + let mut regs = unsafe { aienos_kernel::smmu::MmioRegisters::new(iort.base as usize) }; + unsafe { + aienos_kernel::smmu::configure_linear_stream( + &mut regs, + stream_id, + STREAM_ENTRIES, + core::ptr::addr_of_mut!((*tables).stream_table).cast(), + 16, + core::ptr::addr_of_mut!((*tables).command_queue).cast(), + 16, + core::ptr::addr_of_mut!((*tables).event_queue).cast(), + core::ptr::addr_of_mut!((*tables).context), + dma_root as u64, + )?; + } + Ok(stream_id) +} + fn enter_kernel_mmu( memory_map: &impl MemoryMap, pool_base: usize, @@ -167,6 +274,7 @@ fn enter_kernel_mmu( xhci_mmio: Option, ecam: Option, gic: Option, + smmu_mmio: Option, ) -> (usize, usize, bool) { let descriptors: alloc::vec::Vec<_> = memory_map .entries() @@ -213,6 +321,12 @@ fn enter_kernel_mmu( }); } } + if let Some(base) = smmu_mmio { + mmio.push(AddressRange { + start: base & !4095, + length: 0x20000, + }); + } let (plan, decision) = map_plan::build_map_plan(&descriptors, image.start, image, sections, attrs, &mmio) .expect("identity map plan rejected firmware layout"); @@ -700,6 +814,8 @@ struct AcpiFacts { gic: Option, #[cfg(feature = "usb-keyboard")] mcfg: Option<&'static [u8]>, + #[cfg(feature = "usb-keyboard")] + iort: Option, } fn discover_acpi(boot_mpidr: u64) -> AcpiFacts { @@ -739,6 +855,8 @@ fn discover_acpi(boot_mpidr: u64) -> AcpiFacts { b"SPCR" => facts.spcr = acpi::spcr_console(table).ok(), #[cfg(feature = "usb-keyboard")] b"MCFG" => facts.mcfg = Some(table), + #[cfg(feature = "usb-keyboard")] + b"IORT" => facts.iort = acpi::iort_smmuv3(table).ok().flatten(), _ => {} } } @@ -1135,8 +1253,16 @@ fn main() -> Status { #[cfg(not(feature = "usb-keyboard"))] None, acpi_facts.gic, + #[cfg(feature = "usb-keyboard")] + acpi_facts.iort.as_ref().map(|i| i.base), + #[cfg(not(feature = "usb-keyboard"))] + None, ); + #[cfg(feature = "usb-keyboard")] + let smmu_result = + configure_smmu_for_xhci(acpi_facts.iort.as_ref(), xhci, pt_pool, pt_frames_used); + fatal::set_fault_hook(on_fault); fatal::install_exception_vectors(); stage(VECTORS_INSTALLED); @@ -1191,6 +1317,20 @@ fn main() -> Status { if mmu_on { "enabled" } else { "disabled" } ); let _ = writeln!(report, "pt_frames_used: {pt_frames_used}"); + #[cfg(feature = "usb-keyboard")] + match smmu_result { + Ok(stream_id) => { + let _ = writeln!( + report, + "smmu: enabled base={:#x} stream_id={stream_id:#x}", + acpi_facts.iort.as_ref().map_or(0, |i| i.base) + ); + let _ = writeln!(report, "smmu_dma_window: xhci only, translation active"); + } + Err(error) => { + let _ = writeln!(report, "smmu: unavailable ({error:?})"); + } + } // Cooperative threads at EL1 (issue #29): two workers each record a tag and // yield five times; the line reports the order actually observed. let (trace, trace_len) = unsafe { aienos_kernel::thread::run_demo() }; @@ -1297,6 +1437,10 @@ fn main() -> Status { summary.conventional_kb(), el, report.as_str(), + smmu_result.is_ok(), + acpi_facts.iort.as_ref().map(|s| s.base), + smmu_result.ok(), + unsafe { core::ptr::addr_of_mut!((*smmu_tables()).event_queue).cast_const() }, ); finish(screen) } diff --git a/crates/aienos-boot/src/usb_keyboard.rs b/crates/aienos-boot/src/usb_keyboard.rs index 90dc0e3b..6c032c99 100644 --- a/crates/aienos-boot/src/usb_keyboard.rs +++ b/crates/aienos-boot/src/usb_keyboard.rs @@ -25,6 +25,8 @@ fn listen_secs() -> u64 { .unwrap_or(30) } +const DEBUG_XHCI_WITHOUT_SMMU: bool = cfg!(feature = "debug-xhci-without-smmu"); + /// DMA memory for the driver, used only after firmware exit. static mut DMA: DmaMemory = DmaMemory::new(); @@ -45,6 +47,16 @@ impl XhciLocation { pub fn ecam_location(self) -> (u16, u8) { (self.segment, self.bus) } + pub fn requester_id(self) -> u32 { + (u32::from(self.bus) << 8) | (u32::from(self.device) << 3) | u32::from(self.function) + } + pub fn stream_id(self, iort: &acpi::IortSmmu) -> Option { + iort.stream_id_for(self.requester_id()) + } + pub fn dma_window(self) -> (u64, usize) { + let base = core::ptr::addr_of!(DMA) as u64; + (base & !0xfff, core::mem::size_of::()) + } } /// Walk every root bridge for the first xHCI controller (pre-exit only). @@ -138,10 +150,14 @@ pub fn run( mcfg: Option<&[u8]>, screen: &mut Option, conventional_memory_kb: u64, - exception_level: u8, + _exception_level: u8, boot_report: &str, + smmu_ready: bool, + smmu_base: Option, + smmu_stream_id: Option, + smmu_events: *const [[u64; 4]; 16], ) { - let mut line = aienos_kernel::report::ReportBuf::<160>::new(); + let mut line = aienos_kernel::report::ReportBuf::<512>::new(); let Some(at) = xhci else { say(screen, "\nkeyboard: unavailable (no xHCI controller)\n"); return; @@ -152,6 +168,26 @@ pub fn run( at.segment, at.bus, at.device, at.function, at.mmio ); say(screen, line.as_str()); + if !smmu_ready && !DEBUG_XHCI_WITHOUT_SMMU { + say( + screen, + "keyboard: unavailable (SMMU DMA isolation not active)\n", + ); + return; + } + let dma_mode = if smmu_ready { + "smmu-translated" + } else { + "debug-identity" + }; + let mut mode = aienos_kernel::report::ReportBuf::<128>::new(); + let _ = writeln!( + mode, + "xhci_debug: dma_mode={dma_mode} dma_base={:#x} bytes={}", + core::ptr::addr_of!(DMA) as usize, + core::mem::size_of::() + ); + say(screen, mode.as_str()); let ecam = mcfg.and_then(|t| acpi::mcfg_window(t, at.segment, at.bus).ok().flatten()); if !ecam.is_some_and(|w| enable_controller(&w, &at)) { say( @@ -166,9 +202,30 @@ pub fn run( let mut keyboard = match started { Ok(k) => k, Err(e) => { - let mut msg = aienos_kernel::report::ReportBuf::<160>::new(); - let _ = writeln!(msg, "keyboard: unavailable ({e})"); + let mut msg = aienos_kernel::report::ReportBuf::<512>::new(); + let _ = writeln!(msg, "keyboard: unavailable ({e:?})"); say(screen, msg.as_str()); + if let Some(base) = smmu_base { + let reg = |offset| MmioReg::::new(base as usize + offset).read(); + aienos_kernel::arch::aarch64::clean_invalidate_dcache_range( + smmu_events as usize, + core::mem::size_of::<[[u64; 4]; 16]>(), + ); + let events = unsafe { core::ptr::read_volatile(smmu_events) }; + let mut fault = aienos_kernel::report::ReportBuf::<1024>::new(); + let _ = writeln!(fault, "smmu_fault: GERROR={:#x} GERRORN={:#x} EVENTQ_PROD={:#x} EVENTQ_CONS={:#x} events={events:016x?}", reg(0x60), reg(0x64), reg(0xa8), reg(0xac)); + say(screen, fault.as_str()); + if let Some(sid) = smmu_stream_id { + let table_base = (u64::from(reg(0x84)) << 32 | u64::from(reg(0x80))) & !0x3f; + let cfg = reg(0x88); + let ste_addr = table_base + u64::from(sid) * 64; + let ste0 = unsafe { core::ptr::read_volatile(ste_addr as *const u64) }; + let ste1 = unsafe { core::ptr::read_volatile((ste_addr + 8) as *const u64) }; + let mut entry = aienos_kernel::report::ReportBuf::<192>::new(); + let _ = writeln!(entry, "smmu_ste: base={table_base:#x} cfg={cfg:#x} sid={sid:#x} addr={ste_addr:#x} words=[{ste0:#x},{ste1:#x}]"); + say(screen, entry.as_str()); + } + } return; } }; diff --git a/crates/aienos-kernel/src/acpi.rs b/crates/aienos-kernel/src/acpi.rs index 5ffb0d5d..3f41c46e 100644 --- a/crates/aienos-kernel/src/acpi.rs +++ b/crates/aienos-kernel/src/acpi.rs @@ -262,6 +262,96 @@ pub fn madt_cpu_topology_for( /// MCFG allocations start after the header and 8 reserved bytes. const MCFG_ENTRIES_OFFSET: usize = 44; const MCFG_ENTRY_LEN: usize = 16; +const IORT_NODE_HEADER_LEN: usize = 16; +const IORT_NODE_SMMUV3: u8 = 4; +const IORT_NODE_ROOT_COMPLEX: u8 = 2; + +/// PCI requester ID range routed through a SMMUv3 node. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct IortStreamMapping { + pub input_base: u32, + pub id_count: u32, + pub output_base: u32, +} + +/// SMMUv3 base and the PCI requester ID mappings that target it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IortSmmu { + pub base: u64, + pub pci_streams: alloc::vec::Vec, +} + +impl IortSmmu { + /// Resolve a PCI requester ID through the first matching root-complex map. + pub fn stream_id_for(&self, requester_id: u32) -> Option { + self.pci_streams.iter().find_map(|mapping| { + let relative = requester_id.checked_sub(mapping.input_base)?; + (relative <= mapping.id_count) + .then(|| mapping.output_base.checked_add(relative)) + .flatten() + }) + } +} + +/// Reads the first SMMUv3 node and PCI root-complex mappings to it from IORT. +pub fn iort_smmuv3(iort: &[u8]) -> Result, AcpiError> { + let iort = checked_table(iort, b"IORT")?; + let count = u32_at(iort, 36).ok_or(AcpiError::Truncated)? as usize; + let mut at = u32_at(iort, 40).ok_or(AcpiError::Truncated)? as usize; + let mut smmu = None; + let mut roots = alloc::vec::Vec::new(); + for _ in 0..count { + let hdr = iort + .get(at..at + IORT_NODE_HEADER_LEN) + .ok_or(AcpiError::BadEntry)?; + let kind = hdr[0]; + let len = u16::from_le_bytes([hdr[1], hdr[2]]) as usize; + if len < IORT_NODE_HEADER_LEN || at.checked_add(len).is_none_or(|end| end > iort.len()) { + return Err(AcpiError::BadEntry); + } + let node = &iort[at..at + len]; + let map_count = u32_at(node, 8).ok_or(AcpiError::BadEntry)? as usize; + let map_offset = u32_at(node, 12).ok_or(AcpiError::BadEntry)? as usize; + let map_bytes = map_count.checked_mul(20).ok_or(AcpiError::BadEntry)?; + if map_count != 0 + && (map_offset < IORT_NODE_HEADER_LEN + || map_offset + .checked_add(map_bytes) + .is_none_or(|end| end > len)) + { + return Err(AcpiError::BadEntry); + } + if kind == IORT_NODE_SMMUV3 && smmu.is_none() { + // SMMUv3 node's first field after the common header is Base Address. + let base = u64_at(node, 16).ok_or(AcpiError::BadEntry)?; + if base == 0 { + return Err(AcpiError::BadEntry); + } + smmu = Some((at as u32, base)); + } + if kind == IORT_NODE_ROOT_COMPLEX { + roots.push((node.to_vec(), map_offset, map_count)); + } + at += len; + } + let Some((smmu_offset, base)) = smmu else { + return Ok(None); + }; + let mut pci_streams = alloc::vec::Vec::new(); + for (node, map_offset, map_count) in roots { + for i in 0..map_count { + let m = &node[map_offset + i * 20..map_offset + (i + 1) * 20]; + if u32_at(m, 12) == Some(smmu_offset) { + pci_streams.push(IortStreamMapping { + input_base: u32_at(m, 0).ok_or(AcpiError::BadEntry)?, + id_count: u32_at(m, 4).ok_or(AcpiError::BadEntry)?, + output_base: u32_at(m, 8).ok_or(AcpiError::BadEntry)?, + }); + } + } + } + Ok(Some(IortSmmu { base, pci_streams })) +} /// One PCI Express enhanced configuration (ECAM) window from the MCFG table. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -335,6 +425,46 @@ mod tests { t } + #[test] + fn parses_iort_smmuv3_base_and_pci_stream_mapping() { + let mut table = std::vec![0u8; 48 + 36 + 36]; + table[..4].copy_from_slice(b"IORT"); + table[36..40].copy_from_slice(&2u32.to_le_bytes()); + table[40..44].copy_from_slice(&48u32.to_le_bytes()); + let smmu = 48; + table[smmu] = IORT_NODE_SMMUV3; + table[smmu + 1..smmu + 3].copy_from_slice(&36u16.to_le_bytes()); + table[smmu + 16..smmu + 24].copy_from_slice(&0x0900_0000u64.to_le_bytes()); + let root = smmu + 36; + table[root] = IORT_NODE_ROOT_COMPLEX; + table[root + 1..root + 3].copy_from_slice(&36u16.to_le_bytes()); + table[root + 8..root + 12].copy_from_slice(&1u32.to_le_bytes()); + table[root + 12..root + 16].copy_from_slice(&16u32.to_le_bytes()); + table[root + 16..root + 20].copy_from_slice(&0x400u32.to_le_bytes()); + table[root + 20..root + 24].copy_from_slice(&0xffu32.to_le_bytes()); + table[root + 24..root + 28].copy_from_slice(&0x800u32.to_le_bytes()); + table[root + 28..root + 32].copy_from_slice(&(smmu as u32).to_le_bytes()); + let len = table.len() as u32; + table[4..8].copy_from_slice(&len.to_le_bytes()); + let sum = table.iter().fold(0u8, |s, b| s.wrapping_add(*b)); + table[9] = 0u8.wrapping_sub(sum); + assert_eq!( + iort_smmuv3(&table).unwrap(), + Some(IortSmmu { + base: 0x0900_0000, + pci_streams: std::vec![IortStreamMapping { + input_base: 0x400, + id_count: 0xff, + output_base: 0x800, + }], + }) + ); + let smmu = iort_smmuv3(&table).unwrap().unwrap(); + assert_eq!(smmu.stream_id_for(0x400), Some(0x800)); + assert_eq!(smmu.stream_id_for(0x4ff), Some(0x8ff)); + assert_eq!(smmu.stream_id_for(0x500), None); + } + #[test] fn extracts_gicd_and_gicr_bases() { let mut dist = std::vec![0u8; 24]; diff --git a/crates/aienos-kernel/src/smmu.rs b/crates/aienos-kernel/src/smmu.rs index c24b8c9e..f31fb5fc 100644 --- a/crates/aienos-kernel/src/smmu.rs +++ b/crates/aienos-kernel/src/smmu.rs @@ -25,6 +25,7 @@ pub const EVENTQ_BASE: u32 = 0xa0; pub const EVENTQ_PROD: u32 = 0xa8; pub const EVENTQ_CONS: u32 = 0xac; pub const GBPA: u32 = 0x44; +pub const IDR1_SIDSIZE_MASK: u32 = 0x3f; pub trait Registers { fn read(&mut self, offset: u32) -> u32; @@ -75,19 +76,28 @@ impl ContextDescriptor { if t0sz > 39 || ttb0 & 0xfff != 0 { return Err(Error::InvalidWindow); } + // CD word 0 carries the TTBR0/TTBR1 configuration and every control + // bit: T0SZ, TG0, IRGN0, ORGN0, SH0, EPD0, EPD1, V, IPS, AA64, R, A + // and ASID. EPD0 stays clear so the TTBR0 stage-1 walk runs; EPD1 + // disables the unused TTBR1 walk. let word0 = u64::from(t0sz) - | (0b01 << 8) - | (0b01 << 10) - | (0b10 << 12) - | (1 << 30) - | (1 << 31) - // IPS (bits 34:32) = 0b101, a 48-bit output range: DMA windows - // above 4 GiB must translate (0 would limit it to 32 bits). - | (0b101 << 32) - | (1 << 41) + | (0b01 << 8) // IRGN0: write-back + | (0b01 << 10) // ORGN0: write-back + | (0b11 << 12) // SH0: inner shareable + | (1 << 30) // EPD1: TTBR1 walk disabled + | (1 << 31) // V: descriptor valid + | (0b101 << 32) // IPS: 5 (48-bit) + | (1 << 41) // AA64 + | (1 << 45) // R: record faults + | (1 << 46) // A: access flag | (u64::from(asid) << 48); - let word1 = ttb0 & 0x000f_ffff_ffff_fff0; - Ok(Self([word0, word1, 0, mair, 0, 0, 0, 0])) + // CD word 1 is the 4 KiB-aligned TTBR0 (48-bit physical address). + let word1 = ttb0 & 0x0000_ffff_ffff_fff0; + // CD word 2 is TTBR1, unused because EPD1 is set. + let word2 = 0; + // CD word 3 is MAIR. + let word3 = mair & 0x0000_0000_0000_ffff; + Ok(Self([word0, word1, word2, word3, 0, 0, 0, 0])) } } @@ -151,16 +161,184 @@ pub fn submit_command( /// Keep global abort enabled until command queues and translation state are ready. pub fn enable(regs: &mut R, spins: usize) -> Result<(), Error> { let gbpa = regs.read(GBPA); - regs.write(GBPA, gbpa | 1 | (1 << 31)); + // GBPA.ABORT is bit 20; bit 31 commits the requested global-bypass update. + regs.write(GBPA, (gbpa & !(1 << 20)) | (1 << 31)); regs.write(CR0, 0); wait_cr0(regs, 0, spins)?; regs.write(CR0, 1); wait_cr0(regs, 1, spins) } +/// Register mapping for an identity-mapped SMMUv3 register aperture. +pub struct MmioRegisters { + base: usize, +} + +impl MmioRegisters { + /// # Safety + /// `base` must address a mapped SMMUv3 register aperture. + pub const unsafe fn new(base: usize) -> Self { + Self { base } + } + + pub fn write64(&mut self, offset: u32, value: u64) { + unsafe { + core::ptr::write_volatile((self.base + offset as usize) as *mut u32, value as u32); + core::ptr::write_volatile( + (self.base + offset as usize + 4) as *mut u32, + (value >> 32) as u32, + ); + } + } +} + +impl Registers for MmioRegisters { + fn read(&mut self, offset: u32) -> u32 { + unsafe { core::ptr::read_volatile((self.base + offset as usize) as *const u32) } + } + + fn write(&mut self, offset: u32, value: u32) { + unsafe { core::ptr::write_volatile((self.base + offset as usize) as *mut u32, value) } + } +} + +fn submit_raw( + regs: &mut R, + cursor: &mut QueueCursor, + entries: u32, + queue: *mut [u64; 2], + cmd: [u64; 2], +) -> Result<(), Error> { + submit_command( + regs, + cursor, + entries, + cmd, + |index, words| unsafe { core::ptr::write_volatile(queue.add(index as usize), words) }, + 1_000_000, + ) +} + +/// Configure one DMA stream to translate only the supplied stream table's PTEs. +/// The linear stream table starts with every stream in abort mode. +/// +/// # Safety +/// All descriptor and queue pointers must address live, aligned, physically +/// contiguous RAM visible to the SMMU. `base` must be mapped device memory. +#[allow(clippy::too_many_arguments)] +pub unsafe fn configure_linear_stream( + regs: &mut MmioRegisters, + stream_id: u32, + stream_entries: u32, + stream_table: *mut [u64; 8], + command_entries: u32, + command_queue: *mut [u64; 2], + event_entries: u32, + event_queue: *mut [u64; 4], + context: *mut [u64; 8], + translation_root: u64, +) -> Result<(), Error> { + if stream_entries == 0 + || !stream_entries.is_power_of_two() + || stream_id >= stream_entries + || command_entries < 2 + || !command_entries.is_power_of_two() + || event_entries < 2 + || !event_entries.is_power_of_two() + || stream_table as usize & (stream_entries as usize * STE_BYTES - 1) != 0 + || command_queue as usize & 0x3f != 0 + || event_queue as usize & 0x3f != 0 + || context as usize & 0x3f != 0 + || translation_root & 0xfff != 0 + { + return Err(Error::InvalidWindow); + } + let sid_bits = stream_entries.trailing_zeros(); + if regs.read(IDR1) & IDR1_SIDSIZE_MASK < sid_bits { + return Err(Error::InvalidWindow); + } + let table = unsafe { core::slice::from_raw_parts_mut(stream_table, stream_entries as usize) }; + for entry in table.iter_mut() { + unsafe { core::ptr::write(entry, Ste::abort().0) }; + } + unsafe { + core::ptr::write( + context, + ContextDescriptor::stage1(translation_root, 1, 0x00ff, 16)?.0, + ); + core::ptr::write( + stream_table.add(stream_id as usize), + Ste::stage1(context as u64).0, + ); + } + + let gbpa = regs.read(GBPA); + regs.write(GBPA, gbpa | (1 << 20) | (1 << 31)); + for _ in 0..1_000_000 { + if regs.read(GBPA) & (1 << 31) == 0 { + break; + } + } + regs.write(CR0, 0); + wait_cr0(regs, 0, 1_000_000)?; + regs.write(CR1, 0x0d75); + regs.write64( + CMDQ_BASE, + command_queue as u64 | u64::from(command_entries.trailing_zeros()), + ); + regs.write(CMDQ_CONS, 0); + regs.write(CMDQ_PROD, 0); + regs.write64( + EVENTQ_BASE, + event_queue as u64 | u64::from(event_entries.trailing_zeros()), + ); + regs.write(EVENTQ_CONS, 0); + regs.write(EVENTQ_PROD, 0); + regs.write(STRTAB_BASE_CFG, sid_bits); + regs.write64(STRTAB_BASE, stream_table as u64); + regs.write(CR0, 0x0c); // CMDQEN | EVENTQEN; SMMUEN remains clear. + wait_cr0(regs, 0x0c, 1_000_000)?; + + let mut cursor = QueueCursor { + index: 0, + wrap: false, + }; + submit_raw( + regs, + &mut cursor, + command_entries, + command_queue, + command(CMD_CFGI_STE, stream_id, true), + )?; + submit_raw( + regs, + &mut cursor, + command_entries, + command_queue, + command(CMD_TLBI_NSNH_ALL, 0, false), + )?; + submit_raw( + regs, + &mut cursor, + command_entries, + command_queue, + command(CMD_SYNC, 0, false), + )?; + let gbpa = regs.read(GBPA); + regs.write(GBPA, (gbpa & !(1 << 20)) | (1 << 31)); + for _ in 0..1_000_000 { + if regs.read(GBPA) & (1 << 31) == 0 { + break; + } + } + regs.write(CR0, 0x0d); // SMMUEN | CMDQEN | EVENTQEN + wait_cr0(regs, 0x0d, 1_000_000) +} + fn wait_cr0(regs: &mut R, expected: u32, spins: usize) -> Result<(), Error> { for _ in 0..spins { - if regs.read(CR0ACK) & 1 == expected { + // CR0ACK mirrors the enabled queue and SMMU bits from CR0. + if regs.read(CR0ACK) & 0x0f == expected & 0x0f { return Ok(()); } } @@ -202,7 +380,7 @@ pub fn build_dma_policy( .map(window.iova, window.pa, window.length, MapFlags::KERNEL_DATA) .map_err(Error::PageTable)?; } - let cd = ContextDescriptor::stage1(table.root().0 as u64, asid, 0xff00, 16)?; + let cd = ContextDescriptor::stage1(table.root().0 as u64, asid, 0x00ff, 16)?; Ok(DmaPolicy { stream_id, ste: Ste::stage1(cd_address), @@ -257,15 +435,18 @@ mod tests { cd.0[0], 16 | (1 << 8) | (1 << 10) - | (2 << 12) + | (3 << 12) | (1 << 30) | (1 << 31) - | (0b101 << 32) + | (0b101_u64 << 32) | (1 << 41) + | (1 << 45) + | (1 << 46) | (0x1234_u64 << 48) ); - assert_eq!(cd.0[1], 0x4000); - assert_eq!(cd.0[3], 0xff00); + assert_eq!(cd.0[1], 0x4000, "TTBR0"); + assert_eq!(cd.0[2], 0, "TTBR1 unused (EPD1 set)"); + assert_eq!(cd.0[3], 0xff00, "MAIR"); } #[test] fn command_words_and_queue_wrap() { @@ -294,11 +475,8 @@ mod tests { let mut regs = Fake::default(); regs.values.insert(GBPA, 0); enable(&mut regs, 2).unwrap(); - assert_eq!( - ®s.writes[..3], - &[(GBPA, 1 | (1 << 31)), (CR0, 0), (CR0, 1)] - ); - assert_eq!(regs.values[&GBPA] & 1, 1); + assert_eq!(®s.writes[..3], &[(GBPA, 1 << 31), (CR0, 0), (CR0, 1)]); + assert_eq!(regs.values[&GBPA] & (1 << 20), 0); } #[test] fn policy_maps_only_allowed_windows() { diff --git a/crates/aienos-kernel/src/usb/xhci/controller.rs b/crates/aienos-kernel/src/usb/xhci/controller.rs index 6b8f865b..87bb20ff 100644 --- a/crates/aienos-kernel/src/usb/xhci/controller.rs +++ b/crates/aienos-kernel/src/usb/xhci/controller.rs @@ -84,7 +84,24 @@ pub enum Error { Unsupported(&'static str), Timeout(&'static str), HostSystemError, - Failed { step: &'static str, code: u8 }, + CommandTimeout { + step: &'static str, + command_addr: u64, + command_words: [u32; 4], + dcbaap: u64, + erstba: u64, + erstsz: u32, + crcr: u64, + erdp: u64, + usbcmd: u32, + usbsts: u32, + config: u32, + last_event: [u32; 4], + }, + Failed { + step: &'static str, + code: u8, + }, NoKeyboard, } @@ -94,6 +111,10 @@ impl fmt::Display for Error { Self::Absent => f.write_str("xHCI registers absent"), Self::Unsupported(what) => write!(f, "unsupported: {what}"), Self::Timeout(step) => write!(f, "timed out: {step}"), + Self::CommandTimeout { step, command_addr, command_words, crcr, erdp, usbcmd, usbsts, config, last_event, .. } => write!( + f, + "timed out: {step}; cmd@{command_addr:#x}={command_words:08x?}; CRCR={crcr:#x} ERDP={erdp:#x} USBCMD={usbcmd:#x} USBSTS={usbsts:#x} CONFIG={config:#x} last_event={last_event:08x?}" + ), Self::HostSystemError => f.write_str("host system error"), Self::Failed { step, code } => write!(f, "{step} failed (completion {code})"), Self::NoKeyboard => f.write_str("no boot keyboard on any connected port"), @@ -144,6 +165,7 @@ pub struct Keyboard { control: ProducerRing, reports: ProducerRing, slot: u8, + last_event: [u32; 4], dci: u8, port: u8, device: Option, @@ -215,6 +237,7 @@ impl Keyboard { device: None, retire_pending: false, halted: false, + last_event: [0; 4], }; keyboard.run()?; @@ -428,11 +451,30 @@ impl Keyboard { fn command(&mut self, trb: Trb, step: &'static str) -> Result { let addr = self.commands.push(trb); + let command_words = unsafe { read_volatile(addr as *const Trb) }.0; self.sync_to_device(); self.doorbell(0, 0); - let event = self.wait_event(step, |e| { - e.kind() == kind::COMMAND_COMPLETION && e.pointer() == addr - })?; + let event = self + .wait_event(step, |e| { + e.kind() == kind::COMMAND_COMPLETION && e.pointer() == addr + }) + .map_err(|error| match error { + Error::Timeout(_) => Error::CommandTimeout { + step, + command_addr: addr, + command_words, + dcbaap: unsafe { read_volatile((self.op + op::DCBAAP) as *const u64) }, + erstba: unsafe { read_volatile((self.rt + rt::ERSTBA) as *const u64) }, + erstsz: MmioReg::::new(self.rt + rt::ERSTSZ).read(), + crcr: unsafe { read_volatile((self.op + op::CRCR) as *const u64) }, + erdp: unsafe { read_volatile((self.rt + rt::ERDP) as *const u64) }, + usbcmd: self.op_reg(op::USBCMD).read(), + usbsts: self.op_reg(op::USBSTS).read(), + config: self.op_reg(op::CONFIG).read(), + last_event: self.last_event, + }, + other => other, + })?; match event.completion_code() { completion::SUCCESS => Ok(event), code => Err(Error::Failed { step, code }), @@ -542,6 +584,7 @@ impl Keyboard { self.sync_from_device(); while let Some(event) = self.events.pop() { self.retire_pending = true; + self.last_event = event.0; if wanted(&event) { self.retire(); return Ok(event); diff --git a/evidence/fix_m3_smmuv3_ste_cd_2026-09-24.md b/evidence/fix_m3_smmuv3_ste_cd_2026-09-24.md new file mode 100644 index 00000000..1a329bef --- /dev/null +++ b/evidence/fix_m3_smmuv3_ste_cd_2026-09-24.md @@ -0,0 +1,118 @@ +# Fix chain: SMMUv3 xHCI DMA confinement (branch fix/m3-smmuv3-ste-cd-layout) + +Base: 675d8c4 (forensic snapshot, branch wip/m3-smmu-c-bad-ste-635111c). +This note is appended to per commit; the original snapshot evidence is left +untouched in wip_m3_smmuv3_c_bad_ste_2026-09-24.md. + +## Commit 1: fix(smmu): runtime-align linear stream table for QEMU SMMUv3 + +### Build blocker (root cause) + +The snapshot tree did not build for aarch64-unknown-uefi. `cargo check` passes, +but the real `cargo build` traps rustc (SIGTRAP) in the COFF object writer. +A/B on the static alignment attribute: + + align(8192) BUILD OK + align(16384) SIGTRAP + align(262144) SIGTRAP + +COFF/PE cannot encode section alignment above 8192, so `repr(C, align(262144))` +on SMMU_TABLES was unbuildable. This is why the alignment fix had never been +re-run; the reported C_BAD_STE run came from the older align(4096) image. + +### Change + +- Removed `repr(C, align(262144))` from SMMU_TABLES. +- Allocate the tables at runtime: `Layout::from_size_align(size_of::(), + 262144)`, zeroed, cached in a shared `AtomicUsize`; one accessor + `smmu_tables()` feeds both the configure path and the fault-dump path. +- Kept 4096 stream table entries. +- Added explicit geometry asserts: table size == 262144, LOG2SIZE == 12, + SID < 4096, and the aligned base % 262144 == 0. + +### Verification + + cargo fmt --check OK + cargo build --release -p aienos-boot --target aarch64-unknown-uefi \ + --features usb-keyboard OK + +### QEMU result (AIENOS_QEMU_SMMU=1) + + smmu_ste: base=0xbbf40000 cfg=0xc sid=0x10 addr=0xbbf40400 words=[0xbbf8030b,0x0] + +- base 0xbbf40000 is 256 KiB aligned; cfg 0xc is LOG2SIZE=12, FMT=0 (linear). +- STE address == base + 0x10 * 64. STE is valid (V=1, Config=5, S1Fmt=0, + CTXPTR=0xbbf80300). +- C_BAD_STE (0x04) is eliminated. The next event was C_BAD_CD (0x0a): the STE + is accepted, the CD is fetched, and QEMU rejected the CD. + +## Commit 2: fix(smmu): correct AArch64 context descriptor layout + +### Root cause + +ContextDescriptor::stage1 placed the CD control fields one 64-bit word too +high. QEMU and Linux define them inside CD word 0: + + CD_0: T0SZ[5:0] TG0[7:6] IRGN0[9:8] ORGN0[11:10] SH0[13:12] EPD0[14] + ENDI[15] T1SZ[21:16] TG1[23:22] EPD1[30] V[31] IPS[34:32] + AA64[41] R[45] A[46] ASID[63:48] + CD_1: TTBR0 + CD_2: TTBR1 + CD_3: MAIR + +The old code put IPS/AA64/R/A/ASID in word 1 and TTBR0 in word 2, so QEMU read +CD_AARCH64=0 and CD_A=0 and rejected the descriptor (C_BAD_CD). It also set +word 0 bit 14 = EPD0, disabling the TTBR0 walk, and put MAIR in word 4. + +### Change + +- CD word 0 now holds T0SZ/TG0/IRGN0/ORGN0/SH0, EPD1, V, IPS, AA64, R, A and + ASID; EPD0 is clear so the TTBR0 stage-1 walk runs. +- CD word 1 is TTBR0, word 2 is TTBR1 (unused, EPD1 set), word 3 is MAIR. +- descriptor_layouts and policy_maps_only_allowed_windows updated to the new + layout (TTBR0 now cd.0[1], MAIR now cd.0[3]). + +Note: MAIR is CD word 3 per the SMMUv3 spec and Linux +(arm_smmu_write_ctx_desc writes cdptr[3] = cd->mair), not word 2. + +### Verification + + cargo fmt --check OK + cargo test -p aienos-kernel smmu 5 passed + cargo build --release -p aienos-boot --target aarch64-unknown-uefi \ + --features usb-keyboard OK + AIENOS_QEMU_TIMEOUT=90 bash scripts/qemu_smmu_test.sh QEMU_KEYBOARD: PASS + +### QEMU smmuv3 trace (config decoded once, then cached) + + smmuv3_get_ste STE addr: 0xbbf40400 + smmuv3_get_cd CD addr: 0xbbf80300 + smmuv3_decode_cd oas=44 + smmuv3_decode_cd_tt TT[0]:tsz:16 ttb:0xbc32f000 granule_sz:12 had:0 + smmuv3_translate_success 583 + smmuv3_config_cache_hit 582 + smmuv3_translate_disable 192 (pre-enable bypass) + smmuv3_get_ste / get_cd / decode_cd = 1 each (accepted, then cached) + no smmuv3_record_event, no fault events + +### AIENOS serial proof + + smmu: enabled base=0x9050000 stream_id=0x10 + smmu_dma_window: xhci only, translation active + keyboard: ready (port 5, slot 1, endpoint 0x81) + keyboard_echo: abc / help / el / mem / exit + keyboard: done (exit) + +### Acceptance progression + + C_BAD_STE gone PROVEN + C_BAD_CD gone PROVEN + CD accepted PROVEN + stage-1 PT walk reached PROVEN (TT[0] tsz16 granule12, 583 translate_success) + DMA translation succeeds PROVEN + xHCI Enable Slot completes PROVEN (keyboard: ready) + keyboard attaches PROVEN + typed-input proof PROVEN (keyboard_echo: abc ... exit) + +SMMUv3 DMA confinement for the xHCI controller is now demonstrated in QEMU. +Emulator only; this says nothing about Machine 1 hardware. diff --git a/evidence/smmu_qemu_pass_raw_2026-09-24.md b/evidence/smmu_qemu_pass_raw_2026-09-24.md new file mode 100644 index 00000000..7618a2d1 --- /dev/null +++ b/evidence/smmu_qemu_pass_raw_2026-09-24.md @@ -0,0 +1,79 @@ +# Raw evidence: SMMUv3 xHCI DMA confinement PASS in QEMU + +Commit under test: c2cf564 (fix/m3-smmuv3-ste-cd-layout) +Environment: spark-b87b, QEMU 8.2.2 (Debian 1:8.2.2+ds-0ubuntu1.18), +rustc 1.98.1 (48a229cea 2026-09-01). + +## Exact successful invocations + + # standard acceptance run + AIENOS_QEMU_TIMEOUT=90 bash scripts/qemu_smmu_test.sh + + # verbose capture (serial console + QEMU smmuv3 trace) + AIENOS_QEMU_VERBOSE=1 AIENOS_QEMU_SMMU_TRACE=1 AIENOS_QEMU_TIMEOUT=90 \ + bash scripts/qemu_smmu_test.sh + +Both exited 0 and ended with "QEMU_KEYBOARD: PASS". + +## Full raw logs (sha256, on the run host) + + 075457e5f33f55d99f66ba0d4a6ddec8c20f17801a37fa54ebb088886938552e smmu_verbose.log (1633 lines) + cd3102654313d43e87ee379132f7811f9e5551be26213ac1262d59e133ea1c5c smmu_pass.log (23 lines) + +## QEMU smmuv3 trace: command queue, STE, CD, config decode + + smmuv3_cmdq_opcode <--- SMMU_CMD_CFGI_STE + smmuv3_cmdq_cfgi_ste streamid= 0x10 + smmuv3_config_cache_inv Config cache INV for sid=0x10 + smmuv3_cmdq_opcode <--- SMMU_CMD_TLBI_NSNH_ALL + smmuv3_cmdq_tlbi_nh + smmuv3_cmdq_opcode <--- SMMU_CMD_SYNC + smmuv3_config_cache_miss Config cache MISS for sid=0x10 (hits=0, misses=1, hit rate=0) + smmuv3_find_ste sid=0x10 features:0x0, sid_split:0x0 + smmuv3_get_ste STE addr: 0xbbf40400 + smmuv3_get_cd CD addr: 0xbbf80300 + smmuv3_decode_cd oas=44 + smmuv3_decode_cd_tt TT[0]:tsz:16 ttb:0xbc32f000 granule_sz:12 had:0 + +## QEMU smmuv3 trace: event counts + + 583 smmuv3_translate_success + 582 smmuv3_config_cache_hit + 192 smmuv3_translate_disable (pre-enable bypass) + 1 smmuv3_get_ste + 1 smmuv3_get_cd + 1 smmuv3_decode_cd + 1 smmuv3_config_cache_miss + 1 smmuv3_config_cache_inv + 1 smmuv3_cmdq_cfgi_ste + 1 smmuv3_cmdq_tlbi_nh + 0 smmuv3_record_event + 0 fault events + +## AIENOS serial console (raw lines) + + kernel_el: EL1h + mmu: enabled + smmu: enabled base=0x9050000 stream_id=0x10 + smmu_dma_window: xhci only, translation active + keyboard: xhci 0000:00:02.0 mmio 0x8000004000 + keyboard: ready (port 5, slot 1, endpoint 0x81) + keyboard_echo: abc + keyboard_line: abc + keyboard: done (enter) + keyboard_echo: help + keyboard_line: help + keyboard: done (enter) + keyboard_echo: el + keyboard_line: el + keyboard: done (enter) + keyboard_echo: mem + keyboard_line: mem + keyboard: done (enter) + keyboard_echo: exit + keyboard_line: exit + keyboard: done (exit) + +## Script verdict + + QEMU_KEYBOARD: PASS diff --git a/scripts/qemu_keyboard_test.sh b/scripts/qemu_keyboard_test.sh index d48de561..24aa12c2 100755 --- a/scripts/qemu_keyboard_test.sh +++ b/scripts/qemu_keyboard_test.sh @@ -24,12 +24,24 @@ keys=(a b c) expected="abc" attempts="${AIENOS_KEYBOARD_ATTEMPTS:-3}" boot_timeout="${AIENOS_QEMU_TIMEOUT:-180}" +machine="virt,virtualization=on,gic-version=3" +if [[ "${AIENOS_QEMU_SMMU:-0}" == "1" ]]; then + machine+=",iommu=smmuv3" +fi + +# Without an SMMU the keyboard capability is fail-closed, so the identity-DMA +# path is only reachable behind the debug bypass feature. The confined path is +# covered by qemu_smmu_test.sh (AIENOS_QEMU_SMMU=1). +default_features="usb-keyboard" +if [[ "${AIENOS_QEMU_SMMU:-0}" != "1" ]]; then + default_features="usb-keyboard,debug-xhci-without-smmu" +fi # Own target directory: a keyboard-enabled image never lands where hardware # staging or the other tests pick up the handoff image. commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" AIENOS_COMMIT="${commit}" AIENOS_RESTART_SECS=1 AIENOS_KEYBOARD_SECS=60 cargo build --quiet --release \ - -p aienos-boot --target aarch64-unknown-uefi --features usb-keyboard --bin aienos-handoff \ + -p aienos-boot --target aarch64-unknown-uefi --features "${AIENOS_BUILD_FEATURES:-$default_features}" --bin aienos-handoff \ --target-dir target/qemu-keyboard work="$(mktemp -d)" @@ -73,8 +85,13 @@ boot_once() { mkfifo "${work}/mon.in" "${work}/mon.out" # Single-threaded TCG: multi-threaded TCG intermittently loses the # firmware's timer wake-up and hangs before AIENOS output (#61). + local -a smmu_trace=() + if [[ "${AIENOS_QEMU_SMMU_TRACE:-0}" == "1" ]]; then + smmu_trace=(-d unimp,guest_errors -trace "smmuv3_*") + fi qemu-system-aarch64 \ - -M virt,virtualization=on,gic-version=3 -accel tcg,thread=single -cpu max -smp 4 -m 2048 \ + "${smmu_trace[@]}" \ + -M "${machine}" -accel tcg,thread=single -cpu max -smp 4 -m 2048 \ -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ -drive if=pflash,format=raw,file="${work}/vars.fd" \ -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \ @@ -138,6 +155,10 @@ echo "attempts ${attempt}, ${elapsed} s (commit ${commit:0:12}), sent lines: abc check "left firmware and entered the kernel" "kernel: alive" check "xHCI controller found before exit" "keyboard: xhci " check "keyboard attached by the AIENOS driver" "keyboard: ready" +if [[ "${AIENOS_QEMU_SMMU:-0}" == "1" ]]; then + check "IORT stream configured for xHCI DMA" "smmu: enabled" + check "xHCI DMA window translated" "smmu_dma_window: xhci only, translation active" +fi check "typed text echoed on the serial console" "keyboard_echo: ${expected}" check "line ended by Enter and reported" "keyboard_line: ${expected}\$" check "keyboard phase finished on Enter" "keyboard: done (enter)" diff --git a/scripts/qemu_smmu_test.sh b/scripts/qemu_smmu_test.sh new file mode 100755 index 00000000..1714faf4 --- /dev/null +++ b/scripts/qemu_smmu_test.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Exercise IORT discovery, SMMUv3 translation and real xHCI keyboard DMA. +set -euo pipefail +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" +AIENOS_QEMU_SMMU=1 exec bash scripts/qemu_keyboard_test.sh diff --git a/scripts/verify_all.sh b/scripts/verify_all.sh index ee0e7460..9dea907f 100755 --- a/scripts/verify_all.sh +++ b/scripts/verify_all.sh @@ -61,6 +61,7 @@ echo "" echo "--- [SEED-0A USB Keyboard in QEMU (input.keyboard.usb)] ---" if command -v qemu-system-aarch64 >/dev/null && [[ -r "${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" ]]; then ./scripts/qemu_keyboard_test.sh + ./scripts/qemu_smmu_test.sh else echo "SKIPPED: qemu-system-aarch64 or AAVMF firmware not present on host." fi ```