From a2fefc28df2ef6f7de37ba192c9faf1decaad8fe Mon Sep 17 00:00:00 2001 From: Drake Date: Thu, 24 Sep 2026 09:38:39 -0500 Subject: [PATCH 1/4] kernel(usb): xHCI rings and input contexts (SEED-0A input.keyboard.usb, part 2b) Stacked on part 2a. Host-tested ring and context bookkeeping for the polled xHCI keyboard driver (xHCI 1.2 sections 4.9 and 6.2): - ProducerRing (command and transfer rings): Link TRB with Toggle Cycle in the last slot, handed to the controller only when the producer reaches it; TRB dwords 0-2 written before the cycle dword with a barrier between. A test models the controller consuming the ring across many wraps. - EventRing: single segment, no Link TRB, consumer wraps at the segment end and flips its cycle state; ERST entry and ERDP value helpers. - InputContext: input control, slot and endpoint contexts for 32- and 64-byte context sizes; interval conversion for full/low vs high/super speed; endpoint address to device context index. Fixes against the draft on seed0a/xhci-keyboard-driver: the event ring wrapped one TRB early (as if it had a Link TRB); the slot context put the root port number in dword 0 (route string) instead of dword 1 bits 23:16; endpoint context fields were written at byte offsets 0x41/0x44 so CErr landed in the wrong dword; the interrupt endpoint had no Interval. Co-authored-by: Drake Co-Authored-By: Claude Opus 5.5 --- crates/aienos-kernel/src/usb/xhci/context.rs | 226 ++++++++++++++++ crates/aienos-kernel/src/usb/xhci/mod.rs | 2 + crates/aienos-kernel/src/usb/xhci/ring.rs | 271 +++++++++++++++++++ 3 files changed, 499 insertions(+) create mode 100644 crates/aienos-kernel/src/usb/xhci/context.rs create mode 100644 crates/aienos-kernel/src/usb/xhci/ring.rs diff --git a/crates/aienos-kernel/src/usb/xhci/context.rs b/crates/aienos-kernel/src/usb/xhci/context.rs new file mode 100644 index 00000000..68a96e20 --- /dev/null +++ b/crates/aienos-kernel/src/usb/xhci/context.rs @@ -0,0 +1,226 @@ +//! Input contexts for Address Device, Evaluate Context and Configure +//! Endpoint (xHCI 1.2 section 6.2), plus the speed and interval rules the +//! driver needs to fill them. +//! +//! An input context is an Input Control Context followed by a Slot Context +//! and one Endpoint Context per device context index (DCI 1 is the default +//! control endpoint). Each is 32 bytes, or 64 when HCCPARAMS1.CSZ is set. + +/// Port speed IDs from PORTSC (default Protocol Speed ID mapping). +pub mod speed { + pub const FULL: u8 = 1; + pub const LOW: u8 = 2; + pub const HIGH: u8 = 3; + pub const SUPER: u8 = 4; +} + +/// Endpoint Context EP Type values. +pub const EP_TYPE_CONTROL: u8 = 4; +pub const EP_TYPE_INTERRUPT_IN: u8 = 7; +/// Error count: retry a failing transaction three times before halting. +const CERR: u32 = 3; +/// Device context index of the default control endpoint. +pub const CONTROL_DCI: u8 = 1; +/// Highest device context index. +const MAX_DCI: u8 = 31; + +/// Default control endpoint packet size before the device descriptor is read. +pub fn default_control_max_packet(port_speed: u8) -> u16 { + match port_speed { + speed::HIGH => 64, + s if s >= speed::SUPER => 512, + _ => 8, + } +} + +/// Endpoint Context Interval (period 125 us * 2^n) for an interrupt +/// endpoint's bInterval. Full and low speed give bInterval in 1 ms frames; +/// high and super speed already give it as 2^(bInterval - 1) microframes. +pub fn interrupt_interval(port_speed: u8, b_interval: u8) -> u8 { + match port_speed { + speed::FULL | speed::LOW => { + let microframes = u32::from(b_interval.max(1)) * 8; + (31 - microframes.leading_zeros()).clamp(3, 10) as u8 + } + _ => b_interval.clamp(1, 16) - 1, + } +} + +/// Device context index for a non-control endpoint address such as 0x81. +pub fn endpoint_dci(endpoint_address: u8) -> Option { + let number = endpoint_address & 0x0f; + if number == 0 { + return None; + } + Some(number * 2 + u8::from(endpoint_address & 0x80 != 0)) +} + +/// What one Endpoint Context says. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EndpointConfig { + pub ep_type: u8, + pub max_packet: u16, + pub interval: u8, + /// TR Dequeue Pointer with the Dequeue Cycle State in bit 0. + pub dequeue: u64, + pub average_trb_length: u16, + pub max_esit_payload: u16, +} + +/// An input context being filled in caller-owned, zeroed memory. +pub struct InputContext<'a> { + words: &'a mut [u32], + stride: usize, +} + +impl<'a> InputContext<'a> { + /// Zero `words` and lay out an input context with `context_bytes`-sized + /// entries. `None` for a size other than 32 or 64 or too little memory. + pub fn new(words: &'a mut [u32], context_bytes: usize) -> Option { + let stride = match context_bytes { + 32 => 8, + 64 => 16, + _ => return None, + }; + // Input control context, slot context and 31 endpoint contexts. + if words.len() < stride * (usize::from(MAX_DCI) + 2) { + return None; + } + words.fill(0); + Some(Self { words, stride }) + } + + fn entry(&mut self, index: usize) -> &mut [u32] { + let start = index * self.stride; + &mut self.words[start..start + 8] + } + + /// Add Context flags: bit 0 the slot context, bit n the endpoint of DCI n. + pub fn add(&mut self, flags: u32) { + self.entry(0)[1] = flags; + } + + /// Slot Context for a device on root hub port `root_port` (1-based, no + /// hub route) whose highest valid endpoint is `context_entries`. + pub fn slot(&mut self, port_speed: u8, root_port: u8, context_entries: u8) { + let slot = self.entry(1); + slot[0] = u32::from(context_entries & 0x1f) << 27 | u32::from(port_speed & 0xf) << 20; + slot[1] = u32::from(root_port) << 16; + } + + /// Endpoint Context for `dci` (1..=31); other indexes are ignored. + pub fn endpoint(&mut self, dci: u8, config: &EndpointConfig) { + if !(1..=MAX_DCI).contains(&dci) { + return; + } + let ep = self.entry(usize::from(dci) + 1); + ep[0] = u32::from(config.interval) << 16; + ep[1] = + CERR << 1 | u32::from(config.ep_type & 0x7) << 3 | u32::from(config.max_packet) << 16; + ep[2] = config.dequeue as u32; + ep[3] = (config.dequeue >> 32) as u32; + ep[4] = u32::from(config.average_trb_length) | u32::from(config.max_esit_payload) << 16; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn interval_converts_frames_and_exponents_to_125us_units() { + // QEMU usb-kbd: full speed, bInterval 7 ms -> 56 microframes -> 2^5. + assert_eq!(interrupt_interval(speed::FULL, 7), 5); + assert_eq!(interrupt_interval(speed::FULL, 10), 6); + assert_eq!(interrupt_interval(speed::LOW, 1), 3); + assert_eq!(interrupt_interval(speed::FULL, 255), 10); + assert_eq!(interrupt_interval(speed::FULL, 0), 3); + assert_eq!(interrupt_interval(speed::HIGH, 4), 3); + assert_eq!(interrupt_interval(speed::SUPER, 0), 0); + assert_eq!(interrupt_interval(speed::HIGH, 200), 15); + } + + #[test] + fn endpoint_addresses_map_to_device_context_indexes() { + assert_eq!(endpoint_dci(0x81), Some(3)); + assert_eq!(endpoint_dci(0x82), Some(5)); + assert_eq!(endpoint_dci(0x01), Some(2)); + assert_eq!(endpoint_dci(0x8f), Some(31)); + assert_eq!(endpoint_dci(0x80), None); + assert_eq!(default_control_max_packet(speed::LOW), 8); + assert_eq!(default_control_max_packet(speed::HIGH), 64); + assert_eq!(default_control_max_packet(speed::SUPER), 512); + } + + #[test] + fn address_device_context_puts_port_and_endpoint_zero_in_place() { + let mut words = [0xdead_beef_u32; 8 * 33]; + let mut input = InputContext::new(&mut words, 32).unwrap(); + input.add(0b11); + input.slot(speed::FULL, 5, 1); + input.endpoint( + CONTROL_DCI, + &EndpointConfig { + ep_type: EP_TYPE_CONTROL, + max_packet: 8, + interval: 0, + dequeue: 0x4000_1000 | 1, + average_trb_length: 8, + max_esit_payload: 0, + }, + ); + assert_eq!(words[1], 0b11, "add flags in the input control context"); + assert_eq!(words[0], 0, "no drop flags"); + // Slot context at 0x20: entries 1, full speed; root port in dword 1. + assert_eq!(words[8], 1 << 27 | 1 << 20); + assert_eq!(words[9], 5 << 16); + // Endpoint 0 context at 0x40: CErr 3, type control, max packet 8. + assert_eq!(words[17], 3 << 1 | 4 << 3 | 8 << 16); + assert_eq!([words[18], words[19]], [0x4000_1001, 0]); + assert_eq!(words[20], 8); + assert!(words[21..].iter().all(|w| *w == 0), "memory was zeroed"); + } + + #[test] + fn large_contexts_double_the_stride_and_bad_sizes_are_refused() { + let mut words = [0u32; 16 * 33]; + let mut input = InputContext::new(&mut words, 64).unwrap(); + input.slot(speed::HIGH, 2, 3); + input.endpoint( + 3, + &EndpointConfig { + ep_type: EP_TYPE_INTERRUPT_IN, + max_packet: 8, + interval: 6, + dequeue: 0x2_0000_0001, + average_trb_length: 8, + max_esit_payload: 8, + }, + ); + input.endpoint( + 0, + &EndpointConfig { + ep_type: 0, + max_packet: 0, + interval: 0, + dequeue: u64::MAX, + average_trb_length: 0, + max_esit_payload: 0, + }, + ); + assert_eq!(words[16], 3 << 27 | 3 << 20); + assert_eq!(words[17], 2 << 16); + let ep = 16 * 4; // DCI 3 is entry 4 + assert_eq!(words[ep], 6 << 16); + assert_eq!(words[ep + 1], 3 << 1 | 7 << 3 | 8 << 16); + assert_eq!([words[ep + 2], words[ep + 3]], [1, 2]); + assert_eq!(words[ep + 4], 8 | 8 << 16); + assert_eq!( + words[18..32], + [0; 14], + "DCI 0 did not overwrite the slot context" + ); + assert!(InputContext::new(&mut words, 48).is_none()); + assert!(InputContext::new(&mut words[..100], 32).is_none()); + } +} diff --git a/crates/aienos-kernel/src/usb/xhci/mod.rs b/crates/aienos-kernel/src/usb/xhci/mod.rs index 1600bcd6..280f51be 100644 --- a/crates/aienos-kernel/src/usb/xhci/mod.rs +++ b/crates/aienos-kernel/src/usb/xhci/mod.rs @@ -2,4 +2,6 @@ //! driver, host-tested against the xHCI 1.2 specification. Register access //! and controller bring-up come later in the series and build on these. +pub mod context; +pub mod ring; pub mod trb; diff --git a/crates/aienos-kernel/src/usb/xhci/ring.rs b/crates/aienos-kernel/src/usb/xhci/ring.rs new file mode 100644 index 00000000..03088afb --- /dev/null +++ b/crates/aienos-kernel/src/usb/xhci/ring.rs @@ -0,0 +1,271 @@ +//! Command, transfer and event rings (xHCI 1.2 section 4.9). +//! +//! A producer ring (command or transfer) is written by software and consumed +//! by the controller; its last slot holds a Link TRB back to the start with +//! Toggle Cycle set. An event ring is written by the controller and consumed +//! by software; it has no Link TRB, so the consumer wraps and flips its cycle +//! state at the end of the single segment. +//! +//! Ownership of each TRB is carried by its cycle bit. The producer writes +//! dwords 0 to 2 first and the dword holding the cycle bit last, with a +//! barrier between, so the controller never sees a half-written TRB as valid. +//! The consumer reads the cycle bit first and the rest only after a barrier. +//! Cache maintenance for non-coherent DMA is the caller's job. + +use super::trb::{Trb, CYCLE}; +use crate::arch::aarch64::dmb; +use core::ptr::{read_volatile, write_volatile}; + +const TRB_BYTES: u64 = 16; + +/// Software-produced ring (command ring or one endpoint's transfer ring). +/// +/// The driver waits for each command or transfer to complete before pushing +/// the next, so the ring can never lap the controller. +pub struct ProducerRing { + base: *mut Trb, + len: usize, + dma: u64, + enqueue: usize, + cycle: bool, +} + +impl ProducerRing { + /// Take over `len` TRBs at `base`, zero them and install the Link TRB. + /// `None` when the ring is too short to hold a TRB and its link. + /// + /// # Safety + /// `base` must be valid for reads and writes of `len` TRBs for as long as + /// the ring is used, not accessed through any other path meanwhile, and + /// `dma` must be the controller-visible address of `base`. + pub unsafe fn new(base: *mut Trb, len: usize, dma: u64) -> Option { + if len < 2 { + return None; + } + for i in 0..len { + // SAFETY: in bounds by the caller's contract. + unsafe { write_volatile(base.add(i), Trb::default()) }; + } + // The link starts with cycle 0: the controller (cycle 1) must not + // follow it until the producer reaches it and hands it over. + // SAFETY: `len - 1` is in bounds. + unsafe { write_volatile(base.add(len - 1), Trb::link(dma)) }; + Some(Self { + base, + len, + dma, + enqueue: 0, + cycle: true, + }) + } + + /// Controller-visible address of the ring start. + pub fn dma(&self) -> u64 { + self.dma + } + + /// Enqueue pointer with the producer cycle state in bit 0, the format of + /// CRCR and of an endpoint context's TR Dequeue Pointer. + pub fn dequeue_pointer(&self) -> u64 { + (self.dma + self.enqueue as u64 * TRB_BYTES) | u64::from(self.cycle) + } + + /// Write `trb` at the enqueue slot, owned by the controller, and return + /// its controller-visible address (events name completed TRBs by it). + pub fn push(&mut self, trb: Trb) -> u64 { + let addr = self.dma + self.enqueue as u64 * TRB_BYTES; + self.write_owned(self.enqueue, trb); + self.enqueue += 1; + if self.enqueue == self.len - 1 { + // SAFETY: the link slot is in bounds. + let link = unsafe { read_volatile(self.base.add(self.len - 1)) }; + self.write_owned(self.len - 1, link); + self.enqueue = 0; + self.cycle = !self.cycle; + } + addr + } + + fn write_owned(&mut self, index: usize, trb: Trb) { + let trb = trb.with_cycle(self.cycle); + // SAFETY: `index < len` at every call site. + let slot = unsafe { self.base.add(index) } as *mut u32; + for i in 0..3 { + // SAFETY: dwords 0..3 of an in-bounds TRB. + unsafe { write_volatile(slot.add(i), trb.0[i]) }; + } + dmb(); + // SAFETY: dword 3 of the same TRB. + unsafe { write_volatile(slot.add(3), trb.0[3]) }; + } +} + +/// Controller-produced event ring of one segment. +pub struct EventRing { + base: *const Trb, + len: usize, + dma: u64, + dequeue: usize, + cycle: bool, +} + +impl EventRing { + /// Take over `len` TRBs at `base` and zero them. `None` when empty. + /// + /// # Safety + /// As for [`ProducerRing::new`]: `base` valid for `len` TRBs for the + /// ring's lifetime, written only by the controller afterwards, and `dma` + /// its controller-visible address. + pub unsafe fn new(base: *mut Trb, len: usize, dma: u64) -> Option { + if len == 0 || len > u16::MAX as usize { + return None; + } + for i in 0..len { + // SAFETY: in bounds by the caller's contract. + unsafe { write_volatile(base.add(i), Trb::default()) }; + } + Some(Self { + base, + len, + dma, + dequeue: 0, + cycle: true, + }) + } + + /// The single Event Ring Segment Table entry describing this ring. + pub fn segment_table_entry(&self) -> [u32; 4] { + [self.dma as u32, (self.dma >> 32) as u32, self.len as u32, 0] + } + + /// Address of the next event to consume, the value for ERDP. + pub fn dequeue_pointer(&self) -> u64 { + self.dma + self.dequeue as u64 * TRB_BYTES + } + + /// The next event, if the controller has written one. + pub fn pop(&mut self) -> Option { + // SAFETY: `dequeue < len`, in bounds by the constructor's contract. + let slot = unsafe { self.base.add(self.dequeue) } as *const u32; + // SAFETY: dword 3 of an in-bounds TRB. + let control = unsafe { read_volatile(slot.add(3)) }; + if (control & CYCLE != 0) != self.cycle { + return None; + } + dmb(); + let mut trb = Trb([0, 0, 0, control]); + for i in 0..3 { + // SAFETY: dwords 0..3 of the same TRB. + trb.0[i] = unsafe { read_volatile(slot.add(i)) }; + } + self.dequeue += 1; + if self.dequeue == self.len { + self.dequeue = 0; + self.cycle = !self.cycle; + } + Some(trb) + } +} + +#[cfg(test)] +mod tests { + use super::super::trb::{kind, TOGGLE_CYCLE}; + use super::*; + + /// Minimal model of the controller consuming a producer ring: follow + /// TRBs while their cycle bit matches, obey Link TRBs and Toggle Cycle. + struct Consumer { + index: usize, + cycle: bool, + } + + impl Consumer { + fn take(&mut self, ring: &[Trb]) -> Option { + loop { + let trb = ring[self.index]; + if trb.cycle() != self.cycle { + return None; + } + if trb.kind() == kind::LINK { + assert_eq!(trb.pointer(), ring.as_ptr() as u64, "link targets start"); + if trb.0[3] & TOGGLE_CYCLE != 0 { + self.cycle = !self.cycle; + } + self.index = 0; + continue; + } + self.index += 1; + return Some(trb); + } + } + } + + #[test] + fn controller_sees_every_push_in_order_across_many_wraps() { + let mut memory = [Trb::default(); 4]; + let dma = memory.as_ptr() as u64; + // SAFETY: `memory` outlives the ring and is only read below. + let mut ring = unsafe { ProducerRing::new(memory.as_mut_ptr(), 4, dma) }.unwrap(); + let mut consumer = Consumer { + index: 0, + cycle: true, + }; + assert!(consumer.take(&memory).is_none(), "fresh ring is empty"); + for n in 0..20u32 { + let expected = dma + 16 * (n as u64 % 3); + assert_eq!( + ring.push(Trb([n, 0, 0, u32::from(kind::NORMAL) << 10])), + expected + ); + let seen = consumer.take(&memory).expect("pushed TRB is visible"); + assert_eq!(seen.0[0], n); + assert!(consumer.take(&memory).is_none(), "nothing beyond the push"); + } + } + + #[test] + fn dequeue_pointer_carries_the_cycle_state_and_flips_after_the_link() { + let mut memory = [Trb::default(); 3]; + let dma = memory.as_ptr() as u64; + // SAFETY: as above. + let mut ring = unsafe { ProducerRing::new(memory.as_mut_ptr(), 3, dma) }.unwrap(); + assert_eq!(ring.dequeue_pointer(), dma | 1); + ring.push(Trb::default()); + assert_eq!(ring.dequeue_pointer(), (dma + 16) | 1); + ring.push(Trb::default()); + assert_eq!(ring.dequeue_pointer(), dma, "wrapped with cycle 0"); + assert!(memory[2].cycle(), "link handed over with the old cycle"); + assert!(unsafe { ProducerRing::new(memory.as_mut_ptr(), 1, dma) }.is_none()); + } + + #[test] + fn event_ring_consumes_matching_cycles_and_wraps_without_a_link() { + let mut memory = [Trb::default(); 3]; + let dma = memory.as_ptr() as u64; + // SAFETY: the test plays the controller through `base` only. + let base = memory.as_mut_ptr(); + let mut ring = unsafe { EventRing::new(base, 3, dma) }.unwrap(); + assert_eq!( + ring.segment_table_entry(), + [dma as u32, (dma >> 32) as u32, 3, 0] + ); + let post = |i: usize, id: u32, cycle: bool| unsafe { + base.add(i) + .write_volatile(Trb([id, 0, 1 << 24, 33 << 10]).with_cycle(cycle)); + }; + assert!(ring.pop().is_none()); + for (i, id) in [(0, 10), (1, 11), (2, 12)] { + post(i, id, true); + } + assert_eq!(ring.pop().unwrap().0[0], 10); + assert_eq!(ring.dequeue_pointer(), dma + 16); + assert_eq!(ring.pop().unwrap().0[0], 11); + assert_eq!(ring.pop().unwrap().0[0], 12); + assert_eq!(ring.dequeue_pointer(), dma, "wrapped at the segment end"); + // Old events (cycle 1) are not consumed twice after the wrap. + assert!(ring.pop().is_none()); + post(0, 13, false); + assert_eq!(ring.pop().unwrap().0[0], 13); + assert!(ring.pop().is_none()); + } +} From 3ea3af09fee5acf2e195b2ab341de8a927c83ac5 Mon Sep 17 00:00:00 2001 From: Drake Date: Thu, 24 Sep 2026 09:43:35 -0500 Subject: [PATCH 2/4] kernel(usb): add xHCI discovery and keyboard descriptors (SEED-0A 2c) --- crates/aienos-kernel/src/acpi.rs | 80 ++++++ crates/aienos-kernel/src/arch/aarch64.rs | 53 ++++ crates/aienos-kernel/src/usb/descriptor.rs | 164 +++++++++++++ crates/aienos-kernel/src/usb/mod.rs | 6 +- crates/aienos-kernel/src/usb/xhci/mod.rs | 270 ++++++++++++++++++++- 5 files changed, 568 insertions(+), 5 deletions(-) create mode 100644 crates/aienos-kernel/src/usb/descriptor.rs diff --git a/crates/aienos-kernel/src/acpi.rs b/crates/aienos-kernel/src/acpi.rs index 3a0ed54a..89e43761 100644 --- a/crates/aienos-kernel/src/acpi.rs +++ b/crates/aienos-kernel/src/acpi.rs @@ -259,6 +259,50 @@ pub fn madt_cpu_topology_for( Ok(topo) } +/// MCFG allocations start after the header and 8 reserved bytes. +const MCFG_ENTRIES_OFFSET: usize = 44; +const MCFG_ENTRY_LEN: usize = 16; + +/// One PCI Express enhanced configuration (ECAM) window from the MCFG table. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EcamWindow { + pub base: u64, + pub segment: u16, + pub start_bus: u8, + pub end_bus: u8, +} + +impl EcamWindow { + /// Address of config register `offset` of `bus:device.function`, or + /// `None` outside this window or the 4 KiB function space. + pub fn config_address(&self, bus: u8, device: u8, function: u8, offset: u16) -> Option { + let in_window = (self.start_bus..=self.end_bus).contains(&bus); + if !in_window || device > 31 || function > 7 || offset > 0xfff { + return None; + } + let bus = u64::from(bus - self.start_bus); + let function_offset = u64::from(device) << 15 | u64::from(function) << 12; + Some(self.base + (bus << 20 | function_offset | u64::from(offset))) + } +} + +/// The ECAM window of a validated MCFG table covering `segment` and `bus`. +pub fn mcfg_window(mcfg: &[u8], segment: u16, bus: u8) -> Result, AcpiError> { + let mcfg = checked_table(mcfg, b"MCFG")?; + let entries = mcfg.get(MCFG_ENTRIES_OFFSET..).ok_or(AcpiError::Truncated)?; + Ok(entries + .as_chunks::() + .0 + .iter() + .map(|e| EcamWindow { + base: u64_at(e, 0).unwrap_or(0), + segment: u16::from_le_bytes([e[8], e[9]]), + start_bus: e[10], + end_bus: e[11], + }) + .find(|w| w.segment == segment && (w.start_bus..=w.end_bus).contains(&bus))) +} + #[cfg(test)] mod tests { use super::*; @@ -422,6 +466,42 @@ mod tests { assert_eq!(spcr_console(&bad), Err(AcpiError::BadChecksum)); } + fn mcfg(windows: &[(u64, u16, u8, u8)]) -> Vec { + let mut t = std::vec![0u8; MCFG_ENTRIES_OFFSET]; + t[..4].copy_from_slice(b"MCFG"); + for (base, segment, start, end) in windows { + t.extend_from_slice(&base.to_le_bytes()); + t.extend_from_slice(&segment.to_le_bytes()); + t.extend_from_slice(&[*start, *end, 0, 0, 0, 0]); + } + let len = t.len() as u32; + t[4..8].copy_from_slice(&len.to_le_bytes()); + let sum = t.iter().fold(0u8, |s, b| s.wrapping_add(*b)); + t[9] = 0u8.wrapping_sub(sum); + t + } + + #[test] + fn mcfg_finds_the_ecam_window_for_a_segment_and_bus() { + // QEMU virt high ECAM, plus a second segment starting at bus 0x80. + let table = mcfg(&[(0x40_1000_0000, 0, 0, 0xff), (0x6000_0000, 1, 0x80, 0x8f)]); + let qemu = mcfg_window(&table, 0, 0).unwrap().unwrap(); + assert_eq!(qemu.base, 0x40_1000_0000); + assert_eq!(qemu.config_address(0, 2, 0, 0x04), Some(0x40_1001_0004)); + let second = mcfg_window(&table, 1, 0x81).unwrap().unwrap(); + // Bus numbers count from the window's start bus. + assert_eq!(second.config_address(0x81, 1, 3, 0x10), Some(0x6010_b010)); + assert_eq!(second.config_address(0x90, 0, 0, 0), None, "past end bus"); + assert_eq!(second.config_address(0x80, 32, 0, 0), None); + assert_eq!(second.config_address(0x80, 0, 8, 0), None); + assert_eq!(second.config_address(0x80, 0, 0, 0x1000), None); + assert_eq!(mcfg_window(&table, 1, 0x7f).unwrap(), None); + assert_eq!(mcfg_window(&table, 2, 0).unwrap(), None); + let mut bad = table.clone(); + bad[50] ^= 1; + assert_eq!(mcfg_window(&bad, 0, 0), Err(AcpiError::BadChecksum)); + } + #[test] fn reads_xsdt_entry_addresses() { let mut xsdt = std::vec![0u8; SDT_HEADER_LEN]; diff --git a/crates/aienos-kernel/src/arch/aarch64.rs b/crates/aienos-kernel/src/arch/aarch64.rs index bef08b2d..a294f891 100644 --- a/crates/aienos-kernel/src/arch/aarch64.rs +++ b/crates/aienos-kernel/src/arch/aarch64.rs @@ -172,6 +172,59 @@ pub fn isb() { } } +/// Smallest data cache line in bytes, from CTR_EL0.DminLine (log2 of the +/// line size in 4-byte words). Maintenance loops must step by this, never by +/// a guess: `dc` acts on the one line holding the address it is given. +pub fn dcache_line_bytes() -> usize { + #[cfg(target_arch = "aarch64")] + { + let ctr: u64; + unsafe { + core::arch::asm!("mrs {0}, ctr_el0", out(reg) ctr, options(nomem, nostack, preserves_flags)); + } + 4 << ((ctr >> 16) & 0xf) + } + #[cfg(not(target_arch = "aarch64"))] + { + 64 + } +} + +/// Clean `[addr, addr + size)` to the point of coherency so a DMA master +/// sees what the CPU wrote. No-op on hosts. +pub fn clean_dcache_range(addr: usize, size: usize) { + #[cfg(target_arch = "aarch64")] + dcache_range(addr, size, |line| unsafe { + core::arch::asm!("dc cvac, {0}", in(reg) line, options(nostack, preserves_flags)); + }); + #[cfg(not(target_arch = "aarch64"))] + let _ = (addr, size); +} + +/// Clean and invalidate `[addr, addr + size)` so the next CPU read sees what +/// a DMA master wrote. Cleaning first means no CPU write in a shared line is +/// lost. No-op on hosts. +pub fn clean_invalidate_dcache_range(addr: usize, size: usize) { + #[cfg(target_arch = "aarch64")] + dcache_range(addr, size, |line| unsafe { + core::arch::asm!("dc civac, {0}", in(reg) line, options(nostack, preserves_flags)); + }); + #[cfg(not(target_arch = "aarch64"))] + let _ = (addr, size); +} + +#[cfg(target_arch = "aarch64")] +fn dcache_range(addr: usize, size: usize, op: impl Fn(usize)) { + let line = dcache_line_bytes(); + let end = addr.saturating_add(size); + let mut cursor = addr & !(line - 1); + while cursor < end { + op(cursor); + cursor += line; + } + dsb(); +} + /// Disable interrupts (set DAIF flags). #[inline(always)] pub fn disable_interrupts() { diff --git a/crates/aienos-kernel/src/usb/descriptor.rs b/crates/aienos-kernel/src/usb/descriptor.rs new file mode 100644 index 00000000..8b22cf2f --- /dev/null +++ b/crates/aienos-kernel/src/usb/descriptor.rs @@ -0,0 +1,164 @@ +//! USB descriptor parsing for keyboard bring-up (USB 2.0 section 9.6, HID +//! 1.11 appendix B): the device descriptor's control packet size and the +//! boot keyboard interface inside a configuration descriptor. + +const DESCRIPTOR_DEVICE: u8 = 1; +const DESCRIPTOR_CONFIGURATION: u8 = 2; +const DESCRIPTOR_INTERFACE: u8 = 4; +const DESCRIPTOR_ENDPOINT: u8 = 5; +const CLASS_HID: u8 = 3; +const SUBCLASS_BOOT: u8 = 1; +const PROTOCOL_KEYBOARD: u8 = 1; +const TRANSFER_INTERRUPT: u8 = 3; + +/// bMaxPacketSize0 from the first 8 bytes of a device descriptor. +pub fn control_max_packet(device_descriptor: &[u8]) -> Option { + match device_descriptor { + [len, DESCRIPTOR_DEVICE, _, _, _, _, _, size, ..] if *len >= 8 && *size > 0 => Some(*size), + _ => None, + } +} + +/// Where a boot-protocol keyboard's reports come from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BootKeyboard { + /// bConfigurationValue to pass to SET_CONFIGURATION. + pub configuration: u8, + pub interface: u8, + /// Interrupt-IN endpoint address, for example 0x81. + pub endpoint_address: u8, + pub max_packet: u16, + /// bInterval as the device states it. + pub interval: u8, +} + +/// First boot keyboard interface (class 3, subclass 1, protocol 1) with an +/// interrupt-IN endpoint in a configuration descriptor and what follows it. +/// Parsing stops at wTotalLength or the end of `bytes`, whichever is first, +/// and at any descriptor whose length is impossible. +pub fn find_boot_keyboard(bytes: &[u8]) -> Option { + if bytes.len() < 9 || bytes[0] < 9 || bytes[1] != DESCRIPTOR_CONFIGURATION { + return None; + } + let total = usize::from(u16::from_le_bytes([bytes[2], bytes[3]])).min(bytes.len()); + let configuration = bytes[5]; + let mut interface = None; + let mut at = 0; + while at + 2 <= total { + let len = usize::from(bytes[at]); + if len < 2 || at + len > total { + return None; + } + let d = &bytes[at..at + len]; + match d[1] { + DESCRIPTOR_INTERFACE if len >= 9 => { + let keyboard = + d[5] == CLASS_HID && d[6] == SUBCLASS_BOOT && d[7] == PROTOCOL_KEYBOARD; + interface = keyboard.then_some(d[2]); + } + DESCRIPTOR_ENDPOINT if len >= 7 => { + let is_in = d[2] & 0x80 != 0; + if let (Some(interface), true, TRANSFER_INTERRUPT) = (interface, is_in, d[3] & 0x3) + { + return Some(BootKeyboard { + configuration, + interface, + endpoint_address: d[2], + max_packet: u16::from_le_bytes([d[4], d[5]]) & 0x7ff, + interval: d[6], + }); + } + } + _ => {} + } + at += len; + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Configuration descriptor QEMU 8.2.2 usb-kbd returned to the driver in + /// the QEMU keyboard test: config, interface, HID, endpoint 0x81. + const KEYBOARD: [u8; 34] = [ + 9, 2, 34, 0, 1, 1, 8, 0xa0, 50, // + 9, 4, 0, 0, 1, 3, 1, 1, 0, // + 9, 0x21, 0x11, 0x01, 0, 1, 0x22, 63, 0, // + 7, 5, 0x81, 3, 8, 0, 7, + ]; + + #[test] + fn finds_the_keyboard_interrupt_in_endpoint() { + assert_eq!( + find_boot_keyboard(&KEYBOARD), + Some(BootKeyboard { + configuration: 1, + interface: 0, + endpoint_address: 0x81, + max_packet: 8, + interval: 7, + }) + ); + } + + #[test] + fn skips_a_mouse_interface_and_out_endpoints_in_a_composite_device() { + let composite: [u8; 50] = [ + 9, 2, 50, 0, 2, 2, 0, 0xa0, 50, // + 9, 4, 0, 0, 1, 3, 1, 2, 0, // boot mouse + 7, 5, 0x81, 3, 4, 0, 10, // + 9, 4, 1, 0, 2, 3, 1, 1, 0, // boot keyboard + 7, 5, 0x02, 3, 8, 0, 10, // interrupt OUT (LEDs): not this + 9, 0x21, 0x11, 0x01, 0, 1, 0x22, 63, 0, + ]; + let mut with_endpoint = [0u8; 57]; + with_endpoint[..50].copy_from_slice(&composite); + with_endpoint[50..].copy_from_slice(&[7, 5, 0x83, 3, 8, 0, 4]); + with_endpoint[2] = 57; + let found = find_boot_keyboard(&with_endpoint).unwrap(); + assert_eq!((found.configuration, found.interface), (2, 1)); + assert_eq!(found.endpoint_address, 0x83); + assert_eq!(found.interval, 4); + assert_eq!( + find_boot_keyboard(&composite), + None, + "mouse only, no keyboard IN" + ); + } + + #[test] + fn stops_at_total_length_and_malformed_descriptors() { + let mut short_total = KEYBOARD; + short_total[2] = 27; // total length excludes the endpoint + assert_eq!(find_boot_keyboard(&short_total), None); + let mut zero_len = KEYBOARD; + zero_len[9] = 0; + assert_eq!(find_boot_keyboard(&zero_len), None, "no endless loop"); + let mut overrun = KEYBOARD; + overrun[27] = 200; + assert_eq!(find_boot_keyboard(&overrun), None); + assert_eq!(find_boot_keyboard(&KEYBOARD[..20]), None, "truncated read"); + assert_eq!( + find_boot_keyboard(&[9, 1, 0, 0]), + None, + "not a configuration" + ); + } + + #[test] + fn reads_the_control_packet_size_from_a_device_descriptor() { + assert_eq!( + control_max_packet(&[18, 1, 0x00, 0x02, 0, 0, 0, 64]), + Some(64) + ); + assert_eq!( + control_max_packet(&[18, 1, 0x10, 0x01, 0, 0, 0, 8, 0x27, 0x06]), + Some(8) + ); + assert_eq!(control_max_packet(&[18, 2, 0, 0, 0, 0, 0, 8]), None); + assert_eq!(control_max_packet(&[18, 1, 0, 0, 0, 0, 0, 0]), None); + assert_eq!(control_max_packet(&[18, 1, 0]), None); + } +} diff --git a/crates/aienos-kernel/src/usb/mod.rs b/crates/aienos-kernel/src/usb/mod.rs index 7e5e9071..aa4c67b6 100644 --- a/crates/aienos-kernel/src/usb/mod.rs +++ b/crates/aienos-kernel/src/usb/mod.rs @@ -3,8 +3,10 @@ //! After `ExitBootServices` the firmware's USB keyboard support is gone, so //! AIENOS must drive the keyboard itself. This module holds the parts that //! need no hardware: decoding HID boot-protocol keyboard reports into key -//! events and text, and the xHCI data structures a polled controller driver -//! builds on (ADR 0012, SEED-0A experiment #1 `input.keyboard.usb`). +//! events and text, parsing the descriptors that locate a boot keyboard, and +//! the xHCI data structures (TRBs, rings, contexts) a polled controller +//! driver builds on (ADR 0012, SEED-0A experiment #1 `input.keyboard.usb`). +pub mod descriptor; pub mod hid; pub mod xhci; diff --git a/crates/aienos-kernel/src/usb/xhci/mod.rs b/crates/aienos-kernel/src/usb/xhci/mod.rs index 280f51be..00e82aa2 100644 --- a/crates/aienos-kernel/src/usb/xhci/mod.rs +++ b/crates/aienos-kernel/src/usb/xhci/mod.rs @@ -1,7 +1,271 @@ -//! xHCI (USB 3 host controller) data structures for the polled keyboard -//! driver, host-tested against the xHCI 1.2 specification. Register access -//! and controller bring-up come later in the series and build on these. +//! xHCI (USB 3 host controller) building blocks for the polled keyboard +//! driver: PCI recognition, capability decoding, register layout, port +//! status helpers, TRBs, rings and input contexts. All pure data layout and +//! bookkeeping, host-tested against the xHCI 1.2 specification; register +//! access and controller bring-up follow in the next part of the series. pub mod context; pub mod ring; pub mod trb; + +/// PCI class code of an xHCI controller: serial bus (0x0c), USB (0x03), +/// programming interface xHCI (0x30). +pub const XHCI_CLASS_CODE: u32 = 0x0c_03_30; +/// PCI command register bits the driver needs: memory decode and DMA. +pub const PCI_COMMAND_MEMORY: u16 = 1 << 1; +pub const PCI_COMMAND_BUS_MASTER: u16 = 1 << 2; + +/// Base of an xHCI controller's register block from its PCI header: the +/// class/revision dword (offset 0x08) and BAR0/BAR1 (offsets 0x10, 0x14). +/// `None` for another device class, an I/O or unprogrammed BAR, or a failed +/// (all-ones) read. +pub fn xhci_mmio_base(class_revision: u32, bar0_low: u32, bar0_high: u32) -> Option { + if class_revision == u32::MAX || class_revision >> 8 != XHCI_CLASS_CODE { + return None; + } + let base = match bar0_low & 0x7 { + // 32-bit memory BAR. + 0b000 => u64::from(bar0_low & !0xf), + // 64-bit memory BAR (what the xHCI specification requires). + 0b100 => u64::from(bar0_high) << 32 | u64::from(bar0_low & !0xf), + _ => return None, + }; + (base != 0 && bar0_low != u32::MAX).then_some(base) +} + +/// Operational register offsets from the operational base (CAPLENGTH). +pub mod op { + pub const USBCMD: usize = 0x00; + pub const USBSTS: usize = 0x04; + pub const CRCR: usize = 0x18; + pub const DCBAAP: usize = 0x30; + pub const CONFIG: usize = 0x38; + /// PORTSC of root hub port `port` (1-based). + pub const fn portsc(port: u8) -> usize { + 0x400 + 0x10 * (port as usize - 1) + } + pub const USBCMD_RUN: u32 = 1 << 0; + pub const USBCMD_RESET: u32 = 1 << 1; + pub const USBSTS_HALTED: u32 = 1 << 0; + pub const USBSTS_HOST_ERROR: u32 = 1 << 2; + pub const USBSTS_NOT_READY: u32 = 1 << 11; +} + +/// Interrupter 0 register offsets from the runtime base (RTSOFF). Each +/// interrupter set is 32 bytes and set 0 starts at 0x20. +pub mod rt { + pub const IMAN: usize = 0x20; + pub const ERSTSZ: usize = 0x28; + pub const ERSTBA: usize = 0x30; + pub const ERDP: usize = 0x38; + /// ERDP Event Handler Busy, cleared by writing 1. + pub const ERDP_BUSY: u64 = 1 << 3; +} + +/// What the capability registers say about a controller. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Capabilities { + /// Offset of the operational registers (CAPLENGTH). + pub operational_offset: usize, + pub runtime_offset: usize, + pub doorbell_offset: usize, + pub max_slots: u8, + pub max_ports: u8, + /// Scratchpad pages the controller asks software to provide. + pub scratchpad_pages: u16, + /// HCCPARAMS1.AC64: the controller can reach 64-bit addresses. + pub addresses_64: bool, + /// Context entry size, 32 or 64 bytes (HCCPARAMS1.CSZ). + pub context_bytes: usize, +} + +impl Capabilities { + /// Decode CAPLENGTH/HCIVERSION (offset 0x00), HCSPARAMS1 (0x04), + /// HCSPARAMS2 (0x08), HCCPARAMS1 (0x10), DBOFF (0x14) and RTSOFF (0x18). + /// `None` when the block reads as absent or inconsistent. + pub fn decode( + version_length: u32, + hcsparams1: u32, + hcsparams2: u32, + hccparams1: u32, + dboff: u32, + rtsoff: u32, + ) -> Option { + let cap_length = (version_length & 0xff) as usize; + let version = version_length >> 16; + if version_length == u32::MAX || cap_length < 0x20 || version < 0x0090 { + return None; + } + let max_slots = (hcsparams1 & 0xff) as u8; + let max_ports = (hcsparams1 >> 24) as u8; + if max_slots == 0 || max_ports == 0 { + return None; + } + let scratchpad_hi = (hcsparams2 >> 21) & 0x1f; + let scratchpad_lo = (hcsparams2 >> 27) & 0x1f; + Some(Self { + operational_offset: cap_length, + runtime_offset: (rtsoff & !0x1f) as usize, + doorbell_offset: (dboff & !0x3) as usize, + max_slots, + max_ports, + scratchpad_pages: (scratchpad_hi << 5 | scratchpad_lo) as u16, + addresses_64: hccparams1 & 1 != 0, + context_bytes: if hccparams1 & (1 << 2) != 0 { 64 } else { 32 }, + }) + } +} + +/// PORTSC bits (xHCI 1.2 section 5.4.8). +pub mod portsc { + pub const CONNECTED: u32 = 1 << 0; + pub const ENABLED: u32 = 1 << 1; + pub const RESET: u32 = 1 << 4; + pub const POWER: u32 = 1 << 9; + pub const RESET_CHANGE: u32 = 1 << 21; + /// Change bits, all write-1-to-clear: CSC, PEC, WRC, OCC, PRC, PLC, CEC. + pub const CHANGES: u32 = 0x7f << 17; + /// Bits that keep their value when written back: read-only fields and + /// the preserved read/write ones (Linux calls this state "neutral"). + const READ_ONLY: u32 = 1 << 0 | 1 << 3 | 0xf << 10 | 1 << 30; + const PRESERVED: u32 = 0xf << 5 | 1 << 9 | 0x3 << 14 | 0x7 << 25; + + /// A write value that changes nothing: it keeps the preserved fields + /// and writes 0 to Port Enabled (writing 1 disables the port) and to + /// every write-1-to-clear change bit. + pub fn neutral(value: u32) -> u32 { + value & (READ_ONLY | PRESERVED) + } + + /// Port speed ID (bits 13:10). + pub fn speed(value: u32) -> u8 { + ((value >> 10) & 0xf) as u8 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recognizes_xhci_class_and_memory_bars() { + // qemu-xhci as read in the QEMU keyboard test: class 0x0c0330 rev 1, + // 64-bit BAR at 0x80_0000_4000. + assert_eq!( + xhci_mmio_base(0x0c03_3001, 0x0000_4004, 0x80), + Some(0x80_0000_4000) + ); + assert_eq!( + xhci_mmio_base(0x0c03_3000, 0x0000_000c, 0x6), + Some(0x6_0000_0000) + ); + // A 32-bit BAR ignores the next dword (it belongs to BAR1). + assert_eq!( + xhci_mmio_base(0x0c03_3000, 0xfe00_0000, 0x1234), + Some(0xfe00_0000) + ); + } + + #[test] + fn rejects_other_classes_io_and_unprogrammed_bars() { + assert!( + xhci_mmio_base(0x0c03_2000, 0x1000_0004, 0).is_none(), + "EHCI" + ); + assert!( + xhci_mmio_base(0x0c03_0000, 0x1000_0004, 0).is_none(), + "UHCI" + ); + assert!( + xhci_mmio_base(0x0600_0000, 0x1000_0004, 0).is_none(), + "bridge" + ); + assert!( + xhci_mmio_base(u32::MAX, 0x1000_0004, 0).is_none(), + "failed read" + ); + assert!( + xhci_mmio_base(0x0c03_3000, 0x0000_1001, 0).is_none(), + "I/O BAR" + ); + assert!( + xhci_mmio_base(0x0c03_3000, 0x1000_0002, 0).is_none(), + "below 1 MiB type" + ); + assert!( + xhci_mmio_base(0x0c03_3000, 0x0000_0004, 0).is_none(), + "unprogrammed" + ); + assert!(xhci_mmio_base(0x0c03_3000, u32::MAX, u32::MAX).is_none()); + } + + #[test] + fn capabilities_decode_qemu_xhci_registers() { + // Read from qemu-xhci in QEMU 8.2.2: CAPLENGTH 0x40, version 1.00, 64 + // slots, 16 interrupters, 8 ports, no scratchpad, AC64, 32-byte contexts. + let caps = Capabilities::decode( + 0x0100_0040, + 0x0800_1040, + 0x0000_000f, + 0x0008_7001, + 0x2000, + 0x1000, + ) + .unwrap(); + assert_eq!(caps.operational_offset, 0x40); + assert_eq!(caps.max_slots, 64); + assert_eq!(caps.max_ports, 8); + assert_eq!(caps.scratchpad_pages, 0); + assert!(caps.addresses_64); + assert_eq!(caps.context_bytes, 32); + assert_eq!( + (caps.doorbell_offset, caps.runtime_offset), + (0x2000, 0x1000) + ); + } + + #[test] + fn capabilities_decode_scratchpads_large_contexts_and_reject_absent_blocks() { + // Scratchpad count hi = 1 (bit 21), lo = 2 (bit 28): 34 pages. + let caps = Capabilities::decode( + 0x0110_0020, + 0x0400_0020, + 1 << 21 | 2 << 27, + 1 << 2, + 0x3003, + 0x201f, + ) + .unwrap(); + assert_eq!(caps.scratchpad_pages, 34); + assert_eq!(caps.context_bytes, 64); + assert!(!caps.addresses_64); + assert_eq!( + (caps.doorbell_offset, caps.runtime_offset), + (0x3000, 0x2000) + ); + assert!(Capabilities::decode(u32::MAX, u32::MAX, 0, 0, 0, 0).is_none()); + assert!(Capabilities::decode(0x0100_0010, 0x0800_1040, 0, 0, 0, 0).is_none()); + assert!( + Capabilities::decode(0x0100_0040, 0x0800_1000, 0, 0, 0, 0).is_none(), + "0 slots" + ); + } + + #[test] + fn portsc_neutral_never_disables_the_port_or_acks_changes() { + // Connected, enabled, powered, high speed, reset-change pending. + let value = portsc::CONNECTED + | portsc::ENABLED + | portsc::POWER + | 3 << 10 + | portsc::RESET_CHANGE + | 1 << 17; + let neutral = portsc::neutral(value); + assert_eq!(neutral & portsc::ENABLED, 0, "writing PED=1 would disable"); + assert_eq!(neutral & portsc::CHANGES, 0, "no change bit acknowledged"); + assert_ne!(neutral & portsc::POWER, 0, "power stays on"); + assert_eq!(portsc::speed(value), 3); + assert_eq!(op::portsc(1), 0x400); + assert_eq!(op::portsc(3), 0x420); + } +} From 5c1418a61f647500cd472e9ffa8049e9928dee6a Mon Sep 17 00:00:00 2001 From: Drake Date: Thu, 24 Sep 2026 09:46:00 -0500 Subject: [PATCH 3/4] kernel(usb): bring up polled xHCI keyboard controller (SEED-0A 2c) --- .../aienos-kernel/src/usb/xhci/controller.rs | 616 ++++++++++++++++++ crates/aienos-kernel/src/usb/xhci/mod.rs | 1 + 2 files changed, 617 insertions(+) create mode 100644 crates/aienos-kernel/src/usb/xhci/controller.rs diff --git a/crates/aienos-kernel/src/usb/xhci/controller.rs b/crates/aienos-kernel/src/usb/xhci/controller.rs new file mode 100644 index 00000000..140930a7 --- /dev/null +++ b/crates/aienos-kernel/src/usb/xhci/controller.rs @@ -0,0 +1,616 @@ +//! Polled xHCI bring-up of one HID boot keyboard. +//! +//! Sequence: halt and reset the controller, program one command ring, one +//! event ring (interrupter 0, interrupts left disabled) and the device +//! context array, run it, then for each connected root port: reset the port, +//! Enable Slot, Address Device, read the device and configuration +//! descriptors, and if a boot keyboard is found SET_CONFIGURATION, +//! SET_PROTOCOL(boot), SET_IDLE(0) and Configure Endpoint for its +//! interrupt-IN endpoint. Reports are then read by polling the event ring. +//! +//! No interrupts, no exception-vector changes and no allocator (ADR 0009). +//! Every wait is bounded by the architectural counter, so a missing or +//! wedged controller costs a bounded delay and an error, never a hang. +//! All DMA memory is one caller-owned [`DmaMemory`], used at its identity +//! address and kept coherent with explicit cache maintenance. + +use super::context::{ + default_control_max_packet, endpoint_dci, interrupt_interval, EndpointConfig, InputContext, + CONTROL_DCI, EP_TYPE_CONTROL, EP_TYPE_INTERRUPT_IN, +}; +use super::ring::{EventRing, ProducerRing}; +use super::trb::{completion, kind, request, SetupPacket, Trb}; +use super::{op, portsc, rt, Capabilities}; +use crate::arch::aarch64::{ + clean_dcache_range, clean_invalidate_dcache_range, counter_frequency_hz, counter_ticks, MmioReg, +}; +use crate::usb::descriptor::{control_max_packet, find_boot_keyboard, BootKeyboard}; +use crate::usb::hid::BOOT_REPORT_LEN; +use core::fmt; +use core::ptr::{addr_of_mut, read_volatile, write_bytes, write_volatile}; + +const PAGE_BYTES: usize = 4096; +const RING_TRBS: usize = PAGE_BYTES / 16; +const REPORT_OFFSET: usize = 0; +const DESCRIPTOR_OFFSET: usize = 512; +const DESCRIPTOR_MAX: u16 = 255; + +/// One 4 KiB page of DMA memory. Page alignment keeps every structure +/// inside one 64 KiB boundary, as the specification requires. +#[repr(C, align(4096))] +pub struct DmaPage([u32; PAGE_BYTES / 4]); + +/// Every structure the controller reads or writes, one page each. +#[repr(C)] +pub struct DmaMemory { + dcbaa: DmaPage, + device_context: DmaPage, + input_context: DmaPage, + command_ring: DmaPage, + event_ring: DmaPage, + segment_table: DmaPage, + control_ring: DmaPage, + report_ring: DmaPage, + buffer: DmaPage, +} + +impl DmaMemory { + pub const fn new() -> Self { + const ZERO: DmaPage = DmaPage([0; PAGE_BYTES / 4]); + Self { + dcbaa: ZERO, + device_context: ZERO, + input_context: ZERO, + command_ring: ZERO, + event_ring: ZERO, + segment_table: ZERO, + control_ring: ZERO, + report_ring: ZERO, + buffer: ZERO, + } + } +} + +impl Default for DmaMemory { + fn default() -> Self { + Self::new() + } +} + +/// Why no keyboard is available. Every variant is reached by a bounded path. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Error { + Absent, + Unsupported(&'static str), + Timeout(&'static str), + HostSystemError, + Failed { step: &'static str, code: u8 }, + NoKeyboard, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Absent => f.write_str("xHCI registers absent"), + Self::Unsupported(what) => write!(f, "unsupported: {what}"), + Self::Timeout(step) => write!(f, "timed out: {step}"), + 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"), + } + } +} + +/// Bounded wait: a time limit on the architectural counter, or a poll count +/// when the counter frequency is unknown. +struct Deadline { + start: u64, + ticks: u64, + polls: u32, +} + +impl Deadline { + fn after_ms(ms: u64) -> Self { + Self { + start: counter_ticks(), + ticks: counter_frequency_hz().saturating_mul(ms) / 1000, + polls: 0, + } + } + + fn expired(&mut self) -> bool { + self.polls = self.polls.saturating_add(1); + if self.ticks == 0 { + return self.polls > 1_000_000; + } + counter_ticks().wrapping_sub(self.start) > self.ticks + } +} + +fn write64(addr: usize, value: u64) { + MmioReg::::new(addr).write(value as u32); + MmioReg::::new(addr + 4).write((value >> 32) as u32); +} + +/// A running controller with one attached boot keyboard. +pub struct Keyboard { + op: usize, + rt: usize, + db: usize, + mem: *mut DmaMemory, + context_bytes: usize, + commands: ProducerRing, + events: EventRing, + control: ProducerRing, + reports: ProducerRing, + slot: u8, + dci: u8, + port: u8, + device: Option, + retire_pending: bool, + halted: bool, +} + +impl Keyboard { + /// Reset the controller at `mmio_base` and attach the first boot + /// keyboard found on a root port. + /// + /// # Safety + /// `mmio_base` must be the mapped register block of an xHCI controller + /// with memory decode and bus mastering enabled that nothing else drives, + /// and `mem` must be identity-mapped memory that stays valid and unused + /// by anything else for as long as the returned driver or the controller + /// may run. + pub unsafe fn start(mmio_base: u64, mem: *mut DmaMemory) -> Result { + let base = mmio_base as usize; + let cap = |offset: usize| MmioReg::::new(base + offset).read(); + let caps = Capabilities::decode(cap(0), cap(4), cap(8), cap(0x10), cap(0x14), cap(0x18)) + .ok_or(Error::Absent)?; + if caps.scratchpad_pages != 0 { + return Err(Error::Unsupported("controller asks for scratchpad pages")); + } + let end = mem as u64 + core::mem::size_of::() as u64; + if !caps.addresses_64 && end > u64::from(u32::MAX) { + return Err(Error::Unsupported( + "DMA memory above 4 GiB on a 32-bit controller", + )); + } + let op = base + caps.operational_offset; + reset(op)?; + + // SAFETY: the caller hands `mem` over exclusively. + unsafe { write_bytes(mem, 0, 1) }; + let page = |p: *mut DmaPage| (p as *mut Trb, p as u64); + // SAFETY: each ring gets its own page inside `mem`. + let (commands, events, control, reports) = unsafe { + let (c, c_dma) = page(addr_of_mut!((*mem).command_ring)); + let (e, e_dma) = page(addr_of_mut!((*mem).event_ring)); + let (t, t_dma) = page(addr_of_mut!((*mem).control_ring)); + let (r, r_dma) = page(addr_of_mut!((*mem).report_ring)); + ( + ProducerRing::new(c, RING_TRBS, c_dma), + EventRing::new(e, RING_TRBS, e_dma), + ProducerRing::new(t, RING_TRBS, t_dma), + ProducerRing::new(r, RING_TRBS, r_dma), + ) + }; + let (Some(commands), Some(events), Some(control), Some(reports)) = + (commands, events, control, reports) + else { + return Err(Error::Unsupported("ring memory")); + }; + let mut keyboard = Self { + op, + rt: base + caps.runtime_offset, + db: base + caps.doorbell_offset, + mem, + context_bytes: caps.context_bytes, + commands, + events, + control, + reports, + slot: 0, + dci: 0, + port: 0, + device: None, + retire_pending: false, + halted: false, + }; + keyboard.run()?; + + let mut outcome = Err(Error::NoKeyboard); + for port in 1..=caps.max_ports { + let status = keyboard.op_reg(op::portsc(port)).read(); + if status & portsc::CONNECTED == 0 { + continue; + } + outcome = keyboard.attach(port); + if outcome.is_ok() { + break; + } + if keyboard.slot != 0 { + let slot = keyboard.slot; + let _ = keyboard.command(Trb::disable_slot(slot), "Disable Slot"); + keyboard.slot = 0; + } + } + outcome.map(|()| keyboard) + } + + /// Root hub port, slot and interrupt-IN endpoint address of the keyboard. + pub fn location(&self) -> (u8, u8, u8) { + let endpoint = self.device.map_or(0, |d| d.endpoint_address); + (self.port, self.slot, endpoint) + } + + /// True once the report endpoint failed; no further reports arrive. + pub fn is_halted(&self) -> bool { + self.halted + } + + fn op_reg(&self, offset: usize) -> MmioReg { + MmioReg::new(self.op + offset) + } + + fn run(&mut self) -> Result<(), Error> { + let mem = self.mem; + // SAFETY: pages of the exclusively owned DMA memory. + let (dcbaa, segment_table) = unsafe { + ( + addr_of_mut!((*mem).dcbaa), + addr_of_mut!((*mem).segment_table), + ) + }; + let entry = self.events.segment_table_entry(); + // SAFETY: the segment table page is ours; 4 dwords fit. + unsafe { write_volatile(segment_table as *mut [u32; 4], entry) }; + self.sync_to_device(); + + let config = self.op_reg(op::CONFIG); + // One device slot is enough for one keyboard. + config.write(config.read() & !0xff | 1); + write64(self.op + op::DCBAAP, dcbaa as u64); + write64(self.op + op::CRCR, self.commands.dequeue_pointer()); + MmioReg::::new(self.rt + rt::ERSTSZ).write(1); + write64(self.rt + rt::ERDP, self.events.dequeue_pointer()); + write64(self.rt + rt::ERSTBA, segment_table as u64); + + let usbcmd = self.op_reg(op::USBCMD); + usbcmd.write(usbcmd.read() | op::USBCMD_RUN); + wait(Deadline::after_ms(100), || { + self.op_reg(op::USBSTS).read() & op::USBSTS_HALTED == 0 + }) + .map_err(|()| Error::Timeout("controller run")) + } + + fn reset_port(&mut self, port: u8) -> Result { + let reg = self.op_reg(op::portsc(port)); + let status = reg.read(); + if status & portsc::ENABLED == 0 { + // USB 2 ports need a reset to enable; USB 3 ports train on their own. + reg.write(portsc::neutral(status) | portsc::RESET); + wait(Deadline::after_ms(500), || { + reg.read() & portsc::RESET_CHANGE != 0 + }) + .map_err(|()| Error::Timeout("port reset"))?; + } + let status = reg.read(); + reg.write(portsc::neutral(status) | status & portsc::CHANGES); + if status & portsc::ENABLED == 0 { + return Err(Error::Unsupported("port did not enable")); + } + Ok(portsc::speed(status)) + } + + fn attach(&mut self, port: u8) -> Result<(), Error> { + let speed = self.reset_port(port)?; + self.port = port; + let event = self.command(Trb::enable_slot(), "Enable Slot")?; + self.slot = event.slot_id(); + if self.slot == 0 { + return Err(Error::Unsupported("slot id")); + } + let mem = self.mem; + // SAFETY: pages of the exclusively owned DMA memory; a slot ID (at + // most 255) indexes inside the 512-entry DCBAA page. + unsafe { + let device_context = addr_of_mut!((*mem).device_context); + write_bytes(device_context, 0, 1); + let dcbaa = addr_of_mut!((*mem).dcbaa) as *mut u64; + write_volatile(dcbaa.add(usize::from(self.slot)), device_context as u64); + let ring = addr_of_mut!((*mem).control_ring); + self.control = ProducerRing::new(ring as *mut Trb, RING_TRBS, ring as u64) + .ok_or(Error::Unsupported("ring memory"))?; + } + + let mut max_packet = default_control_max_packet(speed); + self.control_context(speed, max_packet, 0b11, 1); + self.slot_command(Trb::address_device, "Address Device")?; + + let device = self.control_in( + SetupPacket::get_descriptor(request::DESCRIPTOR_DEVICE, 0, 8), + "GET_DESCRIPTOR(device)", + )?; + let reported = control_max_packet(&device[..8]).map_or(max_packet, |size| { + if speed >= super::context::speed::SUPER { + 1 << size.min(9) + } else { + u16::from(size) + } + }); + if reported != max_packet { + max_packet = reported; + self.control_context(speed, max_packet, 0b10, 1); + self.slot_command(Trb::evaluate_context, "Evaluate Context")?; + } + + let config = self.control_in( + SetupPacket::get_descriptor(request::DESCRIPTOR_CONFIGURATION, 0, DESCRIPTOR_MAX), + "GET_DESCRIPTOR(configuration)", + )?; + let keyboard = find_boot_keyboard(&config).ok_or(Error::NoKeyboard)?; + let dci = endpoint_dci(keyboard.endpoint_address).ok_or(Error::NoKeyboard)?; + self.control_transfer( + SetupPacket::set_configuration(keyboard.configuration), + "SET_CONFIGURATION", + )?; + self.control_transfer( + SetupPacket::set_boot_protocol(keyboard.interface), + "SET_PROTOCOL", + )?; + // Keyboards may stall SET_IDLE; unchanged reports are then ignored + // by the decoder anyway. + let _ = self.control_transfer( + SetupPacket::set_idle_forever(keyboard.interface), + "SET_IDLE", + ); + + let (dequeue, bytes) = (self.reports.dequeue_pointer(), self.context_bytes); + let mut input = InputContext::new(self.input_context(), bytes) + .ok_or(Error::Unsupported("context size"))?; + input.add(1 | 1 << dci); + input.slot(speed, port, dci); + input.endpoint( + dci, + &EndpointConfig { + ep_type: EP_TYPE_INTERRUPT_IN, + max_packet: keyboard.max_packet, + interval: interrupt_interval(speed, keyboard.interval), + dequeue, + average_trb_length: BOOT_REPORT_LEN as u16, + max_esit_payload: keyboard.max_packet, + }, + ); + self.slot_command(Trb::configure_endpoint, "Configure Endpoint")?; + self.dci = dci; + self.device = Some(keyboard); + self.arm(); + Ok(()) + } + + fn input_context(&mut self) -> &mut [u32] { + // SAFETY: the input context page is only touched here, between + // commands, while the controller is not reading it. + unsafe { &mut (*addr_of_mut!((*self.mem).input_context)).0 } + } + + fn control_context(&mut self, speed: u8, max_packet: u16, add: u32, entries: u8) { + let dequeue = self.control.dequeue_pointer(); + let (port, bytes) = (self.port, self.context_bytes); + if let Some(mut input) = InputContext::new(self.input_context(), bytes) { + input.add(add); + input.slot(speed, port, entries); + input.endpoint( + CONTROL_DCI, + &EndpointConfig { + ep_type: EP_TYPE_CONTROL, + max_packet, + interval: 0, + dequeue, + average_trb_length: 8, + max_esit_payload: 0, + }, + ); + } + } + + fn slot_command(&mut self, build: fn(u64, u8) -> Trb, step: &'static str) -> Result<(), Error> { + // SAFETY: address of a page of the owned DMA memory. + let input = unsafe { addr_of_mut!((*self.mem).input_context) } as u64; + self.command(build(input, self.slot), step).map(|_| ()) + } + + fn doorbell(&self, target: u8, value: u8) { + MmioReg::::new(self.db + usize::from(target) * 4).write(u32::from(value)); + } + + fn command(&mut self, trb: Trb, step: &'static str) -> Result { + let addr = self.commands.push(trb); + self.sync_to_device(); + self.doorbell(0, 0); + let event = self.wait_event(step, |e| { + e.kind() == kind::COMMAND_COMPLETION && e.pointer() == addr + })?; + match event.completion_code() { + completion::SUCCESS => Ok(event), + code => Err(Error::Failed { step, code }), + } + } + + fn control_in( + &mut self, + setup: SetupPacket, + step: &'static str, + ) -> Result<[u8; DESCRIPTOR_MAX as usize], Error> { + let buffer = self.buffer_ptr(DESCRIPTOR_OFFSET); + // SAFETY: the descriptor area lies inside the owned buffer page. + unsafe { write_bytes(buffer, 0, usize::from(DESCRIPTOR_MAX)) }; + self.control_transfer(setup, step)?; + let mut bytes = [0u8; DESCRIPTOR_MAX as usize]; + for (i, b) in bytes.iter_mut().enumerate() { + // SAFETY: as above; the controller finished writing. + *b = unsafe { read_volatile(buffer.add(i)) }; + } + Ok(bytes) + } + + fn control_transfer(&mut self, setup: SetupPacket, step: &'static str) -> Result<(), Error> { + let buffer = self.buffer_ptr(DESCRIPTOR_OFFSET) as u64; + self.control.push(Trb::setup_stage(&setup)); + if setup.length > 0 { + self.control.push(Trb::data_stage(&setup, buffer)); + } + let status = self.control.push(Trb::status_stage(&setup)); + self.sync_to_device(); + self.doorbell(self.slot, CONTROL_DCI); + let slot = self.slot; + let event = self.wait_event(step, |e| { + e.kind() == kind::TRANSFER_EVENT + && e.slot_id() == slot + && e.endpoint_id() == CONTROL_DCI + && (e.pointer() == status || !e.completed_ok()) + })?; + if !event.completed_ok() { + return Err(Error::Failed { + step, + code: event.completion_code(), + }); + } + Ok(()) + } + + fn buffer_ptr(&self, offset: usize) -> *mut u8 { + // SAFETY: address arithmetic inside the owned buffer page. + unsafe { (addr_of_mut!((*self.mem).buffer) as *mut u8).add(offset) } + } + + /// Queue one report transfer on the interrupt-IN endpoint. + fn arm(&mut self) { + let buffer = self.buffer_ptr(REPORT_OFFSET) as u64; + self.reports + .push(Trb::normal(buffer, BOOT_REPORT_LEN as u32)); + self.sync_to_device(); + self.doorbell(self.slot, self.dci); + } + + /// Consume pending events; return a completed keyboard report, if any. + /// Other events (port changes, stray completions) are retired and dropped. + pub fn poll(&mut self) -> Option<[u8; BOOT_REPORT_LEN]> { + if self.halted { + return None; + } + self.sync_from_device(); + let mut report = None; + while let Some(event) = self.events.pop() { + self.retire_pending = true; + let ours = event.kind() == kind::TRANSFER_EVENT + && event.slot_id() == self.slot + && event.endpoint_id() == self.dci; + if !ours { + continue; + } + if !event.completed_ok() { + // The endpoint halted; recovering it is not attempted. + self.halted = true; + break; + } + if event.residual() == 0 { + let buffer = self.buffer_ptr(REPORT_OFFSET); + let mut bytes = [0u8; BOOT_REPORT_LEN]; + for (i, b) in bytes.iter_mut().enumerate() { + // SAFETY: the report area lies inside the owned buffer page. + *b = unsafe { read_volatile(buffer.add(i)) }; + } + report = Some(bytes); + } + self.arm(); + break; + } + self.retire(); + report + } + + fn wait_event( + &mut self, + step: &'static str, + wanted: impl Fn(&Trb) -> bool, + ) -> Result { + let mut deadline = Deadline::after_ms(1000); + loop { + self.sync_from_device(); + while let Some(event) = self.events.pop() { + self.retire_pending = true; + if wanted(&event) { + self.retire(); + return Ok(event); + } + } + self.retire(); + if self.op_reg(op::USBSTS).read() & op::USBSTS_HOST_ERROR != 0 { + return Err(Error::HostSystemError); + } + if deadline.expired() { + return Err(Error::Timeout(step)); + } + core::hint::spin_loop(); + } + } + + /// Tell the controller how far the event ring was consumed. + fn retire(&mut self) { + if self.retire_pending { + write64( + self.rt + rt::ERDP, + self.events.dequeue_pointer() | rt::ERDP_BUSY, + ); + self.retire_pending = false; + } + } + + /// Make CPU writes to the DMA memory visible to the controller. + fn sync_to_device(&self) { + clean_dcache_range(self.mem as usize, core::mem::size_of::()); + } + + /// Drop stale cached copies of what the controller writes. + fn sync_from_device(&self) { + // SAFETY: addresses of pages of the owned DMA memory. + let (events, buffer) = unsafe { + ( + addr_of_mut!((*self.mem).event_ring), + addr_of_mut!((*self.mem).buffer), + ) + }; + clean_invalidate_dcache_range(events as usize, PAGE_BYTES); + clean_invalidate_dcache_range(buffer as usize, PAGE_BYTES); + } +} + +fn wait(mut deadline: Deadline, mut done: impl FnMut() -> bool) -> Result<(), ()> { + while !done() { + if deadline.expired() { + return Err(()); + } + core::hint::spin_loop(); + } + Ok(()) +} + +/// Stop the controller, reset it and wait until it is ready for setup. +fn reset(op: usize) -> Result<(), Error> { + let usbcmd = MmioReg::::new(op + op::USBCMD); + let usbsts = MmioReg::::new(op + op::USBSTS); + if usbsts.read() == u32::MAX { + return Err(Error::Absent); + } + usbcmd.write(usbcmd.read() & !op::USBCMD_RUN); + wait(Deadline::after_ms(100), || { + usbsts.read() & op::USBSTS_HALTED != 0 + }) + .map_err(|()| Error::Timeout("controller halt"))?; + usbcmd.write(op::USBCMD_RESET); + wait(Deadline::after_ms(1000), || { + usbcmd.read() & op::USBCMD_RESET == 0 && usbsts.read() & op::USBSTS_NOT_READY == 0 + }) + .map_err(|()| Error::Timeout("controller reset")) +} diff --git a/crates/aienos-kernel/src/usb/xhci/mod.rs b/crates/aienos-kernel/src/usb/xhci/mod.rs index 00e82aa2..d5da37d2 100644 --- a/crates/aienos-kernel/src/usb/xhci/mod.rs +++ b/crates/aienos-kernel/src/usb/xhci/mod.rs @@ -5,6 +5,7 @@ //! access and controller bring-up follow in the next part of the series. pub mod context; +pub mod controller; pub mod ring; pub mod trb; From 928de21a99c2d66c60d5c82ef616dac5cda6f7eb Mon Sep 17 00:00:00 2001 From: Drake Date: Thu, 24 Sep 2026 09:46:30 -0500 Subject: [PATCH 4/4] boot(usb): wire and prove QEMU keyboard input (SEED-0A 2d) Co-authored-by: Drake Co-Authored-By: Claude Opus 5.5 --- crates/aienos-boot/Cargo.toml | 3 + crates/aienos-boot/src/handoff.rs | 11 ++ crates/aienos-boot/src/usb_keyboard.rs | 204 +++++++++++++++++++++++++ scripts/qemu_keyboard_test.sh | 144 +++++++++++++++++ scripts/verify_all.sh | 9 ++ 5 files changed, 371 insertions(+) create mode 100644 crates/aienos-boot/src/usb_keyboard.rs create mode 100755 scripts/qemu_keyboard_test.sh diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml index 379592f3..1fd60880 100644 --- a/crates/aienos-boot/Cargo.toml +++ b/crates/aienos-boot/Cargo.toml @@ -15,6 +15,9 @@ uefi-base = ["dep:uefi"] # UART after boot services exit, so the two features must not be combined. firmware = ["uefi-base", "uefi/panic_handler"] handoff = ["uefi-base", "dep:aienos-kernel", "dep:aienos-accel", "uefi/alloc", "uefi/global_allocator"] +# 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"] [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 68f02dc8..72b08f5e 100644 --- a/crates/aienos-boot/src/handoff.rs +++ b/crates/aienos-boot/src/handoff.rs @@ -45,6 +45,9 @@ use uefi::runtime::{ResetType, VariableAttributes, VariableVendor}; use uefi::table::cfg::ConfigTableEntry; use uefi::{cstr16, guid, CStr16}; +#[cfg(feature = "usb-keyboard")] +mod usb_keyboard; + /// Commit this image was built from; `scripts/stage_one_time_boot.sh` sets it. const COMMIT: &str = match option_env!("AIENOS_COMMIT") { Some(commit) => commit, @@ -396,6 +399,8 @@ unsafe fn table_at<'a>(addr: usize) -> Option<&'a [u8]> { struct AcpiFacts { cpu: Option, spcr: Option, + #[cfg(feature = "usb-keyboard")] + mcfg: Option<&'static [u8]>, } fn discover_acpi(boot_mpidr: u64) -> AcpiFacts { @@ -430,6 +435,8 @@ fn discover_acpi(boot_mpidr: u64) -> AcpiFacts { match &table[..4] { b"APIC" => facts.cpu = acpi::madt_cpu_topology_for(table, Some(boot_mpidr)).ok(), b"SPCR" => facts.spcr = acpi::spcr_console(table).ok(), + #[cfg(feature = "usb-keyboard")] + b"MCFG" => facts.mcfg = Some(table), _ => {} } } @@ -706,6 +713,8 @@ fn main() -> Status { stage(FRAMEBUFFER_DISCOVERY); let framebuffer = discover_framebuffer(); *FRAMEBUFFER.lock() = framebuffer; + #[cfg(feature = "usb-keyboard")] + let xhci = usb_keyboard::find_xhci(); let mut pre = Report::new(); header(&mut pre, "pre_exit"); @@ -878,5 +887,7 @@ fn main() -> Status { let _ = writeln!(s, "boot halted: no usable memory region"); } } + #[cfg(feature = "usb-keyboard")] + usb_keyboard::run(xhci, acpi_facts.mcfg, &mut screen); finish(screen) } diff --git a/crates/aienos-boot/src/usb_keyboard.rs b/crates/aienos-boot/src/usb_keyboard.rs new file mode 100644 index 00000000..d5a94870 --- /dev/null +++ b/crates/aienos-boot/src/usb_keyboard.rs @@ -0,0 +1,204 @@ +//! SEED-0A candidate `input.keyboard.usb` (ADR 0012): after firmware exit, +//! drive the xHCI controller with the polled AIENOS driver and echo typed +//! keys on the SPCR console and the screen. +//! +//! Built only with the `usb-keyboard` feature, which the QEMU keyboard test +//! enables and hardware staging does not: the candidate is proven in QEMU +//! and never admitted to Machine 1 before M3 can confine it. + +use aienos_kernel::acpi::{self, EcamWindow}; +use aienos_kernel::arch::aarch64::{counter_frequency_hz, counter_ticks, MmioReg}; +use aienos_kernel::console::EarlyConsole; +use aienos_kernel::display::Screen; +use aienos_kernel::usb::hid::{BootKeyboardDecoder, KeyEvent, TextSink}; +use aienos_kernel::usb::xhci::controller::{DmaMemory, Keyboard}; +use aienos_kernel::usb::xhci::{self, PCI_COMMAND_BUS_MASTER, PCI_COMMAND_MEMORY}; +use core::fmt::Write; +use uefi::boot::{OpenProtocolAttributes, OpenProtocolParams}; +use uefi::proto::pci::root_bridge::PciRootBridgeIo; +use uefi::proto::pci::PciIoAddress; + +/// Seconds to wait for a line; `AIENOS_KEYBOARD_SECS` at build time. +fn listen_secs() -> u64 { + option_env!("AIENOS_KEYBOARD_SECS") + .and_then(|s| s.parse().ok()) + .unwrap_or(30) +} + +/// DMA memory for the driver, used only after firmware exit. +static mut DMA: DmaMemory = DmaMemory::new(); + +/// Where the first xHCI controller sits, found before firmware exit. +#[derive(Clone, Copy)] +pub struct XhciLocation { + segment: u16, + bus: u8, + device: u8, + function: u8, + mmio: u64, +} + +/// Walk every root bridge for the first xHCI controller (pre-exit only). +pub fn find_xhci() -> Option { + for handle in uefi::boot::find_handles::().ok()? { + // Shared open, read-only use, as in GB10 discovery. + let params = OpenProtocolParams { + handle, + agent: uefi::boot::image_handle(), + controller: None, + }; + let Ok(mut root) = (unsafe { + uefi::boot::open_protocol::( + params, + OpenProtocolAttributes::GetProtocol, + ) + }) else { + continue; + }; + let (bus_min, bus_max) = crate::bus_ranges(&mut root).unwrap_or((0, 0)); + for bus in bus_min..=bus_max { + for device in 0..32u8 { + for function in 0..8u8 { + let address = PciIoAddress::new(bus, device, function); + let mut read = |offset| { + root.pci() + .read_one::(address.with_register(offset)) + .ok() + }; + let Some(_) = read(0).filter(|id| id & 0xffff != 0xffff) else { + if function == 0 { + break; + } + continue; + }; + let bar = (read(0x08), read(0x10), read(0x14)); + if let (Some(class), Some(low), Some(high)) = bar { + if let Some(mmio) = xhci::xhci_mmio_base(class, low, high) { + let segment = root.segment_nr() as u16; + return Some(XhciLocation { + segment, + bus, + device, + function, + mmio, + }); + } + } + let multi = read(0x0c).is_some_and(|v| v & 0x80_0000 != 0); + if function == 0 && !multi { + break; + } + } + } + } + } + None +} + +fn console() -> Option { + crate::CONSOLE + .try_lock() + .and_then(|k| *k) + .and_then(EarlyConsole::from_kind) +} + +/// Write `text` to the SPCR console and the screen. +fn say(screen: &mut Option, text: &str) { + if let Some(console) = console() { + console.write_str(text); + } + if let Some(s) = screen.as_mut() { + let _ = s.write_str(text); + } +} + +/// Enable memory decode and bus mastering through ECAM: firmware may have +/// turned them off when it stopped its own USB driver at exit. +fn enable_controller(ecam: &EcamWindow, at: &XhciLocation) -> bool { + let Some(addr) = ecam.config_address(at.bus, at.device, at.function, 0x04) else { + return false; + }; + let command = MmioReg::::new(addr as usize); + command.write(command.read() | PCI_COMMAND_MEMORY | PCI_COMMAND_BUS_MASTER); + true +} + +/// Post-exit: bring up the keyboard and echo keys until Enter or timeout. +pub fn run(xhci: Option, mcfg: Option<&[u8]>, screen: &mut Option) { + let mut line = aienos_kernel::report::ReportBuf::<160>::new(); + let Some(at) = xhci else { + say(screen, "\nkeyboard: unavailable (no xHCI controller)\n"); + return; + }; + let _ = writeln!( + line, + "\nkeyboard: xhci {:04x}:{:02x}:{:02x}.{} mmio {:#x}", + at.segment, at.bus, at.device, at.function, at.mmio + ); + say(screen, line.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( + screen, + "keyboard: unavailable (no ECAM window for the controller)\n", + ); + return; + } + // SAFETY: firmware has exited and released the controller; DMA is used + // by nothing else, is identity-mapped, and lives for the whole boot. + let started = unsafe { Keyboard::start(at.mmio, core::ptr::addr_of_mut!(DMA)) }; + 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})"); + say(screen, msg.as_str()); + return; + } + }; + let (port, slot, endpoint) = keyboard.location(); + let mut msg = aienos_kernel::report::ReportBuf::<200>::new(); + let _ = writeln!( + msg, + "keyboard: ready (port {port}, slot {slot}, endpoint {endpoint:#04x})" + ); + let _ = write!( + msg, + "keyboard: type a line, Enter ends it ({} s)\nkeyboard_echo: ", + listen_secs() + ); + say(screen, msg.as_str()); + + let mut decoder = BootKeyboardDecoder::new(); + let mut text = TextSink::<64>::new(); + let mut entered = false; + let deadline = listen_secs().saturating_mul(counter_frequency_hz()); + let start = counter_ticks(); + while !entered && counter_ticks().wrapping_sub(start) < deadline && !keyboard.is_halted() { + let Some(report) = keyboard.poll() else { + core::hint::spin_loop(); + continue; + }; + decoder.handle_report(&report, |event| { + if event == KeyEvent::Enter { + entered = true; + } else if let KeyEvent::Char(c) = event { + let mut buf = [0u8; 4]; + say(screen, c.encode_utf8(&mut buf)); + text.record(event); + } + }); + } + let mut end = aienos_kernel::report::ReportBuf::<200>::new(); + let reason = match (entered, keyboard.is_halted()) { + (true, _) => "enter", + (false, true) => "endpoint halted", + (false, false) => "timeout", + }; + let _ = writeln!( + end, + "\nkeyboard_line: {}\nkeyboard: done ({reason})", + text.as_str() + ); + say(screen, end.as_str()); +} diff --git a/scripts/qemu_keyboard_test.sh b/scripts/qemu_keyboard_test.sh new file mode 100755 index 00000000..7d776794 --- /dev/null +++ b/scripts/qemu_keyboard_test.sh @@ -0,0 +1,144 @@ +#!/usr/bin/env bash +# SEED-0A `input.keyboard.usb` proof in QEMU (ADR 0012): boot the handoff +# image built with the `usb-keyboard` feature on a qemu-xhci controller with +# a usb-kbd, wait until the AIENOS driver reports the keyboard ready after +# ExitBootServices, type keys through the QEMU monitor (`sendkey`), and check +# that the same text comes back on the serial console. Emulator only: it says +# nothing about Machine 1 hardware. +# +# A boot that shows no AIENOS output at all is retried (firmware hang before +# AIENOS runs, issue #61); any failure after AIENOS output fails at once. +# +# Needs qemu-system-aarch64 and AAVMF (Ubuntu: qemu-system-arm qemu-efi-aarch64). +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" + +code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" +vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}" +command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; exit 2; } + +keys=(a b c) +expected="abc" +attempts="${AIENOS_KEYBOARD_ATTEMPTS:-3}" +boot_timeout="${AIENOS_QEMU_TIMEOUT:-180}" + +# 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 \ + --target-dir target/qemu-keyboard + +work="$(mktemp -d)" +qemu_pid="" +cleanup() { + [[ -n "${qemu_pid}" ]] && kill "${qemu_pid}" 2>/dev/null || true + exec 3>&- 2>/dev/null || true + rm -rf "${work}" +} +trap cleanup EXIT +mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" +touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" +cp target/qemu-keyboard/aarch64-unknown-uefi/release/aienos-handoff.efi "${work}/esp/EFI/BOOT/BOOTAA64.EFI" + +serial_has() { tr -d '\r' 2>/dev/null <"${work}/serial.log" | grep -q -- "$1"; } +qemu_running() { kill -0 "${qemu_pid}" 2>/dev/null; } + +# Wait until the serial log contains one of the patterns or QEMU exits. +wait_for() { # seconds, pattern... + local deadline=$(( $(date +%s) + $1 )); shift + while (( $(date +%s) < deadline )) && qemu_running; do + for p in "$@"; do serial_has "${p}" && return 0; done + sleep 0.2 + done + for p in "$@"; do serial_has "${p}" && return 0; done + return 1 +} + +stop_qemu() { + if [[ -n "${qemu_pid}" ]]; then + kill "${qemu_pid}" 2>/dev/null || true + wait "${qemu_pid}" 2>/dev/null || true + fi + qemu_pid="" + exec 3>&- 2>/dev/null || true +} + +boot_once() { + cp "${vars_fd}" "${work}/vars.fd" + rm -f "${work}/serial.log" "${work}/mon.in" "${work}/mon.out" + mkfifo "${work}/mon.in" "${work}/mon.out" + qemu-system-aarch64 \ + -M virt,virtualization=on -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" \ + -device virtio-blk-pci,drive=esp \ + -device qemu-xhci,id=xhci -device usb-kbd,bus=xhci.0 \ + -device ramfb -display none -nic none \ + -chardev pipe,id=mon,path="${work}/mon" -mon chardev=mon,mode=readline \ + -serial file:"${work}/serial.log" -no-reboot & + qemu_pid=$! + # Drain monitor output so QEMU never blocks writing it. + cat "${work}/mon.out" >/dev/null & + exec 3>"${work}/mon.in" + + if ! wait_for "${boot_timeout}" "report_kind: pre_exit"; then + echo "attempt ${attempt}: no AIENOS output within ${boot_timeout} s (firmware hang, issue #61)" + stop_qemu + return 2 + fi + if wait_for "${boot_timeout}" "keyboard: ready" "keyboard: unavailable" "report_kind: panic" "report_kind: fault" \ + && serial_has "keyboard: ready"; then + for key in "${keys[@]}" ret; do + echo "sendkey ${key}" >&3 + sleep 0.3 + done + fi + local deadline=$(( $(date +%s) + 90 )) + while qemu_running && (( $(date +%s) < deadline )); do sleep 0.5; done + qemu_running && echo "QEMU still running after the keyboard phase" + stop_qemu + return 0 +} + +started=$(date +%s) +attempt=1 +while :; do + status=0 + boot_once || status=$? + [[ "${status}" != 2 || "${attempt}" -ge "${attempts}" ]] && break + attempt=$(( attempt + 1 )) +done +elapsed=$(( $(date +%s) - started )) + +tr -d '\r' <"${work}/serial.log" >"${work}/serial.txt" 2>/dev/null || true +failed=0 +check() { # description, pattern + if grep -q -- "$2" "${work}/serial.txt"; then + echo "PASS $1" + else + echo "FAIL $1" + failed=1 + fi +} +echo "attempts ${attempt}, ${elapsed} s (commit ${commit:0:12}), sent keys: ${keys[*]} ret" +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" +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)" +if grep -qE "report_kind: (panic|fault)" "${work}/serial.txt"; then + echo "FAIL panic or fault reported" + failed=1 +fi + +if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then + echo "---- serial console ----" + cat "${work}/serial.txt" +fi +[[ "${failed}" == 0 ]] && echo "QEMU_KEYBOARD: PASS" || { echo "QEMU_KEYBOARD: FAIL"; exit 1; } diff --git a/scripts/verify_all.sh b/scripts/verify_all.sh index 7a48b90c..ee0e7460 100755 --- a/scripts/verify_all.sh +++ b/scripts/verify_all.sh @@ -56,6 +56,15 @@ else echo "SKIPPED: qemu-system-aarch64 or AAVMF firmware not present on host." fi +# Step 6b: SEED-0A USB keyboard candidate, proven in QEMU only (ADR 0012). +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 +else + echo "SKIPPED: qemu-system-aarch64 or AAVMF firmware not present on host." +fi + echo "" echo "============================================================" echo "HOST VERIFICATIONS PASSED."