Skip to main content

usb_stack/device/
bus.rs

1//! USB bus trait and allocator.
2//!
3//! # Architecture
4//!
5//! - [`UsbBus`] — hardware-abstraction trait implemented by the peripheral driver.
6//! - [`UsbBusAllocator`] — wraps a bus during the pre-enable allocation phase,
7//!   then *freezes* it (enabling the peripheral) and returns a shared bus reference
8//!   that both [`UsbDevice`](crate::device::UsbDevice) and class endpoint handles
9//!   can borrow from.
10//!
11//! ## Key improvements over `usb-device`
12//!
13//! - No `portable_atomic` / `AtomicPtr` — endpoint handles borrow `&'a B` directly.
14//! - No `mem::forget` hack — `UnsafeCell<B>` + `Cell<bool>` give safe interior-
15//!   mutability without leaking the `RefMut` borrow-count.
16//! - `UsbClass<B>` is not required to be generic over `B` by the allocator itself;
17//!   Endpoint handles carry `&'a B` which is erased to `&'a dyn UsbBus` where needed.
18
19use core::cell::{Cell, UnsafeCell};
20
21use crate::device::endpoint::Endpoint;
22use crate::device::error::{UsbError, UsbResult};
23use crate::endpoint::{Direction, EndpointAddress, EndpointDir, EndpointType};
24
25// ─── PollResult ───────────────────────────────────────────────────────────────
26
27/// Events returned by [`UsbBus::poll`].
28pub enum PollResult {
29    /// No events to report.
30    None,
31    /// The USB bus was reset by the host.
32    Reset,
33    /// One or more endpoints have received or completed data.
34    ///
35    /// Each field is a 16-bit mask where bit *n* corresponds to endpoint *n*.
36    Data {
37        /// Endpoints that received an OUT packet.
38        ep_out: u16,
39        /// Endpoints whose IN transfer completed.
40        ep_in_complete: u16,
41        /// Endpoints that received a SETUP packet (normally only EP0, bit 0).
42        ep_setup: u16,
43    },
44    /// The host asserted USB suspend.
45    Suspend,
46    /// The host deasserted USB suspend (resume).
47    Resume,
48}
49
50impl PollResult {
51    /// `true` for [`PollResult::Data`], i.e. when endpoint events are pending.
52    #[inline]
53    pub fn is_data(self) -> bool {
54        matches!(self, Self::Data { .. })
55    }
56}
57
58// ─── UsbBus trait ─────────────────────────────────────────────────────────────
59
60/// Low-level hardware abstraction trait for a USB peripheral.
61///
62/// Implement this trait to add support for a new microcontroller.  All methods
63/// that mutate hardware state take `&self` (not `&mut self`) because the bus is
64/// shared by reference between [`UsbDevice`](crate::device::UsbDevice) and
65/// endpoint handles.  Implementations must use interior mutability (atomics,
66/// `UnsafeCell`, etc.) where needed.
67///
68/// # `alloc_ep` vs later methods
69///
70/// [`alloc_ep`](UsbBus::alloc_ep) takes `&mut self` and is only called *before*
71/// [`enable`](UsbBus::enable).  All other methods take `&self`.
72pub trait UsbBus: Sized {
73    // ── Allocation phase ────────────────────────────────────────────────────
74
75    /// Allocate an endpoint.
76    ///
77    /// Called by [`UsbBusAllocator`] before [`enable`](UsbBus::enable).
78    ///
79    /// * `dir`        — endpoint direction.
80    /// * `addr`       — if `Some`, request exactly that address; if `None`, use
81    ///   the next available one.
82    /// * `ep_type`    — transfer type.
83    /// * `max_packet` — maximum packet size in bytes.
84    /// * `interval`   — polling interval (interrupt/isochronous endpoints).
85    fn alloc_ep(
86        &mut self,
87        dir: Direction,
88        addr: Option<EndpointAddress>,
89        ep_type: EndpointType,
90        max_packet: u16,
91        interval: u8,
92    ) -> UsbResult<EndpointAddress>;
93
94    /// Enable the USB peripheral.  Called once, after all endpoints have been
95    /// allocated.  The device will be reset shortly after by the host.
96    fn enable(&mut self);
97
98    // ── Bus events ──────────────────────────────────────────────────────────
99
100    /// Reset endpoint state after a USB bus reset.
101    ///
102    /// All previously allocated endpoints must be re-initialised to the state
103    /// they were in right after [`alloc_ep`](UsbBus::alloc_ep).
104    fn reset(&self);
105
106    /// Set the device USB address.
107    fn set_device_address(&self, addr: u8);
108
109    /// Poll for bus events.  Usually called from an interrupt handler or the
110    /// main loop.  Must be called at least once every 10 ms while connected.
111    fn poll(&self) -> PollResult;
112
113    // ── Endpoint I/O ────────────────────────────────────────────────────────
114
115    /// Write a single packet to an IN endpoint.
116    ///
117    /// Returns the number of bytes actually written.
118    ///
119    /// # Errors
120    /// - [`WouldBlock`](UsbError::WouldBlock) — previous packet still pending.
121    /// - [`BufferOverflow`](UsbError::BufferOverflow) — `buf` exceeds `max_packet`.
122    fn write(&self, addr: EndpointAddress, buf: &[u8]) -> UsbResult<usize>;
123
124    /// Read a single packet from an OUT endpoint into `buf`.
125    ///
126    /// Returns the number of bytes read.
127    ///
128    /// # Errors
129    /// - [`WouldBlock`](UsbError::WouldBlock) — no packet available.
130    /// - [`BufferOverflow`](UsbError::BufferOverflow) — packet exceeds `buf`.
131    fn read(&self, addr: EndpointAddress, buf: &mut [u8]) -> UsbResult<usize>;
132
133    /// Set or clear the STALL condition on an endpoint.
134    fn set_stalled(&self, addr: EndpointAddress, stalled: bool);
135
136    /// Return `true` if the endpoint is currently stalled.
137    fn is_stalled(&self, addr: EndpointAddress) -> bool;
138
139    // ── Power management ────────────────────────────────────────────────────
140
141    /// Enter USB suspend mode.
142    fn suspend(&self);
143
144    /// Resume from suspend mode.
145    fn resume(&self);
146
147    /// Simulate a USB disconnect (force re-enumeration).
148    ///
149    /// The default implementation returns [`Unsupported`](UsbError::Unsupported).
150    fn force_reset(&self) -> UsbResult<()> {
151        Err(UsbError::Unsupported)
152    }
153
154    // ── Quirks ──────────────────────────────────────────────────────────────
155
156    /// When `true`, [`set_device_address`](UsbBus::set_device_address) must be
157    /// called *before* the status stage of a SET_ADDRESS request is completed
158    /// (non-standard, required by some peripherals).
159    ///
160    /// Default: `false` (USB 2.0 spec §9.4.6 behaviour).
161    const SET_ADDRESS_BEFORE_STATUS: bool = false;
162
163    /// Largest packet size bulk and interrupt endpoints support on this bus.
164    ///
165    /// Classes use it to size their endpoints: 64 bytes for full-speed buses,
166    /// 512 for high-speed ones. Default: 64.
167    const MAX_PACKET_SIZE: u16 = 64;
168}
169
170// ─── Opaque handle types ──────────────────────────────────────────────────────
171
172/// An opaque handle to an allocated USB interface number.
173#[derive(Clone, Copy, PartialEq, Eq, Debug)]
174#[cfg_attr(feature = "defmt", derive(defmt::Format))]
175pub struct InterfaceNumber(pub(crate) u8);
176
177impl InterfaceNumber {
178    /// Construct an interface number from its raw value.
179    ///
180    /// Classes normally obtain one from
181    /// [`UsbBusAllocator::interface`](crate::device::bus::UsbBusAllocator::interface);
182    /// this is for protocol tables and tests that carry a fixed number.
183    #[inline]
184    pub const fn new(number: u8) -> Self {
185        Self(number)
186    }
187}
188
189impl From<InterfaceNumber> for u8 {
190    fn from(n: InterfaceNumber) -> u8 {
191        n.0
192    }
193}
194
195/// An opaque handle to an allocated USB string descriptor index.
196#[derive(Clone, Copy, PartialEq, Eq, Debug)]
197#[cfg_attr(feature = "defmt", derive(defmt::Format))]
198pub struct StringIndex(u8);
199
200impl StringIndex {
201    pub(crate) fn new(index: u8) -> Self {
202        Self(index)
203    }
204}
205
206impl From<StringIndex> for u8 {
207    fn from(s: StringIndex) -> u8 {
208        s.0
209    }
210}
211
212// ─── UsbBusAllocator ──────────────────────────────────────────────────────────
213
214/// Wraps a [`UsbBus`] during the endpoint-allocation phase.
215///
216/// Classes call the `bulk`, `interrupt`, `interface`, and `string` helper methods
217/// in their constructors to obtain typed endpoint handles and resource indices.
218/// Once all classes are constructed, [`UsbDevice::build`](crate::device::UsbDevice)
219/// calls `freeze()` internally, which enables the
220/// peripheral and returns a `&B` reference that persists for the allocator's
221/// lifetime.
222///
223/// ## Why no `mem::forget`
224///
225/// The original `usb-device` crate used `mem::forget` on a `RefMut` guard to
226/// permanently lock a `RefCell<B>`.  This crate instead uses `UnsafeCell<B>` +
227/// `Cell<bool>` for the frozen flag.  The safety invariant is:
228/// - Before `freeze`: only `alloc_ep` (via `&mut *self.bus.get()`) mutates the bus,
229///   and it is called sequentially (single-threaded embedded context).
230/// - After `freeze`: no `&mut B` is ever created again; all `&B` users are sound.
231pub struct UsbBusAllocator<B: UsbBus> {
232    bus: UnsafeCell<B>,
233    frozen: Cell<bool>,
234    next_interface: Cell<u8>,
235    next_string_index: Cell<u8>,
236}
237
238// Safety: access management is described in the module doc; correct only for
239// single-threaded embedded contexts where `B: Send`.
240unsafe impl<B: UsbBus + Send> Send for UsbBusAllocator<B> {}
241unsafe impl<B: UsbBus + Sync> Sync for UsbBusAllocator<B> {}
242
243impl<B: UsbBus> UsbBusAllocator<B> {
244    /// Wrap a bus implementation.  The bus must not yet be enabled.
245    pub fn new(bus: B) -> Self {
246        Self {
247            bus: UnsafeCell::new(bus),
248            frozen: Cell::new(false),
249            next_interface: Cell::new(0),
250            // Indices 0–3 are reserved: 0=lang-IDs, 1=manufacturer, 2=product, 3=serial.
251            next_string_index: Cell::new(4),
252        }
253    }
254
255    // ── Low-level allocation ─────────────────────────────────────────────────
256
257    /// Allocate an endpoint with the specified direction and parameters.
258    ///
259    /// This delegates to [`UsbBus::alloc_ep`].  Prefer the typed helpers
260    /// (`bulk`, `interrupt`, …) in class constructors.
261    pub fn alloc<D: EndpointDir>(
262        &self,
263        addr: Option<EndpointAddress>,
264        ep_type: EndpointType,
265        max_packet: u16,
266        interval: u8,
267    ) -> UsbResult<Endpoint<'_, B, D>> {
268        assert!(
269            !self.frozen.get(),
270            "cannot allocate endpoints after UsbBusAllocator::freeze()"
271        );
272        let ep_addr = unsafe {
273            (*self.bus.get()).alloc_ep(D::DIRECTION, addr, ep_type, max_packet, interval)?
274        };
275        // Safety: bus is inside UnsafeCell; no &mut B exists after this call returns.
276        let bus: &B = unsafe { &*self.bus.get() };
277        Ok(Endpoint::new(bus, ep_addr, ep_type, max_packet, interval))
278    }
279
280    // ── Typed helpers ────────────────────────────────────────────────────────
281
282    /// Allocate a control endpoint (panics on allocation failure).
283    pub fn control<D: EndpointDir>(&self, max_packet: u16) -> Endpoint<'_, B, D> {
284        self.alloc(None, EndpointType::Control, max_packet, 0)
285            .expect("control endpoint allocation failed")
286    }
287
288    /// Allocate a bulk endpoint (panics on allocation failure).
289    pub fn bulk<D: EndpointDir>(&self, max_packet: u16) -> Endpoint<'_, B, D> {
290        self.alloc(None, EndpointType::Bulk, max_packet, 0)
291            .expect("bulk endpoint allocation failed")
292    }
293
294    /// Allocate an interrupt endpoint (panics on allocation failure).
295    pub fn interrupt<D: EndpointDir>(&self, max_packet: u16, interval: u8) -> Endpoint<'_, B, D> {
296        self.alloc(None, EndpointType::Interrupt, max_packet, interval)
297            .expect("interrupt endpoint allocation failed")
298    }
299
300    /// Allocate an isochronous endpoint (panics on allocation failure).
301    pub fn isochronous<D: EndpointDir>(
302        &self,
303        synchronization: crate::endpoint::IsoSynchronization,
304        usage: crate::endpoint::IsoUsage,
305        max_packet: u16,
306        interval: u8,
307    ) -> Endpoint<'_, B, D> {
308        self.alloc(
309            None,
310            EndpointType::Isochronous {
311                synchronization,
312                usage,
313            },
314            max_packet,
315            interval,
316        )
317        .expect("isochronous endpoint allocation failed")
318    }
319
320    // ── Resource handles ─────────────────────────────────────────────────────
321
322    /// Allocate the next sequential interface number.
323    pub fn interface(&self) -> InterfaceNumber {
324        assert!(
325            !self.frozen.get(),
326            "cannot allocate interfaces after freeze()"
327        );
328        let n = self.next_interface.get();
329        self.next_interface.set(n + 1);
330        InterfaceNumber(n)
331    }
332
333    /// Allocate the next sequential string descriptor index.
334    pub fn string(&self) -> StringIndex {
335        assert!(!self.frozen.get(), "cannot allocate strings after freeze()");
336        let i = self.next_string_index.get();
337        self.next_string_index.set(i + 1);
338        StringIndex(i)
339    }
340
341    // ── Freeze ───────────────────────────────────────────────────────────────
342
343    /// Enable the USB peripheral and return a long-lived shared reference to it.
344    ///
345    /// After this call no further endpoint / interface / string allocation is
346    /// possible.  The returned `&B` has the same lifetime as the allocator itself.
347    ///
348    /// # Safety
349    ///
350    /// Callers must ensure they do not call any `&mut B` method on the underlying
351    /// bus after this point.  `UsbDevice::build` is the only intended caller.
352    pub(crate) fn freeze(&self) -> &B {
353        if !self.frozen.get() {
354            self.frozen.set(true);
355            // Safety: no concurrent mutable access; frozen flag prevents further
356            // &mut B creation through the allocator API.
357            unsafe { (*self.bus.get()).enable() };
358        }
359        // Safety: bus lives as long as &self; no &mut B will be created again.
360        unsafe { &*self.bus.get() }
361    }
362
363    // ── Internal accessors ───────────────────────────────────────────────────
364
365    #[allow(dead_code)]
366    pub(crate) fn num_interfaces(&self) -> u8 {
367        self.next_interface.get()
368    }
369}