use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::time::Duration;
use serde_json::{json, Value};
use crate::{
io_err, io_or_timeout, Addr, ConnectOpts, Device, DeviceInfo, Error, Link, RegBind, Reply,
Stream, TransportKind,
};
use std::io;
const RPC_TIMEOUT: Duration = Duration::from_secs(30);
const WO_SLOT_RUNNING: u8 = 0x34;
const WI_HOST_RESET: u8 = 0x00;
pub(crate) struct Sim {
sock: TcpStream,
}
impl Sim {
pub(crate) fn connect(addr: SocketAddr, timeout: Duration) -> Result<Sim, Error> {
let sock = TcpStream::connect_timeout(&addr, timeout).map_err(Error::Io)?;
sock.set_nodelay(true).map_err(Error::Io)?;
sock.set_read_timeout(Some(RPC_TIMEOUT))
.map_err(Error::Io)?;
sock.set_write_timeout(Some(RPC_TIMEOUT))
.map_err(Error::Io)?;
Ok(Sim { sock })
}
fn rpc(&mut self, req: &Value) -> Result<Vec<u8>, Error> {
let body = serde_json::to_vec(req)
.map_err(|e| io_err(io::ErrorKind::InvalidData, e.to_string()))?;
let len = u32::try_from(body.len()).map_err(|_| {
io_err(
io::ErrorKind::InvalidData,
"request longer than the framing",
)
})?;
self.sock
.write_all(&len.to_be_bytes())
.map_err(io_or_timeout)?;
self.sock.write_all(&body).map_err(io_or_timeout)?;
self.sock.flush().map_err(io_or_timeout)?;
let mut hdr = [0u8; 4];
self.sock.read_exact(&mut hdr).map_err(io_or_timeout)?;
let mut rsp = vec![0u8; u32::from_be_bytes(hdr) as usize];
self.sock.read_exact(&mut rsp).map_err(io_or_timeout)?;
Ok(rsp)
}
fn json(&mut self, req: &Value) -> Result<Value, Error> {
let rsp = self.rpc(req)?;
let v: Value = serde_json::from_slice(&rsp).map_err(|e| {
io_err(
io::ErrorKind::InvalidData,
format!("undecodable reply to {}: {e}", req["op"]),
)
})?;
if let Some(t) = v.get("err").and_then(Value::as_str) {
return Err(io_err(
io::ErrorKind::InvalidData,
format!("simulator refused {}: {t}", req["op"]),
));
}
Ok(v)
}
pub(crate) fn identity(&self) -> Value {
json!({"serial": "KDISIM01", "transport": "sim"})
}
pub(crate) fn reg_read(&mut self, r: RegBind) -> Result<u32, Error> {
if r.kind != "wireout" {
return Err(io_err(
io::ErrorKind::InvalidInput,
format!("{} endpoints are not readable", r.kind),
));
}
let v = self.wireout(r.addr)?;
Ok((v & r.mask()) >> r.lo)
}
fn wireout(&mut self, addr: u8) -> Result<u32, Error> {
let v = self.json(&json!({"op": "wireout_read", "addr": addr}))?;
v.get("value")
.and_then(Value::as_u64)
.map(|x| x as u32)
.ok_or_else(|| {
io_err(
io::ErrorKind::InvalidData,
format!("wireout_read 0x{addr:02x}: reply carries no integer `value`"),
)
})
}
pub(crate) fn reg_write(&mut self, r: RegBind, word: u32) -> Result<(), Error> {
match r.kind {
"wirein" => {
self.json(&json!({
"op": "wirein_write", "addr": r.addr, "value": word, "mask": u32::MAX,
}))?;
Ok(())
}
"triggerin" => {
self.json(&json!({"op": "trigger", "addr": r.addr, "bit": r.lo}))?;
Ok(())
}
k => Err(io_err(
io::ErrorKind::InvalidInput,
format!("{k} endpoints are not writable"),
)),
}
}
pub(crate) fn stream_read(&mut self, s: Stream, _buf: &mut [u8]) -> Result<usize, Error> {
Err(io_err(
io::ErrorKind::Unsupported,
format!(
"the sim harness stubs DDR3 and emits no frames: stream `{}` cannot be read here \
(rhd.DdrPipeFifoSim covers that path)",
s.token()
),
))
}
pub(crate) fn message(
&mut self,
_id: &str,
name: &str,
_args: &[(&str, crate::Arg<'_>)],
_token: &str,
) -> Result<Reply, Error> {
Err(io_err(
io::ErrorKind::Unsupported,
format!("the sim harness runs no firmware: `{name}` has no channel to reach"),
))
}
}
impl Device {
#[cfg_attr(docsrs, doc(cfg(feature = "sim")))]
pub fn connect_sim(addr: SocketAddr, timeout: Duration) -> Result<Device, Error> {
let link = Sim::connect(addr, timeout)?;
let info = DeviceInfo {
serial: "KDISIM01".to_string(),
vendor: String::new(),
compatible: String::new(),
board_id: None,
kdi: None,
transport: TransportKind::Sim,
addr: Addr::Socket(addr),
};
Device::bind(
Link::Sim(link),
info,
&ConnectOpts {
need_caps: Vec::new(),
ready_timeout: timeout,
},
)
}
#[cfg_attr(docsrs, doc(cfg(feature = "sim")))]
pub fn sim_engine_running(&mut self) -> Result<bool, Error> {
match &mut self.link {
Link::Sim(s) => Ok(s.wireout(WO_SLOT_RUNNING)? != 0),
_ => Err(io_err(
io::ErrorKind::Unsupported,
"sim_engine_running is only meaningful against the Verilator harness",
)),
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "sim")))]
pub fn sim_host_reset(&mut self) -> Result<(), Error> {
let Link::Sim(s) = &mut self.link else {
return Err(io_err(
io::ErrorKind::Unsupported,
"sim_host_reset is only meaningful against the Verilator harness",
));
};
s.json(
&json!({"op": "wirein_write", "addr": WI_HOST_RESET, "value": 1, "mask": u32::MAX}),
)?;
std::thread::sleep(Duration::from_millis(100));
let Link::Sim(s) = &mut self.link else {
unreachable!("the link cannot change kind mid-call")
};
s.json(
&json!({"op": "wirein_write", "addr": WI_HOST_RESET, "value": 0, "mask": u32::MAX}),
)?;
Ok(())
}
}