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)]
68pub struct DeviceOpError {
69    /// The operation that failed, e.g. `"write (17 bytes)"`.
70    pub op: String,
71    /// The device, e.g. `"/dev/dvb/adapter3/ca0"`.
72    pub device: String,
73    source: io::Error,
74}
75
76impl DeviceOpError {
77    /// Wrap `source` (an error from `op` on `device`) into an [`io::Error`] of
78    /// the same kind that displays all three.
79    #[must_use]
80    pub fn wrap(op: impl Into<String>, device: &str, source: io::Error) -> io::Error {
81        let kind = source.kind();
82        io::Error::new(
83            kind,
84            DeviceOpError {
85                op: op.into(),
86                device: device.to_owned(),
87                source,
88            },
89        )
90    }
91
92    /// The OS errno of the underlying failure, if it had one.
93    #[must_use]
94    pub fn errno(&self) -> Option<i32> {
95        self.source.raw_os_error()
96    }
97
98    /// The OS errno of `err` whether or not it is wrapped in a
99    /// [`DeviceOpError`] (a plain OS error answers for itself).
100    #[must_use]
101    pub fn errno_of(err: &io::Error) -> Option<i32> {
102        err.raw_os_error().or_else(|| {
103            err.get_ref()
104                .and_then(|inner| inner.downcast_ref::<DeviceOpError>())
105                .and_then(DeviceOpError::errno)
106        })
107    }
108}
109
110impl std::fmt::Display for DeviceOpError {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        write!(f, "{}: {} failed: {}", self.device, self.op, self.source)
113    }
114}
115
116impl std::error::Error for DeviceOpError {
117    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
118        Some(&self.source)
119    }
120}
121
122/// The link-layer device the EN 50221 runtime drives.
123///
124/// All methods mirror the operations a host performs on the CA file descriptor
125/// per EN 50221. Implementations: [`MockCaDevice`] (in-memory, for tests +
126/// differential harness) and the `linux` `CaDevice` over `/dev/dvb/.../ca`.
127pub trait CaDevice {
128    /// Read one link-layer TPDU frame into `buf`; returns the byte count.
129    /// `Ok(0)` means no data available (non-blocking).
130    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
131
132    /// Write one link-layer TPDU frame.
133    fn write(&mut self, buf: &[u8]) -> io::Result<()>;
134
135    /// Reset the interface / slot (ioctl `CA_RESET`).
136    fn reset(&mut self) -> io::Result<()>;
137
138    /// How long the module needs after [`reset`](Self::reset) returns before
139    /// it accepts `Create_T_C` (the DD/cxd2099 class of drivers only
140    /// re-initialise the slot seconds after `CA_RESET`).
141    ///
142    /// `reset` itself must not sleep for this: the sans-IO
143    /// [`Driver`](crate::Driver) reads this value after `reset` and holds the
144    /// transport quiet until it elapses on its injectable clock, so a CAM
145    /// hot-plug edge no longer freezes `pump` (audit r10-O-10). Defaults to
146    /// [`Duration::ZERO`](std::time::Duration::ZERO) — an implementation whose
147    /// `reset` already blocks until the module is usable keeps working
148    /// unchanged.
149    fn reset_settle(&self) -> std::time::Duration {
150        std::time::Duration::ZERO
151    }
152
153    /// Query slot status (ioctl `CA_GET_SLOT_INFO`).
154    fn slot_info(&mut self) -> io::Result<SlotInfo>;
155
156    /// Wait up to `timeout` for the device to become readable; `Ok(true)` if
157    /// readable. The runtime's poll loop calls this between reads.
158    fn poll(&mut self, timeout: std::time::Duration) -> io::Result<bool>;
159}
160
161/// One recorded device operation, for assertions + differential testing.
162#[derive(Debug, Clone, PartialEq, Eq)]
163#[non_exhaustive]
164pub enum DeviceOp {
165    /// A `write()` of these exact bytes.
166    Write(Vec<u8>),
167    /// A `reset()` ioctl.
168    Reset,
169    /// A `slot_info()` ioctl.
170    SlotInfo,
171}
172
173/// In-memory [`CaDevice`] for tests and the differential harness.
174///
175/// - `inbound` is a scripted queue of frames the "module" (mock CAM) sends up;
176///   each [`read`](CaDevice::read) pops one.
177/// - every host-side operation is appended to `ops` so a test (or a differential
178///   comparison against an external reference) can assert the exact emitted
179///   `write`/ioctl sequence.
180#[derive(Debug, Default)]
181pub struct MockCaDevice {
182    /// Scripted frames the module sends to the host (FIFO).
183    pub inbound: std::collections::VecDeque<Vec<u8>>,
184    /// Recorded host-side operations, in order.
185    pub ops: Vec<DeviceOp>,
186    /// Slot status returned by [`slot_info`](CaDevice::slot_info).
187    pub slot: SlotInfo,
188}
189
190impl MockCaDevice {
191    /// New mock with a ready module in slot 0 and the given inbound script.
192    #[must_use]
193    pub fn new(inbound: impl IntoIterator<Item = Vec<u8>>) -> Self {
194        Self {
195            inbound: inbound.into_iter().collect(),
196            ops: Vec::new(),
197            slot: SlotInfo {
198                num: 0,
199                module_ready: true,
200                module_present: true,
201            },
202        }
203    }
204
205    /// The bytes written by the host so far, concatenated (convenience for
206    /// byte-exact differential comparison against the C reference).
207    #[must_use]
208    pub fn written(&self) -> Vec<u8> {
209        self.ops
210            .iter()
211            .filter_map(|o| match o {
212                DeviceOp::Write(b) => Some(b.clone()),
213                _ => None,
214            })
215            .flatten()
216            .collect()
217    }
218}
219
220impl CaDevice for MockCaDevice {
221    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
222        match self.inbound.pop_front() {
223            Some(frame) => {
224                let n = frame.len().min(buf.len());
225                buf[..n].copy_from_slice(&frame[..n]);
226                Ok(n)
227            }
228            None => Ok(0),
229        }
230    }
231
232    fn write(&mut self, buf: &[u8]) -> io::Result<()> {
233        self.ops.push(DeviceOp::Write(buf.to_vec()));
234        Ok(())
235    }
236
237    fn reset(&mut self) -> io::Result<()> {
238        self.ops.push(DeviceOp::Reset);
239        Ok(())
240    }
241
242    fn slot_info(&mut self) -> io::Result<SlotInfo> {
243        self.ops.push(DeviceOp::SlotInfo);
244        Ok(self.slot)
245    }
246
247    fn poll(&mut self, _timeout: std::time::Duration) -> io::Result<bool> {
248        Ok(!self.inbound.is_empty())
249    }
250}
251
252/// One link-layer event for diagnostics, captured in both directions by
253/// [`RecordingCaDevice`].
254#[derive(Debug, Clone, PartialEq, Eq)]
255#[non_exhaustive]
256pub enum LinkEvent {
257    /// Host → module: a frame the host wrote.
258    Tx(Vec<u8>),
259    /// Module → host: a frame the host read.
260    Rx(Vec<u8>),
261    /// A `reset()` ioctl.
262    Reset,
263    /// A `slot_info()` ioctl and the status it returned.
264    SlotInfo(SlotInfo),
265}
266
267/// A [`CaDevice`] decorator that records every frame in **both** directions
268/// (plus ioctls) for live-CAM diagnostics. Wrap a real device, run, then dump
269/// the [`log`](Self::log) — or decode it with
270/// [`trace::decode_log`](crate::trace::decode_log) — to get an annotated byte
271/// trace without hand-instrumenting the device:
272///
273/// ```no_run
274/// # use dvb_ci_runtime::{Driver, device::RecordingCaDevice, trace};
275/// # fn real_device() -> dvb_ci_runtime::MockCaDevice { dvb_ci_runtime::MockCaDevice::new([]) }
276/// let mut driver = Driver::new(RecordingCaDevice::new(real_device()));
277/// driver.init().unwrap();
278/// // ... pump ...
279/// println!("{}", trace::decode_log(driver.device().log()));
280/// ```
281#[derive(Debug, Default)]
282pub struct RecordingCaDevice<D> {
283    inner: D,
284    /// The captured link events, in order.
285    pub log: Vec<LinkEvent>,
286    /// Last logged slot status, so repeated identical `slot_info()` polls
287    /// (the driver now samples every [`pump`](crate::Driver::pump) for
288    /// hot-plug edge detection — #726) don't swamp the trace; only a change
289    /// is recorded, same rationale as `poll()` below.
290    last_slot: Option<SlotInfo>,
291}
292
293impl<D: CaDevice> RecordingCaDevice<D> {
294    /// Wrap `inner`, recording all I/O.
295    pub fn new(inner: D) -> Self {
296        Self {
297            inner,
298            log: Vec::new(),
299            last_slot: None,
300        }
301    }
302
303    /// The recorded link events, in order.
304    #[must_use]
305    pub fn log(&self) -> &[LinkEvent] {
306        &self.log
307    }
308
309    /// Borrow the wrapped device.
310    pub fn inner(&self) -> &D {
311        &self.inner
312    }
313}
314
315impl<D: CaDevice> CaDevice for RecordingCaDevice<D> {
316    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
317        let n = self.inner.read(buf)?;
318        if n > 0 {
319            self.log.push(LinkEvent::Rx(buf[..n].to_vec()));
320        }
321        Ok(n)
322    }
323
324    fn write(&mut self, buf: &[u8]) -> io::Result<()> {
325        self.log.push(LinkEvent::Tx(buf.to_vec()));
326        self.inner.write(buf)
327    }
328
329    fn reset(&mut self) -> io::Result<()> {
330        self.log.push(LinkEvent::Reset);
331        self.inner.reset()
332    }
333
334    /// Forwarded: without this the wrapper falls back to the trait default
335    /// (`Duration::ZERO`) and `Driver::init` writes the first TPDU straight
336    /// after `CA_RESET` (EINVAL on a CXD2099). Guarded by
337    /// `tests/wrapper_forwards_defaults.rs`.
338    fn reset_settle(&self) -> std::time::Duration {
339        self.inner.reset_settle()
340    }
341
342    fn slot_info(&mut self) -> io::Result<SlotInfo> {
343        let si = self.inner.slot_info()?;
344        if self.last_slot != Some(si) {
345            self.log.push(LinkEvent::SlotInfo(si));
346            self.last_slot = Some(si);
347        }
348        Ok(si)
349    }
350
351    fn poll(&mut self, timeout: std::time::Duration) -> io::Result<bool> {
352        // Polls are not recorded (they would swamp the trace).
353        self.inner.poll(timeout)
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    #[test]
362    fn recording_device_captures_both_directions() {
363        let inner = MockCaDevice::new([vec![0x83, 0x01, 0x01]]);
364        let mut dev = RecordingCaDevice::new(inner);
365        dev.reset().unwrap();
366        dev.write(&[0x82, 0x01, 0x01]).unwrap();
367        let mut buf = [0u8; 16];
368        dev.read(&mut buf).unwrap();
369        assert_eq!(
370            dev.log(),
371            &[
372                LinkEvent::Reset,
373                LinkEvent::Tx(vec![0x82, 0x01, 0x01]),
374                LinkEvent::Rx(vec![0x83, 0x01, 0x01]),
375            ]
376        );
377    }
378
379    #[test]
380    fn mock_records_writes_and_replays_inbound() {
381        let mut dev = MockCaDevice::new([vec![0x01, 0x02], vec![0x03]]);
382        // host writes
383        dev.write(&[0xAA, 0xBB]).unwrap();
384        dev.reset().unwrap();
385        // module frames replay in order
386        let mut buf = [0u8; 16];
387        assert_eq!(dev.read(&mut buf).unwrap(), 2);
388        assert_eq!(&buf[..2], &[0x01, 0x02]);
389        assert_eq!(dev.read(&mut buf).unwrap(), 1);
390        assert_eq!(dev.read(&mut buf).unwrap(), 0); // drained
391        assert_eq!(dev.written(), vec![0xAA, 0xBB]);
392        assert_eq!(dev.ops[1], DeviceOp::Reset);
393    }
394}