Skip to main content

ch32_hal/usbhs/
mod.rs

1//! USBHS device mode peripheral driver
2//! Note that this currently only implements device mode
3//!
4//! Every transfer completes in the interrupt handler: it reads the shared status
5//! (`INT_ST`, `RX_LEN`) and releases `INT_FG` at once -- isochronous transactions ignore
6//! `INT_BUSY` and would overwrite them -- then records the result per endpoint and wakes
7//! the task. Bulk / interrupt endpoints keep flow control by answering NAK until their
8//! task has taken the data (OUT) or loaded the next packet (IN).
9//!
10//! Isochronous endpoints run without a task in the loop:
11//! - OUT: a ring of [`ISO_OUT_SLOTS`] packet buffers. The interrupt points the endpoint's
12//!   DMA at the next free slot after each packet; `read` drains the ring, or
13//!   [`iso_out_take`] in place. A full ring drops the newest packet, and zero-length
14//!   packets are not delivered (arrivals are detected by a marker in the slot).
15//! - IN: a ring of [`ISO_IN_SLOTS`] packets. After each IN transaction the interrupt
16//!   loads the next queued packet, or a zero-length one when none is queued. `write`
17//!   waits for a free slot, so a writer keeps the ring full and stays at most
18//!   [`ISO_IN_SLOTS`] packets ahead; [`iso_in_prime`] queues from an interrupt (e.g. an
19//!   explicit feedback value from the SOF callback), [`iso_in_fill`] in place.
20//! - Both work from the SOF callback, without a task: one packet each way per microframe.
21//! - Each slot is one endpoint buffer from the driver's buffer array, so the array needs
22//!   room for the rings: one buffer for EP0 and each bulk / interrupt endpoint, plus
23//!   [`ISO_OUT_SLOTS`] per isochronous OUT and [`ISO_IN_SLOTS`] per isochronous IN.
24//!
25//! [`set_sof_callback`] runs a function from the interrupt on every SOF (125 us at high
26//! speed).
27//!
28//! An endpoint number can be used for both an IN and an OUT endpoint of the same type.
29//! Isochronous and bulk / interrupt endpoints must use different numbers: a PING to a bulk
30//! OUT whose number is isochronous on the IN side hangs the SIE.
31//!
32//! Not supported: remote wakeup, high-bandwidth isochronous (more than one transaction per
33//! microframe), hardware double buffering, full-speed operation (the block is configured
34//! for high speed).
35
36use core::future::poll_fn;
37use core::marker::PhantomData;
38use core::sync::atomic::{AtomicBool, AtomicU16, AtomicU32, AtomicU8, AtomicUsize, Ordering};
39use core::task::Poll;
40
41use bitmaps::Bitmap;
42use ch32_metapac::usbhs::regs::{EpBufMod, EpConfig, EpType};
43use ch32_metapac::usbhs::vals::{EndpointType as EpKind, EpRxResponse, EpTog, EpTxResponse, SpeedType, UsbToken};
44use control::ControlPipe;
45use embassy_sync::waitqueue::AtomicWaker;
46use embassy_usb_driver::{
47    Direction, EndpointAddress, EndpointAllocError, EndpointInfo, EndpointType, Event, Unsupported,
48};
49use endpoint::Endpoint;
50
51use crate::gpio::{AFType, Speed};
52use crate::interrupt::typelevel::Interrupt;
53use crate::usb::{Dir, EndpointBufferAllocator, EndpointDataBuffer, In, Out};
54use crate::{interrupt, Peri, PeripheralType};
55
56pub mod control;
57mod endpoint;
58
59const MAX_NR_EP: usize = 16;
60const EP_MAX_PACKET_SIZE: u16 = 64;
61
62/// Packet buffers per isochronous OUT endpoint (15 packets can wait for the task).
63pub const ISO_OUT_SLOTS: usize = 16;
64/// Packets queued per isochronous IN endpoint.
65pub const ISO_IN_SLOTS: usize = 2;
66// the ring indices are u8s that wrap and are masked: slot counts are powers of two up to 256
67const _: () = assert!(256 % ISO_OUT_SLOTS == 0 && 256 % ISO_IN_SLOTS == 0);
68
69/// The pattern an armed isochronous OUT slot is filled with (see `iso_out_check`)
70const ISO_OUT_MARK: u32 = 0x5A3C_A5C3;
71/// Isochronous OUT endpoints, a bit each
72static ISO_OUT_EPS: AtomicU16 = AtomicU16::new(0);
73/// Isochronous IN endpoints polled every (micro)frame, a bit each
74static ISO_IN_EVERY: AtomicU16 = AtomicU16::new(0);
75/// Of those, the ones paced by `iso_in_advance` instead of their completions
76static ISO_IN_PACED: AtomicU16 = AtomicU16::new(0);
77/// A paced endpoint's last microframe advanced (`NO_FRAME`: none since enabled)
78static PACED_LAST: [AtomicU16; MAX_NR_EP] = [const { AtomicU16::new(NO_FRAME) }; MAX_NR_EP];
79
80/// The iso IN endpoints the interrupt completes: polled every microframe, not paced.
81fn iso_in_every(d: crate::pac::usbhs::Usbd) -> u16 {
82    in_enabled(d, ISO_IN_EVERY.load(Ordering::Relaxed) & !ISO_IN_PACED.load(Ordering::Relaxed))
83}
84
85/// The endpoints of `mask` (bit n: endpoint n) whose IN direction is enabled.
86fn in_enabled(d: crate::pac::usbhs::Usbd, mask: u16) -> u16 {
87    if mask == 0 {
88        return 0;
89    }
90    // EP_CONFIG bit n: endpoint n's IN enable
91    mask & d.ep_config().read().0 as u16
92}
93
94/// The endpoints of `mask` (bit n: endpoint n) whose OUT direction is enabled.
95fn out_enabled(d: crate::pac::usbhs::Usbd, mask: u16) -> u16 {
96    if mask == 0 {
97        return 0;
98    }
99    // EP_CONFIG bits 16..: endpoint n's OUT enable
100    mask & (d.ep_config().read().0 >> 16) as u16
101}
102
103/// The isochronous IN response: "data ready" (TinyUSB `USBHS_EP_T_RES_NYET`).
104const TX_RES_ISO: EpTxResponse = EpTxResponse::_RESERVED_1;
105
106static BUS_WAKER: AtomicWaker = AtomicWaker::new();
107
108/// Per endpoint and direction, shared between the interrupt and the endpoint's task.
109pub(crate) struct EpState {
110    pub(crate) waker: AtomicWaker,
111    /// bulk / interrupt / control: OUT -- a packet of `len` bytes is in the buffer; IN --
112    /// the loaded packet went out
113    pub(crate) ready: AtomicBool,
114    pub(crate) len: AtomicU16,
115    /// bulk / interrupt: OUT -- a read is waiting (the endpoint answers ACK); IN -- a packet
116    /// is loaded
117    pub(crate) armed: AtomicBool,
118    pub(crate) iso: AtomicBool,
119    // isochronous ring: slot i at base + (i % slots) * stride; [tail, head) hold packets
120    pub(crate) base: AtomicU32,
121    pub(crate) stride: AtomicU16,
122    pub(crate) slots: AtomicU8,
123    pub(crate) head: AtomicU8,
124    pub(crate) tail: AtomicU8,
125    /// IN: slot `tail` is loaded in the endpoint (else a zero-length packet is)
126    pub(crate) loaded: AtomicBool,
127    pub(crate) lens: [AtomicU16; ISO_OUT_SLOTS],
128    /// OUT: packets dropped on a full ring
129    pub(crate) overruns: AtomicU32,
130    /// IN: the frame number of the last iso completion (`NO_FRAME`: none)
131    pub(crate) last_frame: AtomicU16,
132    /// isochronous OUT: the packet size the slots are marked over
133    pub(crate) max_len: AtomicU16,
134    /// isochronous OUT: the shortest packet since enabled (marks below it get overwritten)
135    pub(crate) min_len: AtomicU16,
136    /// isochronous OUT: the armed slot's address
137    pub(crate) armed_slot: AtomicU32,
138    /// bulk / interrupt: R_TOG / T_TOG after the last packet taken / sent (DATA1: true)
139    pub(crate) tog: AtomicBool,
140}
141
142impl EpState {
143    #[allow(clippy::declare_interior_mutable_const)]
144    const NEW: Self = Self {
145        waker: AtomicWaker::new(),
146        ready: AtomicBool::new(false),
147        len: AtomicU16::new(0),
148        armed: AtomicBool::new(false),
149        iso: AtomicBool::new(false),
150        base: AtomicU32::new(0),
151        stride: AtomicU16::new(0),
152        slots: AtomicU8::new(1),
153        head: AtomicU8::new(0),
154        tail: AtomicU8::new(0),
155        loaded: AtomicBool::new(false),
156        lens: [const { AtomicU16::new(0) }; ISO_OUT_SLOTS],
157        overruns: AtomicU32::new(0),
158        last_frame: AtomicU16::new(NO_FRAME),
159        max_len: AtomicU16::new(0),
160        min_len: AtomicU16::new(0),
161        armed_slot: AtomicU32::new(0),
162        tog: AtomicBool::new(false),
163    };
164
165    fn reset(&self) {
166        self.last_frame.store(NO_FRAME, Ordering::Relaxed);
167        self.ready.store(false, Ordering::Relaxed);
168        self.armed.store(false, Ordering::Relaxed);
169        self.head.store(0, Ordering::Relaxed);
170        self.tail.store(0, Ordering::Relaxed);
171        self.loaded.store(false, Ordering::Relaxed);
172        self.tog.store(false, Ordering::Relaxed);
173    }
174
175    pub(crate) fn count(&self) -> u8 {
176        self.head
177            .load(Ordering::Acquire)
178            .wrapping_sub(self.tail.load(Ordering::Acquire))
179    }
180
181    pub(crate) fn slot_addr(&self, i: u8) -> u32 {
182        let n = self.slots.load(Ordering::Relaxed);
183        self.base.load(Ordering::Relaxed) + (i & (n - 1)) as u32 * self.stride.load(Ordering::Relaxed) as u32
184    }
185}
186
187pub(crate) static OUT_STATE: [EpState; MAX_NR_EP] = [EpState::NEW; MAX_NR_EP];
188pub(crate) static IN_STATE: [EpState; MAX_NR_EP] = [EpState::NEW; MAX_NR_EP];
189
190/// The setup packet, copied out of the EP0 buffer by the interrupt.
191static SETUP: [AtomicU32; 2] = [AtomicU32::new(0), AtomicU32::new(0)];
192static SETUP_READY: AtomicBool = AtomicBool::new(false);
193/// EP0's buffer: the DMA address registers read back only their low 16 bits.
194static EP0_BUF: AtomicU32 = AtomicU32::new(0);
195
196/// The peripheral's base address, for the free functions (0 until a driver exists).
197static REGS: AtomicUsize = AtomicUsize::new(0);
198static SOF_CALLBACK: AtomicUsize = AtomicUsize::new(0);
199/// The frame number of the last SOF handled
200static SOF_FRAME: AtomicU16 = AtomicU16::new(NO_FRAME);
201/// Polls of MIS_ST to wait for an iso OUT to finish: longer than a 1024-byte packet
202const SIE_WAIT: u32 = 2000;
203
204/// The frame number register: frame (bits 10:0) and microframe (bits 15:13); bits 12:11
205/// are always 0, so this is never a frame number.
206const NO_FRAME: u16 = 0x1800;
207const MICROFRAME_MASK: u16 = (1 << 14) - 1;
208
209/// A frame number as a microframe count
210fn microframe_index(frame: u16) -> u16 {
211    (frame & 0x7FF) << 3 | frame >> 13
212}
213
214fn frame_of_index(i: u16) -> u16 {
215    (i >> 3) & 0x7FF | (i & 7) << 13
216}
217
218fn dregs() -> Option<crate::pac::usbhs::Usbd> {
219    match REGS.load(Ordering::Acquire) {
220        0 => None,
221        a => Some(unsafe { crate::pac::usbhs::Usbd::from_ptr(a as _) }),
222    }
223}
224
225/// Call `f` from the USB interrupt on every SOF (every 125 us microframe at high speed).
226/// Keep it short: it delays every other USB completion.
227pub fn set_sof_callback(f: fn()) {
228    SOF_CALLBACK.store(f as usize, Ordering::Release);
229    if let Some(d) = dregs() {
230        critical_section::with(|_| d.int_en().modify(|w| w.set_sof_act(true)));
231    }
232}
233
234/// The current microframe number: 8 per frame, wrapping at 2^14. Read from the frame
235/// number register, so it also counts microframes whose SOF interrupt was missed.
236pub fn microframe() -> u16 {
237    dregs().map_or(0, |d| microframe_index(d.frame_no().read().frame_no()))
238}
239
240/// Whether the host enabled endpoint `ep` in `direction` (for an isochronous one: selected
241/// its interface's streaming alternate setting).
242pub fn endpoint_enabled(ep: usize, direction: Direction) -> bool {
243    let Some(d) = dregs() else { return false };
244    if ep == 0 || ep >= MAX_NR_EP {
245        return false;
246    }
247    match direction {
248        Direction::Out => d.ep_config().read().r_en(ep - 1),
249        Direction::In => d.ep_config().read().t_en(ep - 1),
250    }
251}
252
253/// Take the oldest packet waiting on isochronous OUT endpoint `ep`, in place: `f` reads
254/// it, then its slot goes back to the ring. `None`: no packet waiting (or not an
255/// isochronous OUT endpoint). One reader per endpoint; callable from interrupts.
256pub fn iso_out_take<R>(ep: usize, f: impl FnOnce(&[u8]) -> R) -> Option<R> {
257    if ep == 0 || ep >= MAX_NR_EP {
258        return None;
259    }
260    let s = &OUT_STATE[ep];
261    if !s.iso.load(Ordering::Relaxed) || s.count() == 0 {
262        return None;
263    }
264    let tail = s.tail.load(Ordering::Relaxed);
265    let n = s.slots.load(Ordering::Relaxed);
266    let len = s.lens[(tail & (n - 1)) as usize].load(Ordering::Relaxed) as usize;
267    // SAFETY: a slot in [tail, head): the DMA is done with it until tail moves
268    let r = f(unsafe { core::slice::from_raw_parts(s.slot_addr(tail) as *const u8, len) });
269    s.tail.store(tail.wrapping_add(1), Ordering::Release);
270    Some(r)
271}
272
273/// Packets dropped because isochronous OUT endpoint `ep`'s ring was full (the newest packet
274/// is dropped), since the driver was created. 0 for an endpoint that is not isochronous OUT.
275pub fn iso_out_overruns(ep: usize) -> u32 {
276    if ep == 0 || ep >= MAX_NR_EP || !OUT_STATE[ep].iso.load(Ordering::Relaxed) {
277        return 0;
278    }
279    OUT_STATE[ep].overruns.load(Ordering::Relaxed)
280}
281
282/// Wake `waker` when isochronous IN endpoint `ep` sends a packet (a slot frees up), to
283/// refill it from a task. One waiter per endpoint, shared with the endpoint's `write`.
284pub fn iso_in_register_waker(ep: usize, waker: &core::task::Waker) {
285    if ep != 0 && ep < MAX_NR_EP {
286        IN_STATE[ep].waker.register(waker);
287    }
288}
289
290/// Packets queued on isochronous IN endpoint `ep` and not yet taken by the host
291/// (including the one loaded in the endpoint).
292pub fn iso_in_pending(ep: usize) -> u8 {
293    if ep == 0 || ep >= MAX_NR_EP {
294        return 0;
295    }
296    IN_STATE[ep].count()
297}
298
299/// Pace isochronous IN endpoint `ep` (polled every microframe) from outside: the interrupt
300/// no longer moves it on after an IN; `iso_in_advance`, called once in each microframe after
301/// the host's IN to it and well before the next, does.
302///
303/// The USBHS keeps one status for all endpoints, and an iso IN raises its flag a little
304/// before the SIE is free, so the interrupt mostly can't tell such an IN went out until the
305/// next SOF -- and a host polls an iso IN early in the microframe (~3 us after the SOF on
306/// Linux), so loading the next packet there races it: now and then the loaded packet goes
307/// out again. A timer some way into the microframe has tens of us on either side.
308pub fn iso_in_set_paced(ep: usize, paced: bool) {
309    if ep == 0 || ep >= MAX_NR_EP {
310        return;
311    }
312    critical_section::with(|_| {
313        let m = ISO_IN_PACED.load(Ordering::Relaxed);
314        ISO_IN_PACED.store(if paced { m | 1 << ep } else { m & !(1 << ep) }, Ordering::Relaxed);
315        PACED_LAST[ep].store(NO_FRAME, Ordering::Relaxed);
316    });
317}
318
319/// A paced iso IN endpoint (`iso_in_set_paced`): the host took a packet in each microframe
320/// since the last call; they move on and the next queued packet is loaded. Call it at the
321/// USB interrupt's priority (it shares the endpoint's state with it), some way into the
322/// microframe: after the host's IN, before the next microframe's.
323pub fn iso_in_advance(ep: usize) {
324    let Some(d) = dregs() else { return };
325    if ep == 0 || ep >= MAX_NR_EP || ISO_IN_PACED.load(Ordering::Relaxed) & 1 << ep == 0 {
326        return;
327    }
328    if in_enabled(d, 1 << ep) == 0 {
329        PACED_LAST[ep].store(NO_FRAME, Ordering::Relaxed);
330        return;
331    }
332    let now = microframe_index(d.frame_no().read().frame_no());
333    let last = PACED_LAST[ep].load(Ordering::Relaxed);
334    let n = if last == NO_FRAME { 1 } else { now.wrapping_sub(microframe_index(last)) & MICROFRAME_MASK };
335    // more than the ring holds: the rest went out empty anyway
336    for _ in 0..n.min(ISO_IN_SLOTS as u16 + 1) {
337        iso_in_complete(d, ep);
338    }
339    PACED_LAST[ep].store(frame_of_index(now), Ordering::Relaxed);
340}
341
342/// Queue one packet on isochronous IN endpoint `ep`; callable from interrupts. `false`:
343/// not queued (ring full, endpoint not enabled or not isochronous, packet too long).
344pub fn iso_in_prime(ep: usize, data: &[u8]) -> bool {
345    let Some(d) = dregs() else { return false };
346    if ep == 0 || ep >= MAX_NR_EP || !d.ep_config().read().t_en(ep - 1) {
347        return false;
348    }
349    iso_in_enqueue(ep, data)
350}
351
352/// Build one packet on isochronous IN endpoint `ep` in place and queue it: `f` fills the
353/// next free slot (one endpoint buffer; keep to the endpoint's max packet size) and
354/// returns the packet's length. `false`: not queued and `f` not run (ring full, endpoint
355/// not enabled or not isochronous). Callable from interrupts.
356pub fn iso_in_fill(ep: usize, f: impl FnOnce(&mut [u8]) -> usize) -> bool {
357    let Some(d) = dregs() else { return false };
358    if ep == 0 || ep >= MAX_NR_EP || !d.ep_config().read().t_en(ep - 1) {
359        return false;
360    }
361    iso_in_enqueue_with(ep, f)
362}
363
364/// Copy `data` into the next free slot and publish it (see [`iso_in_enqueue_with`]).
365pub(crate) fn iso_in_enqueue(ep: usize, data: &[u8]) -> bool {
366    if data.len() > IN_STATE[ep].stride.load(Ordering::Relaxed) as usize {
367        return false;
368    }
369    iso_in_enqueue_with(ep, |slot| {
370        slot[..data.len()].copy_from_slice(data);
371        data.len()
372    })
373}
374
375/// `f` fills the next free slot, then it's published. The slot at `head` is never touched
376/// by the interrupt, so `f` runs without a critical section. One producer per endpoint.
377///
378/// The producer never loads the endpoint itself: the interrupt loads the next packet after
379/// every IN, the zero-length one included. Loading while the endpoint answers an IN with
380/// the zero-length packet (the ring ran empty) can't be told apart from the packet going
381/// out, and that packet would be lost; this way it goes out one microframe later.
382fn iso_in_enqueue_with(ep: usize, f: impl FnOnce(&mut [u8]) -> usize) -> bool {
383    let s = &IN_STATE[ep];
384    let n = s.slots.load(Ordering::Relaxed);
385    if !s.iso.load(Ordering::Relaxed) || s.count() >= n {
386        return false;
387    }
388    let head = s.head.load(Ordering::Relaxed);
389    let stride = s.stride.load(Ordering::Relaxed) as usize;
390    // SAFETY: the slot is inside the ring's buffers and not in [tail, head)
391    let len = f(unsafe { core::slice::from_raw_parts_mut(s.slot_addr(head) as *mut u8, stride) }).min(stride);
392    s.lens[(head & (n - 1)) as usize].store(len as u16, Ordering::Relaxed);
393    s.head.store(head.wrapping_add(1), Ordering::Release);
394    true
395}
396
397/// Record an iso IN completion in microframe `frame` (interrupt only); `false` if one is
398/// recorded in it already.
399fn first_in_frame(s: &EpState, frame: u16) -> bool {
400    let first = s.last_frame.load(Ordering::Relaxed) != frame;
401    s.last_frame.store(frame, Ordering::Relaxed);
402    first
403}
404
405/// An iso IN completion: the loaded packet went out, load the next. Interrupt only.
406fn iso_in_complete(d: crate::pac::usbhs::Usbd, ep: usize) {
407    let s = &IN_STATE[ep];
408    if s.loaded.load(Ordering::Relaxed) {
409        s.tail
410            .store(s.tail.load(Ordering::Relaxed).wrapping_add(1), Ordering::Release);
411    }
412    iso_in_load(d, ep);
413    s.waker.wake();
414}
415
416/// Bulk / interrupt / control: NAK before releasing the flag, so the next transaction
417/// waits for the task.
418fn nak_non_iso(d: crate::pac::usbhs::Usbd, st: ch32_metapac::usbhs::regs::IntSt) {
419    let ep = st.endp() as usize;
420    match st.token() {
421        // bulk / interrupt: before knowing whether a packet went through (`toggled`), so the
422        // next can't land on it
423        UsbToken::OUT if (ep == 0 && st.tog_ok()) || (ep != 0 && !OUT_STATE[ep].iso.load(Ordering::Relaxed)) => {
424            d.ep_rx_ctrl(ep).modify(|w| w.set_mask_uep_r_res(EpRxResponse::NAK))
425        }
426        UsbToken::IN if !IN_STATE[ep].iso.load(Ordering::Relaxed) => {
427            d.ep_tx_ctrl(ep).modify(|w| w.set_mask_uep_t_res(EpTxResponse::NAK))
428        }
429        _ => {}
430    }
431}
432
433/// A packet went through a bulk / interrupt endpoint (not EP0): the SIE flips its toggle on
434/// each one it accepts (OUT) or the host ACKs (IN). INT_ST's TOG_OK can't tell: the flag comes
435/// a little before the SIE goes free, and an entry that early reads it before it's final.
436/// Waits for the SIE. The entry NAKed the endpoint; a read / write still waiting gets it back.
437fn toggled(r: crate::pac::usbhs::Usb, d: crate::pac::usbhs::Usbd, ep: usize, dir: Direction) -> bool {
438    let mut n = 0;
439    while !r.mis_st().read().sie_free() && n < SIE_WAIT {
440        n += 1;
441    }
442    let (s, tog) = match dir {
443        Direction::Out => (&OUT_STATE[ep], d.ep_rx_ctrl(ep).read().mask_uep_r_tog()),
444        Direction::In => (&IN_STATE[ep], d.ep_tx_ctrl(ep).read().mask_uep_t_tog()),
445    };
446    let tog = tog == EpTog::DATA1;
447    if s.tog.load(Ordering::Relaxed) == tog {
448        if s.armed.load(Ordering::Relaxed) {
449            match dir {
450                Direction::Out => d.ep_rx_ctrl(ep).modify(|w| w.set_mask_uep_r_res(EpRxResponse::ACK)),
451                Direction::In => d.ep_tx_ctrl(ep).modify(|w| w.set_mask_uep_t_res(EpTxResponse::ACK)),
452            }
453        }
454        return false;
455    }
456    s.tog.store(tog, Ordering::Relaxed);
457    s.armed.store(false, Ordering::Relaxed);
458    true
459}
460
461/// Isochronous OUT arrivals, by the slot's first word: the endpoint's slot gets `ISO_OUT_MARK`
462/// when it's armed, so a packet in it shows whatever INT_ST shows -- with the flag one bit, a
463/// late entry may stand for an OUT and show the transaction after it. (a packet that starts
464/// with the mark is lost; zero-length ones aren't seen.) Interrupt only.
465fn iso_out_check(r: crate::pac::usbhs::Usb, d: crate::pac::usbhs::Usbd, entry: Option<(usize, u16)>) {
466    // a disabled endpoint's slot still holds its last packet: it is not an arrival
467    let mut eps = out_enabled(d, ISO_OUT_EPS.load(Ordering::Relaxed));
468    while eps != 0 {
469        let ep = eps.trailing_zeros() as usize;
470        eps &= eps - 1;
471        let s = &OUT_STATE[ep];
472        let slot = s.armed_slot.load(Ordering::Relaxed);
473        // SAFETY: the armed slot, a buffer of this endpoint
474        if unsafe { core::ptr::read_volatile(slot as *const u32) } == ISO_OUT_MARK {
475            continue;
476        }
477        let max = s.max_len.load(Ordering::Relaxed) as usize;
478        let len = match entry {
479            // RX_LEN as this packet's entry read it (releasing the flag clears it)
480            Some((e, len)) if e == ep => len,
481            _ => {
482                // read after the slot: while its OUT is the last token, the packet may still be
483                // arriving (or its DMA finishing), and its own entry follows
484                let st = r.int_st().read();
485                if st.token() == UsbToken::OUT && st.endp() as usize == ep {
486                    continue;
487                }
488                marked_len(slot, max) as u16
489            }
490        };
491        if len != 0 && len < s.min_len.load(Ordering::Relaxed) {
492            s.min_len.store(len, Ordering::Relaxed);
493        }
494        let n = s.slots.load(Ordering::Relaxed);
495        let mut head = s.head.load(Ordering::Relaxed);
496        // what the slot to arm holds (marks past it are still there)
497        let mut dirty = len as usize;
498        if head.wrapping_sub(s.tail.load(Ordering::Acquire)) < n - 1 {
499            s.lens[(head & (n - 1)) as usize].store(len, Ordering::Relaxed);
500            head = head.wrapping_add(1);
501            s.head.store(head, Ordering::Release);
502            dirty = s.lens[(head & (n - 1)) as usize].load(Ordering::Relaxed) as usize;
503        } else {
504            // full: the next packet overwrites this slot
505            s.overruns
506                .store(s.overruns.load(Ordering::Relaxed).wrapping_add(1), Ordering::Relaxed);
507        }
508        let from = s.min_len.load(Ordering::Relaxed) as usize;
509        iso_out_arm(d, ep, s.slot_addr(head), from, dirty.min(max));
510        s.waker.wake();
511    }
512}
513
514/// The length of a packet in a slot filled with `ISO_OUT_MARK` before it: up to its last
515/// byte that differs from the pattern.
516fn marked_len(slot: u32, max: usize) -> usize {
517    let mark = ISO_OUT_MARK.to_le_bytes();
518    let words = slot as *const u32;
519    // SAFETY: the slot holds `max` bytes, rounded up to words when marked
520    let word = |i: usize| unsafe { core::ptr::read_volatile(words.add(i)) };
521    // the first word of the marks after the packet (a packet word that matches the mark can
522    // throw this off: 2^-32), then the last byte before them that differs
523    let (mut lo, mut hi) = (0, max.div_ceil(4));
524    while lo < hi {
525        let mid = (lo + hi) / 2;
526        if word(mid) == ISO_OUT_MARK {
527            hi = mid;
528        } else {
529            lo = mid + 1;
530        }
531    }
532    let w = lo;
533    if w == 0 {
534        return 0;
535    }
536    let last = word(w - 1).to_le_bytes();
537    let mut b = 4;
538    while last[b - 1] == mark[b - 1] {
539        b -= 1;
540    }
541    ((w - 1) * 4 + b).min(max)
542}
543
544/// Point isochronous OUT endpoint `ep` at the slot at `addr`, marked empty: its first word
545/// and its bytes `from..dirty` are marked again -- past `dirty` they still are, and below
546/// `from` (no packet is that short) the next packet overwrites them.
547fn iso_out_arm(d: crate::pac::usbhs::Usbd, ep: usize, addr: u32, from: usize, dirty: usize) {
548    let words = addr as *mut u32;
549    // SAFETY: a slot of this endpoint, not the reader's, word aligned
550    unsafe { core::ptr::write_volatile(words, ISO_OUT_MARK) };
551    for i in (from / 4).max(1)..dirty.div_ceil(4) {
552        unsafe { core::ptr::write_volatile(words.add(i), ISO_OUT_MARK) };
553    }
554    OUT_STATE[ep].armed_slot.store(addr, Ordering::Relaxed);
555    d.ep_rx_dma(ep - 1).write_value(addr);
556}
557
558/// A new microframe's SOF (once each, possibly from a later entry). An iso IN endpoint
559/// polled every microframe completes in each: one that didn't in the last went out unseen,
560/// its completion merged into another entry's flag (the host repeats a packet otherwise).
561/// Not while an IN to that endpoint is on the bus: that may be its packet going out late.
562/// An IN to another endpoint doesn't hold it back: a host polling a bulk IN (NAKed) at the
563/// SOF would otherwise leave the packet loaded, and it goes out twice.
564fn on_sof(r: crate::pac::usbhs::Usb, d: crate::pac::usbhs::Usbd, frame: u16) {
565    SOF_FRAME.store(frame, Ordering::Relaxed);
566    let prev = microframe_index(frame).wrapping_sub(1) & MICROFRAME_MASK;
567    let mut eps = iso_in_every(d);
568    while eps != 0 {
569        let ep = eps.trailing_zeros() as usize;
570        eps &= eps - 1;
571        let s = &IN_STATE[ep];
572        let last = s.last_frame.load(Ordering::Relaxed);
573        if last != NO_FRAME && microframe_index(last) == prev {
574            continue;
575        }
576        if !r.mis_st().read().sie_free() {
577            let st = r.int_st().read();
578            if st.token() == UsbToken::IN && st.endp() as usize == ep {
579                continue;
580            }
581        }
582        s.last_frame.store(frame_of_index(prev), Ordering::Relaxed);
583        iso_in_complete(d, ep);
584    }
585    let f = SOF_CALLBACK.load(Ordering::Acquire);
586    if f != 0 {
587        // SAFETY: stored from a `fn()` in `set_sof_callback`
588        let f: fn() = unsafe { core::mem::transmute(f) };
589        f();
590    }
591}
592
593/// Load slot `tail` into the endpoint, or a zero-length packet if the ring is empty.
594/// Interrupt only (see `iso_in_enqueue_with`).
595fn iso_in_load(d: crate::pac::usbhs::Usbd, ep: usize) {
596    let s = &IN_STATE[ep];
597    if s.count() > 0 {
598        let tail = s.tail.load(Ordering::Relaxed);
599        let n = s.slots.load(Ordering::Relaxed);
600        d.ep_tx_dma(ep - 1).write_value(s.slot_addr(tail));
601        d.ep_t_len(ep)
602            .write(|w| w.set_len(s.lens[(tail & (n - 1)) as usize].load(Ordering::Relaxed)));
603        s.loaded.store(true, Ordering::Relaxed);
604    } else {
605        d.ep_t_len(ep).write(|w| w.set_len(0));
606        s.loaded.store(false, Ordering::Relaxed);
607    }
608}
609
610/// The setup packet, if one arrived since the last call.
611pub(crate) fn take_setup() -> Option<[u8; 8]> {
612    critical_section::with(|_| {
613        if SETUP_READY.load(Ordering::Acquire) {
614            SETUP_READY.store(false, Ordering::Release);
615            let a = SETUP[0].load(Ordering::Relaxed).to_le_bytes();
616            let b = SETUP[1].load(Ordering::Relaxed).to_le_bytes();
617            Some([a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3]])
618        } else {
619            None
620        }
621    })
622}
623
624/// A setup packet arrived and ends whatever control transfer EP0 was in.
625pub(crate) fn setup_pending() -> bool {
626    SETUP_READY.load(Ordering::Acquire)
627}
628
629pub struct InterruptHandler<T: Instance> {
630    _phantom: PhantomData<T>,
631}
632
633impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
634    unsafe fn on_interrupt() {
635        let r = T::regs();
636        let d = T::dregs();
637        let flag = r.int_fg().read();
638
639        if flag.bus_rst() {
640            //mask the interrupt and let the main thread handle it
641            r.int_en().modify(|w| w.set_bus_rst(false));
642            BUS_WAKER.wake();
643        };
644        if flag.suspend() {
645            //mask the interrupt and let the main thread handle it
646            r.int_en().modify(|w| w.set_suspend(false));
647            BUS_WAKER.wake();
648        };
649        if flag.fifo_ov() {
650            r.int_fg().write(|w| w.set_fifo_ov(true));
651        }
652        if flag.hst_sof() {
653            r.int_fg().write(|w| w.set_hst_sof(true));
654        }
655
656        if flag.transfer() {
657            // INT_ST shows a token as soon as it arrives, not when its transaction completes:
658            // an entry that runs late (the next transaction is already on the bus) reads a
659            // token that hasn't completed
660            let mut busy = !r.mis_st().read().sie_free();
661            let mut st = r.int_st().read();
662            let mut len = r.rx_len().read();
663            if !busy || (st.token() != UsbToken::SOF && st.endp() != 0) {
664                nak_non_iso(d, st);
665            }
666            // release early: INT_ST / RX_LEN are read
667            r.int_fg().write(|w| w.set_transfer(true));
668            // an iso OUT on the bus: this entry is its own (raised a little before the SIE goes
669            // free) or a late one. take it here once it's in -- left to a later entry, the next
670            // microframe's OUT may land on it first. its completion after the release sets
671            // RX_LEN (and the flag again: that entry finds it taken)
672            let mut out_late = false;
673            let mut rx_len_ok = true;
674            if busy && st.token() == UsbToken::OUT && OUT_STATE[st.endp() as usize].iso.load(Ordering::Relaxed) {
675                let mut n = 0;
676                while !r.mis_st().read().sie_free() && n < SIE_WAIT {
677                    n += 1;
678                }
679                let now = r.int_st().read();
680                len = r.rx_len().read();
681                // 0: it completed before the release, which cleared RX_LEN; another token:
682                // the next transaction already. the slot shows the length
683                if len == 0 || now.token() != UsbToken::OUT || now.endp() != st.endp() {
684                    rx_len_ok = false;
685                }
686                busy = false;
687                out_late = true;
688            } else if busy
689                && st.endp() != 0
690                && match st.token() {
691                    UsbToken::OUT => true, // iso: above
692                    UsbToken::IN => !IN_STATE[st.endp() as usize].iso.load(Ordering::Relaxed),
693                    _ => false,
694                }
695            {
696                // bulk / interrupt raise their flag before the SIE goes free too: this may be the
697                // shown transaction's own entry (`toggled` tells). an OUT completing after the
698                // release sets RX_LEN again
699                let mut n = 0;
700                while !r.mis_st().read().sie_free() && n < SIE_WAIT {
701                    n += 1;
702                }
703                busy = false;
704                let now = r.rx_len().read();
705                if now != 0 {
706                    len = now;
707                }
708            } else if busy && r.mis_st().read().sie_free() && !r.int_fg().read().transfer() {
709                // it completed before the release, which took its flag (and RX_LEN): handle it
710                // here
711                busy = false;
712                st = r.int_st().read();
713                rx_len_ok = false;
714                nak_non_iso(d, st);
715            }
716            let ep = st.endp() as usize;
717            let token = st.token();
718            let iso = match token {
719                UsbToken::OUT => OUT_STATE[ep].iso.load(Ordering::Relaxed),
720                UsbToken::IN => IN_STATE[ep].iso.load(Ordering::Relaxed),
721                _ => true,
722            };
723            let frame = d.frame_no().read().frame_no();
724            // an iso IN raises its flag a little before the SIE goes free (its only entry):
725            // with this microframe's SOF handled, the entry is that IN's own
726            if busy && iso && token == UsbToken::IN && SOF_FRAME.load(Ordering::Relaxed) == frame {
727                busy = false;
728            }
729            // the flag is one bit: a late entry also stands for what completed before the
730            // token it shows. the SOF if this microframe's wasn't handled
731            if token != UsbToken::SOF && SOF_FRAME.load(Ordering::Relaxed) != frame {
732                on_sof(r, d, frame);
733            }
734
735            if out_late {
736                // what raised a late entry completed before the OUT: the iso INs polled every
737                // microframe that haven't completed in it (hosts poll them first; the SOF
738                // catches up the ones polled after)
739                let mut eps = iso_in_every(d);
740                while eps != 0 {
741                    let i = eps.trailing_zeros() as usize;
742                    eps &= eps - 1;
743                    if first_in_frame(&IN_STATE[i], frame) {
744                        iso_in_complete(d, i);
745                    }
746                }
747            }
748            if !busy {
749                match token {
750                    UsbToken::SOF => {
751                        if SOF_FRAME.load(Ordering::Relaxed) != frame {
752                            on_sof(r, d, frame);
753                        }
754                    }
755                    // iso OUT: see iso_out_check
756                    UsbToken::OUT if iso => {}
757                    // no new packet (a retransmit after a lost ACK, or one NAKed): the endpoint
758                    // stays as it is
759                    UsbToken::OUT if ep != 0 && !toggled(r, d, ep, Direction::Out) => {}
760                    UsbToken::OUT if ep == 0 && !st.tog_ok() => {}
761                    UsbToken::OUT => {
762                        let s = &OUT_STATE[ep];
763                        if ep == 0 {
764                            d.ep_rx_ctrl(0)
765                                .modify(|w| w.set_mask_uep_r_tog(flip(w.mask_uep_r_tog())));
766                        }
767                        s.len.store(len, Ordering::Relaxed);
768                        s.armed.store(false, Ordering::Relaxed);
769                        s.ready.store(true, Ordering::Release);
770                        s.waker.wake();
771                    }
772                    // one iso IN per microframe (no high bandwidth): a second completion in
773                    // one is a stale INT_ST, already counted
774                    // paced: `iso_in_advance` moves it on
775                    UsbToken::IN if iso && ISO_IN_PACED.load(Ordering::Relaxed) & 1 << ep != 0 => {}
776                    UsbToken::IN if iso && !first_in_frame(&IN_STATE[ep], frame) => {}
777                    UsbToken::IN if iso => iso_in_complete(d, ep),
778                    UsbToken::IN if ep != 0 && !toggled(r, d, ep, Direction::In) => {}
779                    UsbToken::IN => {
780                        let s = &IN_STATE[ep];
781                        if ep == 0 {
782                            d.ep_tx_ctrl(0)
783                                .modify(|w| w.set_mask_uep_t_tog(flip(w.mask_uep_t_tog())));
784                            s.armed.store(false, Ordering::Relaxed);
785                        }
786                        s.ready.store(true, Ordering::Release);
787                        s.waker.wake();
788                    }
789                    UsbToken::SETUP => {}
790                }
791            }
792            let entry = (!busy && rx_len_ok && token == UsbToken::OUT && iso && st.tog_ok()).then_some((ep, len));
793            // an OUT completes too early in its microframe to merge into the next SOF's entry,
794            // and a busy entry takes its own OUT above
795            if token != UsbToken::SOF {
796                iso_out_check(r, d, entry);
797            }
798            if ep == 0 {
799                ep0_moved_on(d, token);
800            }
801        }
802
803        if flag.setup_act() {
804            // a new control transfer: whatever EP0 was doing is over
805            d.ep_rx_ctrl(0).write(|w| w.set_mask_uep_r_res(EpRxResponse::NAK));
806            d.ep_tx_ctrl(0).write(|w| w.set_mask_uep_t_res(EpTxResponse::NAK));
807            let buf = EP0_BUF.load(Ordering::Relaxed) as *const u32;
808            SETUP[0].store(core::ptr::read_volatile(buf), Ordering::Relaxed);
809            SETUP[1].store(core::ptr::read_volatile(buf.add(1)), Ordering::Relaxed);
810            for s in [&OUT_STATE[0], &IN_STATE[0]] {
811                s.ready.store(false, Ordering::Relaxed);
812                s.armed.store(false, Ordering::Relaxed);
813            }
814            SETUP_READY.store(true, Ordering::Release);
815            r.int_fg().write(|w| w.set_setup_act(true));
816            OUT_STATE[0].waker.wake();
817            IN_STATE[0].waker.wake();
818        }
819    }
820}
821
822/// An EP0 stage whose completion no entry saw: the flag is one bit and INT_ST shows the
823/// latest token, NAKed ones too, so a host polling a bulk IN right after an EP0 transaction
824/// hides it (EP0 has no auto toggle to tell). The host's token for the other direction says
825/// it went through: the status stage after the last data packet. (one hidden before the
826/// last gets resent with the same toggle, which the host drops, and completes then.)
827fn ep0_moved_on(d: crate::pac::usbhs::Usbd, token: UsbToken) {
828    match token {
829        UsbToken::OUT if IN_STATE[0].armed.load(Ordering::Relaxed) => {
830            d.ep_tx_ctrl(0).modify(|w| {
831                w.set_mask_uep_t_res(EpTxResponse::NAK);
832                w.set_mask_uep_t_tog(flip(w.mask_uep_t_tog()));
833            });
834            let s = &IN_STATE[0];
835            s.armed.store(false, Ordering::Relaxed);
836            s.ready.store(true, Ordering::Release);
837            s.waker.wake();
838        }
839        UsbToken::IN if OUT_STATE[0].armed.load(Ordering::Relaxed) => {
840            d.ep_rx_ctrl(0).modify(|w| {
841                w.set_mask_uep_r_res(EpRxResponse::NAK);
842                w.set_mask_uep_r_tog(flip(w.mask_uep_r_tog()));
843            });
844            // `len`: the packet the stage expects (`ControlPipe` sets it)
845            let s = &OUT_STATE[0];
846            s.armed.store(false, Ordering::Relaxed);
847            s.ready.store(true, Ordering::Release);
848            s.waker.wake();
849        }
850        _ => {}
851    }
852}
853
854fn flip(t: EpTog) -> EpTog {
855    match t {
856        EpTog::DATA0 => EpTog::DATA1,
857        _ => EpTog::DATA0,
858    }
859}
860
861pub struct WakeupInterruptHandler<T: Instance> {
862    _phantom: PhantomData<T>,
863}
864
865impl<T: Instance> interrupt::typelevel::Handler<T::WakeupInterrupt> for WakeupInterruptHandler<T> {
866    unsafe fn on_interrupt() {
867        // not used by this driver (resume shows up through the SUSPEND flag)
868        T::WakeupInterrupt::disable();
869    }
870}
871
872pub struct Driver<'d, T: Instance, const NR_EP: usize, const SIZE: usize> {
873    phantom: PhantomData<&'d T>,
874    allocator: EndpointBufferAllocator<'d, NR_EP, SIZE>,
875    allocated_in: Bitmap<MAX_NR_EP>,
876    allocated_out: Bitmap<MAX_NR_EP>,
877    /// endpoint numbers with an isochronous endpoint in either direction
878    iso_nums: Bitmap<MAX_NR_EP>,
879    /// endpoint numbers with a bulk / interrupt endpoint in either direction
880    other_nums: Bitmap<MAX_NR_EP>,
881}
882
883impl<'d, T: Instance, const NR_EP: usize, const SIZE: usize> Driver<'d, T, NR_EP, SIZE> {
884    /// `ep_buffer`: one buffer for EP0 and each bulk / interrupt endpoint, plus the
885    /// isochronous rings ([`ISO_OUT_SLOTS`] / [`ISO_IN_SLOTS`] buffers each).
886    pub fn new(
887        _peri: Peri<'d, T>,
888        _irqs: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>>
889            + interrupt::typelevel::Binding<T::WakeupInterrupt, WakeupInterruptHandler<T>>
890            + 'd,
891        dp: Peri<'d, impl DpPin<T, 0>>,
892        dm: Peri<'d, impl DmPin<T, 0>>,
893        ep_buffer: &'d mut [EndpointDataBuffer<SIZE>; NR_EP],
894    ) -> Self {
895        assert!(ep_buffer.len() > 0);
896
897        dp.set_as_af_output(AFType::OutputPushPull, Speed::High);
898        dm.set_as_af_output(AFType::OutputPushPull, Speed::High);
899
900        T::enable_and_reset();
901
902        let allocator = EndpointBufferAllocator::new(ep_buffer);
903
904        let r = T::regs();
905        let h = T::hregs();
906
907        r.ctrl().write(|w| {
908            w.set_clr_all(true);
909            w.set_reset_sie(true);
910        });
911
912        // Sleep for 10uS from WCH C code
913        crate::internal::delay::block_for_us(10);
914
915        // Following WCH C code.... unclear why clr_all is not also cleared here
916        r.ctrl().modify(|w| w.set_reset_sie(false));
917        h.ctrl().write(|w| w.set_phy_suspendm(true));
918
919        r.ctrl().write(|w| {
920            w.set_int_busy(true);
921            w.set_dma_en(true);
922            // TODO: HS, Configurable?
923            w.set_speed_type(SpeedType::HIGHSPEED);
924        });
925
926        for s in OUT_STATE.iter().chain(IN_STATE.iter()) {
927            s.reset();
928            s.iso.store(false, Ordering::Relaxed);
929        }
930        SETUP_READY.store(false, Ordering::Relaxed);
931        REGS.store(r.as_ptr() as usize, Ordering::Release);
932
933        r.int_en().write(|w| {
934            w.set_dev_nak(false);
935            w.set_fifo_ov(true);
936            w.set_setup_act(true);
937            w.set_suspend(true);
938            w.set_bus_rst(true);
939            w.set_transfer(true);
940            w.set_sof_act(SOF_CALLBACK.load(Ordering::Relaxed) != 0);
941        });
942
943        Self {
944            phantom: PhantomData,
945            allocator,
946            allocated_in: Bitmap::new(),
947            allocated_out: Bitmap::new(),
948            iso_nums: Bitmap::new(),
949            other_nums: Bitmap::new(),
950        }
951    }
952
953    fn alloc_endpoint<D: Dir>(
954        &mut self,
955        ep_type: EndpointType,
956        ep_addr: Option<EndpointAddress>,
957        max_packet_size: u16,
958        interval_ms: u8,
959        dir: Direction,
960    ) -> Result<Endpoint<'d, T, D, SIZE>, EndpointAllocError> {
961        let iso = ep_type == EndpointType::Isochronous;
962        // the other direction's type: a PING to a bulk OUT whose number is iso on the IN side
963        // hangs the SIE (no endpoint answers after it)
964        let taken = if iso { self.other_nums } else { self.iso_nums };
965        let allocated = match dir {
966            Direction::Out => &mut self.allocated_out,
967            Direction::In => &mut self.allocated_in,
968        };
969        let addr = match ep_addr {
970            Some(addr) => {
971                // Use the provided endpoint address
972                if addr.direction() != dir {
973                    return Err(EndpointAllocError);
974                }
975
976                let ep_num = addr.index();
977                if ep_num == 0 || ep_num >= MAX_NR_EP || allocated.get(ep_num) || taken.get(ep_num) {
978                    return Err(EndpointAllocError);
979                }
980
981                allocated.set(ep_num, true);
982                addr
983            }
984            None => {
985                // Find a free endpoint address; endpoint 0 is the control pipe's
986                let ep_num = (1..MAX_NR_EP)
987                    .find(|&i| !allocated.get(i) && !taken.get(i))
988                    .ok_or(EndpointAllocError)?;
989                allocated.set(ep_num, true);
990                EndpointAddress::from_parts(ep_num, dir)
991            }
992        };
993
994        if iso {
995            self.iso_nums.set(addr.index(), true);
996        } else {
997            self.other_nums.set(addr.index(), true);
998        }
999        let slots = match (iso, dir) {
1000            (false, _) => 1,
1001            (true, Direction::Out) => ISO_OUT_SLOTS,
1002            (true, Direction::In) => ISO_IN_SLOTS,
1003        };
1004        // the ring's slots are consecutive buffers of the array
1005        let data = self.allocator.alloc_endpoint(max_packet_size)?;
1006        for _ in 1..slots {
1007            self.allocator.alloc_endpoint(max_packet_size)?;
1008        }
1009
1010        let s = state(addr);
1011        s.iso.store(iso, Ordering::Relaxed);
1012        // one packet per microframe (the only rate the SOF catch-up handles): the descriptor's
1013        // bInterval is 1 at high speed, but 0 is accepted as "every microframe" by drivers that
1014        // pass it through
1015        if iso && dir == Direction::In && interval_ms <= 1 {
1016            ISO_IN_EVERY.store(
1017                ISO_IN_EVERY.load(Ordering::Relaxed) | 1 << addr.index(),
1018                Ordering::Relaxed,
1019            );
1020        }
1021        s.max_len.store(max_packet_size, Ordering::Relaxed);
1022        if iso && dir == Direction::Out {
1023            ISO_OUT_EPS.store(
1024                ISO_OUT_EPS.load(Ordering::Relaxed) | 1 << addr.index(),
1025                Ordering::Relaxed,
1026            );
1027        }
1028        s.base.store(data.addr() as u32, Ordering::Relaxed);
1029        s.stride.store(SIZE as u16, Ordering::Relaxed);
1030        s.slots.store(slots as u8, Ordering::Relaxed);
1031        s.reset();
1032
1033        Ok(Endpoint::new(
1034            EndpointInfo {
1035                addr,
1036                ep_type,
1037                max_packet_size,
1038                interval_ms,
1039                max_burst: 0,
1040            },
1041            data,
1042        ))
1043    }
1044}
1045
1046pub(crate) fn state(addr: EndpointAddress) -> &'static EpState {
1047    match addr.direction() {
1048        Direction::Out => &OUT_STATE[addr.index()],
1049        Direction::In => &IN_STATE[addr.index()],
1050    }
1051}
1052
1053/// Sets or clears the STALL handshake of an endpoint, for the bus and the
1054/// endpoint alike.
1055fn set_endpoint_stalled<T: Instance>(ep_addr: EndpointAddress, stalled: bool) {
1056    let index = ep_addr.index();
1057    let d = T::dregs();
1058    let s = state(ep_addr);
1059    let iso = s.iso.load(Ordering::Relaxed);
1060    critical_section::with(|_| match (ep_addr.direction(), stalled) {
1061        (Direction::Out, true) => d
1062            .ep_rx_ctrl(index)
1063            .modify(|v| v.set_mask_uep_r_res(EpRxResponse::STALL)),
1064        (Direction::In, true) => {
1065            d.ep_t_len(index).write(|v| v.set_len(0));
1066            d.ep_tx_ctrl(index)
1067                .modify(|v| v.set_mask_uep_t_res(EpTxResponse::STALL));
1068        }
1069        (Direction::Out, false) => {
1070            s.tog.store(false, Ordering::Relaxed);
1071            d.ep_rx_ctrl(index).write(|v| {
1072                // a read still waiting stays armed (or it would NAK forever)
1073                v.set_mask_uep_r_res(if iso {
1074                    EpRxResponse::NYET
1075                } else if s.armed.load(Ordering::Relaxed) {
1076                    EpRxResponse::ACK
1077                } else {
1078                    EpRxResponse::NAK
1079                });
1080                v.set_mask_uep_r_tog(EpTog::DATA0);
1081                v.set_r_tog_auto(index != 0 && !iso);
1082            })
1083        }
1084        (Direction::In, false) => {
1085            s.tog.store(false, Ordering::Relaxed);
1086            d.ep_tx_ctrl(index).write(|v| {
1087                v.set_mask_uep_t_res(if iso { TX_RES_ISO } else { EpTxResponse::NAK });
1088                v.set_mask_uep_t_tog(EpTog::DATA0);
1089                v.set_t_tog_auto(index != 0 && !iso);
1090            })
1091        }
1092    });
1093    if !stalled && ep_addr.direction() == Direction::In && !iso {
1094        // a write waiting on the stalled endpoint finishes (its data is dropped)
1095        s.armed.store(false, Ordering::Relaxed);
1096        s.ready.store(true, Ordering::Release);
1097    }
1098    s.waker.wake();
1099}
1100
1101fn is_endpoint_stalled<T: Instance>(ep_addr: EndpointAddress) -> bool {
1102    let index = ep_addr.index();
1103    let d = T::dregs();
1104    match ep_addr.direction() {
1105        Direction::Out => d.ep_rx_ctrl(index).read().mask_uep_r_res() == EpRxResponse::STALL,
1106        Direction::In => d.ep_tx_ctrl(index).read().mask_uep_t_res() == EpTxResponse::STALL,
1107    }
1108}
1109
1110impl<'d, T: Instance, const NR_EP: usize, const SIZE: usize> embassy_usb_driver::Driver<'d>
1111    for Driver<'d, T, NR_EP, SIZE>
1112{
1113    type EndpointOut = Endpoint<'d, T, Out, SIZE>;
1114    type EndpointIn = Endpoint<'d, T, In, SIZE>;
1115    type ControlPipe = ControlPipe<'d, T, SIZE>;
1116    type Bus = Bus<'d, T>;
1117
1118    fn alloc_endpoint_out(
1119        &mut self,
1120        config: &embassy_usb_driver::EndpointConfig,
1121    ) -> Result<Self::EndpointOut, EndpointAllocError> {
1122        self.alloc_endpoint(
1123            config.ep_type,
1124            config.addr,
1125            config.max_packet_size,
1126            config.interval_ms,
1127            Direction::Out,
1128        )
1129    }
1130
1131    fn alloc_endpoint_in(
1132        &mut self,
1133        config: &embassy_usb_driver::EndpointConfig,
1134    ) -> Result<Self::EndpointIn, EndpointAllocError> {
1135        self.alloc_endpoint(
1136            config.ep_type,
1137            config.addr,
1138            config.max_packet_size,
1139            config.interval_ms,
1140            Direction::In,
1141        )
1142    }
1143
1144    fn start(mut self, control_max_packet_size: u16) -> (Self::Bus, Self::ControlPipe) {
1145        let d = T::dregs();
1146
1147        let ep0_buf = self.allocator.alloc_endpoint(control_max_packet_size).unwrap();
1148        d.ep0_dma().write_value(ep0_buf.addr() as u32);
1149        EP0_BUF.store(ep0_buf.addr() as u32, Ordering::Relaxed);
1150        d.ep_max_len(0).write(|w| w.set_len(control_max_packet_size));
1151        d.ep_rx_ctrl(0).write(|w| w.set_mask_uep_r_res(EpRxResponse::NAK));
1152        d.ep_tx_ctrl(0).write(|w| w.set_mask_uep_t_res(EpTxResponse::NAK));
1153
1154        let ep0 = Endpoint::new(
1155            EndpointInfo {
1156                // todo fix in embassy usb driver ep_addr should be u8 with top bit unset
1157                addr: EndpointAddress::from_parts(0, Direction::Out),
1158                ep_type: EndpointType::Control,
1159                max_packet_size: EP_MAX_PACKET_SIZE,
1160                interval_ms: 0,
1161                max_burst: 0,
1162            },
1163            ep0_buf,
1164        );
1165
1166        critical_section::with(|_| {
1167            T::Interrupt::unpend();
1168            unsafe { T::Interrupt::enable() };
1169        });
1170
1171        (
1172            Bus {
1173                _phantom: PhantomData,
1174                fake_power_on: false,
1175            },
1176            ControlPipe::new(ep0),
1177        )
1178    }
1179}
1180
1181pub struct Bus<'d, T: Instance> {
1182    _phantom: PhantomData<&'d mut T>,
1183    fake_power_on: bool,
1184}
1185
1186impl<'d, T: Instance> Bus<'d, T> {
1187    fn bus_reset(&mut self) {
1188        let regs = T::regs();
1189        let d = T::dregs();
1190
1191        critical_section::with(|_| {
1192            // Reset device address
1193            regs.dev_ad().write(|v| {
1194                v.set_addr(0);
1195            });
1196
1197            // Reset endpoint state on bus reset
1198            // EP0 get ACK/NAK so it can recieve setup
1199            d.ep_rx_ctrl(0).write(|v| v.set_mask_uep_r_res(EpRxResponse::ACK));
1200            d.ep_tx_ctrl(0).write(|v| v.set_mask_uep_t_res(EpTxResponse::NAK));
1201
1202            // Mark all other EPs as NAK
1203            for i in 1..=15 {
1204                d.ep_tx_ctrl(i).write(|v| v.set_mask_uep_t_res(EpTxResponse::NAK));
1205                d.ep_rx_ctrl(i).write(|v| v.set_mask_uep_r_res(EpRxResponse::NAK));
1206            }
1207
1208            // Disable all endpoints [1, 15]
1209            d.ep_config().write_value(EpConfig::default());
1210            d.ep_type().write_value(EpType::default());
1211            d.ep_buf_mod().write_value(EpBufMod::default());
1212
1213            for s in OUT_STATE.iter().chain(IN_STATE.iter()) {
1214                s.reset();
1215            }
1216            SETUP_READY.store(false, Ordering::Relaxed);
1217        });
1218        for s in OUT_STATE.iter().chain(IN_STATE.iter()) {
1219            s.waker.wake();
1220        }
1221    }
1222}
1223
1224impl<'d, T: Instance> embassy_usb_driver::Bus for Bus<'d, T> {
1225    async fn enable(&mut self) {
1226        critical_section::with(|_| T::regs().ctrl().modify(|v| v.set_dev_pu_en(true)));
1227    }
1228
1229    async fn disable(&mut self) {
1230        // Detach: drop the D+ pull-up and pulse the SIE reset, the mechanism WCH's
1231        // `USBHS_Device_Init(DISABLE)` uses. Without the reset the device never attaches again:
1232        // when `enable` sets the pull-up back, D+ stays low.
1233        let r = T::regs();
1234        critical_section::with(|_| {
1235            r.ctrl().modify(|w| {
1236                w.set_dev_pu_en(false);
1237                w.set_clr_all(true);
1238                w.set_reset_sie(true);
1239            })
1240        });
1241        crate::internal::delay::block_for_us(10);
1242        critical_section::with(|_| {
1243            r.ctrl().modify(|w| {
1244                w.set_clr_all(false);
1245                w.set_reset_sie(false);
1246            })
1247        });
1248        // embassy-usb enables the bus again only on `PowerDetected`, which `poll` fakes once.
1249        self.fake_power_on = false;
1250    }
1251
1252    async fn poll(&mut self) -> Event {
1253        // TODO: VBUS detection
1254        if !self.fake_power_on {
1255            self.fake_power_on = true;
1256            return Event::PowerDetected;
1257        }
1258        poll_fn(|cx| {
1259            BUS_WAKER.register(cx.waker());
1260
1261            let r = T::regs();
1262            let flag = r.int_fg().read();
1263
1264            if flag.bus_rst() {
1265                self.bus_reset();
1266                r.int_fg().write(|w| w.set_bus_rst(true));
1267                critical_section::with(|_| {
1268                    r.int_en().modify(|w| w.set_bus_rst(true));
1269                });
1270                Poll::Ready(Event::Reset)
1271            } else if flag.suspend() {
1272                let mis_st = r.mis_st().read();
1273                r.int_fg().write(|w| w.set_suspend(true));
1274                critical_section::with(|_| {
1275                    r.int_en().modify(|w| w.set_suspend(true));
1276                });
1277                if mis_st.suspend() {
1278                    Poll::Ready(Event::Suspend)
1279                } else {
1280                    Poll::Ready(Event::Resume)
1281                }
1282            } else {
1283                Poll::Pending
1284            }
1285        })
1286        .await
1287    }
1288
1289    fn endpoint_set_enabled(&mut self, ep_addr: EndpointAddress, enabled: bool) {
1290        let index = ep_addr.index();
1291        if index == 0 {
1292            return;
1293        }
1294        let d = T::dregs();
1295        let s = state(ep_addr);
1296        let iso = s.iso.load(Ordering::Relaxed);
1297        let kind = if iso && enabled { EpKind::ISO } else { EpKind::NISO };
1298
1299        critical_section::with(|_| {
1300            s.reset();
1301            if enabled && !iso && ep_addr.direction() == Direction::Out {
1302                s.armed.store(true, Ordering::Relaxed);
1303            }
1304            match ep_addr.direction() {
1305                Direction::Out => {
1306                    if iso {
1307                        // every slot marked, so arming one marks what its last packet covered
1308                        let max = s.max_len.load(Ordering::Relaxed) as usize;
1309                        for k in 0..s.slots.load(Ordering::Relaxed) {
1310                            s.lens[k as usize].store(max as u16, Ordering::Relaxed);
1311                        }
1312                        s.min_len.store(max as u16, Ordering::Relaxed);
1313                        for k in (0..s.slots.load(Ordering::Relaxed)).rev() {
1314                            iso_out_arm(d, index, s.slot_addr(k), 0, max);
1315                        }
1316                    } else {
1317                        d.ep_rx_dma(index - 1).write_value(s.slot_addr(0));
1318                    }
1319                    d.ep_rx_ctrl(index).write(|v| {
1320                        v.set_mask_uep_r_tog(EpTog::DATA0);
1321                        // armed as soon as it's enabled: a host may send the first packet
1322                        // right after SET_CONFIGURATION. the interrupt NAKs after each packet
1323                        // until the next read()
1324                        v.set_mask_uep_r_res(match (enabled, iso) {
1325                            (false, _) => EpRxResponse::NAK,
1326                            (true, true) => EpRxResponse::NYET, // isochronous: no handshake
1327                            (true, false) => EpRxResponse::ACK,
1328                        });
1329                        v.set_r_tog_auto(!iso);
1330                    });
1331                    d.ep_type().modify(|v| v.set_r_type(index - 1, kind));
1332                    d.ep_config().modify(|v| v.set_r_en(index - 1, enabled));
1333                }
1334                Direction::In => {
1335                    PACED_LAST[index].store(NO_FRAME, Ordering::Relaxed);
1336                    d.ep_tx_dma(index - 1).write_value(s.slot_addr(0));
1337                    d.ep_t_len(index).write(|v| v.set_len(0));
1338                    d.ep_tx_ctrl(index).write(|v| {
1339                        v.set_mask_uep_t_tog(EpTog::DATA0);
1340                        // isochronous: answers every IN, with a zero-length packet when
1341                        // nothing is queued
1342                        v.set_mask_uep_t_res(if iso && enabled { TX_RES_ISO } else { EpTxResponse::NAK });
1343                        v.set_t_tog_auto(!iso);
1344                    });
1345                    d.ep_type().modify(|v| v.set_t_type(index - 1, kind));
1346                    d.ep_config().modify(|v| v.set_t_en(index - 1, enabled));
1347                }
1348            }
1349        });
1350        s.waker.wake();
1351    }
1352
1353    fn endpoint_set_stalled(&mut self, ep_addr: EndpointAddress, stalled: bool) {
1354        set_endpoint_stalled::<T>(ep_addr, stalled);
1355    }
1356
1357    fn endpoint_is_stalled(&mut self, ep_addr: EndpointAddress) -> bool {
1358        is_endpoint_stalled::<T>(ep_addr)
1359    }
1360
1361    async fn remote_wakeup(&mut self) -> Result<(), Unsupported> {
1362        Err(Unsupported)
1363    }
1364}
1365
1366/// USB endpoint.
1367trait SealedInstance: crate::peripheral::RccPeripheral {
1368    fn regs() -> crate::pac::usbhs::Usb;
1369    fn dregs() -> crate::pac::usbhs::Usbd;
1370    fn hregs() -> crate::pac::usbhs::Usbh;
1371}
1372
1373/// UsbHs peripheral instance
1374#[allow(private_bounds)]
1375pub trait Instance: SealedInstance + PeripheralType + 'static {
1376    /// Regular interrupt for this instance
1377    type Interrupt: interrupt::typelevel::Interrupt;
1378    /// Wakeup interrupt for this instance
1379    type WakeupInterrupt: interrupt::typelevel::Interrupt;
1380}
1381
1382foreach_peripheral!(
1383    (usbhs, $inst:ident) => {
1384        use crate::peripherals;
1385        impl SealedInstance for peripherals::$inst {
1386            fn regs() -> crate::pac::usbhs::Usb {
1387                crate::pac::$inst
1388            }
1389
1390            fn dregs() -> crate::pac::usbhs::Usbd {
1391                unsafe {
1392                    crate::pac::usbhs::Usbd::from_ptr(crate::pac::$inst.as_ptr())
1393                }
1394            }
1395
1396            fn hregs() -> crate::pac::usbhs::Usbh {
1397                unsafe {
1398                    crate::pac::usbhs::Usbh::from_ptr(crate::pac::$inst.as_ptr())
1399                }
1400            }
1401        }
1402
1403        impl Instance for peripherals::$inst {
1404            type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL;
1405            type WakeupInterrupt = crate::_generated::peripheral_interrupts::$inst::WAKEUP;
1406        }
1407    };
1408);
1409
1410pin_trait!(DmPin, Instance);
1411pin_trait!(DpPin, Instance);