Skip to main content

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