git clone https://garage44.eu/jeroen/pinnacle.gitcartopolis-agent · 2026-11-30T15:17:02Z
feat(kernel): a Pinebook Pro's keyboard and touchpad, through OHCI On a Pinebook Pro the keyboard and touchpad are one full-speed USB device on the RK3399's first USB 2.0 host, whose EHCI hands such a device to the OHCI beside it; Pinnacle drove only xHCI, so on a board nothing answered keys or the touchpad. Now an OHCI driver (from the device tree's generic-ohci, and on PCI, which is how QEMU offers one) addresses the devices on its root ports at boot and hands their input interfaces to the HID driver, a report polled every frame. On the RK3399 the kernel first does what Linux does whatever the loader left: the hosts' clock gates opened, each USB 2.0 PHY's 480 MHz output on and its host port out of suspend, and the EHCIs halted with CONFIGFLAG cleared, so every port is the OHCI's even after a loader used the EHCI. The console says what was there before, for the first try on a board. The RK3399's USB does not snoop the caches, and nothing in the kernel did DMA maintenance yet: every descriptor has a cache line of its own and is cleaned after the core writes it and invalidated before reading what the controller wrote. A live endpoint descriptor is never written while the controller may write it (new ones go in front, the frame table pointed at them), else a clean could write a stale head back. Untried on hardware: QEMU's caches are coherent, and the port's 5 V (a GPIO regulator on the Pinebook Pro) is left as the loader set it. The self-check's first ARM boot now has a keyboard and a mouse on QEMU's OHCI and requires both read.
docs/hardware.md | 39 ++-
kernel/src/board/rk3399.rs | 42 +++
kernel/src/drivers/usb/mod.rs | 12 +-
kernel/src/drivers/usb/ohci.rs | 641 +++++++++++++++++++++++++++++++++++++++++
xtask/src/main.rs | 18 +-
5 files changed, 746 insertions(+), 6 deletions(-)
diff --git a/docs/hardware.md b/docs/hardware.md
index a764c06..e4cc9a8 100644
--- a/docs/hardware.md
+++ b/docs/hardware.md
@@ -77,8 +77,42 @@ size (turning the screen is refused). With no lit screen it says
Which boards this shows anything on is not known yet. A Pinebook Pro with
Tow-Boot leaves its eDP panel lit; whether the PinePhone Pro's Tow-Boot
lights its panel at all, and whether U-Boot on either passes a
-`simple-framebuffer`, needs the board. Touch, the keyboard, eMMC, the
-battery and the PMIC all wait for drivers.
+`simple-framebuffer`, needs the board. eMMC, the battery, the PMIC and a
+touch screen (the PinePhone Pro's, on I²C) wait for drivers.
+
+## The keyboard and touchpad
+
+A Pinebook Pro's keyboard and touchpad are one USB device inside it, at
+full speed (USB 1.1), on the RK3399's first USB 2.0 host: its EHCI hands
+such a device to the OHCI beside it, which Pinnacle drives
+(`drivers/usb/ohci.rs`). The kernel first does what Linux does to that
+host whatever the loader left: the hosts' clocks ungated in the CRU, each
+USB 2.0 PHY's clock output on and its host port out of suspend in the GRF
+(`board::usb_hosts_on`), and each EHCI halted with its ports given to its
+OHCI. None of it has run on a board yet; on the serial console it should
+say something like this (the device's name is its own, and Linux's logs
+of a Pinebook Pro give it as HAILUCK's):
+
+```
+usb: rk3399 hosts: gates 0x0 0x0, PHY ports 0x2 0x2; turned on
+ehci: usb@fe380000: 1 ports to its companion
+ohci0: OHCI, 1 ports
+ohci0: port 1: keyboard (HAILUCK CO.,LTD USB KEYBOARD)
+ohci0: port 1: mouse (HAILUCK CO.,LTD USB KEYBOARD)
+```
+
+The values before "turned on" are what the loader left (a set gate bit
+was a gated clock; a PHY port of 1 was suspended). A device of the second
+host's port (the Pinebook Pro's USB-A 2.0 port) is found the same way, as
+`ohci1`, when it is there at boot; a device plugged in later is not seen.
+The port's 5 V (the Pinebook Pro's `vcc5v0_usb`, a GPIO) is left as the
+loader set it: with no `ohciN: port` line at all, it is the first thing
+to look at.
+
+In QEMU, `cargo xtask pinebook-demo` boots with that input and no other
+(QEMU's keyboard and mouse on its OHCI), chooses the data's password on
+the keyboard and opens Settings with the mouse's pointer and click; the
+self-check's first boot has the same OHCI devices beside the xHCI ones.
In QEMU the same path runs as a loader would leave it: `cargo xtask test`
boots once with a device tree that carries a lit screen and reserved
@@ -102,6 +136,7 @@ run on a real machine yet.
|---|---|---|
| USB (`drivers/usb`): an xHCI host controller | every device on its root ports, given an address, its configuration read and chosen; plugged in and pulled out later, followed by a kernel task | PCI class 0c:03:30 |
| USB hubs (`usb::hub`) | USB 2 and USB 3 hubs, up to five deep: told to the controller as hubs, ports powered, each device reset and addressed by its route (through a high-speed hub's translator when it is slower); its status-change endpoint followed for plugging in and out | class 09 |
+| USB 1.1 (`usb/ohci.rs`): an OHCI host controller | the keyboards and pointing devices on its root ports at boot, given an address and their input interfaces read, a report polled every frame; no hubs, no sticks, nothing plugged in later. Its descriptors cleaned from and invalidated in the cores' caches, for a board whose USB does not see them (the RK3399) | `generic-ohci`, PCI class 0c:03:10 |
| USB keyboards (`usb::hid`) | the boot protocol's report, keys as the virtio keyboard's (Linux's codes) | HID class |
| USB mice, tablets, touch screens (`usb::hid`) | the report descriptor read for X, Y, wheel and buttons; absolute devices point where they point, a mouse moves a pointer the kernel keeps and the display server draws | HID class |
| USB sticks and disks (`usb::storage`) | Bulk-Only Transport, SCSI READ/WRITE(10), up to 64 KiB a command | class 08, subclass 06, protocol 50 |
diff --git a/kernel/src/board/rk3399.rs b/kernel/src/board/rk3399.rs
index 54e8dd3..4000556 100644
--- a/kernel/src/board/rk3399.rs
+++ b/kernel/src/board/rk3399.rs
@@ -81,6 +81,48 @@ pub fn clock() -> u64 {
/// No real-time clock driven yet: the time set stays in the kernel.
pub fn set_clock(_seconds: u64) {}
+/// The two USB 2.0 hosts (EHCI and OHCI each), as Linux brings them up
+/// whatever the loader left: their bus clocks ungated, and each one's PHY
+/// port powered. A Pinebook Pro's keyboard and touchpad are on the first.
+/// From Linux's `clk-rk3399.c` (a set gate bit is a gated clock; the CRU's
+/// registers take a mask of the bits written in their upper half):
+/// CLKGATE_CON6 bits 5 and 6 the PHYs' 24 MHz references, CLKGATE_CON20
+/// bits 5 to 8 hclk_host0, its arbiter, hclk_host1 and its arbiter. From
+/// its `phy-rockchip-inno-usb2.c`, in the GRF: each PHY's 480 MHz output
+/// on (bit 4 of 0xe450 and 0xe460 written 0), then its host port out of
+/// suspend (bits 1:0 of 0xe458 and 0xe468 written 2), each followed by
+/// the wait Linux gives it. What was there before is said on the console,
+/// for a first try on a board.
+pub fn usb_hosts_on() {
+ const CRU: usize = 0xff76_0000;
+ const GRF: usize = 0xff77_0000;
+ let at = |base: usize, offset: usize| crate::mmu::virt(base + offset) as *mut u32;
+ // SAFETY: the CRU's and the GRF's registers, always clocked, mapped as
+ // Device memory.
+ let read = |p: *mut u32| unsafe { p.read_volatile() };
+ // SAFETY: as above.
+ let write = |p: *mut u32, value: u32| unsafe { p.write_volatile(value) };
+ let gates = (read(at(CRU, 0x300 + 6 * 4)), read(at(CRU, 0x300 + 20 * 4)));
+ let phys = (read(at(GRF, 0xe458)), read(at(GRF, 0xe468)));
+ crate::println!(
+ "usb: rk3399 hosts: gates {:#x} {:#x}, PHY ports {:#x} {:#x}; turned on",
+ gates.0 & 0b11 << 5,
+ gates.1 & 0b1111 << 5,
+ phys.0 & 3,
+ phys.1 & 3
+ );
+ write(at(CRU, 0x300 + 6 * 4), 0b11 << (5 + 16));
+ write(at(CRU, 0x300 + 20 * 4), 0b1111 << (5 + 16));
+ for phy in [0xe450, 0xe460] {
+ write(at(GRF, phy), 1 << (4 + 16));
+ }
+ crate::drivers::usb::spin_ms(2);
+ for port in [0xe458, 0xe468] {
+ write(at(GRF, port), 0b11 << 16 | 2);
+ }
+ crate::drivers::usb::spin_ms(2);
+}
+
/// The screen U-Boot left lit, if it did: the first window of either
/// display controller (VOP-big, VOP-little), read from its registers.
/// A controller whose bus clocks are gated is not read: a read of a
diff --git a/kernel/src/drivers/usb/mod.rs b/kernel/src/drivers/usb/mod.rs
index 1f6f995..d2453d1 100644
--- a/kernel/src/drivers/usb/mod.rs
+++ b/kernel/src/drivers/usb/mod.rs
@@ -17,9 +17,13 @@
//! 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;
@@ -541,14 +545,15 @@ pub fn init() -> usize {
for (controller, _) in &started {
controller.host.lock().changed = 0;
}
- taken
+ // 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.
-fn spin_ms(ms: u64) {
+pub(crate) fn spin_ms(ms: u64) {
let end = crate::timer::now_ms() + ms;
while crate::timer::now_ms() < end {
core::hint::spin_loop();
@@ -1195,7 +1200,8 @@ pub fn interrupt(intid: u32) -> bool {
block::wake(*WATCHER.lock());
}
}
- !controllers.is_empty()
+ let ohci = ohci::interrupt(intid);
+ !controllers.is_empty() || ohci
}
/// The task that attaches devices plugged in and lets go of those pulled
diff --git a/kernel/src/drivers/usb/ohci.rs b/kernel/src/drivers/usb/ohci.rs
new file mode 100644
index 0000000..5d6f20a
--- /dev/null
+++ b/kernel/src/drivers/usb/ohci.rs
@@ -0,0 +1,641 @@
+//! 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
+}
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index 47131a7..b386f9c 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -1083,6 +1083,14 @@ fn hardware(name: &str, arch: Arch) -> Result<Vec<String>> {
"ich9-ahci,id=ahci",
"-device",
"ide-hd,drive=sata,bus=ahci.0",
+ // USB 1.1, as a board's USB 2.0 host hands a keyboard and a
+ // touchpad to its OHCI (a Pinebook Pro's own are there).
+ "-device",
+ "pci-ohci,id=ohci",
+ "-device",
+ "usb-kbd,bus=ohci.0",
+ "-device",
+ "usb-mouse,bus=ohci.0",
]
.map(String::from),
),
@@ -1102,6 +1110,14 @@ const HARDWARE_LINES: &[&str] = &[
"storage ok",
];
+/// What the self-check says of [`hardware`]'s OHCI, on ARM only: a
+/// keyboard and a mouse on it, read through it.
+const OHCI_LINES: &[&str] = &[
+ "ohci0: OHCI, ",
+ "ohci0: port 1: keyboard (QEMU USB Keyboard)",
+ "ohci0: port 2: mouse (QEMU USB Mouse)",
+];
+
/// How QEMU is given the 3D virtio-gpu, whose Venus runs the guest's Vulkan on
/// the host's, where this machine's QEMU has the device. `PINNACLE_GPU3D=0`
/// leaves it out.
@@ -1610,7 +1626,7 @@ fn test() -> Result {
};
let out = boot(machine, load, &guest)?;
if guest.hardware {
- for expected in HARDWARE_LINES {
+ for expected in HARDWARE_LINES.iter().chain(OHCI_LINES) {
if !out.contains(expected) {
return Err(format!("{machine}, {what}: no \"{expected}\" in the output"));
}