garage44.eu/jeroen/pinnacle

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

.. /hid/src/i2c.rs

raw

//! HID over I²C (Microsoft's HID over I2C Protocol Specification 1.0):
//! a laptop's touchpad, and some keyboards, on an I²C bus rather than
//! USB. The firmware's ACPI says where (the device's `I2cSerialBus`
//! resource: its controller and address) and which register its HID
//! descriptor is at (its `_DSM`, [`DSM_UUID`] function 1); everything
//! else the device says itself, in that descriptor.
//!
//! Bringing one up ([`Bringup`], a state machine, so that whoever runs
//! it may sleep between steps): read the 30-byte HID descriptor, turn
//! the device on (SET_POWER ON), RESET it and wait for its answer (an
//! input report of length 0), read its report descriptor. From then on
//! ([`Device`]) each read of the input register is a 2-byte length
//! (with itself) and a report; a length of 0 is nothing to say.
//!
//! The input register is read as Linux's `i2c-hid` reads it: a plain
//! read at the device's address, no register written first. A device
//! raises its interrupt line while it has a report; with no line
//! followed, the reads come by polling, and a device with nothing to say
//! answers a length of 0.

use crate::{Layout, Pointer, PointerEvent};
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;

/// An I²C bus as a HID device needs it, at 7-bit (or 10-bit) address
/// `addr`.
pub trait I2cBus {
    /// Writes `write`, then with a repeated start reads `read.len()`
    /// bytes: one transfer. Empty `write`: a plain read; empty `read`: a
    /// plain write. False when the device did not answer (no
    /// acknowledgement) or the bus failed.
    fn write_read(&mut self, addr: u16, write: &[u8], read: &mut [u8]) -> bool;

    /// Writes `bytes`, and stops.
    fn write(&mut self, addr: u16, bytes: &[u8]) -> bool {
        self.write_read(addr, bytes, &mut [])
    }
}

/// The `_DSM` that answers the HID descriptor's register (function 1,
/// revision 1), `3CDFF6F7-4267-4555-AD05-B30A3D8938DE`, as the 16-byte
/// buffer AML's `ToUUID` makes of it (the first three groups little
/// endian).
pub const DSM_UUID: [u8; 16] = [
    0xf7, 0xf6, 0xdf, 0x3c, 0x67, 0x42, 0x55, 0x45, 0xad, 0x05, 0xb3, 0x0a, 0x3d, 0x89, 0x38, 0xde,
];

/// How long the HID descriptor is (wHIDDescLength), in version 1.0.
pub const DESCRIPTOR_LEN: usize = 30;

/// Command opcodes (section 7.2), written to the command register.
const RESET: u8 = 0x01;
const SET_POWER: u8 = 0x08;
/// SET_POWER's states.
const POWER_ON: u8 = 0;

/// Steps: how often the reset's answer is looked for, and how long
/// apart (ms): a second in all. The specification gives a device five
/// seconds; Linux, too, goes on without the answer.
const RESET_TRIES: u32 = 100;
const RESET_EVERY_MS: u32 = 10;
/// How often the HID descriptor is asked for: a device just powered
/// may not acknowledge the first.
const DESCRIPTOR_TRIES: u32 = 3;
/// The longest report descriptor and input report taken.
const MAX_REPORT_DESCRIPTOR: usize = 8192;
const MAX_INPUT: usize = 4096;

/// The HID descriptor (section 5.1): where the device's registers are,
/// what it is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct HidDescriptor {
    /// bcdVersion: 0x0100.
    pub version: u16,
    pub report_descriptor_length: u16,
    pub report_descriptor_register: u16,
    pub input_register: u16,
    /// The longest input report, with its two length bytes.
    pub max_input_length: u16,
    pub output_register: u16,
    pub max_output_length: u16,
    pub command_register: u16,
    pub data_register: u16,
    pub vendor: u16,
    pub product: u16,
    pub version_id: u16,
}

impl HidDescriptor {
    /// Reads the 30 bytes; None unless they say they are 30 long and of
    /// version 1.0.
    pub fn parse(b: &[u8]) -> Option<HidDescriptor> {
        let w = |i: usize| -> Option<u16> { Some(u16::from_le_bytes([*b.get(2 * i)?, *b.get(2 * i + 1)?])) };
        if usize::from(w(0)?) != DESCRIPTOR_LEN || w(1)? != 0x0100 {
            return None;
        }
        Some(HidDescriptor {
            version: w(1)?,
            report_descriptor_length: w(2)?,
            report_descriptor_register: w(3)?,
            input_register: w(4)?,
            max_input_length: w(5)?,
            output_register: w(6)?,
            max_output_length: w(7)?,
            command_register: w(8)?,
            data_register: w(9)?,
            vendor: w(10)?,
            product: w(11)?,
            version_id: w(12)?,
        })
    }
}

/// Why a device was not brought up, or stopped answering.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    /// The HID descriptor's register did not answer.
    NoDescriptor,
    /// It answered, not with a version 1.0 HID descriptor.
    BadDescriptor,
    /// SET_POWER ON, or RESET, was not acknowledged.
    PowerOn,
    Reset,
    /// The report descriptor could not be read.
    NoReportDescriptor,
    /// The report descriptor has no report with an X and a Y.
    NoPointer,
    /// A read of the input register failed.
    Input,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self {
            Error::NoDescriptor => "no HID descriptor",
            Error::BadDescriptor => "not a HID 1.0 descriptor",
            Error::PowerOn => "SET_POWER not acknowledged",
            Error::Reset => "RESET not acknowledged",
            Error::NoReportDescriptor => "no report descriptor",
            Error::NoPointer => "no pointer in its reports",
            Error::Input => "the input register did not answer",
        })
    }
}

/// Where a [`Bringup`] is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
    Descriptor,
    PowerOn,
    Reset,
    ResetAnswer,
    ReportDescriptor,
}

/// What the caller does after a [`Bringup::step`].
#[derive(Debug, PartialEq, Eq)]
pub enum Step {
    /// Step again after `ms` milliseconds (0: at once).
    Again(u32),
    Ready(Device),
    Failed(Error),
}

/// A device being brought up, a step at a time.
#[derive(Clone, Debug)]
pub struct Bringup {
    address: u16,
    register: u16,
    state: State,
    tries: u32,
    descriptor: HidDescriptor,
    reset_answered: bool,
}

impl Bringup {
    /// The device at `address` whose HID descriptor is at `register`
    /// (from `_DSM`).
    pub fn new(address: u16, register: u16) -> Bringup {
        Bringup {
            address,
            register,
            state: State::Descriptor,
            tries: 0,
            descriptor: HidDescriptor::default(),
            reset_answered: false,
        }
    }

    fn command(&self, bus: &mut dyn I2cBus, opcode: u8, low: u8) -> bool {
        let r = self.descriptor.command_register.to_le_bytes();
        bus.write(self.address, &[r[0], r[1], low, opcode])
    }

    /// The next step.
    pub fn step(&mut self, bus: &mut dyn I2cBus) -> Step {
        match self.state {
            State::Descriptor => {
                let mut b = [0u8; DESCRIPTOR_LEN];
                if !bus.write_read(self.address, &self.register.to_le_bytes(), &mut b) {
                    self.tries += 1;
                    return if self.tries < DESCRIPTOR_TRIES {
                        Step::Again(10)
                    } else {
                        Step::Failed(Error::NoDescriptor)
                    };
                }
                let Some(d) = HidDescriptor::parse(&b) else {
                    return Step::Failed(Error::BadDescriptor);
                };
                self.descriptor = d;
                self.state = State::PowerOn;
                Step::Again(0)
            }
            State::PowerOn => {
                if !self.command(bus, SET_POWER, POWER_ON) {
                    return Step::Failed(Error::PowerOn);
                }
                self.state = State::Reset;
                // Some devices want a moment to wake (Linux gives 60 ms
                // to those it knows of).
                Step::Again(RESET_EVERY_MS)
            }
            State::Reset => {
                if !self.command(bus, RESET, 0) {
                    return Step::Failed(Error::Reset);
                }
                self.state = State::ResetAnswer;
                self.tries = 0;
                Step::Again(RESET_EVERY_MS)
            }
            State::ResetAnswer => {
                let mut b = vec![0u8; input_length(&self.descriptor)];
                if bus.write_read(self.address, &[], &mut b) && b[0] == 0 && b[1] == 0 {
                    self.reset_answered = true;
                    self.state = State::ReportDescriptor;
                    return Step::Again(0);
                }
                self.tries += 1;
                if self.tries >= RESET_TRIES {
                    self.state = State::ReportDescriptor;
                    return Step::Again(0);
                }
                Step::Again(RESET_EVERY_MS)
            }
            State::ReportDescriptor => {
                let length = usize::from(self.descriptor.report_descriptor_length);
                if length == 0 || length > MAX_REPORT_DESCRIPTOR {
                    return Step::Failed(Error::NoReportDescriptor);
                }
                let mut report_descriptor = vec![0u8; length];
                let register = self.descriptor.report_descriptor_register.to_le_bytes();
                if !bus.write_read(self.address, &register, &mut report_descriptor) {
                    return Step::Failed(Error::NoReportDescriptor);
                }
                let Some(layout) = crate::parse_relative(&report_descriptor) else {
                    return Step::Failed(Error::NoPointer);
                };
                Step::Ready(Device {
                    address: self.address,
                    descriptor: self.descriptor,
                    input: vec![0; input_length(&self.descriptor)],
                    report_descriptor,
                    layout,
                    reset_answered: self.reset_answered,
                })
            }
        }
    }
}

/// How many bytes an input read takes: the device's longest report,
/// with its length.
fn input_length(d: &HidDescriptor) -> usize {
    usize::from(d.max_input_length).clamp(2, MAX_INPUT)
}

/// Brings up the device at `address`, its HID descriptor at `register`,
/// calling `wait` with the milliseconds to wait between steps.
pub fn bring_up(
    bus: &mut dyn I2cBus,
    address: u16,
    register: u16,
    mut wait: impl FnMut(u32),
) -> Result<Device, Error> {
    let mut b = Bringup::new(address, register);
    loop {
        match b.step(bus) {
            Step::Again(0) => {}
            Step::Again(ms) => wait(ms),
            Step::Ready(d) => return Ok(d),
            Step::Failed(e) => return Err(e),
        }
    }
}

/// A device brought up: its descriptors, and its pointer's layout.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Device {
    pub address: u16,
    pub descriptor: HidDescriptor,
    pub report_descriptor: Vec<u8>,
    /// The report the pointer is read from: the mouse's, where the
    /// device has one beside a precision touchpad's.
    pub layout: Layout,
    /// Whether the RESET was answered with its empty report.
    pub reset_answered: bool,
    input: Vec<u8>,
}

impl Device {
    /// Reads the input register: the report it holds (its ID first,
    /// where the device numbers its reports), or None when it has
    /// nothing to say (a length of 0, or no more than the length itself)
    /// or says it has more than it can.
    pub fn read_input(&mut self, bus: &mut dyn I2cBus) -> Result<Option<&[u8]>, Error> {
        Ok(self.read(bus)?.map(|n| &self.input[2..n]))
    }

    /// The input report's end in `input`, if there is one.
    fn read(&mut self, bus: &mut dyn I2cBus) -> Result<Option<usize>, Error> {
        if !bus.write_read(self.address, &[], &mut self.input) {
            return Err(Error::Input);
        }
        let length = usize::from(u16::from_le_bytes([self.input[0], self.input[1]]));
        Ok((length > 2 && length <= self.input.len()).then_some(length))
    }

    /// Reads the input register once, and moves `pointer` by what it
    /// says on a `screen` of that size. True when a report came.
    pub fn poll(
        &mut self,
        bus: &mut dyn I2cBus,
        pointer: &mut Pointer,
        screen: (i32, i32),
        out: &mut Vec<PointerEvent>,
    ) -> Result<bool, Error> {
        let Some(end) = self.read(bus)? else {
            return Ok(false);
        };
        pointer.report(&self.layout, &self.input[2..end], screen, out);
        Ok(true)
    }
}