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 / context.rs

319 lines · 11966 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//! Input contexts for Address Device, Evaluate Context and Configure
17//! Endpoint (xHCI 1.2 section 6.2), plus the speed and interval rules the
18//! driver needs to fill them.
19//!
20//! An input context is an Input Control Context followed by a Slot Context
21//! and one Endpoint Context per device context index (DCI 1 is the default
22//! control endpoint). Each is 32 bytes, or 64 when HCCPARAMS1.CSZ is set.
23
24/// Port speed IDs from PORTSC (default Protocol Speed ID mapping).
25pub mod speed {
26 pub const FULL: u8 = 1;
27 pub const LOW: u8 = 2;
28 pub const HIGH: u8 = 3;
29 pub const SUPER: u8 = 4;
30}
31
32/// Endpoint Context EP Type values.
33pub const EP_TYPE_CONTROL: u8 = 4;
34pub const EP_TYPE_INTERRUPT_IN: u8 = 7;
35pub const EP_TYPE_ISOCH_OUT: u8 = 1;
36/// Error count: retry a failing transaction three times before halting.
37const CERR: u32 = 3;
38/// Device context index of the default control endpoint.
39pub const CONTROL_DCI: u8 = 1;
40/// Highest device context index.
41const MAX_DCI: u8 = 31;
42
43/// Default control endpoint packet size before the device descriptor is read.
44pub fn default_control_max_packet(port_speed: u8) -> u16 {
45 match port_speed {
46 speed::HIGH => 64,
47 s if s >= speed::SUPER => 512,
48 _ => 8,
49 }
50}
51
52/// Endpoint Context Interval (period 125 us * 2^n) for an interrupt
53/// endpoint's bInterval. Full and low speed give bInterval in 1 ms frames;
54/// high and super speed already give it as 2^(bInterval - 1) microframes.
55pub fn interrupt_interval(port_speed: u8, b_interval: u8) -> u8 {
56 match port_speed {
57 speed::FULL | speed::LOW => {
58 let microframes = u32::from(b_interval.max(1)) * 8;
59 (31 - microframes.leading_zeros()).clamp(3, 10) as u8
60 }
61 _ => b_interval.clamp(1, 16) - 1,
62 }
63}
64
65/// xHCI Interval for an isochronous endpoint (xHCI 1.2 section 6.2.3.6):
66/// full speed counts 1 ms frames as 2^(bInterval-1), i.e. bInterval + 2 in
67/// 125 us exponent units; high/super speed use bInterval - 1 directly.
68/// (Interrupt endpoints follow a different full-speed rule.)
69pub fn isoch_interval(port_speed: u8, b_interval: u8) -> u8 {
70 let b = b_interval.clamp(1, 16);
71 match port_speed {
72 speed::FULL | speed::LOW => b + 2,
73 _ => b - 1,
74 }
75}
76
77/// Configure an isochronous OUT endpoint from the raw `wMaxPacketSize`.
78/// Bits 10:0 are the packet size; for high speed, bits 12:11 are the extra
79/// transactions per microframe, which go in Max Burst Size (Mult is
80/// SuperSpeed-only). `max_esit_payload` is the bytes per service interval.
81pub fn isoch_out_endpoint(
82 port_speed: u8,
83 b_interval: u8,
84 w_max_packet_size: u16,
85 max_esit_payload: u16,
86 dequeue: u64,
87) -> EndpointConfig {
88 let high_bandwidth = if port_speed == speed::HIGH {
89 ((w_max_packet_size >> 11) & 0x3) as u8
90 } else {
91 0
92 };
93 EndpointConfig {
94 ep_type: EP_TYPE_ISOCH_OUT,
95 max_packet: w_max_packet_size & 0x7ff,
96 max_burst: high_bandwidth,
97 interval: isoch_interval(port_speed, b_interval),
98 dequeue,
99 average_trb_length: max_esit_payload,
100 max_esit_payload,
101 }
102}
103
104/// Device context index for a non-control endpoint address such as 0x81.
105pub fn endpoint_dci(endpoint_address: u8) -> Option<u8> {
106 let number = endpoint_address & 0x0f;
107 if number == 0 {
108 return None;
109 }
110 Some(number * 2 + u8::from(endpoint_address & 0x80 != 0))
111}
112
113/// What one Endpoint Context says.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct EndpointConfig {
116 pub ep_type: u8,
117 pub max_packet: u16,
118 /// Max Burst Size (Endpoint Context dword 1 bits 15:8).
119 pub max_burst: u8,
120 pub interval: u8,
121 /// TR Dequeue Pointer with the Dequeue Cycle State in bit 0.
122 pub dequeue: u64,
123 pub average_trb_length: u16,
124 pub max_esit_payload: u16,
125}
126
127/// An input context being filled in caller-owned, zeroed memory.
128pub struct InputContext<'a> {
129 words: &'a mut [u32],
130 stride: usize,
131}
132
133impl<'a> InputContext<'a> {
134 /// Zero `words` and lay out an input context with `context_bytes`-sized
135 /// entries. `None` for a size other than 32 or 64 or too little memory.
136 pub fn new(words: &'a mut [u32], context_bytes: usize) -> Option<Self> {
137 let stride = match context_bytes {
138 32 => 8,
139 64 => 16,
140 _ => return None,
141 };
142 // Input control context, slot context and 31 endpoint contexts.
143 if words.len() < stride * (usize::from(MAX_DCI) + 2) {
144 return None;
145 }
146 words.fill(0);
147 Some(Self { words, stride })
148 }
149
150 fn entry(&mut self, index: usize) -> &mut [u32] {
151 let start = index * self.stride;
152 &mut self.words[start..start + 8]
153 }
154
155 /// Add Context flags: bit 0 the slot context, bit n the endpoint of DCI n.
156 pub fn add(&mut self, flags: u32) {
157 self.entry(0)[1] = flags;
158 }
159
160 /// Slot Context for a device on root hub port `root_port` (1-based, no
161 /// hub route) whose highest valid endpoint is `context_entries`.
162 pub fn slot(&mut self, port_speed: u8, root_port: u8, context_entries: u8) {
163 let slot = self.entry(1);
164 slot[0] = u32::from(context_entries & 0x1f) << 27 | u32::from(port_speed & 0xf) << 20;
165 slot[1] = u32::from(root_port) << 16;
166 }
167
168 /// Endpoint Context for `dci` (1..=31); other indexes are ignored.
169 pub fn endpoint(&mut self, dci: u8, config: &EndpointConfig) {
170 if !(1..=MAX_DCI).contains(&dci) {
171 return;
172 }
173 let ep = self.entry(usize::from(dci) + 1);
174 ep[0] = u32::from(config.interval) << 16;
175 ep[1] = CERR << 1
176 | u32::from(config.ep_type & 0x7) << 3
177 | u32::from(config.max_burst) << 8
178 | u32::from(config.max_packet) << 16;
179 ep[2] = config.dequeue as u32;
180 ep[3] = (config.dequeue >> 32) as u32;
181 ep[4] = u32::from(config.average_trb_length) | u32::from(config.max_esit_payload) << 16;
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
190 fn interval_converts_frames_and_exponents_to_125us_units() {
191 // QEMU usb-kbd: full speed, bInterval 7 ms -> 56 microframes -> 2^5.
192 assert_eq!(interrupt_interval(speed::FULL, 7), 5);
193 assert_eq!(interrupt_interval(speed::FULL, 10), 6);
194 assert_eq!(interrupt_interval(speed::LOW, 1), 3);
195 assert_eq!(interrupt_interval(speed::FULL, 255), 10);
196 assert_eq!(interrupt_interval(speed::FULL, 0), 3);
197 assert_eq!(interrupt_interval(speed::HIGH, 4), 3);
198 assert_eq!(interrupt_interval(speed::SUPER, 0), 0);
199 assert_eq!(interrupt_interval(speed::HIGH, 200), 15);
200 }
201
202 #[test]
203 fn endpoint_addresses_map_to_device_context_indexes() {
204 assert_eq!(endpoint_dci(0x81), Some(3));
205 assert_eq!(endpoint_dci(0x82), Some(5));
206 assert_eq!(endpoint_dci(0x01), Some(2));
207 assert_eq!(endpoint_dci(0x8f), Some(31));
208 assert_eq!(endpoint_dci(0x80), None);
209 assert_eq!(default_control_max_packet(speed::LOW), 8);
210 assert_eq!(default_control_max_packet(speed::HIGH), 64);
211 assert_eq!(default_control_max_packet(speed::SUPER), 512);
212 }
213
214 #[test]
215 fn address_device_context_puts_port_and_endpoint_zero_in_place() {
216 let mut words = [0xdead_beef_u32; 8 * 33];
217 let mut input = InputContext::new(&mut words, 32).unwrap();
218 input.add(0b11);
219 input.slot(speed::FULL, 5, 1);
220 input.endpoint(
221 CONTROL_DCI,
222 &EndpointConfig {
223 ep_type: EP_TYPE_CONTROL,
224 max_burst: 0,
225 max_packet: 8,
226 interval: 0,
227 dequeue: 0x4000_1000 | 1,
228 average_trb_length: 8,
229 max_esit_payload: 0,
230 },
231 );
232 assert_eq!(words[1], 0b11, "add flags in the input control context");
233 assert_eq!(words[0], 0, "no drop flags");
234 // Slot context at 0x20: entries 1, full speed; root port in dword 1.
235 assert_eq!(words[8], 1 << 27 | 1 << 20);
236 assert_eq!(words[9], 5 << 16);
237 // Endpoint 0 context at 0x40: CErr 3, type control, max packet 8.
238 assert_eq!(words[17], 3 << 1 | 4 << 3 | 8 << 16);
239 assert_eq!([words[18], words[19]], [0x4000_1001, 0]);
240 assert_eq!(words[20], 8);
241 assert!(words[21..].iter().all(|w| *w == 0), "memory was zeroed");
242 }
243
244 #[test]
245 fn large_contexts_double_the_stride_and_bad_sizes_are_refused() {
246 let mut words = [0u32; 16 * 33];
247 let mut input = InputContext::new(&mut words, 64).unwrap();
248 input.slot(speed::HIGH, 2, 3);
249 input.endpoint(
250 3,
251 &EndpointConfig {
252 ep_type: EP_TYPE_INTERRUPT_IN,
253 max_burst: 0,
254 max_packet: 8,
255 interval: 6,
256 dequeue: 0x2_0000_0001,
257 average_trb_length: 8,
258 max_esit_payload: 8,
259 },
260 );
261 input.endpoint(
262 0,
263 &EndpointConfig {
264 ep_type: 0,
265 max_burst: 0,
266 max_packet: 0,
267 interval: 0,
268 dequeue: u64::MAX,
269 average_trb_length: 0,
270 max_esit_payload: 0,
271 },
272 );
273 assert_eq!(words[16], 3 << 27 | 3 << 20);
274 assert_eq!(words[17], 2 << 16);
275 let ep = 16 * 4; // DCI 3 is entry 4
276 assert_eq!(words[ep], 6 << 16);
277 assert_eq!(words[ep + 1], 3 << 1 | 7 << 3 | 8 << 16);
278 assert_eq!([words[ep + 2], words[ep + 3]], [1, 2]);
279 assert_eq!(words[ep + 4], 8 | 8 << 16);
280 assert_eq!(
281 words[18..32],
282 [0; 14],
283 "DCI 0 did not overwrite the slot context"
284 );
285 assert!(InputContext::new(&mut words, 48).is_none());
286 assert!(InputContext::new(&mut words[..100], 32).is_none());
287 }
288
289 #[test]
290 fn isochronous_out_endpoint_fields_encode_in_context() {
291 let mut words = [0u32; 8 * 33];
292 let mut input = InputContext::new(&mut words, 32).unwrap();
293 input.endpoint(
294 2,
295 &isoch_out_endpoint(speed::HIGH, 4, 192, 192, 0x1234_5001),
296 );
297 let ep = 8 * 3;
298 assert_eq!(words[ep], 3 << 16);
299 assert_eq!(
300 words[ep + 1],
301 CERR << 1 | (EP_TYPE_ISOCH_OUT as u32) << 3 | 192 << 16
302 );
303 assert_eq!([words[ep + 2], words[ep + 3]], [0x1234_5001, 0]);
304 assert_eq!(words[ep + 4], 192 | 192 << 16);
305 }
306 #[test]
307 fn isoch_interval_and_high_bandwidth_burst() {
308 // Review regressions: FS isochronous bInterval 2 = 2 ms = 2^4 x 125 us.
309 assert_eq!(isoch_interval(speed::FULL, 1), 3);
310 assert_eq!(isoch_interval(speed::FULL, 2), 4);
311 assert_eq!(isoch_interval(speed::HIGH, 4), 3);
312 // HS wMaxPacketSize 0x1400: 1024 bytes, 2 extra transactions.
313 let ep = isoch_out_endpoint(speed::HIGH, 1, 0x1400, 3072, 0x1000);
314 assert_eq!((ep.max_packet, ep.max_burst), (1024, 2));
315 // Full speed: bits 12:11 are reserved, never a burst.
316 let ep = isoch_out_endpoint(speed::FULL, 1, 0x1400, 1023, 0x1000);
317 assert_eq!((ep.max_packet, ep.max_burst), (1024 & 0x7ff, 0));
318 }
319}