usb-stack 0.3.0

MCU-independent USB device and host stack core: bus traits, control transfers, enumeration, classes (CDC-ACM, HID, GS_USB, i2c-tiny-usb, UAC 1.0) and a HID host
Documentation
//! USB hubs.
//!
//! A hub is an ordinary device with one class-specific interface: the host
//! powers its downstream ports, waits for a device to appear, resets the port
//! and then enumerates the new device at address zero. [`Hub`] wraps the
//! [`Device`] that enumerated the hub and performs those steps.
//!
//! ```text
//! let device = host.enumerate()?;             // the hub itself
//! let hub = Hub::open(&device)?;              // SET_CONFIGURATION + hub descriptor
//! hub.power_ports()?;                         // PORT_POWER on every port
//! hub.wait_for_connection(1, 2000)?;          // something was plugged in
//! hub.reset_port(1)?;                         // PORT_RESET, wait for C_PORT_RESET
//! let child = hub.enumerate_child(1, address)?;
//! ```
//!
//! The hub is left configured and powered, so a later device on the same port
//! only needs [`reset_port`](Hub::reset_port) and
//! [`enumerate_child`](Hub::enumerate_child).
//!
//! Devices behind a high-speed hub that run at full or low speed need the
//! hub's transaction translator. [`enumerate_child`](Hub::enumerate_child)
//! records it in the [`HubRoute`] it hands to the controller; controllers
//! without split-transaction support report [`HostError::Unsupported`].

use crate::descriptor::{class_code, descriptor_type, hub};
use crate::endpoint::Direction;
use crate::host::controller::{DeviceAddress, HostController, HubRoute, Speed, Translator};
use crate::host::device::Device;
use crate::host::error::{HostError, HostResult};
use crate::request::{Recipient, Request, RequestType, StandardRequest};

/// Room for the hub descriptor: the nine-byte header plus the removable and
/// port-power bitmaps of a fifteen-port hub.
const DESCRIPTOR_MAX: usize = 15;

/// How often the driver polls a port while it waits for a change.
const POLL_MS: u32 = 5;

/// How long a port reset may take before it is reported as a timeout.
const RESET_TIMEOUT_MS: u32 = 200;

// ─── Hub descriptor ──────────────────────────────────────────────────────────

/// The hub class descriptor (USB 2.0 §11.23.2.1).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HubDescriptor {
    /// `bNbrPorts`.
    pub ports: u8,
    /// `wHubCharacteristics`.
    pub characteristics: u16,
    /// `bPwrOn2PwrGood` converted to milliseconds.
    pub power_on_delay_ms: u32,
}

impl HubDescriptor {
    /// Length of the descriptor header; the bitmaps that follow depend on the
    /// port count.
    pub const LEN: usize = 9;

    /// Parse the bytes returned by the class-specific `GET_DESCRIPTOR`.
    pub fn parse(bytes: &[u8]) -> HostResult<Self> {
        if bytes.len() < Self::LEN || bytes[0] < Self::LEN as u8 || bytes[1] != descriptor_type::HUB
        {
            return Err(HostError::Malformed);
        }
        Ok(Self {
            ports: bytes[2],
            characteristics: u16::from_le_bytes([bytes[3], bytes[4]]),
            // bPwrOn2PwrGood counts two-millisecond units.
            power_on_delay_ms: u32::from(bytes[5]) * 2,
        })
    }

    /// Logical power switching mode.
    #[inline]
    pub fn power_switching(&self) -> u16 {
        self.characteristics & hub::characteristics::POWER_SWITCHING_MASK
    }

    /// Transaction translator think time, in high-speed hubs.
    #[inline]
    pub fn tt_think_time(&self) -> u8 {
        ((self.characteristics & hub::characteristics::TT_THINK_TIME_MASK)
            >> hub::characteristics::TT_THINK_TIME_SHIFT) as u8
    }
}

// ─── Port status ─────────────────────────────────────────────────────────────

/// What `GET_STATUS` reports for a downstream port.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct HubPortStatus {
    /// `wPortStatus`.
    pub status: u16,
    /// `wPortChange`.
    pub change: u16,
}

impl HubPortStatus {
    /// A device is attached.
    #[inline]
    pub fn connected(&self) -> bool {
        self.status & hub::port_status::CONNECTION != 0
    }

    /// The port is enabled and can be used.
    #[inline]
    pub fn enabled(&self) -> bool {
        self.status & hub::port_status::ENABLE != 0
    }

    /// The port is drawing too much current.
    #[inline]
    pub fn over_current(&self) -> bool {
        self.status & hub::port_status::OVER_CURRENT != 0
    }

    /// Speed of the attached device.
    ///
    /// A full-speed hub never sets [`HIGH_SPEED`](hub::port_status::HIGH_SPEED),
    /// so this is [`Speed::Full`] unless the low-speed bit is set.
    #[inline]
    pub fn speed(&self) -> Speed {
        if self.status & hub::port_status::HIGH_SPEED != 0 {
            Speed::High
        } else if self.status & hub::port_status::LOW_SPEED != 0 {
            Speed::Low
        } else {
            Speed::Full
        }
    }
}

// ─── Hub ─────────────────────────────────────────────────────────────────────

/// An enumerated hub.
pub struct Hub<'d, 'a, C: HostController> {
    device: &'a Device<'d, C>,
    descriptor: HubDescriptor,
}

impl<'d, 'a, C: HostController> Hub<'d, 'a, C> {
    /// Select the hub's configuration and read its class descriptor.
    ///
    /// The hub keeps answering control requests either way, but its
    /// downstream ports cannot be powered before `SET_CONFIGURATION`.
    pub fn open(device: &'a Device<'d, C>) -> HostResult<Self> {
        let class = device.descriptor().class;
        // A high-speed hub reports protocol 1 or 2 (single or multiple TT), so
        // match the class and subclass instead of the whole triple.
        let interface = device
            .configuration()
            .interfaces()
            .any(|interface| interface.class() == class_code::HUB && interface.sub_class() == 0);
        if class != class_code::HUB && !interface {
            return Err(HostError::Protocol);
        }

        let value = device.configuration().value();
        if value != 0 {
            device.set_configuration(value)?;
        }

        let mut raw = [0u8; DESCRIPTOR_MAX];
        let request = Request::custom(
            Direction::In,
            RequestType::Class,
            Recipient::Device,
            StandardRequest::GET_DESCRIPTOR,
            (descriptor_type::HUB as u16) << 8,
            0,
            DESCRIPTOR_MAX as u16,
        );
        let length = device.control(&request, &mut raw)?;
        let descriptor = HubDescriptor::parse(&raw[..length])?;

        Ok(Self { device, descriptor })
    }

    /// The hub device that was enumerated.
    #[inline]
    pub fn device(&self) -> &'a Device<'d, C> {
        self.device
    }

    /// The class descriptor read in [`open`](Self::open).
    #[inline]
    pub fn descriptor(&self) -> &HubDescriptor {
        &self.descriptor
    }

    /// Number of downstream ports.
    #[inline]
    pub fn ports(&self) -> u8 {
        self.descriptor.ports
    }

    /// Power every downstream port that is not powered yet and wait for
    /// `bPwrOn2PwrGood` to elapse.
    ///
    /// A ganged hub powers all ports from one switch, so the first request
    /// already powers the rest; asking port by port is harmless and keeps the
    /// driver independent of the switching mode.
    pub fn power_ports(&self) -> HostResult<()> {
        for port in 1..=self.descriptor.ports {
            let status = self.port_status(port)?;
            if status.status & hub::port_status::POWER == 0 {
                self.set_port_feature(port, hub::feature::PORT_POWER)?;
            }
        }
        self.device
            .controller()
            .wait_millis(self.descriptor.power_on_delay_ms);
        Ok(())
    }

    /// Read `wPortStatus` and `wPortChange` of `port`.
    pub fn port_status(&self, port: u8) -> HostResult<HubPortStatus> {
        self.check_port(port)?;
        let request = Request::custom(
            Direction::In,
            RequestType::Class,
            Recipient::Other,
            StandardRequest::GET_STATUS,
            0,
            u16::from(port),
            4,
        );
        let mut raw = [0u8; 4];
        if self.device.control(&request, &mut raw)? < raw.len() {
            return Err(HostError::Malformed);
        }
        Ok(HubPortStatus {
            status: u16::from_le_bytes([raw[0], raw[1]]),
            change: u16::from_le_bytes([raw[2], raw[3]]),
        })
    }

    /// Clear every change bit in `change`.
    ///
    /// The change bits of `wPortChange` map one to one onto the `C_PORT_*`
    /// feature selectors, which is why the selector is the bit position plus
    /// the selector of `C_PORT_CONNECTION`.
    pub fn clear_port_change(&self, port: u8, change: u16) -> HostResult<()> {
        for bit in 0..5u16 {
            if change & (1 << bit) != 0 {
                self.clear_port_feature(port, hub::feature::C_PORT_CONNECTION + bit)?;
            }
        }
        Ok(())
    }

    /// Wait until a device is attached to `port`.
    pub fn wait_for_connection(&self, port: u8, timeout_ms: u32) -> HostResult<HubPortStatus> {
        self.poll_until(port, timeout_ms, HubPortStatus::connected)
    }

    /// Reset `port` and report the speed of the device behind it.
    ///
    /// This is what the root port's `reset_port` does for the hub itself: the
    /// device answers at address zero afterwards and has to be enumerated with
    /// [`enumerate_child`](Self::enumerate_child).
    pub fn reset_port(&self, port: u8) -> HostResult<Speed> {
        let status = self.port_status(port)?;
        if !status.connected() {
            return Err(HostError::Disconnected);
        }
        // A stale change bit would make the new reset look like an old event.
        self.clear_port_change(port, status.change)?;

        // PORT_RESET is only defined for a disabled port. A device that is
        // being re-enumerated may still be enabled from the previous round.
        if status.enabled() {
            self.clear_port_feature(port, hub::feature::PORT_ENABLE)?;
            let status = self.poll_until(port, RESET_TIMEOUT_MS, |status| !status.enabled())?;
            self.clear_port_change(port, status.change)?;
        }

        self.set_port_feature(port, hub::feature::PORT_RESET)?;
        let status = self.poll_until(port, RESET_TIMEOUT_MS, |status| {
            status.change & hub::port_change::RESET != 0
        })?;
        self.clear_port_change(port, status.change)?;

        if !status.enabled() {
            return Err(HostError::Disconnected);
        }
        Ok(status.speed())
    }

    /// Enumerate the device attached to `port` at `address`.
    ///
    /// The port must have been reset with [`reset_port`](Self::reset_port)
    /// first.
    pub fn enumerate_child(&self, port: u8, address: DeviceAddress) -> HostResult<Device<'d, C>> {
        let status = self.port_status(port)?;
        if !status.connected() || !status.enabled() {
            return Err(HostError::Disconnected);
        }
        let speed = status.speed();
        let route = self.child_route(port, speed);
        Device::enumerate_downstream(self.device.controller(), address, speed, route)
    }

    fn child_route(&self, port: u8, speed: Speed) -> HubRoute {
        let translator = match (self.device.speed(), speed) {
            // High speed all the way: the hub just forwards the packets.
            (Speed::High, Speed::High) => None,
            // A FS/LS device behind a high-speed hub needs this hub's
            // transaction translator.
            (Speed::High, _) => Some(Translator {
                hub: self.device.address(),
                port,
            }),
            // A FS hub is transparent; a device behind it inherits whatever
            // translator the hub itself uses.
            _ => self.device.route().and_then(|route| route.translator),
        };
        HubRoute {
            hub: self.device.address(),
            port,
            translator,
        }
    }

    fn poll_until(
        &self,
        port: u8,
        timeout_ms: u32,
        satisfied: impl Fn(&HubPortStatus) -> bool,
    ) -> HostResult<HubPortStatus> {
        let mut waited = 0;
        loop {
            let status = self.port_status(port)?;
            if satisfied(&status) {
                return Ok(status);
            }
            if waited >= timeout_ms {
                return Err(HostError::Timeout);
            }
            self.device.controller().wait_millis(POLL_MS);
            waited += POLL_MS;
        }
    }

    fn set_port_feature(&self, port: u8, feature: u16) -> HostResult<()> {
        self.port_request(StandardRequest::SET_FEATURE, feature, port)
    }

    fn clear_port_feature(&self, port: u8, feature: u16) -> HostResult<()> {
        self.port_request(StandardRequest::CLEAR_FEATURE, feature, port)
    }

    fn port_request(&self, request: u8, feature: u16, port: u8) -> HostResult<()> {
        self.check_port(port)?;
        let request = Request::custom(
            Direction::Out,
            RequestType::Class,
            Recipient::Other,
            request,
            feature,
            u16::from(port),
            0,
        );
        self.device.control(&request, &mut [])?;
        Ok(())
    }

    fn check_port(&self, port: u8) -> HostResult<()> {
        if port == 0 || port > self.descriptor.ports {
            return Err(HostError::Protocol);
        }
        Ok(())
    }
}