garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/drivers/usb/hub.rs

raw

//! USB hubs (class 9): a laptop's own (its webcam and Bluetooth are often
//! behind one), a dock's, a desk's. The hub is told to the controller as
//! one (its ports, its transaction translator's think time), its ports
//! are powered, each device on one is reset and addressed by its route
//! (`Place`), and its status-change endpoint says when a port changes
//! after that; the watching task then looks at its ports (`ports_changed`).
//! USB 2 hubs and USB 3 hubs (whose ports' status reads otherwise, and
//! which want their depth among the hubs told) alike.

use super::{Controller, Descriptor, Interface, Place, configure_hub_endpoints, physical};
use super::{TRB_IOC, TRB_NORMAL, TRB_SHORT_OK};
use crate::mm::pages;
use crate::println;
use alloc::sync::Arc;

/// A hub the controller holds: how many ports, its status-change endpoint
/// (DCI) and the page it reports into.
pub struct Hub {
    pub ports: u8,
    pub superspeed: bool,
    pub endpoint: u8,
    pub buffer: usize,
    pub length: usize,
    /// Where it is, for its devices' names in the log (`2`, `2.3`).
    pub name: alloc::string::String,
}

// Port features (SET_FEATURE / CLEAR_FEATURE), and the change features.
const PORT_RESET: u16 = 4;
const PORT_POWER: u16 = 8;
const C_PORT_CONNECTION: u16 = 16;
const C_PORT_ENABLE: u16 = 17;
const C_PORT_SUSPEND: u16 = 18;
const C_PORT_OVER_CURRENT: u16 = 19;
const C_PORT_RESET: u16 = 20;
const C_PORT_LINK_STATE: u16 = 25;
const C_PORT_CONFIG_ERROR: u16 = 26;
const C_BH_PORT_RESET: u16 = 29;

/// wPortStatus: connected, enabled; on a USB 2 hub low speed (bit 9) and
/// high speed (bit 10).
const CONNECTED: u16 = 1;
const ENABLED: u16 = 1 << 1;
const LOW_SPEED: u16 = 1 << 9;
const HIGH_SPEED: u16 = 1 << 10;
/// wPortChange: the reset done (bit 4; a warm reset's, bit 5, on USB 3).
const RESET_DONE: u16 = 1 << 4;
const WARM_RESET_DONE: u16 = 1 << 5;

fn set_feature(controller: &Controller, slot: u8, port: u8, feature: u16, page: usize) -> bool {
    let f = feature.to_le_bytes();
    controller
        .control(slot, [0x23, 3, f[0], f[1], port, 0, 0, 0], page, 0)
        .is_some()
}

fn clear_feature(controller: &Controller, slot: u8, port: u8, feature: u16, page: usize) {
    let f = feature.to_le_bytes();
    controller.control(slot, [0x23, 1, f[0], f[1], port, 0, 0, 0], page, 0);
}

/// GET_STATUS of a port: wPortStatus, wPortChange.
fn status(controller: &Controller, slot: u8, port: u8, page: usize) -> Option<(u16, u16)> {
    let n = controller.control(slot, [0xa3, 0, 0, 0, port, 0, 4, 0], page, 4)?;
    if n < 4 {
        return None;
    }
    // SAFETY: the four bytes the hub wrote, in our page.
    let b = unsafe { core::slice::from_raw_parts(page as *const u8, 4) };
    Some((u16::from_le_bytes([b[0], b[1]]), u16::from_le_bytes([b[2], b[3]])))
}

fn wait_ms(ms: u64) {
    let end = crate::timer::now_ms() + ms;
    while crate::timer::now_ms() < end {
        core::hint::spin_loop();
    }
}

/// Takes the hub in `slot` (`name` where it is): tells the controller,
/// powers its ports, attaches what is on them and starts listening for
/// changes. True when it is a hub the controller took.
pub fn attach(
    controller: &Arc<Controller>,
    slot: u8,
    name: &str,
    d: &Descriptor,
    interface: &Interface,
    page: usize,
) -> bool {
    let Some(&endpoint) = interface
        .endpoints
        .iter()
        .find(|e| e.0 & 0x80 != 0 && e.1 & 3 == 3)
    else {
        return false;
    };
    let (place, speed) = {
        let h = controller.host.lock();
        let Some(s) = h.slots.iter().find(|s| s.id == slot) else {
            return false;
        };
        (s.place, s.speed)
    };
    if place.depth >= 5 {
        println!(
            "usb{}: port {name}: a hub five deep, past what USB allows",
            controller.number
        );
        return false;
    }
    let superspeed = speed >= 4;
    // The hub's descriptor: USB 3's (0x2a) or USB 2's (0x29).
    let kind = if superspeed { 0x2a } else { 0x29 };
    let Some(n) = controller.control(slot, [0xa0, 6, 0, kind, 0, 0, 16, 0], page, 16) else {
        return false;
    };
    // SAFETY: the bytes the hub wrote, in our page.
    let descriptor = unsafe { core::slice::from_raw_parts(page as *const u8, n) }.to_vec();
    if descriptor.len() < 7 {
        return false;
    }
    let ports = descriptor[2].min(15);
    let characteristics = u16::from_le_bytes([descriptor[3], descriptor[4]]);
    let power_on_ms = u64::from(descriptor[5]) * 2;
    // A high-speed hub's translator think time, in its characteristics' bits 5–6.
    let ttt = if speed == 3 {
        u32::from(characteristics >> 5 & 3)
    } else {
        0
    };
    let Some(dcis) = configure_hub_endpoints(controller, slot, &[endpoint], ports, ttt) else {
        println!(
            "usb{}: port {name}: the controller would not take the hub",
            controller.number
        );
        return false;
    };
    if superspeed {
        // SET_HUB_DEPTH: how many hubs are above it.
        controller.control(slot, [0x20, 12, place.depth, 0, 0, 0, 0, 0], page, 0);
    }
    for port in 1..=ports {
        set_feature(controller, slot, port, PORT_POWER, page);
    }
    wait_ms(power_on_ms.max(20));
    let Some(buffer) = pages::alloc(0) else {
        return false;
    };
    let length = (usize::from(ports) + 1).div_ceil(8);
    {
        let mut h = controller.host.lock();
        if let Some(s) = h.slots.iter_mut().find(|s| s.id == slot) {
            s.hub = Some(Hub {
                ports,
                superspeed,
                endpoint: dcis[0],
                buffer,
                length,
                name: name.into(),
            });
        }
    }
    println!(
        "usb{}: port {name}: hub ({}), {ports} ports{}",
        controller.number,
        d.product_name,
        if superspeed { ", USB 3" } else { "" }
    );
    // What is plugged in already.
    for port in 1..=ports {
        port_changed(controller, slot, port, page);
    }
    // Then listening: a report each time a port changes.
    let mut h = controller.host.lock();
    if let Some(s) = h.slots.iter_mut().find(|s| s.id == slot)
        && let Some(ring) = s.rings[dcis[0] as usize].as_mut()
    {
        ring.push(
            physical(buffer) as u64,
            length as u32,
            TRB_NORMAL << 10 | TRB_IOC | TRB_SHORT_OK,
        );
    }
    h.ring_doorbell(slot, u32::from(dcis[0]));
    true
}

/// The hub in `slot` says a port changed: each is looked at. With the
/// controller's one-at-a-time lock held.
pub fn ports_changed(controller: &Arc<Controller>, slot: u8) {
    let ports = {
        let h = controller.host.lock();
        h.slots
            .iter()
            .find(|s| s.id == slot)
            .and_then(|s| s.hub.as_ref())
            .map(|hub| hub.ports)
    };
    let Some(ports) = ports else { return };
    let Some(page) = pages::alloc(0) else { return };
    for port in 1..=ports {
        port_changed(controller, slot, port, page);
    }
    pages::free(page, 0);
}

/// Port `port` of the hub in `slot`: what changed cleared, a device that
/// came reset and attached, one that went let go of.
fn port_changed(controller: &Arc<Controller>, slot: u8, port: u8, page: usize) {
    let Some((now, changed)) = status(controller, slot, port, page) else {
        return;
    };
    let superspeed = {
        let h = controller.host.lock();
        h.slots
            .iter()
            .find(|s| s.id == slot)
            .and_then(|s| s.hub.as_ref())
            .is_some_and(|h| h.superspeed)
    };
    let clears: &[(u16, u16)] = if superspeed {
        &[
            (1, C_PORT_CONNECTION),
            (1 << 3, C_PORT_OVER_CURRENT),
            (1 << 4, C_PORT_RESET),
            (1 << 5, C_BH_PORT_RESET),
            (1 << 6, C_PORT_LINK_STATE),
            (1 << 7, C_PORT_CONFIG_ERROR),
        ]
    } else {
        &[
            (1, C_PORT_CONNECTION),
            (1 << 1, C_PORT_ENABLE),
            (1 << 2, C_PORT_SUSPEND),
            (1 << 3, C_PORT_OVER_CURRENT),
            (1 << 4, C_PORT_RESET),
        ]
    };
    for &(bit, feature) in clears {
        if changed & bit != 0 {
            clear_feature(controller, slot, port, feature, page);
        }
    }
    let child = {
        let h = controller.host.lock();
        h.slots
            .iter()
            .find(|s| s.parent == Some((slot, port)))
            .map(|s| s.id)
    };
    let (hub_place, hub_speed, hub_name) = {
        let h = controller.host.lock();
        let Some(s) = h.slots.iter().find(|s| s.id == slot) else {
            return;
        };
        (
            s.place,
            s.speed,
            s.hub.as_ref().map(|h| h.name.clone()).unwrap_or_default(),
        )
    };
    let name = alloc::format!("{hub_name}.{port}");
    match (now & CONNECTED != 0, child) {
        (true, None) => {
            let Some(speed) = reset(controller, slot, port, superspeed, page) else {
                println!("usb{}: port {name} did not reset", controller.number);
                return;
            };
            // Behind a high-speed hub, a slower device's transfers go
            // through that hub's translator; behind a slower hub, through
            // the one it is behind, if any.
            let tt = if matches!(speed, 1 | 2) && hub_speed == 3 {
                Some((slot, port))
            } else {
                hub_place.tt
            };
            let place = Place {
                root: hub_place.root,
                route: hub_place.route | u32::from(port.min(15)) << (4 * u32::from(hub_place.depth)),
                depth: hub_place.depth + 1,
                parent: Some((slot, port)),
                tt,
            };
            super::attach_at(controller, place, speed, &name);
        }
        (false, Some(child)) => {
            super::let_go(controller, child);
            println!("usb{}: port {name}: unplugged", controller.number);
        }
        _ => {}
    }
}

/// Resets port `port` of the hub in `slot` and waits for it: the device's
/// speed as the controller numbers them (1 full, 2 low, 3 high, 4 super),
/// or None when it did not come back enabled.
fn reset(controller: &Controller, slot: u8, port: u8, superspeed: bool, page: usize) -> Option<u32> {
    // A USB 3 port is enabled by its link; reset it only if it is not.
    let (now, _) = status(controller, slot, port, page)?;
    if !(superspeed && now & ENABLED != 0) {
        set_feature(controller, slot, port, PORT_RESET, page);
        let deadline = crate::timer::now_ms() + 500;
        loop {
            wait_ms(10);
            let (_, changed) = status(controller, slot, port, page)?;
            if changed & (RESET_DONE | WARM_RESET_DONE) != 0 {
                clear_feature(controller, slot, port, C_PORT_RESET, page);
                break;
            }
            if crate::timer::now_ms() > deadline {
                return None;
            }
        }
        // The reset's recovery time, before the device is spoken to.
        wait_ms(10);
    }
    let (now, _) = status(controller, slot, port, page)?;
    if now & ENABLED == 0 && !superspeed {
        return None;
    }
    Some(if superspeed {
        4
    } else if now & LOW_SPEED != 0 {
        2
    } else if now & HIGH_SPEED != 0 {
        3
    } else {
        1
    })
}