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, DriverBounds, device::RecordingCaDevice, trace};
264/// # fn real_device() -> dvb_ci_runtime::MockCaDevice { dvb_ci_runtime::MockCaDevice::new([]) }
265/// # fn bounds() -> DriverBounds { unimplemented!() }
266/// let mut driver = Driver::new(RecordingCaDevice::new(real_device()), bounds());
267/// driver.init().unwrap();
268/// // ... pump ...
269/// println!("{}", trace::decode_log(driver.device().log()));
270/// ```
271#[derive(Debug, Default)]
272pub struct RecordingCaDevice<D> {
273    inner: D,
274    /// The captured link events, in order.
275    pub log: Vec<LinkEvent>,
276    /// Last logged slot status, so repeated identical `slot_info()` polls
277    /// (the driver now samples every [`pump`](crate::Driver::pump) for
278    /// hot-plug edge detection — #726) don't swamp the trace; only a change
279    /// is recorded, same rationale as `poll()` below.
280    last_slot: Option<SlotInfo>,
281}
282
283impl<D: CaDevice> RecordingCaDevice<D> {
284    /// Wrap `inner`, recording all I/O.
285    pub fn new(inner: D) -> Self {
286        Self {
287            inner,
288            log: Vec::new(),
289            last_slot: None,
290        }
291    }
292
293    /// The recorded link events, in order.
294    #[must_use]
295    pub fn log(&self) -> &[LinkEvent] {
296        &self.log
297    }
298
299    /// Borrow the wrapped device.
300    pub fn inner(&self) -> &D {
301        &self.inner
302    }
303}
304
305impl<D: CaDevice> CaDevice for RecordingCaDevice<D> {
306    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
307        let n = self.inner.read(buf)?;
308        if n > 0 {
309            self.log.push(LinkEvent::Rx(buf[..n].to_vec()));
310        }
311        Ok(n)
312    }
313
314    fn write(&mut self, buf: &[u8]) -> io::Result<()> {
315        self.log.push(LinkEvent::Tx(buf.to_vec()));
316        self.inner.write(buf)
317    }
318
319    fn reset(&mut self) -> io::Result<()> {
320        self.log.push(LinkEvent::Reset);
321        self.inner.reset()
322    }
323
324    /// Forwarded: without this the wrapper falls back to the trait default
325    /// (`Duration::ZERO`) and `Driver::init` writes the first TPDU straight
326    /// after `CA_RESET` (EINVAL on a CXD2099). Guarded by
327    /// `tests/wrapper_forwards_defaults.rs`.
328    fn reset_settle(&self) -> std::time::Duration {
329        self.inner.reset_settle()
330    }
331
332    fn slot_info(&mut self) -> io::Result<SlotInfo> {
333        let si = self.inner.slot_info()?;
334        if self.last_slot != Some(si) {
335            self.log.push(LinkEvent::SlotInfo(si));
336            self.last_slot = Some(si);
337        }
338        Ok(si)
339    }
340
341    fn poll(&mut self, timeout: std::time::Duration) -> io::Result<bool> {
342        // Polls are not recorded (they would swamp the trace).
343        self.inner.poll(timeout)
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    #[test]
352    fn device_op_error_displays_and_chains_its_source() {
353        let wrapped = DeviceOpError::wrap(
354            "write (17 bytes)",
355            "/dev/dvb/adapter3/ca0",
356            io::Error::from_raw_os_error(22),
357        );
358        let inner = wrapped
359            .get_ref()
360            .and_then(|e| e.downcast_ref::<DeviceOpError>())
361            .expect("wrapped");
362        assert_eq!(
363            inner.to_string(),
364            format!(
365                "/dev/dvb/adapter3/ca0: write (17 bytes) failed: {}",
366                io::Error::from_raw_os_error(22)
367            )
368        );
369        let source = std::error::Error::source(inner).expect("source");
370        assert_eq!(
371            source.to_string(),
372            io::Error::from_raw_os_error(22).to_string()
373        );
374    }
375
376    /// The read buffer must fit the largest frame the link can encode: the
377    /// 2-byte link header, the 1-byte `tpdu_tag`, the widest `length_field`
378    /// (3 bytes) and that field's own maximum (65535) of `t_c_id` + data.
379    #[test]
380    fn max_ca_frame_fits_the_widest_link_frame() {
381        assert_eq!(MAX_CA_FRAME, 65_541);
382        // The same ceiling expressed from the widest SPDU one T_Data_Last can
383        // carry plus that TPDU's own framing (tag, long-form length, t_c_id).
384        assert_eq!(MAX_CA_FRAME, crate::transport::MAX_SPDU_LEN + 2 + 1 + 3 + 1);
385    }
386
387    /// A wrapped device failure must keep the errno reachable (it classifies
388    /// `EINVAL`/`ENODEV` per operation), name the device and the operation in
389    /// its Display, and keep the original error as its source.
390    #[test]
391    fn device_op_error_reports_errno_text_and_source() {
392        let wrapped = DeviceOpError::wrap(
393            "read (4096 bytes)",
394            "/dev/dvb/adapter3/ca0",
395            io::Error::from_raw_os_error(22),
396        );
397        let inner = wrapped
398            .get_ref()
399            .and_then(|e| e.downcast_ref::<DeviceOpError>())
400            .unwrap();
401        assert_eq!(inner.errno(), Some(22));
402        assert_eq!(DeviceOpError::errno_of(&wrapped), Some(22));
403        assert_eq!(
404            DeviceOpError::errno_of(&io::Error::from_raw_os_error(5)),
405            Some(5),
406            "a plain OS error answers for itself"
407        );
408        assert_eq!(DeviceOpError::errno_of(&io::Error::other("x")), None);
409
410        let text = wrapped.to_string();
411        assert!(text.contains("/dev/dvb/adapter3/ca0"), "{text}");
412        assert!(text.contains("read (4096 bytes)"), "{text}");
413        assert!(text.contains("Invalid argument"), "{text}");
414        assert_eq!(wrapped.kind(), io::ErrorKind::InvalidInput);
415        assert!(std::error::Error::source(inner).is_some());
416    }
417
418    /// A `read` that finds nothing must not be recorded as an (empty) Rx event,
419    /// or the trace fills with noise the CAM never sent.
420    #[test]
421    fn recording_device_ignores_an_empty_read() {
422        let mut dev = RecordingCaDevice::new(MockCaDevice::new([]));
423        let mut buf = [0u8; 16];
424        assert_eq!(dev.read(&mut buf).unwrap(), 0);
425        assert!(
426            dev.log().is_empty(),
427            "a zero-length read is not an Rx event: {:?}",
428            dev.log()
429        );
430    }
431
432    /// `slot_info` is sampled on every pump for hot-plug edge detection (#726),
433    /// so the trace keeps one entry per *change*: the first sample is logged,
434    /// a repeat of it is not, and a changed status is.
435    #[test]
436    fn recording_device_logs_slot_info_only_when_it_changes() {
437        let ready = SlotInfo {
438            num: 2,
439            module_ready: true,
440            module_present: true,
441        };
442        let mut mock = MockCaDevice::new([]);
443        mock.slot = ready;
444        let mut dev = RecordingCaDevice::new(mock);
445
446        assert_eq!(dev.slot_info().unwrap(), ready);
447        assert_eq!(
448            dev.slot_info().unwrap(),
449            ready,
450            "the wrapper returns the device's own status"
451        );
452        assert_eq!(
453            dev.log(),
454            &[LinkEvent::SlotInfo(SlotInfo {
455                num: 2,
456                module_ready: true,
457                module_present: true,
458            })],
459            "two identical samples must leave exactly one entry"
460        );
461
462        dev.inner.slot = SlotInfo {
463            num: 2,
464            module_ready: false,
465            module_present: false,
466        };
467        dev.slot_info().unwrap();
468        assert_eq!(dev.log().len(), 2);
469        assert_eq!(
470            dev.log()[1],
471            LinkEvent::SlotInfo(SlotInfo {
472                num: 2,
473                module_ready: false,
474                module_present: false,
475            })
476        );
477    }
478
479    /// `poll` must report the wrapped device's readiness, not a constant.
480    #[test]
481    fn recording_device_poll_follows_the_inner_device() {
482        let mut dev = RecordingCaDevice::new(MockCaDevice::new([]));
483        assert!(!dev.poll(std::time::Duration::ZERO).unwrap());
484        dev.inner.inbound.push_back(vec![0x80, 0x02, 0x01, 0x00]);
485        assert!(dev.poll(std::time::Duration::ZERO).unwrap());
486    }
487
488    /// The mock reports readability only while frames are queued, so a test
489    /// that reads with no data sees `Ok(0)`.
490    #[test]
491    fn mock_poll_reports_only_queued_frames() {
492        let mut dev = MockCaDevice::new([]);
493        assert!(!dev.poll(std::time::Duration::ZERO).unwrap());
494        dev.inbound.push_back(vec![0x81, 0x01, 0x01]);
495        assert!(dev.poll(std::time::Duration::ZERO).unwrap());
496    }
497
498    #[test]
499    fn recording_device_captures_both_directions() {
500        let inner = MockCaDevice::new([vec![0x83, 0x01, 0x01]]);
501        let mut dev = RecordingCaDevice::new(inner);
502        dev.reset().unwrap();
503        dev.write(&[0x82, 0x01, 0x01]).unwrap();
504        let mut buf = [0u8; 16];
505        dev.read(&mut buf).unwrap();
506        assert_eq!(
507            dev.log(),
508            &[
509                LinkEvent::Reset,
510                LinkEvent::Tx(vec![0x82, 0x01, 0x01]),
511                LinkEvent::Rx(vec![0x83, 0x01, 0x01]),
512            ]
513        );
514    }
515
516    #[test]
517    fn mock_records_writes_and_replays_inbound() {
518        let mut dev = MockCaDevice::new([vec![0x01, 0x02], vec![0x03]]);
519        // host writes
520        dev.write(&[0xAA, 0xBB]).unwrap();
521        dev.reset().unwrap();
522        // module frames replay in order
523        let mut buf = [0u8; 16];
524        assert_eq!(dev.read(&mut buf).unwrap(), 2);
525        assert_eq!(&buf[..2], &[0x01, 0x02]);
526        assert_eq!(dev.read(&mut buf).unwrap(), 1);
527        assert_eq!(dev.read(&mut buf).unwrap(), 0); // drained
528        assert_eq!(dev.written(), vec![0xAA, 0xBB]);
529        assert_eq!(dev.ops[1], DeviceOp::Reset);
530    }
531}