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

690 lines · 26266 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//! Polled xHCI bring-up of one HID boot keyboard.
17//!
18//! Sequence: halt and reset the controller, program one command ring, one
19//! event ring (interrupter 0, interrupts left disabled) and the device
20//! context array, run it, then for each connected root port: reset the port,
21//! Enable Slot, Address Device, read the device and configuration
22//! descriptors, and if a boot keyboard is found SET_CONFIGURATION,
23//! SET_PROTOCOL(boot), SET_IDLE(0) and Configure Endpoint for its
24//! interrupt-IN endpoint. Reports are then read by polling the event ring.
25//!
26//! No interrupts, no exception-vector changes and no allocator (ADR 0009).
27//! Every wait is bounded by the architectural counter, so a missing or
28//! wedged controller costs a bounded delay and an error, never a hang.
29//! All DMA memory is one caller-owned [`DmaMemory`], used at its identity
30//! address and kept coherent with explicit cache maintenance.
31
32use super::context::{
33 default_control_max_packet, endpoint_dci, interrupt_interval, EndpointConfig, InputContext,
34 CONTROL_DCI, EP_TYPE_CONTROL, EP_TYPE_INTERRUPT_IN,
35};
36use super::ring::{EventRing, ProducerRing};
37use super::trb::{completion, kind, request, SetupPacket, Trb};
38use super::{op, portsc, rt, Capabilities};
39use crate::arch::aarch64::{
40 clean_dcache_range, clean_invalidate_dcache_range, counter_frequency_hz, counter_ticks, MmioReg,
41};
42use crate::usb::descriptor::{control_max_packet, find_boot_keyboard, BootKeyboard};
43use crate::usb::hid::BOOT_REPORT_LEN;
44use core::fmt;
45use core::ptr::{addr_of_mut, read_volatile, write_bytes, write_volatile};
46
47const PAGE_BYTES: usize = 4096;
48const RING_TRBS: usize = PAGE_BYTES / 16;
49const REPORT_OFFSET: usize = 0;
50const DESCRIPTOR_OFFSET: usize = 512;
51const DESCRIPTOR_MAX: u16 = 255;
52
53/// One 4 KiB page of DMA memory. Page alignment keeps every structure
54/// inside one 64 KiB boundary, as the specification requires.
55#[repr(C, align(4096))]
56pub struct DmaPage([u32; PAGE_BYTES / 4]);
57
58/// Every structure the controller reads or writes, one page each.
59#[repr(C)]
60pub struct DmaMemory {
61 dcbaa: DmaPage,
62 device_context: DmaPage,
63 input_context: DmaPage,
64 command_ring: DmaPage,
65 event_ring: DmaPage,
66 segment_table: DmaPage,
67 control_ring: DmaPage,
68 report_ring: DmaPage,
69 buffer: DmaPage,
70}
71
72impl DmaMemory {
73 pub const fn new() -> Self {
74 const ZERO: DmaPage = DmaPage([0; PAGE_BYTES / 4]);
75 Self {
76 dcbaa: ZERO,
77 device_context: ZERO,
78 input_context: ZERO,
79 command_ring: ZERO,
80 event_ring: ZERO,
81 segment_table: ZERO,
82 control_ring: ZERO,
83 report_ring: ZERO,
84 buffer: ZERO,
85 }
86 }
87}
88
89impl Default for DmaMemory {
90 fn default() -> Self {
91 Self::new()
92 }
93}
94
95/// Why no keyboard is available. Every variant is reached by a bounded path.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum Error {
98 Absent,
99 Unsupported(&'static str),
100 Timeout(&'static str),
101 HostSystemError,
102 CommandTimeout {
103 step: &'static str,
104 command_addr: u64,
105 command_words: [u32; 4],
106 dcbaap: u64,
107 erstba: u64,
108 erstsz: u32,
109 crcr: u64,
110 erdp: u64,
111 usbcmd: u32,
112 usbsts: u32,
113 config: u32,
114 last_event: [u32; 4],
115 },
116 Failed {
117 step: &'static str,
118 code: u8,
119 },
120 NoKeyboard,
121}
122
123impl fmt::Display for Error {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 match self {
126 Self::Absent => f.write_str("xHCI registers absent"),
127 Self::Unsupported(what) => write!(f, "unsupported: {what}"),
128 Self::Timeout(step) => write!(f, "timed out: {step}"),
129 Self::CommandTimeout { step, command_addr, command_words, crcr, erdp, usbcmd, usbsts, config, last_event, .. } => write!(
130 f,
131 "timed out: {step}; cmd@{command_addr:#x}={command_words:08x?}; CRCR={crcr:#x} ERDP={erdp:#x} USBCMD={usbcmd:#x} USBSTS={usbsts:#x} CONFIG={config:#x} last_event={last_event:08x?}"
132 ),
133 Self::HostSystemError => f.write_str("host system error"),
134 Self::Failed { step, code } => write!(f, "{step} failed (completion {code})"),
135 Self::NoKeyboard => f.write_str("no boot keyboard on any connected port"),
136 }
137 }
138}
139
140/// Bounded wait: a time limit on the architectural counter, or a poll count
141/// when the counter frequency is unknown.
142struct Deadline {
143 start: u64,
144 ticks: u64,
145 polls: u32,
146}
147
148impl Deadline {
149 fn after_ms(ms: u64) -> Self {
150 Self {
151 start: counter_ticks(),
152 ticks: counter_frequency_hz().saturating_mul(ms) / 1000,
153 polls: 0,
154 }
155 }
156
157 fn expired(&mut self) -> bool {
158 self.polls = self.polls.saturating_add(1);
159 if self.ticks == 0 {
160 return self.polls > 1_000_000;
161 }
162 counter_ticks().wrapping_sub(self.start) > self.ticks
163 }
164}
165
166fn write64(addr: usize, value: u64) {
167 // SAFETY: callers pass a 64-bit register inside the controller register
168 // block that `Keyboard::start`'s contract requires to be mapped.
169 unsafe { MmioReg::<u32>::new(addr) }.write(value as u32);
170 // SAFETY: the high half of the same 64-bit register.
171 unsafe { MmioReg::<u32>::new(addr + 4) }.write((value >> 32) as u32);
172}
173
174/// A running controller with one attached boot keyboard.
175pub struct Keyboard {
176 op: usize,
177 rt: usize,
178 db: usize,
179 mem: *mut DmaMemory,
180 context_bytes: usize,
181 commands: ProducerRing,
182 events: EventRing,
183 control: ProducerRing,
184 reports: ProducerRing,
185 slot: u8,
186 last_event: [u32; 4],
187 dci: u8,
188 port: u8,
189 device: Option<BootKeyboard>,
190 retire_pending: bool,
191 halted: bool,
192}
193
194impl Keyboard {
195 /// Reset the controller at `mmio_base` and attach the first boot
196 /// keyboard found on a root port.
197 ///
198 /// # Safety
199 /// `mmio_base` must be the mapped register block of an xHCI controller
200 /// with memory decode and bus mastering enabled that nothing else drives,
201 /// and `mem` must be identity-mapped memory that stays valid and unused
202 /// by anything else for as long as the returned driver or the controller
203 /// may run.
204 pub unsafe fn start(mmio_base: u64, mem: *mut DmaMemory) -> Result<Self, Error> {
205 let base = mmio_base as usize;
206 // SAFETY: the capability registers sit at the start of the register
207 // block that this function's contract requires to be mapped.
208 let cap = |offset: usize| unsafe { MmioReg::<u32>::new(base + offset) }.read();
209 let caps = Capabilities::decode(cap(0), cap(4), cap(8), cap(0x10), cap(0x14), cap(0x18))
210 .ok_or(Error::Absent)?;
211 if caps.scratchpad_pages != 0 {
212 return Err(Error::Unsupported("controller asks for scratchpad pages"));
213 }
214 let end = mem as u64 + core::mem::size_of::<DmaMemory>() as u64;
215 if !caps.addresses_64 && end > u64::from(u32::MAX) {
216 return Err(Error::Unsupported(
217 "DMA memory above 4 GiB on a 32-bit controller",
218 ));
219 }
220 let op = base + caps.operational_offset;
221 reset(op)?;
222
223 // SAFETY: the caller hands `mem` over exclusively.
224 unsafe { write_bytes(mem, 0, 1) };
225 let page = |p: *mut DmaPage| (p as *mut Trb, p as u64);
226 // SAFETY: each ring gets its own page inside `mem`.
227 let (commands, events, control, reports) = unsafe {
228 let (c, c_dma) = page(addr_of_mut!((*mem).command_ring));
229 let (e, e_dma) = page(addr_of_mut!((*mem).event_ring));
230 let (t, t_dma) = page(addr_of_mut!((*mem).control_ring));
231 let (r, r_dma) = page(addr_of_mut!((*mem).report_ring));
232 (
233 ProducerRing::new(c, RING_TRBS, c_dma),
234 EventRing::new(e, RING_TRBS, e_dma),
235 ProducerRing::new(t, RING_TRBS, t_dma),
236 ProducerRing::new(r, RING_TRBS, r_dma),
237 )
238 };
239 let (Some(commands), Some(events), Some(control), Some(reports)) =
240 (commands, events, control, reports)
241 else {
242 return Err(Error::Unsupported("ring memory"));
243 };
244 let mut keyboard = Self {
245 op,
246 rt: base + caps.runtime_offset,
247 db: base + caps.doorbell_offset,
248 mem,
249 context_bytes: caps.context_bytes,
250 commands,
251 events,
252 control,
253 reports,
254 slot: 0,
255 dci: 0,
256 port: 0,
257 device: None,
258 retire_pending: false,
259 halted: false,
260 last_event: [0; 4],
261 };
262 keyboard.run()?;
263
264 let mut outcome = Err(Error::NoKeyboard);
265 for port in 1..=caps.max_ports {
266 let status = keyboard.op_reg(op::portsc(port)).read();
267 if status & portsc::CONNECTED == 0 {
268 continue;
269 }
270 outcome = keyboard.attach(port);
271 if outcome.is_ok() {
272 break;
273 }
274 if keyboard.slot != 0 {
275 let slot = keyboard.slot;
276 let _ = keyboard.command(Trb::disable_slot(slot), "Disable Slot");
277 keyboard.slot = 0;
278 }
279 }
280 outcome.map(|()| keyboard)
281 }
282
283 /// Root hub port, slot and interrupt-IN endpoint address of the keyboard.
284 pub fn location(&self) -> (u8, u8, u8) {
285 let endpoint = self.device.map_or(0, |d| d.endpoint_address);
286 (self.port, self.slot, endpoint)
287 }
288
289 /// True once the report endpoint failed; no further reports arrive.
290 pub fn is_halted(&self) -> bool {
291 self.halted
292 }
293
294 fn op_reg(&self, offset: usize) -> MmioReg<u32> {
295 // SAFETY: `op` is the operational register base inside the register
296 // block `start` was given, and callers pass `op::` offsets.
297 unsafe { MmioReg::new(self.op + offset) }
298 }
299
300 fn run(&mut self) -> Result<(), Error> {
301 let mem = self.mem;
302 // SAFETY: pages of the exclusively owned DMA memory.
303 let (dcbaa, segment_table) = unsafe {
304 (
305 addr_of_mut!((*mem).dcbaa),
306 addr_of_mut!((*mem).segment_table),
307 )
308 };
309 let entry = self.events.segment_table_entry();
310 // SAFETY: the segment table page is ours; 4 dwords fit.
311 unsafe { write_volatile(segment_table as *mut [u32; 4], entry) };
312 self.sync_to_device();
313
314 let config = self.op_reg(op::CONFIG);
315 // One device slot is enough for one keyboard.
316 config.write(config.read() & !0xff | 1);
317 write64(self.op + op::DCBAAP, dcbaa as u64);
318 write64(self.op + op::CRCR, self.commands.dequeue_pointer());
319 // SAFETY: ERSTSZ is a runtime register inside the block `start` was given.
320 unsafe { MmioReg::<u32>::new(self.rt + rt::ERSTSZ) }.write(1);
321 write64(self.rt + rt::ERDP, self.events.dequeue_pointer());
322 write64(self.rt + rt::ERSTBA, segment_table as u64);
323
324 let usbcmd = self.op_reg(op::USBCMD);
325 usbcmd.write(usbcmd.read() | op::USBCMD_RUN);
326 wait(Deadline::after_ms(100), || {
327 self.op_reg(op::USBSTS).read() & op::USBSTS_HALTED == 0
328 })
329 .map_err(|()| Error::Timeout("controller run"))
330 }
331
332 fn reset_port(&mut self, port: u8) -> Result<u8, Error> {
333 let reg = self.op_reg(op::portsc(port));
334 let status = reg.read();
335 if status & portsc::ENABLED == 0 {
336 // USB 2 ports need a reset to enable; USB 3 ports train on their own.
337 reg.write(portsc::neutral(status) | portsc::RESET);
338 wait(Deadline::after_ms(500), || {
339 reg.read() & portsc::RESET_CHANGE != 0
340 })
341 .map_err(|()| Error::Timeout("port reset"))?;
342 }
343 let status = reg.read();
344 reg.write(portsc::neutral(status) | status & portsc::CHANGES);
345 if status & portsc::ENABLED == 0 {
346 return Err(Error::Unsupported("port did not enable"));
347 }
348 Ok(portsc::speed(status))
349 }
350
351 fn attach(&mut self, port: u8) -> Result<(), Error> {
352 let speed = self.reset_port(port)?;
353 self.port = port;
354 let event = self.command(Trb::enable_slot(), "Enable Slot")?;
355 self.slot = event.slot_id();
356 if self.slot == 0 {
357 return Err(Error::Unsupported("slot id"));
358 }
359 let mem = self.mem;
360 // SAFETY: pages of the exclusively owned DMA memory; a slot ID (at
361 // most 255) indexes inside the 512-entry DCBAA page.
362 unsafe {
363 let device_context = addr_of_mut!((*mem).device_context);
364 write_bytes(device_context, 0, 1);
365 let dcbaa = addr_of_mut!((*mem).dcbaa) as *mut u64;
366 write_volatile(dcbaa.add(usize::from(self.slot)), device_context as u64);
367 let ring = addr_of_mut!((*mem).control_ring);
368 self.control = ProducerRing::new(ring as *mut Trb, RING_TRBS, ring as u64)
369 .ok_or(Error::Unsupported("ring memory"))?;
370 }
371
372 let mut max_packet = default_control_max_packet(speed);
373 self.control_context(speed, max_packet, 0b11, 1);
374 self.slot_command(Trb::address_device, "Address Device")?;
375
376 let device = self.control_in(
377 SetupPacket::get_descriptor(request::DESCRIPTOR_DEVICE, 0, 8),
378 "GET_DESCRIPTOR(device)",
379 )?;
380 let reported = control_max_packet(&device[..8]).map_or(max_packet, |size| {
381 if speed >= super::context::speed::SUPER {
382 1 << size.min(9)
383 } else {
384 u16::from(size)
385 }
386 });
387 if reported != max_packet {
388 max_packet = reported;
389 self.control_context(speed, max_packet, 0b10, 1);
390 self.slot_command(Trb::evaluate_context, "Evaluate Context")?;
391 }
392
393 let config = self.control_in(
394 SetupPacket::get_descriptor(request::DESCRIPTOR_CONFIGURATION, 0, DESCRIPTOR_MAX),
395 "GET_DESCRIPTOR(configuration)",
396 )?;
397 let keyboard = find_boot_keyboard(&config).ok_or(Error::NoKeyboard)?;
398 let dci = endpoint_dci(keyboard.endpoint_address).ok_or(Error::NoKeyboard)?;
399 self.control_transfer(
400 SetupPacket::set_configuration(keyboard.configuration),
401 "SET_CONFIGURATION",
402 )?;
403 self.control_transfer(
404 SetupPacket::set_boot_protocol(keyboard.interface),
405 "SET_PROTOCOL",
406 )?;
407 // Keyboards may stall SET_IDLE; unchanged reports are then ignored
408 // by the decoder anyway.
409 let _ = self.control_transfer(
410 SetupPacket::set_idle_forever(keyboard.interface),
411 "SET_IDLE",
412 );
413
414 let (dequeue, bytes) = (self.reports.dequeue_pointer(), self.context_bytes);
415 let mut input = InputContext::new(self.input_context(), bytes)
416 .ok_or(Error::Unsupported("context size"))?;
417 input.add(1 | 1 << dci);
418 input.slot(speed, port, dci);
419 input.endpoint(
420 dci,
421 &EndpointConfig {
422 ep_type: EP_TYPE_INTERRUPT_IN,
423 max_burst: 0,
424 max_packet: keyboard.max_packet,
425 interval: interrupt_interval(speed, keyboard.interval),
426 dequeue,
427 average_trb_length: BOOT_REPORT_LEN as u16,
428 max_esit_payload: keyboard.max_packet,
429 },
430 );
431 self.slot_command(Trb::configure_endpoint, "Configure Endpoint")?;
432 self.dci = dci;
433 self.device = Some(keyboard);
434 self.arm();
435 Ok(())
436 }
437
438 fn input_context(&mut self) -> &mut [u32] {
439 // SAFETY: the input context page is only touched here, between
440 // commands, while the controller is not reading it.
441 unsafe { &mut (*addr_of_mut!((*self.mem).input_context)).0 }
442 }
443
444 fn control_context(&mut self, speed: u8, max_packet: u16, add: u32, entries: u8) {
445 let dequeue = self.control.dequeue_pointer();
446 let (port, bytes) = (self.port, self.context_bytes);
447 if let Some(mut input) = InputContext::new(self.input_context(), bytes) {
448 input.add(add);
449 input.slot(speed, port, entries);
450 input.endpoint(
451 CONTROL_DCI,
452 &EndpointConfig {
453 ep_type: EP_TYPE_CONTROL,
454 max_burst: 0,
455 max_packet,
456 interval: 0,
457 dequeue,
458 average_trb_length: 8,
459 max_esit_payload: 0,
460 },
461 );
462 }
463 }
464
465 fn slot_command(&mut self, build: fn(u64, u8) -> Trb, step: &'static str) -> Result<(), Error> {
466 // SAFETY: address of a page of the owned DMA memory.
467 let input = unsafe { addr_of_mut!((*self.mem).input_context) } as u64;
468 self.command(build(input, self.slot), step).map(|_| ())
469 }
470
471 fn doorbell(&self, target: u8, value: u8) {
472 // SAFETY: `db` is the doorbell array inside the register block `start`
473 // was given; `target` is the command ring (0) or this keyboard's slot.
474 unsafe { MmioReg::<u32>::new(self.db + usize::from(target) * 4) }.write(u32::from(value));
475 }
476
477 fn command(&mut self, trb: Trb, step: &'static str) -> Result<Trb, Error> {
478 let addr = self.commands.push(trb);
479 let command_words = unsafe { read_volatile(addr as *const Trb) }.0;
480 self.sync_to_device();
481 self.doorbell(0, 0);
482 let event = self
483 .wait_event(step, |e| {
484 e.kind() == kind::COMMAND_COMPLETION && e.pointer() == addr
485 })
486 .map_err(|error| match error {
487 Error::Timeout(_) => Error::CommandTimeout {
488 step,
489 command_addr: addr,
490 command_words,
491 dcbaap: unsafe { read_volatile((self.op + op::DCBAAP) as *const u64) },
492 erstba: unsafe { read_volatile((self.rt + rt::ERSTBA) as *const u64) },
493 // SAFETY: ERSTSZ is a runtime register inside the block `start` was given.
494 erstsz: unsafe { MmioReg::<u32>::new(self.rt + rt::ERSTSZ) }.read(),
495 crcr: unsafe { read_volatile((self.op + op::CRCR) as *const u64) },
496 erdp: unsafe { read_volatile((self.rt + rt::ERDP) as *const u64) },
497 usbcmd: self.op_reg(op::USBCMD).read(),
498 usbsts: self.op_reg(op::USBSTS).read(),
499 config: self.op_reg(op::CONFIG).read(),
500 last_event: self.last_event,
501 },
502 other => other,
503 })?;
504 match event.completion_code() {
505 completion::SUCCESS => Ok(event),
506 code => Err(Error::Failed { step, code }),
507 }
508 }
509
510 fn control_in(
511 &mut self,
512 setup: SetupPacket,
513 step: &'static str,
514 ) -> Result<[u8; DESCRIPTOR_MAX as usize], Error> {
515 let buffer = self.buffer_ptr(DESCRIPTOR_OFFSET);
516 // SAFETY: the descriptor area lies inside the owned buffer page.
517 unsafe { write_bytes(buffer, 0, usize::from(DESCRIPTOR_MAX)) };
518 self.control_transfer(setup, step)?;
519 let mut bytes = [0u8; DESCRIPTOR_MAX as usize];
520 for (i, b) in bytes.iter_mut().enumerate() {
521 // SAFETY: as above; the controller finished writing.
522 *b = unsafe { read_volatile(buffer.add(i)) };
523 }
524 Ok(bytes)
525 }
526
527 fn control_transfer(&mut self, setup: SetupPacket, step: &'static str) -> Result<(), Error> {
528 let buffer = self.buffer_ptr(DESCRIPTOR_OFFSET) as u64;
529 self.control.push(Trb::setup_stage(&setup));
530 if setup.length > 0 {
531 self.control.push(Trb::data_stage(&setup, buffer));
532 }
533 let status = self.control.push(Trb::status_stage(&setup));
534 self.sync_to_device();
535 self.doorbell(self.slot, CONTROL_DCI);
536 let slot = self.slot;
537 let event = self.wait_event(step, |e| {
538 e.kind() == kind::TRANSFER_EVENT
539 && e.slot_id() == slot
540 && e.endpoint_id() == CONTROL_DCI
541 && (e.pointer() == status || !e.completed_ok())
542 })?;
543 if !event.completed_ok() {
544 return Err(Error::Failed {
545 step,
546 code: event.completion_code(),
547 });
548 }
549 Ok(())
550 }
551
552 fn buffer_ptr(&self, offset: usize) -> *mut u8 {
553 // SAFETY: address arithmetic inside the owned buffer page.
554 unsafe { (addr_of_mut!((*self.mem).buffer) as *mut u8).add(offset) }
555 }
556
557 /// Queue one report transfer on the interrupt-IN endpoint.
558 fn arm(&mut self) {
559 let buffer = self.buffer_ptr(REPORT_OFFSET) as u64;
560 self.reports
561 .push(Trb::normal(buffer, BOOT_REPORT_LEN as u32));
562 self.sync_to_device();
563 self.doorbell(self.slot, self.dci);
564 }
565
566 /// Consume pending events; return a completed keyboard report, if any.
567 /// Other events (port changes, stray completions) are retired and dropped.
568 pub fn poll(&mut self) -> Option<[u8; BOOT_REPORT_LEN]> {
569 if self.halted {
570 return None;
571 }
572 self.sync_from_device();
573 let mut report = None;
574 while let Some(event) = self.events.pop() {
575 self.retire_pending = true;
576 let ours = event.kind() == kind::TRANSFER_EVENT
577 && event.slot_id() == self.slot
578 && event.endpoint_id() == self.dci;
579 if !ours {
580 continue;
581 }
582 if !event.completed_ok() {
583 // The endpoint halted; recovering it is not attempted.
584 self.halted = true;
585 break;
586 }
587 if event.residual() == 0 {
588 let buffer = self.buffer_ptr(REPORT_OFFSET);
589 let mut bytes = [0u8; BOOT_REPORT_LEN];
590 for (i, b) in bytes.iter_mut().enumerate() {
591 // SAFETY: the report area lies inside the owned buffer page.
592 *b = unsafe { read_volatile(buffer.add(i)) };
593 }
594 report = Some(bytes);
595 }
596 self.arm();
597 break;
598 }
599 self.retire();
600 report
601 }
602
603 fn wait_event(
604 &mut self,
605 step: &'static str,
606 wanted: impl Fn(&Trb) -> bool,
607 ) -> Result<Trb, Error> {
608 let mut deadline = Deadline::after_ms(1000);
609 loop {
610 self.sync_from_device();
611 while let Some(event) = self.events.pop() {
612 self.retire_pending = true;
613 self.last_event = event.0;
614 if wanted(&event) {
615 self.retire();
616 return Ok(event);
617 }
618 }
619 self.retire();
620 if self.op_reg(op::USBSTS).read() & op::USBSTS_HOST_ERROR != 0 {
621 return Err(Error::HostSystemError);
622 }
623 if deadline.expired() {
624 return Err(Error::Timeout(step));
625 }
626 core::hint::spin_loop();
627 }
628 }
629
630 /// Tell the controller how far the event ring was consumed.
631 fn retire(&mut self) {
632 if self.retire_pending {
633 write64(
634 self.rt + rt::ERDP,
635 self.events.dequeue_pointer() | rt::ERDP_BUSY,
636 );
637 self.retire_pending = false;
638 }
639 }
640
641 /// Make CPU writes to the DMA memory visible to the controller.
642 fn sync_to_device(&self) {
643 clean_dcache_range(self.mem as usize, core::mem::size_of::<DmaMemory>());
644 }
645
646 /// Drop stale cached copies of what the controller writes.
647 fn sync_from_device(&self) {
648 // SAFETY: addresses of pages of the owned DMA memory.
649 let (events, buffer) = unsafe {
650 (
651 addr_of_mut!((*self.mem).event_ring),
652 addr_of_mut!((*self.mem).buffer),
653 )
654 };
655 clean_invalidate_dcache_range(events as usize, PAGE_BYTES);
656 clean_invalidate_dcache_range(buffer as usize, PAGE_BYTES);
657 }
658}
659
660fn wait(mut deadline: Deadline, mut done: impl FnMut() -> bool) -> Result<(), ()> {
661 while !done() {
662 if deadline.expired() {
663 return Err(());
664 }
665 core::hint::spin_loop();
666 }
667 Ok(())
668}
669
670/// Stop the controller, reset it and wait until it is ready for setup.
671fn reset(op: usize) -> Result<(), Error> {
672 // SAFETY: `start` passes the operational register base of the register
673 // block its contract requires to be mapped; USBCMD and USBSTS are inside it.
674 let usbcmd = unsafe { MmioReg::<u32>::new(op + op::USBCMD) };
675 // SAFETY: as above.
676 let usbsts = unsafe { MmioReg::<u32>::new(op + op::USBSTS) };
677 if usbsts.read() == u32::MAX {
678 return Err(Error::Absent);
679 }
680 usbcmd.write(usbcmd.read() & !op::USBCMD_RUN);
681 wait(Deadline::after_ms(100), || {
682 usbsts.read() & op::USBSTS_HALTED != 0
683 })
684 .map_err(|()| Error::Timeout("controller halt"))?;
685 usbcmd.write(op::USBCMD_RESET);
686 wait(Deadline::after_ms(1000), || {
687 usbcmd.read() & op::USBCMD_RESET == 0 && usbsts.read() & op::USBSTS_NOT_READY == 0
688 })
689 .map_err(|()| Error::Timeout("controller reset"))
690}