garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/usb/mod.rs

raw

//! USB, through an xHCI host controller (eXtensible Host Controller
//! Interface 1.2), on PCI (class 0c:03:30): what every PC and laptop of the
//! last decade has, and most ARM boards. The controller is set up, each
//! device on its root ports is given an address, its descriptors are read
//! and a configuration chosen, and a class driver takes what it offers:
//! keyboards, mice and tablets (`hid`) and sticks and disks (`storage`).
//! Devices plugged in later, and pulled out, arrive as port changes, which
//! a kernel task of its own handles ([`watch`]). A hub (`hub`) is a device
//! too, whose ports are looked after the same way, a level down: what is
//! behind it is addressed by its route through the hubs (the route
//! string), as a laptop's webcam, a dock's ports and a desk's hub are.
//!
//! Synchronous work (commands, control transfers, a stick's requests) goes
//! one at a time per controller, behind a sleeping lock; its completion
//! arrives as an event, by interrupt (MSI-X on a PC, INTx on ARM), and the
//! waiting task sleeps meanwhile (`block::wait`). Input devices' reports
//! arrive the same way and are handled in the interrupt itself.
//!
//! Not here yet: isochronous transfers (audio, cameras), USB 3's streams.
//!
//! Beside it, `ohci`: the USB 1.1 controller an ARM board's USB 2.0 host
//! hands its keyboards and mice to, a Pinebook Pro's own among them.

pub mod hid;
pub mod hub;
pub mod ohci;
pub mod storage;

use crate::drivers::block;
use crate::mm::pages;
use crate::mmu::physical;
use crate::println;
use crate::sync::{Mutex, SpinLock};
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicBool, Ordering, fence};

const CLASS: u32 = 0x0c_03_30;

// Operational registers, from the capability registers' length on.
const USBCMD: usize = 0x00;
const USBSTS: usize = 0x04;
const CRCR: usize = 0x18;
const DCBAAP: usize = 0x30;
const CONFIG: usize = 0x38;
const PORTS: usize = 0x400;
const CMD_RUN: u32 = 1;
const CMD_RESET: u32 = 1 << 1;
const CMD_INTERRUPTS: u32 = 1 << 2;
const STS_HALTED: u32 = 1;
const STS_EVENT: u32 = 1 << 3;
const STS_NOT_READY: u32 = 1 << 11;

const PORT_CONNECTED: u32 = 1;
const PORT_ENABLED: u32 = 1 << 1;
const PORT_RESET: u32 = 1 << 4;
const PORT_POWER: u32 = 1 << 9;
/// The change bits, each cleared by writing it 1.
const PORT_CHANGES: u32 = 0x7f << 17;
const PORT_RESET_CHANGE: u32 = 1 << 21;
/// The bits a write must give back as read, so as to change nothing else
/// (never PORT_ENABLED, whose 1 turns the port off).
const PORT_PRESERVE: u32 = 0x0e00_c3e0;

// TRB types.
const TRB_NORMAL: u32 = 1;
const TRB_SETUP: u32 = 2;
const TRB_DATA: u32 = 3;
const TRB_STATUS: u32 = 4;
const TRB_LINK: u32 = 6;
const TRB_ENABLE_SLOT: u32 = 9;
const TRB_DISABLE_SLOT: u32 = 10;
const TRB_ADDRESS_DEVICE: u32 = 11;
const TRB_CONFIGURE_ENDPOINT: u32 = 12;
const TRB_EVALUATE_CONTEXT: u32 = 13;
const TRB_TRANSFER_EVENT: u32 = 32;
const TRB_COMMAND_COMPLETION: u32 = 33;
const TRB_PORT_STATUS_CHANGE: u32 = 34;
const TRB_CYCLE: u32 = 1;
const TRB_TOGGLE: u32 = 1 << 1;
const TRB_SHORT_OK: u32 = 1 << 2;
const TRB_IOC: u32 = 1 << 5;
const TRB_IMMEDIATE: u32 = 1 << 6;
const TRB_IN: u32 = 1 << 16;

const CODE_SUCCESS: u32 = 1;
const CODE_SHORT: u32 = 13;

/// TRBs in a ring: one page, the last a link back to the first.
const RING: usize = 256;

/// A ring of TRBs the driver produces: commands, or a transfer ring.
struct Ring {
    base: usize,
    at: usize,
    cycle: bool,
}

impl Ring {
    fn new() -> Option<Ring> {
        let base = pages::alloc(0)?;
        // SAFETY: a fresh page, ours.
        unsafe { core::ptr::write_bytes(base as *mut u8, 0, crate::mm::PAGE) };
        Some(Ring {
            base,
            at: 0,
            cycle: true,
        })
    }

    fn physical(&self) -> u64 {
        physical(self.base) as u64
    }

    fn write(&self, index: usize, parameter: u64, status: u32, control: u32) {
        let at = (self.base + index * 16) as *mut u32;
        // SAFETY: a TRB of the ring's page.
        unsafe {
            at.write_volatile(parameter as u32);
            at.add(1).write_volatile((parameter >> 32) as u32);
            at.add(2).write_volatile(status);
            fence(Ordering::SeqCst);
            // The control word, with its cycle bit, last: it hands the TRB over.
            at.add(3).write_volatile(control);
        }
    }

    /// Puts a TRB on the ring; its physical address, as events name it.
    fn push(&mut self, parameter: u64, status: u32, control: u32) -> u64 {
        let cycle = if self.cycle { TRB_CYCLE } else { 0 };
        let address = self.physical() + self.at as u64 * 16;
        self.write(self.at, parameter, status, control | cycle);
        self.at += 1;
        if self.at == RING - 1 {
            self.write(self.at, self.physical(), 0, TRB_LINK << 10 | TRB_TOGGLE | cycle);
            self.at = 0;
            self.cycle = !self.cycle;
        }
        address
    }
}

/// The ring of events the controller produces, and its one-entry table.
struct Events {
    base: usize,
    table: usize,
    at: usize,
    cycle: bool,
}

/// An event, as read off the ring.
#[derive(Clone, Copy, Debug)]
struct Event {
    parameter: u64,
    status: u32,
    control: u32,
}

impl Event {
    fn kind(&self) -> u32 {
        (self.control >> 10) & 0x3f
    }
    fn code(&self) -> u32 {
        self.status >> 24
    }
    fn slot(&self) -> u8 {
        (self.control >> 24) as u8
    }
    fn endpoint(&self) -> u8 {
        ((self.control >> 16) & 0x1f) as u8
    }
}

/// What a synchronous request waits for: its command's completion, or a
/// transfer's on (slot, endpoint).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Pending {
    Command,
    Transfer(u8, u8),
}

/// A device, as far as the controller is concerned.
struct Slot {
    id: u8,
    /// The root port it is behind, and where: the hub's slot and port
    /// when it is behind one.
    port: u8,
    parent: Option<(u8, u8)>,
    /// Where it is, as `address` gave it.
    place: Place,
    /// Its speed, as the slot context has it (1 full, 2 low, 3 high, 4 on).
    speed: u32,
    /// A hub: its ports, and its status-change endpoint.
    hub: Option<hub::Hub>,
    /// Its transfer rings, by endpoint (DCI 1–31; 1 the control endpoint).
    rings: [Option<Ring>; 32],
    /// The input device's endpoints and what reads their reports.
    inputs: Vec<hid::Reader>,
    device_context: usize,
    /// For a storage device: told when it goes, and its disk's name.
    gone: Option<(Arc<AtomicBool>, String)>,
}

/// One controller.
struct Host {
    regs: usize,
    op: usize,
    runtime: usize,
    doorbells: usize,
    /// 64-byte contexts, not 32.
    wide: bool,
    ports: u8,
    commands: Ring,
    events: Events,
    dcbaa: usize,
    slots: Vec<Slot>,
    pending: Option<Pending>,
    /// The completion of what was pending: its code, the bytes not
    /// transferred, and for a command its slot.
    result: Option<(u32, u32, u8)>,
    waiter: Option<usize>,
    /// Ports whose status changed, for the watching task.
    changed: u32,
    /// Hubs (by slot) whose ports changed.
    hubs_changed: Vec<u8>,
}

impl Host {
    fn read(&self, at: usize) -> u32 {
        // SAFETY: the controller's registers.
        unsafe { (at as *const u32).read_volatile() }
    }

    fn write(&self, at: usize, value: u32) {
        // SAFETY: as in `read`.
        unsafe { (at as *mut u32).write_volatile(value) }
    }

    fn write64(&self, at: usize, value: u64) {
        self.write(at, value as u32);
        self.write(at + 4, (value >> 32) as u32);
    }

    fn portsc(&self, port: u8) -> usize {
        self.op + PORTS + 0x10 * (port as usize - 1)
    }

    fn context_size(&self) -> usize {
        if self.wide { 64 } else { 32 }
    }

    fn ring_doorbell(&self, slot: u8, target: u32) {
        fence(Ordering::SeqCst);
        self.write(self.doorbells + 4 * slot as usize, target);
    }

    fn slot(&mut self, id: u8) -> Option<&mut Slot> {
        self.slots.iter_mut().find(|s| s.id == id)
    }

    /// Takes every event waiting; returns the input events to deliver.
    fn collect(&mut self) -> Vec<pinnacle_abi::InputEvent> {
        let mut input = Vec::new();
        let interrupter = self.runtime + 0x20;
        loop {
            let at = self.events.base + self.events.at * 16;
            // SAFETY: the event ring's TRB at its dequeue point.
            let control = unsafe { ((at + 12) as *const u32).read_volatile() };
            if (control & TRB_CYCLE != 0) != self.events.cycle {
                break;
            }
            fence(Ordering::SeqCst);
            // SAFETY: as above; the controller wrote it whole before its cycle bit.
            let event = unsafe {
                let p = at as *const u32;
                Event {
                    parameter: u64::from(p.read_volatile()) | u64::from(p.add(1).read_volatile()) << 32,
                    status: p.add(2).read_volatile(),
                    control,
                }
            };
            self.events.at += 1;
            if self.events.at == RING {
                self.events.at = 0;
                self.events.cycle = !self.events.cycle;
            }
            self.handle(event, &mut input);
        }
        // Where it may write next, and the handler busy bit cleared.
        let dequeue = physical(self.events.base) as u64 + self.events.at as u64 * 16;
        self.write64(interrupter + 0x18, dequeue | 1 << 3);
        input
    }

    fn handle(&mut self, event: Event, input: &mut Vec<pinnacle_abi::InputEvent>) {
        match event.kind() {
            TRB_COMMAND_COMPLETION if self.pending == Some(Pending::Command) => {
                self.result = Some((event.code(), 0, event.slot()));
            }
            TRB_TRANSFER_EVENT => {
                let (slot, endpoint) = (event.slot(), event.endpoint());
                if self.pending == Some(Pending::Transfer(slot, endpoint)) {
                    self.result = Some((event.code(), event.status & 0xff_ffff, slot));
                    return;
                }
                // A hub's status-change endpoint: one of its ports changed.
                if let Some(s) = self.slot(slot)
                    && let Some(hub) = s.hub.as_ref().filter(|h| h.endpoint == endpoint)
                {
                    let (buffer, length) = (hub.buffer, hub.length);
                    let ring = s.rings[endpoint as usize].as_mut().unwrap();
                    ring.push(
                        physical(buffer) as u64,
                        length as u32,
                        TRB_NORMAL << 10 | TRB_IOC | TRB_SHORT_OK,
                    );
                    if !self.hubs_changed.contains(&slot) {
                        self.hubs_changed.push(slot);
                    }
                    self.ring_doorbell(slot, u32::from(endpoint));
                    return;
                }
                let regs = self.doorbells;
                if let Some(s) = self.slot(slot)
                    && let Some(reader) = s.inputs.iter_mut().find(|r| r.endpoint == endpoint)
                {
                    if matches!(event.code(), CODE_SUCCESS | CODE_SHORT) {
                        reader.report(input);
                    }
                    // Offered again, for the next report.
                    let ring = s.rings[endpoint as usize].as_mut().unwrap();
                    ring.push(
                        physical(reader.buffer) as u64,
                        reader.length as u32,
                        TRB_NORMAL << 10 | TRB_IOC | TRB_SHORT_OK,
                    );
                    fence(Ordering::SeqCst);
                    // SAFETY: the slot's doorbell.
                    unsafe { ((regs + 4 * slot as usize) as *mut u32).write_volatile(u32::from(endpoint)) };
                }
            }
            TRB_PORT_STATUS_CHANGE => {
                let port = (event.parameter >> 24) as u8;
                if (1..=32).contains(&port) {
                    self.changed |= 1 << (port - 1);
                }
            }
            _ => {}
        }
    }
}

/// A controller: what its interrupt handler and its users share, and the
/// lock that lets one synchronous request at a time through.
pub struct Controller {
    host: SpinLock<Host>,
    ops: Mutex<()>,
    intid: u32,
    number: usize,
}

static CONTROLLERS: SpinLock<Vec<Arc<Controller>>> = SpinLock::new(Vec::new());

impl Controller {
    /// Waits for what is pending to complete: its code, the bytes left, and
    /// its slot.
    fn wait(&self) -> (u32, u32, u8) {
        let deadline = crate::timer::now_ms() + 5_000;
        let mut answer = None;
        block::wait(
            &self.host,
            |h| &mut h.waiter,
            |h| {
                let input = h.collect();
                deliver(input);
                if let Some(r) = h.result.take() {
                    answer = Some(r);
                    h.pending = None;
                    return true;
                }
                if crate::timer::now_ms() > deadline {
                    h.pending = None;
                    return true;
                }
                false
            },
        );
        // No answer in five seconds: a controller or device that hangs.
        answer.unwrap_or((0, 0, 0))
    }

    /// Runs a command and waits for it: its completion code and slot.
    fn command(&self, parameter: u64, control: u32) -> (u32, u8) {
        {
            let mut h = self.host.lock();
            h.pending = Some(Pending::Command);
            h.result = None;
            h.commands.push(parameter, 0, control);
            h.ring_doorbell(0, 0);
        }
        let (code, _, slot) = self.wait();
        (code, slot)
    }

    /// A control transfer on `slot`'s endpoint 0: `request` (the 8-byte
    /// setup packet), its data (`length` bytes in or out of `buffer`, a
    /// page of ours). The bytes moved, or None when it failed.
    fn control(&self, slot: u8, request: [u8; 8], buffer: usize, length: usize) -> Option<usize> {
        let into_host = request[0] & 0x80 != 0;
        {
            let mut h = self.host.lock();
            h.pending = Some(Pending::Transfer(slot, 1));
            h.result = None;
            let ring = h.slot(slot)?.rings[1].as_mut()?;
            let kind = match (length, into_host) {
                (0, _) => 0,
                (_, false) => 2,
                (_, true) => 3,
            };
            ring.push(
                u64::from_le_bytes(request),
                8,
                TRB_SETUP << 10 | TRB_IMMEDIATE | kind << 16,
            );
            if length > 0 {
                ring.push(
                    physical(buffer) as u64,
                    length as u32,
                    TRB_DATA << 10 | if into_host { TRB_IN } else { 0 },
                );
            }
            let status_in = length == 0 || !into_host;
            ring.push(
                0,
                0,
                TRB_STATUS << 10 | TRB_IOC | if status_in { TRB_IN } else { 0 },
            );
            h.ring_doorbell(slot, 1);
        }
        // The status stage's event: the data stage's own, without IOC,
        // reports only a short packet, which ends the transfer here too.
        let (code, left, _) = self.wait();
        match code {
            CODE_SUCCESS => Some(length),
            CODE_SHORT => Some(length.saturating_sub(left as usize)),
            _ => None,
        }
    }

    /// A bulk transfer on `slot`'s endpoint `dci`: `length` bytes in or out
    /// of `buffer` (physically contiguous). The bytes moved, or None.
    fn bulk(&self, slot: u8, dci: u8, buffer: usize, length: usize) -> Option<usize> {
        {
            let mut h = self.host.lock();
            h.pending = Some(Pending::Transfer(slot, dci));
            h.result = None;
            let ring = h.slot(slot)?.rings[dci 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(dci));
        }
        let (code, left, _) = self.wait();
        match code {
            CODE_SUCCESS | CODE_SHORT => Some(length.saturating_sub(left as usize)),
            _ => None,
        }
    }
}

/// Sends input events to whoever reads them (`input`).
fn deliver(events: Vec<pinnacle_abi::InputEvent>) {
    if !events.is_empty() {
        crate::drivers::input::deliver(events);
    }
}

/// Sets up every xHCI controller and the devices plugged into it. Returns
/// how many devices a class driver took.
pub fn init() -> usize {
    let mut taken = 0;
    let mut started = Vec::new();
    for f in crate::pci::find_class(CLASS) {
        crate::pci::claim(&f, "xhci", crate::device::Class::Other);
        let number = CONTROLLERS.lock().len();
        let Some(regs) = f.bar_address(0, 0) else {
            println!("usb{number}: no registers");
            continue;
        };
        let Some(intid) = f.take_interrupt() else {
            println!("usb{number}: no interrupt");
            continue;
        };
        let Some(host) = start(regs) else {
            println!("usb{number}: the controller did not start");
            continue;
        };
        let ports = host.ports;
        let controller = Arc::new(Controller {
            host: SpinLock::new(host),
            ops: Mutex::new(()),
            intid,
            number,
        });
        CONTROLLERS.lock().push(controller.clone());
        crate::gic::enable_shared(intid);
        println!("usb{number}: xHCI, {ports} ports");
        started.push((controller, alloc::vec![false; usize::from(ports)]));
    }
    // A real machine's devices come back a while after the controller's
    // reset (a USB 3 link trains again, a USB 2 device connects once its
    // port is powered): QEMU's are there at once, a stick on a laptop takes
    // up to a second. Each root port is tried as soon as it says connected,
    // until SETTLE_MS after the last controller started, so the stick the
    // system starts from is a disk before the disks are looked through.
    let deadline = crate::timer::now_ms() + SETTLE_MS;
    loop {
        for (controller, tried) in &mut started {
            for port in 1..=tried.len() as u8 {
                let done = &mut tried[usize::from(port) - 1];
                if *done {
                    continue;
                }
                let h = controller.host.lock();
                let connected = h.read(h.portsc(port)) & PORT_CONNECTED != 0;
                drop(h);
                if connected {
                    *done = true;
                    taken += usize::from(attach(controller, port));
                }
            }
        }
        let now = crate::timer::now_ms();
        if started.is_empty() || now >= deadline {
            break;
        }
        while crate::timer::now_ms() < now + 10 {
            core::hint::spin_loop();
        }
    }
    // What changed during the boot's own attaching is done with.
    for (controller, _) in &started {
        controller.host.lock().changed = 0;
    }
    // USB 1.1's own controllers, where a board's keyboard may be.
    taken + ohci::init()
}

/// How long the boot waits for root ports to say a device is there.
const SETTLE_MS: u64 = 1_500;

/// Waits `ms` milliseconds, spinning.
pub(crate) fn spin_ms(ms: u64) {
    let end = crate::timer::now_ms() + ms;
    while crate::timer::now_ms() < end {
        core::hint::spin_loop();
    }
}

/// Resets the controller at `regs`, gives it its memory and starts it.
fn start(regs: usize) -> Option<Host> {
    let read = |at: usize| {
        // SAFETY: the controller's registers.
        unsafe { (at as *const u32).read_volatile() }
    };
    let caplength = read(regs) & 0xff;
    let params1 = read(regs + 4);
    let params2 = read(regs + 8);
    let cparams = read(regs + 0x10);
    let op = regs + caplength as usize;
    let host = Host {
        regs,
        op,
        runtime: regs + (read(regs + 0x18) & !0x1f) as usize,
        doorbells: regs + (read(regs + 0x14) & !3) as usize,
        wide: cparams & (1 << 2) != 0,
        ports: (params1 >> 24) as u8,
        commands: Ring::new()?,
        events: Events {
            base: pages::alloc(0)?,
            table: pages::alloc(0)?,
            at: 0,
            cycle: true,
        },
        dcbaa: pages::alloc(0)?,
        slots: Vec::new(),
        pending: None,
        result: None,
        waiter: None,
        changed: 0,
        hubs_changed: Vec::new(),
    };
    take_from_firmware(&host, (cparams >> 16) as usize * 4);
    let wait = |cond: &dyn Fn() -> bool| {
        let deadline = crate::timer::now_ms() + 1_000;
        while !cond() {
            if crate::timer::now_ms() > deadline {
                return false;
            }
            core::hint::spin_loop();
        }
        true
    };
    host.write(op + USBCMD, host.read(op + USBCMD) & !CMD_RUN);
    if !wait(&|| read(op + USBSTS) & STS_HALTED != 0) {
        return None;
    }
    host.write(op + USBCMD, CMD_RESET);
    // Intel's controllers may hang the machine when read within a
    // millisecond of the reset (Linux waits as long).
    spin_ms(1);
    if !wait(&|| read(op + USBCMD) & CMD_RESET == 0 && read(op + USBSTS) & STS_NOT_READY == 0) {
        return None;
    }
    let slots = (params1 & 0xff).min(32);
    host.write(op + CONFIG, slots);
    // SAFETY: fresh pages, ours.
    unsafe {
        for page in [host.events.base, host.events.table, host.dcbaa] {
            core::ptr::write_bytes(page as *mut u8, 0, crate::mm::PAGE);
        }
    }
    // The scratchpad the controller may ask for, a page each, in DCBAA's
    // first entry.
    let scratchpads = ((params2 >> 21) & 0x1f) << 5 | (params2 >> 27);
    if scratchpads > 0 {
        let list = pages::alloc(0)?;
        for i in 0..scratchpads as usize {
            let page = pages::alloc(0)?;
            // SAFETY: a fresh page, and the list's entry.
            unsafe {
                core::ptr::write_bytes(page as *mut u8, 0, crate::mm::PAGE);
                (list as *mut u64).add(i).write(physical(page) as u64);
            }
        }
        // SAFETY: DCBAA's first entry.
        unsafe { (host.dcbaa as *mut u64).write(physical(list) as u64) };
    }
    host.write64(op + DCBAAP, physical(host.dcbaa) as u64);
    host.write64(op + CRCR, host.commands.physical() | 1);
    // The event ring: one segment, the whole page.
    // SAFETY: the table's one entry.
    unsafe {
        let t = host.events.table as *mut u32;
        let base = physical(host.events.base) as u64;
        t.write(base as u32);
        t.add(1).write((base >> 32) as u32);
        t.add(2).write(RING as u32);
    }
    let interrupter = host.runtime + 0x20;
    host.write(interrupter + 0x08, 1);
    host.write64(interrupter + 0x18, physical(host.events.base) as u64);
    host.write64(interrupter + 0x10, physical(host.events.table) as u64);
    // Interrupts on, at most one every 40 µs (160 × 250 ns).
    host.write(interrupter + 0x04, 160);
    host.write(interrupter, 0b11);
    host.write(op + USBCMD, CMD_RUN | CMD_INTERRUPTS);
    if !wait(&|| read(op + USBSTS) & STS_HALTED == 0) {
        return None;
    }
    // Every port powered.
    for port in 1..=host.ports {
        let at = host.portsc(port);
        let v = host.read(at);
        if v & PORT_POWER == 0 {
            host.write(at, (v & PORT_PRESERVE) | PORT_POWER);
        }
    }
    Some(host)
}

/// Takes the controller from a firmware that drove it (a PC's keyboard in
/// its setup screens): the USB Legacy Support capability's semaphores.
fn take_from_firmware(host: &Host, first: usize) {
    if first == 0 {
        return;
    }
    let mut at = host.regs + first;
    for _ in 0..64 {
        let cap = host.read(at);
        if cap & 0xff == 1 {
            const BIOS: u32 = 1 << 16;
            const OS: u32 = 1 << 24;
            host.write(at, cap | OS);
            let deadline = crate::timer::now_ms() + 1_000;
            while host.read(at) & BIOS != 0 && crate::timer::now_ms() < deadline {
                core::hint::spin_loop();
            }
            // Its SMIs off.
            host.write(at + 4, 0);
            return;
        }
        let next = ((cap >> 8) & 0xff) as usize * 4;
        if next == 0 {
            return;
        }
        at += next;
    }
}

/// A device's descriptor, as far as choosing a driver goes.
pub struct Descriptor {
    pub vendor: u16,
    pub product: u16,
    pub product_name: String,
}

/// An interface of the configuration chosen, with its endpoints.
#[derive(Clone, Debug)]
pub struct Interface {
    pub number: u8,
    pub class: u8,
    pub subclass: u8,
    pub protocol: u8,
    /// Endpoint address (bit 7: in), attributes, max packet size, interval.
    pub endpoints: Vec<(u8, u8, u16, u8)>,
    /// The HID descriptor's report descriptor length, for an input device.
    pub report_length: u16,
}

/// The endpoint context index of endpoint `address`.
fn dci(address: u8) -> u8 {
    (address & 0x0f) * 2 + (address >> 7)
}

/// Where a device is: the root port it is behind, its route through the
/// hubs between (a nibble a hub, the port on it), how many hubs that is,
/// the hub's slot and port it is on, and for a low- or full-speed device
/// behind a high-speed hub, the hub (slot, port) whose transaction
/// translator carries its transfers.
#[derive(Clone, Copy, Debug, Default)]
pub struct Place {
    pub root: u8,
    pub route: u32,
    pub depth: u8,
    pub parent: Option<(u8, u8)>,
    pub tt: Option<(u8, u8)>,
}

/// Gives the device on root port `port` an address, reads what it is and
/// hands its interfaces to the class drivers. True when one took it.
fn attach(controller: &Arc<Controller>, port: u8) -> bool {
    let _one = controller.ops.lock();
    let at = controller.host.lock().portsc(port);
    let read = |h: &Host| h.read(at);
    let portsc = read(&controller.host.lock());
    if portsc & PORT_CONNECTED == 0 {
        return false;
    }
    // A USB 2 port is enabled by a reset; a USB 3 one is by its link.
    if portsc & PORT_ENABLED == 0 {
        let h = controller.host.lock();
        h.write(at, (portsc & PORT_PRESERVE) | PORT_RESET);
        drop(h);
        let deadline = crate::timer::now_ms() + 500;
        loop {
            let v = read(&controller.host.lock());
            if v & PORT_RESET_CHANGE != 0 {
                break;
            }
            if crate::timer::now_ms() > deadline {
                println!("usb{}: port {port} did not reset", controller.number);
                return false;
            }
            core::hint::spin_loop();
        }
        // The reset's recovery time (USB 2.0, 7.1.7.5), as a hub's ports
        // are given it.
        spin_ms(10);
    }
    let h = controller.host.lock();
    let v = h.read(at);
    h.write(at, (v & PORT_PRESERVE) | (v & PORT_CHANGES));
    drop(h);
    if v & PORT_ENABLED == 0 {
        return false;
    }
    let speed = (v >> 10) & 0xf;
    let place = Place {
        root: port,
        ..Place::default()
    };
    attach_at(controller, place, speed, &alloc::format!("{port}"))
}

/// Addresses the device at `place`, of `speed`, and configures it, with
/// the controller's one-at-a-time lock held; `name` is where it is
/// (`2`, `2.3`), for the log. True when a class driver took it.
pub(crate) fn attach_at(controller: &Arc<Controller>, place: Place, speed: u32, name: &str) -> bool {
    let Some(slot) = address(controller, place, speed) else {
        println!("usb{}: port {name}: no address", controller.number);
        return false;
    };
    let Some(page) = pages::alloc(0) else { return false };
    let taken = configure(controller, slot, place.root, name, page);
    pages::free(page, 0);
    if !taken {
        let mut h = controller.host.lock();
        h.slots.retain(|s| s.id != slot);
        drop(h);
        controller.command(0, TRB_DISABLE_SLOT << 10 | u32::from(slot) << 24);
    }
    taken
}

/// Enables a slot for the device at `place` and addresses it. Its slot.
fn address(controller: &Arc<Controller>, place: Place, speed: u32) -> Option<u8> {
    let (code, slot) = controller.command(0, TRB_ENABLE_SLOT << 10);
    if code != CODE_SUCCESS || slot == 0 {
        return None;
    }
    let ep0 = Ring::new()?;
    let device_context = pages::alloc(0)?;
    let input = pages::alloc(0)?;
    let mut h = controller.host.lock();
    let size = h.context_size();
    // SAFETY: fresh pages, and DCBAA's entry for the slot.
    unsafe {
        core::ptr::write_bytes(device_context as *mut u8, 0, crate::mm::PAGE);
        core::ptr::write_bytes(input as *mut u8, 0, crate::mm::PAGE);
        (h.dcbaa as *mut u64)
            .add(slot as usize)
            .write(physical(device_context) as u64);
        let ctx = |n: usize| (input + n * size) as *mut u32;
        // Add the slot and endpoint 0.
        ctx(0).add(1).write(0b11);
        ctx(1).write(place.route & 0xf_ffff | speed << 20 | 1 << 27);
        ctx(1).add(1).write(u32::from(place.root) << 16);
        if let Some((hub, port)) = place.tt.filter(|_| matches!(speed, 1 | 2)) {
            ctx(1).add(2).write(u32::from(hub) | u32::from(port) << 8);
        }
        let packet: u32 = match speed {
            2 => 8,
            1 | 3 => 64,
            _ => 512,
        };
        // Control, three retries, its packet size, its ring.
        ctx(2).add(1).write(3 << 1 | 4 << 3 | packet << 16);
        let ring = ep0.physical() | 1;
        ctx(2).add(2).write(ring as u32);
        ctx(2).add(3).write((ring >> 32) as u32);
        ctx(2).add(4).write(8);
    }
    let mut rings: [Option<Ring>; 32] = Default::default();
    rings[1] = Some(ep0);
    h.slots.push(Slot {
        id: slot,
        port: place.root,
        parent: place.parent,
        place,
        speed,
        hub: None,
        rings,
        inputs: Vec::new(),
        device_context,
        gone: None,
    });
    drop(h);
    let (code, _) = controller.command(
        physical(input) as u64,
        TRB_ADDRESS_DEVICE << 10 | u32::from(slot) << 24,
    );
    pages::free(input, 0);
    (code == CODE_SUCCESS).then_some(slot)
}

/// GET_DESCRIPTOR of `kind` (index `index`), up to `length` bytes into `page`.
fn get_descriptor(
    controller: &Controller,
    slot: u8,
    kind: u8,
    index: u8,
    page: usize,
    length: u16,
) -> Option<usize> {
    let l = length.to_le_bytes();
    controller.control(
        slot,
        [0x80, 6, index, kind, 0, 0, l[0], l[1]],
        page,
        length as usize,
    )
}

/// A string descriptor, in English where it has a choice.
fn string(controller: &Controller, slot: u8, index: u8, page: usize) -> String {
    if index == 0 {
        return String::new();
    }
    let l = 255u16.to_le_bytes();
    let Some(n) = controller.control(slot, [0x80, 6, index, 3, 0x09, 0x04, l[0], l[1]], page, 255) else {
        return String::new();
    };
    // SAFETY: the bytes the device wrote.
    let bytes = unsafe { core::slice::from_raw_parts(page as *const u8, n) };
    let units: Vec<u16> = bytes
        .get(2..n.min(usize::from(bytes[0])))
        .unwrap_or(&[])
        .as_chunks::<2>()
        .0
        .iter()
        .map(|&c| u16::from_le_bytes(c))
        .collect();
    String::from(String::from_utf16_lossy(&units).trim())
}

/// Reads the device's descriptors, chooses its first configuration and
/// hands each interface to the class drivers. True when one took it.
fn configure(controller: &Arc<Controller>, slot: u8, port: u8, name: &str, page: usize) -> bool {
    let Some(n) = get_descriptor(controller, slot, 1, 0, page, 8) else {
        return false;
    };
    // SAFETY: the bytes the device wrote, in our page.
    let bytes = |n: usize| unsafe { core::slice::from_raw_parts(page as *const u8, n) }.to_vec();
    if n < 8 {
        return false;
    }
    // Endpoint 0's real packet size, when it is not what was guessed.
    let packet = u32::from(bytes(8)[7]);
    {
        let h = controller.host.lock();
        let size = h.context_size();
        let s = h.slots.iter().find(|s| s.id == slot).unwrap();
        // SAFETY: the device context the controller filled.
        let current = unsafe { ((s.device_context + size) as *const u32).add(1).read_volatile() } >> 16;
        let wanted = if packet == 9 { 512 } else { packet };
        drop(h);
        if wanted != current && wanted != 0 {
            evaluate_packet_size(controller, slot, wanted);
        }
    }
    let Some(n) = get_descriptor(controller, slot, 1, 0, page, 18) else {
        return false;
    };
    let device = bytes(n.min(18));
    let mut d = Descriptor {
        vendor: u16::from_le_bytes([device[8], device[9]]),
        product: u16::from_le_bytes([device[10], device[11]]),
        product_name: String::new(),
    };
    let product_index = device[15];
    let Some(n) = get_descriptor(controller, slot, 2, 0, page, 9) else {
        return false;
    };
    let total = u16::from_le_bytes([bytes(n)[2], bytes(n)[3]]).min(4096);
    let Some(n) = get_descriptor(controller, slot, 2, 0, page, total) else {
        return false;
    };
    let config = bytes(n);
    let value = config[5];
    let interfaces = parse_configuration(&config);
    d.product_name = string(controller, slot, product_index, page);
    if d.product_name.is_empty() {
        d.product_name = alloc::format!("{:04x}:{:04x}", d.vendor, d.product);
    }
    // SET_CONFIGURATION.
    if controller
        .control(slot, [0x00, 9, value, 0, 0, 0, 0, 0], page, 0)
        .is_none()
    {
        return false;
    }
    let mut taken = false;
    for interface in interfaces {
        taken |= match interface.class {
            3 => hid::attach(controller, slot, port, &d, &interface, page),
            8 => storage::attach(controller, slot, port, &d, &interface),
            9 => hub::attach(controller, slot, name, &d, &interface, page),
            _ => false,
        };
    }
    if !taken {
        println!(
            "usb{}: port {name}: {}, no driver for it",
            controller.number, d.product_name
        );
    }
    taken
}

/// The interfaces (their first settings) and endpoints a configuration
/// descriptor lists.
pub fn parse_configuration(config: &[u8]) -> Vec<Interface> {
    let mut interfaces: Vec<Interface> = Vec::new();
    let mut at = 0;
    while at + 2 <= config.len() {
        let length = usize::from(config[at]);
        if length < 2 || at + length > config.len() {
            break;
        }
        let d = &config[at..at + length];
        match d[1] {
            4 if length >= 9 && d[3] == 0 => interfaces.push(Interface {
                number: d[2],
                class: d[5],
                subclass: d[6],
                protocol: d[7],
                endpoints: Vec::new(),
                report_length: 0,
            }),
            // An alternate setting: its endpoints are not the first's.
            4 => interfaces.push(Interface {
                number: 0xff,
                class: 0xff,
                subclass: 0,
                protocol: 0,
                endpoints: Vec::new(),
                report_length: 0,
            }),
            5 if length >= 7 => {
                if let Some(i) = interfaces.last_mut() {
                    i.endpoints
                        .push((d[2], d[3], u16::from_le_bytes([d[4], d[5]]) & 0x7ff, d[6]));
                }
            }
            0x21 if length >= 9 => {
                if let Some(i) = interfaces.last_mut() {
                    i.report_length = u16::from_le_bytes([d[7], d[8]]);
                }
            }
            _ => {}
        }
        at += length;
    }
    interfaces.retain(|i| i.number != 0xff);
    interfaces
}

/// Tells the controller endpoint 0's packet size, read from the device.
fn evaluate_packet_size(controller: &Controller, slot: u8, packet: u32) {
    let Some(input) = pages::alloc(0) else { return };
    let size = controller.host.lock().context_size();
    // SAFETY: a fresh page.
    unsafe {
        core::ptr::write_bytes(input as *mut u8, 0, crate::mm::PAGE);
        let ctx = |n: usize| (input + n * size) as *mut u32;
        ctx(0).add(1).write(0b10);
        ctx(2).add(1).write(packet << 16);
    }
    controller.command(
        physical(input) as u64,
        TRB_EVALUATE_CONTEXT << 10 | u32::from(slot) << 24,
    );
    pages::free(input, 0);
}

/// Configures endpoints `endpoints` (address, attributes, max packet,
/// interval) of `slot`, each with a transfer ring of its own. The DCIs, or
/// None when the controller refused.
pub fn configure_endpoints(
    controller: &Controller,
    slot: u8,
    endpoints: &[(u8, u8, u16, u8)],
) -> Option<Vec<u8>> {
    configure_slot(controller, slot, endpoints, None)
}

/// As [`configure_endpoints`], for a hub: the slot context says so, with
/// its `ports` and, for a high-speed one, its translator's think time
/// (`ttt`, 0–3).
pub fn configure_hub_endpoints(
    controller: &Controller,
    slot: u8,
    endpoints: &[(u8, u8, u16, u8)],
    ports: u8,
    ttt: u32,
) -> Option<Vec<u8>> {
    configure_slot(controller, slot, endpoints, Some((ports, ttt)))
}

fn configure_slot(
    controller: &Controller,
    slot: u8,
    endpoints: &[(u8, u8, u16, u8)],
    hub: Option<(u8, u32)>,
) -> Option<Vec<u8>> {
    let input = pages::alloc(0)?;
    let mut h = controller.host.lock();
    let size = h.context_size();
    let s = h.slots.iter().position(|s| s.id == slot)?;
    let device_context = h.slots[s].device_context;
    let speed = {
        // SAFETY: the slot context the controller keeps.
        unsafe { (device_context as *const u32).read_volatile() >> 20 & 0xf }
    };
    let mut dcis = Vec::new();
    // SAFETY: a fresh page; the slot context copied from the device's.
    unsafe {
        core::ptr::write_bytes(input as *mut u8, 0, crate::mm::PAGE);
        core::ptr::copy_nonoverlapping(device_context as *const u8, (input + size) as *mut u8, size);
    }
    let mut highest = 1;
    for &(address, attributes, packet, interval) in endpoints {
        let d = dci(address);
        let ring = Ring::new()?;
        let in_ = address & 0x80 != 0;
        let kind = match (attributes & 3, in_) {
            (2, false) => 2,
            (3, false) => 3,
            (2, true) => 6,
            (3, true) => 7,
            _ => continue,
        };
        // Interrupt endpoints' interval, as a power of two of 125 µs.
        let exponent = match speed {
            1 | 2 => (u32::from(interval.max(1)) * 8).ilog2().clamp(3, 10),
            _ => u32::from(interval.clamp(1, 16)) - 1,
        };
        // SAFETY: the input context's entries, in our page.
        unsafe {
            let ctx = |n: usize| (input + n * size) as *mut u32;
            let add = ctx(0).add(1);
            add.write(add.read() | 1 << d);
            let e = ctx(1 + d as usize);
            e.write(if attributes & 3 == 3 { exponent << 16 } else { 0 });
            e.add(1).write(3 << 1 | kind << 3 | u32::from(packet) << 16);
            let r = ring.physical() | 1;
            e.add(2).write(r as u32);
            e.add(3).write((r >> 32) as u32);
            e.add(4).write(u32::from(packet) | u32::from(packet) << 16);
        }
        highest = highest.max(d);
        h.slots[s].rings[d as usize] = Some(ring);
        dcis.push(d);
    }
    // SAFETY: as above: the slot context's entries, and its add flag.
    unsafe {
        let slot_ctx = (input + size) as *mut u32;
        slot_ctx.write((slot_ctx.read() & !(0x1f << 27)) | u32::from(highest) << 27);
        if let Some((ports, ttt)) = hub {
            // Hub, in dword 0; its ports in dword 1; the think time in 2.
            slot_ctx.write(slot_ctx.read() | 1 << 26);
            let d1 = slot_ctx.add(1);
            d1.write((d1.read() & 0x00ff_ffff) | u32::from(ports) << 24);
            let d2 = slot_ctx.add(2);
            d2.write((d2.read() & !(3 << 16)) | (ttt & 3) << 16);
        }
        let add = (input as *mut u32).add(1);
        add.write(add.read() | 1);
    }
    drop(h);
    let (code, _) = controller.command(
        physical(input) as u64,
        TRB_CONFIGURE_ENDPOINT << 10 | u32::from(slot) << 24,
    );
    pages::free(input, 0);
    (code == CODE_SUCCESS).then_some(dcis)
}

/// Starts reading an input device's reports on its endpoint `reader`.
fn start_reading(controller: &Controller, slot: u8, reader: hid::Reader) {
    let mut h = controller.host.lock();
    let endpoint = reader.endpoint;
    let (buffer, length) = (reader.buffer, reader.length);
    let Some(s) = h.slot(slot) else { return };
    if let Some(ring) = s.rings[endpoint as usize].as_mut() {
        ring.push(
            physical(buffer) as u64,
            length as u32,
            TRB_NORMAL << 10 | TRB_IOC | TRB_SHORT_OK,
        );
    }
    s.inputs.push(reader);
    h.ring_doorbell(slot, u32::from(endpoint));
}

/// Marks a storage device's slot, so that it is told when it goes.
fn watch_storage(controller: &Controller, slot: u8, gone: Arc<AtomicBool>, name: String) {
    if let Some(s) = controller.host.lock().slot(slot) {
        s.gone = Some((gone, name));
    }
}

/// A controller's interrupt: its events taken. False if `intid` is no
/// controller's.
pub fn interrupt(intid: u32) -> bool {
    let controllers: Vec<_> = CONTROLLERS
        .lock()
        .iter()
        .filter(|c| c.intid == intid)
        .cloned()
        .collect();
    for c in &controllers {
        let (input, waiter, changed) = {
            let mut h = c.host.lock();
            let sts = h.op + USBSTS;
            h.write(sts, STS_EVENT);
            let interrupter = h.runtime + 0x20;
            h.write(interrupter, h.read(interrupter) | 1);
            let input = h.collect();
            let waiter = if h.result.is_some() { h.waiter.take() } else { None };
            (input, waiter, h.changed != 0 || !h.hubs_changed.is_empty())
        };
        deliver(input);
        block::wake(waiter);
        if changed {
            block::wake(*WATCHER.lock());
        }
    }
    let ohci = ohci::interrupt(intid);
    !controllers.is_empty() || ohci
}

/// The task that attaches devices plugged in and lets go of those pulled
/// out, once it runs.
static WATCHER: SpinLock<Option<usize>> = SpinLock::new(None);

/// Starts the task that follows ports changing: a device plugged in is
/// attached, one pulled out let go of.
pub fn watch() {
    if CONTROLLERS.lock().is_empty() {
        return;
    }
    let id = crate::sched::spawn(watching);
    *WATCHER.lock() = Some(id);
}

fn watching() {
    loop {
        let controllers: Vec<_> = CONTROLLERS.lock().clone();
        for c in &controllers {
            let changed = core::mem::take(&mut c.host.lock().changed);
            for port in 1..=32u8 {
                if changed & (1 << (port - 1)) != 0 {
                    port_changed(c, port);
                }
            }
            let hubs = core::mem::take(&mut c.host.lock().hubs_changed);
            for slot in hubs {
                let _one = c.ops.lock();
                hub::ports_changed(c, slot);
            }
        }
        if controllers.iter().all(|c| {
            let h = c.host.lock();
            h.changed == 0 && h.hubs_changed.is_empty()
        }) {
            crate::sched::sleep();
        }
    }
}

/// Root port `port` changed: a device came or went.
fn port_changed(controller: &Arc<Controller>, port: u8) {
    let (connected, slot) = {
        let h = controller.host.lock();
        let at = h.portsc(port);
        let v = h.read(at);
        h.write(at, (v & PORT_PRESERVE) | (v & PORT_CHANGES & !PORT_RESET_CHANGE));
        (
            v & PORT_CONNECTED != 0,
            h.slots
                .iter()
                .find(|s| s.port == port && s.parent.is_none())
                .map(|s| s.id),
        )
    };
    match (connected, slot) {
        (true, None) => {
            attach(controller, port);
        }
        (false, Some(slot)) => {
            let _one = controller.ops.lock();
            let_go(controller, slot);
            println!("usb{}: port {port}: unplugged", controller.number);
        }
        _ => {}
    }
}

/// Lets go of the device in `slot`, gone, and of everything behind it when
/// it is a hub: their disks removed, their slots disabled. With the
/// controller's one-at-a-time lock held.
pub(crate) fn let_go(controller: &Controller, slot: u8) {
    let children: Vec<u8> = controller
        .host
        .lock()
        .slots
        .iter()
        .filter(|s| s.parent.is_some_and(|(hub, _)| hub == slot))
        .map(|s| s.id)
        .collect();
    for child in children {
        let_go(controller, child);
    }
    let gone = {
        let mut h = controller.host.lock();
        let Some(i) = h.slots.iter().position(|s| s.id == slot) else {
            return;
        };
        h.slots.remove(i).gone
    };
    if let Some((gone, name)) = gone {
        gone.store(true, Ordering::Relaxed);
        block::remove_controller(&name);
    }
    controller.command(0, TRB_DISABLE_SLOT << 10 | u32::from(slot) << 24);
}