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

closed derived 88ff16b6dd33904c #71

Imported from GitHub aien-dev/aienux#71 (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 a2fefc28df2ef6f7de37ba192c9faf1decaad8fe

Apply it

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

Changes

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..280f51be 100644
--- a/crates/aienos-kernel/src/usb/xhci/mod.rs
+++ b/crates/aienos-kernel/src/usb/xhci/mod.rs
@@ -2,4 +2,6 @@
 //! driver, host-tested against the xHCI 1.2 specification. Register access
 //! and controller bring-up come later in the series and build on these.
 
+pub mod context;
+pub mod ring;
 pub mod trb;
diff --git a/crates/aienos-kernel/src/usb/xhci/ring.rs b/crates/aienos-kernel/src/usb/xhci/ring.rs
new file mode 100644
index 00000000..03088afb
--- /dev/null
+++ b/crates/aienos-kernel/src/usb/xhci/ring.rs
@@ -0,0 +1,271 @@
+//! Command, transfer and event rings (xHCI 1.2 section 4.9).
+//!
+//! A producer ring (command or transfer) is written by software and consumed
+//! by the controller; its last slot holds a Link TRB back to the start with
+//! Toggle Cycle set. An event ring is written by the controller and consumed
+//! by software; it has no Link TRB, so the consumer wraps and flips its cycle
+//! state at the end of the single segment.
+//!
+//! Ownership of each TRB is carried by its cycle bit. The producer writes
+//! dwords 0 to 2 first and the dword holding the cycle bit last, with a
+//! barrier between, so the controller never sees a half-written TRB as valid.
+//! The consumer reads the cycle bit first and the rest only after a barrier.
+//! Cache maintenance for non-coherent DMA is the caller's job.
+
+use super::trb::{Trb, CYCLE};
+use crate::arch::aarch64::dmb;
+use core::ptr::{read_volatile, write_volatile};
+
+const TRB_BYTES: u64 = 16;
+
+/// Software-produced ring (command ring or one endpoint's transfer ring).
+///
+/// The driver waits for each command or transfer to complete before pushing
+/// the next, so the ring can never lap the controller.
+pub struct ProducerRing {
+    base: *mut Trb,
+    len: usize,
+    dma: u64,
+    enqueue: usize,
+    cycle: bool,
+}
+
+impl ProducerRing {
+    /// Take over `len` TRBs at `base`, zero them and install the Link TRB.
+    /// `None` when the ring is too short to hold a TRB and its link.
+    ///
+    /// # Safety
+    /// `base` must be valid for reads and writes of `len` TRBs for as long as
+    /// the ring is used, not accessed through any other path meanwhile, and
+    /// `dma` must be the controller-visible address of `base`.
+    pub unsafe fn new(base: *mut Trb, len: usize, dma: u64) -> Option<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());
+    }
+}