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