Skip to main content

culvert_async/client/
ced.rs

1use hdmi_hal_async::scdc::ScdcTransport;
2
3use crate::ScdcError;
4use crate::{CedReading, HdmiLanes, RsCorrectionCount};
5use culvert::codec;
6
7use super::Scdc;
8
9impl<T: ScdcTransport> Scdc<T> {
10    /// Reads the per-lane character error counts: the `ERR_DET` block, 0x50–0x58 (lanes
11    /// 0–2, the checksum at 0x56, lane 3), in one [`read_block`](ScdcTransport::read_block),
12    /// and checks the checksum.
13    ///
14    /// `lanes` is the link's: [`HdmiLanes::Three`] for TMDS and 3-lane FRL, `Four` for 4-lane
15    /// FRL (`rate.lanes()`). It decides what the checksum covers and whether lane 3 is read
16    /// as a count.
17    ///
18    /// `Err` only for a transport failure. What the read finds wrong is a
19    /// [`CedWarning`](crate::CedWarning) in the [`CedReading`], with the counters decoded
20    /// either way: a checksum mismatch (most likely a read torn by a counter update), or a
21    /// count for lane 3 when it is not in use. culvert-async does not read again; whether
22    /// to is the caller's decision, and a sink that clears the counters on read returns
23    /// different counts the second time.
24    ///
25    /// One transaction keeps the transport from splitting the block; whether the sink holds
26    /// its registers still during it is up to the sink, and a transport that reads a
27    /// register at a time ([`read_block_bytewise`]), or a bus driver that does, splits it
28    /// anyway. The checksum is the one protection against a torn read that holds on every
29    /// transport and adapter: it catches most torn reads, not all. [`CedReading`] says how
30    /// the counts behave (saturation, clear on read, resets).
31    ///
32    /// `UpdateFlags::ced_update` is set by the sink and kept until the source clears it,
33    /// but it is a hint at most: it has been seen set with every count zero, and a sink may
34    /// never set it. Read the counters regularly rather than only after the flag, and clear
35    /// the flag before reading them
36    /// ([`clear_update_flags`](Self::clear_update_flags) says why).
37    ///
38    /// [`read_block_bytewise`]: hdmi_hal_async::scdc::read_block_bytewise
39    pub async fn read_ced(&mut self, lanes: HdmiLanes) -> Result<CedReading, ScdcError<T::Error>> {
40        let mut block = [0; codec::CED_BLOCK_LEN];
41        self.transport
42            .read_block(codec::CED_BLOCK_START, &mut block)
43            .await
44            .map_err(ScdcError::Transport)?;
45        Ok(codec::decode_ced_block(&block, lanes))
46    }
47
48    /// Reads the Reed-Solomon correction count from `RS_Correction_L/H` (0x59/0x5A).
49    ///
50    /// Returns `None` if the high byte's validity bit (bit 7) is not set: unknown, not
51    /// zero. The count is maintained by the sink in FRL mode.
52    ///
53    /// Both bytes are one [`read_block`](ScdcTransport::read_block): one transaction, so
54    /// the transport does not split them; whether the sink holds them still during it is
55    /// up to the sink, and a transport that reads a register at a time
56    /// ([`read_block_bytewise`]), or a bus driver that does, splits them anyway. The count
57    /// has no checksum, so a torn read cannot be detected: unlike the CED counters, nothing
58    /// protects it on every adapter.
59    ///
60    /// The count accumulates and saturates at 0x7FFF, so a saturated count means "at
61    /// least". A sink may clear it when it is read, so a reading is a running total on
62    /// some sinks and the count since the previous read on others; a reading lower than
63    /// the previous one means a reset (clear on read, hot plug, an SCDC clear), and
64    /// counting starts again from it. Count afresh after retraining, a rate change or a
65    /// hot plug too.
66    ///
67    /// `UpdateFlags::rsed_update` is set by the sink and kept until the source clears it,
68    /// a hint at most, as `ced_update` is; a sink may never set it. Read the count regularly
69    /// rather than only after the flag.
70    ///
71    /// [`read_block_bytewise`]: hdmi_hal_async::scdc::read_block_bytewise
72    pub async fn read_rs_correction(
73        &mut self,
74    ) -> Result<Option<RsCorrectionCount>, ScdcError<T::Error>> {
75        let mut bytes = [0; 2];
76        self.transport
77            .read_block(codec::RS_CORRECTION_L, &mut bytes)
78            .await
79            .map_err(ScdcError::Transport)?;
80        let [low, high] = bytes;
81        Ok(codec::decode_rs_correction(low, high))
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use super::super::Scdc;
88    use super::super::test_transport::{Op, TestTransport};
89    use crate::ScdcError;
90    use crate::{CedCount, CedCounters, CedWarning, FrlRate, HdmiLanes};
91
92    /// A transport whose CED block holds `block`, with the checksum at 0x56 made valid for
93    /// `lanes`.
94    fn with_block(mut block: [u8; 9], lanes: HdmiLanes) -> TestTransport {
95        let covered = match lanes {
96            HdmiLanes::Three => 7,
97            HdmiLanes::Four => 9,
98        };
99        block[6] = 0;
100        let sum = block[..covered]
101            .iter()
102            .fold(0u8, |sum, &b| sum.wrapping_add(b));
103        block[6] = sum.wrapping_neg();
104        let mut sim = TestTransport::new();
105        for (reg, byte) in (0x50..).zip(block) {
106            sim.set(reg, byte);
107        }
108        sim
109    }
110
111    #[pollster::test]
112    async fn read_ced_is_one_block_read_of_0x50_to_0x58() {
113        for lanes in [HdmiLanes::Three, HdmiLanes::Four] {
114            let mut scdc = Scdc::new(TestTransport::new());
115            scdc.read_ced(lanes).await.unwrap();
116            assert_eq!(
117                scdc.into_transport().log()[..2],
118                [Some(Op::ReadBlock(0x50, 9)), None]
119            );
120        }
121    }
122
123    #[pollster::test]
124    async fn ced_validity_bit_required() {
125        // High byte with bit 7 clear → None regardless of counter value.
126        let sim = with_block([0xFF, 0x7F, 0, 0, 0, 0, 0, 0, 0], HdmiLanes::Three);
127        let reading = Scdc::new(sim).read_ced(HdmiLanes::Three).await.unwrap();
128        assert_eq!(reading.counters.lane0, None);
129        assert_eq!(reading.warnings(), []);
130    }
131
132    #[pollster::test]
133    async fn ced_counter_validity_bit_stripped() {
134        // High byte: bit 7 set (valid), counter bits = 0x01; low byte = 0x23.
135        let sim = with_block([0x23, 0x81, 0, 0, 0, 0, 0, 0, 0], HdmiLanes::Three);
136        let reading = Scdc::new(sim).read_ced(HdmiLanes::Three).await.unwrap();
137        assert_eq!(reading.counters.lane0, Some(CedCount::new(0x0123)));
138    }
139
140    #[pollster::test]
141    async fn ced_each_lane_from_its_own_registers() {
142        // A distinct, asymmetric low/high pair per lane, so a swapped byte or lane shows.
143        let block = [0x02, 0x83, 0x04, 0x85, 0x06, 0x87, 0, 0x08, 0x89];
144        let reading = Scdc::new(with_block(block, HdmiLanes::Four))
145            .read_ced(HdmiLanes::Four)
146            .await
147            .unwrap();
148        assert_eq!(
149            reading.counters,
150            CedCounters::new(
151                Some(CedCount::new(0x0302)),
152                Some(CedCount::new(0x0504)),
153                Some(CedCount::new(0x0706)),
154                Some(CedCount::new(0x0908)),
155            )
156        );
157        assert_eq!(reading.warnings(), []);
158    }
159
160    #[pollster::test]
161    async fn ced_lane3_is_not_a_count_in_3_lane_mode() {
162        // The checksum at 0x56 is not lane 3; lane 3 is reported, but not in use.
163        let block = [0, 0, 0, 0, 0, 0, 0, 0x01, 0x80];
164        let reading = Scdc::new(with_block(block, HdmiLanes::Three))
165            .read_ced(HdmiLanes::Three)
166            .await
167            .unwrap();
168        assert_eq!(reading.counters.lane3, None);
169        // The variants are `#[non_exhaustive]`: outside culvert they are matched, as a
170        // caller does, not built.
171        assert!(matches!(
172            reading.warnings(),
173            [CedWarning::UnusedLaneReported { count, .. }] if *count == CedCount::new(1)
174        ));
175    }
176
177    #[pollster::test]
178    async fn ced_checksum_mismatch_is_a_warning_with_the_counts() {
179        let mut sim = with_block([0x34, 0x81, 0, 0, 0, 0, 0, 0, 0], HdmiLanes::Three);
180        let checksum = sim.get(0x56);
181        sim.set(0x56, checksum ^ 0x01);
182        let reading = Scdc::new(sim).read_ced(HdmiLanes::Three).await.unwrap();
183        assert_eq!(reading.counters.lane0, Some(CedCount::new(0x0134)));
184        assert!(matches!(
185            reading.warnings(),
186            [CedWarning::ChecksumMismatch { expected, found, .. }]
187                if *expected == checksum && *found == checksum ^ 0x01
188        ));
189    }
190
191    #[pollster::test]
192    async fn ced_lanes_from_the_link_rate() {
193        let block = [0, 0, 0, 0, 0, 0, 0, 0x08, 0x89];
194        let reading = Scdc::new(with_block(block, HdmiLanes::Four))
195            .read_ced(FrlRate::Rate12Gbps4Lanes.lanes())
196            .await
197            .unwrap();
198        assert_eq!(reading.counters.lane3, Some(CedCount::new(0x0908)));
199        assert_eq!(reading.warnings(), []);
200    }
201
202    #[pollster::test]
203    async fn ced_transport_error() {
204        // The block is one read.
205        assert!(
206            Scdc::new(TestTransport::failing_after(0))
207                .read_ced(HdmiLanes::Three)
208                .await
209                .is_err_and(|error| matches!(error, ScdcError::Transport(())))
210        );
211        assert!(
212            Scdc::new(TestTransport::failing_after(1))
213                .read_ced(HdmiLanes::Three)
214                .await
215                .is_ok()
216        );
217    }
218
219    #[pollster::test]
220    async fn read_rs_correction_reads_low_and_high_in_one_block() {
221        let mut scdc = Scdc::new(TestTransport::new());
222        scdc.read_rs_correction().await.unwrap();
223        assert_eq!(
224            scdc.into_transport().log()[..2],
225            [Some(Op::ReadBlock(0x59, 2)), None]
226        );
227    }
228
229    #[pollster::test]
230    async fn rs_correction_valid_and_invalid() {
231        let mut sim = TestTransport::new();
232        sim.set(0x59, 0x34);
233        sim.set(0x5A, 0x81); // valid, upper counter bits = 0x01
234        assert_eq!(
235            Scdc::new(sim)
236                .read_rs_correction()
237                .await
238                .unwrap()
239                .map(|c| c.value()),
240            Some(0x0134)
241        );
242
243        let mut sim = TestTransport::new();
244        sim.set(0x59, 0xFF);
245        sim.set(0x5A, 0x7F); // validity bit clear
246        assert_eq!(Scdc::new(sim).read_rs_correction().await.unwrap(), None);
247    }
248
249    #[pollster::test]
250    async fn rs_correction_transport_error() {
251        // The count is one block read.
252        assert!(
253            Scdc::new(TestTransport::failing_after(0))
254                .read_rs_correction()
255                .await
256                .is_err_and(|error| matches!(error, ScdcError::Transport(())))
257        );
258        assert!(
259            Scdc::new(TestTransport::failing_after(1))
260                .read_rs_correction()
261                .await
262                .is_ok()
263        );
264    }
265}