Skip to main content

ch32_hal/
usbd.rs

1//! Universal Serial Bus Device(USBD)
2//!
3//! This peripheral is almost the same as usb_v1 in embassy-stm32.
4
5#![macro_use]
6
7use core::future::poll_fn;
8use core::marker::PhantomData;
9use core::sync::atomic::{AtomicBool, Ordering};
10use core::task::Poll;
11
12use embassy_sync::waitqueue::AtomicWaker;
13use embassy_usb_driver as driver;
14use embassy_usb_driver::{
15    Direction, EndpointAddress, EndpointAllocError, EndpointError, EndpointInfo, EndpointType, Event, Unsupported,
16};
17
18use crate::gpio::Speed;
19use crate::interrupt::typelevel::Interrupt;
20use crate::pac::usbd::regs;
21use crate::pac::usbd::vals::{EpType, Stat};
22use crate::pac::{EXTEND, USBRAM};
23use crate::peripheral::RccPeripheral;
24use crate::{interrupt, Peri, PeripheralType};
25
26/// Interrupt handler.
27pub struct InterruptHandler<T: Instance> {
28    _phantom: PhantomData<T>,
29}
30
31impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
32    unsafe fn on_interrupt() {
33        let regs = T::regs();
34
35        let istr = regs.istr().read();
36
37        if istr.susp() {
38            IRQ_SUSPEND.store(true, Ordering::Relaxed);
39            regs.cntr().modify(|w| {
40                w.set_fsusp(true);
41                w.set_lpmode(true);
42            });
43
44            // Write 0 to clear.
45            let mut clear = regs::Istr(!0);
46            clear.set_susp(false);
47            regs.istr().write_value(clear);
48
49            // Wake main thread.
50            BUS_WAKER.wake();
51        }
52
53        if istr.wkup() {
54            IRQ_RESUME.store(true, Ordering::Relaxed);
55            regs.cntr().modify(|w| {
56                w.set_fsusp(false);
57                w.set_lpmode(false);
58            });
59
60            // Write 0 to clear.
61            let mut clear = regs::Istr(!0);
62            clear.set_wkup(false);
63            regs.istr().write_value(clear);
64
65            // Wake main thread.
66            BUS_WAKER.wake();
67        }
68
69        if istr.reset() {
70            IRQ_RESET.store(true, Ordering::Relaxed);
71
72            // Write 0 to clear.
73            let mut clear = regs::Istr(!0);
74            clear.set_reset(false);
75            regs.istr().write_value(clear);
76
77            // Wake main thread.
78            BUS_WAKER.wake();
79        }
80
81        if istr.ctr() {
82            let index = istr.ep_id() as usize;
83            let mut epr = regs.epr(index).read();
84            if epr.ctr_rx() {
85                if index == 0 && epr.setup() {
86                    EP0_SETUP.store(true, Ordering::Relaxed);
87                    // CH32FV2x_V3xRM v2.5 Page 356:
88                    //    During the status phase of a control transfer, if an OUT transaction sent by the host to the device is being
89                    // performed, then the STATUS_OUT bit (EP_KIND in the USBD_EPRx register) should be set, only then if a
90                    // non-zero length of the transfer is received during the status phase data packets, will generate transmission
91                    // errors. After completing the status phase transfer, the application should clear the STATUS_OUT bit, and set
92                    // STAT_RX to ACK to indicate that it is ready to receive a new command request, and set STAT_TX to NAK
93                    // to not accept any data upload requests.
94
95                    // When handling a SETUP IN transaction, STATUS_OUT is set in data_in,
96                    // but it is not cleared after the STATUS transfer ends.
97                    // So if a SETUP OUT transaction immediately follows a SETUP IN transaction,
98                    // since STATUS_OUT remains set after the SETUP IN transaction completes,
99                    // the hardware will treat the subsequent OUT packet as a STATUS packet,
100                    // causing communication errors.
101                    epr.set_ep_kind(false);
102                }
103                EP_OUT_WAKERS[index].wake();
104            }
105            if epr.ctr_tx() {
106                EP_IN_WAKERS[index].wake();
107            }
108            epr.set_dtog_rx(false);
109            epr.set_dtog_tx(false);
110            epr.set_stat_rx(Stat::from_bits(0));
111            epr.set_stat_tx(Stat::from_bits(0));
112            epr.set_ctr_rx(!epr.ctr_rx());
113            epr.set_ctr_tx(!epr.ctr_tx());
114            regs.epr(index).write_value(epr);
115        }
116    }
117}
118
119const EP_COUNT: usize = 8;
120
121// for usbram_16x1_512
122const USBRAM_SIZE: usize = 512;
123const USBRAM_ALIGN: usize = 2;
124
125const NEW_AW: AtomicWaker = AtomicWaker::new();
126static BUS_WAKER: AtomicWaker = NEW_AW;
127static EP0_SETUP: AtomicBool = AtomicBool::new(false);
128static EP_IN_WAKERS: [AtomicWaker; EP_COUNT] = [NEW_AW; EP_COUNT];
129static EP_OUT_WAKERS: [AtomicWaker; EP_COUNT] = [NEW_AW; EP_COUNT];
130static IRQ_RESET: AtomicBool = AtomicBool::new(false);
131static IRQ_SUSPEND: AtomicBool = AtomicBool::new(false);
132static IRQ_RESUME: AtomicBool = AtomicBool::new(false);
133
134fn convert_type(t: EndpointType) -> EpType {
135    match t {
136        EndpointType::Bulk => EpType::BULK,
137        EndpointType::Control => EpType::CONTROL,
138        EndpointType::Interrupt => EpType::INTERRUPT,
139        EndpointType::Isochronous => EpType::ISO,
140    }
141}
142
143fn invariant(mut r: regs::Epr) -> regs::Epr {
144    r.set_ctr_rx(true); // don't clear
145    r.set_ctr_tx(true); // don't clear
146    r.set_dtog_rx(false); // don't toggle
147    r.set_dtog_tx(false); // don't toggle
148    r.set_stat_rx(Stat::from_bits(0));
149    r.set_stat_tx(Stat::from_bits(0));
150    r
151}
152
153fn align_len_up(len: u16) -> u16 {
154    ((len as usize + USBRAM_ALIGN - 1) / USBRAM_ALIGN * USBRAM_ALIGN) as u16
155}
156
157// Returns (actual_len, len_bits)
158fn calc_out_len(len: u16) -> (u16, u16) {
159    match len {
160        // NOTE: this could be 2..=62 with 16bit USBRAM, but not with 32bit. Limit it to 60 for simplicity.
161        2..=60 => (align_len_up(len), align_len_up(len) / 2 << 10),
162        61..=1024 => ((len + 31) / 32 * 32, (((len + 31) / 32 - 1) << 10) | 0x8000),
163        _ => panic!("invalid OUT length {}", len),
164    }
165}
166
167mod btable {
168    use super::*;
169
170    // Format: [ADDR0_TX, COUNT0_TX, ADDR0_RX, COUNT0_RX]
171
172    pub(super) fn write_in<T: Instance>(index: usize, addr: u16) {
173        USBRAM.mem(index * 4 + 0).write_value(addr);
174    }
175
176    pub(super) fn write_in_len<T: Instance>(index: usize, _addr: u16, len: u16) {
177        USBRAM.mem(index * 4 + 1).write_value(len);
178    }
179
180    pub(super) fn write_out<T: Instance>(index: usize, addr: u16, max_len_bits: u16) {
181        USBRAM.mem(index * 4 + 2).write_value(addr);
182        USBRAM.mem(index * 4 + 3).write_value(max_len_bits);
183    }
184
185    pub(super) fn read_out_len<T: Instance>(index: usize) -> u16 {
186        USBRAM.mem(index * 4 + 3).read()
187    }
188}
189
190struct EndpointBuffer<T: Instance> {
191    addr: u16,
192    len: u16,
193    _phantom: PhantomData<T>,
194}
195
196impl<T: Instance> EndpointBuffer<T> {
197    fn read(&mut self, buf: &mut [u8]) {
198        assert!(buf.len() <= self.len as usize);
199        for i in 0..(buf.len() + USBRAM_ALIGN - 1) / USBRAM_ALIGN {
200            let val = USBRAM.mem(self.addr as usize / USBRAM_ALIGN + i).read();
201            let n = USBRAM_ALIGN.min(buf.len() - i * USBRAM_ALIGN);
202            buf[i * USBRAM_ALIGN..][..n].copy_from_slice(&val.to_le_bytes()[..n]);
203        }
204    }
205
206    fn write(&mut self, buf: &[u8]) {
207        assert!(buf.len() <= self.len as usize);
208        for i in 0..(buf.len() + USBRAM_ALIGN - 1) / USBRAM_ALIGN {
209            let mut val = [0u8; USBRAM_ALIGN];
210            let n = USBRAM_ALIGN.min(buf.len() - i * USBRAM_ALIGN);
211            val[..n].copy_from_slice(&buf[i * USBRAM_ALIGN..][..n]);
212
213            let val = u16::from_le_bytes(val);
214            USBRAM.mem(self.addr as usize / USBRAM_ALIGN + i).write_value(val);
215        }
216    }
217}
218
219#[derive(Debug, Clone, Copy)]
220// #[cfg_attr(feature = "defmt", derive(defmt::Format))]
221struct EndpointData {
222    ep_type: EndpointType, // only valid if used_in || used_out
223    used_in: bool,
224    used_out: bool,
225}
226
227/// USB driver.
228pub struct Driver<'d, T: Instance> {
229    phantom: PhantomData<&'d mut T>,
230    alloc: [EndpointData; EP_COUNT],
231    ep_mem_free: u16, // first free address in EP mem, in bytes.
232}
233
234impl<'d, T: Instance> Driver<'d, T> {
235    /// Create a new USB driver.
236    pub fn new(
237        _usb: Peri<'d, T>,
238        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
239        dp: Peri<'d, impl DpPin<T, 0>>,
240        dm: Peri<'d, impl DmPin<T, 0>>,
241    ) -> Self {
242        {
243            //dp.set_as_af_output(crate::gpio::AFType::OutputPushPull, Speed::High);
244            //dm.set_as_af_output(crate::gpio::AFType::OutputPushPull, Speed::High);
245            // 一旦使能了 USBD 模块,作为 UDP 和 UPM 的 GPIO 口会自动连接到内部 USB 收发器,而断开其 GPIO 外设的端口设置。
246            // 所以推荐 GPIO 口配置为推挽方式输出低电平,防止在未开启 USBD 功能前,出现 端口不确定状态或连接 PC 主机时,提前通知有 USB 设备接入。
247            dp.set_as_output(Speed::High);
248            dp.set_low();
249            dm.set_as_output(Speed::High);
250            dm.set_low();
251        }
252
253        // init
254        {
255            // FV2x_V3x
256            EXTEND.ctr().modify(|w| {
257                w.set_usbdpu(true);
258                w.set_usbdls(false); // full speed
259            });
260
261            T::enable_and_reset();
262        }
263
264        let regs = T::regs();
265
266        regs.cntr().write(|w| {
267            w.set_pdwn(false);
268            w.set_fres(true);
269        });
270
271        crate::internal::delay::block_for_us(100_000);
272
273        regs.btable().write(|w| w.set_btable(0));
274
275        // Initialize the bus so that it signals that power is available
276        BUS_WAKER.wake();
277
278        Self {
279            phantom: PhantomData,
280            alloc: [EndpointData {
281                ep_type: EndpointType::Bulk,
282                used_in: false,
283                used_out: false,
284            }; EP_COUNT],
285            ep_mem_free: EP_COUNT as u16 * 8, // for each EP, 4 regs, so 8 bytes
286        }
287    }
288
289    fn alloc_ep_mem(&mut self, len: u16) -> u16 {
290        assert!(len as usize % USBRAM_ALIGN == 0);
291        let addr = self.ep_mem_free;
292        if addr + len > USBRAM_SIZE as _ {
293            panic!("Endpoint memory full");
294        }
295        self.ep_mem_free += len;
296        addr
297    }
298
299    fn is_endpoint_available<D: Dir>(&self, index: usize, ep_type: EndpointType) -> bool {
300        if index == 0 && ep_type != EndpointType::Control {
301            return false; // EP0 is reserved for control
302        }
303
304        let ep = match self.alloc.get(index) {
305            Some(ep) => ep,
306            None => return false,
307        };
308
309        let used = ep.used_out || ep.used_in;
310
311        if used && ep.ep_type == EndpointType::Isochronous {
312            // Isochronous endpoints are always double-buffered.
313            // Their corresponding endpoint/channel registers are forced to be unidirectional.
314            // Do not reuse this index.
315            // FIXME: Bulk endpoints can be double buffered, but are not in the current implementation.
316            return false;
317        }
318
319        let used_dir = match D::dir() {
320            Direction::Out => ep.used_out,
321            Direction::In => ep.used_in,
322        };
323
324        !used || (ep.ep_type == ep_type && !used_dir)
325    }
326
327    fn alloc_endpoint<D: Dir>(
328        &mut self,
329        ep_type: EndpointType,
330        ep_addr: Option<EndpointAddress>,
331        max_packet_size: u16,
332        interval_ms: u8,
333    ) -> Result<Endpoint<'d, T, D>, driver::EndpointAllocError> {
334        let index = if let Some(addr) = ep_addr {
335            // Use the specified endpoint address
336            self.is_endpoint_available::<D>(addr.index(), ep_type)
337                .then_some(addr.index())
338        } else {
339            // Find any available endpoint
340            (0..self.alloc.len()).find(|&i| self.is_endpoint_available::<D>(i, ep_type))
341        };
342
343        let (index, ep) = match index {
344            Some(i) => (i, &mut self.alloc[i]),
345            None => return Err(EndpointAllocError),
346        };
347
348        ep.ep_type = ep_type;
349
350        let buf = match D::dir() {
351            Direction::Out => {
352                assert!(!ep.used_out);
353                ep.used_out = true;
354
355                let (len, len_bits) = calc_out_len(max_packet_size);
356                let addr = self.alloc_ep_mem(len);
357
358                btable::write_out::<T>(index, addr, len_bits);
359
360                EndpointBuffer {
361                    addr,
362                    len,
363                    _phantom: PhantomData,
364                }
365            }
366            Direction::In => {
367                assert!(!ep.used_in);
368                ep.used_in = true;
369
370                let len = align_len_up(max_packet_size);
371                let addr = self.alloc_ep_mem(len);
372
373                // ep_in_len is written when actually TXing packets.
374                btable::write_in::<T>(index, addr);
375
376                EndpointBuffer {
377                    addr,
378                    len,
379                    _phantom: PhantomData,
380                }
381            }
382        };
383
384        Ok(Endpoint {
385            _phantom: PhantomData,
386            info: EndpointInfo {
387                addr: EndpointAddress::from_parts(index, D::dir()),
388                ep_type,
389                max_packet_size,
390                interval_ms,
391                max_burst: 0,
392            },
393            buf,
394        })
395    }
396}
397
398impl<'d, T: Instance> driver::Driver<'d> for Driver<'d, T> {
399    type EndpointOut = Endpoint<'d, T, Out>;
400    type EndpointIn = Endpoint<'d, T, In>;
401    type ControlPipe = ControlPipe<'d, T>;
402    type Bus = Bus<'d, T>;
403
404    fn alloc_endpoint_in(
405        &mut self,
406        config: &driver::EndpointConfig,
407    ) -> Result<Self::EndpointIn, driver::EndpointAllocError> {
408        self.alloc_endpoint(config.ep_type, config.addr, config.max_packet_size, config.interval_ms)
409    }
410
411    fn alloc_endpoint_out(
412        &mut self,
413        config: &driver::EndpointConfig,
414    ) -> Result<Self::EndpointOut, driver::EndpointAllocError> {
415        self.alloc_endpoint(config.ep_type, config.addr, config.max_packet_size, config.interval_ms)
416    }
417
418    fn start(mut self, control_max_packet_size: u16) -> (Self::Bus, Self::ControlPipe) {
419        let ep_out = self
420            .alloc_endpoint(EndpointType::Control, None, control_max_packet_size, 0)
421            .unwrap();
422        let ep_in = self
423            .alloc_endpoint(EndpointType::Control, None, control_max_packet_size, 0)
424            .unwrap();
425        assert_eq!(ep_out.info.addr.index(), 0);
426        assert_eq!(ep_in.info.addr.index(), 0);
427
428        let regs = T::regs();
429
430        regs.cntr().write(|w| {
431            w.set_pdwn(false);
432            w.set_fres(false);
433            w.set_resetm(true);
434            w.set_suspm(true);
435            w.set_wkupm(true);
436            w.set_ctrm(true);
437        });
438
439        unsafe {
440            T::Interrupt::unpend();
441            T::Interrupt::enable();
442        }
443
444        let mut ep_types = [EpType::BULK; EP_COUNT - 1];
445        for i in 1..EP_COUNT {
446            ep_types[i - 1] = convert_type(self.alloc[i].ep_type);
447        }
448
449        (
450            Bus {
451                phantom: PhantomData,
452                ep_types,
453                inited: false,
454            },
455            ControlPipe {
456                _phantom: PhantomData,
457                max_packet_size: control_max_packet_size,
458                ep_out,
459                ep_in,
460            },
461        )
462    }
463}
464
465/// USB bus.
466pub struct Bus<'d, T: Instance> {
467    phantom: PhantomData<&'d mut T>,
468    ep_types: [EpType; EP_COUNT - 1],
469    inited: bool,
470}
471
472impl<'d, T: Instance> driver::Bus for Bus<'d, T> {
473    async fn poll(&mut self) -> Event {
474        poll_fn(move |cx| {
475            BUS_WAKER.register(cx.waker());
476
477            // TODO: implement VBUS detection.
478            if !self.inited {
479                self.inited = true;
480                return Poll::Ready(Event::PowerDetected);
481            }
482
483            let regs = T::regs();
484
485            if IRQ_RESUME.load(Ordering::Acquire) {
486                IRQ_RESUME.store(false, Ordering::Relaxed);
487                return Poll::Ready(Event::Resume);
488            }
489
490            if IRQ_RESET.load(Ordering::Acquire) {
491                IRQ_RESET.store(false, Ordering::Relaxed);
492
493                regs.daddr().write(|w| {
494                    w.set_ef(true);
495                    w.set_add(0);
496                });
497
498                regs.epr(0).write(|w| {
499                    w.set_ep_type(EpType::CONTROL);
500                    w.set_stat_rx(Stat::NAK);
501                    w.set_stat_tx(Stat::NAK);
502                });
503
504                for i in 1..EP_COUNT {
505                    regs.epr(i).write(|w| {
506                        w.set_ea(i as _);
507                        w.set_ep_type(self.ep_types[i - 1]);
508                    })
509                }
510
511                for w in &EP_IN_WAKERS {
512                    w.wake()
513                }
514                for w in &EP_OUT_WAKERS {
515                    w.wake()
516                }
517
518                return Poll::Ready(Event::Reset);
519            }
520
521            if IRQ_SUSPEND.load(Ordering::Acquire) {
522                IRQ_SUSPEND.store(false, Ordering::Relaxed);
523                return Poll::Ready(Event::Suspend);
524            }
525
526            Poll::Pending
527        })
528        .await
529    }
530
531    fn endpoint_set_stalled(&mut self, ep_addr: EndpointAddress, stalled: bool) {
532        set_endpoint_stalled::<T>(ep_addr, stalled);
533    }
534
535    fn endpoint_is_stalled(&mut self, ep_addr: EndpointAddress) -> bool {
536        is_endpoint_stalled::<T>(ep_addr)
537    }
538
539    fn endpoint_set_enabled(&mut self, ep_addr: EndpointAddress, enabled: bool) {
540        // This can race, so do a retry loop.
541        let reg = T::regs().epr(ep_addr.index() as _);
542        match ep_addr.direction() {
543            Direction::In => {
544                loop {
545                    let want_stat = match enabled {
546                        false => Stat::DISABLED,
547                        true => Stat::NAK,
548                    };
549                    let r = reg.read();
550                    if r.stat_tx() == want_stat {
551                        break;
552                    }
553                    let mut w = invariant(r);
554                    w.set_stat_tx(Stat::from_bits(r.stat_tx().to_bits() ^ want_stat.to_bits()));
555                    reg.write_value(w);
556                }
557                EP_IN_WAKERS[ep_addr.index()].wake();
558            }
559            Direction::Out => {
560                loop {
561                    let want_stat = match enabled {
562                        false => Stat::DISABLED,
563                        true => Stat::VALID,
564                    };
565                    let r = reg.read();
566                    if r.stat_rx() == want_stat {
567                        break;
568                    }
569                    let mut w = invariant(r);
570                    w.set_stat_rx(Stat::from_bits(r.stat_rx().to_bits() ^ want_stat.to_bits()));
571                    reg.write_value(w);
572                }
573                EP_OUT_WAKERS[ep_addr.index()].wake();
574            }
575        }
576    }
577
578    async fn enable(&mut self) {
579        // `new` already set the pull-up for the first enable; set it again after a `disable`.
580        // `EXTEND.CTR` also holds other peripherals' settings (the V208's Ethernet PHY).
581        critical_section::with(|_| EXTEND.ctr().modify(|w| w.set_usbdpu(true)));
582    }
583
584    async fn disable(&mut self) {
585        // Detach from the bus: drop the D+ pull-up, the bit WCH's `USB_Port_Set(DISABLE, DISABLE)` clears.
586        critical_section::with(|_| EXTEND.ctr().modify(|w| w.set_usbdpu(false)));
587        // embassy-usb enables the bus again only on `PowerDetected`, which `poll` fakes once.
588        self.inited = false;
589    }
590
591    async fn remote_wakeup(&mut self) -> Result<(), Unsupported> {
592        Err(Unsupported)
593    }
594}
595
596/// Sets or clears the STALL handshake of an endpoint, for the bus and the
597/// endpoint alike.
598fn set_endpoint_stalled<T: Instance>(ep_addr: EndpointAddress, stalled: bool) {
599    // This can race, so do a retry loop.
600    let reg = T::regs().epr(ep_addr.index() as _);
601    match ep_addr.direction() {
602        Direction::In => {
603            loop {
604                let r = reg.read();
605                match r.stat_tx() {
606                    Stat::DISABLED => break, // if disabled, stall does nothing.
607                    Stat::STALL => break,    // done!
608                    _ => {
609                        let want_stat = match stalled {
610                            false => Stat::NAK,
611                            true => Stat::STALL,
612                        };
613                        let mut w = invariant(r);
614                        w.set_stat_tx(Stat::from_bits(r.stat_tx().to_bits() ^ want_stat.to_bits()));
615                        reg.write_value(w);
616                    }
617                }
618            }
619            EP_IN_WAKERS[ep_addr.index()].wake();
620        }
621        Direction::Out => {
622            loop {
623                let r = reg.read();
624                match r.stat_rx() {
625                    Stat::DISABLED => break, // if disabled, stall does nothing.
626                    Stat::STALL => break,    // done!
627                    _ => {
628                        let want_stat = match stalled {
629                            false => Stat::VALID,
630                            true => Stat::STALL,
631                        };
632                        let mut w = invariant(r);
633                        w.set_stat_rx(Stat::from_bits(r.stat_rx().to_bits() ^ want_stat.to_bits()));
634                        reg.write_value(w);
635                    }
636                }
637            }
638            EP_OUT_WAKERS[ep_addr.index()].wake();
639        }
640    }
641}
642
643fn is_endpoint_stalled<T: Instance>(ep_addr: EndpointAddress) -> bool {
644    let regs = T::regs();
645    let epr = regs.epr(ep_addr.index() as _).read();
646    match ep_addr.direction() {
647        Direction::In => epr.stat_tx() == Stat::STALL,
648        Direction::Out => epr.stat_rx() == Stat::STALL,
649    }
650}
651
652trait Dir {
653    fn dir() -> Direction;
654}
655
656/// Marker type for the "IN" direction.
657pub enum In {}
658impl Dir for In {
659    fn dir() -> Direction {
660        Direction::In
661    }
662}
663
664/// Marker type for the "OUT" direction.
665pub enum Out {}
666impl Dir for Out {
667    fn dir() -> Direction {
668        Direction::Out
669    }
670}
671
672/// USB endpoint.
673pub struct Endpoint<'d, T: Instance, D> {
674    _phantom: PhantomData<(&'d mut T, D)>,
675    info: EndpointInfo,
676    buf: EndpointBuffer<T>,
677}
678
679impl<'d, T: Instance, D> Endpoint<'d, T, D> {
680    fn write_data(&mut self, buf: &[u8]) {
681        let index = self.info.addr.index();
682        self.buf.write(buf);
683        btable::write_in_len::<T>(index, self.buf.addr, buf.len() as _);
684    }
685
686    fn read_data(&mut self, buf: &mut [u8]) -> Result<usize, EndpointError> {
687        let index = self.info.addr.index();
688        let rx_len = btable::read_out_len::<T>(index) as usize & 0x3FF;
689        if rx_len > buf.len() {
690            return Err(EndpointError::BufferOverflow);
691        }
692        self.buf.read(&mut buf[..rx_len]);
693        Ok(rx_len)
694    }
695}
696
697impl<'d, T: Instance> driver::Endpoint for Endpoint<'d, T, In> {
698    fn info(&self) -> &EndpointInfo {
699        &self.info
700    }
701
702    async fn wait_enabled(&mut self) {
703        let index = self.info.addr.index();
704        poll_fn(|cx| {
705            EP_IN_WAKERS[index].register(cx.waker());
706            let regs = T::regs();
707            if regs.epr(index).read().stat_tx() == Stat::DISABLED {
708                Poll::Pending
709            } else {
710                Poll::Ready(())
711            }
712        })
713        .await;
714    }
715
716    fn set_stall(&mut self, stalled: bool) -> Result<(), Unsupported> {
717        set_endpoint_stalled::<T>(self.info.addr, stalled);
718        Ok(())
719    }
720
721    fn is_stalled(&self) -> Result<bool, Unsupported> {
722        Ok(is_endpoint_stalled::<T>(self.info.addr))
723    }
724}
725
726impl<'d, T: Instance> driver::Endpoint for Endpoint<'d, T, Out> {
727    fn info(&self) -> &EndpointInfo {
728        &self.info
729    }
730
731    async fn wait_enabled(&mut self) {
732        let index = self.info.addr.index();
733        poll_fn(|cx| {
734            EP_OUT_WAKERS[index].register(cx.waker());
735            let regs = T::regs();
736            if regs.epr(index).read().stat_rx() == Stat::DISABLED {
737                Poll::Pending
738            } else {
739                Poll::Ready(())
740            }
741        })
742        .await;
743    }
744
745    fn set_stall(&mut self, stalled: bool) -> Result<(), Unsupported> {
746        set_endpoint_stalled::<T>(self.info.addr, stalled);
747        Ok(())
748    }
749
750    fn is_stalled(&self) -> Result<bool, Unsupported> {
751        Ok(is_endpoint_stalled::<T>(self.info.addr))
752    }
753}
754
755impl<'d, T: Instance> driver::EndpointOut for Endpoint<'d, T, Out> {
756    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, EndpointError> {
757        let index = self.info.addr.index();
758        let stat = poll_fn(|cx| {
759            EP_OUT_WAKERS[index].register(cx.waker());
760            let regs = T::regs();
761            let stat = regs.epr(index).read().stat_rx();
762            if matches!(stat, Stat::NAK | Stat::DISABLED) {
763                Poll::Ready(stat)
764            } else {
765                Poll::Pending
766            }
767        })
768        .await;
769
770        if stat == Stat::DISABLED {
771            return Err(EndpointError::Disabled);
772        }
773
774        let rx_len = self.read_data(buf)?;
775
776        let regs = T::regs();
777        regs.epr(index).write(|w| {
778            w.set_ep_type(convert_type(self.info.ep_type));
779            w.set_ea(self.info.addr.index() as _);
780            w.set_stat_rx(Stat::from_bits(Stat::NAK.to_bits() ^ Stat::VALID.to_bits()));
781            w.set_stat_tx(Stat::from_bits(0));
782            w.set_ctr_rx(true); // don't clear
783            w.set_ctr_tx(true); // don't clear
784        });
785
786        Ok(rx_len)
787    }
788}
789
790impl<'d, T: Instance> driver::EndpointIn for Endpoint<'d, T, In> {
791    async fn write(&mut self, buf: &[u8]) -> Result<(), EndpointError> {
792        if buf.len() > self.info.max_packet_size as usize {
793            return Err(EndpointError::BufferOverflow);
794        }
795
796        let index = self.info.addr.index();
797
798        let stat = poll_fn(|cx| {
799            EP_IN_WAKERS[index].register(cx.waker());
800            let regs = T::regs();
801            let stat = regs.epr(index).read().stat_tx();
802            if matches!(stat, Stat::NAK | Stat::DISABLED) {
803                Poll::Ready(stat)
804            } else {
805                Poll::Pending
806            }
807        })
808        .await;
809
810        if stat == Stat::DISABLED {
811            return Err(EndpointError::Disabled);
812        }
813
814        self.write_data(buf);
815
816        let regs = T::regs();
817        regs.epr(index).write(|w| {
818            w.set_ep_type(convert_type(self.info.ep_type));
819            w.set_ea(self.info.addr.index() as _);
820            w.set_stat_tx(Stat::from_bits(Stat::NAK.to_bits() ^ Stat::VALID.to_bits()));
821            w.set_stat_rx(Stat::from_bits(0));
822            w.set_ctr_rx(true); // don't clear
823            w.set_ctr_tx(true); // don't clear
824        });
825
826        Ok(())
827    }
828}
829
830/// USB control pipe.
831pub struct ControlPipe<'d, T: Instance> {
832    _phantom: PhantomData<&'d mut T>,
833    max_packet_size: u16,
834    ep_in: Endpoint<'d, T, In>,
835    ep_out: Endpoint<'d, T, Out>,
836}
837
838impl<'d, T: Instance> driver::ControlPipe for ControlPipe<'d, T> {
839    fn max_packet_size(&self) -> usize {
840        usize::from(self.max_packet_size)
841    }
842
843    async fn setup(&mut self) -> [u8; 8] {
844        loop {
845            poll_fn(|cx| {
846                EP_OUT_WAKERS[0].register(cx.waker());
847                if EP0_SETUP.load(Ordering::Relaxed) {
848                    Poll::Ready(())
849                } else {
850                    Poll::Pending
851                }
852            })
853            .await;
854
855            let mut buf = [0; 8];
856            let rx_len = self.ep_out.read_data(&mut buf);
857            if rx_len != Ok(8) {
858                continue;
859            }
860
861            EP0_SETUP.store(false, Ordering::Relaxed);
862
863            return buf;
864        }
865    }
866
867    async fn data_out(&mut self, buf: &mut [u8], first: bool, last: bool) -> Result<usize, EndpointError> {
868        let regs = T::regs();
869
870        // When a SETUP is received, Stat/Stat is set to NAK.
871        // On first transfer, we must set Stat=VALID, to get the OUT data stage.
872        // We want Stat=STALL so that the host gets a STALL if it switches to the status
873        // stage too soon, except in the last transfer we set Stat=NAK so that it waits
874        // for the status stage, which we will ACK or STALL later.
875        if first || last {
876            let mut stat_rx = 0;
877            let mut stat_tx = 0;
878            if first {
879                // change NAK -> VALID
880                stat_rx ^= Stat::NAK.to_bits() ^ Stat::VALID.to_bits();
881                stat_tx ^= Stat::NAK.to_bits() ^ Stat::STALL.to_bits();
882            }
883            if last {
884                // change STALL -> VALID
885                stat_tx ^= Stat::STALL.to_bits() ^ Stat::NAK.to_bits();
886            }
887            // Note: if this is the first AND last transfer, the above effectively
888            // changes stat_tx like NAK -> NAK, so noop.
889            regs.epr(0).write(|w| {
890                w.set_ep_type(EpType::CONTROL);
891                w.set_stat_rx(Stat::from_bits(stat_rx));
892                w.set_stat_tx(Stat::from_bits(stat_tx));
893                w.set_ctr_rx(true); // don't clear
894                w.set_ctr_tx(true); // don't clear
895            });
896        }
897
898        poll_fn(|cx| {
899            EP_OUT_WAKERS[0].register(cx.waker());
900            let regs = T::regs();
901            if regs.epr(0).read().stat_rx() == Stat::NAK {
902                Poll::Ready(())
903            } else {
904                Poll::Pending
905            }
906        })
907        .await;
908
909        if EP0_SETUP.load(Ordering::Relaxed) {
910            return Err(EndpointError::Disabled);
911        }
912
913        let rx_len = self.ep_out.read_data(buf)?;
914
915        regs.epr(0).write(|w| {
916            w.set_ep_type(EpType::CONTROL);
917            w.set_stat_rx(Stat::from_bits(match last {
918                // If last, set STAT_RX=STALL.
919                true => Stat::NAK.to_bits() ^ Stat::STALL.to_bits(),
920                // Otherwise, set STAT_RX=VALID, to allow the host to send the next packet.
921                false => Stat::NAK.to_bits() ^ Stat::VALID.to_bits(),
922            }));
923            w.set_ctr_rx(true); // don't clear
924            w.set_ctr_tx(true); // don't clear
925        });
926
927        Ok(rx_len)
928    }
929
930    async fn data_in(&mut self, data: &[u8], first: bool, last: bool) -> Result<(), EndpointError> {
931        if data.len() > self.ep_in.info.max_packet_size as usize {
932            return Err(EndpointError::BufferOverflow);
933        }
934
935        let regs = T::regs();
936
937        // When a SETUP is received, Stat is set to NAK.
938        // We want it to be STALL in non-last transfers.
939        // We want it to be VALID in last transfer, so the HW does the status stage.
940        if first || last {
941            let mut stat_rx = 0;
942            if first {
943                // change NAK -> STALL
944                stat_rx ^= Stat::NAK.to_bits() ^ Stat::STALL.to_bits();
945            }
946            if last {
947                // change STALL -> VALID
948                stat_rx ^= Stat::STALL.to_bits() ^ Stat::VALID.to_bits();
949            }
950            // Note: if this is the first AND last transfer, the above effectively
951            // does a change of NAK -> VALID.
952            regs.epr(0).write(|w| {
953                w.set_ep_type(EpType::CONTROL);
954                w.set_stat_rx(Stat::from_bits(stat_rx));
955                w.set_ep_kind(last); // set OUT_STATUS if last.
956                w.set_ctr_rx(true); // don't clear
957                w.set_ctr_tx(true); // don't clear
958            });
959        }
960
961        poll_fn(|cx| {
962            EP_IN_WAKERS[0].register(cx.waker());
963            EP_OUT_WAKERS[0].register(cx.waker());
964            let regs = T::regs();
965            if regs.epr(0).read().stat_tx() == Stat::NAK {
966                Poll::Ready(())
967            } else {
968                Poll::Pending
969            }
970        })
971        .await;
972
973        if EP0_SETUP.load(Ordering::Relaxed) {
974            return Err(EndpointError::Disabled);
975        }
976
977        self.ep_in.write_data(data);
978
979        let regs = T::regs();
980        regs.epr(0).write(|w| {
981            w.set_ep_type(EpType::CONTROL);
982            w.set_stat_tx(Stat::from_bits(Stat::NAK.to_bits() ^ Stat::VALID.to_bits()));
983            w.set_ep_kind(last); // set OUT_STATUS if last.
984            w.set_ctr_rx(true); // don't clear
985            w.set_ctr_tx(true); // don't clear
986        });
987
988        Ok(())
989    }
990
991    async fn accept(&mut self) {
992        let regs = T::regs();
993
994        self.ep_in.write_data(&[]);
995
996        // Set OUT=stall, IN=accept
997        let epr = regs.epr(0).read();
998        regs.epr(0).write(|w| {
999            w.set_ep_type(EpType::CONTROL);
1000            w.set_stat_rx(Stat::from_bits(epr.stat_rx().to_bits() ^ Stat::STALL.to_bits()));
1001            w.set_stat_tx(Stat::from_bits(epr.stat_tx().to_bits() ^ Stat::VALID.to_bits()));
1002            w.set_ctr_rx(true); // don't clear
1003            w.set_ctr_tx(true); // don't clear
1004        });
1005
1006        // Wait is needed, so that we don't set the address too soon, breaking the status stage.
1007        // (embassy-usb sets the address after accept() returns)
1008        poll_fn(|cx| {
1009            EP_IN_WAKERS[0].register(cx.waker());
1010            let regs = T::regs();
1011            if regs.epr(0).read().stat_tx() == Stat::NAK {
1012                Poll::Ready(())
1013            } else {
1014                Poll::Pending
1015            }
1016        })
1017        .await;
1018    }
1019
1020    async fn reject(&mut self) {
1021        let regs = T::regs();
1022
1023        // Set IN+OUT to stall
1024        let epr = regs.epr(0).read();
1025        regs.epr(0).write(|w| {
1026            w.set_ep_type(EpType::CONTROL);
1027            w.set_stat_rx(Stat::from_bits(epr.stat_rx().to_bits() ^ Stat::STALL.to_bits()));
1028            w.set_stat_tx(Stat::from_bits(epr.stat_tx().to_bits() ^ Stat::STALL.to_bits()));
1029            w.set_ctr_rx(true); // don't clear
1030            w.set_ctr_tx(true); // don't clear
1031        });
1032    }
1033
1034    async fn accept_set_address(&mut self, addr: u8) {
1035        self.accept().await;
1036
1037        let regs = T::regs();
1038        regs.daddr().write(|w| {
1039            w.set_ef(true);
1040            w.set_add(addr);
1041        });
1042    }
1043}
1044
1045trait SealedInstance {
1046    fn regs() -> crate::pac::usbd::Usb;
1047}
1048
1049/// USB instance trait.
1050#[allow(private_bounds)]
1051pub trait Instance: SealedInstance + RccPeripheral + PeripheralType + 'static {
1052    /// Interrupt for this USB instance.
1053    type Interrupt: interrupt::typelevel::Interrupt;
1054}
1055
1056// Internal PHY pins
1057pin_trait!(DpPin, Instance);
1058pin_trait!(DmPin, Instance);
1059
1060foreach_interrupt!(
1061    ($inst:ident, usbd, $block:ident, LP, $irq:ident) => {
1062        impl SealedInstance for crate::peripherals::$inst {
1063            fn regs() -> crate::pac::usbd::Usb {
1064                crate::pac::$inst
1065            }
1066        }
1067
1068        impl Instance for crate::peripherals::$inst {
1069            type Interrupt = crate::interrupt::typelevel::$irq;
1070        }
1071    };
1072);