Skip to main content

ch32_hal/otg_fs/
mod.rs

1//! USB_FS and OTG_FS device mode peripheral driver
2//! Note that this currently only implements device mode
3//!
4//! Serves the register models of the FS device block: `kind: otg` (`otg_v2`,
5//! the V2/V3 OTG parts), `kind: usbfs` (`usbfs_h4`, CH32H417) and `kind: usb`
6//! (`x0fs` on CH32X035, `v2fs` on CH32V20x/V303). The field-name differences
7//! live in the private `regs` module.
8//!
9//! ## Bidirectional endpoints and buffer sizing
10//!
11//! Non-control endpoint numbers `1..=7` (except `EP4` on CH32X035, which shares
12//! `EP0`'s DMA buffer in hardware) can be allocated in both `IN` and `OUT`
13//! directions simultaneously (for example `0x81` and `0x01`).
14//!
15//! Each endpoint number has a single `UEPn_DMA` base register. With
16//! `UEPn_BUF_MOD = 0`, hardware places `OUT` data at `[UEPn_DMA .. +64)` and,
17//! when both `UEPn_RX_EN` and `UEPn_TX_EN` are enabled, offsets `IN` data to
18//! `[UEPn_DMA + 64 .. +128)`. Because WCH USBFS has no per-endpoint max-RX
19//! length register (and writes two CRC16 bytes past received payloads up to 64
20//! bytes), `EP0` and any `OUT` endpoint always reserve 64 bytes in `ep_buffer`,
21//! and bidirectional endpoint pairs reserve 128 contiguous bytes regardless of
22//! the order in which `alloc_endpoint_in` and `alloc_endpoint_out` were called.
23//! Budget 64 bytes per allocated endpoint plus 64 bytes for `EP0` (for example,
24//! one `EndpointDataBuffer64` per allocated endpoint plus one for `EP0`).
25//!
26//! <div class="warning">
27//! There's a lot of TODOs and panics where things are not implemented
28//! </div>
29//!
30//! List of things that is tested
31//! Untested but expected to work items are noted as well
32//!
33//! Control Pipe:
34//! - [x] Receive `SETUP` packet (Host -> Dev)
35//! - [x] Send `IN` packet (Dev -> Host).
36//! - [x] Receive `OUT` packet (Host -> Dev).
37//!
38//! Other Endpoints:
39//! - [x] Interrupt Out
40//! - [x] Interrupt In
41//! - [x] Bulk Out (CDC-ACM echo on the CH32V203 USBFS)
42//! - [x] Bulk In (same)
43//!
44//! Other Features:
45//! - [x] Set endpoint stall (bulk, on the CH32V203 USBFS)
46//! - [x] Get endpoint stall status (same)
47//! - [ ] Remote wakeup
48//!
49
50use core::future::poll_fn;
51use core::marker::PhantomData;
52use core::sync::atomic::{fence, AtomicBool, AtomicU16, AtomicU32, AtomicU8, AtomicUsize, Ordering};
53use core::task::Poll;
54
55use bitmaps::Bitmap;
56use embassy_sync::waitqueue::AtomicWaker;
57use embassy_usb_driver::{Direction, EndpointAddress, EndpointAllocError, EndpointInfo, EndpointType, Event};
58use endpoint::{ControlPipe, Endpoint};
59use regs::{EpRxResponse, EpTxResponse, Regs, UsbToken};
60
61#[cfg(usb_x0fs)]
62use crate::gpio::Pull;
63#[cfg(otg_v2)]
64use crate::gpio::{AFType, Speed};
65use crate::interrupt::typelevel::Interrupt;
66use crate::usb::{Dir, EndpointDataBuffer, In, Out};
67use crate::{interrupt, peripherals, Peri, PeripheralType, RccPeripheral};
68
69pub mod endpoint;
70mod regs;
71
72// TODO: We technically support 16, but we only allow 8 for now (0, 1-7).
73const MAX_NR_EP: usize = 8;
74const EP_MAX_PACKET_SIZE: u16 = 64;
75
76/// Per-endpoint, per-direction completion state shared between `on_interrupt` and tasks.
77///
78/// Assumes a single USBFS/OTG_FS controller instance per chip (holds across all
79/// `otg_v2`, `usbfs_h4`, `usb_x0fs` and `usb_v2fs` parts).
80pub(crate) struct EpDirState {
81    pub(crate) waker: AtomicWaker,
82    pub(crate) ready: AtomicBool,
83    pub(crate) len: AtomicU16,
84    /// The host or the application halted the endpoint: it answers STALL.
85    pub(crate) stalled: AtomicBool,
86    /// A `read` or `write` waits on the endpoint: clearing a halt answers ACK again.
87    pub(crate) armed: AtomicBool,
88    /// A halt was cleared while a completed transaction still waited for the interrupt: that
89    /// interrupt sets DATA0 instead of advancing the toggle (USB 2.0, 9.4.5).
90    pub(crate) tog_reset: AtomicBool,
91    /// Set by every `endpoint_set_enabled`, cleared when a transfer arms: a transfer armed before
92    /// ends with `Disabled`, even when the endpoint is enabled again at once (same
93    /// SET_CONFIGURATION or SET_INTERFACE).
94    pub(crate) invalidated: AtomicBool,
95}
96
97impl EpDirState {
98    #[allow(clippy::declare_interior_mutable_const)]
99    const NEW: Self = Self {
100        waker: AtomicWaker::new(),
101        ready: AtomicBool::new(false),
102        len: AtomicU16::new(0),
103        stalled: AtomicBool::new(false),
104        armed: AtomicBool::new(false),
105        tog_reset: AtomicBool::new(false),
106        invalidated: AtomicBool::new(false),
107    };
108
109    fn reset(&self) {
110        self.ready.store(false, Ordering::Relaxed);
111        self.len.store(0, Ordering::Relaxed);
112        self.stalled.store(false, Ordering::Relaxed);
113        self.armed.store(false, Ordering::Relaxed);
114        self.tog_reset.store(false, Ordering::Relaxed);
115    }
116}
117
118/// After a transaction on endpoint `ep` (1..) completes: the transfer is no longer armed, the
119/// endpoint answers STALL if halted and NAK otherwise, and the toggle advances, or restarts at
120/// DATA0 if a halt was cleared while this interrupt was pending. Interrupt context.
121fn in_done(regs: regs::Regs, ep: usize) {
122    let st = &IN_STATE[ep];
123    st.armed.store(false, Ordering::Relaxed);
124    let res = if st.stalled.load(Ordering::Relaxed) {
125        EpTxResponse::STALL
126    } else {
127        EpTxResponse::NAK
128    };
129    if st.tog_reset.load(Ordering::Relaxed) {
130        st.tog_reset.store(false, Ordering::Relaxed);
131        regs::ep_tx_ctrl_write(regs, ep, false, res);
132    } else {
133        regs::ep_tx_ctrl_flip_tog(regs, ep, res);
134    }
135}
136
137/// Same as [`in_done`], for an OUT packet whose toggle matched (`TOG_OK`).
138fn out_done(regs: regs::Regs, ep: usize) {
139    let st = &OUT_STATE[ep];
140    st.armed.store(false, Ordering::Relaxed);
141    let res = if st.stalled.load(Ordering::Relaxed) {
142        EpRxResponse::STALL
143    } else {
144        EpRxResponse::NAK
145    };
146    if st.tog_reset.load(Ordering::Relaxed) {
147        st.tog_reset.store(false, Ordering::Relaxed);
148        regs::ep_rx_ctrl_write(regs, ep, false, res);
149    } else {
150        regs::ep_rx_ctrl_flip_tog(regs, ep, res);
151    }
152}
153
154/// Whether a completed transaction of endpoint `ep` in direction `dir` waits for the interrupt.
155/// `INT_BUSY` holds the block on NAK until `UIF_TRANSFER` is cleared, so there is at most one.
156/// An OUT packet counts only if its toggle matched: the interrupt drops the others.
157fn transaction_pending(regs: regs::Regs, ep: usize, dir: Direction) -> bool {
158    if !regs::int_fg(regs).transfer {
159        return false;
160    }
161    let st = regs::int_st(regs);
162    usize::from(st.ep) == ep
163        && match dir {
164            Direction::In => matches!(st.token, UsbToken::IN),
165            Direction::Out => matches!(st.token, UsbToken::OUT) && st.tog_ok,
166        }
167}
168
169/// Halt (`stalled`) or clear the halt of a bulk or interrupt endpoint. Clearing restarts the
170/// toggle at DATA0, halted or not (USB 2.0, 9.4.5), and answers ACK again if a transfer waits.
171/// A halt does not touch the transfer itself: an IN packet armed before keeps its length and data
172/// and goes out once the halt is cleared. An OUT direction that is not enabled is left alone: on a
173/// number shared with an enabled IN, `RX_EN` stays set for the IN buffer offset and OUT must keep
174/// answering NAK.
175///
176/// A transaction that completed before the clear is accounted for by `transaction_pending`; one
177/// still on the wire when the clear runs is not, which needs the host to move data on the
178/// endpoint while it clears that endpoint's halt.
179pub(crate) fn set_endpoint_stalled<T: Instance>(ep_addr: EndpointAddress, stalled: bool) {
180    let ep = ep_addr.index();
181    if ep == 0 || ep >= MAX_NR_EP {
182        return;
183    }
184    let regs = T::regs();
185    let dir = ep_addr.direction();
186    let st = match dir {
187        Direction::In => &IN_STATE[ep],
188        Direction::Out => &OUT_STATE[ep],
189    };
190    critical_section::with(|_| {
191        if dir == Direction::Out && !endpoint::is_out_logically_enabled(ep) {
192            return;
193        }
194        st.stalled.store(stalled, Ordering::Relaxed);
195        if stalled {
196            match dir {
197                Direction::In => regs::ep_tx_ctrl_set_res(regs, ep, EpTxResponse::STALL),
198                Direction::Out => regs::ep_rx_ctrl_set_res(regs, ep, EpRxResponse::STALL),
199            }
200            return;
201        }
202        // Stop new transactions first, then look for one that completed before this request.
203        match dir {
204            Direction::In => regs::ep_tx_ctrl_set_res(regs, ep, EpTxResponse::NAK),
205            Direction::Out => regs::ep_rx_ctrl_set_res(regs, ep, EpRxResponse::NAK),
206        }
207        if transaction_pending(regs, ep, dir) {
208            // Its interrupt sets DATA0 and the response once it has accounted for it.
209            st.tog_reset.store(true, Ordering::Relaxed);
210            return;
211        }
212        let armed = st.armed.load(Ordering::Relaxed);
213        match dir {
214            Direction::In => {
215                let res = if armed { EpTxResponse::ACK } else { EpTxResponse::NAK };
216                regs::ep_tx_ctrl_write(regs, ep, false, res);
217            }
218            Direction::Out => {
219                let res = if armed { EpRxResponse::ACK } else { EpRxResponse::NAK };
220                regs::ep_rx_ctrl_write(regs, ep, false, res);
221            }
222        }
223    });
224}
225
226pub(crate) fn is_endpoint_stalled(ep_addr: EndpointAddress) -> bool {
227    let ep = ep_addr.index();
228    if ep == 0 || ep >= MAX_NR_EP {
229        return false;
230    }
231    match ep_addr.direction() {
232        Direction::In => IN_STATE[ep].stalled.load(Ordering::Relaxed),
233        Direction::Out => OUT_STATE[ep].stalled.load(Ordering::Relaxed),
234    }
235}
236
237static BUS_WAKER: AtomicWaker = AtomicWaker::new();
238pub(crate) static EP0_WAKER: AtomicWaker = AtomicWaker::new();
239pub(crate) static IN_STATE: [EpDirState; MAX_NR_EP] = [EpDirState::NEW; MAX_NR_EP];
240pub(crate) static OUT_STATE: [EpDirState; MAX_NR_EP] = [EpDirState::NEW; MAX_NR_EP];
241
242/// Latest 8-byte SETUP packet copied out of EP0's DMA buffer by `on_interrupt`.
243static SETUP_WORDS: [AtomicU32; 2] = [AtomicU32::new(0), AtomicU32::new(0)];
244static SETUP_PENDING: AtomicBool = AtomicBool::new(false);
245static BUS_RST_PENDING: AtomicBool = AtomicBool::new(false);
246
247const ZERO_ADDR: AtomicUsize = AtomicUsize::new(0);
248/// Full RAM base address backing `UEPn_DMA` for each endpoint number (`0..MAX_NR_EP`).
249///
250/// Stored separately from `UEPn_DMA` because `x0fs`/`v2fs`/`otg_v2` DMA
251/// registers only hold the low 15–16 SRAM offset bits rather than a full pointer.
252static EP_BUF_ADDR: [AtomicUsize; MAX_NR_EP] = [ZERO_ADDR; MAX_NR_EP];
253/// Bitmask of endpoint numbers (`1..MAX_NR_EP`) allocated in both IN and OUT directions.
254static EP_BIDIR_MASK: AtomicU8 = AtomicU8::new(0);
255
256pub(crate) fn ep_buf_addr(ep: usize) -> usize {
257    EP_BUF_ADDR[ep].load(Ordering::Acquire)
258}
259
260pub(crate) fn ep_is_bidir(ep: usize) -> bool {
261    (EP_BIDIR_MASK.load(Ordering::Acquire) & (1 << ep)) != 0
262}
263
264pub(crate) fn setup_pending() -> bool {
265    SETUP_PENDING.load(Ordering::Acquire)
266}
267
268pub(crate) fn bus_rst_pending() -> bool {
269    BUS_RST_PENDING.load(Ordering::Acquire)
270}
271
272pub(crate) fn take_setup() -> Option<[u8; 8]> {
273    critical_section::with(|_| {
274        if !SETUP_PENDING.load(Ordering::Acquire) {
275            return None;
276        }
277        SETUP_PENDING.store(false, Ordering::Release);
278        let w0 = SETUP_WORDS[0].load(Ordering::Relaxed).to_le_bytes();
279        let w1 = SETUP_WORDS[1].load(Ordering::Relaxed).to_le_bytes();
280        let mut out = [0u8; 8];
281        out[..4].copy_from_slice(&w0);
282        out[4..].copy_from_slice(&w1);
283        Some(out)
284    })
285}
286
287/// Validates that `[addr .. addr + len)` is 4-byte aligned and addressable by
288/// this chip's USBFS DMA engine.
289fn validate_dma_region(addr: usize, len: usize) {
290    assert!(addr != 0 && addr % 4 == 0, "USBFS DMA buffer must be 4-byte aligned");
291    let end = addr.checked_add(len).expect("USBFS DMA buffer address overflow");
292    // X035 `UEPn_DMA` latches only bits [14:0] as an offset from 0x2000_0000 (32 KiB window).
293    #[cfg(usb_x0fs)]
294    assert!(
295        addr >= 0x2000_0000 && end <= 0x2000_8000,
296        "CH32X035 USBFS DMA buffer {:#x}..{:#x} outside 0x2000_0000..0x2000_8000",
297        addr,
298        end
299    );
300    // V20x/V30x `UEPn_DMA` addresses a 64 KiB SRAM window starting at 0x2000_0000.
301    #[cfg(any(usb_v2fs, otg_v2))]
302    assert!(
303        addr >= 0x2000_0000 && end <= 0x2001_0000,
304        "USBFS DMA buffer {:#x}..{:#x} outside 64 KiB SRAM window 0x2000_0000..0x2001_0000",
305        addr,
306        end
307    );
308    let _ = end;
309}
310
311/// USB PHY configuration (X035 only).
312#[derive(Clone, Copy, Debug)]
313pub struct Config {
314    /// Use the direct VDD PHY output and pull-up. Clear this when VDD is
315    /// above 4 V.
316    #[cfg(usb_x0fs)]
317    pub usb_phy_v33: bool,
318    /// AFIO pull-up mode for UDP. `0b11` is the USB 1.5 kΩ pull-up for 3.3 V.
319    #[cfg(usb_x0fs)]
320    pub udp_pue: u8,
321}
322
323impl Default for Config {
324    fn default() -> Self {
325        Self {
326            #[cfg(usb_x0fs)]
327            usb_phy_v33: true,
328            #[cfg(usb_x0fs)]
329            udp_pue: 0b11,
330        }
331    }
332}
333
334pub struct InterruptHandler<T: Instance> {
335    _phantom: PhantomData<T>,
336}
337
338impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
339    unsafe fn on_interrupt() {
340        let regs = T::regs();
341        let int_fg = regs::int_fg(regs);
342
343        if int_fg.fifo_ov {
344            error!("[USBFS] FIFO overflow");
345            regs::clear_fifo_ov(regs);
346        }
347
348        if int_fg.bus_rst {
349            // Mask bus_rst until `Bus::poll` processes it; wake EP0 and all
350            // active endpoints so any in-flight control or data transfer aborts.
351            regs::set_bus_rst_ie(regs, false);
352            BUS_RST_PENDING.store(true, Ordering::Release);
353            BUS_WAKER.wake();
354            EP0_WAKER.wake();
355            for ep in 1..MAX_NR_EP {
356                IN_STATE[ep].waker.wake();
357                OUT_STATE[ep].waker.wake();
358            }
359        }
360
361        if int_fg.suspend {
362            regs::set_suspend_ie(regs, false);
363            BUS_WAKER.wake();
364        }
365
366        if int_fg.transfer {
367            let status = regs::int_st(regs);
368            let token = status.token;
369
370            match token {
371                UsbToken::SETUP => {
372                    // Disarm EP0 both ways, snapshot the 8-byte SETUP packet, and
373                    // release `UIF_TRANSFER` immediately so `INT_BUSY` never wedges.
374                    regs::ep_tx_ctrl_write(regs, 0, false, EpTxResponse::NAK);
375                    regs::ep_rx_ctrl_write(regs, 0, false, EpRxResponse::NAK);
376                    IN_STATE[0].reset();
377                    OUT_STATE[0].reset();
378
379                    let ep0_addr = EP_BUF_ADDR[0].load(Ordering::Acquire);
380                    if ep0_addr != 0 {
381                        fence(Ordering::Acquire);
382                        let p = ep0_addr as *const u32;
383                        SETUP_WORDS[0].store(core::ptr::read_volatile(p), Ordering::Relaxed);
384                        SETUP_WORDS[1].store(core::ptr::read_volatile(p.add(1)), Ordering::Relaxed);
385                        SETUP_PENDING.store(true, Ordering::Release);
386                    }
387                    regs::clear_transfer(regs);
388                    EP0_WAKER.wake();
389                }
390                UsbToken::IN => {
391                    let ep = status.ep as usize;
392                    if ep == 0 {
393                        regs::ep_tx_ctrl_set_res(regs, 0, EpTxResponse::NAK);
394                        IN_STATE[0].ready.store(true, Ordering::Release);
395                        regs::clear_transfer(regs);
396                        EP0_WAKER.wake();
397                    } else if ep < MAX_NR_EP {
398                        // With `clear_transfer`, in one go: a halt cleared from a context that
399                        // preempts this handler must not see this transaction still pending.
400                        critical_section::with(|_| {
401                            in_done(regs, ep);
402                            IN_STATE[ep].ready.store(true, Ordering::Release);
403                            regs::clear_transfer(regs);
404                        });
405                        IN_STATE[ep].waker.wake();
406                    } else {
407                        error!("[USBFS] Unexpected EP: {} got token: {:#x}", ep, token.to_bits());
408                        regs::clear_transfer(regs);
409                    }
410                }
411                UsbToken::OUT => {
412                    let ep = status.ep as usize;
413                    if ep == 0 {
414                        if status.tog_ok {
415                            let len = regs::rx_len(regs);
416                            regs::ep_rx_ctrl_set_res(regs, 0, EpRxResponse::NAK);
417                            OUT_STATE[0].len.store(len, Ordering::Relaxed);
418                            OUT_STATE[0].ready.store(true, Ordering::Release);
419                            regs::clear_transfer(regs);
420                            EP0_WAKER.wake();
421                        } else {
422                            // Retransmitted OUT packet: leave EP0 RX armed for the matching toggle.
423                            regs::clear_transfer(regs);
424                        }
425                    } else if ep < MAX_NR_EP {
426                        if status.tog_ok {
427                            let len = regs::rx_len(regs);
428                            critical_section::with(|_| {
429                                out_done(regs, ep);
430                                OUT_STATE[ep].len.store(len, Ordering::Relaxed);
431                                OUT_STATE[ep].ready.store(true, Ordering::Release);
432                                regs::clear_transfer(regs);
433                            });
434                            OUT_STATE[ep].waker.wake();
435                        } else {
436                            // Retransmitted OUT packet: leave endpoint armed.
437                            regs::clear_transfer(regs);
438                        }
439                    } else {
440                        error!("[USBFS] Unexpected EP: {} got token: {:#x}", ep, token.to_bits());
441                        regs::clear_transfer(regs);
442                    }
443                }
444                // X0 names bit 0 of the token field `SOF`, not `RSVD`.
445                _ => {
446                    regs::clear_transfer(regs);
447                }
448            }
449        }
450
451        // Clear the host sof, we are in device mode.... It's garbage
452        if int_fg.hst_sof {
453            regs::clear_hst_sof(regs);
454        }
455    }
456}
457
458pub struct Driver<'d, T: Instance, const NR_EP: usize, const SIZE: usize> {
459    phantom: PhantomData<&'d mut (T, [EndpointDataBuffer<SIZE>; NR_EP])>,
460    buf_base: *mut u8,
461    buf_cap: usize,
462    allocated_in: Bitmap<MAX_NR_EP>,
463    allocated_out: Bitmap<MAX_NR_EP>,
464}
465
466impl<'d, T, const NR_EP: usize, const SIZE: usize> Driver<'d, T, NR_EP, SIZE>
467where
468    T: Instance,
469{
470    pub fn new(
471        _usb: Peri<'d, T>,
472        // _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
473        dp: Peri<'d, impl crate::gpio::Pin>,
474        dm: Peri<'d, impl crate::gpio::Pin>,
475        ep_buffer: &'d mut [EndpointDataBuffer<SIZE>; NR_EP],
476    ) -> Self {
477        Self::new_with_config(_usb, dp, dm, ep_buffer, Config::default())
478    }
479
480    /// Use this when board-level USB PHY or pull-up settings differ from the
481    /// default 3.3 V setup.
482    pub fn new_with_config(
483        _usb: Peri<'d, T>,
484        // _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
485        dp: Peri<'d, impl crate::gpio::Pin>,
486        dm: Peri<'d, impl crate::gpio::Pin>,
487        ep_buffer: &'d mut [EndpointDataBuffer<SIZE>; NR_EP],
488        config: Config,
489    ) -> Self {
490        assert!(!ep_buffer.is_empty());
491
492        // Disable IRQ before resetting hardware and clearing shared static state.
493        T::Interrupt::disable();
494
495        // RM table 9-12: on H4 the FS controller drives DP/DM itself once it
496        // is clocked, so the pins need no alternate-function setup; the
497        // CH32V20x manual says the same of its USBFS (table 10-9).
498        #[cfg(otg_v2)]
499        {
500            dp.set_as_af_output(AFType::OutputPushPull, Speed::High);
501            dm.set_as_af_output(AFType::OutputPushPull, Speed::High);
502            let _ = config;
503        }
504        #[cfg(any(usbfs_h4, usb_v2fs))]
505        let _ = (dp, dm, config);
506        // X035 keeps DP/DM as GPIO inputs and switches the on-die pull-up on
507        // through `AFIO.CTLR` instead of selecting an alternate function.
508        #[cfg(usb_x0fs)]
509        {
510            dp.set_as_input(Pull::Up);
511            dm.set_as_input(Pull::None);
512
513            crate::pac::AFIO.ctlr().modify(|w| {
514                w.set_usb_phy_v33(config.usb_phy_v33);
515                w.set_udp_pue(config.udp_pue);
516                w.set_udm_pue(0);
517                w.set_usb_ioen(true);
518            });
519            regs::save_pull_up(config.udp_pue);
520        }
521
522        T::enable_and_reset();
523
524        // Ensure all non-control endpoints are disabled after reset so no
525        // endpoint appears enabled before `start()` + `SET_CONFIGURATION`.
526        let regs = T::regs();
527        for ep in 1..MAX_NR_EP {
528            endpoint::set_out_logically_enabled(ep, false);
529            regs::ep_set_enabled(regs, ep, Direction::In, false);
530            regs::ep_set_enabled(regs, ep, Direction::Out, false);
531        }
532
533        SETUP_PENDING.store(false, Ordering::Relaxed);
534        BUS_RST_PENDING.store(false, Ordering::Relaxed);
535        EP_BIDIR_MASK.store(0, Ordering::Relaxed);
536        for slot in &EP_BUF_ADDR {
537            slot.store(0, Ordering::Relaxed);
538        }
539        for i in 0..MAX_NR_EP {
540            IN_STATE[i].reset();
541            OUT_STATE[i].reset();
542        }
543
544        let (buf_base, buf_cap) = EndpointDataBuffer::slice_as_mut_ptr(ep_buffer);
545
546        // EP4 shares EP0's DMA buffer on X0, so it cannot be handed out.
547        #[cfg(usb_x0fs)]
548        let reserved = {
549            let mut bm = Bitmap::new();
550            bm.set(4, true);
551            bm
552        };
553        #[cfg(not(usb_x0fs))]
554        let reserved = Bitmap::new();
555
556        Self {
557            phantom: PhantomData,
558            buf_base,
559            buf_cap,
560            allocated_in: reserved,
561            allocated_out: reserved,
562        }
563    }
564
565    #[inline]
566    const fn is_reserved_ep(ep: usize) -> bool {
567        #[cfg(usb_x0fs)]
568        {
569            ep == 4
570        }
571        #[cfg(not(usb_x0fs))]
572        {
573            let _ = ep;
574            false
575        }
576    }
577
578    /// DMA buffer bytes required for an endpoint `ep` (`1..MAX_NR_EP`).
579    ///
580    /// - Bidirectional (`IN` + `OUT`): 128 contiguous bytes (`OUT` at `+0`, `IN` at `+64`).
581    /// - Unidirectional `OUT`: 64 bytes (WCH USBFS has no hardware max-RX-length
582    ///   register and appends 2 CRC16 bytes up to 64 bytes; RM §23.2.2.6 Note 1).
583    /// - Unidirectional `IN`: `min(SIZE, 64)` bytes (4-byte aligned since `SIZE` is a power of two >= 8).
584    #[inline]
585    const fn ep_slot_bytes(has_in: bool, has_out: bool) -> usize {
586        let ep_max = EP_MAX_PACKET_SIZE as usize;
587        match (has_in, has_out) {
588            (true, true) => 2 * ep_max,
589            (false, true) => ep_max,
590            (true, false) => {
591                if SIZE < ep_max {
592                    SIZE
593                } else {
594                    ep_max
595                }
596            }
597            (false, false) => 0,
598        }
599    }
600
601    /// Total DMA buffer bytes required for `EP0` (64 bytes) plus all claimed endpoints.
602    fn required_buffer_bytes(allocated_in: Bitmap<MAX_NR_EP>, allocated_out: Bitmap<MAX_NR_EP>) -> usize {
603        let mut total = usize::from(EP_MAX_PACKET_SIZE); // 64 bytes reserved for EP0
604
605        for ep in 1..MAX_NR_EP {
606            if Self::is_reserved_ep(ep) {
607                continue;
608            }
609            total += Self::ep_slot_bytes(allocated_in.get(ep), allocated_out.get(ep));
610        }
611        total
612    }
613
614    fn find_free_ep_address(&self, dir: Direction) -> Result<u8, EndpointAllocError> {
615        // Endpoint 0 is reserved for the control pipe (claimed in start()).
616        // `next_false_index` searches strictly *after* the given index, so
617        // `next_false_index(0)` only returns non-control endpoints (>= 1),
618        // matching the behavior of Embassy USB drivers.
619        //
620        // Prefer an endpoint number unused in both directions first; fall back
621        // to sharing an endpoint number whose `dir` half is still free.
622        let dir_allocated = match dir {
623            Direction::In => self.allocated_in,
624            Direction::Out => self.allocated_out,
625        };
626        let ep = (self.allocated_in | self.allocated_out)
627            .next_false_index(0)
628            .or_else(|| dir_allocated.next_false_index(0))
629            .ok_or(EndpointAllocError)?;
630        Ok(ep as u8)
631    }
632
633    fn alloc_endpoint<D: Dir>(
634        &mut self,
635        ep_type: EndpointType,
636        ep_addr: Option<EndpointAddress>,
637        max_packet_size: u16,
638        interval_ms: u8,
639        dir: Direction,
640    ) -> Result<Endpoint<'d, T, D, SIZE>, EndpointAllocError> {
641        // Isochronous transfers require different handshake/toggle handling not implemented here.
642        if ep_type == EndpointType::Isochronous {
643            return Err(EndpointAllocError);
644        }
645        if max_packet_size > EP_MAX_PACKET_SIZE || usize::from(max_packet_size) > SIZE {
646            return Err(EndpointAllocError);
647        }
648
649        let addr = match ep_addr {
650            Some(addr) => {
651                // Use the provided endpoint address
652                if addr.direction() != dir {
653                    return Err(EndpointAllocError);
654                }
655
656                let ep_num = addr.index();
657                // Endpoint 0 belongs to the control pipe, which claims it in
658                // start(); class endpoint allocation must never hand it out.
659                if ep_num == 0 || ep_num >= MAX_NR_EP || Self::is_reserved_ep(ep_num) {
660                    return Err(EndpointAllocError);
661                }
662
663                let already_allocated = match dir {
664                    Direction::In => self.allocated_in.get(ep_num),
665                    Direction::Out => self.allocated_out.get(ep_num),
666                };
667                if already_allocated {
668                    return Err(EndpointAllocError);
669                }
670
671                addr
672            }
673            None => {
674                let ep_num = self.find_free_ep_address(dir)?;
675                EndpointAddress::from_parts(ep_num as usize, dir)
676            }
677        };
678
679        let mut next_in = self.allocated_in;
680        let mut next_out = self.allocated_out;
681        match dir {
682            Direction::In => {
683                next_in.set(addr.index(), true);
684            }
685            Direction::Out => {
686                next_out.set(addr.index(), true);
687            }
688        }
689
690        if Self::required_buffer_bytes(next_in, next_out) > self.buf_cap {
691            error!("out of endpoint buffers");
692            return Err(EndpointAllocError);
693        }
694
695        self.allocated_in = next_in;
696        self.allocated_out = next_out;
697
698        Ok(Endpoint::new(EndpointInfo {
699            addr,
700            ep_type,
701            max_packet_size,
702            interval_ms,
703            max_burst: 0,
704        }))
705    }
706}
707
708impl<'d, T: Instance, const NR_EP: usize, const SIZE: usize> embassy_usb_driver::Driver<'d>
709    for Driver<'d, T, NR_EP, SIZE>
710{
711    type EndpointOut = Endpoint<'d, T, Out, SIZE>;
712
713    type EndpointIn = Endpoint<'d, T, In, SIZE>;
714
715    type ControlPipe = ControlPipe<'d, T, SIZE>;
716
717    type Bus = Bus<'d, T>;
718
719    fn alloc_endpoint_out(
720        &mut self,
721        config: &embassy_usb_driver::EndpointConfig,
722    ) -> Result<Self::EndpointOut, EndpointAllocError> {
723        self.alloc_endpoint(
724            config.ep_type,
725            config.addr,
726            config.max_packet_size,
727            config.interval_ms,
728            Direction::Out,
729        )
730    }
731
732    fn alloc_endpoint_in(
733        &mut self,
734        config: &embassy_usb_driver::EndpointConfig,
735    ) -> Result<Self::EndpointIn, EndpointAllocError> {
736        self.alloc_endpoint(
737            config.ep_type,
738            config.addr,
739            config.max_packet_size,
740            config.interval_ms,
741            Direction::In,
742        )
743    }
744
745    fn start(self, control_max_packet_size: u16) -> (Self::Bus, Self::ControlPipe) {
746        assert!(control_max_packet_size <= EP_MAX_PACKET_SIZE);
747        assert!(
748            usize::from(EP_MAX_PACKET_SIZE) <= self.buf_cap,
749            "ep_buffer pool ({} bytes) must hold at least 64 bytes for EP0",
750            self.buf_cap
751        );
752        let regs = T::regs();
753
754        regs::ep_rx_ctrl_write(regs, 0, false, EpRxResponse::NAK);
755
756        regs::reset_sie(regs);
757
758        crate::internal::delay::block_for_us(10);
759
760        // Clear all
761        regs::clear_ctrl(regs);
762
763        // Host SOF is ignored, not our usecase here
764        regs::enable_interrupts(regs);
765
766        regs::enter_device_mode(regs);
767
768        // Lay out contiguous DMA buffers now that all IN/OUT endpoints are known.
769        let ep0_bytes = usize::from(EP_MAX_PACKET_SIZE);
770        let mut offset = 0usize;
771
772        let ep0_addr = unsafe { self.buf_base.add(offset) } as usize;
773        offset += ep0_bytes;
774        validate_dma_region(ep0_addr, ep0_bytes);
775        EP_BUF_ADDR[0].store(ep0_addr, Ordering::Release);
776        regs::set_ep_dma(regs, 0, ep0_addr as u32);
777
778        let mut bidir_mask = 0u8;
779        for ep in 1..MAX_NR_EP {
780            if Self::is_reserved_ep(ep) {
781                continue;
782            }
783            let has_in = self.allocated_in.get(ep);
784            let has_out = self.allocated_out.get(ep);
785            let slot_bytes = Self::ep_slot_bytes(has_in, has_out);
786            if slot_bytes == 0 {
787                continue;
788            }
789            if has_in && has_out {
790                bidir_mask |= 1 << ep;
791            }
792            let addr = unsafe { self.buf_base.add(offset) } as usize;
793            offset += slot_bytes;
794            validate_dma_region(addr, slot_bytes);
795            EP_BUF_ADDR[ep].store(addr, Ordering::Release);
796            regs::set_ep_dma(regs, ep, addr as u32);
797        }
798        assert!(offset <= self.buf_cap, "endpoint buffer pool overflow");
799        EP_BIDIR_MASK.store(bidir_mask, Ordering::Release);
800
801        regs::ep_rx_ctrl_write(regs, 0, false, EpRxResponse::ACK);
802        regs::ep_tx_ctrl_write(regs, 0, false, EpTxResponse::NAK);
803
804        critical_section::with(|_cs| {
805            T::Interrupt::unpend();
806            unsafe {
807                T::Interrupt::enable();
808            }
809        });
810
811        (
812            Bus {
813                _phantom: PhantomData,
814                inited: false,
815            },
816            ControlPipe::new(control_max_packet_size),
817        )
818    }
819}
820
821pub struct Bus<'d, T: Instance> {
822    _phantom: PhantomData<&'d mut T>,
823    inited: bool,
824}
825
826impl<'d, T: Instance> Drop for Bus<'d, T> {
827    fn drop(&mut self) {
828        T::Interrupt::disable();
829        let regs = T::regs();
830        regs::set_pull_up(regs, false);
831        regs::clear_ctrl(regs);
832        for slot in &EP_BUF_ADDR {
833            slot.store(0, Ordering::Release);
834        }
835    }
836}
837
838impl<'d, T: Instance> Bus<'d, T> {
839    fn bus_reset(&mut self) {
840        let regs = T::regs();
841
842        // Reset device address
843        regs::set_device_address(regs, 0);
844
845        SETUP_PENDING.store(false, Ordering::Release);
846        IN_STATE[0].reset();
847        OUT_STATE[0].reset();
848
849        // Restore DMA base pointers for all configured endpoints
850        for (ep, slot) in EP_BUF_ADDR.iter().enumerate() {
851            let addr = slot.load(Ordering::Acquire);
852            if addr != 0 {
853                regs::set_ep_dma(regs, ep, addr as u32);
854            }
855        }
856
857        // Reset endpoint state on bus reset
858        // EP0 gets ACK/NAK so it can receive setup
859        regs::ep_rx_ctrl_write(regs, 0, false, EpRxResponse::ACK);
860        regs::ep_tx_ctrl_write(regs, 0, false, EpTxResponse::NAK);
861
862        // Mark all other EPs as NAK and disabled
863        for i in 1..MAX_NR_EP {
864            use embassy_usb_driver::Bus;
865            self.endpoint_set_enabled(EndpointAddress::from_parts(i, Direction::In), false);
866            self.endpoint_set_enabled(EndpointAddress::from_parts(i, Direction::Out), false);
867        }
868
869        BUS_RST_PENDING.store(false, Ordering::Release);
870        EP0_WAKER.wake();
871    }
872}
873
874impl<'d, T> embassy_usb_driver::Bus for Bus<'d, T>
875where
876    T: Instance,
877{
878    async fn enable(&mut self) {
879        // `start` already set the pull-up for the first enable; set it again after a `disable`.
880        regs::set_pull_up(T::regs(), true);
881
882        // Enable the port
883        regs::enable_port(T::regs());
884
885        // Do a bus reset on "enable"
886        self.bus_reset();
887    }
888
889    async fn disable(&mut self) {
890        // Detach from the bus, as TinyUSB's `dcd_disconnect` does on this block.
891        regs::set_pull_up(T::regs(), false);
892        // embassy-usb enables the bus again only on `PowerDetected`, which `poll` fakes once.
893        self.inited = false;
894    }
895
896    async fn poll(&mut self) -> embassy_usb_driver::Event {
897        // TODO: VBUS detection
898        if !self.inited {
899            self.inited = true;
900            return Event::PowerDetected;
901        }
902
903        poll_fn(|ctx| {
904            BUS_WAKER.register(ctx.waker());
905            let regs = T::regs();
906            let interrupt_flags = regs::int_fg(regs);
907
908            // Either Suspend or Resume has happened
909            if interrupt_flags.suspend {
910                regs::clear_suspend(regs);
911                regs::set_suspend_ie(regs, true);
912
913                if regs::is_suspended(regs) {
914                    Poll::Ready(Event::Suspend)
915                } else {
916                    Poll::Ready(Event::Resume)
917                }
918            } else if interrupt_flags.bus_rst || bus_rst_pending() {
919                trace!("bus: reset");
920                self.bus_reset();
921                regs::clear_bus_rst(regs);
922                regs::set_bus_rst_ie(regs, true);
923
924                Poll::Ready(Event::Reset)
925            } else {
926                Poll::Pending
927            }
928        })
929        .await
930    }
931
932    fn endpoint_set_enabled(&mut self, ep_addr: EndpointAddress, enabled: bool) {
933        #[cfg(feature = "defmt")]
934        trace!(
935            "[USBFS] Endpoint: {}, {}: Set enable={}",
936            ep_addr.index(),
937            ep_addr.direction(),
938            enabled
939        );
940        let ep = ep_addr.index();
941        assert!(ep > 0 && ep < MAX_NR_EP, "invalid USBFS endpoint index {}", ep);
942        let regs = T::regs();
943
944        // Reset data toggle to DATA0 and disarm endpoint to NAK before updating enable state.
945        // For bidirectional endpoint numbers (`ep_is_bidir(ep)`), keep `RX_EN` asserted while
946        // `TX_EN` is enabled (with `R_RES = NAK` when OUT itself is disabled so OUT packets
947        // are never accepted) so hardware's IN DMA offset stays fixed at `+64` across
948        // per-endpoint `SET_CONFIGURATION` / `SET_INTERFACE` enable calls.
949        critical_section::with(|_| match ep_addr.direction() {
950            Direction::In => {
951                IN_STATE[ep].reset();
952                IN_STATE[ep].invalidated.store(true, Ordering::Relaxed);
953                regs::ep_tx_ctrl_write(regs, ep, false, EpTxResponse::NAK);
954                regs::ep_set_enabled(regs, ep, Direction::In, enabled);
955                if ep_is_bidir(ep) {
956                    if enabled {
957                        if !endpoint::is_out_logically_enabled(ep) {
958                            regs::ep_rx_ctrl_write(regs, ep, false, EpRxResponse::NAK);
959                        }
960                        regs::ep_set_enabled(regs, ep, Direction::Out, true);
961                    } else if !endpoint::is_out_logically_enabled(ep) {
962                        regs::ep_set_enabled(regs, ep, Direction::Out, false);
963                    }
964                }
965            }
966            Direction::Out => {
967                OUT_STATE[ep].reset();
968                OUT_STATE[ep].invalidated.store(true, Ordering::Relaxed);
969                endpoint::set_out_logically_enabled(ep, enabled);
970                regs::ep_rx_ctrl_write(regs, ep, false, EpRxResponse::NAK);
971                let rx_hw_en = if !enabled && ep_is_bidir(ep) && regs::ep_is_enabled(regs, ep, Direction::In) {
972                    true
973                } else {
974                    enabled
975                };
976                regs::ep_set_enabled(regs, ep, Direction::Out, rx_hw_en);
977            }
978        });
979
980        match ep_addr.direction() {
981            Direction::In => IN_STATE[ep].waker.wake(),
982            Direction::Out => OUT_STATE[ep].waker.wake(),
983        }
984    }
985
986    fn endpoint_set_stalled(&mut self, ep_addr: EndpointAddress, stalled: bool) {
987        set_endpoint_stalled::<T>(ep_addr, stalled);
988    }
989
990    fn endpoint_is_stalled(&mut self, ep_addr: EndpointAddress) -> bool {
991        is_endpoint_stalled(ep_addr)
992    }
993
994    async fn remote_wakeup(&mut self) -> Result<(), embassy_usb_driver::Unsupported> {
995        todo!()
996    }
997}
998
999pin_trait!(DpPin, Instance);
1000pin_trait!(DmPin, Instance);
1001
1002trait SealedInstance: RccPeripheral {
1003    fn regs() -> Regs;
1004}
1005
1006/// OTG_FS peripheral instance
1007#[allow(private_bounds)]
1008pub trait Instance: SealedInstance + PeripheralType + 'static {
1009    type Interrupt: interrupt::typelevel::Interrupt;
1010}
1011
1012#[cfg(otg_v2)]
1013foreach_peripheral!(
1014    (otg, $inst:ident) => {
1015        impl SealedInstance for peripherals::$inst {
1016            fn regs() -> Regs {
1017                // datasheet
1018                unsafe { Regs::from_ptr(crate::pac::OTG_FS.as_ptr()) }
1019            }
1020        }
1021
1022        impl Instance for peripherals::$inst {
1023            type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL;
1024        }
1025    };
1026);
1027
1028// H4's FS controller (`kind: usbfs`, version `h4`) is the same device block as
1029// the V4x7 OTG FS, addressed at its own base (RM §26).
1030#[cfg(usbfs_h4)]
1031foreach_peripheral!(
1032    (usbfs, $inst:ident) => {
1033        impl SealedInstance for peripherals::$inst {
1034            fn regs() -> Regs {
1035                unsafe { Regs::from_ptr(crate::pac::USBFS.as_ptr()) }
1036            }
1037        }
1038
1039        impl Instance for peripherals::$inst {
1040            type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL;
1041        }
1042    };
1043);
1044
1045// X035's FS controller (`kind: usb`, version `x0fs`) keeps the same device
1046// core in array-grouped registers; the CH32V20x/V303 one (`v2fs`) is the
1047// `otg_v2` block without its OTG registers.
1048#[cfg(any(usb_x0fs, usb_v2fs))]
1049foreach_peripheral!(
1050    (usb, $inst:ident) => {
1051        impl SealedInstance for peripherals::$inst {
1052            fn regs() -> Regs {
1053                unsafe { Regs::from_ptr(crate::pac::$inst.as_ptr()) }
1054            }
1055        }
1056
1057        impl Instance for peripherals::$inst {
1058            type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL;
1059        }
1060    };
1061);