garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/i2c_hid.rs

raw

//! 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);
    }
}