maquette 0.1.0

A simulated HDMI sink for tests: SCDC and EDID registers, a DDC bus, a PHY and a clock under deterministic time, with faults and conformance checks for hdmi-hal's traits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! The bench's DDC bus: `DdcBus` over the sink's targets.

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};

/// What a failed read leaves in its buffer: `DdcBus` leaves the contents unspecified, so a
/// caller that uses them after an error reads this pattern, not plausible data.
pub(crate) const FAILED_READ_FILL: u8 = 0xA5;

/// The bench's DDC bus, a `Copy` handle borrowed from the bench ([`Bench::ddc`]).
///
/// It implements `DdcBus` over the sink's targets, with the capabilities given to the bench
/// (by default `DdcCapabilities::general()`):
///
/// - **Before the sink:** `DdcBus`'s argument rules (an address outside
///   `is_usable_address`, an empty `write`, a segment above `MAX_SEGMENT` or a read past 256
///   bytes of a segment: `Unsupported`; an empty buffer: `Ok`), then the capabilities. A
///   refused call touches no target, takes no time and is recorded with its result.
/// - **Each call is one transaction**, routed to a target; `read_segmented` is split into
///   pieces of `segmented_piece` bytes where the capabilities set one, each piece its own
///   transaction with the pointer and offset written again. Segment 0 writes no pointer.
/// - **Time:** each transaction charges the bench's clock after it is evaluated, by the
///   bench's [`BusTiming`]: every byte of it, address bytes included, as if it all went out,
///   except a transaction nothing answered, which charges its first address byte.
/// - **A failed read** fills its buffer with `0xA5`.
///
/// [`Bench::ddc`]: crate::Bench::ddc
#[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 }
    }

    /// Records a call refused before the sink.
    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))
    }

    /// Runs one transaction, charges it, and returns its result as the call's: one step,
    /// which no other handle's call interleaves with.
    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();
        // The result, and how many bytes went out (`None`: nothing, the adapter is gone).
        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 {
                    // The host acknowledges each byte it reads, so a NACK cannot fall in a
                    // read's data (DDC/CI 1.1 §1.6): it falls on the read's address byte.
                    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)
        })
    }
}

/// Where data byte `byte`, counted across the operations, is cut for a NACK: at the start of
/// its operation's data when it falls in a read, as is.
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
}

/// XORs read byte `byte`, counted across the operations' read data, with `xor`, if the
/// reads reach it.
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();
        }
    }
}

/// How many bytes a transaction put on the wire, address bytes included: all of them when a
/// target answered, the first address byte when none did, none when the adapter is gone.
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,
    }
}

/// The transaction `ops` cut at data byte `byte`, counted across its operations: the
/// operations up to the one that holds it, that one shortened to the bytes before it. A
/// transaction is at most three operations (the pointer, the offset, the read).
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)
}

/// The bench's bus is its own handle: a `Copy` view, passed by value to code that holds a
/// handle to a bus (`hdmi_hal::scdc::ScdcOverDdc::new(bench.ddc())`).
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);
            // `offset + buf.len()` is at most 256, so the piece's offset fits a byte.
            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(())
    }
}

/// A failed call of the bench's DDC bus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BusError {
    /// How it failed.
    pub kind: DdcErrorKind,
    /// The call.
    pub op: BusOp,
    /// The address of the call: for `read_segmented`, the target's.
    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 {}

/// How long the bench's bus operations take on its clock.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BusTiming {
    /// Each byte on the wire, address bytes included.
    pub per_byte: Duration,
    /// Each transaction, on top of its bytes.
    pub per_transaction: Duration,
}

impl BusTiming {
    /// 90 µs a byte, nothing per transaction: a byte is eight data bits and the acknowledge,
    /// nine clocks, at 100 kHz, I²C standard mode's maximum clock. DDC/CI 1.1 assumes
    /// standard mode without precluding faster ones; sources use 100 kHz: i915 as its
    /// conservative default (github.com/torvalds/linux `e9954f3fbddd`,
    /// `drivers/gpu/drm/i915/display/intel_gmbus.c:960–961`), Xilinx for its DDC clock
    /// divider (embeddedsw `97f2baf7f69e`,
    /// `XilinxProcessorIPLib/drivers/v_hdmitx1/src/xv_hdmitx1.c:1580`).
    pub const STANDARD_MODE: Self = Self {
        per_byte: Duration::from_micros(90),
        per_transaction: Duration::ZERO,
    };

    /// The timing with each byte taking `per_byte`.
    #[must_use]
    pub const fn with_per_byte(self, per_byte: Duration) -> Self {
        Self { per_byte, ..self }
    }

    /// The timing with each transaction taking `per_transaction` on top of its bytes.
    #[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);
        }
    }
}