aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / aienos-kernel / src / usb / xhci / ring.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Command, transfer and event rings (xHCI 1.2 section 4.9). |
| 17 | //! |
| 18 | //! A producer ring (command or transfer) is written by software and consumed |
| 19 | //! by the controller; its last slot holds a Link TRB back to the start with |
| 20 | //! Toggle Cycle set. An event ring is written by the controller and consumed |
| 21 | //! by software; it has no Link TRB, so the consumer wraps and flips its cycle |
| 22 | //! state at the end of the single segment. |
| 23 | //! |
| 24 | //! Ownership of each TRB is carried by its cycle bit. The producer writes |
| 25 | //! dwords 0 to 2 first and the dword holding the cycle bit last, with a |
| 26 | //! barrier between, so the controller never sees a half-written TRB as valid. |
| 27 | //! The consumer reads the cycle bit first and the rest only after a barrier. |
| 28 | //! Cache maintenance for non-coherent DMA is the caller's job. |
| 29 | |
| 30 | use super::trb::{Trb, CYCLE}; |
| 31 | use crate::arch::aarch64::dmb; |
| 32 | use core::ptr::{read_volatile, write_volatile}; |
| 33 | |
| 34 | const TRB_BYTES: u64 = 16; |
| 35 | |
| 36 | /// Software-produced ring (command ring or one endpoint's transfer ring). |
| 37 | /// |
| 38 | /// The driver waits for each command or transfer to complete before pushing |
| 39 | /// the next, so the ring can never lap the controller. |
| 40 | pub struct ProducerRing { |
| 41 | base: *mut Trb, |
| 42 | len: usize, |
| 43 | dma: u64, |
| 44 | enqueue: usize, |
| 45 | cycle: bool, |
| 46 | } |
| 47 | |
| 48 | impl ProducerRing { |
| 49 | /// Take over `len` TRBs at `base`, zero them and install the Link TRB. |
| 50 | /// `None` when the ring is too short to hold a TRB and its link. |
| 51 | /// |
| 52 | /// # Safety |
| 53 | /// `base` must be valid for reads and writes of `len` TRBs for as long as |
| 54 | /// the ring is used, not accessed through any other path meanwhile, and |
| 55 | /// `dma` must be the controller-visible address of `base`. |
| 56 | pub unsafe fn new(base: *mut Trb, len: usize, dma: u64) -> Option<Self> { |
| 57 | if len < 2 { |
| 58 | return None; |
| 59 | } |
| 60 | for i in 0..len { |
| 61 | // SAFETY: in bounds by the caller's contract. |
| 62 | unsafe { write_volatile(base.add(i), Trb::default()) }; |
| 63 | } |
| 64 | // The link starts with cycle 0: the controller (cycle 1) must not |
| 65 | // follow it until the producer reaches it and hands it over. |
| 66 | // SAFETY: `len - 1` is in bounds. |
| 67 | unsafe { write_volatile(base.add(len - 1), Trb::link(dma)) }; |
| 68 | Some(Self { |
| 69 | base, |
| 70 | len, |
| 71 | dma, |
| 72 | enqueue: 0, |
| 73 | cycle: true, |
| 74 | }) |
| 75 | } |
| 76 | |
| 77 | /// Controller-visible address of the ring start. |
| 78 | pub fn dma(&self) -> u64 { |
| 79 | self.dma |
| 80 | } |
| 81 | |
| 82 | /// Enqueue pointer with the producer cycle state in bit 0, the format of |
| 83 | /// CRCR and of an endpoint context's TR Dequeue Pointer. |
| 84 | pub fn dequeue_pointer(&self) -> u64 { |
| 85 | (self.dma + self.enqueue as u64 * TRB_BYTES) | u64::from(self.cycle) |
| 86 | } |
| 87 | |
| 88 | /// Write `trb` at the enqueue slot, owned by the controller, and return |
| 89 | /// its controller-visible address (events name completed TRBs by it). |
| 90 | pub fn push(&mut self, trb: Trb) -> u64 { |
| 91 | let addr = self.dma + self.enqueue as u64 * TRB_BYTES; |
| 92 | self.write_owned(self.enqueue, trb); |
| 93 | self.enqueue += 1; |
| 94 | if self.enqueue == self.len - 1 { |
| 95 | // SAFETY: the link slot is in bounds. |
| 96 | let link = unsafe { read_volatile(self.base.add(self.len - 1)) }; |
| 97 | self.write_owned(self.len - 1, link); |
| 98 | self.enqueue = 0; |
| 99 | self.cycle = !self.cycle; |
| 100 | } |
| 101 | addr |
| 102 | } |
| 103 | |
| 104 | /// Enqueue a batch of isochronous packets, chaining all but the last and |
| 105 | /// requesting one completion event for the batch. Returns TRB addresses. |
| 106 | pub fn push_isoch_batch(&mut self, packets: &[Trb], addresses: &mut [u64]) -> usize { |
| 107 | let count = packets.len().min(addresses.len()); |
| 108 | for (i, packet) in packets[..count].iter().enumerate() { |
| 109 | let mut trb = *packet; |
| 110 | trb.0[3] &= !(super::trb::IOC | super::trb::CHAIN); |
| 111 | trb.0[3] |= if i + 1 == count { |
| 112 | super::trb::IOC |
| 113 | } else { |
| 114 | super::trb::CHAIN |
| 115 | }; |
| 116 | addresses[i] = self.push(trb); |
| 117 | } |
| 118 | count |
| 119 | } |
| 120 | |
| 121 | fn write_owned(&mut self, index: usize, trb: Trb) { |
| 122 | let trb = trb.with_cycle(self.cycle); |
| 123 | // SAFETY: `index < len` at every call site. |
| 124 | let slot = unsafe { self.base.add(index) } as *mut u32; |
| 125 | for i in 0..3 { |
| 126 | // SAFETY: dwords 0..3 of an in-bounds TRB. |
| 127 | unsafe { write_volatile(slot.add(i), trb.0[i]) }; |
| 128 | } |
| 129 | dmb(); |
| 130 | // SAFETY: dword 3 of the same TRB. |
| 131 | unsafe { write_volatile(slot.add(3), trb.0[3]) }; |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | /// Controller-produced event ring of one segment. |
| 136 | pub struct EventRing { |
| 137 | base: *const Trb, |
| 138 | len: usize, |
| 139 | dma: u64, |
| 140 | dequeue: usize, |
| 141 | cycle: bool, |
| 142 | } |
| 143 | |
| 144 | impl EventRing { |
| 145 | /// Take over `len` TRBs at `base` and zero them. `None` when empty. |
| 146 | /// |
| 147 | /// # Safety |
| 148 | /// As for [`ProducerRing::new`]: `base` valid for `len` TRBs for the |
| 149 | /// ring's lifetime, written only by the controller afterwards, and `dma` |
| 150 | /// its controller-visible address. |
| 151 | pub unsafe fn new(base: *mut Trb, len: usize, dma: u64) -> Option<Self> { |
| 152 | if len == 0 || len > u16::MAX as usize { |
| 153 | return None; |
| 154 | } |
| 155 | for i in 0..len { |
| 156 | // SAFETY: in bounds by the caller's contract. |
| 157 | unsafe { write_volatile(base.add(i), Trb::default()) }; |
| 158 | } |
| 159 | Some(Self { |
| 160 | base, |
| 161 | len, |
| 162 | dma, |
| 163 | dequeue: 0, |
| 164 | cycle: true, |
| 165 | }) |
| 166 | } |
| 167 | |
| 168 | /// The single Event Ring Segment Table entry describing this ring. |
| 169 | pub fn segment_table_entry(&self) -> [u32; 4] { |
| 170 | [self.dma as u32, (self.dma >> 32) as u32, self.len as u32, 0] |
| 171 | } |
| 172 | |
| 173 | /// Address of the next event to consume, the value for ERDP. |
| 174 | pub fn dequeue_pointer(&self) -> u64 { |
| 175 | self.dma + self.dequeue as u64 * TRB_BYTES |
| 176 | } |
| 177 | |
| 178 | /// The next event, if the controller has written one. |
| 179 | pub fn pop(&mut self) -> Option<Trb> { |
| 180 | // SAFETY: `dequeue < len`, in bounds by the constructor's contract. |
| 181 | let slot = unsafe { self.base.add(self.dequeue) } as *const u32; |
| 182 | // SAFETY: dword 3 of an in-bounds TRB. |
| 183 | let control = unsafe { read_volatile(slot.add(3)) }; |
| 184 | if (control & CYCLE != 0) != self.cycle { |
| 185 | return None; |
| 186 | } |
| 187 | dmb(); |
| 188 | let mut trb = Trb([0, 0, 0, control]); |
| 189 | for i in 0..3 { |
| 190 | // SAFETY: dwords 0..3 of the same TRB. |
| 191 | trb.0[i] = unsafe { read_volatile(slot.add(i)) }; |
| 192 | } |
| 193 | self.dequeue += 1; |
| 194 | if self.dequeue == self.len { |
| 195 | self.dequeue = 0; |
| 196 | self.cycle = !self.cycle; |
| 197 | } |
| 198 | Some(trb) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | #[cfg(test)] |
| 203 | mod tests { |
| 204 | use super::super::trb::{kind, TOGGLE_CYCLE}; |
| 205 | use super::*; |
| 206 | |
| 207 | /// Minimal model of the controller consuming a producer ring: follow |
| 208 | /// TRBs while their cycle bit matches, obey Link TRBs and Toggle Cycle. |
| 209 | struct Consumer { |
| 210 | index: usize, |
| 211 | cycle: bool, |
| 212 | } |
| 213 | |
| 214 | impl Consumer { |
| 215 | fn take(&mut self, ring: &[Trb]) -> Option<Trb> { |
| 216 | loop { |
| 217 | let trb = ring[self.index]; |
| 218 | if trb.cycle() != self.cycle { |
| 219 | return None; |
| 220 | } |
| 221 | if trb.kind() == kind::LINK { |
| 222 | assert_eq!(trb.pointer(), ring.as_ptr() as u64, "link targets start"); |
| 223 | if trb.0[3] & TOGGLE_CYCLE != 0 { |
| 224 | self.cycle = !self.cycle; |
| 225 | } |
| 226 | self.index = 0; |
| 227 | continue; |
| 228 | } |
| 229 | self.index += 1; |
| 230 | return Some(trb); |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | #[test] |
| 236 | fn controller_sees_every_push_in_order_across_many_wraps() { |
| 237 | let mut memory = [Trb::default(); 4]; |
| 238 | let dma = memory.as_ptr() as u64; |
| 239 | // SAFETY: `memory` outlives the ring and is only read below. |
| 240 | let mut ring = unsafe { ProducerRing::new(memory.as_mut_ptr(), 4, dma) }.unwrap(); |
| 241 | let mut consumer = Consumer { |
| 242 | index: 0, |
| 243 | cycle: true, |
| 244 | }; |
| 245 | assert!(consumer.take(&memory).is_none(), "fresh ring is empty"); |
| 246 | for n in 0..20u32 { |
| 247 | let expected = dma + 16 * (n as u64 % 3); |
| 248 | assert_eq!( |
| 249 | ring.push(Trb([n, 0, 0, u32::from(kind::NORMAL) << 10])), |
| 250 | expected |
| 251 | ); |
| 252 | let seen = consumer.take(&memory).expect("pushed TRB is visible"); |
| 253 | assert_eq!(seen.0[0], n); |
| 254 | assert!(consumer.take(&memory).is_none(), "nothing beyond the push"); |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | #[test] |
| 259 | fn dequeue_pointer_carries_the_cycle_state_and_flips_after_the_link() { |
| 260 | let mut memory = [Trb::default(); 3]; |
| 261 | let dma = memory.as_ptr() as u64; |
| 262 | // SAFETY: as above. |
| 263 | let mut ring = unsafe { ProducerRing::new(memory.as_mut_ptr(), 3, dma) }.unwrap(); |
| 264 | assert_eq!(ring.dequeue_pointer(), dma | 1); |
| 265 | ring.push(Trb::default()); |
| 266 | assert_eq!(ring.dequeue_pointer(), (dma + 16) | 1); |
| 267 | ring.push(Trb::default()); |
| 268 | assert_eq!(ring.dequeue_pointer(), dma, "wrapped with cycle 0"); |
| 269 | assert!(memory[2].cycle(), "link handed over with the old cycle"); |
| 270 | assert!(unsafe { ProducerRing::new(memory.as_mut_ptr(), 1, dma) }.is_none()); |
| 271 | } |
| 272 | |
| 273 | #[test] |
| 274 | fn event_ring_consumes_matching_cycles_and_wraps_without_a_link() { |
| 275 | let mut memory = [Trb::default(); 3]; |
| 276 | let dma = memory.as_ptr() as u64; |
| 277 | // SAFETY: the test plays the controller through `base` only. |
| 278 | let base = memory.as_mut_ptr(); |
| 279 | let mut ring = unsafe { EventRing::new(base, 3, dma) }.unwrap(); |
| 280 | assert_eq!( |
| 281 | ring.segment_table_entry(), |
| 282 | [dma as u32, (dma >> 32) as u32, 3, 0] |
| 283 | ); |
| 284 | let post = |i: usize, id: u32, cycle: bool| unsafe { |
| 285 | base.add(i) |
| 286 | .write_volatile(Trb([id, 0, 1 << 24, 33 << 10]).with_cycle(cycle)); |
| 287 | }; |
| 288 | assert!(ring.pop().is_none()); |
| 289 | for (i, id) in [(0, 10), (1, 11), (2, 12)] { |
| 290 | post(i, id, true); |
| 291 | } |
| 292 | assert_eq!(ring.pop().unwrap().0[0], 10); |
| 293 | assert_eq!(ring.dequeue_pointer(), dma + 16); |
| 294 | assert_eq!(ring.pop().unwrap().0[0], 11); |
| 295 | assert_eq!(ring.pop().unwrap().0[0], 12); |
| 296 | assert_eq!(ring.dequeue_pointer(), dma, "wrapped at the segment end"); |
| 297 | // Old events (cycle 1) are not consumed twice after the wrap. |
| 298 | assert!(ring.pop().is_none()); |
| 299 | post(0, 13, false); |
| 300 | assert_eq!(ring.pop().unwrap().0[0], 13); |
| 301 | assert!(ring.pop().is_none()); |
| 302 | } |
| 303 | } |