garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/usb/ohci.rs

raw

//! USB 1.1 through an OHCI host controller (Open Host Controller Interface
//! 1.0a), for the keyboards and pointing devices on one: the full- and
//! low-speed half of an ARM board's USB 2.0 host, beside its EHCI, which
//! hands such devices to it. A Pinebook Pro's own keyboard and touchpad are
//! one full-speed device there (on the RK3399's first USB 2.0 host), and so
//! are most keyboards and mice plugged into a board. Found in the device
//! tree (`generic-ohci`), and on PCI (class 0c:03:10), which is how QEMU
//! offers one to test with.
//!
//! What it does is small on purpose: the devices on its root ports when it
//! starts are given an address, and their input interfaces handed to the
//! HID driver (`hid`), whose reports then arrive by interrupt, one transfer
//! queued per endpoint and polled every frame. Not here: hubs behind it,
//! devices plugged in later, bulk transfers (sticks), isochronous ones.
//!
//! Its descriptors and buffers are in RAM the controller reads and writes
//! itself, which on an RK3399 does not see the cores' caches: each is
//! cleaned to memory after the core writes it and invalidated before the
//! core reads what the controller wrote ([`sync`]), and each descriptor has
//! a cache line to itself, so that cleaning one never writes back over what
//! the controller wrote into its neighbour.

use super::hid::{self, Reader};
use super::{Descriptor, deliver, parse_configuration, spin_ms};
use crate::mm::pages;
use crate::mmu::physical;
use crate::println;
use crate::sync::SpinLock;
use alloc::string::String;
use alloc::vec::Vec;

const CLASS: u32 = 0x0c_03_10;

// Registers.
const REVISION: usize = 0x00;
const CONTROL: usize = 0x04;
const COMMAND_STATUS: usize = 0x08;
const INTERRUPT_STATUS: usize = 0x0c;
const INTERRUPT_ENABLE: usize = 0x10;
const INTERRUPT_DISABLE: usize = 0x14;
const HCCA: usize = 0x18;
const CONTROL_HEAD: usize = 0x20;
const CONTROL_CURRENT: usize = 0x24;
const BULK_HEAD: usize = 0x28;
const BULK_CURRENT: usize = 0x2c;
const FRAME_INTERVAL: usize = 0x34;
const PERIODIC_START: usize = 0x40;
const LOW_SPEED_THRESHOLD: usize = 0x44;
const ROOT_HUB_A: usize = 0x48;
const ROOT_HUB_STATUS: usize = 0x50;
const PORTS: usize = 0x54;

/// HcControl: control and periodic lists on, the functional state
/// operational, four control transfers to one bulk.
const CONTROL_RUN: u32 = 3 | 1 << 2 | 1 << 4 | 0b10 << 6;
/// HcControl: an interrupt routed to firmware (SMM), which owns it.
const CONTROL_FIRMWARE: u32 = 1 << 8;
const COMMAND_RESET: u32 = 1;
const COMMAND_CONTROL_FILLED: u32 = 1 << 1;
const COMMAND_OWNERSHIP: u32 = 1 << 3;
/// Interrupts: the done queue written back, and the master enable.
const WRITEBACK_DONE: u32 = 1 << 1;
const MASTER: u32 = 1 << 31;

// A root port's status, as read; and what writing its bits does.
const PORT_CONNECTED: u32 = 1;
const PORT_ENABLED: u32 = 1 << 1;
const PORT_SET_RESET: u32 = 1 << 4;
const PORT_SET_POWER: u32 = 1 << 8;
const PORT_LOW_SPEED: u32 = 1 << 9;
const PORT_CONNECT_CHANGE: u32 = 1 << 16;
const PORT_RESET_CHANGE: u32 = 1 << 20;
/// HcRhStatus: SetGlobalPower.
const SET_GLOBAL_POWER: u32 = 1 << 16;

// An endpoint descriptor's first word.
const ED_LOW_SPEED: u32 = 1 << 13;
const ED_SKIP: u32 = 1 << 14;
const ED_IN: u32 = 0b10 << 11;
/// Its head pointer's low bits: halted, and the toggle carried.
const ED_HALTED: u32 = 1;

// A transfer descriptor's first word.
const TD_ROUNDING: u32 = 1 << 18;
const TD_SETUP: u32 = 0;
const TD_OUT: u32 = 0b01 << 19;
const TD_IN: u32 = 0b10 << 19;
/// No interrupt when it is done.
const TD_QUIET: u32 = 7 << 21;
const TD_DATA0: u32 = 0b10 << 24;
const TD_DATA1: u32 = 0b11 << 24;
/// Its condition code before the controller has seen it: NotAccessed.
const TD_NOT_ACCESSED: u32 = 0xf << 28;

/// Each descriptor's own cache line, and the pool of them a page holds.
const CELL: usize = 64;

/// Makes `len` bytes at `at` the same in memory and in the caches: cleaned
/// (what the core wrote goes to memory, where the controller reads it) and
/// invalidated (the core's next read comes from memory, where the
/// controller wrote). A no-op where the controller snoops the caches.
fn sync(at: usize, len: usize) {
    #[cfg(target_arch = "aarch64")]
    {
        let ctr: u64;
        // SAFETY: reads a register EL1 may read.
        unsafe { core::arch::asm!("mrs {}, ctr_el0", out(reg) ctr, options(nostack, nomem)) };
        let line = 4usize << (ctr >> 16 & 0xf);
        let mut address = at & !(line - 1);
        // SAFETY: a barrier: the core's writes before the maintenance.
        unsafe { core::arch::asm!("dsb sy", options(nostack)) };
        while address < at + len {
            // SAFETY: clean and invalidate a line of mapped memory of ours,
            // whose dirty bytes the core wrote and means to be seen.
            unsafe { core::arch::asm!("dc civac, {}", in(reg) address, options(nostack)) };
            address += line;
        }
        // SAFETY: a barrier: the maintenance done before what follows.
        unsafe { core::arch::asm!("dsb sy", options(nostack)) };
    }
    #[cfg(not(target_arch = "aarch64"))]
    {
        let _ = (at, len);
        core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
    }
}

fn word(cell: usize, n: usize) -> u32 {
    // SAFETY: a word of a cell of ours.
    unsafe { ((cell + 4 * n) as *const u32).read_volatile() }
}

fn set(cell: usize, words: [u32; 4]) {
    for (n, w) in words.into_iter().enumerate() {
        // SAFETY: as in `word`.
        unsafe { ((cell + 4 * n) as *mut u32).write_volatile(w) };
    }
    sync(cell, 16);
}

/// A physical address as the controller takes it: 32 bits.
fn bus(at: usize) -> u32 {
    let p = physical(at);
    assert!(p < 1 << 32, "ohci: memory above 4 GiB");
    p as u32
}

/// An input endpoint being read: its endpoint descriptor, the two transfer
/// descriptors that take turns (one queued, the other the empty tail), and
/// what reads the reports.
struct Input {
    ed: usize,
    tds: [usize; 2],
    queued: usize,
    reader: Reader,
}

impl Input {
    /// Queues `tds[queued]` for the next report, `tds[1 - queued]` its tail.
    fn queue(&self) {
        let (td, tail) = (self.tds[self.queued], self.tds[1 - self.queued]);
        let buffer = bus(self.reader.buffer);
        sync(self.reader.buffer, self.reader.length);
        set(
            td,
            [
                TD_NOT_ACCESSED | TD_IN | TD_ROUNDING,
                buffer,
                bus(tail),
                buffer + self.reader.length as u32 - 1,
            ],
        );
        // The endpoint is empty (its head is the old tail, this TD): its new
        // tail puts the TD in reach of the controller.
        sync(self.ed, 16);
        let first = word(self.ed, 0);
        let head = word(self.ed, 2) & !ED_HALTED;
        set(self.ed, [first, bus(tail), head, word(self.ed, 3)]);
    }

    /// The queued TD done, if it is: its report read and the next queued.
    fn take(&mut self, out: &mut Vec<pinnacle_abi::InputEvent>) {
        sync(self.ed, 16);
        let td = self.tds[self.queued];
        if word(self.ed, 2) & !0xf == bus(td) {
            return;
        }
        sync(td, 16);
        if word(td, 0) >> 28 == 0 {
            sync(self.reader.buffer, self.reader.length);
            self.reader.report(out);
        }
        self.queued = 1 - self.queued;
        self.queue();
    }
}

/// One controller.
struct Ohci {
    number: usize,
    regs: usize,
    intid: u32,
    ports: u8,
    hcca: usize,
    /// The page of cells, and the next one free.
    pool: usize,
    next: usize,
    /// The one control endpoint, moved from device to device; its setup,
    /// data, status and tail TDs; the setup packet's cell.
    control_ed: usize,
    control_tds: [usize; 4],
    setup: usize,
    /// The newest interrupt endpoint, which the frame table points at.
    first_interrupt: Option<usize>,
    inputs: Vec<Input>,
    address: u8,
}

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

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

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

    fn port(port: u8) -> usize {
        PORTS + 4 * (usize::from(port) - 1)
    }

    fn cell(&mut self) -> Option<usize> {
        if self.next + CELL > crate::mm::PAGE {
            return None;
        }
        let at = self.pool + self.next;
        self.next += CELL;
        Some(at)
    }

    /// Resets the controller at `regs`, gives it its memory and starts it.
    fn start(number: usize, regs: usize, intid: u32) -> Option<Ohci> {
        let hcca = pages::alloc(0)?;
        let pool = pages::alloc(0)?;
        for page in [hcca, pool] {
            // SAFETY: fresh pages, ours.
            unsafe { core::ptr::write_bytes(page as *mut u8, 0, crate::mm::PAGE) };
            sync(page, crate::mm::PAGE);
        }
        let mut c = Ohci {
            number,
            regs,
            intid,
            ports: 0,
            hcca,
            pool,
            next: 0,
            control_ed: 0,
            control_tds: [0; 4],
            setup: 0,
            first_interrupt: None,
            inputs: Vec::new(),
            address: 0,
        };
        if c.read(REVISION) & 0xff != 0x10 {
            println!(
                "ohci{number}: revision {:#x}, not OHCI 1.0",
                c.read(REVISION) & 0xff
            );
            return None;
        }
        c.control_ed = c.cell()?;
        for n in 0..4 {
            c.control_tds[n] = c.cell()?;
        }
        c.setup = c.cell()?;
        // Firmware that owns it (a PC's SMM) is asked to let go.
        if c.read(CONTROL) & CONTROL_FIRMWARE != 0 {
            c.write(COMMAND_STATUS, COMMAND_OWNERSHIP);
            let deadline = crate::timer::now_ms() + 500;
            while c.read(CONTROL) & CONTROL_FIRMWARE != 0 && crate::timer::now_ms() < deadline {
                core::hint::spin_loop();
            }
        }
        c.write(INTERRUPT_DISABLE, 0xc000_007f);
        c.write(COMMAND_STATUS, COMMAND_RESET);
        let deadline = crate::timer::now_ms() + 10;
        while c.read(COMMAND_STATUS) & COMMAND_RESET != 0 {
            if crate::timer::now_ms() > deadline {
                println!("ohci{number}: did not reset");
                return None;
            }
            core::hint::spin_loop();
        }
        // Suspended now, for at most 2 ms: set up and made operational.
        let tail = c.control_tds[3];
        set(c.control_ed, [ED_SKIP | 8 << 16, bus(tail), bus(tail), 0]);
        c.write(HCCA, bus(hcca));
        c.write(CONTROL_HEAD, bus(c.control_ed));
        c.write(CONTROL_CURRENT, 0);
        c.write(BULK_HEAD, 0);
        c.write(BULK_CURRENT, 0);
        // A frame of 12 000 bits, the largest packet that fits one, and
        // periodic transfers from 90 % of it (OHCI 1.0a, 5.1.1.4).
        let interval = 11_999;
        let toggle = !c.read(FRAME_INTERVAL) & 1 << 31;
        c.write(
            FRAME_INTERVAL,
            toggle | ((interval - 210) * 6 / 7) << 16 | interval,
        );
        c.write(PERIODIC_START, interval * 9 / 10);
        c.write(LOW_SPEED_THRESHOLD, 0x628);
        c.write(INTERRUPT_STATUS, 0x7f);
        c.write(CONTROL, CONTROL_RUN);
        let a = c.read(ROOT_HUB_A);
        c.ports = (a & 0xff).min(15) as u8;
        // Power: all ports at once, and each, as the hub switches them.
        c.write(ROOT_HUB_STATUS, SET_GLOBAL_POWER);
        for port in 1..=c.ports {
            c.write(Ohci::port(port), PORT_SET_POWER);
        }
        spin_ms(u64::from(a >> 24).max(10) * 2);
        Some(c)
    }

    /// A control transfer to `address`'s endpoint 0 (`packet` bytes at a
    /// time): the setup packet `request`, its data (`length` bytes in or
    /// out of `buffer`, a page of ours). Waited for by polling: it runs at
    /// boot. The bytes moved, or None when it failed.
    fn control(
        &self,
        address: u8,
        packet: u16,
        low: bool,
        request: [u8; 8],
        buffer: usize,
        length: usize,
    ) -> Option<usize> {
        let into_host = request[0] & 0x80 != 0;
        let [setup, data, status, tail] = self.control_tds;
        // SAFETY: the setup cell, ours.
        unsafe { (self.setup as *mut [u8; 8]).write_volatile(request) };
        sync(self.setup, 8);
        sync(buffer, length.max(1));
        let after_setup = if length > 0 { data } else { status };
        set(
            setup,
            [
                TD_NOT_ACCESSED | TD_SETUP | TD_DATA0 | TD_QUIET,
                bus(self.setup),
                bus(after_setup),
                bus(self.setup) + 7,
            ],
        );
        if length > 0 {
            let direction = if into_host { TD_IN | TD_ROUNDING } else { TD_OUT };
            set(
                data,
                [
                    TD_NOT_ACCESSED | direction | TD_DATA1 | TD_QUIET,
                    bus(buffer),
                    bus(status),
                    bus(buffer) + length as u32 - 1,
                ],
            );
        }
        // The status stage goes the other way, or in when there is no data.
        let back = if length == 0 || !into_host { TD_IN } else { TD_OUT };
        set(
            status,
            [TD_NOT_ACCESSED | back | TD_DATA1 | TD_QUIET, 0, bus(tail), 0],
        );
        // The endpoint, skipped meanwhile (it is empty: nothing in flight).
        let speed = if low { ED_LOW_SPEED } else { 0 };
        let first = u32::from(address) | speed | u32::from(packet) << 16;
        set(self.control_ed, [first | ED_SKIP, bus(tail), bus(tail), 0]);
        spin_ms(1);
        set(self.control_ed, [first, bus(tail), bus(setup), 0]);
        self.write(COMMAND_STATUS, COMMAND_CONTROL_FILLED);
        let deadline = crate::timer::now_ms() + 1_000;
        let head = loop {
            sync(self.control_ed, 16);
            let head = word(self.control_ed, 2);
            if head & !0xf == bus(tail) || head & ED_HALTED != 0 {
                break head;
            }
            if crate::timer::now_ms() > deadline {
                break head | ED_HALTED;
            }
            core::hint::spin_loop();
        };
        // Emptied again, whatever happened.
        set(self.control_ed, [first | ED_SKIP, bus(tail), bus(tail), 0]);
        if head & ED_HALTED != 0 {
            return None;
        }
        if length == 0 {
            return Some(0);
        }
        sync(data, 16);
        sync(buffer, length);
        // Its current buffer pointer: 0 when every byte moved, else the next.
        let at = word(data, 1);
        Some(if at == 0 {
            length
        } else {
            (at - bus(buffer)) as usize
        })
    }

    /// Starts reading `reader`'s reports from endpoint `endpoint` of the
    /// device at `address`.
    fn read_input(
        &mut self,
        address: u8,
        low: bool,
        endpoint: (u8, u8, u16, u8),
        reader: Reader,
    ) -> Option<()> {
        let ed = self.cell()?;
        let tds = [self.cell()?, self.cell()?];
        let speed = if low { ED_LOW_SPEED } else { 0 };
        let first = u32::from(address)
            | u32::from(endpoint.0 & 0xf) << 7
            | ED_IN
            | speed
            | u32::from(endpoint.2) << 16;
        // Linked before the newest, then the frame table pointed at it: the
        // controller's own words of a live endpoint are never written over.
        let next = self.first_interrupt.map_or(0, bus);
        set(ed, [first, bus(tds[0]), bus(tds[0]), next]);
        let input = Input {
            ed,
            tds,
            queued: 0,
            reader,
        };
        input.queue();
        for n in 0..32 {
            // SAFETY: the frame table's entries, the HCCA's first 128 bytes.
            unsafe { (self.hcca as *mut u32).add(n).write_volatile(bus(ed)) };
        }
        sync(self.hcca, 128);
        self.first_interrupt = Some(ed);
        self.inputs.push(input);
        Some(())
    }

    /// The device on root port `port`: reset, addressed, its input
    /// interfaces read. How many a driver took.
    fn attach(&mut self, port: u8, page: usize) -> usize {
        let at = Ohci::port(port);
        self.write(at, PORT_CONNECT_CHANGE);
        // The connection's debounce (USB 2.0, 7.1.7.3), then a reset.
        spin_ms(100);
        self.write(at, PORT_SET_RESET);
        let deadline = crate::timer::now_ms() + 500;
        while self.read(at) & PORT_RESET_CHANGE == 0 {
            if crate::timer::now_ms() > deadline {
                println!("ohci{}: port {port} did not reset", self.number);
                return 0;
            }
            core::hint::spin_loop();
        }
        self.write(at, PORT_RESET_CHANGE);
        spin_ms(10);
        let status = self.read(at);
        if status & PORT_ENABLED == 0 {
            println!("ohci{}: port {port} not enabled after its reset", self.number);
            return 0;
        }
        let low = status & PORT_LOW_SPEED != 0;
        // Endpoint 0's packet size, from the first 8 bytes; then an address.
        let Some(8) = self.control(0, 8, low, [0x80, 6, 0, 1, 0, 0, 8, 0], page, 8) else {
            println!("ohci{}: port {port}: no descriptor", self.number);
            return 0;
        };
        // 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();
        let packet = u16::from(bytes(8)[7]).clamp(8, 64);
        self.address += 1;
        let address = self.address;
        self.control(0, packet, low, [0x00, 5, address, 0, 0, 0, 0, 0], page, 0);
        spin_ms(2);
        let control = |request: [u8; 8], buffer: usize, length: usize| {
            self.control(address, packet, low, request, buffer, length)
        };
        let Some(n) = control([0x80, 6, 0, 1, 0, 0, 18, 0], page, 18).filter(|&n| n >= 16) else {
            println!("ohci{}: port {port}: no address", self.number);
            return 0;
        };
        let device = bytes(n);
        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) = control([0x80, 6, 0, 2, 0, 0, 9, 0], page, 9).filter(|&n| n >= 4) else {
            return 0;
        };
        let total = u16::from_le_bytes([bytes(n)[2], bytes(n)[3]]).min(4096);
        let t = total.to_le_bytes();
        let Some(n) = control([0x80, 6, 0, 2, 0, 0, t[0], t[1]], page, usize::from(total)) else {
            return 0;
        };
        let config = bytes(n);
        let interfaces = parse_configuration(&config);
        if product_index != 0
            && let Some(n) = control([0x80, 6, product_index, 3, 0x09, 0x04, 255, 0], page, 255)
        {
            let b = bytes(n);
            let units: Vec<u16> = b
                .get(2..n.min(usize::from(b[0])))
                .unwrap_or(&[])
                .as_chunks::<2>()
                .0
                .iter()
                .map(|&c| u16::from_le_bytes(c))
                .collect();
            d.product_name = String::from(String::from_utf16_lossy(&units).trim());
        }
        if d.product_name.is_empty() {
            d.product_name = alloc::format!("{:04x}:{:04x}", d.vendor, d.product);
        }
        if control([0x00, 9, config[5], 0, 0, 0, 0, 0], page, 0).is_none() {
            return 0;
        }
        let mut taken = 0;
        for interface in interfaces.iter().filter(|i| i.class == 3) {
            let mut control = |request: [u8; 8], buffer: usize, length: usize| {
                self.control(address, packet, low, request, buffer, length)
            };
            let Some((endpoint, kind)) = hid::prepare(&mut control, interface, page) else {
                continue;
            };
            let Some(buffer) = pages::alloc(0) else { break };
            let reader = Reader::new(endpoint.0, buffer, usize::from(endpoint.2).clamp(1, 64), kind);
            let line = alloc::format!("{} ({})", reader.what(), d.product_name);
            if self.read_input(address, low, endpoint, reader).is_none() {
                break;
            }
            println!("ohci{}: port {port}: {line}", self.number);
            hid::ATTACHED.lock().push(line);
            taken += 1;
        }
        if taken == 0 {
            println!(
                "ohci{}: port {port}: {}, no driver for it",
                self.number, d.product_name
            );
        }
        taken
    }
}

/// Every OHCI controller, from the device tree and on PCI: started, the
/// devices on it set up, its interrupt on. How many input interfaces a
/// driver took.
pub fn init() -> usize {
    let mut found: Vec<(usize, u32)> = Vec::new();
    let tree = crate::device::claim("generic-ohci", "ohci", crate::device::Class::Input, |_| true);
    if !tree.is_empty() {
        // The board's clocks and PHYs for its USB 2.0 hosts, and the EHCIs
        // beside them made to hand every port to their OHCI.
        #[cfg(feature = "board-rk3399")]
        crate::board::usb_hosts_on();
        give_ports_to_companions();
    }
    for device in tree {
        match (device.base(), device.interrupts.first()) {
            (Some(base), Some(&intid)) => found.push((base, intid)),
            _ => println!("ohci: {}: no registers or no interrupt", device.name),
        }
    }
    for f in crate::pci::find_class(CLASS) {
        crate::pci::claim(&f, "ohci", crate::device::Class::Input);
        match (f.bar_address(0, 0), f.take_interrupt()) {
            (Some(base), Some(intid)) => found.push((base, intid)),
            _ => println!("ohci: a PCI function with no registers or no interrupt"),
        }
    }
    let mut taken = 0;
    let Some(page) = pages::alloc(0) else { return 0 };
    for (base, intid) in found {
        let number = CONTROLLERS.lock().len();
        let Some(mut c) = Ohci::start(number, base, intid) else {
            continue;
        };
        println!("ohci{number}: OHCI, {} ports", c.ports);
        // As xHCI's: each port tried once it says connected, until the
        // devices have had time to come.
        let mut tried = [false; 15];
        let deadline = crate::timer::now_ms() + super::SETTLE_MS;
        while crate::timer::now_ms() < deadline && !tried[..usize::from(c.ports)].iter().all(|&t| t) {
            for port in 1..=c.ports {
                if !tried[usize::from(port) - 1] && c.read(Ohci::port(port)) & PORT_CONNECTED != 0 {
                    tried[usize::from(port) - 1] = true;
                    taken += c.attach(port, page);
                }
            }
            spin_ms(10);
        }
        let any = !c.inputs.is_empty();
        CONTROLLERS.lock().push(c);
        if any {
            // Only now, with the controller where its handler finds it.
            let controllers = CONTROLLERS.lock();
            let c = &controllers[number];
            c.write(INTERRUPT_ENABLE, MASTER | WRITEBACK_DONE);
            drop(controllers);
            crate::gic::enable_shared(intid);
        }
    }
    pages::free(page, 0);
    taken
}

/// An EHCI's ports, which it owns once something set its CONFIGFLAG (a
/// loader that used it), given back to its companion OHCI: the EHCI halted
/// and its CONFIGFLAG cleared. Its ports keep their power. Pinnacle has no
/// EHCI driver: a high-speed device is then met at full speed, as USB 1.1.
fn give_ports_to_companions() {
    for device in crate::device::claim("generic-ehci", "ehci", crate::device::Class::Other, |_| true) {
        let Some(base) = device.base() else { continue };
        let read = |at: usize| {
            // SAFETY: the EHCI's registers, its clocks on.
            unsafe { ((base + at) as *const u32).read_volatile() }
        };
        let write = |at: usize, value: u32| {
            // SAFETY: as in `read`.
            unsafe { ((base + at) as *mut u32).write_volatile(value) }
        };
        let op = (read(0) & 0xff) as usize;
        let ports = (read(4) & 0xf) as usize;
        // USBCMD's run bit off, and halted (USBSTS bit 12) within 2 ms.
        write(op, read(op) & !1);
        let deadline = crate::timer::now_ms() + 2;
        while read(op + 4) & 1 << 12 == 0 && crate::timer::now_ms() < deadline {
            core::hint::spin_loop();
        }
        for port in 0..ports {
            let at = op + 0x44 + 4 * port;
            // Powered; the bits written 1 to clear (changes) and the enable
            // (written 0 to turn the port off) left as they are.
            write(at, read(at) & !(1 << 1 | 1 << 3 | 1 << 5) | 1 << 12);
        }
        let was = read(op + 0x40) & 1;
        write(op + 0x40, 0);
        println!(
            "ehci: {}: {ports} ports to its companion{}",
            device.name,
            if was == 1 { " (a loader had them)" } else { "" }
        );
    }
}

/// A controller's interrupt: each input endpoint's report taken. False if
/// `intid` is no controller's.
pub fn interrupt(intid: u32) -> bool {
    let mut events = Vec::new();
    let mut ours = false;
    for c in CONTROLLERS.lock().iter_mut().filter(|c| c.intid == intid) {
        ours = true;
        let status = c.read(INTERRUPT_STATUS) & 0x7f;
        if status == 0 {
            continue;
        }
        c.write(INTERRUPT_STATUS, status);
        for input in &mut c.inputs {
            input.take(&mut events);
        }
    }
    deliver(events);
    ours
}