interplane.Get Omega
Read in your language

aienux

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

Brought by drakestapleton

GitHub aien-dev/aienux#73 (code only)

closed derived 6b8fe7bf26eb6650 #73

Imported from GitHub aien-dev/aienux#73 (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 6af6e015fbbfa15ece755b2f482a56438098c45d · Head 5c1418a61f647500cd472e9ffa8049e9928dee6a

Apply it

git checkout -b patch-6b8fe7bf26eb6650 6af6e015fbbfa15ece755b2f482a56438098c45d
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/6b8fe7bf26eb6650.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
73
5c1418a61f647500cd472e9ffa8049e9928dee6a
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":73,"url":"https://github.com/aien-dev/aienux/pull/73","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:43Z","metadata":"unavailable","state_derived":true}

Changes

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<u64> {
+        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<Option<EcamWindow>, AcpiError> {
+    let mcfg = checked_table(mcfg, b"MCFG")?;
+    let entries = mcfg.get(MCFG_ENTRIES_OFFSET..).ok_or(AcpiError::Truncated)?;
+    Ok(entries
+        .as_chunks::<MCFG_ENTRY_LEN>()
+        .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<u8> {
+        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<u8> {
+    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<BootKeyboard> {
+    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/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<u8> {
+    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<Self> {
+        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/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::<u32>::new(addr).write(value as u32);
+    MmioReg::<u32>::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<BootKeyboard>,
+    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<Self, Error> {
+        let base = mmio_base as usize;
+        let cap = |offset: usize| MmioReg::<u32>::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::<DmaMemory>() 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<u32> {
+        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::<u32>::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<u8, Error> {
+        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::<u32>::new(self.db + usize::from(target) * 4).write(u32::from(value));
+    }
+
+    fn command(&mut self, trb: Trb, step: &'static str) -> Result<Trb, Error> {
+        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<Trb, Error> {
+        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::<DmaMemory>());
+    }
+
+    /// 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::<u32>::new(op + op::USBCMD);
+    let usbsts = MmioReg::<u32>::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 1600bcd6..d5da37d2 100644
--- a/crates/aienos-kernel/src/usb/xhci/mod.rs
+++ b/crates/aienos-kernel/src/usb/xhci/mod.rs
@@ -1,5 +1,272 @@
-//! 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 controller;
+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<u64> {
+    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<Self> {
+        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);
+    }
+}
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<Self> {
+        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<Self> {
+        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<Trb> {
+        // 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<Trb> {
+            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());
+    }
+}