1use 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
72const MAX_NR_EP: usize = 8;
74const EP_MAX_PACKET_SIZE: u16 = 64;
75
76pub(crate) struct EpDirState {
81 pub(crate) waker: AtomicWaker,
82 pub(crate) ready: AtomicBool,
83 pub(crate) len: AtomicU16,
84 pub(crate) stalled: AtomicBool,
86 pub(crate) armed: AtomicBool,
88 pub(crate) tog_reset: AtomicBool,
91 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
118fn 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
137fn 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
154fn 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
169pub(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 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 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
242static 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);
248static EP_BUF_ADDR: [AtomicUsize; MAX_NR_EP] = [ZERO_ADDR; MAX_NR_EP];
253static 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
287fn 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 #[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 #[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#[derive(Clone, Copy, Debug)]
313pub struct Config {
314 #[cfg(usb_x0fs)]
317 pub usb_phy_v33: bool,
318 #[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 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 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 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 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 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 _ => {
446 regs::clear_transfer(regs);
447 }
448 }
449 }
450
451 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 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 pub fn new_with_config(
483 _usb: Peri<'d, T>,
484 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 T::Interrupt::disable();
494
495 #[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 #[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 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 #[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 #[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 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); 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 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 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 if addr.direction() != dir {
653 return Err(EndpointAllocError);
654 }
655
656 let ep_num = addr.index();
657 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 regs::clear_ctrl(regs);
762
763 regs::enable_interrupts(regs);
765
766 regs::enter_device_mode(regs);
767
768 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 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 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 regs::ep_rx_ctrl_write(regs, 0, false, EpRxResponse::ACK);
860 regs::ep_tx_ctrl_write(regs, 0, false, EpTxResponse::NAK);
861
862 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 regs::set_pull_up(T::regs(), true);
881
882 regs::enable_port(T::regs());
884
885 self.bus_reset();
887 }
888
889 async fn disable(&mut self) {
890 regs::set_pull_up(T::regs(), false);
892 self.inited = false;
894 }
895
896 async fn poll(&mut self) -> embassy_usb_driver::Event {
897 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 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 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#[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 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#[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#[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);