Skip to main content

usb_stack/device/
control.rs

1//! Control transfer state machine.
2//!
3//! [`ControlPipe`] manages EP0 state without being generic over the bus type.
4//! It takes `&B` only for the actual hardware I/O operations (read / write),
5//! keeping the state machine logic bus-agnostic.
6//!
7//! [`ControlIn`] and [`ControlOut`] are short-lived handles passed to
8//! [`UsbClass`](crate::device::class::UsbClass) callbacks so classes can accept or reject
9//! a control transfer ergonomically.
10
11use core::cmp::min;
12
13use crate::device::bus::UsbBus;
14use crate::device::error::{UsbError, UsbResult};
15use crate::endpoint::EndpointAddress;
16use crate::request::Request;
17
18// ─── Internal state ───────────────────────────────────────────────────────────
19
20#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21enum State {
22    Idle,
23    /// IN transfer: data stage in progress, sending chunks.
24    DataIn {
25        offset: usize,
26        len: usize,
27    },
28    /// IN transfer: last chunk sent, need a ZLP.
29    DataInZlp,
30    /// IN transfer: ZLP sent, waiting for status OUT.
31    DataInLast,
32    /// STATUS IN: waiting for the host's ZLP OUT to complete.
33    StatusOut,
34    /// CLASS / VENDOR: response built, waiting for our accept/reject call.
35    CompleteIn(Request),
36    /// STATUS OUT: sending ZLP IN to acknowledge OUT data received.
37    StatusIn,
38    /// HOST→DEVICE data stage.
39    DataOut {
40        req: Request,
41        offset: usize,
42        len: usize,
43    },
44    /// Data OUT complete, waiting for accept/reject.  `len` is the number of
45    /// bytes the host actually sent, which is zero for the zero-length OUT
46    /// transfers some requests use.
47    CompleteOut {
48        len: usize,
49    },
50    Error,
51}
52
53// ─── ControlPipe ─────────────────────────────────────────────────────────────
54
55/// Maximum size of the EP0 control transfer staging buffer.
56pub const CONTROL_BUF_SIZE: usize = 256;
57
58/// EP0 control transfer state machine + staging buffer.
59///
60/// Not generic over the bus type; bus I/O is performed via trait-object-style
61/// `&B` references passed on each call.
62pub struct ControlPipe {
63    state: State,
64    buf: [u8; CONTROL_BUF_SIZE],
65    /// EP0 maximum packet size (8, 16, 32 or 64).
66    max_packet_size: u16,
67    /// Optional static buffer used for large IN responses (avoids copy).
68    static_buf: Option<&'static [u8]>,
69}
70
71impl Default for ControlPipe {
72    fn default() -> Self {
73        Self::new(crate::CONTROL_MAX_PACKET_SIZE)
74    }
75}
76
77impl ControlPipe {
78    /// Create an idle control pipe with an empty staging buffer.
79    pub const fn new(max_packet_size: u16) -> Self {
80        Self {
81            state: State::Idle,
82            buf: [0u8; CONTROL_BUF_SIZE],
83            max_packet_size,
84            static_buf: None,
85        }
86    }
87
88    /// Reset to idle (called on bus reset).
89    pub fn reset(&mut self) {
90        self.state = State::Idle;
91        self.static_buf = None;
92    }
93
94    /// Returns `true` when waiting for a class or device to call `accept_*` / `reject`.
95    pub fn waiting_for_response(&self) -> bool {
96        matches!(self.state, State::CompleteIn(_) | State::CompleteOut { .. })
97    }
98
99    /// Data received during the OUT data stage.
100    ///
101    /// Empty for a zero-length OUT transfer, which several requests use (an
102    /// SMBus quick command, for example).
103    pub fn data(&self) -> &[u8] {
104        match self.state {
105            State::CompleteOut { len } => &self.buf[..len],
106            State::DataOut { offset, .. } => &self.buf[..offset],
107            _ => &[],
108        }
109    }
110
111    // ── Event handlers ────────────────────────────────────────────────────
112
113    /// Called when the bus reports a SETUP packet on EP0.
114    ///
115    /// Reads the 8-byte packet from the bus and returns the parsed [`Request`]
116    /// if we should dispatch it immediately, or `None` if we're still in a data
117    /// stage (OUT transfers with a wLength > 0 need more packets first).
118    pub fn handle_setup<B: UsbBus>(&mut self, bus: &B) -> Option<Request> {
119        let mut raw = [0u8; 8];
120        match bus.read(EndpointAddress::EP0_OUT, &mut raw) {
121            Ok(n) if n >= 8 => {}
122            _ => return None,
123        }
124
125        let req = Request::parse(&raw)?;
126
127        // A new SETUP always aborts any previous transfer.
128        self.static_buf = None;
129        bus.set_stalled(EndpointAddress::EP0_OUT, false);
130        bus.set_stalled(EndpointAddress::EP0_IN, false);
131
132        use crate::endpoint::Direction;
133        if req.direction == Direction::Out {
134            if req.length > 0 {
135                if (req.length as usize) > self.buf.len() {
136                    // Data won't fit — silently ignore.
137                    return None;
138                }
139                self.state = State::DataOut {
140                    req,
141                    offset: 0,
142                    len: req.length as usize,
143                };
144                None
145            } else {
146                self.state = State::CompleteOut { len: 0 };
147                Some(req)
148            }
149        } else {
150            self.state = State::CompleteIn(req);
151            Some(req)
152        }
153    }
154
155    /// Called when the bus reports an OUT packet on EP0 (non-SETUP).
156    pub fn handle_out<B: UsbBus>(&mut self, bus: &B) -> UsbResult<Option<Request>> {
157        match self.state {
158            State::DataOut {
159                req,
160                ref mut offset,
161                len,
162            } => {
163                let n = match bus.read(EndpointAddress::EP0_OUT, &mut self.buf[*offset..]) {
164                    Ok(n) => n,
165                    Err(UsbError::WouldBlock) => return Ok(None),
166                    Err(e) => {
167                        self.set_error(bus);
168                        return Err(e);
169                    }
170                };
171                *offset += n;
172                if *offset >= len {
173                    // `offset` is how much the host actually sent, which is
174                    // what the class has to see rather than the staging buffer.
175                    self.state = State::CompleteOut { len: *offset };
176                    return Ok(Some(req));
177                }
178                Ok(None)
179            }
180            // Host terminated DATA IN early with ZLP OUT.
181            State::DataIn { .. } | State::DataInZlp | State::DataInLast | State::StatusOut => {
182                let _ = bus.read(EndpointAddress::EP0_OUT, &mut []);
183                self.state = State::Idle;
184                Ok(None)
185            }
186            _ => {
187                let _ = bus.read(EndpointAddress::EP0_OUT, &mut []);
188                self.set_error(bus);
189                Ok(None)
190            }
191        }
192    }
193
194    /// Called when the bus reports an IN-complete on EP0.
195    ///
196    /// Returns `true` when the entire transfer (including status stage) completed.
197    pub fn handle_in_complete<B: UsbBus>(&mut self, bus: &B) -> UsbResult<bool> {
198        match self.state {
199            State::DataIn { offset, len } => {
200                self.send_in_chunk(bus, offset, len)?;
201                Ok(false)
202            }
203            State::DataInZlp => {
204                bus.write(EndpointAddress::EP0_IN, &[])?;
205                self.state = State::DataInLast;
206                Ok(false)
207            }
208            State::DataInLast => {
209                bus.set_stalled(EndpointAddress::EP0_OUT, false);
210                self.state = State::StatusOut;
211                Ok(false)
212            }
213            State::StatusIn => {
214                self.state = State::Idle;
215                Ok(true)
216            }
217            // Spurious IN-complete in other states is fine to ignore.
218            _ => Ok(false),
219        }
220    }
221
222    // ── Response helpers ──────────────────────────────────────────────────
223
224    /// Accept a control IN request by writing `data` into the staging buffer.
225    pub fn accept_in<B: UsbBus>(
226        &mut self,
227        bus: &B,
228        f: impl FnOnce(&mut [u8]) -> UsbResult<usize>,
229    ) -> UsbResult<()> {
230        let req = match self.state {
231            State::CompleteIn(r) => r,
232            _ => return Err(UsbError::InvalidState),
233        };
234        self.static_buf = None;
235        let len = f(&mut self.buf)?;
236        if len > self.buf.len() {
237            self.set_error(bus);
238            return Err(UsbError::BufferOverflow);
239        }
240        self.start_in_transfer(bus, req, len)
241    }
242
243    /// Accept a control IN request with a pre-built slice.
244    pub fn accept_with<B: UsbBus>(&mut self, bus: &B, data: &[u8]) -> UsbResult<()> {
245        self.accept_in(bus, |buf| {
246            if data.len() > buf.len() {
247                return Err(UsbError::BufferOverflow);
248            }
249            buf[..data.len()].copy_from_slice(data);
250            Ok(data.len())
251        })
252    }
253
254    /// Accept a control IN request with a `'static` slice (zero-copy).
255    pub fn accept_with_static<B: UsbBus>(&mut self, bus: &B, data: &'static [u8]) -> UsbResult<()> {
256        let req = match self.state {
257            State::CompleteIn(r) => r,
258            _ => return Err(UsbError::InvalidState),
259        };
260        self.static_buf = Some(data);
261        self.start_in_transfer(bus, req, data.len())
262    }
263
264    /// Accept a control OUT request (send ZLP status IN).
265    pub fn accept_out<B: UsbBus>(&mut self, bus: &B) -> UsbResult<()> {
266        match self.state {
267            State::CompleteOut { .. } => {}
268            _ => return Err(UsbError::InvalidState),
269        }
270        bus.write(EndpointAddress::EP0_IN, &[])?;
271        self.state = State::StatusIn;
272        Ok(())
273    }
274
275    /// Reject the pending control request by stalling EP0.
276    pub fn reject<B: UsbBus>(&mut self, bus: &B) -> UsbResult<()> {
277        if !self.waiting_for_response() {
278            return Err(UsbError::InvalidState);
279        }
280        self.set_error(bus);
281        Ok(())
282    }
283
284    // ── Private helpers ───────────────────────────────────────────────────
285
286    fn start_in_transfer<B: UsbBus>(
287        &mut self,
288        bus: &B,
289        req: Request,
290        data_len: usize,
291    ) -> UsbResult<()> {
292        let len = min(data_len, req.length as usize);
293        self.state = State::DataIn { offset: 0, len };
294        self.send_in_chunk(bus, 0, len)
295    }
296
297    fn send_in_chunk<B: UsbBus>(&mut self, bus: &B, offset: usize, len: usize) -> UsbResult<()> {
298        let mps = self.max_packet_size.max(8) as usize;
299        let chunk_len = min(len - offset, mps);
300        let src = self.static_buf.unwrap_or(&self.buf);
301        let written = bus.write(EndpointAddress::EP0_IN, &src[offset..offset + chunk_len])?;
302        let new_offset = offset + written;
303        if new_offset >= len {
304            self.static_buf = None;
305            self.state = if written == mps {
306                State::DataInZlp
307            } else {
308                State::DataInLast
309            };
310        } else {
311            self.state = State::DataIn {
312                offset: new_offset,
313                len,
314            };
315        }
316        Ok(())
317    }
318
319    fn set_error<B: UsbBus>(&mut self, bus: &B) {
320        bus.set_stalled(EndpointAddress::EP0_IN, true);
321        bus.set_stalled(EndpointAddress::EP0_OUT, true);
322        self.state = State::Error;
323    }
324}
325
326// ─── ControlIn / ControlOut handles ──────────────────────────────────────────
327
328/// Handle for a pending control IN transfer.
329///
330/// Passed to [`UsbClass::control_in`](crate::device::class::UsbClass::control_in).
331/// Call one of the `accept_*` methods or `reject` to respond; dropping without
332/// calling either passes the request to the next handler.
333pub struct ControlIn<'a, B: UsbBus> {
334    pipe: &'a mut ControlPipe,
335    bus: &'a B,
336    req: &'a Request,
337}
338
339impl<'a, B: UsbBus> ControlIn<'a, B> {
340    pub(crate) fn new(pipe: &'a mut ControlPipe, bus: &'a B, req: &'a Request) -> Self {
341        Self { pipe, bus, req }
342    }
343
344    /// The SETUP packet that initiated this transfer.
345    pub fn request(&self) -> &Request {
346        self.req
347    }
348
349    /// Accept with data written by a closure into the pipe buffer.
350    pub fn accept(self, f: impl FnOnce(&mut [u8]) -> UsbResult<usize>) -> UsbResult<()> {
351        self.pipe.accept_in(self.bus, f)
352    }
353
354    /// Accept with a pre-built data slice.
355    pub fn accept_with(self, data: &[u8]) -> UsbResult<()> {
356        self.pipe.accept_with(self.bus, data)
357    }
358
359    /// Accept with a `'static` slice (avoids copy for large descriptors).
360    pub fn accept_with_static(self, data: &'static [u8]) -> UsbResult<()> {
361        self.pipe.accept_with_static(self.bus, data)
362    }
363
364    /// Reject by stalling EP0.
365    pub fn reject(self) -> UsbResult<()> {
366        self.pipe.reject(self.bus)
367    }
368}
369
370/// Handle for a pending control OUT transfer.
371///
372/// Passed to [`UsbClass::control_out`](crate::device::class::UsbClass::control_out).
373pub struct ControlOut<'a, B: UsbBus> {
374    pipe: &'a mut ControlPipe,
375    bus: &'a B,
376    req: &'a Request,
377}
378
379impl<'a, B: UsbBus> ControlOut<'a, B> {
380    pub(crate) fn new(pipe: &'a mut ControlPipe, bus: &'a B, req: &'a Request) -> Self {
381        Self { pipe, bus, req }
382    }
383
384    /// The SETUP packet that initiated this transfer.
385    pub fn request(&self) -> &Request {
386        self.req
387    }
388
389    /// The data received in the OUT data stage.
390    pub fn data(&self) -> &[u8] {
391        self.pipe.data()
392    }
393
394    /// Accept by sending a ZLP status IN.
395    pub fn accept(self) -> UsbResult<()> {
396        self.pipe.accept_out(self.bus)
397    }
398
399    /// Reject by stalling EP0.
400    pub fn reject(self) -> UsbResult<()> {
401        self.pipe.reject(self.bus)
402    }
403}