Skip to main content

usb_stack/host/
controller.rs

1//! The hardware abstraction the host protocol layer runs on.
2//!
3//! A controller exposes what the USB 2.0 host controller model needs: the state
4//! of the root port, channels, and one transaction at a time on a channel. It
5//! knows nothing about device requests or descriptors.
6
7use crate::endpoint::{EndpointAddress, EndpointType};
8use crate::host::error::HostResult;
9
10// ─── Speed ───────────────────────────────────────────────────────────────────
11
12/// Bus speed negotiated with a device.
13#[derive(Clone, Copy, PartialEq, Eq, Debug)]
14#[cfg_attr(feature = "defmt", derive(defmt::Format))]
15pub enum Speed {
16    /// 1.5 Mbit/s.
17    Low,
18    /// 12 Mbit/s.
19    Full,
20    /// 480 Mbit/s.
21    High,
22}
23
24impl Speed {
25    /// Maximum packet size of a bulk endpoint at this speed.
26    #[inline]
27    pub const fn max_bulk_packet(self) -> u16 {
28        match self {
29            Self::High => 512,
30            _ => 64,
31        }
32    }
33}
34
35// ─── Device address ──────────────────────────────────────────────────────────
36
37/// The 7-bit address the host assigned to a device.
38#[derive(Clone, Copy, PartialEq, Eq, Debug)]
39#[cfg_attr(feature = "defmt", derive(defmt::Format))]
40pub struct DeviceAddress(u8);
41
42impl DeviceAddress {
43    /// The address every device answers to before `SET_ADDRESS`.
44    pub const ZERO: Self = Self(0);
45    /// The address [`Host::enumerate`](crate::host::Host::enumerate) assigns.
46    pub const FIRST: Self = Self(1);
47
48    /// Wrap a raw address.
49    ///
50    /// # Panics
51    ///
52    /// Panics when `value` does not fit in seven bits.
53    pub const fn new(value: u8) -> Self {
54        assert!(value < 0x80, "a USB device address is seven bits wide");
55        Self(value)
56    }
57
58    /// The raw address byte.
59    #[inline]
60    pub const fn raw(self) -> u8 {
61        self.0
62    }
63}
64
65// ─── Port status ─────────────────────────────────────────────────────────────
66
67/// What the root port reports.
68#[derive(Clone, Copy, PartialEq, Eq, Debug)]
69#[cfg_attr(feature = "defmt", derive(defmt::Format))]
70pub struct PortStatus {
71    /// A device is attached.
72    pub connected: bool,
73    /// The port finished a reset and is talking to the device.
74    pub enabled: bool,
75    /// Speed of the attached device; only meaningful while `enabled`.
76    pub speed: Speed,
77    /// The port draws too much current.
78    pub overcurrent: bool,
79}
80
81// ─── Hub routing ─────────────────────────────────────────────────────────────
82
83/// The transaction translator that carries a FS/LS device behind a
84/// high-speed hub.
85///
86/// The hub translates the start-split and complete-split transactions the
87/// device needs; the address and port are what a controller programs into its
88/// split-transaction registers.
89#[derive(Clone, Copy, PartialEq, Eq, Debug)]
90#[cfg_attr(feature = "defmt", derive(defmt::Format))]
91pub struct Translator {
92    /// Address of the high-speed hub acting as the translator.
93    pub hub: DeviceAddress,
94    /// Port on that hub that leads to the device.
95    pub port: u8,
96}
97
98/// Where a device sits below the root port.
99#[derive(Clone, Copy, PartialEq, Eq, Debug)]
100#[cfg_attr(feature = "defmt", derive(defmt::Format))]
101pub struct HubRoute {
102    /// Address of the hub the device is attached to.
103    pub hub: DeviceAddress,
104    /// One-based port number on that hub.
105    pub port: u8,
106    /// The translator that handles this device, when it runs at FS/LS behind a
107    /// high-speed hub. A controller without split support reports
108    /// [`HostError::Unsupported`](crate::host::HostError::Unsupported) when
109    /// this is set.
110    pub translator: Option<Translator>,
111}
112
113// ─── Channel and transactions ────────────────────────────────────────────────
114
115/// A host channel: the hardware slot a single endpoint is driven through.
116#[derive(Clone, Copy, PartialEq, Eq, Debug)]
117#[cfg_attr(feature = "defmt", derive(defmt::Format))]
118pub struct Channel(u8);
119
120impl Channel {
121    /// Wrap a raw channel index.
122    ///
123    /// # Panics
124    ///
125    /// Panics when `index` is 16 or larger: the core implements at most sixteen
126    /// channels.
127    pub const fn new(index: u8) -> Self {
128        assert!(index < 16, "the core implements at most 16 host channels");
129        Self(index)
130    }
131
132    /// The channel index, as used by the `HCCHAR`/`HCINT`/`HCTSIZ` registers.
133    #[inline]
134    pub const fn index(self) -> usize {
135        self.0 as usize
136    }
137}
138
139/// The data toggle a packet starts with.
140///
141/// The protocol layer tracks toggles itself instead of relying on the
142/// controller to remember them, so that a channel can be reprogrammed (after
143/// `SET_ADDRESS`, for instance) without losing the sequence.
144#[derive(Clone, Copy, PartialEq, Eq, Debug)]
145#[cfg_attr(feature = "defmt", derive(defmt::Format))]
146pub enum Toggle {
147    /// DATA0.
148    Data0,
149    /// DATA1.
150    Data1,
151}
152
153/// Endpoint characteristics a channel is programmed with.
154#[derive(Clone, Copy, PartialEq, Eq, Debug)]
155#[cfg_attr(feature = "defmt", derive(defmt::Format))]
156pub struct EndpointConfig {
157    /// Endpoint number and direction.
158    pub address: EndpointAddress,
159    /// Control, bulk or interrupt.
160    pub transfer: EndpointType,
161    /// Maximum packet size.
162    pub max_packet: u16,
163    /// Polling interval in frames, for interrupt endpoints. Controllers that
164    /// poll on demand ignore it.
165    pub interval: u8,
166    /// Speed of the device the endpoint belongs to.
167    pub speed: Speed,
168    /// Hubs between the root port and the device; `None` for a device on the
169    /// root port.
170    pub route: Option<HubRoute>,
171}
172
173// ─── HostController ──────────────────────────────────────────────────────────
174
175/// The peripheral side of the host stack.
176///
177/// Every method takes `&self`, because pipes and the device handle are handed
178/// out by reference; implementations use interior mutability for the registers
179/// and the channel table.
180///
181/// The interface is transaction oriented: one call moves at most one packet.
182/// The protocol layer splits transfers into packets, which keeps controllers
183/// simple and makes the FIFO requirements predictable.
184pub trait HostController {
185    /// Read the root port.
186    fn port_status(&self) -> PortStatus;
187
188    /// Drive a bus reset on the root port, wait for the device to be enabled
189    /// and report the negotiated speed.
190    fn reset_port(&self) -> HostResult<PortStatus>;
191
192    /// Take a free channel.
193    fn alloc_channel(&self) -> HostResult<Channel>;
194
195    /// Give a channel back.
196    fn free_channel(&self, channel: Channel);
197
198    /// Program a channel for one endpoint of `device`.
199    ///
200    /// Called once before the first transfer and again whenever the device
201    /// address or the packet size changes. `endpoint.speed` and
202    /// `endpoint.route` describe the link the device sits on: a low-speed
203    /// device behind a full-speed hub needs different signalling from one on
204    /// the root port, and a FS/LS device behind a high-speed hub needs split
205    /// transactions. Controllers that cannot do either return
206    /// [`HostError::Unsupported`](crate::host::HostError::Unsupported).
207    fn configure(
208        &self,
209        channel: Channel,
210        device: DeviceAddress,
211        endpoint: &EndpointConfig,
212    ) -> HostResult<()>;
213
214    /// Send an eight-byte SETUP packet.
215    fn setup(&self, channel: Channel, packet: &[u8]) -> HostResult<()>;
216
217    /// Receive one packet into `buffer`, which must hold
218    /// `endpoint.max_packet` bytes at most.
219    ///
220    /// Returns the number of bytes the device sent; that is zero for a
221    /// zero-length packet.
222    fn transfer_in(&self, channel: Channel, toggle: Toggle, buffer: &mut [u8])
223    -> HostResult<usize>;
224
225    /// Send one packet from `data`, which must hold `endpoint.max_packet` bytes
226    /// at most.
227    fn transfer_out(&self, channel: Channel, toggle: Toggle, data: &[u8]) -> HostResult<()>;
228
229    /// Wait for at least `millis` milliseconds.
230    ///
231    /// The protocol layer needs the delays the USB specification mandates (2 ms
232    /// after `SET_ADDRESS`, for example) but has no time base of its own.
233    fn wait_millis(&self, millis: u32);
234}