Skip to main content

dvb_ci_runtime/
device.rs

1//! The hardware-abstraction boundary: [`CaDevice`].
2//!
3//! EN 50221 runs over the Linux CA device (`/dev/dvb/adapterN/caM`): the
4//! application reads/writes the TPDU link-layer byte stream and issues a few
5//! ioctls (reset, slot info, capabilities). The runtime is written entirely
6//! against this trait so it can be driven by a real device (the `linux`
7//! feature) *or* by an in-memory mock — which is what makes the state machines
8//! testable without hardware, and enables differential testing against an
9//! external reference (feed both the same mock, compare the emitted
10//! write/ioctl sequences).
11
12use std::io;
13
14/// Largest legal link-layer frame `[slot, connection_id, <TPDU>]` a
15/// [`CaDevice`] can deliver: the 2-byte link header, plus the largest TPDU
16/// EN 50221 Table 1 can encode — `tpdu_tag`(1), `length_field` (up to 3 bytes
17/// total, its maximum-value long form: size indicator plus 2 length bytes),
18/// and the `length_field`'s own max value, 65535, of `t_c_id` plus data (§7
19/// semantics: "length_field codes the length of all following fields", i.e.
20/// t_c_id + data).
21///
22/// A [`Driver`](crate::Driver)'s read buffer is sized to this, so no frame a
23/// device accepts is handed back as an error purely for not fitting it
24/// (audit a20-21).
25pub const MAX_CA_FRAME: usize = 2 + 1 + 3 + 65_535;
26
27/// CA-device slot status (subset of the Linux `ca_slot_info` the runtime needs).
28///
29/// The DVB-CA slot reports two independent bits (uapi `linux/dvb/ca.h`
30/// `ca_slot_info.flags`): `CA_CI_MODULE_PRESENT` (a module is physically
31/// inserted) and `CA_CI_MODULE_READY` (that module has completed its own
32/// init and is usable). A module can be present-but-not-ready briefly after
33/// insertion; the runtime's hot-plug edge detection
34/// ([`Notification::HotPlug`](crate::event::Notification::HotPlug) carrying
35/// [`HotPlug::CamPresent`](crate::event::HotPlug::CamPresent)/
36/// [`CamRemoved`](crate::event::HotPlug::CamRemoved)) keys off
37/// `module_present`, since that is the field that toggles on physical
38/// insert/removal.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40#[non_exhaustive]
41pub struct SlotInfo {
42    /// Slot number.
43    pub num: u8,
44    /// `true` once a module is present and ready (`CA_CI_MODULE_READY`).
45    pub module_ready: bool,
46    /// `true` while a module is physically inserted (`CA_CI_MODULE_PRESENT`),
47    /// regardless of whether it has finished initialising.
48    pub module_present: bool,
49}
50
51/// A failed device operation, with enough context to pinpoint it from a log
52/// line alone: **which operation** (`write`, `read`, `poll`, `ioctl
53/// CA_RESET`, ...), **which device** (the `/dev/dvb/adapterN/...` path, or
54/// the fd role for a `from_file` wrapper) and the **errno**. A bare
55/// `Invalid argument (os error 22)` from `Driver::pump` (seen on a DD CXD2099
56/// during init) names none of those, and the same errno means different
57/// things per operation: the kernel's `dvb_ca_en50221` returns `EINVAL` from
58/// `write` while the slot is not yet `RUNNING`, from `read` when the buffer is
59/// smaller than the pending frame, and from `CA_GET_SLOT_INFO` for a slot it
60/// does not have.
61///
62/// It is carried as the payload of an [`io::Error`] of the *same*
63/// [`io::ErrorKind`] as the original, so `kind()`-based handling is
64/// unchanged; the errno stays reachable through [`errno`](Self::errno) /
65/// [`DeviceOpError::errno_of`] (a wrapped error no longer answers
66/// `raw_os_error()` itself).
67#[derive(Debug, thiserror::Error)]
68#[error("{device}: {op} failed: {source}")]
69pub struct DeviceOpError {
70    /// The operation that failed, e.g. `"write (17 bytes)"`.
71    pub op: String,
72    /// The device, e.g. `"/dev/dvb/adapter3/ca0"`.
73    pub device: String,
74    source: io::Error,
75}
76
77impl DeviceOpError {
78    /// Wrap `source` (an error from `op` on `device`) into an [`io::Error`] of
79    /// the same kind that displays all three.
80    #[must_use]
81    pub fn wrap(op: impl Into<String>, device: &str, source: io::Error) -> io::Error {
82        let kind = source.kind();
83        io::Error::new(
84            kind,
85            DeviceOpError {
86                op: op.into(),
87                device: device.to_owned(),
88                source,
89            },
90        )
91    }
92
93    /// The OS errno of the underlying failure, if it had one.
94    #[must_use]
95    pub fn errno(&self) -> Option<i32> {
96        self.source.raw_os_error()
97    }
98
99    /// The OS errno of `err` whether or not it is wrapped in a
100    /// [`DeviceOpError`] (a plain OS error answers for itself).
101    #[must_use]
102    pub fn errno_of(err: &io::Error) -> Option<i32> {
103        err.raw_os_error().or_else(|| {
104            err.get_ref()
105                .and_then(|inner| inner.downcast_ref::<DeviceOpError>())
106                .and_then(DeviceOpError::errno)
107        })
108    }
109}
110
111/// The link-layer device the EN 50221 runtime drives.
112///
113/// All methods mirror the operations a host performs on the CA file descriptor
114/// per EN 50221. Implementations: [`MockCaDevice`] (in-memory, for tests +
115/// differential harness) and the `linux` `CaDevice` over `/dev/dvb/.../ca`.
116pub trait CaDevice {
117    /// Read one link-layer TPDU frame into `buf`; returns the byte count.
118    /// `Ok(0)` means no data available (non-blocking).
119    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
120
121    /// Write one link-layer TPDU frame.
122    fn write(&mut self, buf: &[u8]) -> io::Result<()>;
123
124    /// Reset the interface / slot (ioctl `CA_RESET`).
125    fn reset(&mut self) -> io::Result<()>;
126
127    /// How long the module needs after [`reset`](Self::reset) returns before
128    /// it accepts `Create_T_C` (the DD/cxd2099 class of drivers only
129    /// re-initialise the slot seconds after `CA_RESET`).
130    ///
131    /// `reset` itself must not sleep for this: the sans-IO
132    /// [`Driver`](crate::Driver) reads this value after `reset` and holds the
133    /// transport quiet until it elapses on its injectable clock, so a CAM
134    /// hot-plug edge no longer freezes `pump` (audit r10-O-10). Defaults to
135    /// [`Duration::ZERO`](std::time::Duration::ZERO) — an implementation whose
136    /// `reset` already blocks until the module is usable keeps working
137    /// unchanged.
138    fn reset_settle(&self) -> std::time::Duration {
139        std::time::Duration::ZERO
140    }
141
142    /// Query slot status (ioctl `CA_GET_SLOT_INFO`).
143    fn slot_info(&mut self) -> io::Result<SlotInfo>;
144
145    /// Wait up to `timeout` for the device to become readable; `Ok(true)` if
146    /// readable. The runtime's poll loop calls this between reads.
147    fn poll(&mut self, timeout: std::time::Duration) -> io::Result<bool>;
148}
149
150/// One recorded device operation, for assertions + differential testing.
151#[derive(Debug, Clone, PartialEq, Eq)]
152#[non_exhaustive]
153pub enum DeviceOp {
154    /// A `write()` of these exact bytes.
155    Write(Vec<u8>),
156    /// A `reset()` ioctl.
157    Reset,
158    /// A `slot_info()` ioctl.
159    SlotInfo,
160}
161
162/// In-memory [`CaDevice`] for tests and the differential harness.
163///
164/// - `inbound` is a scripted queue of frames the "module" (mock CAM) sends up;
165///   each [`read`](CaDevice::read) pops one.
166/// - every host-side operation is appended to `ops` so a test (or a differential
167///   comparison against an external reference) can assert the exact emitted
168///   `write`/ioctl sequence.
169#[derive(Debug, Default)]
170pub struct MockCaDevice {
171    /// Scripted frames the module sends to the host (FIFO).
172    pub inbound: std::collections::VecDeque<Vec<u8>>,
173    /// Recorded host-side operations, in order.
174    pub ops: Vec<DeviceOp>,
175    /// Slot status returned by [`slot_info`](CaDevice::slot_info).
176    pub slot: SlotInfo,
177}
178
179impl MockCaDevice {
180    /// New mock with a ready module in slot 0 and the given inbound script.
181    #[must_use]
182    pub fn new(inbound: impl IntoIterator<Item = Vec<u8>>) -> Self {
183        Self {
184            inbound: inbound.into_iter().collect(),
185            ops: Vec::new(),
186            slot: SlotInfo {
187                num: 0,
188                module_ready: true,
189                module_present: true,
190            },
191        }
192    }
193
194    /// The bytes written by the host so far, concatenated (convenience for
195    /// byte-exact differential comparison against the C reference).
196    #[must_use]
197    pub fn written(&self) -> Vec<u8> {
198        self.ops
199            .iter()
200            .filter_map(|o| match o {
201                DeviceOp::Write(b) => Some(b.clone()),
202                _ => None,
203            })
204            .flatten()
205            .collect()
206    }
207}
208
209impl CaDevice for MockCaDevice {
210    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
211        match self.inbound.pop_front() {
212            Some(frame) => {
213                let n = frame.len().min(buf.len());
214                buf[..n].copy_from_slice(&frame[..n]);
215                Ok(n)
216            }
217            None => Ok(0),
218        }
219    }
220
221    fn write(&mut self, buf: &[u8]) -> io::Result<()> {
222        self.ops.push(DeviceOp::Write(buf.to_vec()));
223        Ok(())
224    }
225
226    fn reset(&mut self) -> io::Result<()> {
227        self.ops.push(DeviceOp::Reset);
228        Ok(())
229    }
230
231    fn slot_info(&mut self) -> io::Result<SlotInfo> {
232        self.ops.push(DeviceOp::SlotInfo);
233        Ok(self.slot)
234    }
235
236    fn poll(&mut self, _timeout: std::time::Duration) -> io::Result<bool> {
237        Ok(!self.inbound.is_empty())
238    }
239}
240
241/// One link-layer event for diagnostics, captured in both directions by
242/// [`RecordingCaDevice`].
243#[derive(Debug, Clone, PartialEq, Eq)]
244#[non_exhaustive]
245pub enum LinkEvent {
246    /// Host → module: a frame the host wrote.
247    Tx(Vec<u8>),
248    /// Module → host: a frame the host read.
249    Rx(Vec<u8>),
250    /// A `reset()` ioctl.
251    Reset,
252    /// A `slot_info()` ioctl and the status it returned.
253    SlotInfo(SlotInfo),
254}
255
256/// A [`CaDevice`] decorator that records every frame in **both** directions
257/// (plus ioctls) for live-CAM diagnostics. Wrap a real device, run, then dump
258/// the [`log`](Self::log) — or decode it with
259/// [`trace::decode_log`](crate::trace::decode_log) — to get an annotated byte
260/// trace without hand-instrumenting the device:
261///
262/// ```no_run
263/// # use dvb_ci_runtime::{Driver, device::RecordingCaDevice, trace};
264/// # fn real_device() -> dvb_ci_runtime::MockCaDevice { dvb_ci_runtime::MockCaDevice::new([]) }
265/// let mut driver = Driver::new(RecordingCaDevice::new(real_device()));
266/// driver.init().unwrap();
267/// // ... pump ...
268/// println!("{}", trace::decode_log(driver.device().log()));
269/// ```
270#[derive(Debug, Default)]
271pub struct RecordingCaDevice<D> {
272    inner: D,
273    /// The captured link events, in order.
274    pub log: Vec<LinkEvent>,
275    /// Last logged slot status, so repeated identical `slot_info()` polls
276    /// (the driver now samples every [`pump`](crate::Driver::pump) for
277    /// hot-plug edge detection — #726) don't swamp the trace; only a change
278    /// is recorded, same rationale as `poll()` below.
279    last_slot: Option<SlotInfo>,
280}
281
282impl<D: CaDevice> RecordingCaDevice<D> {
283    /// Wrap `inner`, recording all I/O.
284    pub fn new(inner: D) -> Self {
285        Self {
286            inner,
287            log: Vec::new(),
288            last_slot: None,
289        }
290    }
291
292    /// The recorded link events, in order.
293    #[must_use]
294    pub fn log(&self) -> &[LinkEvent] {
295        &self.log
296    }
297
298    /// Borrow the wrapped device.
299    pub fn inner(&self) -> &D {
300        &self.inner
301    }
302}
303
304impl<D: CaDevice> CaDevice for RecordingCaDevice<D> {
305    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
306        let n = self.inner.read(buf)?;
307        if n > 0 {
308            self.log.push(LinkEvent::Rx(buf[..n].to_vec()));
309        }
310        Ok(n)
311    }
312
313    fn write(&mut self, buf: &[u8]) -> io::Result<()> {
314        self.log.push(LinkEvent::Tx(buf.to_vec()));
315        self.inner.write(buf)
316    }
317
318    fn reset(&mut self) -> io::Result<()> {
319        self.log.push(LinkEvent::Reset);
320        self.inner.reset()
321    }
322
323    /// Forwarded: without this the wrapper falls back to the trait default
324    /// (`Duration::ZERO`) and `Driver::init` writes the first TPDU straight
325    /// after `CA_RESET` (EINVAL on a CXD2099). Guarded by
326    /// `tests/wrapper_forwards_defaults.rs`.
327    fn reset_settle(&self) -> std::time::Duration {
328        self.inner.reset_settle()
329    }
330
331    fn slot_info(&mut self) -> io::Result<SlotInfo> {
332        let si = self.inner.slot_info()?;
333        if self.last_slot != Some(si) {
334            self.log.push(LinkEvent::SlotInfo(si));
335            self.last_slot = Some(si);
336        }
337        Ok(si)
338    }
339
340    fn poll(&mut self, timeout: std::time::Duration) -> io::Result<bool> {
341        // Polls are not recorded (they would swamp the trace).
342        self.inner.poll(timeout)
343    }
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    #[test]
351    fn device_op_error_displays_and_chains_its_source() {
352        let wrapped = DeviceOpError::wrap(
353            "write (17 bytes)",
354            "/dev/dvb/adapter3/ca0",
355            io::Error::from_raw_os_error(22),
356        );
357        let inner = wrapped
358            .get_ref()
359            .and_then(|e| e.downcast_ref::<DeviceOpError>())
360            .expect("wrapped");
361        assert_eq!(
362            inner.to_string(),
363            format!(
364                "/dev/dvb/adapter3/ca0: write (17 bytes) failed: {}",
365                io::Error::from_raw_os_error(22)
366            )
367        );
368        let source = std::error::Error::source(inner).expect("source");
369        assert_eq!(
370            source.to_string(),
371            io::Error::from_raw_os_error(22).to_string()
372        );
373    }
374
375    /// The read buffer must fit the largest frame the link can encode: the
376    /// 2-byte link header, the 1-byte `tpdu_tag`, the widest `length_field`
377    /// (3 bytes) and that field's own maximum (65535) of `t_c_id` + data.
378    #[test]
379    fn max_ca_frame_fits_the_widest_link_frame() {
380        assert_eq!(MAX_CA_FRAME, 65_541);
381        // The same ceiling expressed from the widest SPDU one T_Data_Last can
382        // carry plus that TPDU's own framing (tag, long-form length, t_c_id).
383        assert_eq!(MAX_CA_FRAME, crate::transport::MAX_SPDU_LEN + 2 + 1 + 3 + 1);
384    }
385
386    /// A wrapped device failure must keep the errno reachable (it classifies
387    /// `EINVAL`/`ENODEV` per operation), name the device and the operation in
388    /// its Display, and keep the original error as its source.
389    #[test]
390    fn device_op_error_reports_errno_text_and_source() {
391        let wrapped = DeviceOpError::wrap(
392            "read (4096 bytes)",
393            "/dev/dvb/adapter3/ca0",
394            io::Error::from_raw_os_error(22),
395        );
396        let inner = wrapped
397            .get_ref()
398            .and_then(|e| e.downcast_ref::<DeviceOpError>())
399            .unwrap();
400        assert_eq!(inner.errno(), Some(22));
401        assert_eq!(DeviceOpError::errno_of(&wrapped), Some(22));
402        assert_eq!(
403            DeviceOpError::errno_of(&io::Error::from_raw_os_error(5)),
404            Some(5),
405            "a plain OS error answers for itself"
406        );
407        assert_eq!(DeviceOpError::errno_of(&io::Error::other("x")), None);
408
409        let text = wrapped.to_string();
410        assert!(text.contains("/dev/dvb/adapter3/ca0"), "{text}");
411        assert!(text.contains("read (4096 bytes)"), "{text}");
412        assert!(text.contains("Invalid argument"), "{text}");
413        assert_eq!(wrapped.kind(), io::ErrorKind::InvalidInput);
414        assert!(std::error::Error::source(inner).is_some());
415    }
416
417    /// A `read` that finds nothing must not be recorded as an (empty) Rx event,
418    /// or the trace fills with noise the CAM never sent.
419    #[test]
420    fn recording_device_ignores_an_empty_read() {
421        let mut dev = RecordingCaDevice::new(MockCaDevice::new([]));
422        let mut buf = [0u8; 16];
423        assert_eq!(dev.read(&mut buf).unwrap(), 0);
424        assert!(
425            dev.log().is_empty(),
426            "a zero-length read is not an Rx event: {:?}",
427            dev.log()
428        );
429    }
430
431    /// `slot_info` is sampled on every pump for hot-plug edge detection (#726),
432    /// so the trace keeps one entry per *change*: the first sample is logged,
433    /// a repeat of it is not, and a changed status is.
434    #[test]
435    fn recording_device_logs_slot_info_only_when_it_changes() {
436        let ready = SlotInfo {
437            num: 2,
438            module_ready: true,
439            module_present: true,
440        };
441        let mut mock = MockCaDevice::new([]);
442        mock.slot = ready;
443        let mut dev = RecordingCaDevice::new(mock);
444
445        assert_eq!(dev.slot_info().unwrap(), ready);
446        assert_eq!(
447            dev.slot_info().unwrap(),
448            ready,
449            "the wrapper returns the device's own status"
450        );
451        assert_eq!(
452            dev.log(),
453            &[LinkEvent::SlotInfo(SlotInfo {
454                num: 2,
455                module_ready: true,
456                module_present: true,
457            })],
458            "two identical samples must leave exactly one entry"
459        );
460
461        dev.inner.slot = SlotInfo {
462            num: 2,
463            module_ready: false,
464            module_present: false,
465        };
466        dev.slot_info().unwrap();
467        assert_eq!(dev.log().len(), 2);
468        assert_eq!(
469            dev.log()[1],
470            LinkEvent::SlotInfo(SlotInfo {
471                num: 2,
472                module_ready: false,
473                module_present: false,
474            })
475        );
476    }
477
478    /// `poll` must report the wrapped device's readiness, not a constant.
479    #[test]
480    fn recording_device_poll_follows_the_inner_device() {
481        let mut dev = RecordingCaDevice::new(MockCaDevice::new([]));
482        assert!(!dev.poll(std::time::Duration::ZERO).unwrap());
483        dev.inner.inbound.push_back(vec![0x80, 0x02, 0x01, 0x00]);
484        assert!(dev.poll(std::time::Duration::ZERO).unwrap());
485    }
486
487    /// The mock reports readability only while frames are queued, so a test
488    /// that reads with no data sees `Ok(0)`.
489    #[test]
490    fn mock_poll_reports_only_queued_frames() {
491        let mut dev = MockCaDevice::new([]);
492        assert!(!dev.poll(std::time::Duration::ZERO).unwrap());
493        dev.inbound.push_back(vec![0x81, 0x01, 0x01]);
494        assert!(dev.poll(std::time::Duration::ZERO).unwrap());
495    }
496
497    #[test]
498    fn recording_device_captures_both_directions() {
499        let inner = MockCaDevice::new([vec![0x83, 0x01, 0x01]]);
500        let mut dev = RecordingCaDevice::new(inner);
501        dev.reset().unwrap();
502        dev.write(&[0x82, 0x01, 0x01]).unwrap();
503        let mut buf = [0u8; 16];
504        dev.read(&mut buf).unwrap();
505        assert_eq!(
506            dev.log(),
507            &[
508                LinkEvent::Reset,
509                LinkEvent::Tx(vec![0x82, 0x01, 0x01]),
510                LinkEvent::Rx(vec![0x83, 0x01, 0x01]),
511            ]
512        );
513    }
514
515    #[test]
516    fn mock_records_writes_and_replays_inbound() {
517        let mut dev = MockCaDevice::new([vec![0x01, 0x02], vec![0x03]]);
518        // host writes
519        dev.write(&[0xAA, 0xBB]).unwrap();
520        dev.reset().unwrap();
521        // module frames replay in order
522        let mut buf = [0u8; 16];
523        assert_eq!(dev.read(&mut buf).unwrap(), 2);
524        assert_eq!(&buf[..2], &[0x01, 0x02]);
525        assert_eq!(dev.read(&mut buf).unwrap(), 1);
526        assert_eq!(dev.read(&mut buf).unwrap(), 0); // drained
527        assert_eq!(dev.written(), vec![0xAA, 0xBB]);
528        assert_eq!(dev.ops[1], DeviceOp::Reset);
529    }
530}