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

branch main Branches Tags History

aienux / crates / aienos-kernel / src / usb / xhci / trb.rs

409 lines · 14466 bytes Raw Blame History
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//! Transfer Request Blocks (xHCI 1.2 section 6.4): the 16-byte records that
17//! commands, transfers and events are made of, and the USB SETUP packet a
18//! control transfer carries.
19//!
20//! Only the TRB types the polled keyboard driver needs are built here. The
21//! cycle bit is left clear; the ring that writes a TRB owns that bit.
22
23/// TRB type numbers (xHCI 1.2 table 6-91).
24pub mod kind {
25 pub const NORMAL: u8 = 1;
26 pub const SETUP_STAGE: u8 = 2;
27 pub const DATA_STAGE: u8 = 3;
28 pub const STATUS_STAGE: u8 = 4;
29 pub const ISOCH: u8 = 5;
30 pub const LINK: u8 = 6;
31 pub const ENABLE_SLOT: u8 = 9;
32 pub const DISABLE_SLOT: u8 = 10;
33 pub const ADDRESS_DEVICE: u8 = 11;
34 pub const CONFIGURE_ENDPOINT: u8 = 12;
35 pub const EVALUATE_CONTEXT: u8 = 13;
36 pub const TRANSFER_EVENT: u8 = 32;
37 pub const COMMAND_COMPLETION: u8 = 33;
38 pub const PORT_STATUS_CHANGE: u8 = 34;
39}
40
41/// Completion codes the driver treats as success (xHCI 1.2 table 6-90).
42pub mod completion {
43 pub const SUCCESS: u8 = 1;
44 pub const SHORT_PACKET: u8 = 13;
45}
46
47/// Control dword (dword 3) flags.
48pub const CYCLE: u32 = 1 << 0;
49/// Link TRB: toggle the consumer cycle state when following this link.
50pub const TOGGLE_CYCLE: u32 = 1 << 1;
51/// Interrupt on short packet: report a short IN transfer on this TRB.
52pub const ISP: u32 = 1 << 2;
53/// Interrupt on completion: post an event when this TRB completes.
54pub const IOC: u32 = 1 << 5;
55/// Continue a transfer descriptor on the next TRB.
56pub const CHAIN: u32 = 1 << 4;
57/// Immediate data: the parameter dwords hold the data (Setup Stage only).
58pub const IDT: u32 = 1 << 6;
59/// Data and Status Stage direction bit: set for device-to-host.
60pub const DIR_IN: u32 = 1 << 16;
61const TYPE_SHIFT: u32 = 10;
62const SLOT_SHIFT: u32 = 24;
63/// Setup Stage transfer type (TRT) values, bits 17:16.
64const TRT_OUT: u32 = 2 << 16;
65const TRT_IN: u32 = 3 << 16;
66/// Isoch TRB Schedule Immediately, used when Frame ID is not selected.
67pub const SIA: u32 = 1 << 31;
68
69/// One 16-byte TRB as four little-endian dwords.
70#[repr(C, align(16))]
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
72pub struct Trb(pub [u32; 4]);
73
74fn split(addr: u64) -> (u32, u32) {
75 (addr as u32, (addr >> 32) as u32)
76}
77
78impl Trb {
79 fn new(parameter: u64, status: u32, trb_type: u8, flags: u32) -> Self {
80 let (lo, hi) = split(parameter);
81 Self([lo, hi, status, u32::from(trb_type) << TYPE_SHIFT | flags])
82 }
83
84 fn for_slot(parameter: u64, trb_type: u8, slot: u8) -> Self {
85 Self::new(parameter, 0, trb_type, u32::from(slot) << SLOT_SHIFT)
86 }
87
88 /// Link TRB back to `target` (the ring start), toggling the cycle state.
89 pub fn link(target: u64) -> Self {
90 Self::new(target, 0, kind::LINK, TOGGLE_CYCLE)
91 }
92
93 pub fn enable_slot() -> Self {
94 Self::new(0, 0, kind::ENABLE_SLOT, 0)
95 }
96
97 pub fn disable_slot(slot: u8) -> Self {
98 Self::for_slot(0, kind::DISABLE_SLOT, slot)
99 }
100
101 /// Address Device with the input context at `input_context`. Block Set
102 /// Address Request is clear, so the device receives SET_ADDRESS.
103 pub fn address_device(input_context: u64, slot: u8) -> Self {
104 Self::for_slot(input_context, kind::ADDRESS_DEVICE, slot)
105 }
106
107 pub fn configure_endpoint(input_context: u64, slot: u8) -> Self {
108 Self::for_slot(input_context, kind::CONFIGURE_ENDPOINT, slot)
109 }
110
111 pub fn evaluate_context(input_context: u64, slot: u8) -> Self {
112 Self::for_slot(input_context, kind::EVALUATE_CONTEXT, slot)
113 }
114
115 /// Setup Stage: the 8-byte SETUP packet as immediate data.
116 pub fn setup_stage(setup: &SetupPacket) -> Self {
117 let trt = match (setup.length, setup.is_in()) {
118 (0, _) => 0,
119 (_, true) => TRT_IN,
120 (_, false) => TRT_OUT,
121 };
122 let [lo, hi] = setup.dwords();
123 Self([
124 lo,
125 hi,
126 8,
127 u32::from(kind::SETUP_STAGE) << TYPE_SHIFT | IDT | trt,
128 ])
129 }
130
131 /// Data Stage of `setup.length` bytes at `buffer`.
132 pub fn data_stage(setup: &SetupPacket, buffer: u64) -> Self {
133 let dir = if setup.is_in() { DIR_IN } else { 0 };
134 Self::new(buffer, u32::from(setup.length), kind::DATA_STAGE, dir)
135 }
136
137 /// Status Stage, which runs opposite to the data (IN when there is none),
138 /// with an event on completion.
139 pub fn status_stage(setup: &SetupPacket) -> Self {
140 let dir = if setup.length > 0 && setup.is_in() {
141 0
142 } else {
143 DIR_IN
144 };
145 Self::new(0, 0, kind::STATUS_STAGE, dir | IOC)
146 }
147
148 /// Normal TRB for an interrupt-IN report of up to `length` bytes, with an
149 /// event on completion or on a short report.
150 pub fn normal(buffer: u64, length: u32) -> Self {
151 Self::new(buffer, length & 0x1_ffff, kind::NORMAL, IOC | ISP)
152 }
153
154 /// One isochronous OUT packet. SuperSpeed TBC/TLBPC are zero for an
155 /// endpoint without a companion descriptor; `last` terminates the batch.
156 pub fn isoch(buffer: u64, length: u32, frame_id: u16, sia: bool, last: bool) -> Self {
157 let mut flags =
158 (u32::from(frame_id & 0x7ff) << 20) | (u32::from(kind::ISOCH) << TYPE_SHIFT);
159 if sia {
160 flags |= SIA;
161 }
162 // One packet per TD: CHAIN would merge packets with different Frame
163 // IDs into a single TD. `last` only requests an interrupt on completion.
164 if last {
165 flags |= IOC;
166 }
167 Self::new(buffer, length & 0x1_ffff, kind::ISOCH, flags & !(0x7 << 7))
168 }
169
170 pub fn kind(&self) -> u8 {
171 ((self.0[3] >> TYPE_SHIFT) & 0x3f) as u8
172 }
173
174 pub fn cycle(&self) -> bool {
175 self.0[3] & CYCLE != 0
176 }
177
178 /// The same TRB with its cycle bit set to `cycle`.
179 pub fn with_cycle(mut self, cycle: bool) -> Self {
180 self.0[3] = self.0[3] & !CYCLE | u32::from(cycle);
181 self
182 }
183
184 /// Event TRBs: completion code, bits 31:24 of dword 2.
185 pub fn completion_code(&self) -> u8 {
186 (self.0[2] >> 24) as u8
187 }
188
189 /// Event and slot-command TRBs: slot ID, bits 31:24 of dword 3.
190 pub fn slot_id(&self) -> u8 {
191 (self.0[3] >> SLOT_SHIFT) as u8
192 }
193
194 /// Transfer events: endpoint (device context index), bits 20:16.
195 pub fn endpoint_id(&self) -> u8 {
196 ((self.0[3] >> 16) & 0x1f) as u8
197 }
198
199 /// Events: the TRB (or port) the event refers to, from dwords 0 and 1.
200 pub fn pointer(&self) -> u64 {
201 u64::from(self.0[1]) << 32 | u64::from(self.0[0])
202 }
203
204 /// Transfer events: bytes not transferred, bits 23:0 of dword 2.
205 pub fn residual(&self) -> u32 {
206 self.0[2] & 0x00ff_ffff
207 }
208
209 /// True for a completion code the driver accepts as a good transfer.
210 pub fn completed_ok(&self) -> bool {
211 matches!(
212 self.completion_code(),
213 completion::SUCCESS | completion::SHORT_PACKET
214 )
215 }
216}
217
218/// Standard and HID class request numbers the keyboard bring-up sends.
219pub mod request {
220 pub const GET_DESCRIPTOR: u8 = 0x06;
221 pub const SET_CONFIGURATION: u8 = 0x09;
222 pub const HID_SET_IDLE: u8 = 0x0a;
223 pub const HID_SET_PROTOCOL: u8 = 0x0b;
224 pub const DESCRIPTOR_DEVICE: u8 = 1;
225 pub const DESCRIPTOR_CONFIGURATION: u8 = 2;
226}
227
228/// The 8-byte USB SETUP packet (USB 2.0 section 9.3).
229#[derive(Clone, Copy, Debug, PartialEq, Eq)]
230pub struct SetupPacket {
231 pub request_type: u8,
232 pub request: u8,
233 pub value: u16,
234 pub index: u16,
235 pub length: u16,
236}
237
238impl SetupPacket {
239 /// Standard GET_DESCRIPTOR from the device.
240 pub fn get_descriptor(descriptor_type: u8, index: u8, length: u16) -> Self {
241 Self {
242 request_type: 0x80,
243 request: request::GET_DESCRIPTOR,
244 value: u16::from(descriptor_type) << 8 | u16::from(index),
245 index: 0,
246 length,
247 }
248 }
249
250 pub fn set_configuration(value: u8) -> Self {
251 Self {
252 request_type: 0x00,
253 request: request::SET_CONFIGURATION,
254 value: u16::from(value),
255 index: 0,
256 length: 0,
257 }
258 }
259
260 /// HID SET_PROTOCOL(boot) to `interface`, so reports use the 8-byte boot
261 /// layout whatever the report descriptor says.
262 pub fn set_boot_protocol(interface: u8) -> Self {
263 Self {
264 request_type: 0x21,
265 request: request::HID_SET_PROTOCOL,
266 value: 0,
267 index: u16::from(interface),
268 length: 0,
269 }
270 }
271
272 /// HID SET_IDLE(0): report only on change, never repeat unchanged state.
273 pub fn set_idle_forever(interface: u8) -> Self {
274 Self {
275 request_type: 0x21,
276 request: request::HID_SET_IDLE,
277 value: 0,
278 index: u16::from(interface),
279 length: 0,
280 }
281 }
282
283 pub fn is_in(&self) -> bool {
284 self.request_type & 0x80 != 0
285 }
286
287 /// The packet as the two little-endian dwords of a Setup Stage TRB.
288 pub fn dwords(&self) -> [u32; 2] {
289 [
290 u32::from(self.request_type)
291 | u32::from(self.request) << 8
292 | u32::from(self.value) << 16,
293 u32::from(self.index) | u32::from(self.length) << 16,
294 ]
295 }
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 #[test]
303 fn trb_is_sixteen_bytes_and_sixteen_aligned() {
304 assert_eq!(core::mem::size_of::<Trb>(), 16);
305 assert_eq!(core::mem::align_of::<Trb>(), 16);
306 }
307
308 #[test]
309 fn setup_packet_bytes_match_the_usb_wire_order() {
310 // GET_DESCRIPTOR(device, 18): 80 06 00 01 00 00 12 00.
311 let get = SetupPacket::get_descriptor(request::DESCRIPTOR_DEVICE, 0, 18);
312 assert_eq!(get.dwords(), [0x0100_0680, 0x0012_0000]);
313 // SET_PROTOCOL(boot) on interface 1: 21 0b 00 00 01 00 00 00.
314 assert_eq!(
315 SetupPacket::set_boot_protocol(1).dwords(),
316 [0x0000_0b21, 0x0000_0001]
317 );
318 assert_eq!(SetupPacket::set_configuration(1).dwords(), [0x0001_0900, 0]);
319 }
320
321 #[test]
322 fn control_stages_carry_idt_transfer_type_and_directions() {
323 let get = SetupPacket::get_descriptor(request::DESCRIPTOR_CONFIGURATION, 0, 64);
324 let setup = Trb::setup_stage(&get);
325 assert_eq!(setup.kind(), kind::SETUP_STAGE);
326 assert_eq!(setup.0[2], 8, "setup TRB transfer length is always 8");
327 assert_ne!(setup.0[3] & IDT, 0, "setup data is immediate");
328 assert_eq!(setup.0[3] & (3 << 16), TRT_IN);
329 let data = Trb::data_stage(&get, 0x1234_5678_9abc_def0);
330 assert_eq!(data.kind(), kind::DATA_STAGE);
331 assert_eq!(data.pointer(), 0x1234_5678_9abc_def0);
332 assert_eq!(data.0[2], 64);
333 assert_ne!(data.0[3] & DIR_IN, 0);
334 let status = Trb::status_stage(&get);
335 assert_eq!(status.kind(), kind::STATUS_STAGE);
336 assert_eq!(status.0[3] & DIR_IN, 0, "status runs OUT after IN data");
337 assert_ne!(status.0[3] & IOC, 0);
338
339 let none = SetupPacket::set_configuration(1);
340 assert_eq!(Trb::setup_stage(&none).0[3] & (3 << 16), 0, "no data stage");
341 assert_ne!(Trb::status_stage(&none).0[3] & DIR_IN, 0, "status IN");
342 }
343
344 #[test]
345 fn command_trbs_place_slot_and_input_context() {
346 let address = Trb::address_device(0x8000_1000, 3);
347 assert_eq!(address.kind(), kind::ADDRESS_DEVICE);
348 assert_eq!(address.slot_id(), 3);
349 assert_eq!(address.pointer(), 0x8000_1000);
350 assert_eq!(Trb::enable_slot().0, [0, 0, 0, 9 << 10]);
351 assert_eq!(
352 Trb::configure_endpoint(0x40, 1).kind(),
353 kind::CONFIGURE_ENDPOINT
354 );
355 assert_eq!(
356 Trb::evaluate_context(0x40, 1).kind(),
357 kind::EVALUATE_CONTEXT
358 );
359 assert_eq!(Trb::disable_slot(2).slot_id(), 2);
360 }
361
362 #[test]
363 fn event_fields_decode_from_their_bit_positions() {
364 // Transfer event: TRB pointer, residual 3, short packet, EP 3, slot 1.
365 let event = Trb([0x1000, 0x2, 13 << 24 | 3, 1 << 24 | 3 << 16 | 32 << 10 | 1]);
366 assert_eq!(event.kind(), kind::TRANSFER_EVENT);
367 assert_eq!(event.pointer(), 0x2_0000_1000);
368 assert_eq!(event.residual(), 3);
369 assert_eq!(event.completion_code(), completion::SHORT_PACKET);
370 assert!(event.completed_ok());
371 assert_eq!(event.endpoint_id(), 3);
372 assert_eq!(event.slot_id(), 1);
373 assert!(event.cycle());
374 assert!(!event.with_cycle(false).cycle());
375 // Stall (code 6) is not a good completion.
376 assert!(!Trb([0, 0, 6 << 24, 0]).completed_ok());
377 }
378
379 #[test]
380 fn normal_trb_asks_for_an_event_on_short_reports() {
381 let normal = Trb::normal(0x9000, 8);
382 assert_eq!(normal.kind(), kind::NORMAL);
383 assert_eq!(normal.0[2], 8);
384 assert_eq!(normal.0[3] & (IOC | ISP), IOC | ISP);
385 let link = Trb::link(0x4000);
386 assert_eq!(link.kind(), kind::LINK);
387 assert_ne!(link.0[3] & TOGGLE_CYCLE, 0);
388 }
389
390 #[test]
391 fn isoch_trb_encodes_frame_id_and_batch_flags() {
392 let first = Trb::isoch(0x1234_5678_9abc_def0, 176, 0x456, false, false);
393 assert_eq!(first.kind(), kind::ISOCH);
394 assert_eq!(first.pointer(), 0x1234_5678_9abc_def0);
395 assert_eq!(first.0[2], 176);
396 assert_eq!((first.0[3] >> 20) & 0x7ff, 0x456);
397 assert_eq!(
398 first.0[3] & CHAIN,
399 0,
400 "each isochronous packet is its own TD"
401 );
402 assert_eq!(first.0[3] & IOC, 0);
403 assert_eq!(first.0[3] & (7 << 7), 0, "SuperSpeed companion fields zero");
404 let last = Trb::isoch(0x2000, 180, 7, true, true);
405 assert_ne!(last.0[3] & SIA, 0);
406 assert_ne!(last.0[3] & IOC, 0);
407 assert_eq!(last.0[3] & CHAIN, 0);
408 }
409}