Skip to main content

rpi_hal/usb/
dwc2.rs

1//! Host-mode bring-up for the BCM2836/2837's DWC2 USB OTG controller
2//! — core reset, forcing host mode, powering and resetting the root
3//! port, plus the low-level DMA-mode channel primitives (including
4//! split transactions through a hub's transaction translator)
5//! [`crate::usb::control`] builds actual control transfers on top of.
6//! Nothing here understands USB protocol state (SETUP/DATA/STATUS
7//! staging, retries) — see this module's parent for the split.
8//!
9//! ## The controller must be powered on first
10//!
11//! On this board the firmware hands the DWC2 core off only *partially*
12//! powered: every global, host and per-channel register reads and
13//! writes normally, the core enters host mode, the root port detects a
14//! connection and enables, and the frame timer (`HFNUM`) runs — yet no
15//! channel transaction ever executes. A channel arms perfectly (`CHENA`
16//! set, `HCTSIZ`/`HCDMA`/`HCCHAR` all reading back exactly as
17//! programmed) and then sits there forever: `CHENA` never clears, the
18//! request queue never moves, and `HCINT` stays all-zero, no completion
19//! and no error. Nothing programmed *through the DWC2 register block*
20//! changes this, because the register block is not what's unpowered.
21//! The fix lives outside this driver entirely — the caller must first
22//! power the USB HCD on through the VideoCore mailbox
23//! ([`crate::mailbox::Mailbox::set_power_state`] with
24//! [`crate::mailbox::PowerDeviceId::UsbHcd`]) before calling
25//! [`Dwc2Host::init`]; once fully
26//! powered, the very same register sequence completes transfers
27//! immediately.
28//!
29//! ## DMA, not slave mode
30//!
31//! An earlier version of this driver used slave (PIO/FIFO-push) mode
32//! — program a channel, push bytes into its FIFO by hand, pop received
33//! bytes back out. On real hardware that produced a channel that
34//! looked fully armed (`HCCHAR`/`HCTSIZ` read back exactly as
35//! programmed, FIFO/request-queue space was visibly consumed) but
36//! never generated a single `HCINT` bit, not even an error — total
37//! silence. `GHWCFG2.ARCHITECTURE` (this PAC calls it
38//! `hw_config0().architecture()`) confirmed why: this SoC's DWC2
39//! instantiation reports `internal_dma`, not `slave_only` — slave mode
40//! isn't just unused here, it isn't implemented in this silicon at
41//! all. Every transfer here goes through `HCDMA` instead.
42//!
43//! DMA means the buffer a channel reads from/writes to is touched by
44//! the core directly over the bus, not through the ARM core's cache —
45//! the same cache-coherency concern `mailbox.rs` already had to
46//! handle, for the same reason (this crate's MMU maps RAM Cacheable).
47//! `clean_range` runs before an OUT/SETUP transfer, `invalidate_range`
48//! after an IN transfer, and the buffer's address is translated to the
49//! VideoCore bus alias the same way (see `to_vc_bus_address`) before
50//! it's ever written to `HCDMA`.
51
52/// Interrupt-driven `async` twins of [`Channel`]'s transfer primitives —
53/// see the module's own documentation for the interrupt wiring an
54/// application must provide.
55///
56/// Available only with the `async` feature enabled.
57#[cfg(feature = "async")]
58#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
59pub mod asynch;
60
61#[cfg(feature = "async")]
62pub use asynch::on_irq;
63
64use core::cell::Cell;
65
66use crate::cache::{clean_range, invalidate_range, MIN_CACHE_LINE};
67use crate::pac::{USB_OTG_GLOBAL, USB_OTG_HOST, USB_OTG_PWRCLK};
68use crate::timer::Timer;
69
70/// Translates a plain ARM physical address to the VideoCore's
71/// `0xC000_0000`-based "direct, uncached" bus alias — see
72/// `mailbox.rs`'s identical helper and doc comment. Every DMA-capable
73/// peripheral on this SoC (the mailbox, the standalone DMA
74/// controller, and this USB core alike) shares the same bus address
75/// space, so the same translation applies here, not just there.
76fn to_vc_bus_address(physical_address: u32) -> u32 {
77    (physical_address & 0x3FFF_FFFF) | 0xC000_0000
78}
79
80/// Which data-toggle PID a packet on a host channel carries. The
81/// numeric values are `HCTSIZ.DPID`'s encoding.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum DataPid {
84    /// `2'b00` — DATA0. The first packet on a freshly configured
85    /// interrupt/bulk endpoint, and every other packet as the toggle
86    /// alternates.
87    Data0,
88    /// `2'b10` — DATA1. Every DATA/STATUS packet in a control transfer
89    /// after the initial SETUP (control transfers always start their
90    /// data stage at DATA1), and the alternate interrupt/bulk toggle.
91    Data1,
92    /// `2'b11` — every SETUP packet.
93    Setup,
94}
95
96impl DataPid {
97    fn bits(self) -> u8 {
98        match self {
99            DataPid::Data0 => 0b00,
100            DataPid::Data1 => 0b10,
101            DataPid::Setup => 0b11,
102        }
103    }
104
105    /// The next data toggle after this one — `DATA0`↔`DATA1`. `Setup`
106    /// has no toggle (a SETUP stage is always a single packet) and maps
107    /// to itself.
108    fn toggled(self) -> DataPid {
109        match self {
110            DataPid::Data0 => DataPid::Data1,
111            DataPid::Data1 => DataPid::Data0,
112            DataPid::Setup => DataPid::Setup,
113        }
114    }
115}
116
117/// Host-channel transfer type — `HCCHAR.EPTYP`'s encoding. Only the
118/// types this driver issues so far.
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120enum EndpointType {
121    /// Control endpoint (endpoint 0).
122    Control,
123    /// Interrupt endpoint (e.g. a hub's status-change endpoint or a HID
124    /// report endpoint). Periodic on this core — for an *interrupt*
125    /// endpoint a bulk channel type was tried instead and the
126    /// transaction wouldn't run at all (see [`Channel::interrupt_in`]);
127    /// a genuine bulk endpoint still uses [`Self::Bulk`] below.
128    Interrupt,
129    /// Bulk endpoint (e.g. the LAN9514 Ethernet controller's frame RX/TX
130    /// endpoints). Non-periodic — scheduled on the non-periodic request
131    /// queue like control, not the periodic one interrupt uses.
132    Bulk,
133}
134
135impl EndpointType {
136    fn bits(self) -> u8 {
137        match self {
138            EndpointType::Control => 0b00,
139            EndpointType::Bulk => 0b10,
140            EndpointType::Interrupt => 0b11,
141        }
142    }
143}
144
145/// Why a single-packet channel transfer didn't complete successfully.
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147pub enum TransferError {
148    /// The device returned STALL — it doesn't support/recognize the
149    /// request.
150    Stall,
151    /// `HCINT.TXERR` — a transaction error (no response, bad CRC,
152    /// etc.).
153    TransactionError,
154    /// `HCINT.BBERR` — babble (the device sent more than expected).
155    Babble,
156    /// The device NAK'd this attempt — normal USB flow control (“not
157    /// ready yet, ask again”), not a real error. Left for the caller
158    /// to retry; see [`crate::usb::control`]'s retry wrapper.
159    Nak,
160    /// A caller-level retry budget was exhausted while the device
161    /// kept NAKing — distinct from a single [`Self::Nak`].
162    NakTimeout,
163    /// `HCINT.FRMOR` — frame overrun. A periodic (interrupt or
164    /// isochronous) transaction was still in progress when the
165    /// microframe it was scheduled in ran out, and the core abandoned
166    /// it.
167    ///
168    /// This is about *when* the transaction was started, not about the
169    /// device: a periodic transfer armed late in a microframe has too
170    /// little of it left to finish. Retrying on the next interval is
171    /// the normal response, which is why callers should treat this much
172    /// as they treat [`Self::Nak`] rather than as a hard failure.
173    FrameOverrun,
174    /// `HCINT.DTERR` — the packet arrived carrying the opposite data
175    /// toggle to the one expected, so it was discarded as a
176    /// retransmission of one already received. Means host and device
177    /// have lost toggle synchronisation.
178    DataToggleError,
179    /// The channel halted (`HCINT.CHH`) without `HCINT.XFRC` (transfer
180    /// complete) and without any specific error/status bit set — an
181    /// unexplained halt. Not expected in normal operation now that
182    /// completion is detected via `CHH`; a defensive branch rather than
183    /// a condition seen in practice.
184    Halted,
185    /// The channel never halted (`HCINT.CHH` never set) within this
186    /// driver's timeout — the transaction appears stuck rather than
187    /// having reached any terminal condition.
188    Timeout,
189}
190
191/// Locates the hub transaction translator a full/low-speed device sits
192/// behind, for split transactions. A full- or low-speed device plugged
193/// into a high-speed hub can't talk to a high-speed host directly: the
194/// host issues the transaction to the hub's transaction translator (a
195/// "start split"), which relays it to the device at the slower speed,
196/// then polls the translator for the result (a "complete split"). This
197/// says which translator — identified by the hub's device address and
198/// the downstream port the device is on.
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200pub struct SplitTarget {
201    /// Device address of the hub whose transaction translator relays to
202    /// the device.
203    pub hub_address: u8,
204    /// The hub's downstream port number (1-based) the device is on.
205    pub port: u8,
206}
207
208/// Which device (and at what speed/max packet size) a control
209/// transfer's low-level primitives should talk to — bundled together
210/// since every stage of a given transfer shares the same values;
211/// passing them as separate parameters through every method pushed
212/// `start_channel`'s argument count over clippy's limit for no real
213/// benefit.
214#[derive(Clone, Copy, Debug, PartialEq, Eq)]
215pub struct ControlEndpoint {
216    /// USB device address (0 before `SET_ADDRESS`).
217    pub address: u8,
218    /// Whether the device is low-speed — see [`Dwc2Host::port_speed`].
219    pub low_speed: bool,
220    /// Endpoint 0's max packet size for this transfer (`8` for the
221    /// first, address-0 probe every real host issues before it knows
222    /// the device's real value).
223    pub max_packet_size: u16,
224    /// `Some` if the device is a full/low-speed device behind a
225    /// high-speed hub and its transfers must go through that hub's
226    /// transaction translator as split transactions (see
227    /// [`SplitTarget`]); `None` for a device that reaches the host
228    /// directly (on the root port, or any high-speed device).
229    pub split: Option<SplitTarget>,
230}
231
232/// The shape of one channel transaction, bundled so
233/// [`Channel::start_channel`]/[`Channel::run_transaction`] don't
234/// exceed clippy's argument-count limit.
235#[derive(Clone, Copy)]
236struct Transaction {
237    /// Endpoint number (0 for control transfers).
238    endpoint_number: u8,
239    /// Endpoint transfer type.
240    endpoint_type: EndpointType,
241    /// Transfer direction: `true` = IN (device→host), `false` = OUT.
242    direction_in: bool,
243    /// Data toggle / PID for this transaction.
244    pid: DataPid,
245    /// Number of bytes to transfer.
246    transfer_size: u32,
247    /// Physical address of the DMA buffer (`start_channel` translates
248    /// it to the VideoCore bus alias).
249    dma_address: u32,
250}
251
252/// Largest control-transfer data payload this driver's shared DMA
253/// scratch buffer can hold, in bytes. 256 covers a full device
254/// descriptor (18 bytes), the configuration descriptors read during
255/// enumeration of the devices this stack targets, and a HID *report*
256/// descriptor — the one descriptor here that routinely runs past a
257/// hundred bytes (a game controller's is typically 100-200; see
258/// [`crate::usb::hid::gamepad`]), and which must be read in a single
259/// transfer because GET_DESCRIPTOR has no way to request an offset into
260/// one. A multiple of the 64-byte cache line, so [`DmaBuffer`] stays
261/// line-aligned at both ends.
262const DMA_BUFFER_LEN: usize = 256;
263
264/// Largest data payload a single transfer through a channel's DMA
265/// scratch buffer can carry, in bytes — every control-transfer stage
266/// ([`Channel::control_data_in`], [`Channel::control_data_out`]) and an
267/// interrupt-IN poll ([`Channel::interrupt_in`]). A caller sizing a
268/// buffer for one of those (a descriptor read, a report endpoint's
269/// packets) can check it against this instead of guessing. Bulk transfers
270/// DMA straight from/to the caller's buffer and aren't bounded by it.
271pub const MAX_TRANSFER_LEN: usize = DMA_BUFFER_LEN;
272
273/// Cache-line aligned (64 bytes — a Cortex-A7 L1 D-cache line, so
274/// [`invalidate_range`] after a DMA-IN can never discard a neighbouring
275/// dirty line) scratch buffer every control-transfer stage's DMA reads
276/// from / writes to. The DWC2 DMA engine walks it packet by packet for
277/// multi-packet transfers, so it must be large enough for the whole
278/// transfer at once — hence [`DMA_BUFFER_LEN`], which is also a whole
279/// number of cache lines.
280///
281/// One per [`Channel`], not one per controller: two channels running at
282/// once must not be staging their packets through the same memory.
283#[repr(C, align(64))]
284struct DmaBuffer([u8; DMA_BUFFER_LEN]);
285
286/// Upper bound on host channels, from the PAC rather than the silicon:
287/// `USB_OTG_HOST::host_channel(n)` indexes a fixed 12-entry array and
288/// refuses to compile past it. The core reports its real count in
289/// `GHWCFG2` (8 on this SoC), which is what [`Dwc2Host::alloc_channel`]
290/// actually hands out — this only keeps a nonsense read from indexing
291/// out of range.
292const MAX_CHANNELS: usize = 12;
293
294// Host channel interrupt (`HCINT`) bit masks — the terminal conditions
295// a transaction can halt with. Used directly as masks rather than
296// through the PAC's per-bit accessors so a single read can be tested
297// for several conditions (the split logic cares about `ACK`/`NYET`,
298// which the plain control path doesn't).
299/// `HCINT.XFRC` — transfer completed successfully.
300const HCINT_XFRC: u32 = 1 << 0;
301/// `HCINT.CHH` — channel halted (the DMA-mode "transaction done" flag).
302const HCINT_CHH: u32 = 1 << 1;
303/// `HCINT.STALL` — the device returned STALL.
304const HCINT_STALL: u32 = 1 << 3;
305/// `HCINT.NAK` — the device returned NAK.
306const HCINT_NAK: u32 = 1 << 4;
307/// `HCINT.ACK` — an ACK handshake was received/transmitted (a hub's
308/// transaction translator ACKs a start-split it has accepted).
309const HCINT_ACK: u32 = 1 << 5;
310/// `HCINT.NYET` — for a complete-split, the translator hasn't finished
311/// the relayed downstream transaction yet; poll again.
312const HCINT_NYET: u32 = 1 << 6;
313/// `HCINT.TXERR` — a transaction error (no response, bad CRC, etc.).
314const HCINT_TXERR: u32 = 1 << 7;
315/// `HCINT.BBERR` — babble (the device sent more than expected).
316const HCINT_BBERR: u32 = 1 << 8;
317/// `HCINT.FRMOR` — frame overrun: a periodic transaction was still
318/// running when its (micro)frame ended, so the core abandoned it. A
319/// scheduling failure, not a device fault — see
320/// [`TransferError::FrameOverrun`].
321const HCINT_FRMOR: u32 = 1 << 9;
322/// `HCINT.DTERR` — data toggle error: the packet arrived with the PID
323/// this endpoint's toggle didn't expect.
324const HCINT_DTERR: u32 = 1 << 10;
325
326/// How many times to poll a split transaction's complete-split phase
327/// while the hub's transaction translator answers `NYET`/`NAK` before
328/// giving up. The translator relays the transaction at full/low speed,
329/// which takes up to a frame, so completion can be a few microframes
330/// out; this bounds the wait rather than spinning forever.
331const MAX_CSPLIT_POLLS: u32 = 8;
332
333/// Delay between complete-split polls, in microseconds — five 125µs
334/// microframes, matching the reference driver's spacing. The
335/// transaction translator needs time to run the relayed full/low-speed
336/// transaction before it has a result, so polling faster than this
337/// just wastes bus cycles getting `NYET`.
338const CSPLIT_RETRY_DELAY_US: u32 = 5 * 125;
339
340/// Host-mode DWC2 controller: reset, powered up, and (after
341/// [`Self::reset_port`]) able to hand out [`Channel`]s — the host
342/// channels every transfer actually runs on.
343///
344/// What lives here is bus-level and shared: the root port, and the pool
345/// of host channels. What lives on [`Channel`] is everything to do with
346/// moving bytes — DMA-mode control transfers (up to
347/// [`MAX_TRANSFER_LEN`] bytes of data per transfer, the DWC2 handling
348/// the multi-packet split), interrupt-IN polls and bulk transfers, on
349/// directly-connected devices or full/low-speed devices behind a hub
350/// (via split transactions — see [`SplitTarget`]). The split is what
351/// lets two endpoints be driven at once: a [`Channel`] borrows this
352/// type immutably, so several can be outstanding, each with its own
353/// registers and its own DMA buffer. No enumeration state machine or
354/// hub traversal lives here either — those belong above the channel
355/// primitives.
356pub struct Dwc2Host {
357    global: USB_OTG_GLOBAL,
358    host: USB_OTG_HOST,
359    /// One bit per host channel, set while a [`Channel`] handle for it
360    /// is outstanding. Interior-mutable so [`Self::alloc_channel`] can
361    /// take `&self` and so hand out more than one channel at a time.
362    allocated: Cell<u16>,
363    /// How many host channels this core actually implements, read from
364    /// `GHWCFG2` in [`Self::init`] rather than assumed.
365    num_channels: u8,
366}
367
368impl Dwc2Host {
369    /// Resets the DWC2 core, ungates its clock, forces host mode,
370    /// sizes the FIFOs, and powers the root port — everything the
371    /// Synopsys databook documents as needed before a device's
372    /// connection can even be detected, let alone enumerated. The PHY
373    /// clock select and frame interval are programmed later, in
374    /// [`Self::reset_port`], once the enumerated port speed is known.
375    ///
376    /// The caller must have already powered the USB controller on
377    /// through the VideoCore mailbox (see this module's doc); without
378    /// that the register writes here all appear to succeed but no
379    /// transfer ever runs.
380    ///
381    /// Takes a `&Timer` because two of these steps have real,
382    /// documented settling times (not guesses) that must elapse
383    /// before the next register access is meaningful: this crate's
384    /// System Timer is already free-running from boot, so there's no
385    /// reason to approximate them with a raw cycle-count busy-wait the
386    /// way `pwm.rs` had to (no `Timer` reference was available there).
387    pub fn init(
388        global: USB_OTG_GLOBAL,
389        host: USB_OTG_HOST,
390        pwrclk: USB_OTG_PWRCLK,
391        timer: &Timer,
392    ) -> Self {
393        // Core soft reset. The databook requires the AHB master be
394        // idle (`AHBIDL`) before asserting it, then waiting for the
395        // (self-clearing) reset bit to actually clear before touching
396        // anything else.
397        while global.grstctl().read().ahbidl().bit_is_clear() {}
398        global.grstctl().modify(|_, w| w.csrst().set_bit());
399        while global.grstctl().read().csrst().bit_is_set() {}
400        // Databook-recommended settling time after core reset.
401        timer.delay_ms(3);
402
403        // Ungate the PHY/host clock: `PCGCCTL` (this SoC's "USB power"
404        // register) gates the clock the entire USB transfer engine runs
405        // on -- stop-Pclk, gate-HCLK, power-clamp, power-down. Its reset
406        // state leaves that clock gated, so every config and per-channel
407        // register (which live on a *different*, always-running bus
408        // clock) programs and reads back perfectly while the transfer
409        // engine itself is frozen: a channel arms flawlessly (`CHENA`
410        // set, `HCTSIZ`/`HCDMA`/`HCCHAR` all correct) but is never
411        // arbitrated onto the bus, `HFNUM`'s frame counter never
412        // advances, and `HCINT` stays all-zero forever. Writing the
413        // whole register to 0 clears every gating bit at once -- the
414        // first thing a known-working reference driver for this SoC
415        // (rsta2's `circle`/`uspi`) does in host init, before touching
416        // FIFOs or powering the port.
417        pwrclk.pcgcctl().write(|w| unsafe { w.bits(0) });
418
419        // Configure FIFO sizes. Confirmed on real hardware, not
420        // assumed: this SoC's reset default for `GNPTXFSIZ_HOST`
421        // (0x0200) decodes to a non-periodic TX FIFO *depth* of 0
422        // words (only `NPTXFSA`, the start address, is nonzero).
423        // These FIFOs are still real and still used internally even
424        // in DMA mode (the DMA engine fills/drains them automatically
425        // instead of software doing it by hand) -- a zero-depth FIFO
426        // is still wrong regardless of transfer mode.
427        //
428        // 1024 (0x400) words each, matching the reference driver for
429        // this SoC (rsta2's `circle`/`uspi`), which fits comfortably in
430        // this core's FIFO RAM (its total is far larger than the 3×0x400
431        // used here). An earlier, far smaller RxFIFO (0x80 = 128 words)
432        // worked for control and interrupt transfers but silently broke
433        // bulk-IN: the host only issues an IN token once its RxFIFO can
434        // hold a whole max-packet packet *plus* the status word the core
435        // pushes alongside it, and 128 words is exactly one 512-byte
436        // high-speed bulk packet with no room for that status -- so the
437        // channel armed but `HCINT` stayed all-zero forever (the same
438        // dead-channel signature as an unpowered core). A packet that
439        // small (<=64 bytes, control/interrupt) left room and worked; a
440        // 512-byte bulk packet did not. `NPTXFSA` must start after the
441        // RxFIFO's own words, hence `0x400`.
442        unsafe {
443            global.grxfsiz().write(|w| w.rxfd().bits(0x400));
444            global.gnptxfsiz_host().write(|w| {
445                w.nptxfsa().bits(0x400);
446                w.nptxfd().bits(0x400)
447            });
448            // Host periodic TX FIFO, sized right after the non-periodic
449            // one (start 0x800 = 0x400 RX + 0x400 NPTX). On this core
450            // this write does not stick -- `HPTXFSIZ` reads back 0
451            // regardless -- so this SoC apparently has no separately
452            // sizable host periodic TX FIFO. Harmless: interrupt (HID)
453            // transfers work anyway, the core handling periodic FIFO
454            // space itself.
455            global.hptxfsiz().write(|w| {
456                w.ptxsa().bits(0x800);
457                w.ptxfd().bits(0x400)
458            });
459        }
460
461        // Re-flush both FIFOs after resizing them -- the databook's
462        // recommended sequence whenever FIFO sizes change, so stale
463        // FIFO state from the old sizing can't linger.
464        global.grstctl().modify(|_, w| w.rxfflsh().set_bit());
465        while global.grstctl().read().rxfflsh().bit_is_set() {}
466        unsafe {
467            global
468                .grstctl()
469                .modify(|_, w| w.txfnum().bits(0x10).txfflsh().set_bit());
470        }
471        while global.grstctl().read().txfflsh().bit_is_set() {}
472
473        // Force host mode. The databook requires waiting 25ms after
474        // this before the mode change is guaranteed to have taken
475        // effect.
476        global.gusbcfg().modify(|_, w| w.fhmod().set_bit());
477        timer.delay_ms(25);
478
479        // Enable DMA mode. Confirmed on real hardware, not assumed:
480        // `GHWCFG2.ARCHITECTURE` reports `internal_dma`, not
481        // `slave_only` -- this core doesn't implement slave/PIO mode
482        // at all, so this bit isn't optional the way it might be on
483        // other DWC2 instantiations.
484        // `AXI_WAIT`: wait for all AXI writes to actually land before
485        // signaling DMA completion -- matches a known-working
486        // Broadcom-targeting reference driver's core init (rsta2's
487        // `uspi`/`circle`), not something the generic Synopsys
488        // databook flags as host-mode-mandatory, but cheap and
489        // directly relevant to whether this driver's own DMA
490        // completion signaling can be trusted.
491        // `GINT`: enables the core asserting its interrupt line to the
492        // CPU. Irrelevant to this pure-polling driver (nothing in this
493        // crate unmasks IRQ at the CPU level or routes USB through
494        // `Lic`, so the line, if asserted, is observed by nothing), but
495        // set to match the reference drivers' core init and leave the
496        // core ready for a future interrupt-driven path.
497        global
498            .gahbcfg()
499            .modify(|_, w| w.dmaen().set_bit().axi_wait().set_bit().gint().set_bit());
500
501        // Unmask the host-channel and port interrupts in `GINTMSK`, and
502        // mask start-of-frame. `GINTMSK` gates whether a pending source
503        // propagates to the core's interrupt line, so it has no bearing
504        // on the blocking path (which reads `HCINT`/`HFNUM` directly);
505        // it decides what an application that routes USB to the ARM core
506        // (`Lic::enable_usb_irq`) will actually see. `HCIM` (host
507        // channels, bit 25) and `PRTIM` (port, bit 24) use raw bits
508        // because this PAC generates a reader but no writer for the
509        // port-interrupt mask.
510        //
511        // `SOFM` is deliberately *cleared*. A high-speed port raises SOF
512        // every 125µs, so leaving it unmasked hands an application that
513        // enables the USB IRQ an 8kHz interrupt with nothing to service
514        // it — and since the line stays asserted until `GINTSTS.SOF` is
515        // acked, the core re-enters the handler forever rather than
516        // merely wasting cycles. Only [`Channel`]'s periodic-split
517        // scheduling needs SOF, and it unmasks the bit for exactly as
518        // long as some channel is waiting on a microframe.
519        global.gintmsk().modify(|_, w| w.sofm().clear_bit());
520        unsafe {
521            global
522                .gintmsk()
523                .modify(|r, w| w.bits(r.bits() | (1 << 24) | (1 << 25)));
524        }
525
526        // HNP/SRP (OTG session negotiation capability) aren't used by
527        // a plain host-only driver -- also matching the same
528        // reference driver, which explicitly clears both. Left at
529        // their reset defaults, this core may run OTG session/HNP
530        // negotiation logic that competes with straightforward
531        // host-mode operation; `SRQINT`/`CIDSCHG` (OTG session/
532        // connector-ID events) showing up in this driver's own
533        // `GINTSTS` dumps during bring-up is consistent with that.
534        global
535            .gusbcfg()
536            .modify(|_, w| w.hnpcap().clear_bit().srpcap().clear_bit());
537
538        // NB: `HCFG.FSLSPCS` (FS/LS PHY clock select) and `HFIR`
539        // (frame interval) are deliberately *not* programmed here, even
540        // though they're logically part of host setup. On real hardware,
541        // the port's connect/enable hardware sequence overwrites both:
542        // writing `HFIR = 48000` and `HCFG.FSLSPCS = 1` here, then
543        // reading them back after a device connected, showed `HFIR`
544        // reverted to its 60MHz reset default (0xea60) and `HCFG`
545        // cleared -- the core recomputes them from the enumerated port
546        // speed once the port comes up, discarding whatever was written
547        // beforehand. They're programmed in [`Self::reset_port`]
548        // instead, after the port is enabled and its speed is known,
549        // which is also where real DWC2 host drivers do it (their
550        // port-enable-change interrupt handler).
551
552        // Power the root port. `.write()`, not `.modify()`: `PCDET`/
553        // `PENCHNG`/`POCCHNG` are write-1-to-clear status bits, and
554        // `PENA` disables an already-enabled port if written 1 without
555        // meaning to (a well-known DWC2 footgun) — `.modify()` would
556        // read back and re-write whatever they currently hold,
557        // silently clearing or disabling something this call never
558        // meant to touch. `.write()`'s zeroed baseline (this
559        // register's reset value) plus only ever setting `ppwr` avoids
560        // that entirely.
561        host.hprt().write(|w| w.ppwr().set_bit());
562
563        // How many host channels this core implements. `GHWCFG2`
564        // (`hw_config0` in this PAC — see the module doc on its naming)
565        // encodes it as the count minus one, so a core reporting 7 has
566        // 8. Read rather than hardcoded, and still capped at the number
567        // the PAC will index: `host_channel(n)` panics at compile time
568        // past 12, and a bogus read must not turn into an out-of-range
569        // register access.
570        let num_channels =
571            (global.hw_config0().read().host_channel_count().bits() + 1).min(MAX_CHANNELS as u8);
572
573        Self {
574            global,
575            host,
576            allocated: Cell::new(0),
577            num_channels,
578        }
579    }
580
581    /// How many host channels this core implements — the ceiling on how
582    /// many [`Channel`]s can be outstanding at once (8 on this SoC).
583    pub fn num_channels(&self) -> usize {
584        self.num_channels as usize
585    }
586
587    /// Takes the lowest-numbered free host channel out of the pool,
588    /// returning `None` when every channel this core has is already
589    /// handed out.
590    ///
591    /// Exhaustion is reported, not queued: a caller that needs a channel
592    /// and can't have one is in a position to say so (or to wait on its
593    /// own terms), whereas a queue hidden in here would silently
594    /// serialise transfers a caller believed were concurrent. The
595    /// [`Channel`] returns its slot to the pool when dropped, so a
596    /// short-lived transfer can scope one rather than holding it.
597    ///
598    /// Takes `&self`, so several channels can be outstanding at once —
599    /// that's the whole point of the split between this type and
600    /// [`Channel`].
601    pub fn alloc_channel(&self) -> Option<Channel<'_>> {
602        let allocated = self.allocated.get();
603        let index = (0..self.num_channels as usize).find(|i| allocated & (1 << i) == 0)?;
604        self.allocated.set(allocated | (1 << index));
605        Some(Channel {
606            owner: self,
607            index,
608            dma_buffer: DmaBuffer([0; DMA_BUFFER_LEN]),
609            last_hcint: Cell::new(0),
610        })
611    }
612
613    /// True if the root port currently reports a device electrically
614    /// connected (`HPRT.PCSTS`). On this board, in practice, that's
615    /// the on-board SMSC LAN9514 hub — see this module's parent.
616    pub fn port_connected(&self) -> bool {
617        self.host.hprt().read().pcsts().bit_is_set()
618    }
619
620    /// USB bus reset on the root port — required before any transfer
621    /// will work, and before [`Self::port_speed`] is meaningful.
622    /// Asserts `PRST` for 50ms (generous relative to the USB 2.0
623    /// spec's 10ms minimum reset signaling time, matching what most
624    /// real host controllers use for root-hub-facing ports), then
625    /// clears it and waits 10ms recovery time (also spec-mandated).
626    /// Finally programs the FS/LS PHY clock and frame interval now
627    /// that the port is enabled and its speed is known (see below).
628    ///
629    /// Same `.write()`-with-zeroed-status-bits care as [`Self::init`]'s
630    /// port power-up — see that method's doc comment.
631    pub fn reset_port(&self, timer: &Timer) {
632        self.host
633            .hprt()
634            .write(|w| w.ppwr().set_bit().prst().set_bit());
635        timer.delay_ms(50);
636        self.host.hprt().write(|w| w.ppwr().set_bit());
637        timer.delay_ms(10);
638
639        // Acknowledge the port-change status bits the reset/enable
640        // sequence latched (`PCDET` device-connect, `PENCHNG` enable-
641        // change, `POCCHNG` overcurrent-change) -- all write-1-to-clear.
642        // Standard post-reset housekeeping the reference drivers do:
643        // left pending they keep `GINTSTS.PRTINT` permanently asserted,
644        // stale noise for any future interrupt-driven path. Same
645        // `.write()`-with-`ppwr`-only care as [`Self::init`]'s port
646        // power-up -- setting `PENA` here would *disable* the port, so
647        // it's deliberately left 0 in this write (writing 0 to `PENA`
648        // is a no-op; only writing 1 disables).
649        self.host.hprt().write(|w| {
650            w.ppwr().set_bit();
651            w.pcdet().set_bit();
652            w.penchng().set_bit();
653            w.pocchng().set_bit()
654        });
655
656        // Program the FS/LS PHY clock select and frame interval *here*,
657        // after the port has been reset and enabled, rather than in
658        // `init`. On real hardware the port's connect/enable hardware
659        // sequence overwrites both `HCFG.FSLSPCS` and `HFIR` with
660        // values recomputed from the enumerated port speed, discarding
661        // anything written before the port came up (see `init`'s note).
662        // This is also where real DWC2 host drivers do it — in their
663        // port-enable-change interrupt handler, keyed off the detected
664        // speed — not once at core init.
665        //
666        // Only for a full/low-speed port. This SoC's DWC2 uses an
667        // internal UTMI+ PHY that does reach high speed (the on-board
668        // LAN9514 hub enumerates at HS on this root port), and at HS
669        // the port bring-up already leaves `HFIR` at the correct 60MHz-
670        // based reset default (0xea60 = 60000 = 1ms) and `FSLSPCS` is a
671        // don't-care. Only a full/low-speed port needs the 48MHz FS/LS
672        // PHY clock selected (`FSLSPCS = 1`) and the matching 1ms frame
673        // interval (`HFIR.FRIVL = 48000`); forcing those at HS would
674        // set the wrong frame interval.
675        if self.port_speed() != 0 {
676            unsafe {
677                self.host.hcfg().modify(|_, w| w.fslspcs().bits(1));
678                self.host.hfir().write(|w| w.frivl().bits(48_000));
679            }
680        }
681    }
682
683    /// True if the root port is enabled (`HPRT.PENA`) — set by
684    /// hardware once a device successfully responds to
685    /// [`Self::reset_port`], never something software sets directly
686    /// (writing 1 here manually would actually *disable* an
687    /// already-enabled port — see [`Self::init`]'s doc comment on the
688    /// same footgun).
689    pub fn port_enabled(&self) -> bool {
690        self.host.hprt().read().pena().bit_is_set()
691    }
692
693    /// The root port's detected device speed (`HPRT.PSPD`), valid only
694    /// once [`Self::port_enabled`] is true: `0` = high-speed, `1` =
695    /// full-speed, `2` = low-speed. All three are reachable on this SoC
696    /// — the on-board LAN9514 hub enumerates at high speed on this root
697    /// port.
698    pub fn port_speed(&self) -> u8 {
699        self.host.hprt().read().pspd().bits()
700    }
701
702    /// Direct access to the underlying global/OTG control registers,
703    /// for diagnostics or lower-level work this type doesn't expose
704    /// yet — mirrors [`crate::pac`]'s own role for other drivers in
705    /// this crate.
706    pub fn global(&self) -> &USB_OTG_GLOBAL {
707        &self.global
708    }
709
710    /// Direct access to the underlying host-mode registers (per-
711    /// channel registers included) — see [`Self::global`].
712    pub fn host(&self) -> &USB_OTG_HOST {
713        &self.host
714    }
715
716    /// Returns a channel's slot to the pool. Called by [`Channel`]'s
717    /// `Drop`, which is the only way a slot is ever freed.
718    fn free_channel(&self, index: usize) {
719        self.allocated.set(self.allocated.get() & !(1 << index));
720    }
721}
722
723/// One host channel, taken from [`Dwc2Host::alloc_channel`] — the thing
724/// a USB transfer actually runs on.
725///
726/// Every transfer primitive lives here rather than on [`Dwc2Host`]
727/// because a host channel is genuinely independent hardware: its
728/// registers are its own, and the core arbitrates between channels by
729/// itself. Holding one is therefore what grants the right to run a
730/// transfer, and two callers holding two channels can drive two
731/// endpoints without either taking a mutable borrow of the controller.
732///
733/// The channel carries the DMA scratch buffer its control and
734/// interrupt transfers stage through, so it is not a trivially cheap
735/// value to move around — allocate one per endpoint that needs one and
736/// keep it, rather than re-allocating per transfer. Dropping it frees
737/// the slot for another caller.
738pub struct Channel<'a> {
739    /// The controller this channel belongs to — borrowed immutably, so
740    /// its siblings can be outstanding at the same time.
741    owner: &'a Dwc2Host,
742    /// This channel's index into the core's host-channel registers.
743    index: usize,
744    /// This channel's own DMA staging buffer — see [`DmaBuffer`].
745    dma_buffer: DmaBuffer,
746    /// Raw `HCINT` value captured at the most recent halt on this
747    /// channel — see [`Self::last_interrupt`]. Interior-mutable so the
748    /// transfer path (which takes `&self`) can record it.
749    last_hcint: Cell<u32>,
750}
751
752impl Drop for Channel<'_> {
753    fn drop(&mut self) {
754        self.owner.free_channel(self.index);
755    }
756}
757
758impl Channel<'_> {
759    /// This channel's index into the core's host-channel registers.
760    /// Only of interest for diagnostics — nothing in this API takes a
761    /// channel number any more.
762    pub fn index(&self) -> usize {
763        self.index
764    }
765
766    /// The raw `HCINT` (host channel interrupt) value captured the last
767    /// time this channel halted — the exact bits the transfer's
768    /// [`TransferError`]/success was derived from (`XFRC`, `STALL`,
769    /// `NAK`, `ACK`, `NYET`, `TXERR`, `BBERR`, `CHH`, …). This driver
770    /// collapses those bits into a coarse result; a caller debugging a
771    /// transfer that fails or behaves unexpectedly can read the
772    /// underlying bits here to see exactly what the hardware reported.
773    /// Only meaningful immediately after a transfer method returns.
774    pub fn last_interrupt(&self) -> u32 {
775        self.last_hcint.get()
776    }
777
778    /// The core's host-mode register block, for the handful of shared
779    /// registers a channel touches (`HAINTMSK`, `HFNUM`) alongside its
780    /// own.
781    fn regs(&self) -> &USB_OTG_HOST {
782        &self.owner.host
783    }
784
785    /// This channel's own register block.
786    fn ch(&self) -> &crate::pac::usb_otg_host::HOST_CHANNEL {
787        self.owner.host.host_channel(self.index)
788    }
789
790    /// Runs one SETUP-stage transaction: 8 raw bytes, always PID SETUP,
791    /// always OUT direction (a SETUP token is functionally an OUT
792    /// transfer at the protocol level).
793    pub fn control_setup(
794        &mut self,
795        endpoint: ControlEndpoint,
796        setup: &[u8; 8],
797        timer: &Timer,
798    ) -> Result<(), TransferError> {
799        self.dma_buffer.0[..8].copy_from_slice(setup);
800        let address = self.dma_buffer.0.as_ptr() as u32;
801        clean_range(address, 8);
802
803        let txn = Transaction {
804            endpoint_number: 0,
805            endpoint_type: EndpointType::Control,
806            direction_in: false,
807            pid: DataPid::Setup,
808            transfer_size: 8,
809            dma_address: address,
810        };
811        self.run_transaction(endpoint, &txn, timer)?;
812        Ok(())
813    }
814
815    /// Runs one DATA-stage IN transaction, reading up to `buf.len()`
816    /// bytes (always starting at PID DATA1 — see [`DataPid::Data1`]; the
817    /// DWC2 toggles DATA1/DATA0 itself across a multi-packet transfer).
818    /// Returns the number of bytes actually received, which can be less
819    /// than `buf.len()` if the device sent a short packet. `buf.len()`
820    /// must be at most [`MAX_TRANSFER_LEN`] — this channel's DMA scratch
821    /// buffer size.
822    pub fn control_data_in(
823        &mut self,
824        endpoint: ControlEndpoint,
825        buf: &mut [u8],
826        timer: &Timer,
827    ) -> Result<usize, TransferError> {
828        debug_assert!(buf.len() <= DMA_BUFFER_LEN);
829
830        let address = self.dma_buffer.0.as_ptr() as u32;
831        let txn = Transaction {
832            endpoint_number: 0,
833            endpoint_type: EndpointType::Control,
834            direction_in: true,
835            pid: DataPid::Data1,
836            transfer_size: buf.len() as u32,
837            dma_address: address,
838        };
839        let received = self.run_transaction(endpoint, &txn, timer)?;
840
841        invalidate_range(address, buf.len());
842        buf[..received].copy_from_slice(&self.dma_buffer.0[..received]);
843        Ok(received)
844    }
845
846    /// Runs one zero-length STATUS-stage OUT transaction (always PID
847    /// DATA1 — see [`DataPid::Data1`]), completing a control transfer
848    /// that had a device-to-host (IN) data stage, or no data stage in
849    /// the host-to-device direction.
850    pub fn control_status_out(
851        &mut self,
852        endpoint: ControlEndpoint,
853        timer: &Timer,
854    ) -> Result<(), TransferError> {
855        let address = self.dma_buffer.0.as_ptr() as u32;
856        let txn = Transaction {
857            endpoint_number: 0,
858            endpoint_type: EndpointType::Control,
859            direction_in: false,
860            pid: DataPid::Data1,
861            transfer_size: 0,
862            dma_address: address,
863        };
864        self.run_transaction(endpoint, &txn, timer)?;
865        Ok(())
866    }
867
868    /// Runs one zero-length STATUS-stage IN transaction (always PID
869    /// DATA1 — see [`DataPid::Data1`]), completing a control transfer
870    /// that had no data stage (e.g. SET_ADDRESS, SET_CONFIGURATION): a
871    /// no-data control transfer's status stage is always IN, the
872    /// opposite of its (absent) data stage.
873    pub fn control_status_in(
874        &mut self,
875        endpoint: ControlEndpoint,
876        timer: &Timer,
877    ) -> Result<(), TransferError> {
878        let address = self.dma_buffer.0.as_ptr() as u32;
879        let txn = Transaction {
880            endpoint_number: 0,
881            endpoint_type: EndpointType::Control,
882            direction_in: true,
883            pid: DataPid::Data1,
884            transfer_size: 0,
885            dma_address: address,
886        };
887        self.run_transaction(endpoint, &txn, timer)?;
888        Ok(())
889    }
890
891    /// Runs one DATA-stage OUT transaction, sending `data` (always
892    /// starting at PID DATA1 — see [`DataPid::Data1`]; the DWC2 toggles
893    /// across a multi-packet transfer itself). For the host-to-device
894    /// control transfers that carry data (e.g. a vendor register write —
895    /// see [`crate::usb::control::vendor_out`]); the plain SET_ADDRESS/
896    /// SET_CONFIGURATION requests have no data stage and use
897    /// [`Self::control_status_in`] directly. `data.len()` must be at most
898    /// [`MAX_TRANSFER_LEN`].
899    pub fn control_data_out(
900        &mut self,
901        endpoint: ControlEndpoint,
902        data: &[u8],
903        timer: &Timer,
904    ) -> Result<(), TransferError> {
905        debug_assert!(data.len() <= DMA_BUFFER_LEN);
906
907        self.dma_buffer.0[..data.len()].copy_from_slice(data);
908        let address = self.dma_buffer.0.as_ptr() as u32;
909        clean_range(address, data.len());
910
911        let txn = Transaction {
912            endpoint_number: 0,
913            endpoint_type: EndpointType::Control,
914            direction_in: false,
915            pid: DataPid::Data1,
916            transfer_size: data.len() as u32,
917            dma_address: address,
918        };
919        self.run_transaction(endpoint, &txn, timer)?;
920        Ok(())
921    }
922
923    /// Runs one interrupt-IN transaction on `endpoint_number` of
924    /// `endpoint`'s device, reading up to `buf.len()` bytes into `buf`
925    /// and returning how many were received (0 is possible). `endpoint`
926    /// supplies the device address/speed/split and *this endpoint's*
927    /// max packet size.
928    ///
929    /// `data_toggle` holds the endpoint's DATA0/DATA1 toggle, which —
930    /// unlike a control transfer — persists across transfers: start it
931    /// `false` (DATA0) when the device is configured, then pass the same
932    /// `&mut bool` back on every poll. It flips only on a successful
933    /// transfer, and is left unchanged on [`TransferError::Nak`] (the
934    /// endpoint had nothing to send — the normal "no event yet" answer
935    /// when polling), so a NAK'd poll can simply be retried.
936    ///
937    /// The caller is responsible for pacing polls (the endpoint's
938    /// `bInterval`).
939    pub fn interrupt_in(
940        &mut self,
941        endpoint: ControlEndpoint,
942        endpoint_number: u8,
943        data_toggle: &mut bool,
944        buf: &mut [u8],
945        timer: &Timer,
946    ) -> Result<usize, TransferError> {
947        debug_assert!(buf.len() <= DMA_BUFFER_LEN);
948
949        let address = self.dma_buffer.0.as_ptr() as u32;
950        let txn = Transaction {
951            endpoint_number,
952            endpoint_type: EndpointType::Interrupt,
953            direction_in: true,
954            pid: if *data_toggle {
955                DataPid::Data1
956            } else {
957                DataPid::Data0
958            },
959            transfer_size: buf.len() as u32,
960            dma_address: address,
961        };
962        let received = self.run_transaction(endpoint, &txn, timer)?;
963        // Only a completed transfer advances the toggle; a NAK left it
964        // untouched by returning early above.
965        *data_toggle = !*data_toggle;
966
967        invalidate_range(address, buf.len());
968        buf[..received].copy_from_slice(&self.dma_buffer.0[..received]);
969        Ok(received)
970    }
971
972    /// Runs one bulk-OUT transfer on `endpoint_number` of `endpoint`'s
973    /// device, sending all of `buf` (which may span several max-packet
974    /// packets — the DWC2 splits it and toggles the PID across them from
975    /// one channel start). Returns the number of bytes sent. DMA reads
976    /// straight from `buf`, so there's no size cap from the shared
977    /// control scratch buffer.
978    ///
979    /// `data_toggle` is the endpoint's persistent DATA0/DATA1 toggle,
980    /// like [`Self::interrupt_in`]'s: start it `false` after configuring
981    /// the endpoint and pass the same `&mut bool` each call. On success
982    /// it's updated to the toggle the *next* transfer must resume with
983    /// (read back from the hardware, which is correct even across a
984    /// multi-packet transfer); a [`TransferError::Nak`] leaves it
985    /// unchanged so the caller can retry.
986    ///
987    /// Not yet exercised on real hardware — added as the primitive the
988    /// LAN9514 Ethernet driver's frame TX will use (see
989    /// [`crate::usb::lan9514`]).
990    pub fn bulk_out(
991        &mut self,
992        endpoint: ControlEndpoint,
993        endpoint_number: u8,
994        data_toggle: &mut bool,
995        buf: &[u8],
996        timer: &Timer,
997    ) -> Result<usize, TransferError> {
998        let address = buf.as_ptr() as u32;
999        clean_range(address, buf.len());
1000
1001        let txn = Transaction {
1002            endpoint_number,
1003            endpoint_type: EndpointType::Bulk,
1004            direction_in: false,
1005            pid: Self::toggle_pid(*data_toggle),
1006            transfer_size: buf.len() as u32,
1007            dma_address: address,
1008        };
1009        let sent = self.run_transaction(endpoint, &txn, timer)?;
1010        *data_toggle = self.next_toggle();
1011        Ok(sent)
1012    }
1013
1014    /// Runs one bulk-IN transfer on `endpoint_number` of `endpoint`'s
1015    /// device, reading up to `buf.len()` bytes into `buf` and returning
1016    /// how many arrived (a short packet ends it early). DMA writes
1017    /// straight into `buf`, so `buf` **must be cache-line aligned and
1018    /// occupy whole cache lines** — the cache invalidation after the
1019    /// transfer works at cache-line granularity, and a buffer sharing a
1020    /// line with other live data would have that data discarded.
1021    ///
1022    /// `data_toggle` behaves as in [`Self::bulk_out`].
1023    ///
1024    /// `buf` is rounded *down* to a whole number of max-packet packets
1025    /// for the transfer size: the DWC2 won't run a multi-packet IN whose
1026    /// programmed size isn't a multiple of the max packet size (the
1027    /// channel arms but never leaves `HCINT` all-zero). A short packet
1028    /// still ends the transfer early, so this only caps how much one call
1029    /// can read — `buf` should therefore be at least one max packet, and
1030    /// sizing it to a whole number of packets wastes nothing.
1031    pub fn bulk_in(
1032        &mut self,
1033        endpoint: ControlEndpoint,
1034        endpoint_number: u8,
1035        data_toggle: &mut bool,
1036        buf: &mut [u8],
1037        timer: &Timer,
1038    ) -> Result<usize, TransferError> {
1039        let address = buf.as_mut_ptr() as u32;
1040        debug_assert!(
1041            address.is_multiple_of(MIN_CACHE_LINE),
1042            "bulk IN buffer must be cache-line aligned"
1043        );
1044
1045        let max_packet_size = endpoint.max_packet_size.max(1) as u32;
1046        let transfer_size = buf.len() as u32 / max_packet_size * max_packet_size;
1047
1048        let txn = Transaction {
1049            endpoint_number,
1050            endpoint_type: EndpointType::Bulk,
1051            direction_in: true,
1052            pid: Self::toggle_pid(*data_toggle),
1053            transfer_size,
1054            dma_address: address,
1055        };
1056        let received = self.run_transaction(endpoint, &txn, timer)?;
1057        *data_toggle = self.next_toggle();
1058
1059        invalidate_range(address, buf.len());
1060        Ok(received)
1061    }
1062
1063    /// The [`DataPid`] a persistent toggle (`false` = DATA0, `true` =
1064    /// DATA1) selects for the next bulk/interrupt packet.
1065    fn toggle_pid(data_toggle: bool) -> DataPid {
1066        if data_toggle {
1067            DataPid::Data1
1068        } else {
1069            DataPid::Data0
1070        }
1071    }
1072
1073    /// The data toggle (`true` = DATA1) to resume the next transfer on
1074    /// this channel with, read back from `HCTSIZ.DPID` after a completed
1075    /// transfer — the DWC2 leaves it pointing at the next expected PID,
1076    /// which is correct even when the transfer spanned several packets
1077    /// (so it can't just be flipped like the single-packet interrupt
1078    /// path does).
1079    fn next_toggle(&self) -> bool {
1080        self.ch().hctsiz().read().dpid().bits() == DataPid::Data1.bits()
1081    }
1082
1083    /// Programs `HCSPLT`/`HCDMA`/`HCTSIZ`/`HCCHAR` for one DMA
1084    /// transaction described by `txn`
1085    /// and enables the channel — this alone starts the transaction (the
1086    /// DMA engine pulls from / pushes to `txn.dma_address` on its own
1087    /// once `CHENA` is set); [`Self::wait_for_halt`] just waits for it
1088    /// to finish. `txn.dma_address` is a plain physical address,
1089    /// translated to the VideoCore bus alias here (see
1090    /// [`to_vc_bus_address`]). `complete_split` selects the
1091    /// start-split (`false`) vs complete-split (`true`) phase and is
1092    /// meaningful only when `endpoint.split` is set.
1093    ///
1094    /// `.write()`, not `.modify()`, for `HCCHAR`: unlike `HPRT`, it's
1095    /// fully per-channel, so there's no cross-channel state to
1096    /// preserve — every field this transaction needs is specified
1097    /// here.
1098    ///
1099    /// `odd_frame` overrides the `HCCHAR.ODDFRM` bit: periodic split
1100    /// scheduling (see [`Self::run_periodic_split_packet`]) computes it
1101    /// per microframe and passes `Some`, while everything else passes
1102    /// `None` to get the default (frame parity for a direct transfer,
1103    /// cleared for a non-periodic split).
1104    fn start_channel(
1105        &self,
1106        endpoint: ControlEndpoint,
1107        txn: &Transaction,
1108        complete_split: bool,
1109        odd_frame: Option<bool>,
1110    ) {
1111        let ch = self.ch();
1112
1113        // Clear any stale interrupt bits left over from a previous
1114        // transaction on this channel -- `HCINT` bits are
1115        // write-1-to-clear and don't self-clear just because a new
1116        // transaction is starting.
1117        unsafe {
1118            ch.hcint().write(|w| w.bits(0xffff_ffff));
1119        }
1120
1121        // Program the per-channel interrupt mask explicitly, rather
1122        // than leaving it at its reset value — the known-working
1123        // reference driver for this SoC does the same before every
1124        // channel start.
1125        //
1126        // `CHH` alone, not every condition. `HCINTMSK` gates only what
1127        // reaches `HAINT` and the core's interrupt line; the `HCINT`
1128        // bits themselves latch regardless, so the blocking path (which
1129        // reads `HCINT` directly) sees exactly what it always did, and
1130        // so does [`Self::interpret_halt`] at the halt. What the
1131        // narrower mask buys is that "this channel raised `HAINT`" means
1132        // "this channel halted" and nothing else — which is what
1133        // [`asynch::on_irq`] needs. With every condition unmasked, an
1134        // intermediate `ACK` or `NAK` would assert the line too, and a
1135        // handler would have to either ack it (destroying a bit the
1136        // split logic reads at the halt — `run_split_packet` keys off
1137        // `ACK`) or leave it asserted (a re-entering interrupt forever).
1138        unsafe {
1139            ch.hcintmsk().write(|w| w.bits(HCINT_CHH));
1140        }
1141
1142        // `HAINTMSK` -- which decides whether this channel's `HCINT`
1143        // reaches `GINTSTS` and so the CPU -- is deliberately *not*
1144        // touched here, even though this is where the reference driver
1145        // for this SoC (Broadcom/Raspberry Pi Foundation's `dwc_otg`)
1146        // sets it. It is managed by the async layer instead, per wait
1147        // (see `asynch`'s `arm`/`disarm`).
1148        //
1149        // The distinction only matters once something routes USB to the
1150        // ARM core, and then it matters a great deal. This function
1151        // serves both the blocking and the async path. A blocking
1152        // transfer wants no interrupt at all: it polls `HCINT` itself.
1153        // If its channel were unmasked here, its halt would assert the
1154        // controller's interrupt line, and the handler -- which
1155        // services only channels an async transfer is waiting on, and
1156        // must leave a polled channel's `HCINT` latched for its owner
1157        // to read -- would return without acking it. The line is level
1158        // triggered, so the core would re-enter the handler forever and
1159        // the polling loop it interrupted would never resume. A hang,
1160        // not a slow-down, and only in a program that mixes the two
1161        // styles.
1162
1163        // Split control (`HCSPLT`): for a device behind a high-speed
1164        // hub's transaction translator, enable the split and address
1165        // the translator (hub address + downstream port), with
1166        // `complsplt` selecting the start-split (`false`) or
1167        // complete-split (`true`) phase and `xactpos = 0b11` meaning the
1168        // whole payload (not an isochronous-OUT slice). For a
1169        // direct-connected device, zero it — explicitly, so leftover
1170        // state can't make the channel act like a split.
1171        unsafe {
1172            match endpoint.split {
1173                Some(split) => ch.hcsplt().write(|w| {
1174                    w.hubaddr().bits(split.hub_address);
1175                    w.prtaddr().bits(split.port);
1176                    w.xactpos().bits(0b11);
1177                    w.complsplt().bit(complete_split);
1178                    w.spliten().set_bit()
1179                }),
1180                None => ch.hcsplt().write(|w| w.bits(0)),
1181            }
1182        }
1183
1184        unsafe {
1185            ch.hcdma()
1186                .write(|w| w.dmaaddr().bits(to_vc_bus_address(txn.dma_address)));
1187        }
1188
1189        // Packet count: how many max-packet-size packets `transfer_size`
1190        // spans, rounded up, minimum 1 (a zero-length transfer is still
1191        // one — empty — packet). With `PKTCNT > 1` the DWC2 DMA engine
1192        // moves each packet to/from consecutive buffer offsets and
1193        // toggles the DATA0/DATA1 PID itself, so a whole multi-packet
1194        // control-data stage runs from a single channel start.
1195        let max_packet_size = endpoint.max_packet_size.max(1) as u32;
1196        let packet_count = txn.transfer_size.div_ceil(max_packet_size).max(1);
1197
1198        unsafe {
1199            ch.hctsiz().write(|w| {
1200                w.xfrsiz().bits(txn.transfer_size);
1201                w.pktcnt().bits(packet_count as u16);
1202                w.dpid().bits(txn.pid.bits())
1203            });
1204        }
1205
1206        // Odd/even frame bit. A periodic split passes it in explicitly
1207        // (its scheduler picks the microframe each start-/complete-split
1208        // runs in — see [`Self::run_periodic_split_packet`]). Otherwise:
1209        // for a direct (non-split) transfer, set it from the current
1210        // frame's parity — the reference drivers for this SoC (rsta2's
1211        // `circle`/`uspi`) do this on every non-split channel start
1212        // regardless of endpoint type. For a non-periodic split transfer
1213        // it must be *cleared*: those same drivers' non-periodic split
1214        // scheduler reports odd-frame = false, and leaving frame parity
1215        // in it here mis-schedules the start-split (observed as a
1216        // transaction error on the start-split).
1217        let odd_frame = match odd_frame {
1218            Some(odd) => odd,
1219            None if endpoint.split.is_some() => false,
1220            None => self.regs().hfnum().read().frnum().bits() & 1 == 1,
1221        };
1222
1223        unsafe {
1224            ch.hcchar().write(|w| {
1225                w.mpsiz().bits(endpoint.max_packet_size);
1226                w.epnum().bits(txn.endpoint_number);
1227                w.epdir().bit(txn.direction_in);
1228                w.lsdev().bit(endpoint.low_speed);
1229                w.eptyp().bits(txn.endpoint_type.bits());
1230                w.mc().bits(1);
1231                w.dad().bits(endpoint.address);
1232                w.oddfrm().bit(odd_frame);
1233                w.chena().set_bit()
1234            });
1235        }
1236    }
1237
1238    /// Acknowledges (clears) every pending bit in this channel's
1239    /// `HCINT`.
1240    fn ack_hcint(&self) {
1241        unsafe {
1242            self.ch().hcint().write(|w| w.bits(0xffff_ffff));
1243        }
1244    }
1245
1246    /// Forcibly halts this channel after [`Self::run_channel`] times out,
1247    /// leaving it in a clean, reusable state. A timeout means `HCINT`
1248    /// never signaled completion, so — per the DWC2 databook — `CHENA`
1249    /// may still be set and the transaction still technically active in
1250    /// hardware. Confirmed the hard way on real hardware: once one
1251    /// control transfer timed out, every subsequent attempt on that
1252    /// same channel *also* failed, each a different way (`Stall`, then
1253    /// `Timeout` again, ...) — consistent with each new attempt's
1254    /// `start_channel` call reprogramming and re-enabling a channel
1255    /// that was still live from the timed-out one, rather than starting
1256    /// clean. The databook's documented way to abort an active channel
1257    /// is requesting a disable (`CHDIS` set, `CHENA` left set) and
1258    /// waiting for `HCINT.CHH` (channel halted); this does that, with
1259    /// its own short timeout so a channel that won't halt can't wedge
1260    /// the caller forever either.
1261    fn abort_channel(&self, timer: &Timer) {
1262        const ABORT_TIMEOUT_US: u64 = 10_000;
1263
1264        let ch = self.ch();
1265        ch.hcchar()
1266            .modify(|_, w| w.chdis().set_bit().chena().set_bit());
1267
1268        let start = timer.now_micros();
1269        while ch.hcint().read().chh().bit_is_clear() {
1270            if timer.now_micros() - start > ABORT_TIMEOUT_US {
1271                break;
1272            }
1273        }
1274        self.ack_hcint();
1275    }
1276
1277    /// Waits for this channel to halt (`HCINT.CHH` — the DMA-mode
1278    /// completion signal), returning the raw `HCINT` value at that
1279    /// point. On timeout (the channel never halts) forcibly disables it
1280    /// via [`Self::abort_channel`] and returns [`TransferError::Timeout`].
1281    ///
1282    /// Polls for `CHH` specifically, not `XFRC`: a halted channel is
1283    /// already in a clean, reusable state, so returning on `CHH`
1284    /// (whatever the reason) lets [`Self::start_channel`] re-arm it
1285    /// directly on the next call. Waiting on `XFRC` instead would spin
1286    /// the full timeout on any non-success halt (`STALL`, `NAK`, a
1287    /// complete-split `NYET`, or the reason-less `CHH`-only halt this
1288    /// SoC produces intermittently) and then have to force a disable —
1289    /// and forcing `CHDIS`/`CHENA` on an already-halted channel was
1290    /// observed to wedge the core into a dead, all-zero-`HCINT` state.
1291    fn wait_for_halt(&self, timer: &Timer) -> Result<u32, TransferError> {
1292        const TIMEOUT_US: u64 = 50_000;
1293
1294        let ch = self.ch();
1295        let start = timer.now_micros();
1296        loop {
1297            let hcint = ch.hcint().read().bits();
1298            if hcint & HCINT_CHH != 0 {
1299                self.last_hcint.set(hcint);
1300                self.ack_hcint();
1301                return Ok(hcint);
1302            }
1303            if timer.now_micros() - start > TIMEOUT_US {
1304                // Record the channel's `HCINT` at the moment it timed out
1305                // (before the abort clears it) so [`Self::last_interrupt`]
1306                // reflects the stuck transfer, not the last successful one.
1307                self.last_hcint.set(hcint);
1308                self.abort_channel(timer);
1309                return Err(TransferError::Timeout);
1310            }
1311        }
1312    }
1313
1314    /// Maps a halted channel's `HCINT` bits to a transfer result. On
1315    /// `XFRC` (success) returns the bytes actually transferred —
1316    /// `requested` (the originally programmed size) minus
1317    /// `HCTSIZ.XFRSIZ`'s leftover count, which is why `requested` is
1318    /// passed in; otherwise maps the reason bit to a [`TransferError`],
1319    /// or [`TransferError::Halted`] for a halt with no reason bit set.
1320    fn interpret_halt(&self, hcint: u32, requested: usize) -> Result<usize, TransferError> {
1321        if hcint & HCINT_XFRC != 0 {
1322            let remaining = self.ch().hctsiz().read().xfrsiz().bits() as usize;
1323            Ok(requested - remaining)
1324        } else if hcint & HCINT_STALL != 0 {
1325            Err(TransferError::Stall)
1326        } else if hcint & HCINT_TXERR != 0 {
1327            Err(TransferError::TransactionError)
1328        } else if hcint & HCINT_BBERR != 0 {
1329            Err(TransferError::Babble)
1330        } else if hcint & HCINT_FRMOR != 0 {
1331            Err(TransferError::FrameOverrun)
1332        } else if hcint & HCINT_DTERR != 0 {
1333            Err(TransferError::DataToggleError)
1334        } else if hcint & HCINT_NAK != 0 {
1335            Err(TransferError::Nak)
1336        } else {
1337            Err(TransferError::Halted)
1338        }
1339    }
1340
1341    /// Runs one non-split channel transaction: wait for the (already
1342    /// armed) channel to halt, then interpret the result.
1343    fn run_channel(&self, timer: &Timer) -> Result<usize, TransferError> {
1344        let requested = self.ch().hctsiz().read().xfrsiz().bits() as usize;
1345        let hcint = self.wait_for_halt(timer)?;
1346        self.interpret_halt(hcint, requested)
1347    }
1348
1349    /// Arms and runs one channel transfer, transparently doing split
1350    /// transactions when `endpoint.split` is set, or a plain transaction
1351    /// otherwise. `txn.transfer_size` bytes move to/from
1352    /// `txn.dma_address` (a plain physical address; [`Self::start_channel`]
1353    /// translates it). Returns the number of bytes moved.
1354    fn run_transaction(
1355        &self,
1356        endpoint: ControlEndpoint,
1357        txn: &Transaction,
1358        timer: &Timer,
1359    ) -> Result<usize, TransferError> {
1360        if endpoint.split.is_none() {
1361            // Direct: the DWC2 handles the whole (possibly multi-packet)
1362            // transfer from one channel start.
1363            self.start_channel(endpoint, txn, false, None);
1364            return self.run_channel(timer);
1365        }
1366
1367        // Split: the DWC2 does one packet per start-split/complete-split,
1368        // so a multi-packet transfer is driven a packet at a time here,
1369        // advancing the buffer and toggling the data PID as it goes.
1370        // Interrupt (periodic) splits are scheduled against the
1371        // microframe counter; control (non-periodic) splits aren't.
1372        let periodic = txn.endpoint_type == EndpointType::Interrupt;
1373        let max_packet_size = endpoint.max_packet_size.max(1) as u32;
1374        let mut offset = 0;
1375        let mut pid = txn.pid;
1376        loop {
1377            let this_packet = (txn.transfer_size - offset).min(max_packet_size);
1378            let packet = Transaction {
1379                transfer_size: this_packet,
1380                dma_address: txn.dma_address + offset,
1381                pid,
1382                ..*txn
1383            };
1384            let received = if periodic {
1385                self.run_periodic_split_packet(endpoint, &packet, timer)? as u32
1386            } else {
1387                self.run_split_packet(endpoint, &packet, timer)? as u32
1388            };
1389            offset += received;
1390            pid = pid.toggled();
1391            // Done once the whole transfer is satisfied, or the device
1392            // ended it early with a short packet (fewer than a full max
1393            // packet size).
1394            if received < this_packet || offset >= txn.transfer_size {
1395                break;
1396            }
1397        }
1398        Ok(offset as usize)
1399    }
1400
1401    /// Runs one single-packet split transaction — the start-split (which
1402    /// the hub's transaction translator must ACK) then complete-split
1403    /// polling until it has the relayed downstream result. Returns the
1404    /// bytes moved for this packet.
1405    ///
1406    /// The first complete-split poll goes out immediately after the
1407    /// start-split's ACK; subsequent polls are paced a few microframes
1408    /// apart ([`CSPLIT_RETRY_DELAY_US`]) to give the translator time to
1409    /// run the relayed full/low-speed transaction. `XFRC` means done;
1410    /// `NYET` (translator not finished) and `NAK` (device not ready)
1411    /// mean poll again, up to [`MAX_CSPLIT_POLLS`] times; any real error
1412    /// bit ends it.
1413    fn run_split_packet(
1414        &self,
1415        endpoint: ControlEndpoint,
1416        packet: &Transaction,
1417        timer: &Timer,
1418    ) -> Result<usize, TransferError> {
1419        let requested = packet.transfer_size as usize;
1420
1421        self.start_channel(endpoint, packet, false, None);
1422        let hcint = self.wait_for_halt(timer)?;
1423        if hcint & HCINT_ACK == 0 {
1424            return self.interpret_halt(hcint, requested);
1425        }
1426
1427        let mut hcint = 0;
1428        for attempt in 0..MAX_CSPLIT_POLLS {
1429            if attempt > 0 {
1430                timer.delay_us(CSPLIT_RETRY_DELAY_US);
1431            }
1432            self.start_channel(endpoint, packet, true, None);
1433            hcint = self.wait_for_halt(timer)?;
1434            if hcint & (HCINT_NYET | HCINT_NAK) != 0 && hcint & HCINT_XFRC == 0 {
1435                continue;
1436            }
1437            return self.interpret_halt(hcint, requested);
1438        }
1439        // Exhausted the poll budget -- report the last result (a bare
1440        // NYET/NAK maps to a retryable error the caller can re-drive).
1441        self.interpret_halt(hcint, requested)
1442    }
1443
1444    /// Runs one single-packet *periodic* split transaction — an
1445    /// interrupt endpoint's start-/complete-split, which unlike the
1446    /// non-periodic control split ([`Self::run_split_packet`]) must be
1447    /// scheduled against the microframe counter (`HFNUM.FRNUM`, which
1448    /// counts 125µs microframes on this high-speed root port). The
1449    /// scheduling — which microframe the start-split goes out in, and
1450    /// the consecutive microframes the complete-splits retry in — mirrors
1451    /// the periodic frame scheduler of a known-working reference driver
1452    /// for this SoC (rsta2's `circle`/`uspi`, `dwhciframeschedper.c`):
1453    /// a fixed complete-split delivered on a fixed 5-microframe cadence
1454    /// (what [`Self::run_split_packet`] does) never lands in the window
1455    /// where the transaction translator has the relayed full/low-speed
1456    /// result, so it only ever reads `NYET` and the transfer never
1457    /// completes.
1458    ///
1459    /// - Start-split: the next microframe after now, skipping microframe
1460    ///   6 (the reference scheduler avoids scheduling a start-split there,
1461    ///   since its complete-splits would straddle the 1ms frame boundary).
1462    ///   Expects `ACK`.
1463    /// - Complete-split: first at start-frame + 2 microframes, then each
1464    ///   following microframe, `HCCHAR.ODDFRM` tracking each one's parity.
1465    ///   `XFRC` completes it; `NYET`/`ACK` means the translator isn't done
1466    ///   — retry a bounded number of times (matching the reference
1467    ///   driver's count); `NAK` means the device had nothing to send this
1468    ///   interval.
1469    ///
1470    /// Both an exhausted `NYET` retry budget and a device `NAK` map to
1471    /// [`TransferError::Nak`]: for an interrupt-IN poll both simply mean
1472    /// "no report ready this interval", which the caller re-drives on its
1473    /// next poll — not a real error.
1474    fn run_periodic_split_packet(
1475        &self,
1476        endpoint: ControlEndpoint,
1477        packet: &Transaction,
1478        timer: &Timer,
1479    ) -> Result<usize, TransferError> {
1480        let requested = packet.transfer_size as usize;
1481
1482        // Start-split, scheduled for the next microframe (skipping
1483        // microframe 6, as the reference scheduler does).
1484        let mut next_frame = (self.current_microframe() + 1) & 7;
1485        if next_frame == 6 {
1486            next_frame = 7;
1487        }
1488        self.wait_for_microframe(next_frame, timer);
1489        self.start_channel(endpoint, packet, false, Some(next_frame & 1 == 1));
1490        let hcint = self.wait_for_halt(timer)?;
1491        // The transaction translator must ACK a start-split it accepted;
1492        // anything else (a real error, or a NAK/NYET) ends the attempt.
1493        if hcint & HCINT_ACK == 0 {
1494            return self.interpret_halt(hcint, requested);
1495        }
1496
1497        // Complete-split: first two microframes on from the start-split,
1498        // then each consecutive microframe. `tries` bounds the NYET
1499        // retries the same way the reference scheduler does (one fewer
1500        // when the start-split landed in microframe 5, whose complete-
1501        // split window is shorter before the frame boundary).
1502        let mut tries: i32 = if next_frame != 5 { 3 } else { 2 };
1503        next_frame = (next_frame + 2) & 7;
1504        loop {
1505            self.wait_for_microframe(next_frame, timer);
1506            self.start_channel(endpoint, packet, true, Some(next_frame & 1 == 1));
1507            let hcint = self.wait_for_halt(timer)?;
1508
1509            // A real error bit, or success, is terminal.
1510            if hcint & (HCINT_STALL | HCINT_TXERR | HCINT_BBERR | HCINT_XFRC) != 0 {
1511                return self.interpret_halt(hcint, requested);
1512            }
1513            // Translator not finished yet — retry in the next microframe
1514            // until the budget is spent.
1515            if hcint & (HCINT_NYET | HCINT_ACK) != 0 {
1516                if tries == 0 {
1517                    return Err(TransferError::Nak);
1518                }
1519                tries -= 1;
1520                next_frame = (next_frame + 1) & 7;
1521                continue;
1522            }
1523            // Device had nothing to send this interval.
1524            if hcint & HCINT_NAK != 0 {
1525                return Err(TransferError::Nak);
1526            }
1527            // No recognized bit set — an unexplained halt.
1528            return self.interpret_halt(hcint, requested);
1529        }
1530    }
1531
1532    /// The current microframe within the 1ms frame (`HFNUM.FRNUM & 7`) —
1533    /// on this high-speed root port `FRNUM` counts 125µs microframes, so
1534    /// the low three bits are the microframe index periodic split
1535    /// scheduling keys off.
1536    fn current_microframe(&self) -> u8 {
1537        (self.regs().hfnum().read().frnum().bits() & 7) as u8
1538    }
1539
1540    /// Busy-waits until [`Self::current_microframe`] reaches `frame`,
1541    /// bounded by a timeout so a frame counter that isn't advancing (the
1542    /// port down, say) can't wedge the caller — the scheduled microframe
1543    /// is at most 7 away (≈1ms), so a 2ms cap is generous while still
1544    /// guaranteeing forward progress.
1545    fn wait_for_microframe(&self, frame: u8, timer: &Timer) {
1546        let start = timer.now_micros();
1547        while self.current_microframe() != frame {
1548            if timer.now_micros() - start > 2_000 {
1549                break;
1550            }
1551        }
1552    }
1553}