Files
RedBear-OS/drivers/gpio/intel-gpiod/src/main.rs
T

402 lines
13 KiB
Rust

use std::collections::BTreeMap;
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::path::Path;
use std::process;
use acpi_resource::{
AddressResourceType, ExtendedIrqDescriptor, FixedMemory32Descriptor, GpioDescriptor,
IrqDescriptor, Memory32RangeDescriptor, ResourceDescriptor,
};
use anyhow::{Context, Result};
use common::{MemoryType, PhysBorrowed, Prot};
use serde::{Deserialize, Serialize};
const SUPPORTED_IDS: &[&str] = &["INT34C5", "INTC1055"];
const PADNFGPIO_OWN_BASE: usize = 0x20;
const PADNFGPIO_PADCFG_BASE: usize = 0x700;
const GPI_INT_STATUS: usize = 0x100;
const GPI_INT_EN: usize = 0x120;
const INTEL_GPIO_MMIO_WINDOW: usize = PADNFGPIO_PADCFG_BASE + core::mem::size_of::<u32>();
#[derive(Debug, Deserialize)]
struct AmlSymbol {
name: String,
value: AmlValue,
}
#[derive(Debug, Deserialize)]
enum AmlValue {
Integer(u64),
String(String),
}
#[derive(Clone, Debug)]
struct ControllerResources {
mmio_base: usize,
mmio_len: usize,
pin_count: usize,
supports_interrupt: bool,
gpio_int_count: usize,
gpio_io_count: usize,
}
#[derive(Debug)]
struct ControllerDescriptor {
device: String,
hid: String,
resources: ControllerResources,
}
struct RegisteredController {
_mmio: Option<PhysBorrowed>,
_registration: File,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct GpioControllerInfo {
id: u32,
name: String,
pin_count: usize,
supports_interrupt: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
enum GpioControlRequest {
RegisterController { info: GpioControllerInfo },
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
enum GpioControlResponse {
ControllerRegistered { id: u32 },
Error(String),
}
fn main() {
common::setup_logging(
"gpio",
"intel-gpio",
"intel-gpiod",
common::output_level(),
common::file_level(),
);
daemon::Daemon::new(daemon_runner);
}
fn daemon_runner(daemon: daemon::Daemon) -> ! {
if let Err(err) = daemon_main(daemon) {
log::error!("intel-gpiod: {err:#}");
process::exit(1);
}
process::exit(0);
}
fn daemon_main(daemon: daemon::Daemon) -> Result<()> {
common::init();
let controllers =
discover_controllers(SUPPORTED_IDS).context("failed to discover Intel GPIO controllers")?;
if controllers.is_empty() {
log::info!("intel-gpiod: no supported Intel GPIO ACPI controllers found");
}
let mut registered = Vec::new();
for controller in controllers {
match register_controller(controller) {
Ok(controller) => registered.push(controller),
Err(err) => log::warn!("intel-gpiod: controller registration skipped: {err:#}"),
}
}
daemon.ready();
libredox::call::setrens(0, 0).context("failed to enter null namespace")?;
log::info!("intel-gpiod: registered {} controller(s)", registered.len());
loop {
std::thread::park();
}
}
fn discover_controllers(supported_ids: &[&str]) -> Result<Vec<ControllerDescriptor>> {
let mut matched = BTreeMap::new();
let entries = match fs::read_dir("/scheme/acpi/symbols") {
Ok(entries) => entries,
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock || err.raw_os_error() == Some(11) => {
log::debug!("intel-gpiod: ACPI symbols are not ready yet");
return Ok(Vec::new());
}
Err(err) => return Err(err).context("failed to read /scheme/acpi/symbols"),
};
for entry in entries {
let entry = entry.context("failed to read ACPI symbol directory entry")?;
let Some(file_name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
if !file_name.ends_with("_HID") && !file_name.ends_with("_CID") {
continue;
}
let Some(id) = read_symbol_id(&entry.path())? else {
continue;
};
if !supported_ids.iter().any(|candidate| *candidate == id) {
continue;
}
let device = file_name
.strip_suffix("_HID")
.or_else(|| file_name.strip_suffix("_CID"))
.map(str::to_owned);
if let Some(device) = device {
matched.entry(device).or_insert(id);
}
}
let mut controllers = Vec::new();
for (device, hid) in matched {
let resources = read_controller_resources(&device)
.with_context(|| format!("failed to read resources for {device}"))?;
controllers.push(ControllerDescriptor {
device,
hid,
resources,
});
}
Ok(controllers)
}
fn read_symbol_id(path: &Path) -> Result<Option<String>> {
let contents = fs::read_to_string(path)
.with_context(|| format!("failed to read ACPI symbol {}", path.display()))?;
let symbol = match ron::from_str::<AmlSymbol>(&contents) {
Ok(symbol) => symbol,
Err(err) => {
log::debug!(
"intel-gpiod: skipping {} because the symbol payload was not a scalar ID: {err}",
path.display(),
);
return Ok(None);
}
};
let id = match symbol.value {
AmlValue::Integer(integer) => eisa_id_from_integer(integer),
AmlValue::String(string) => string,
};
log::debug!("intel-gpiod: {} -> {id}", symbol.name);
Ok(Some(id))
}
fn read_controller_resources(device: &str) -> Result<ControllerResources> {
let contents = fs::read_to_string(format!("/scheme/acpi/resources/{device}"))
.with_context(|| format!("failed to read /scheme/acpi/resources/{device}"))?;
let resources = ron::from_str::<Vec<ResourceDescriptor>>(&contents)
.with_context(|| format!("failed to decode RON resources for {device}"))?;
let mut mmio = None;
let mut supports_interrupt = false;
let mut gpio_int_count = 0usize;
let mut gpio_io_count = 0usize;
let mut pin_count = 0usize;
for resource in &resources {
match resource {
ResourceDescriptor::FixedMemory32(FixedMemory32Descriptor {
address,
address_length,
..
}) if mmio.is_none() => {
mmio = Some((
*address as usize,
(*address_length as usize).max(INTEL_GPIO_MMIO_WINDOW),
));
}
ResourceDescriptor::Memory32Range(Memory32RangeDescriptor {
minimum,
maximum,
address_length,
..
}) if mmio.is_none() && maximum >= minimum => {
let span = maximum.saturating_sub(*minimum).saturating_add(1) as usize;
mmio = Some((
*minimum as usize,
span.max((*address_length as usize).max(INTEL_GPIO_MMIO_WINDOW)),
));
}
ResourceDescriptor::Address32(descriptor)
if mmio.is_none()
&& matches!(descriptor.resource_type, AddressResourceType::MemoryRange) =>
{
mmio = Some((
descriptor.minimum as usize,
(descriptor.address_length as usize).max(INTEL_GPIO_MMIO_WINDOW),
));
}
ResourceDescriptor::Address64(descriptor)
if mmio.is_none()
&& matches!(descriptor.resource_type, AddressResourceType::MemoryRange) =>
{
let base = usize::try_from(descriptor.minimum)
.context("64-bit MMIO base does not fit in usize")?;
let len = usize::try_from(descriptor.address_length)
.context("64-bit MMIO length does not fit in usize")?;
mmio = Some((base, len.max(INTEL_GPIO_MMIO_WINDOW)));
}
ResourceDescriptor::Irq(IrqDescriptor { interrupts, .. }) => {
supports_interrupt |= !interrupts.is_empty();
}
ResourceDescriptor::ExtendedIrq(ExtendedIrqDescriptor { interrupts, .. }) => {
supports_interrupt |= !interrupts.is_empty();
}
ResourceDescriptor::GpioInt(descriptor) => {
gpio_int_count += 1;
supports_interrupt = true;
pin_count = pin_count.max(pin_count_from_descriptor(descriptor));
}
ResourceDescriptor::GpioIo(descriptor) => {
gpio_io_count += 1;
pin_count = pin_count.max(pin_count_from_descriptor(descriptor));
}
_ => {}
}
}
let (mmio_base, mmio_len) = mmio.context("no MMIO resource was found")?;
Ok(ControllerResources {
mmio_base,
mmio_len,
pin_count,
supports_interrupt,
gpio_int_count,
gpio_io_count,
})
}
fn pin_count_from_descriptor(descriptor: &GpioDescriptor) -> usize {
descriptor
.pins
.iter()
.copied()
.max()
.map(|pin| usize::from(pin).saturating_add(1))
.unwrap_or(0)
}
fn register_controller(controller: ControllerDescriptor) -> Result<RegisteredController> {
let ControllerDescriptor {
device,
hid,
resources,
} = controller;
let mmio = match PhysBorrowed::map(
resources.mmio_base,
resources.mmio_len,
Prot::RW,
MemoryType::Uncacheable,
) {
Ok(mapping) => Some(mapping),
Err(err) => {
log::warn!(
"intel-gpiod: failed to map MMIO for {device} ({:#x}, len {:#x}): {err}",
resources.mmio_base,
resources.mmio_len,
);
None
}
};
log::info!(
"intel-gpiod: discovered {device} hid={hid} mmio={:#x}+{:#x} pin_count={} gpio_int={} gpio_io={} supports_interrupt={}",
resources.mmio_base,
resources.mmio_len,
resources.pin_count,
resources.gpio_int_count,
resources.gpio_io_count,
resources.supports_interrupt,
);
log::debug!(
"intel-gpiod: register model own={PADNFGPIO_OWN_BASE:#x} padcfg={PADNFGPIO_PADCFG_BASE:#x} gpi_int_status={GPI_INT_STATUS:#x} gpi_int_en={GPI_INT_EN:#x}",
);
let info = GpioControllerInfo {
id: 0,
name: format!("intel-gpio:{device}"),
pin_count: resources.pin_count,
supports_interrupt: resources.supports_interrupt,
};
let mut registration = register_with_gpiod(&info)
.with_context(|| format!("failed to register {device} with gpiod"))?;
let response = read_registration_response(&mut registration)
.with_context(|| format!("failed to read gpiod registration response for {device}"))?;
match response {
GpioControlResponse::ControllerRegistered { id } => {
log::info!(
"RB_INTEL_GPIOD_DEVICE device={} hid={} controller_id={} pin_count={} supports_interrupt={}",
device,
hid,
id,
info.pin_count,
info.supports_interrupt,
);
}
GpioControlResponse::Error(message) => {
anyhow::bail!("gpiod rejected Intel GPIO controller {device}: {message}");
}
}
Ok(RegisteredController {
_mmio: mmio,
_registration: registration,
})
}
fn register_with_gpiod(info: &GpioControllerInfo) -> Result<File> {
let mut file = OpenOptions::new()
.read(true)
.write(true)
.open("/scheme/gpio/register")
.context("failed to open /scheme/gpio/register")?;
let payload = ron::ser::to_string(&GpioControlRequest::RegisterController { info: info.clone() })
.context("failed to encode GPIO controller registration")?;
file.write_all(payload.as_bytes())
.context("failed to send GPIO controller registration")?;
Ok(file)
}
fn read_registration_response(file: &mut File) -> Result<GpioControlResponse> {
let mut buffer = vec![0_u8; 4096];
let count = file
.read(&mut buffer)
.context("failed to read GPIO registration response")?;
buffer.truncate(count);
let text = std::str::from_utf8(&buffer).context("GPIO registration response was not UTF-8")?;
ron::from_str(text).context("failed to decode GPIO registration response")
}
fn eisa_id_from_integer(integer: u64) -> String {
let vendor = integer & 0xFFFF;
let device = (integer >> 16) & 0xFFFF;
let vendor_rev = ((vendor & 0xFF) << 8) | (vendor >> 8);
let vendor_1 = (((vendor_rev >> 10) & 0x1F) as u8 + 64) as char;
let vendor_2 = (((vendor_rev >> 5) & 0x1F) as u8 + 64) as char;
let vendor_3 = (((vendor_rev >> 0) & 0x1F) as u8 + 64) as char;
let device_1 = (device >> 4) & 0xF;
let device_2 = (device >> 0) & 0xF;
let device_3 = (device >> 12) & 0xF;
let device_4 = (device >> 8) & 0xF;
format!(
"{vendor_1}{vendor_2}{vendor_3}{device_1:01X}{device_2:01X}{device_3:01X}{device_4:01X}"
)
}