garage44.eu/jeroen/pinnacle

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

.. /kernel/src/drivers/i2c_dw.rs

raw

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