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#72 (code only)

closed derived c7506f33a525a377 #72

Imported from GitHub aien-dev/aienux#72 (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 3ea3af09fee5acf2e195b2ab341de8a927c83ac5

Apply it

git checkout -b patch-c7506f33a525a377 6af6e015fbbfa15ece755b2f482a56438098c45d
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/c7506f33a525a377.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
72
3ea3af09fee5acf2e195b2ab341de8a927c83ac5
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":72,"url":"https://github.com/aien-dev/aienux/pull/72","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/mod.rs b/crates/aienos-kernel/src/usb/xhci/mod.rs
index 1600bcd6..00e82aa2 100644
--- a/crates/aienos-kernel/src/usb/xhci/mod.rs
+++ b/crates/aienos-kernel/src/usb/xhci/mod.rs
@@ -1,5 +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<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());
+    }
+}