Skip to main content

ch32_hal/usbhs/
control.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, EpTog, EpTxResponse};
7use embassy_usb_driver::EndpointError;
8
9use super::endpoint::Endpoint;
10use super::{setup_pending, take_setup, EpState, Instance, IN_STATE, OUT_STATE};
11use crate::usb::InOut;
12
13pub struct ControlPipe<'d, T: Instance, const SIZE: usize> {
14    _phantom: PhantomData<&'d mut T>,
15    ep0: Endpoint<'d, T, InOut, SIZE>,
16}
17
18impl<'d, T: Instance, const SIZE: usize> ControlPipe<'d, T, SIZE> {
19    pub(crate) fn new(ep0: Endpoint<'d, T, InOut, SIZE>) -> Self {
20        Self {
21            _phantom: PhantomData,
22            ep0,
23        }
24    }
25
26    /// Runs the zero-length IN status stage. Returns false if a new setup packet replaced it.
27    async fn status_in(&self) -> bool {
28        let d = T::dregs();
29
30        if setup_pending() {
31            return false;
32        }
33        IN_STATE[0].ready.store(false, Ordering::Relaxed);
34        critical_section::with(|_| {
35            d.ep_t_len(0).write(|w| w.set_len(0));
36            d.ep_tx_ctrl(0).modify(|w| {
37                // status stage starts with DATA1
38                w.set_mask_uep_t_tog(EpTog::DATA1);
39                w.set_mask_uep_t_res(EpTxResponse::ACK);
40            });
41        });
42
43        complete(&IN_STATE[0]).await.is_ok()
44    }
45}
46
47/// Wait for the interrupt to complete an EP0 stage; a new setup packet aborts it.
48async fn complete(s: &EpState) -> Result<usize, EndpointError> {
49    poll_fn(|ctx| {
50        s.waker.register(ctx.waker());
51        if s.ready.load(Ordering::Acquire) {
52            s.ready.store(false, Ordering::Relaxed);
53            Poll::Ready(Ok(s.len.load(Ordering::Relaxed) as usize))
54        } else if setup_pending() {
55            Poll::Ready(Err(EndpointError::Disabled))
56        } else {
57            Poll::Pending
58        }
59    })
60    .await
61}
62
63impl<'d, T: Instance, const SIZE: usize> embassy_usb_driver::ControlPipe for ControlPipe<'d, T, SIZE> {
64    fn max_packet_size(&self) -> usize {
65        use embassy_usb_driver::Endpoint;
66
67        self.ep0.info().max_packet_size as usize
68    }
69
70    async fn setup(&mut self) -> [u8; 8] {
71        // the interrupt copied it and set EP0 to NAK both ways
72        poll_fn(|ctx| {
73            OUT_STATE[0].waker.register(ctx.waker());
74            match take_setup() {
75                Some(p) => Poll::Ready(p),
76                None => Poll::Pending,
77            }
78        })
79        .await
80    }
81
82    async fn data_out(&mut self, buf: &mut [u8], first: bool, _last: bool) -> Result<usize, EndpointError> {
83        let d = T::dregs();
84
85        if buf.len() > self.ep0.data.max_packet_size as usize {
86            return Err(EndpointError::BufferOverflow);
87        }
88        if setup_pending() {
89            return Err(EndpointError::Disabled);
90        }
91
92        OUT_STATE[0].ready.store(false, Ordering::Relaxed);
93        critical_section::with(|_| {
94            // the chunks embassy-usb asks for are the host's packets: the length if the
95            // interrupt only sees the host move on
96            OUT_STATE[0].len.store(buf.len() as u16, Ordering::Relaxed);
97            OUT_STATE[0].armed.store(true, Ordering::Relaxed);
98            if first {
99                d.ep_rx_ctrl(0).write(|v| {
100                    v.set_mask_uep_r_tog(EpTog::DATA1);
101                    v.set_mask_uep_r_res(EpRxResponse::ACK);
102                })
103            } else {
104                // the interrupt flipped the toggle after the last packet
105                d.ep_rx_ctrl(0).modify(|v| v.set_mask_uep_r_res(EpRxResponse::ACK))
106            }
107        });
108
109        let len = complete(&OUT_STATE[0]).await?;
110        if len > buf.len() {
111            return Err(EndpointError::BufferOverflow);
112        }
113        self.ep0.data.buffer.read_volatile(&mut buf[..len]);
114        Ok(len)
115    }
116
117    async fn data_in(&mut self, data: &[u8], first: bool, last: bool) -> Result<(), EndpointError> {
118        let d = T::dregs();
119
120        if data.len() > self.ep0.data.max_packet_size as usize {
121            return Err(EndpointError::BufferOverflow);
122        }
123        if setup_pending() {
124            return Err(EndpointError::Disabled);
125        }
126
127        self.ep0.data.buffer.write_volatile(data);
128        IN_STATE[0].ready.store(false, Ordering::Relaxed);
129        critical_section::with(|_| {
130            if last {
131                // the status stage (a zero-length OUT, DATA1) right away: the host gets through
132                // even if no entry sees the data packet's completion (its OUT stands for it)
133                OUT_STATE[0].ready.store(false, Ordering::Relaxed);
134                OUT_STATE[0].len.store(0, Ordering::Relaxed);
135                d.ep_rx_ctrl(0).write(|w| {
136                    w.set_mask_uep_r_tog(EpTog::DATA1);
137                    w.set_mask_uep_r_res(EpRxResponse::ACK);
138                });
139            }
140            IN_STATE[0].armed.store(true, Ordering::Relaxed);
141            d.ep_t_len(0).write(|v| v.set_len(data.len() as u16));
142            if first {
143                d.ep_tx_ctrl(0).write(|v| {
144                    v.set_mask_uep_t_res(EpTxResponse::ACK);
145                    v.set_mask_uep_t_tog(EpTog::DATA1);
146                })
147            } else {
148                d.ep_tx_ctrl(0).modify(|v| v.set_mask_uep_t_res(EpTxResponse::ACK));
149            }
150        });
151
152        complete(&IN_STATE[0]).await?;
153
154        if last {
155            if complete(&OUT_STATE[0]).await? != 0 {
156                error!("Expected 0 len OUT stage, found non-zero len, aborting");
157                return Err(EndpointError::BufferOverflow);
158            }
159        }
160        Ok(())
161    }
162
163    async fn accept(&mut self) {
164        // the host may send a new setup packet instead of the status stage: nothing left to do then
165        let _ = self.status_in().await;
166    }
167
168    async fn reject(&mut self) {
169        let d = T::dregs();
170
171        critical_section::with(|_| {
172            OUT_STATE[0].armed.store(false, Ordering::Relaxed);
173            IN_STATE[0].armed.store(false, Ordering::Relaxed);
174            d.ep_tx_ctrl(0).modify(|v| v.set_mask_uep_t_res(EpTxResponse::STALL));
175            d.ep_rx_ctrl(0).modify(|v| v.set_mask_uep_r_res(EpRxResponse::STALL));
176        });
177    }
178
179    async fn accept_set_address(&mut self, addr: u8) {
180        trace!("accepting address: {}", addr);
181        // USB 2.0 ยง9.4.6: the address changes only after the status stage completes.
182        if self.status_in().await {
183            T::regs().dev_ad().write(|w| w.set_addr(addr));
184        }
185    }
186}