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