use core::fmt;
use core::time::Duration;
use hdmi_hal::ddc::{
DdcBus, DdcCapabilities, DdcError, DdcErrorKind, DdcHandle, EddcTarget, MAX_SEGMENT,
SEGMENT_POINTER, is_usable_address,
};
use crate::bench::{Core, Reach};
use crate::fault::{Effect, Point, Strike};
use crate::target::Operation;
use crate::transcript::{BusOp, BusRecord};
pub(crate) const FAILED_READ_FILL: u8 = 0xA5;
#[derive(Clone, Copy)]
pub struct Ddc<'b> {
core: &'b (dyn Core + Sync + 'b),
}
impl<'b> Ddc<'b> {
pub(crate) fn new(core: &'b (dyn Core + Sync + 'b)) -> Self {
Self { core }
}
fn refuse(&self, record: BusRecord) -> Result<(), BusError> {
let record = BusRecord {
result: Err(DdcErrorKind::Unsupported),
..record
};
self.core.record(record);
Err(BusError::from_record(&record, DdcErrorKind::Unsupported))
}
fn run(&self, record: BusRecord, ops: &mut [Operation<'_>]) -> Result<(), BusError> {
let mut result = None;
self.core
.serialized(&mut || result = Some(self.run_serialized(record, ops)));
result.expect("the step ran")
}
fn run_serialized(&self, record: BusRecord, ops: &mut [Operation<'_>]) -> Result<(), BusError> {
let strike = self.core.strike(&record);
self.core.run_actions(true);
let data: usize = ops.iter().map(Operation::len).sum();
let (result, wire_bytes) = match strike {
Some(
strike @ Strike {
effect: Effect::Fail(kind),
point: Point::Before,
..
},
) => {
self.core.struck_before(record, strike, kind);
(Err(kind), Some(1))
}
Some(
strike @ Strike {
effect: Effect::Fail(_),
point: Point::Partway { byte },
..
},
) if usize::from(byte) < data => {
let byte = match strike.effect {
Effect::Fail(DdcErrorKind::NoAcknowledge(_)) => {
read_start(ops, usize::from(byte))
}
_ => usize::from(byte),
};
let (mut cut, n) = cut(ops, byte);
let (result, reach) = self.core.transaction(record, &mut cut[..n], Some(strike));
(result, wire(reach, &cut[..n]))
}
_ => {
let (result, reach) = self.core.transaction(record, ops, strike);
(result, wire(reach, ops))
}
};
if let (
Ok(()),
Some(Strike {
effect: Effect::Corrupt { byte, xor },
..
}),
) = (result, strike)
{
corrupt(ops, usize::from(byte), xor);
}
self.core.run_actions(false);
if let Some(bytes) = wire_bytes {
let timing = self.core.timing();
let bytes = u32::try_from(bytes).unwrap_or(u32::MAX);
let extra = match strike.map(|strike| strike.effect) {
Some(Effect::Slow(longer)) => longer,
Some(Effect::Fail(DdcErrorKind::Timeout)) => self
.capabilities()
.stretch_timeout_us()
.map_or(Duration::ZERO, |us| Duration::from_micros(u64::from(us))),
_ => Duration::ZERO,
};
self.core.clock().advance(
timing
.per_transaction
.saturating_add(timing.per_byte.saturating_mul(bytes))
.saturating_add(extra),
);
}
result.map_err(|kind| {
for op in ops.iter_mut() {
if let Operation::Read { buf, .. } = op {
buf.fill(FAILED_READ_FILL);
}
}
BusError::from_record(&record, kind)
})
}
}
fn read_start(ops: &[Operation<'_>], byte: usize) -> usize {
let mut before = 0;
for op in ops {
let len = op.len();
if byte < before + len {
return match op {
Operation::Read { .. } => before,
Operation::Write { .. } => byte,
};
}
before += len;
}
byte
}
fn corrupt(ops: &mut [Operation<'_>], byte: usize, xor: u8) {
let mut left = byte;
for op in ops.iter_mut() {
if let Operation::Read { buf, .. } = op {
if let Some(target) = buf.get_mut(left) {
*target ^= xor;
return;
}
left -= buf.len();
}
}
}
fn wire(reach: Reach, ops: &[Operation<'_>]) -> Option<usize> {
match reach {
Reach::Answered => Some(ops.iter().map(|op| op.len().saturating_add(1)).sum()),
Reach::Unanswered => Some(1),
Reach::Detached => None,
}
}
fn cut<'s>(ops: &'s mut [Operation<'_>], byte: usize) -> ([Operation<'s>; 3], usize) {
let mut cut = [
Operation::Write {
addr: 0,
bytes: &[],
},
Operation::Write {
addr: 0,
bytes: &[],
},
Operation::Write {
addr: 0,
bytes: &[],
},
];
let mut left = byte;
let mut n = 0;
for op in ops.iter_mut() {
if n == cut.len() {
break;
}
let take = op.len().min(left);
cut[n] = match op {
Operation::Write { addr, bytes } => Operation::Write {
addr: *addr,
bytes: &bytes[..take],
},
Operation::Read { addr, buf } => Operation::Read {
addr: *addr,
buf: &mut buf[..take],
},
};
n += 1;
left -= take;
if left == 0 {
break;
}
}
(cut, n)
}
impl fmt::Debug for Ddc<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Ddc")
.field("capabilities", &self.core.capabilities())
.finish_non_exhaustive()
}
}
fn saturating_len(len: usize) -> u16 {
u16::try_from(len).unwrap_or(u16::MAX)
}
impl DdcHandle for Ddc<'_> {
type Bus = Self;
fn bus(&self) -> &Self {
self
}
}
impl DdcBus for Ddc<'_> {
type Error = BusError;
fn capabilities(&self) -> DdcCapabilities {
self.core.capabilities()
}
fn write(&self, addr: u8, bytes: &[u8]) -> Result<(), BusError> {
self.core.spend();
let record = BusRecord {
op: BusOp::Write,
addr,
first: bytes.first().copied(),
written: saturating_len(bytes.len()),
read: 0,
result: Ok(()),
};
let caps = self.capabilities();
if !is_usable_address(addr)
|| bytes.is_empty()
|| !caps.reaches(addr)
|| bytes.len() > usize::from(caps.write_max())
{
return self.refuse(record);
}
self.run(record, &mut [Operation::Write { addr, bytes }])
}
fn write_read(&self, addr: u8, bytes: &[u8], buf: &mut [u8]) -> Result<(), BusError> {
if bytes.is_empty() {
return self.read(addr, buf);
}
self.core.spend();
let record = BusRecord {
op: BusOp::WriteRead,
addr,
first: bytes.first().copied(),
written: saturating_len(bytes.len()),
read: saturating_len(buf.len()),
result: Ok(()),
};
if !is_usable_address(addr) {
return self.refuse(record);
}
if buf.is_empty() {
self.core.record(record);
return Ok(());
}
let caps = self.capabilities();
let (write_max, read_max) = caps.write_read_max();
if !caps.reaches(addr)
|| bytes.len() > usize::from(write_max)
|| buf.len() > usize::from(read_max)
{
return self.refuse(record);
}
self.run(
record,
&mut [
Operation::Write { addr, bytes },
Operation::Read { addr, buf },
],
)
}
fn read(&self, addr: u8, buf: &mut [u8]) -> Result<(), BusError> {
self.core.spend();
let record = BusRecord {
op: BusOp::Read,
addr,
first: None,
written: 0,
read: saturating_len(buf.len()),
result: Ok(()),
};
if !is_usable_address(addr) {
return self.refuse(record);
}
if buf.is_empty() {
self.core.record(record);
return Ok(());
}
let caps = self.capabilities();
if !caps.reaches(addr) || buf.len() > usize::from(caps.read_max()) {
return self.refuse(record);
}
self.run(record, &mut [Operation::Read { addr, buf }])
}
fn read_segmented(
&self,
target: EddcTarget,
segment: u8,
offset: u8,
buf: &mut [u8],
) -> Result<(), BusError> {
self.core.spend();
let addr = target.address();
let pointer = u16::from(segment > 0);
let record = BusRecord {
op: BusOp::ReadSegmented { target, segment },
addr,
first: Some(offset),
written: pointer + 1,
read: saturating_len(buf.len()),
result: Ok(()),
};
if buf.is_empty() {
self.core.record(record);
return Ok(());
}
let caps = self.capabilities();
if segment > MAX_SEGMENT
|| usize::from(offset) + buf.len() > 256
|| !caps.reads_target(target)
|| caps.max_segment().is_none_or(|max| segment > max)
{
return self.refuse(record);
}
let piece = match caps.segmented_piece() {
Some(piece) if piece > 0 => usize::from(piece),
_ => buf.len(),
};
let mut start = 0;
while start < buf.len() {
let end = buf.len().min(start + piece);
let piece_offset = offset.wrapping_add(start as u8);
let record = BusRecord {
first: Some(piece_offset),
read: saturating_len(end - start),
..record
};
let chunk = &mut buf[start..end];
let offset_byte = [piece_offset];
let segment_byte = [segment];
let result = if segment > 0 {
self.run(
record,
&mut [
Operation::Write {
addr: SEGMENT_POINTER,
bytes: &segment_byte,
},
Operation::Write {
addr,
bytes: &offset_byte,
},
Operation::Read { addr, buf: chunk },
],
)
} else {
self.run(
record,
&mut [
Operation::Write {
addr,
bytes: &offset_byte,
},
Operation::Read { addr, buf: chunk },
],
)
};
if let Err(error) = result {
buf.fill(FAILED_READ_FILL);
return Err(error);
}
start = end;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BusError {
pub kind: DdcErrorKind,
pub op: BusOp,
pub addr: u8,
}
impl BusError {
fn from_record(record: &BusRecord, kind: DdcErrorKind) -> Self {
Self {
kind,
op: record.op,
addr: record.addr,
}
}
}
impl DdcError for BusError {
fn kind(&self) -> DdcErrorKind {
self.kind
}
}
impl fmt::Display for BusError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} at {:#04x} failed: ", self.op, self.addr)?;
crate::transcript::describe_ddc(self.kind, f)
}
}
impl core::error::Error for BusError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BusTiming {
pub per_byte: Duration,
pub per_transaction: Duration,
}
impl BusTiming {
pub const STANDARD_MODE: Self = Self {
per_byte: Duration::from_micros(90),
per_transaction: Duration::ZERO,
};
#[must_use]
pub const fn with_per_byte(self, per_byte: Duration) -> Self {
Self { per_byte, ..self }
}
#[must_use]
pub const fn with_per_transaction(self, per_transaction: Duration) -> Self {
Self {
per_transaction,
..self
}
}
}
impl Default for BusTiming {
fn default() -> Self {
Self::STANDARD_MODE
}
}
#[cfg(test)]
mod tests {
extern crate std;
use std::string::ToString;
use hdmi_hal::ddc::{DdcErrorKind, EddcTarget, NoAcknowledgeSource};
use super::BusError;
use crate::transcript::BusOp;
fn error(op: BusOp, addr: u8, kind: DdcErrorKind) -> std::string::String {
BusError { kind, op, addr }.to_string()
}
#[test]
fn bus_errors_print_as_sentences() {
use DdcErrorKind as K;
let segmented = |target, segment| BusOp::ReadSegmented { target, segment };
let cases = [
(
BusOp::Write,
K::NoAcknowledge(NoAcknowledgeSource::Address),
"write at 0x50 failed: the address was not acknowledged",
),
(
BusOp::WriteRead,
K::NoAcknowledge(NoAcknowledgeSource::Data),
"write_read at 0x50 failed: a data byte was not acknowledged",
),
(
BusOp::Read,
K::NoAcknowledge(NoAcknowledgeSource::Unknown),
"read at 0x50 failed: a byte was not acknowledged",
),
(
segmented(EddcTarget::Edid, 1),
K::Timeout,
"read_segmented of the EDID, segment 1 at 0x50 failed: it timed out",
),
(
segmented(EddcTarget::DisplayId, 0),
K::Busy,
"read_segmented of the DisplayID, segment 0 at 0x50 failed: the bus was busy",
),
(
BusOp::Read,
K::Unsupported,
"read at 0x50 failed: unsupported",
),
(
BusOp::Read,
K::Detached,
"read at 0x50 failed: the adapter is detached",
),
(BusOp::Read, K::Other, "read at 0x50 failed: it failed"),
];
for (op, kind, text) in cases {
assert_eq!(error(op, 0x50, kind), text);
}
}
}