406 lines
13 KiB
Rust
406 lines
13 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
//! Versioned local wire contract between Alkane OS and an SDK hardware backend.
|
|
|
|
use crate::HardwareBackend;
|
|
use std::fmt;
|
|
use std::io::{self, Read, Write};
|
|
use std::net::Shutdown;
|
|
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
|
|
use std::os::unix::ffi::OsStrExt;
|
|
use std::os::unix::net::UnixStream;
|
|
use std::path::Path;
|
|
use std::time::{Duration, Instant};
|
|
|
|
const MAGIC: [u8; 4] = *b"ALKH";
|
|
const VERSION: u8 = 1;
|
|
const RESPONSE: u16 = 1;
|
|
const HEADER_LEN: usize = 16;
|
|
const MAX_PAYLOAD: usize = 4096;
|
|
const IO_TIMEOUT: Duration = Duration::from_secs(2);
|
|
|
|
const SEND_FRAME: u8 = 1;
|
|
const RECEIVE_FRAME: u8 = 2;
|
|
const SET_CHAIN_RESET: u8 = 3;
|
|
const SET_FAN_TARGET: u8 = 4;
|
|
const READ_TEMPERATURE: u8 = 5;
|
|
const SET_PSU_ENABLED: u8 = 6;
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
compile_error!("Alkane HAL sockets require Linux");
|
|
|
|
#[cfg(target_os = "linux")]
|
|
mod sys {
|
|
pub use std::ffi::{c_char as CChar, c_int as CInt, c_void as CVoid};
|
|
pub type SaFamily = u16;
|
|
pub type SocklenT = u32;
|
|
|
|
pub const AF_UNIX: CInt = 1;
|
|
pub const SOCK_STREAM: CInt = 1;
|
|
pub const SOCK_NONBLOCK: CInt = 0x800;
|
|
pub const SOCK_CLOEXEC: CInt = 0x80000;
|
|
pub const SOL_SOCKET: CInt = 1;
|
|
pub const SO_ERROR: CInt = 4;
|
|
pub const POLLOUT: i16 = 4;
|
|
pub const EAGAIN: CInt = 11;
|
|
pub const EISCONN: CInt = 106;
|
|
pub const EINPROGRESS: CInt = 115;
|
|
|
|
#[repr(C)]
|
|
pub struct SockaddrUn {
|
|
pub sun_family: SaFamily,
|
|
pub sun_path: [CChar; 108],
|
|
}
|
|
|
|
#[repr(C)]
|
|
pub struct PollFd {
|
|
pub fd: CInt,
|
|
pub events: i16,
|
|
pub revents: i16,
|
|
}
|
|
|
|
extern "C" {
|
|
pub fn socket(domain: CInt, socket_type: CInt, protocol: CInt) -> CInt;
|
|
pub fn connect(fd: CInt, address: *const CVoid, length: SocklenT) -> CInt;
|
|
pub fn poll(fds: *mut PollFd, count: usize, timeout_ms: CInt) -> CInt;
|
|
pub fn getsockopt(
|
|
fd: CInt,
|
|
level: CInt,
|
|
name: CInt,
|
|
value: *mut CVoid,
|
|
length: *mut SocklenT,
|
|
) -> CInt;
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum HalError {
|
|
Io(io::Error),
|
|
Protocol(&'static str),
|
|
Device(u8),
|
|
FrameTooLong,
|
|
InvalidFanPercent,
|
|
}
|
|
|
|
impl fmt::Display for HalError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::Io(error) => write!(f, "HAL I/O: {error}"),
|
|
Self::Protocol(message) => write!(f, "HAL protocol: {message}"),
|
|
Self::Device(code) => write!(f, "HAL device error: {code}"),
|
|
Self::FrameTooLong => f.write_str("HAL frame exceeds the wire limit"),
|
|
Self::InvalidFanPercent => f.write_str("HAL fan target exceeds 100 percent"),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for HalError {}
|
|
|
|
impl From<io::Error> for HalError {
|
|
fn from(error: io::Error) -> Self {
|
|
Self::Io(error)
|
|
}
|
|
}
|
|
|
|
/// Local client for the privileged board backend supplied by the SDK image.
|
|
pub struct HalClient {
|
|
stream: UnixStream,
|
|
sequence: u32,
|
|
poisoned: bool,
|
|
}
|
|
|
|
impl HalClient {
|
|
fn poison(&mut self) {
|
|
self.poisoned = true;
|
|
let _ = self.stream.shutdown(Shutdown::Both);
|
|
}
|
|
|
|
pub fn connect(path: impl AsRef<Path>) -> Result<Self, HalError> {
|
|
let stream = connect_until(path.as_ref(), Instant::now() + IO_TIMEOUT)?;
|
|
Self::from_stream(stream)
|
|
}
|
|
|
|
pub fn from_stream(stream: UnixStream) -> Result<Self, HalError> {
|
|
stream.set_read_timeout(Some(IO_TIMEOUT))?;
|
|
stream.set_write_timeout(Some(IO_TIMEOUT))?;
|
|
Ok(Self {
|
|
stream,
|
|
sequence: 0,
|
|
poisoned: false,
|
|
})
|
|
}
|
|
|
|
fn exchange(&mut self, opcode: u8, payload: &[u8]) -> Result<Vec<u8>, HalError> {
|
|
if self.poisoned {
|
|
return Err(HalError::Protocol("connection is unusable"));
|
|
}
|
|
if payload.len() > MAX_PAYLOAD {
|
|
return Err(HalError::FrameTooLong);
|
|
}
|
|
let result = self.exchange_inner(opcode, payload);
|
|
if let Err(ref error) = result {
|
|
if !matches!(error, HalError::Device(_)) {
|
|
self.poison();
|
|
// A backend power lease must expire on disconnect. Reusing a
|
|
// desynchronized stream could silently discard an off request.
|
|
}
|
|
}
|
|
result
|
|
}
|
|
|
|
fn exchange_inner(&mut self, opcode: u8, payload: &[u8]) -> Result<Vec<u8>, HalError> {
|
|
let deadline = Instant::now() + IO_TIMEOUT;
|
|
self.sequence = self.sequence.wrapping_add(1);
|
|
let sequence = self.sequence;
|
|
let mut header = [0_u8; HEADER_LEN];
|
|
header[..4].copy_from_slice(&MAGIC);
|
|
header[4] = VERSION;
|
|
header[5] = opcode;
|
|
header[8..12].copy_from_slice(&sequence.to_le_bytes());
|
|
header[12..16].copy_from_slice(&(payload.len() as u32).to_le_bytes());
|
|
write_all_until(&mut self.stream, &header, deadline)?;
|
|
write_all_until(&mut self.stream, payload, deadline)?;
|
|
|
|
read_exact_until(&mut self.stream, &mut header, deadline)?;
|
|
if header[..4] != MAGIC || header[4] != VERSION || header[5] != opcode {
|
|
return Err(HalError::Protocol("response identity mismatch"));
|
|
}
|
|
if u16::from_le_bytes([header[6], header[7]]) != RESPONSE {
|
|
return Err(HalError::Protocol("response flag missing"));
|
|
}
|
|
if u32::from_le_bytes(header[8..12].try_into().unwrap()) != sequence {
|
|
return Err(HalError::Protocol("response sequence mismatch"));
|
|
}
|
|
let length = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
|
|
if !(1..=MAX_PAYLOAD).contains(&length) {
|
|
return Err(HalError::Protocol("invalid response length"));
|
|
}
|
|
let mut body = vec![0_u8; length];
|
|
read_exact_until(&mut self.stream, &mut body, deadline)?;
|
|
if body[0] != 0 {
|
|
if !matches!(body[0], 1..=3) || body.len() != 1 {
|
|
return Err(HalError::Protocol("invalid error response"));
|
|
}
|
|
return Err(HalError::Device(body[0]));
|
|
}
|
|
Ok(body[1..].to_vec())
|
|
}
|
|
|
|
fn empty_reply(&mut self, opcode: u8, payload: &[u8]) -> Result<(), HalError> {
|
|
if !self.exchange(opcode, payload)?.is_empty() {
|
|
self.poison();
|
|
return Err(HalError::Protocol("unexpected response data"));
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn timeout_error() -> io::Error {
|
|
io::Error::new(io::ErrorKind::TimedOut, "HAL operation timed out")
|
|
}
|
|
|
|
fn remaining(deadline: Instant) -> io::Result<Duration> {
|
|
deadline
|
|
.checked_duration_since(Instant::now())
|
|
.filter(|duration| !duration.is_zero())
|
|
.ok_or_else(timeout_error)
|
|
}
|
|
|
|
fn write_all_until(stream: &mut UnixStream, mut data: &[u8], deadline: Instant) -> io::Result<()> {
|
|
while !data.is_empty() {
|
|
stream.set_write_timeout(Some(remaining(deadline)?))?;
|
|
match stream.write(data) {
|
|
Ok(0) => {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::WriteZero,
|
|
"HAL socket closed",
|
|
))
|
|
}
|
|
Ok(count) => data = &data[count..],
|
|
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
|
Err(error) => return Err(error),
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn read_exact_until(
|
|
stream: &mut UnixStream,
|
|
mut data: &mut [u8],
|
|
deadline: Instant,
|
|
) -> io::Result<()> {
|
|
while !data.is_empty() {
|
|
stream.set_read_timeout(Some(remaining(deadline)?))?;
|
|
match stream.read(data) {
|
|
Ok(0) => {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::UnexpectedEof,
|
|
"HAL socket closed",
|
|
))
|
|
}
|
|
Ok(count) => data = &mut data[count..],
|
|
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
|
Err(error) => return Err(error),
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn connect_until(path: &Path, deadline: Instant) -> io::Result<UnixStream> {
|
|
let bytes = path.as_os_str().as_bytes();
|
|
let max_path =
|
|
std::mem::size_of::<sys::SockaddrUn>() - std::mem::offset_of!(sys::SockaddrUn, sun_path);
|
|
if bytes.is_empty() || bytes.len() >= max_path || bytes.contains(&0) {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::InvalidInput,
|
|
"invalid HAL socket path",
|
|
));
|
|
}
|
|
let raw = unsafe {
|
|
sys::socket(
|
|
sys::AF_UNIX,
|
|
sys::SOCK_STREAM | sys::SOCK_NONBLOCK | sys::SOCK_CLOEXEC,
|
|
0,
|
|
)
|
|
};
|
|
if raw < 0 {
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
let fd = unsafe { OwnedFd::from_raw_fd(raw) };
|
|
let mut address: sys::SockaddrUn = unsafe { std::mem::zeroed() };
|
|
address.sun_family = sys::AF_UNIX as sys::SaFamily;
|
|
for (destination, source) in address.sun_path.iter_mut().zip(bytes) {
|
|
*destination = *source as sys::CChar;
|
|
}
|
|
let length =
|
|
(std::mem::offset_of!(sys::SockaddrUn, sun_path) + bytes.len() + 1) as sys::SocklenT;
|
|
loop {
|
|
let result = unsafe {
|
|
sys::connect(
|
|
fd.as_raw_fd(),
|
|
&address as *const _ as *const sys::CVoid,
|
|
length,
|
|
)
|
|
};
|
|
if result == 0 {
|
|
break;
|
|
}
|
|
let error = io::Error::last_os_error();
|
|
if error.raw_os_error() == Some(sys::EISCONN) {
|
|
break;
|
|
}
|
|
if !matches!(
|
|
error.raw_os_error(),
|
|
Some(sys::EINPROGRESS) | Some(sys::EAGAIN)
|
|
) {
|
|
return Err(error);
|
|
}
|
|
let mut poll_fd = sys::PollFd {
|
|
fd: fd.as_raw_fd(),
|
|
events: sys::POLLOUT,
|
|
revents: 0,
|
|
};
|
|
let wait = remaining(deadline)?.as_millis().min(i32::MAX as u128) as i32;
|
|
let polled = unsafe { sys::poll(&mut poll_fd, 1, wait.max(1)) };
|
|
if polled < 0 {
|
|
let error = io::Error::last_os_error();
|
|
if error.kind() == io::ErrorKind::Interrupted {
|
|
continue;
|
|
}
|
|
return Err(error);
|
|
}
|
|
if polled == 0 {
|
|
return Err(timeout_error());
|
|
}
|
|
let mut socket_error: sys::CInt = 0;
|
|
let mut socket_error_len = std::mem::size_of_val(&socket_error) as sys::SocklenT;
|
|
if unsafe {
|
|
sys::getsockopt(
|
|
fd.as_raw_fd(),
|
|
sys::SOL_SOCKET,
|
|
sys::SO_ERROR,
|
|
&mut socket_error as *mut _ as *mut sys::CVoid,
|
|
&mut socket_error_len,
|
|
)
|
|
} < 0
|
|
{
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
if socket_error != 0 {
|
|
return Err(io::Error::from_raw_os_error(socket_error));
|
|
}
|
|
if error.raw_os_error() == Some(sys::EINPROGRESS) {
|
|
break;
|
|
}
|
|
}
|
|
let stream = UnixStream::from(fd);
|
|
stream.set_nonblocking(false)?;
|
|
Ok(stream)
|
|
}
|
|
|
|
impl HardwareBackend for HalClient {
|
|
type Error = HalError;
|
|
|
|
fn send_frame(&mut self, chain: u8, frame: &[u8]) -> Result<(), Self::Error> {
|
|
if frame.len() > MAX_PAYLOAD - 3 {
|
|
return Err(HalError::FrameTooLong);
|
|
}
|
|
let mut body = Vec::with_capacity(frame.len() + 3);
|
|
body.push(chain);
|
|
body.extend_from_slice(&(frame.len() as u16).to_le_bytes());
|
|
body.extend_from_slice(frame);
|
|
self.empty_reply(SEND_FRAME, &body)
|
|
}
|
|
|
|
fn receive_frame(&mut self, chain: u8, frame: &mut [u8]) -> Result<usize, Self::Error> {
|
|
if frame.len() > MAX_PAYLOAD - 3 {
|
|
return Err(HalError::FrameTooLong);
|
|
}
|
|
let mut request = [0_u8; 3];
|
|
request[0] = chain;
|
|
request[1..].copy_from_slice(&(frame.len() as u16).to_le_bytes());
|
|
let body = self.exchange(RECEIVE_FRAME, &request)?;
|
|
if body.len() < 2 {
|
|
self.poison();
|
|
return Err(HalError::Protocol("missing receive length"));
|
|
}
|
|
let count = u16::from_le_bytes([body[0], body[1]]) as usize;
|
|
if count > frame.len() || body.len() != count + 2 {
|
|
self.poison();
|
|
return Err(HalError::Protocol("invalid received frame size"));
|
|
}
|
|
frame[..count].copy_from_slice(&body[2..]);
|
|
Ok(count)
|
|
}
|
|
|
|
fn set_chain_reset(&mut self, chain: u8, asserted: bool) -> Result<(), Self::Error> {
|
|
self.empty_reply(SET_CHAIN_RESET, &[chain, u8::from(asserted)])
|
|
}
|
|
|
|
fn set_fan_target(&mut self, fan: u8, percent: u8) -> Result<(), Self::Error> {
|
|
if percent > 100 {
|
|
return Err(HalError::InvalidFanPercent);
|
|
}
|
|
self.empty_reply(SET_FAN_TARGET, &[fan, percent])
|
|
}
|
|
|
|
fn read_temperature_mc(&mut self, sensor: u8) -> Result<i32, Self::Error> {
|
|
let body = self.exchange(READ_TEMPERATURE, &[sensor])?;
|
|
let bytes: [u8; 4] = match body.try_into() {
|
|
Ok(bytes) => bytes,
|
|
Err(_) => {
|
|
self.poison();
|
|
return Err(HalError::Protocol("invalid temperature response"));
|
|
}
|
|
};
|
|
Ok(i32::from_le_bytes(bytes))
|
|
}
|
|
|
|
fn set_psu_enabled(&mut self, enabled: bool) -> Result<(), Self::Error> {
|
|
let result = self.empty_reply(SET_PSU_ENABLED, &[u8::from(enabled)]);
|
|
if !enabled && result.is_err() {
|
|
self.poison();
|
|
}
|
|
result
|
|
}
|
|
}
|