Skip to main content

usb_stack/host/class/
hub.rs

1//! USB hubs.
2//!
3//! A hub is an ordinary device with one class-specific interface: the host
4//! powers its downstream ports, waits for a device to appear, resets the port
5//! and then enumerates the new device at address zero. [`Hub`] wraps the
6//! [`Device`] that enumerated the hub and performs those steps.
7//!
8//! ```text
9//! let device = host.enumerate()?;             // the hub itself
10//! let hub = Hub::open(&device)?;              // SET_CONFIGURATION + hub descriptor
11//! hub.power_ports()?;                         // PORT_POWER on every port
12//! hub.wait_for_connection(1, 2000)?;          // something was plugged in
13//! hub.reset_port(1)?;                         // PORT_RESET, wait for C_PORT_RESET
14//! let child = hub.enumerate_child(1, address)?;
15//! ```
16//!
17//! The hub is left configured and powered, so a later device on the same port
18//! only needs [`reset_port`](Hub::reset_port) and
19//! [`enumerate_child`](Hub::enumerate_child).
20//!
21//! Devices behind a high-speed hub that run at full or low speed need the
22//! hub's transaction translator. [`enumerate_child`](Hub::enumerate_child)
23//! records it in the [`HubRoute`] it hands to the controller; controllers
24//! without split-transaction support report [`HostError::Unsupported`].
25
26use crate::descriptor::{class_code, descriptor_type, hub};
27use crate::endpoint::Direction;
28use crate::host::controller::{DeviceAddress, HostController, HubRoute, Speed, Translator};
29use crate::host::device::Device;
30use crate::host::error::{HostError, HostResult};
31use crate::request::{Recipient, Request, RequestType, StandardRequest};
32
33/// Room for the hub descriptor: the nine-byte header plus the removable and
34/// port-power bitmaps of a fifteen-port hub.
35const DESCRIPTOR_MAX: usize = 15;
36
37/// How often the driver polls a port while it waits for a change.
38const POLL_MS: u32 = 5;
39
40/// How long a port reset may take before it is reported as a timeout.
41const RESET_TIMEOUT_MS: u32 = 200;
42
43// ─── Hub descriptor ──────────────────────────────────────────────────────────
44
45/// The hub class descriptor (USB 2.0 §11.23.2.1).
46#[derive(Clone, Copy, PartialEq, Eq, Debug)]
47#[cfg_attr(feature = "defmt", derive(defmt::Format))]
48pub struct HubDescriptor {
49    /// `bNbrPorts`.
50    pub ports: u8,
51    /// `wHubCharacteristics`.
52    pub characteristics: u16,
53    /// `bPwrOn2PwrGood` converted to milliseconds.
54    pub power_on_delay_ms: u32,
55}
56
57impl HubDescriptor {
58    /// Length of the descriptor header; the bitmaps that follow depend on the
59    /// port count.
60    pub const LEN: usize = 9;
61
62    /// Parse the bytes returned by the class-specific `GET_DESCRIPTOR`.
63    pub fn parse(bytes: &[u8]) -> HostResult<Self> {
64        if bytes.len() < Self::LEN || bytes[0] < Self::LEN as u8 || bytes[1] != descriptor_type::HUB
65        {
66            return Err(HostError::Malformed);
67        }
68        Ok(Self {
69            ports: bytes[2],
70            characteristics: u16::from_le_bytes([bytes[3], bytes[4]]),
71            // bPwrOn2PwrGood counts two-millisecond units.
72            power_on_delay_ms: u32::from(bytes[5]) * 2,
73        })
74    }
75
76    /// Logical power switching mode.
77    #[inline]
78    pub fn power_switching(&self) -> u16 {
79        self.characteristics & hub::characteristics::POWER_SWITCHING_MASK
80    }
81
82    /// Transaction translator think time, in high-speed hubs.
83    #[inline]
84    pub fn tt_think_time(&self) -> u8 {
85        ((self.characteristics & hub::characteristics::TT_THINK_TIME_MASK)
86            >> hub::characteristics::TT_THINK_TIME_SHIFT) as u8
87    }
88}
89
90// ─── Port status ─────────────────────────────────────────────────────────────
91
92/// What `GET_STATUS` reports for a downstream port.
93#[derive(Clone, Copy, PartialEq, Eq, Debug)]
94#[cfg_attr(feature = "defmt", derive(defmt::Format))]
95pub struct HubPortStatus {
96    /// `wPortStatus`.
97    pub status: u16,
98    /// `wPortChange`.
99    pub change: u16,
100}
101
102impl HubPortStatus {
103    /// A device is attached.
104    #[inline]
105    pub fn connected(&self) -> bool {
106        self.status & hub::port_status::CONNECTION != 0
107    }
108
109    /// The port is enabled and can be used.
110    #[inline]
111    pub fn enabled(&self) -> bool {
112        self.status & hub::port_status::ENABLE != 0
113    }
114
115    /// The port is drawing too much current.
116    #[inline]
117    pub fn over_current(&self) -> bool {
118        self.status & hub::port_status::OVER_CURRENT != 0
119    }
120
121    /// Speed of the attached device.
122    ///
123    /// A full-speed hub never sets [`HIGH_SPEED`](hub::port_status::HIGH_SPEED),
124    /// so this is [`Speed::Full`] unless the low-speed bit is set.
125    #[inline]
126    pub fn speed(&self) -> Speed {
127        if self.status & hub::port_status::HIGH_SPEED != 0 {
128            Speed::High
129        } else if self.status & hub::port_status::LOW_SPEED != 0 {
130            Speed::Low
131        } else {
132            Speed::Full
133        }
134    }
135}
136
137// ─── Hub ─────────────────────────────────────────────────────────────────────
138
139/// An enumerated hub.
140pub struct Hub<'d, 'a, C: HostController> {
141    device: &'a Device<'d, C>,
142    descriptor: HubDescriptor,
143}
144
145impl<'d, 'a, C: HostController> Hub<'d, 'a, C> {
146    /// Select the hub's configuration and read its class descriptor.
147    ///
148    /// The hub keeps answering control requests either way, but its
149    /// downstream ports cannot be powered before `SET_CONFIGURATION`.
150    pub fn open(device: &'a Device<'d, C>) -> HostResult<Self> {
151        let class = device.descriptor().class;
152        // A high-speed hub reports protocol 1 or 2 (single or multiple TT), so
153        // match the class and subclass instead of the whole triple.
154        let interface = device
155            .configuration()
156            .interfaces()
157            .any(|interface| interface.class() == class_code::HUB && interface.sub_class() == 0);
158        if class != class_code::HUB && !interface {
159            return Err(HostError::Protocol);
160        }
161
162        let value = device.configuration().value();
163        if value != 0 {
164            device.set_configuration(value)?;
165        }
166
167        let mut raw = [0u8; DESCRIPTOR_MAX];
168        let request = Request::custom(
169            Direction::In,
170            RequestType::Class,
171            Recipient::Device,
172            StandardRequest::GET_DESCRIPTOR,
173            (descriptor_type::HUB as u16) << 8,
174            0,
175            DESCRIPTOR_MAX as u16,
176        );
177        let length = device.control(&request, &mut raw)?;
178        let descriptor = HubDescriptor::parse(&raw[..length])?;
179
180        Ok(Self { device, descriptor })
181    }
182
183    /// The hub device that was enumerated.
184    #[inline]
185    pub fn device(&self) -> &'a Device<'d, C> {
186        self.device
187    }
188
189    /// The class descriptor read in [`open`](Self::open).
190    #[inline]
191    pub fn descriptor(&self) -> &HubDescriptor {
192        &self.descriptor
193    }
194
195    /// Number of downstream ports.
196    #[inline]
197    pub fn ports(&self) -> u8 {
198        self.descriptor.ports
199    }
200
201    /// Power every downstream port that is not powered yet and wait for
202    /// `bPwrOn2PwrGood` to elapse.
203    ///
204    /// A ganged hub powers all ports from one switch, so the first request
205    /// already powers the rest; asking port by port is harmless and keeps the
206    /// driver independent of the switching mode.
207    pub fn power_ports(&self) -> HostResult<()> {
208        for port in 1..=self.descriptor.ports {
209            let status = self.port_status(port)?;
210            if status.status & hub::port_status::POWER == 0 {
211                self.set_port_feature(port, hub::feature::PORT_POWER)?;
212            }
213        }
214        self.device
215            .controller()
216            .wait_millis(self.descriptor.power_on_delay_ms);
217        Ok(())
218    }
219
220    /// Read `wPortStatus` and `wPortChange` of `port`.
221    pub fn port_status(&self, port: u8) -> HostResult<HubPortStatus> {
222        self.check_port(port)?;
223        let request = Request::custom(
224            Direction::In,
225            RequestType::Class,
226            Recipient::Other,
227            StandardRequest::GET_STATUS,
228            0,
229            u16::from(port),
230            4,
231        );
232        let mut raw = [0u8; 4];
233        if self.device.control(&request, &mut raw)? < raw.len() {
234            return Err(HostError::Malformed);
235        }
236        Ok(HubPortStatus {
237            status: u16::from_le_bytes([raw[0], raw[1]]),
238            change: u16::from_le_bytes([raw[2], raw[3]]),
239        })
240    }
241
242    /// Clear every change bit in `change`.
243    ///
244    /// The change bits of `wPortChange` map one to one onto the `C_PORT_*`
245    /// feature selectors, which is why the selector is the bit position plus
246    /// the selector of `C_PORT_CONNECTION`.
247    pub fn clear_port_change(&self, port: u8, change: u16) -> HostResult<()> {
248        for bit in 0..5u16 {
249            if change & (1 << bit) != 0 {
250                self.clear_port_feature(port, hub::feature::C_PORT_CONNECTION + bit)?;
251            }
252        }
253        Ok(())
254    }
255
256    /// Wait until a device is attached to `port`.
257    pub fn wait_for_connection(&self, port: u8, timeout_ms: u32) -> HostResult<HubPortStatus> {
258        self.poll_until(port, timeout_ms, HubPortStatus::connected)
259    }
260
261    /// Reset `port` and report the speed of the device behind it.
262    ///
263    /// This is what the root port's `reset_port` does for the hub itself: the
264    /// device answers at address zero afterwards and has to be enumerated with
265    /// [`enumerate_child`](Self::enumerate_child).
266    pub fn reset_port(&self, port: u8) -> HostResult<Speed> {
267        let status = self.port_status(port)?;
268        if !status.connected() {
269            return Err(HostError::Disconnected);
270        }
271        // A stale change bit would make the new reset look like an old event.
272        self.clear_port_change(port, status.change)?;
273
274        // PORT_RESET is only defined for a disabled port. A device that is
275        // being re-enumerated may still be enabled from the previous round.
276        if status.enabled() {
277            self.clear_port_feature(port, hub::feature::PORT_ENABLE)?;
278            let status = self.poll_until(port, RESET_TIMEOUT_MS, |status| !status.enabled())?;
279            self.clear_port_change(port, status.change)?;
280        }
281
282        self.set_port_feature(port, hub::feature::PORT_RESET)?;
283        let status = self.poll_until(port, RESET_TIMEOUT_MS, |status| {
284            status.change & hub::port_change::RESET != 0
285        })?;
286        self.clear_port_change(port, status.change)?;
287
288        if !status.enabled() {
289            return Err(HostError::Disconnected);
290        }
291        Ok(status.speed())
292    }
293
294    /// Enumerate the device attached to `port` at `address`.
295    ///
296    /// The port must have been reset with [`reset_port`](Self::reset_port)
297    /// first.
298    pub fn enumerate_child(&self, port: u8, address: DeviceAddress) -> HostResult<Device<'d, C>> {
299        let status = self.port_status(port)?;
300        if !status.connected() || !status.enabled() {
301            return Err(HostError::Disconnected);
302        }
303        let speed = status.speed();
304        let route = self.child_route(port, speed);
305        Device::enumerate_downstream(self.device.controller(), address, speed, route)
306    }
307
308    fn child_route(&self, port: u8, speed: Speed) -> HubRoute {
309        let translator = match (self.device.speed(), speed) {
310            // High speed all the way: the hub just forwards the packets.
311            (Speed::High, Speed::High) => None,
312            // A FS/LS device behind a high-speed hub needs this hub's
313            // transaction translator.
314            (Speed::High, _) => Some(Translator {
315                hub: self.device.address(),
316                port,
317            }),
318            // A FS hub is transparent; a device behind it inherits whatever
319            // translator the hub itself uses.
320            _ => self.device.route().and_then(|route| route.translator),
321        };
322        HubRoute {
323            hub: self.device.address(),
324            port,
325            translator,
326        }
327    }
328
329    fn poll_until(
330        &self,
331        port: u8,
332        timeout_ms: u32,
333        satisfied: impl Fn(&HubPortStatus) -> bool,
334    ) -> HostResult<HubPortStatus> {
335        let mut waited = 0;
336        loop {
337            let status = self.port_status(port)?;
338            if satisfied(&status) {
339                return Ok(status);
340            }
341            if waited >= timeout_ms {
342                return Err(HostError::Timeout);
343            }
344            self.device.controller().wait_millis(POLL_MS);
345            waited += POLL_MS;
346        }
347    }
348
349    fn set_port_feature(&self, port: u8, feature: u16) -> HostResult<()> {
350        self.port_request(StandardRequest::SET_FEATURE, feature, port)
351    }
352
353    fn clear_port_feature(&self, port: u8, feature: u16) -> HostResult<()> {
354        self.port_request(StandardRequest::CLEAR_FEATURE, feature, port)
355    }
356
357    fn port_request(&self, request: u8, feature: u16, port: u8) -> HostResult<()> {
358        self.check_port(port)?;
359        let request = Request::custom(
360            Direction::Out,
361            RequestType::Class,
362            Recipient::Other,
363            request,
364            feature,
365            u16::from(port),
366            0,
367        );
368        self.device.control(&request, &mut [])?;
369        Ok(())
370    }
371
372    fn check_port(&self, port: u8) -> HostResult<()> {
373        if port == 0 || port > self.descriptor.ports {
374            return Err(HostError::Protocol);
375        }
376        Ok(())
377    }
378}