git clone https://garage44.eu/jeroen/pinnacle.gitcartopolis-agent · 2026-11-30T14:15:17Z
feat(kernel): a laptop's I²C touchpad, through Intel's LPSS DesignWare controllers drivers/i2c_dw.rs: the Synopsys DesignWare I²C masters on Intel's LPSS PCI functions (8086, class 0c:80:00), 8th to 13th generation. Each is brought to D0, taken out of LPSS's reset (0x3 at BAR0+0x204), checked to be I²C (LPSS's caps) and a DesignWare (IC_COMP_TYPE 0x44570140), and made a 7-bit master with repeated starts at 400 kHz (100 kHz where the device asks less). SCL timings come from the controller's AML (FMCN, SSCN), else from a 120 MHz input clock as Linux computes them. Transfers are polled with deadlines, no interrupts: a write, a read, or a write then a read with a repeated start; TX_ABRT ends one with false and the cause kept. drivers/i2c_hid.rs (x86_64): every PNP0C50/ACPI0C50 device present by _STA, through power::with_namespace: _PS0 (its own and its controller's), I2cSerialBus from _CRS (address, speed, controller path), _DSM (UUID 3CDFF6F7-…, revision 1, function 1) for the HID descriptor's register; the controller matched to its PCI function by the AML device's _ADR (dev << 16 | fn) on the root bridge's bus (_BBN, else 0). Brought up by pinnacle_hid::i2c, then read by a kernel task every 8 ms: there is no GPIO driver to follow its interrupt line, and the boot log says so. Relative reports move the kernel's pointer BY_MOUSE, as the PS/2 touchpad does, through drivers::input::deliver. Each touchpad is listed in Settings → Hardware as an input device of the driver i2c-hid, each controller as i2c-designware. Called from kmain after power::init, its task started beside power::watch. Docs: hardware.md's driver table, its "Not yet" (GPIO interrupts, the precision touchpad mode, LPSS in ACPI mode) and what to look for in the boot log; a roadmap row. Tested: cargo xtask pc and cargo xtask laptop pass, the boot log saying "i2c: 0 DesignWare controllers" (QEMU has none); clippy for the PC and qemu-virt kernels shows nothing in these files. Nothing here has run on a laptop: the controller, the AML matching and the polling are untried.
docs/hardware.md | 21 ++-
docs/roadmap.md | 1 +
kernel/src/drivers/i2c_dw.rs | 345 ++++++++++++++++++++++++++++++++++++++++++
kernel/src/drivers/i2c_hid.rs | 306 +++++++++++++++++++++++++++++++++++++
kernel/src/drivers/mod.rs | 4 +
kernel/src/main.rs | 4 +
6 files changed, 677 insertions(+), 4 deletions(-)
diff --git a/docs/hardware.md b/docs/hardware.md
index b99eb11..5aab394 100644
--- a/docs/hardware.md
+++ b/docs/hardware.md
@@ -115,6 +115,8 @@ run on a real machine yet.
| The firmware's AML (`aml/`, the crate `pinnacle-aml`; `x86_64/power.rs`) | the DSDT and every SSDT loaded and run by an interpreter of Pinnacle's own: devices, names, methods, operation regions and their fields (memory, I/O, PCI configuration, the embedded controller, CMOS), `_INI`, `_REG`, `_STA`, `_CRS` decoded (I/O, memory, interrupts, GPIO, I²C); a loop runs at most a million times, calls nest at most 64 deep, a device whose body fails loses itself only | the DSDT, SSDTs |
| The embedded controller (`x86_64/power.rs`) | its two ports and GPE from AML (`PNP0C09`, `_CRS`, `_GPE`), reads and writes for AML's regions, its events (`_Qxx`) run in a kernel task when its GPE fires | `PNP0C09` |
| Battery, charger, lid (`x86_64/power.rs`) | `_BIX` or `_BIF`, `_BST`, `_PSR`, `_LID` asked live (`power` system call, 71): level, charging, minutes left, capacities, model; the firmware's notifications and a lid or charger change sent to the display server as input events, which draws the battery in the status bar and locks the screen when the lid closes | `PNP0C0A`, `ACPI0003`, `PNP0C0D` |
+| I²C on Intel's LPSS (`drivers/i2c_dw.rs`) | the Synopsys DesignWare I²C controllers of Intel's 8th to 13th generation chipsets: brought to D0, out of LPSS's reset, checked by their component type (`DW`, 0x44570140); a 7-bit master with repeated starts, at 400 kHz (100 kHz where a device asks less), SCL's timings from the controller's AML (`FMCN`, `SSCN`), else from a 120 MHz input clock; transfers polled, with deadlines, an abort (no acknowledgement) ending one with an error. No interrupts, no DMA | PCI 8086, class 0c:80:00 |
+| Touchpads on I²C (`drivers/i2c_hid.rs`, PC only; the protocol in `hid/`, the crate `pinnacle-hid`, beside USB's report descriptors) | HID over I²C (Microsoft's 1.0): each `PNP0C50`/`ACPI0C50` device present by `_STA`, powered by `_PS0`, its address and controller from `_CRS` (`I2cSerialBus`; the controller the PCI function its `_ADR` names), its HID descriptor's register from `_DSM`; SET_POWER ON, RESET and its empty answer, the report descriptor read and its mouse report followed (a precision touchpad's own reports are not asked for). **Polled** every 8 ms from a kernel task: its interrupt is a GPIO line and there is no GPIO driver yet. Moves the kernel's pointer as the PS/2 touchpad does | `PNP0C50`, `ACPI0C50` |
Interrupts are message interrupts on a PC (MSI-X, or MSI for AHCI and
Ethernet) and INTx on ARM (routed by the device tree); a PC's wired ones
@@ -127,8 +129,12 @@ core's RDSEED or RDRAND as well.
Not yet: isochronous USB (audio, cameras), USB 3 streams, NVMe namespaces
with metadata, more than one I/O queue, a SATA port multiplier, SD and
-eMMC (they wait for the first device); I²C-HID (most touchpads' own
-protocol, and some keyboards'), Intel's Wi-Fi, a graphics driver (the
+eMMC (they wait for the first device); GPIO interrupts (Intel's GPIO
+controllers, `INT34xx`: an I²C touchpad is read every 8 ms instead of
+when its line says), a touchpad's precision mode (fingers, gestures,
+palm rejection: only its mouse report is read), I²C keyboards and touch
+screens, LPSS controllers firmware hides from PCI (its "ACPI mode"),
+Intel's Wi-Fi, a graphics driver (the
screen stays at the firmware's mode, uncached, without brightness),
recording through HDA, HDMI and DisplayPort audio, a codec's vendor-specific
set-up (some laptops' speakers stay silent without Realtek's coefficients),
@@ -157,7 +163,10 @@ the pointer on the home screen; the status bar shows a battery, from an SSDT giv
`system_powerdown`, ACPI's fixed event) turns it off. A screenshot each
step, in `target/demo-laptop/`.
-What that cannot show is what QEMU does not have: an I²C touchpad, Intel's
+What that cannot show is what QEMU does not have: an I²C touchpad (QEMU
+has no DesignWare controller: the boot log says `i2c: 0 DesignWare
+controllers`; the protocol is tested against a fake touchpad, `cargo test
+-p pinnacle-hid`), Intel's
Wi-Fi and graphics, an embedded controller, a laptop's own HDA codec (QEMU's has one
line out and no speaker, headphone jack or EAPD, so the jack's switching
is untried), and every firmware's own mistakes. Those wait for a machine.
@@ -192,7 +201,11 @@ What to look for, line by line: `framebuffer:` (the firmware's screen),
`apic: x2APIC mode` (with `xapic` on the command line as the fallback to
try), `acpi: a laptop, in ACPI mode; off by \_S5 …; the power button
heard`, `ps2: a keyboard and a mouse or touchpad` (absent: the keyboard is
-not on the controller, or the touchpad is I²C-only), `usb0: xHCI`, each
+not on the controller, or the touchpad is I²C-only), `i2c: 2 DesignWare
+controllers` and `touchpad: ELAN0001 at 0x15 on \_SB.PC00.I2C1, HID
+04f3:3140, polled` (or why not: no controller of this kernel's, no
+`_DSM`, a step not acknowledged), `touchpad: ELAN0001: its first report`
+once a finger moves, `usb0: xHCI`, each
USB device and hub, `nvme0:`, `hda: codec 0: 10ec:0257, speaker on pin
0x14, headphones on 0x21 (out), EAPD on` (the codec and its pins; a
second codec with only HDMI says `no analog output`), `net: Intel
diff --git a/docs/roadmap.md b/docs/roadmap.md
index f50b4c3..7673eca 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -74,6 +74,7 @@ What is still missing for daily use, and the projects it will take, is in
| An Intel laptop without trying one (`hardware.md`, "A laptop, without one"): the firmware's screen (GOP) drawn on, the boot log on it and a panic over it, the machine left on (a laptop has no serial port); x2APIC; the I/O APIC with the MADT's overrides; the keyboard controller's keyboard and touchpad (PS/2), a pointer the display server draws; ACPI's FADT: off by `\_S5`, restart by its reset register, the power button; USB hubs (USB 2 and 3, a translator's route for slower devices); Intel's e1000e Ethernet (82574L to I219); randomness from RDSEED/RDRAND; booted with no virtio device at all. `cargo xtask laptop`: the stick behind a hub installs on NVMe and turns off by ACPI, the disk starts, the password typed on PS/2, the power button turns it off | Done in QEMU (2026-11-29); not tried on a laptop. Not here: I²C-HID touchpads, Intel Wi-Fi and graphics, battery and lid (they need AML run), the I219's PHY waking from ULP |
| Intel HDA sound (`drivers/hda.rs`, `hardware.md`): the controller reset, CORB/RIRB (immediate registers as the fallback), codecs from STATESTS, the first with an analog output walked from its speaker pin (else line out) and headphone jack to a converter through mixers and selectors, powered, unmuted at 0 dB, EAPD on; one output stream of eight 10 ms periods fed by the kernel's mixer, as virtio-sound's are, an interrupt a period, the position by LPIB, stopped once nothing plays; the speaker off while headphones are in (unsolicited response); `cargo xtask laptop` hears the self-check's tone through QEMU's `ich9-intel-hda` | Done in QEMU (2026-11-30); not tried on a laptop. Not here: recording, HDMI/DP audio, vendor coefficient set-ups, Intel's DSP (SOF) mode, the jack's switching (QEMU's codec has none) |
| A laptop's battery, charger and lid, from its firmware (`aml/`, `x86_64/power.rs`, `hardware.md`): an AML interpreter of Pinnacle's own (no ACPICA) loads the DSDT and SSDTs and runs their methods, bounded (a million loop rounds, 64 calls deep), a device that fails losing itself only; `_CRS` decoded, GPIO and I²C included; the embedded controller found from AML and driving its regions, its `_Qxx` events and the firmware's `_Lxx`/`_Exx` GPE methods run in a kernel task; `_BIX`/`_BIF`, `_BST`, `_PSR`, `_LID` asked live by the `power` system call (71); a lid or charger change an input event to the display server, which draws the battery in the status bar and locks when the lid closes. `cargo xtask laptop` gives QEMU a battery, charger and lid as an SSDT written with `pinnacle_aml::asm` | Done in QEMU (2026-11-30): QEMU's DSDT loads with no failure; no embedded controller tried (QEMU has none). Not here: sleep (S3, S0ix), battery warnings (`_BTP`), thermal zones and fans |
+| A laptop's touchpad on I²C (`hid/`, `drivers/i2c_dw.rs`, `drivers/i2c_hid.rs`, `hardware.md`): HID report descriptors and the pointer moved out of USB into the crate `pinnacle-hid`, shared by both; HID over I²C (Microsoft's 1.0) as a state machine over an `I2cBus` trait: the HID descriptor from the register `_DSM` names, SET_POWER ON, RESET and its empty answer, the report descriptor, the input register (a length, then a report), the mouse report a precision touchpad sends until told otherwise turned into pointer moves; Intel's LPSS DesignWare I²C controllers (8th to 13th generation) as polled masters, their timings from `FMCN`/`SSCN`; the touchpad found as `PNP0C50` in the AML, its controller by `_ADR`, read every 8 ms by a kernel task | Done in QEMU (2026-11-30) as far as QEMU goes: it has no DesignWare controller (`i2c: 0 DesignWare controllers`), so only the protocol is tested, against a fake ELAN touchpad; untried on a laptop. Not here: GPIO interrupts (the touchpad is polled), the precision touchpad's fingers and gestures, I²C keyboards and touch screens, LPSS in ACPI mode |
| Disks with partitions (`pinnacle-disk`: GPT and FAT32, shared with `xtask`): Pinnacle's system and data partitions mounted, the system the one the loader names (`root=`), any other disk free; Settings → Disks lists each, what it holds and where Pinnacle can go | Done |
| Installing on a disk (`install`, Settings → Disks → Install): from a USB stick (`cargo xtask installer [pc]`), a partition table, a boot partition with the stick's loader and kernel and a command line naming the new system, the system copied file by file, a blank data partition the first start makes a vault; `cargo xtask install-test [pc]` installs on NVMe in QEMU under edk2 and starts from it, `install-demo [pc]` does it in Settings with a USB tablet and keyboard | Done in QEMU on both (no UEFI boot entry written: the disk is found by the path every firmware tries) |
| Pinnacle's own UEFI loader (`boot/`): the kernel and its command line read from the boot partition, started as a boot image on ARM (the command line in a copy of the device tree) and by Multiboot2 on a PC (the memory map, GOP's framebuffer, ACPI's root pointer); no GRUB (`cargo xtask pc-efi`) | Done in QEMU (edk2); U-Boot's UEFI untried |
diff --git a/kernel/src/drivers/i2c_dw.rs b/kernel/src/drivers/i2c_dw.rs
new file mode 100644
index 0000000..b48cff1
--- /dev/null
+++ b/kernel/src/drivers/i2c_dw.rs
@@ -0,0 +1,345 @@
+//! I²C masters on Intel's LPSS (Low Power Subsystem): the Synopsys
+//! DesignWare I²C controllers a laptop of Intel's 8th to 13th generation
+//! (Sunrise Point to Alder Lake's PCH) has its touchpad, and often its
+//! touch screen, behind. Each is a PCI function of Intel's (class
+//! 0c:80:00) whose BAR 0 holds the DesignWare's registers, and at 0x200
+//! LPSS's own (its reset, its kind: I²C, UART or SPI).
+//!
+//! Transfers are polled, with deadlines: a write, a read, or a write and
+//! a read with a repeated start between, as HID over I²C asks
+//! ([`I2cBus`]). No interrupt is used; an abort (no acknowledgement, a
+//! lost arbitration) ends the transfer with false. The clock's timings
+//! come from the controller's AML (`SSCN`, `FMCN`) where the firmware has
+//! them, else from the LPSS's 120 MHz input clock, as Linux's
+//! `i2c-designware` computes them.
+
+use crate::sync::Mutex;
+use alloc::vec::Vec;
+use pinnacle_hid::i2c::I2cBus;
+
+/// LPSS functions: "other serial bus controller".
+const CLASS: u32 = 0x0c8000;
+/// IC_COMP_TYPE's value, "DW" and 0x0140.
+const DW_TYPE: u32 = 0x4457_0140;
+
+// The DesignWare's registers (DesignWare DW_apb_i2c databook).
+const IC_CON: usize = 0x00;
+const IC_TAR: usize = 0x04;
+const IC_DATA_CMD: usize = 0x10;
+const IC_SS_SCL_HCNT: usize = 0x14;
+const IC_SS_SCL_LCNT: usize = 0x18;
+const IC_FS_SCL_HCNT: usize = 0x1c;
+const IC_FS_SCL_LCNT: usize = 0x20;
+const IC_INTR_MASK: usize = 0x30;
+const IC_RAW_INTR_STAT: usize = 0x34;
+const IC_RX_TL: usize = 0x38;
+const IC_TX_TL: usize = 0x3c;
+const IC_CLR_INTR: usize = 0x40;
+const IC_CLR_TX_ABRT: usize = 0x54;
+const IC_CLR_STOP_DET: usize = 0x60;
+const IC_ENABLE: usize = 0x6c;
+const IC_STATUS: usize = 0x70;
+const IC_RXFLR: usize = 0x78;
+const IC_SDA_HOLD: usize = 0x7c;
+const IC_TX_ABRT_SOURCE: usize = 0x80;
+const IC_ENABLE_STATUS: usize = 0x9c;
+const IC_COMP_PARAM_1: usize = 0xf4;
+const IC_COMP_TYPE: usize = 0xfc;
+
+const CON_MASTER: u32 = 1;
+const CON_SPEED_STANDARD: u32 = 1 << 1;
+const CON_SPEED_FAST: u32 = 2 << 1;
+const CON_10BIT_MASTER: u32 = 1 << 4;
+const CON_RESTART: u32 = 1 << 5;
+const CON_SLAVE_DISABLE: u32 = 1 << 6;
+
+const CMD_READ: u32 = 1 << 8;
+const CMD_STOP: u32 = 1 << 9;
+const CMD_RESTART: u32 = 1 << 10;
+
+const INTR_TX_ABRT: u32 = 1 << 6;
+const INTR_STOP_DET: u32 = 1 << 9;
+
+const STATUS_TFNF: u32 = 1 << 1;
+const STATUS_MST_ACTIVITY: u32 = 1 << 5;
+
+// LPSS's private registers, at 0x200 into BAR 0.
+const PRIVATE: usize = 0x200;
+const PRIV_RESETS: usize = 0x04;
+/// Out of reset: the function's two reset bits.
+const RESETS_FUNCTION: u32 = 0x3;
+const PRIV_CAPS: usize = 0xfc;
+
+/// The LPSS's input clock on Sunrise Point and after, in kHz.
+const CLOCK_KHZ: u64 = 120_000;
+
+/// A mode's SCL high and low counts and SDA hold time, in input clocks:
+/// `SSCN` or `FMCN`'s package.
+pub type Timing = (u16, u16, u16);
+
+/// The timings for standard (100 kHz) and fast (400 kHz) mode.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct Timings {
+ pub standard: Option<Timing>,
+ pub fast: Option<Timing>,
+}
+
+/// SCL's counts from a mode's minimum high and low times and the fall
+/// time (ns), as Linux's `i2c_dw_scl_hcnt`/`_lcnt` compute them.
+fn counts(high_ns: u64, low_ns: u64, fall_ns: u64) -> Timing {
+ let high = (CLOCK_KHZ * high_ns).div_ceil(1_000_000).saturating_sub(8);
+ let low = (CLOCK_KHZ * (low_ns + fall_ns))
+ .div_ceil(1_000_000)
+ .saturating_sub(1);
+ // SDA held 300 ns past SCL's fall.
+ let hold = CLOCK_KHZ * 300 / 1_000_000;
+ (high as u16, low as u16, hold as u16)
+}
+
+/// One controller.
+pub struct Controller {
+ pub bus: u8,
+ pub device: u8,
+ pub function: u8,
+ regs: usize,
+ /// IC_TAR as last set: it changes only with the controller off.
+ target: Option<u16>,
+ con: u32,
+ /// How many reads may be queued before their bytes are taken.
+ rx_depth: usize,
+ /// Transfers aborted, and the last abort's cause (IC_TX_ABRT_SOURCE).
+ pub aborts: u32,
+ pub last_abort: u32,
+}
+
+/// Every controller found, as [`init`] left them.
+pub static CONTROLLERS: Mutex<Vec<Controller>> = Mutex::new(Vec::new());
+
+/// Waits for `done`, at most `ms`.
+fn until(ms: u64, mut done: impl FnMut() -> bool) -> bool {
+ let deadline = crate::timer::now_ms() + ms;
+ loop {
+ if done() {
+ return true;
+ }
+ if crate::timer::now_ms() > deadline {
+ return false;
+ }
+ core::hint::spin_loop();
+ }
+}
+
+/// Brings the function to D0 if it sleeps (its PCI power management
+/// capability), as firmware may leave LPSS.
+fn power_on(f: &crate::pci::Function) {
+ const PM: u8 = 0x01;
+ if let Some((_, cap)) = f.capabilities().find(|&(id, _)| id == PM) {
+ let pmcsr = f.read16(cap + 4);
+ if pmcsr & 3 != 0 {
+ f.write16(cap + 4, pmcsr & !3);
+ // D3hot to D0: 10 ms (PCI PM 1.2, 5.6.1).
+ crate::apic::wait_us(10_000);
+ }
+ }
+}
+
+/// Finds every DesignWare I²C controller on LPSS, takes it out of reset
+/// and makes it a master at 400 kHz. Says how many on the boot log.
+pub fn init() -> usize {
+ let mut found = Vec::new();
+ for f in crate::pci::find_class(CLASS) {
+ if f.vendor != 0x8086 {
+ continue;
+ }
+ // The DesignWare's registers and LPSS's both.
+ let (Some(regs), Some(_)) = (
+ f.bar_address(0, 0),
+ f.bar_address(0, (PRIVATE + PRIV_CAPS) as u64),
+ ) else {
+ continue;
+ };
+ power_on(&f);
+ f.enable(false);
+ let private = regs + PRIVATE;
+ // SAFETY: LPSS's own registers, in the function's BAR 0.
+ unsafe {
+ ((private + PRIV_RESETS) as *mut u32).write_volatile(RESETS_FUNCTION);
+ }
+ // SAFETY: as above.
+ let caps = unsafe { ((private + PRIV_CAPS) as *const u32).read_volatile() };
+ // Its kind, in bits 4 to 7: 0 is I²C (1 a UART, 2 SPI).
+ if caps != u32::MAX && (caps >> 4) & 0xf != 0 {
+ continue;
+ }
+ let mut c = Controller {
+ bus: f.bus,
+ device: f.device,
+ function: f.function,
+ regs,
+ target: None,
+ con: 0,
+ rx_depth: 1,
+ aborts: 0,
+ last_abort: 0,
+ };
+ if c.r(IC_COMP_TYPE) != DW_TYPE {
+ continue;
+ }
+ let param = c.r(IC_COMP_PARAM_1);
+ c.rx_depth = (((param >> 8) & 0xff) as usize + 1).clamp(1, 256);
+ if param == 0 || param == u32::MAX {
+ c.rx_depth = 8;
+ }
+ c.configure(400_000, Timings::default());
+ crate::pci::claim(&f, "i2c-designware", crate::device::Class::Other);
+ found.push(c);
+ }
+ let n = found.len();
+ *CONTROLLERS.lock() = found;
+ crate::println!("i2c: {n} DesignWare controllers");
+ n
+}
+
+impl Controller {
+ fn r(&self, offset: usize) -> u32 {
+ // SAFETY: a register of the controller, in its BAR 0.
+ unsafe { ((self.regs + offset) as *const u32).read_volatile() }
+ }
+
+ fn w(&self, offset: usize, value: u32) {
+ // SAFETY: as in `r`.
+ unsafe { ((self.regs + offset) as *mut u32).write_volatile(value) }
+ }
+
+ fn enable(&mut self, on: bool) -> bool {
+ self.w(IC_ENABLE, u32::from(on));
+ until(10, || self.r(IC_ENABLE_STATUS) & 1 == u32::from(on))
+ }
+
+ /// Makes it a 7-bit master with repeated starts, at `speed_hz` (fast
+ /// mode from 400 kHz up, standard below), with `timings` where the
+ /// firmware gave them.
+ pub fn configure(&mut self, speed_hz: u32, timings: Timings) {
+ self.enable(false);
+ let fast = speed_hz >= 400_000;
+ let standard = timings.standard.unwrap_or(counts(4000, 4700, 300));
+ let fast_mode = timings.fast.unwrap_or(counts(600, 1300, 300));
+ self.w(IC_SS_SCL_HCNT, u32::from(standard.0));
+ self.w(IC_SS_SCL_LCNT, u32::from(standard.1));
+ self.w(IC_FS_SCL_HCNT, u32::from(fast_mode.0));
+ self.w(IC_FS_SCL_LCNT, u32::from(fast_mode.1));
+ let hold = if fast { fast_mode.2 } else { standard.2 };
+ if hold != 0 {
+ self.w(IC_SDA_HOLD, u32::from(hold));
+ }
+ self.con = CON_MASTER
+ | CON_RESTART
+ | CON_SLAVE_DISABLE
+ | if fast { CON_SPEED_FAST } else { CON_SPEED_STANDARD };
+ self.w(IC_CON, self.con);
+ self.w(IC_INTR_MASK, 0);
+ self.w(IC_RX_TL, 0);
+ self.w(IC_TX_TL, 0);
+ self.target = None;
+ }
+
+ /// Points it at `addr`, turning it off and on if it was elsewhere.
+ fn target(&mut self, addr: u16) -> bool {
+ if self.target == Some(addr) {
+ return true;
+ }
+ if !self.enable(false) {
+ return false;
+ }
+ let ten_bit = addr > 0x7f;
+ self.w(
+ IC_CON,
+ if ten_bit {
+ self.con | CON_10BIT_MASTER
+ } else {
+ self.con
+ },
+ );
+ self.w(IC_TAR, u32::from(addr & 0x3ff));
+ let on = self.enable(true);
+ self.target = on.then_some(addr);
+ on
+ }
+
+ /// After an abort or a deadline missed: waits for the bus to be let
+ /// go, and turns the controller off, to be pointed again next time.
+ fn recover(&mut self) {
+ until(5, || self.r(IC_STATUS) & STATUS_MST_ACTIVITY == 0);
+ self.enable(false);
+ self.target = None;
+ }
+
+ fn transfer(&mut self, addr: u16, write: &[u8], read: &mut [u8]) -> bool {
+ let total = write.len() + read.len();
+ if total == 0 || !self.target(addr) {
+ return false;
+ }
+ // Whatever an earlier transfer left.
+ while self.r(IC_RXFLR) > 0 {
+ self.r(IC_DATA_CMD);
+ }
+ self.r(IC_CLR_INTR);
+ // A byte is 90 µs at 100 kHz: 20 ms and a millisecond per ten.
+ let deadline = crate::timer::now_ms() + 20 + total as u64 / 10;
+ let (mut sent, mut got) = (0, 0);
+ loop {
+ // Commands in while the FIFO has room, no more reads queued
+ // than the receive FIFO holds.
+ while sent < total && self.r(IC_STATUS) & STATUS_TFNF != 0 {
+ let reading = sent >= write.len();
+ if reading && sent - write.len() - got >= self.rx_depth {
+ break;
+ }
+ let mut cmd = if reading {
+ CMD_READ
+ | if sent == write.len() && !write.is_empty() {
+ CMD_RESTART
+ } else {
+ 0
+ }
+ } else {
+ u32::from(write[sent])
+ };
+ if sent + 1 == total {
+ cmd |= CMD_STOP;
+ }
+ self.w(IC_DATA_CMD, cmd);
+ sent += 1;
+ }
+ while got < read.len() && self.r(IC_RXFLR) > 0 {
+ read[got] = self.r(IC_DATA_CMD) as u8;
+ got += 1;
+ }
+ // An abort comes with a stop too: looked at first. A stop
+ // with bytes still in the FIFO is taken next time round.
+ let raw = self.r(IC_RAW_INTR_STAT);
+ if raw & INTR_TX_ABRT != 0 {
+ self.last_abort = self.r(IC_TX_ABRT_SOURCE);
+ self.aborts += 1;
+ self.r(IC_CLR_TX_ABRT);
+ self.recover();
+ return false;
+ }
+ if sent == total && got == read.len() && raw & INTR_STOP_DET != 0 {
+ self.r(IC_CLR_STOP_DET);
+ return true;
+ }
+ if crate::timer::now_ms() > deadline {
+ self.recover();
+ return false;
+ }
+ core::hint::spin_loop();
+ }
+ }
+}
+
+impl I2cBus for Controller {
+ fn write_read(&mut self, addr: u16, write: &[u8], read: &mut [u8]) -> bool {
+ self.transfer(addr, write, read)
+ }
+}
diff --git a/kernel/src/drivers/i2c_hid.rs b/kernel/src/drivers/i2c_hid.rs
new file mode 100644
index 0000000..42c427b
--- /dev/null
+++ b/kernel/src/drivers/i2c_hid.rs
@@ -0,0 +1,306 @@
+//! A laptop's touchpad on I²C: HID over I²C (`pinnacle_hid::i2c`),
+//! through Intel's LPSS DesignWare controllers (`drivers::i2c_dw`).
+//!
+//! Nothing on I²C says what is there: the firmware's AML does. Each
+//! device answering to `PNP0C50` (or `ACPI0C50`) and present by its
+//! `_STA` is powered (`_PS0`), its `_CRS` gives its address, speed and
+//! controller (`I2cSerialBus`), its `_DSM` the register its HID
+//! descriptor is at. The controller is the PCI function its AML device's
+//! `_ADR` names (device << 16 | function) on the root bridge's bus.
+//!
+//! The device signals a report by pulling a GPIO line (`GpioInt` in its
+//! `_CRS`), and the kernel has no GPIO driver yet: its input register is
+//! read from a kernel task every 8 ms instead. A relative report moves
+//! the kernel's pointer as the PS/2 touchpad's does (`BY_MOUSE`); the
+//! precision touchpad's own reports (fingers, gestures) are not asked
+//! for, and the device sends its mouse's.
+
+use crate::drivers::i2c_dw::{self, Timing, Timings};
+use crate::sync::Mutex;
+use alloc::string::String;
+use alloc::vec;
+use alloc::vec::Vec;
+use pinnacle_aml::resource::Resource;
+use pinnacle_aml::{Host, Namespace, Path, Value};
+use pinnacle_hid::Pointer;
+use pinnacle_hid::i2c::{self, DSM_UUID, Device};
+
+/// How often the input register is read, in ms.
+const POLL_MS: u64 = 8;
+
+/// What the firmware says of one HID device on I²C.
+struct Described {
+ path: Path,
+ /// Its own ID (`ELAN0001`), or `PNP0C50` when it has no other.
+ id: String,
+ address: u16,
+ speed: u32,
+ controller: Path,
+ /// Its controller's PCI bus, device and function.
+ pci: Option<(u8, u8, u8)>,
+ timings: Timings,
+ /// The HID descriptor's register, from `_DSM`.
+ register: Option<u16>,
+ /// Its interrupt: a GPIO pin and the controller it is on.
+ gpio: Option<(u16, String)>,
+}
+
+/// A touchpad brought up.
+struct Touchpad {
+ name: String,
+ /// Its controller, in [`i2c_dw::CONTROLLERS`].
+ controller: usize,
+ device: Device,
+ pointer: Pointer,
+ failures: u32,
+ reported: bool,
+}
+
+static TOUCHPADS: Mutex<Vec<Touchpad>> = Mutex::new(Vec::new());
+
+/// A mode's package from the controller's AML (`SSCN`, `FMCN`): SCL's
+/// high and low counts, SDA's hold.
+fn timing(ns: &mut Namespace, host: &mut dyn Host, controller: &Path, name: &[u8; 4]) -> Option<Timing> {
+ let Some(Ok(Value::Package(p))) = ns.evaluate_if(&controller.child(*name), Vec::new(), host) else {
+ return None;
+ };
+ let at = |i: usize| p.get(i).and_then(Value::integer).map(|v| v as u16);
+ Some((at(0)?, at(1)?, at(2).unwrap_or(0)))
+}
+
+/// Every present HID-over-I²C device, as AML describes it; each powered
+/// on by its `_PS0`, and its controller by its own.
+fn describe(ns: &mut Namespace, host: &mut dyn Host) -> Vec<Described> {
+ let mut paths = ns.find("PNP0C50", host);
+ for p in ns.find("ACPI0C50", host) {
+ if !paths.contains(&p) {
+ paths.push(p);
+ }
+ }
+ let mut out = Vec::new();
+ for path in paths {
+ if ns.status(&path, host) & 1 == 0 {
+ continue;
+ }
+ let ids = ns.ids(&path, host);
+ let id = ids
+ .iter()
+ .find(|i| *i != "PNP0C50" && *i != "ACPI0C50")
+ .or(ids.first())
+ .cloned()
+ .unwrap_or_default();
+ let resources = ns.resources(&path, host).unwrap_or_default();
+ let Some((address, speed, source)) = resources.iter().find_map(|r| match r {
+ Resource::I2c {
+ address,
+ speed,
+ source,
+ ..
+ } => Some((*address, *speed, source.clone())),
+ _ => None,
+ }) else {
+ continue;
+ };
+ let gpio = resources.iter().find_map(|r| match r {
+ Resource::Gpio {
+ interrupt: true,
+ pins,
+ source,
+ ..
+ } => Some((pins.first().copied().unwrap_or(0), source.clone())),
+ _ => None,
+ });
+ // The controller's path: absolute as firmware writes it, else
+ // from the device's scope.
+ let mut controller = Path::parse(&source);
+ if !source.starts_with('\\') && ns.get(&controller).is_none() {
+ let mut p = path.parent();
+ for seg in Path::parse(&source).0 {
+ p = p.child(seg);
+ }
+ controller = p;
+ }
+ for device in [&controller, &path] {
+ if let Some(Err(e)) = ns.evaluate_if(&device.child(*b"_PS0"), Vec::new(), host) {
+ crate::println!("touchpad: {device}._PS0: {e}");
+ }
+ }
+ let adr = match ns.evaluate_if(&controller.child(*b"_ADR"), Vec::new(), host) {
+ Some(Ok(v)) => v.integer(),
+ _ => None,
+ };
+ let bus = match ns.evaluate_if(&controller.parent().child(*b"_BBN"), Vec::new(), host) {
+ Some(Ok(v)) => v.integer().unwrap_or(0),
+ _ => 0,
+ };
+ let pci = adr.map(|a| (bus as u8, (a >> 16) as u8, a as u8));
+ let timings = Timings {
+ standard: timing(ns, host, &controller, b"SSCN"),
+ fast: timing(ns, host, &controller, b"FMCN"),
+ };
+ let args = vec![
+ Value::Buffer(DSM_UUID.to_vec()),
+ Value::Integer(1),
+ Value::Integer(1),
+ Value::Package(Vec::new()),
+ ];
+ let register = match ns.evaluate_if(&path.child(*b"_DSM"), args, host) {
+ Some(Ok(v)) => v.integer().map(|r| r as u16),
+ Some(Err(e)) => {
+ crate::println!("touchpad: {path}._DSM: {e}");
+ None
+ }
+ None => None,
+ };
+ out.push(Described {
+ path,
+ id,
+ address,
+ speed,
+ controller,
+ pci,
+ timings,
+ register,
+ gpio,
+ });
+ }
+ out
+}
+
+/// Finds the I²C controllers and the touchpads behind them, and brings
+/// each touchpad up. After `power::init`, before the scheduler runs
+/// ([`watch`] starts reading them). Returns how many work.
+pub fn init() -> usize {
+ let described = crate::power::with_namespace(describe).unwrap_or_default();
+ i2c_dw::init();
+ let mut pads = Vec::new();
+ for d in described {
+ let line = alloc::format!("{} at {:#x} on {}", d.id, d.address, d.controller);
+ let mut controllers = i2c_dw::CONTROLLERS.lock();
+ let Some(index) = d.pci.and_then(|(bus, device, function)| {
+ controllers
+ .iter()
+ .position(|c| (c.bus, c.device, c.function) == (bus, device, function))
+ }) else {
+ crate::println!("touchpad: {line}: its controller is not one this kernel drives");
+ continue;
+ };
+ let Some(register) = d.register else {
+ crate::println!("touchpad: {line}: no HID descriptor register (_DSM)");
+ continue;
+ };
+ let controller = &mut controllers[index];
+ controller.configure(d.speed, d.timings);
+ let device = match i2c::bring_up(controller, d.address, register, |ms| {
+ crate::apic::wait_us(u64::from(ms) * 1000)
+ }) {
+ Ok(device) => device,
+ Err(e) => {
+ crate::println!(
+ "touchpad: {line}: {e} (aborts {}, last cause {:#x})",
+ controller.aborts,
+ controller.last_abort
+ );
+ continue;
+ }
+ };
+ drop(controllers);
+ let h = device.descriptor;
+ crate::println!(
+ "touchpad: {line}, HID {:04x}:{:04x}, polled{}",
+ h.vendor,
+ h.product,
+ if device.reset_answered {
+ ""
+ } else {
+ " (its reset was not answered)"
+ }
+ );
+ if let Some((pin, source)) = &d.gpio {
+ crate::println!(
+ "touchpad: its interrupt, GPIO pin {pin} on {source}, not followed (no GPIO driver yet): read every {POLL_MS} ms"
+ );
+ }
+ crate::device::add(crate::device::Device {
+ name: alloc::format!("{}", d.path),
+ compatible: vec![d.id.clone(), String::from("PNP0C50")],
+ regs: Vec::new(),
+ interrupts: Vec::new(),
+ driver: Some(("i2c-hid", crate::device::Class::Input)),
+ properties: Vec::new(),
+ });
+ let (width, height) = screen();
+ pads.push(Touchpad {
+ name: d.id,
+ controller: index,
+ device,
+ pointer: Pointer::new(width, height),
+ failures: 0,
+ reported: false,
+ });
+ }
+ let n = pads.len();
+ *TOUCHPADS.lock() = pads;
+ n
+}
+
+/// Starts the kernel task that reads the touchpads, if there are any.
+/// After the scheduler runs.
+pub fn watch() {
+ if !TOUCHPADS.lock().is_empty() {
+ crate::sched::spawn(polling);
+ }
+}
+
+/// The screen's size, which the pointer is kept in.
+fn screen() -> (i32, i32) {
+ crate::drivers::display::DISPLAY
+ .lock()
+ .as_ref()
+ .map_or((1, 1), |d| (d.width as i32, d.height as i32))
+}
+
+/// Sleeps the calling kernel task until `deadline` (ms since boot).
+fn sleep_until(deadline: u64) {
+ crate::arch::kernel_call(pinnacle_abi::call::SLEEP_UNTIL, deadline);
+}
+
+/// Reads every touchpad's input register, every [`POLL_MS`], and sends
+/// what moved to the display server.
+fn polling() {
+ loop {
+ let next = crate::timer::now_ms() + POLL_MS;
+ let screen = screen();
+ let mut events = Vec::new();
+ {
+ let mut pads = TOUCHPADS.lock();
+ let mut controllers = i2c_dw::CONTROLLERS.lock();
+ for pad in pads.iter_mut() {
+ let Some(c) = controllers.get_mut(pad.controller) else {
+ continue;
+ };
+ let mut moved = Vec::new();
+ match pad.device.poll(c, &mut pad.pointer, screen, &mut moved) {
+ Ok(report) => {
+ pad.failures = 0;
+ if report && !core::mem::replace(&mut pad.reported, true) {
+ crate::println!("touchpad: {}: its first report", pad.name);
+ }
+ }
+ Err(e) => {
+ pad.failures += 1;
+ // Said once a stretch of failures, not every 8 ms.
+ if pad.failures == 125 {
+ crate::println!("touchpad: {}: {e} for a second, still reading", pad.name);
+ }
+ }
+ }
+ events.extend(moved.into_iter().map(super::input::pointer_event));
+ }
+ }
+ if !events.is_empty() {
+ super::input::deliver(events);
+ }
+ sleep_until(next);
+ }
+}
diff --git a/kernel/src/drivers/mod.rs b/kernel/src/drivers/mod.rs
index 117f632..9ca3e3a 100644
--- a/kernel/src/drivers/mod.rs
+++ b/kernel/src/drivers/mod.rs
@@ -10,6 +10,10 @@ pub mod e1000;
pub mod gpu;
pub mod gpu3d;
pub mod hda;
+#[cfg(target_arch = "x86_64")]
+pub mod i2c_dw;
+#[cfg(target_arch = "x86_64")]
+pub mod i2c_hid;
pub mod input;
pub mod net;
pub mod nvme;
diff --git a/kernel/src/main.rs b/kernel/src/main.rs
index 09ffb47..86244a2 100644
--- a/kernel/src/main.rs
+++ b/kernel/src/main.rs
@@ -172,6 +172,9 @@ extern "C" fn kmain(start_info: usize, magic: u32) -> ! {
}
// The firmware's AML: the embedded controller, battery, charger, lid.
power::init(boot.rsdp);
+ // A touchpad on I²C, found through the AML; read by a task of its own,
+ // started beside `power::watch`.
+ drivers::i2c_hid::init();
// USB before the disks: a stick is one of them.
// Not inside println!: the driver prints as it goes, and the console's
// lock is held while println!'s arguments are worked out.
@@ -261,6 +264,7 @@ extern "C" fn kmain(start_info: usize, magic: u32) -> ! {
}
drivers::usb::watch();
power::watch();
+ drivers::i2c_hid::watch();
let inputs = drivers::input::init();
println!("input: {inputs} devices");
drivers::screen_log::stop();