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// ─── Channel and transactions ────────────────────────────────────────────────
82
83/// A host channel: the hardware slot a single endpoint is driven through.
84#[derive(Clone, Copy, PartialEq, Eq, Debug)]
85#[cfg_attr(feature = "defmt", derive(defmt::Format))]
86pub struct Channel(u8);
87
88impl Channel {
89 /// Wrap a raw channel index.
90 ///
91 /// # Panics
92 ///
93 /// Panics when `index` is 16 or larger: the core implements at most sixteen
94 /// channels.
95 pub const fn new(index: u8) -> Self {
96 assert!(index < 16, "the core implements at most 16 host channels");
97 Self(index)
98 }
99
100 /// The channel index, as used by the `HCCHAR`/`HCINT`/`HCTSIZ` registers.
101 #[inline]
102 pub const fn index(self) -> usize {
103 self.0 as usize
104 }
105}
106
107/// The data toggle a packet starts with.
108///
109/// The protocol layer tracks toggles itself instead of relying on the
110/// controller to remember them, so that a channel can be reprogrammed (after
111/// `SET_ADDRESS`, for instance) without losing the sequence.
112#[derive(Clone, Copy, PartialEq, Eq, Debug)]
113#[cfg_attr(feature = "defmt", derive(defmt::Format))]
114pub enum Toggle {
115 /// DATA0.
116 Data0,
117 /// DATA1.
118 Data1,
119}
120
121/// Endpoint characteristics a channel is programmed with.
122#[derive(Clone, Copy, PartialEq, Eq, Debug)]
123#[cfg_attr(feature = "defmt", derive(defmt::Format))]
124pub struct EndpointConfig {
125 /// Endpoint number and direction.
126 pub address: EndpointAddress,
127 /// Control, bulk or interrupt.
128 pub transfer: EndpointType,
129 /// Maximum packet size.
130 pub max_packet: u16,
131 /// Polling interval in frames, for interrupt endpoints. Controllers that
132 /// poll on demand ignore it.
133 pub interval: u8,
134}
135
136// ─── HostController ──────────────────────────────────────────────────────────
137
138/// The peripheral side of the host stack.
139///
140/// Every method takes `&self`, because pipes and the device handle are handed
141/// out by reference; implementations use interior mutability for the registers
142/// and the channel table.
143///
144/// The interface is transaction oriented: one call moves at most one packet.
145/// The protocol layer splits transfers into packets, which keeps controllers
146/// simple and makes the FIFO requirements predictable.
147pub trait HostController {
148 /// Read the root port.
149 fn port_status(&self) -> PortStatus;
150
151 /// Drive a bus reset on the root port, wait for the device to be enabled
152 /// and report the negotiated speed.
153 fn reset_port(&self) -> HostResult<PortStatus>;
154
155 /// Take a free channel.
156 fn alloc_channel(&self) -> HostResult<Channel>;
157
158 /// Give a channel back.
159 fn free_channel(&self, channel: Channel);
160
161 /// Program a channel for one endpoint of `device`.
162 ///
163 /// Called once before the first transfer and again whenever the device
164 /// address or the packet size changes.
165 fn configure(
166 &self,
167 channel: Channel,
168 device: DeviceAddress,
169 endpoint: &EndpointConfig,
170 ) -> HostResult<()>;
171
172 /// Send an eight-byte SETUP packet.
173 fn setup(&self, channel: Channel, packet: &[u8]) -> HostResult<()>;
174
175 /// Receive one packet into `buffer`, which must hold
176 /// `endpoint.max_packet` bytes at most.
177 ///
178 /// Returns the number of bytes the device sent; that is zero for a
179 /// zero-length packet.
180 fn transfer_in(&self, channel: Channel, toggle: Toggle, buffer: &mut [u8])
181 -> HostResult<usize>;
182
183 /// Send one packet from `data`, which must hold `endpoint.max_packet` bytes
184 /// at most.
185 fn transfer_out(&self, channel: Channel, toggle: Toggle, data: &[u8]) -> HostResult<()>;
186
187 /// Wait for at least `millis` milliseconds.
188 ///
189 /// The protocol layer needs the delays the USB specification mandates (2 ms
190 /// after `SET_ADDRESS`, for example) but has no time base of its own.
191 fn wait_millis(&self, millis: u32);
192}