Skip to main content

ch32_hal/usbhs/
endpoint.rs

1use core::future::poll_fn;
2use core::marker::PhantomData;
3use core::sync::atomic::Ordering;
4use core::task::Poll;
5
6use ch32_metapac::usbhs::vals::{EpRxResponse, EpTxResponse};
7use embassy_usb_driver::{Direction, EndpointError, EndpointIn, EndpointInfo, EndpointOut, EndpointType, Unsupported};
8
9use super::{is_endpoint_stalled, iso_in_enqueue, set_endpoint_stalled, state, EpState, Instance};
10use crate::usb::{Dir, EndpointData, In, Out};
11
12pub struct Endpoint<'d, T: Instance, D: Dir, const SIZE: usize> {
13    _phantom: PhantomData<(&'d mut T, D)>,
14    info: EndpointInfo,
15    pub(crate) data: EndpointData<'d, SIZE>,
16}
17
18impl<'d, T: Instance, D: Dir, const SIZE: usize> Endpoint<'d, T, D, SIZE> {
19    pub(crate) fn new(info: EndpointInfo, data: EndpointData<'d, SIZE>) -> Self {
20        let index = info.addr.index();
21        T::dregs().ep_max_len(index).write(|v| v.set_len(info.max_packet_size));
22        if info.ep_type != EndpointType::Control {
23            match info.addr.direction() {
24                Direction::Out => {
25                    T::dregs().ep_rx_dma(index - 1).write_value(data.buffer.addr() as u32);
26                }
27                Direction::In => {
28                    T::dregs().ep_tx_dma(index - 1).write_value(data.buffer.addr() as u32);
29                }
30            }
31        }
32        Self {
33            _phantom: PhantomData,
34            info,
35            data,
36        }
37    }
38
39    fn state(&self) -> &'static EpState {
40        state(self.info.addr)
41    }
42
43    async fn wait_enabled_internal(&mut self) {
44        poll_fn(|ctx| {
45            self.state().waker.register(ctx.waker());
46            if self.is_enabled() {
47                Poll::Ready(())
48            } else {
49                Poll::Pending
50            }
51        })
52        .await;
53    }
54
55    fn is_enabled(&self) -> bool {
56        match self.info.addr.direction() {
57            Direction::Out => T::dregs().ep_config().read().r_en(self.info.addr.index() - 1),
58            Direction::In => T::dregs().ep_config().read().t_en(self.info.addr.index() - 1),
59        }
60    }
61}
62
63impl<'d, T: Instance, D: Dir, const SIZE: usize> embassy_usb_driver::Endpoint for Endpoint<'d, T, D, SIZE> {
64    fn info(&self) -> &EndpointInfo {
65        &self.info
66    }
67
68    async fn wait_enabled(&mut self) {
69        self.wait_enabled_internal().await
70    }
71
72    fn set_stall(&mut self, stalled: bool) -> Result<(), Unsupported> {
73        set_endpoint_stalled::<T>(self.info.addr, stalled);
74        Ok(())
75    }
76
77    fn is_stalled(&self) -> Result<bool, Unsupported> {
78        Ok(is_endpoint_stalled::<T>(self.info.addr))
79    }
80}
81
82impl<'d, T: Instance, const SIZE: usize> EndpointOut for Endpoint<'d, T, Out, SIZE> {
83    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, EndpointError> {
84        if !self.is_enabled() {
85            return Err(EndpointError::Disabled);
86        }
87        // The buffer must be at least as large as the endpoint's max_packet_size
88        // to avoid potential buffer overflow when receiving data
89        if buf.len() < self.data.max_packet_size as usize {
90            return Err(EndpointError::BufferOverflow);
91        }
92
93        let s = self.state();
94        let index = self.info.addr.index();
95
96        if s.iso.load(Ordering::Relaxed) {
97            // drain the ring the interrupt fills
98            return poll_fn(|ctx| {
99                s.waker.register(ctx.waker());
100                if !self.is_enabled() {
101                    return Poll::Ready(Err(EndpointError::Disabled));
102                }
103                match super::iso_out_take(index, |p| {
104                    let len = p.len().min(buf.len());
105                    buf[..len].copy_from_slice(&p[..len]);
106                    len
107                }) {
108                    Some(len) => Poll::Ready(Ok(len)),
109                    None => Poll::Pending,
110                }
111            })
112            .await;
113        }
114
115        // arm: ACK until the interrupt has one packet, then NAK until the next read
116        critical_section::with(|_| {
117            if !s.ready.load(Ordering::Acquire) {
118                s.armed.store(true, Ordering::Relaxed);
119                T::dregs()
120                    .ep_rx_ctrl(index)
121                    .modify(|v| v.set_mask_uep_r_res(EpRxResponse::ACK));
122            }
123        });
124
125        poll_fn(|ctx| {
126            s.waker.register(ctx.waker());
127            if s.ready.load(Ordering::Acquire) {
128                s.ready.store(false, Ordering::Relaxed);
129                let len = s.len.load(Ordering::Relaxed) as usize;
130                if len > buf.len() {
131                    return Poll::Ready(Err(EndpointError::BufferOverflow));
132                }
133                self.data.buffer.read_volatile(&mut buf[..len]);
134                Poll::Ready(Ok(len))
135            } else if !self.is_enabled() {
136                Poll::Ready(Err(EndpointError::Disabled))
137            } else {
138                Poll::Pending
139            }
140        })
141        .await
142    }
143}
144
145impl<'d, T: Instance, const SIZE: usize> EndpointIn for Endpoint<'d, T, In, SIZE> {
146    async fn write(&mut self, buf: &[u8]) -> Result<(), EndpointError> {
147        if !self.is_enabled() {
148            return Err(EndpointError::Disabled);
149        }
150        if buf.len() > self.data.max_packet_size as usize {
151            return Err(EndpointError::BufferOverflow);
152        }
153
154        let s = self.state();
155        let index = self.info.addr.index();
156
157        if s.iso.load(Ordering::Relaxed) {
158            // queue it; wait while the ring is full
159            return poll_fn(|ctx| {
160                s.waker.register(ctx.waker());
161                if !self.is_enabled() {
162                    return Poll::Ready(Err(EndpointError::Disabled));
163                }
164                if iso_in_enqueue(index, buf) {
165                    Poll::Ready(Ok(()))
166                } else {
167                    Poll::Pending
168                }
169            })
170            .await;
171        }
172
173        s.ready.store(false, Ordering::Relaxed);
174        self.data.buffer.write_volatile(buf);
175        let d = T::dregs();
176        critical_section::with(|_| {
177            s.armed.store(true, Ordering::Relaxed);
178            d.ep_t_len(index).write(|v| v.set_len(buf.len() as u16));
179            d.ep_tx_ctrl(index).modify(|v| v.set_mask_uep_t_res(EpTxResponse::ACK));
180        });
181
182        poll_fn(|ctx| {
183            s.waker.register(ctx.waker());
184            if s.ready.load(Ordering::Acquire) {
185                s.ready.store(false, Ordering::Relaxed);
186                Poll::Ready(Ok(()))
187            } else if !self.is_enabled() {
188                Poll::Ready(Err(EndpointError::Disabled))
189            } else {
190                Poll::Pending
191            }
192        })
193        .await
194    }
195}