Skip to main content

dvb_ci_runtime/
linux.rs

1//! Linux `/dev/dvb/adapterN/caM` [`CaDevice`] implementation (the `linux`
2//! feature).
3//!
4//! This is the one place the crate uses `unsafe` — the DVB CA ioctls
5//! (`CA_RESET`, `CA_GET_SLOT_INFO`) via `rustix::ioctl`, confined to the
6//! private `ioctl` submodule below, which exposes safe functions. The ioctl
7//! request numbers are built by `rustix::ioctl::opcode` (the per-architecture
8//! `_IOC` encoding — it differs between x86/arm and mips/powerpc/sparc) from
9//! `include/uapi/linux/dvb/ca.h`'s group/number/type, not hard-coded magic.
10//!
11//! Runtime behaviour requires a real DVB card with a CI slot; it is
12//! compile-checked in CI but exercised only on hardware.
13use std::fs::{File, OpenOptions};
14use std::io::{self, Read, Write};
15use std::os::unix::fs::OpenOptionsExt;
16use std::os::unix::io::AsFd;
17use std::path::Path;
18use std::time::{Duration, Instant};
19
20use rustix::event::{Nsecs, PollFd, PollFlags, Timespec};
21use rustix::fs::OFlags;
22use rustix::io::Errno;
23
24const O_NONBLOCK: i32 = OFlags::NONBLOCK.bits() as i32;
25
26use crate::dataplane::{CiDataDevice, PartialWrite};
27use crate::device::{CaDevice, DeviceOpError, MAX_CA_FRAME, SlotInfo};
28use mpeg_ts::ts::TS_PACKET_SIZE;
29
30/// Poll a file descriptor for readability up to `timeout`.
31///
32/// `EINTR` surfaces as an `io::Error` of kind `Interrupted`, exactly as it did
33/// with `libc::poll` on `main` (which also returned `last_os_error()` on `-1`
34/// and did not retry). Nothing retries it further up either: the driver pump
35/// does `self.device.poll(timeout)?`. A stray signal therefore still aborts
36/// one pump call, unchanged by this migration. Only `POLLIN` counts as
37/// readable; `POLLHUP`/`POLLERR` alone report `false`, as before. Unlike the
38/// old millisecond truncation the timeout keeps its sub-millisecond part.
39// `Nsecs` is `i64` on rustix's linux_raw backend (where `From<u32>` would do) but
40// `c_long` (`i32`) under its libc backend on 32-bit targets, where only
41// `TryFrom` exists; keep the portable form.
42fn poll_readable(fd: &impl AsFd, timeout: Duration) -> io::Result<bool> {
43    let mut fds = [PollFd::new(fd, PollFlags::IN)];
44    let ts = Timespec {
45        tv_sec: i64::try_from(timeout.as_secs()).unwrap_or(i64::MAX),
46        tv_nsec: timeout.subsec_nanos() as Nsecs,
47    };
48    rustix::event::poll(&mut fds, Some(&ts))?;
49    Ok(fds[0].revents().contains(PollFlags::IN))
50}
51
52/// Poll a file descriptor for writability (`POLLOUT`) up to `timeout`; the
53/// write-side twin of [`poll_readable`] (same timeout handling, same `EINTR`
54/// behaviour). `POLLERR`/`POLLHUP` alone report `false`.
55fn poll_writable(fd: &impl AsFd, timeout: Duration) -> io::Result<bool> {
56    let mut fds = [PollFd::new(fd, PollFlags::OUT)];
57    let ts = Timespec {
58        tv_sec: i64::try_from(timeout.as_secs()).unwrap_or(i64::MAX),
59        tv_nsec: timeout.subsec_nanos() as Nsecs,
60    };
61    rustix::event::poll(&mut fds, Some(&ts))?;
62    Ok(fds[0].revents().contains(PollFlags::OUT))
63}
64
65/// TS packets per `write(2)` to the CI data device. 21 x 188 = 3948 bytes is
66/// under `PIPE_BUF` (4096), so on a pipe/FIFO stand-in each call is atomic
67/// (all of it or `EAGAIN`, never a torn packet), and a stall can leave at most
68/// one chunk unsent. The real device takes any whole-packet multiple.
69const WRITE_CHUNK_PACKETS: usize = 21;
70/// The waits of a [`LinuxCiDataDevice`], both the caller's: the kernel fixes neither.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct CiDataTimings {
73    /// How long [`CiDataDevice::write`] waits for a full device buffer to drain before giving up
74    /// with a [`PartialWrite`] (whole packets already accepted).
75    pub write_stall_timeout: Duration,
76    /// How long to wait for room to finish a packet the device accepted only part of: the one
77    /// situation that cannot be handed back to the caller.
78    pub torn_packet_timeout: Duration,
79}
80
81/// Bytes of the `[slot, connection_id]` link header the CA device expects in
82/// front of every TPDU written to it.
83const LINK_HEADER_LEN: usize = 2;
84
85/// Write `chunk` (a whole number of TS packets) to `file`, returning how many
86/// bytes the device accepted — always a whole number of packets. A short or
87/// non-packet-aligned write is completed (waiting up to
88/// [`CiDataTimings::torn_packet_timeout`] for room) so a packet is never left half written;
89/// only if that wait fails is an error returned.
90fn write_whole_packets(
91    file: &mut File,
92    chunk: &[u8],
93    torn_packet_timeout: Duration,
94) -> io::Result<usize> {
95    let mut n = 0;
96    while n < chunk.len() {
97        match file.write(&chunk[n..]) {
98            Ok(0) => {
99                return Err(io::Error::new(
100                    io::ErrorKind::WriteZero,
101                    "CI data device accepted 0 bytes",
102                ));
103            }
104            Ok(k) => n += k,
105            Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
106            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
107                if n.is_multiple_of(TS_PACKET_SIZE) {
108                    // Device full at a packet boundary: nothing torn.
109                    return Ok(n);
110                }
111                // Mid-packet: the remainder must go in before anything else.
112                if !poll_writable(file, torn_packet_timeout)? {
113                    return Err(io::Error::new(
114                        io::ErrorKind::TimedOut,
115                        "CI data device stayed full with a TS packet half written",
116                    ));
117                }
118            }
119            Err(e) => return Err(e),
120        }
121    }
122    Ok(n)
123}
124
125// --- DVB CA ioctl request numbers (uapi/linux/dvb/ca.h) --------------------
126//
127// The `_IOC` request encoding is NOT one layout on Linux: x86/arm/arm64/riscv/
128// s390x/... use the asm-generic one (2 direction bits, 14 size bits), but
129// mips/powerpc/sparc use 3 direction bits, 13 size bits and different
130// direction values (`_IOC_NONE` = 1, `_IOC_READ` = 2, `_IOC_WRITE` = 4). A
131// hand-rolled asm-generic encoding therefore issues the WRONG request on those
132// targets (r10-W-1). `rustix::ioctl::opcode` carries the per-architecture
133// table, so the request numbers are derived from it rather than re-encoded
134// here.
135use rustix::ioctl::{Opcode, opcode};
136
137/// The DVB CA ioctl "magic" group, `'o'` (uapi `linux/dvb/ca.h`).
138const DVB_CA_MAGIC: u8 = b'o';
139/// `_IO('o', 128)` (uapi `linux/dvb/ca.h`).
140const CA_RESET: Opcode = opcode::none(DVB_CA_MAGIC, 128);
141/// `_IOR('o', 130, ca_slot_info_t)` (uapi `linux/dvb/ca.h`).
142const CA_GET_SLOT_INFO: Opcode = opcode::read::<CaSlotInfo>(DVB_CA_MAGIC, 130);
143/// `CA_CI_MODULE_PRESENT` — a module (or card) is physically inserted in the
144/// slot (uapi `linux/dvb/ca.h` `ca_slot_info.flags`, bit 0).
145const CA_CI_MODULE_PRESENT: u32 = 1;
146/// `CA_CI_MODULE_READY` — the inserted module has completed its own init and
147/// is usable (uapi `linux/dvb/ca.h` `ca_slot_info.flags`, bit 1). Distinct
148/// from `CA_CI_MODULE_PRESENT`: a module can be present but not yet ready
149/// briefly after insertion.
150const CA_CI_MODULE_READY: u32 = 2;
151
152/// Mirror of the kernel's `struct ca_slot_info` (uapi `linux/dvb/ca.h`):
153/// `int num; int type; unsigned int flags;` — three 4-byte fields.
154#[repr(C)]
155struct CaSlotInfo {
156    num: i32,
157    typ: i32,
158    flags: u32,
159}
160
161/// Size of the kernel's `struct ca_slot_info` (3 x 4 bytes).
162#[cfg(test)]
163const KERNEL_CA_SLOT_INFO_SIZE: usize = 12;
164/// Alignment of the kernel's `struct ca_slot_info` (4-byte `int`s).
165#[cfg(test)]
166const KERNEL_CA_SLOT_INFO_ALIGN: usize = 4;
167
168/// The only `unsafe` in the crate: the two DVB CA ioctls, behind safe fns.
169#[allow(unsafe_code)]
170mod ioctl {
171    use super::{CA_GET_SLOT_INFO, CA_RESET, CaSlotInfo};
172    use rustix::ioctl::{NoArg, Updater, ioctl};
173    use std::io;
174    use std::os::unix::io::BorrowedFd;
175
176    /// `CA_RESET` on `fd`.
177    pub(super) fn ca_reset(fd: BorrowedFd<'_>) -> io::Result<()> {
178        // SAFETY: `CA_RESET` is `_IO('o', 128)` (built by `rustix::ioctl::
179        // opcode::none`, the correct request for this target architecture)
180        // and takes no argument, so there is no memory for the kernel to read
181        // or write. `fd` is a live borrowed descriptor for the whole call.
182        unsafe { ioctl(fd, NoArg::<CA_RESET>::new()) }.map_err(io::Error::from)
183    }
184
185    /// `CA_GET_SLOT_INFO` on `fd`, filling `info` (its `num` selects the slot).
186    pub(super) fn ca_get_slot_info(fd: BorrowedFd<'_>, info: &mut CaSlotInfo) -> io::Result<()> {
187        // SAFETY: the request is `_IOR('o', 130, CaSlotInfo)` (built by
188        // `rustix::ioctl::opcode::read::<CaSlotInfo>`, per-architecture): the
189        // kernel reads `num` and writes the whole `ca_slot_info`, whose
190        // size/alignment `CaSlotInfo` mirrors (`#[repr(C)]`, asserted by the
191        // `ca_slot_info_matches_kernel_layout` test). `Updater` passes a
192        // pointer to the exclusive, fully-initialised `info`, which outlives
193        // the call. `fd` is live for the whole call.
194        unsafe { ioctl(fd, Updater::<CA_GET_SLOT_INFO, CaSlotInfo>::new(info)) }
195            .map_err(io::Error::from)
196    }
197}
198
199/// A [`CaDevice`] backed by a Linux DVB CA character device.
200///
201/// The kernel `dvb_ca_en50221` character device carries a 2-byte link header on
202/// every read/write — `[slot_id, connection_id, <TPDU>]`. This type adds/strips
203/// that header, so the sans-IO transport deals in bare TPDUs. (Writing a raw
204/// TPDU without the header is rejected `EINVAL` by the driver.)
205#[derive(Debug)]
206pub struct LinuxCaDevice {
207    file: File,
208    slot: u8,
209    /// Settle time after `CA_RESET` before the module is usable: the DD/cxd2099 (and others)
210    /// only (re)initialise the slot a couple of seconds after reset, and `Create_T_C` sent too
211    /// early is ignored. The caller states it.
212    reset_settle: Duration,
213    /// Device path for error context (see [`DeviceOpError`]).
214    label: String,
215}
216
217impl LinuxCaDevice {
218    /// Open `/dev/dvb/adapter{adapter}/ca{ca}` (slot 0); `reset_settle` is the wait after
219    /// `CA_RESET`.
220    pub fn open(adapter: u32, ca: u32, reset_settle: Duration) -> io::Result<Self> {
221        let path = format!("/dev/dvb/adapter{adapter}/ca{ca}");
222        let file = OpenOptions::new()
223            .read(true)
224            .write(true)
225            .open(&path)
226            .map_err(|e| DeviceOpError::wrap("open (O_RDWR)", &path, e))?;
227        Ok(Self {
228            file,
229            slot: 0,
230            reset_settle,
231            label: path,
232        })
233    }
234
235    /// Wrap an already-open CA device file for `slot`.
236    #[must_use]
237    pub fn from_file(file: File, slot: u8, reset_settle: Duration) -> Self {
238        Self {
239            file,
240            slot,
241            reset_settle,
242            label: format!("CA device (slot {slot}, from_file)"),
243        }
244    }
245
246    /// The `connection_id` for a TPDU = its `t_c_id`, which follows the tag +
247    /// `length_field`. Falls back to 1 (the single connection) if unparseable.
248    fn connection_id(tpdu: &[u8]) -> u8 {
249        dvb_ci::length::decode(tpdu.get(1..).unwrap_or(&[]))
250            .ok()
251            .and_then(|(_, hdr)| tpdu.get(1 + hdr).copied())
252            .unwrap_or(1)
253    }
254}
255
256impl CaDevice for LinuxCaDevice {
257    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
258        // Read one kernel frame `[slot, connection_id, <TPDU>]` into a scratch
259        // buffer and hand the bare TPDU up. `poll` gates this, so it won't block;
260        // `WouldBlock` is reported as "no data".
261        let mut frame = [0u8; MAX_CA_FRAME];
262        let n = match self.file.read(&mut frame) {
263            Ok(n) => n,
264            Err(e) if e.kind() == io::ErrorKind::WouldBlock => return Ok(0),
265            Err(e) => {
266                return Err(DeviceOpError::wrap(
267                    format!("read (<= {} byte frame)", frame.len()),
268                    &self.label,
269                    e,
270                ));
271            }
272        };
273        if n == frame.len() {
274            // A `read()` reports only how many bytes it actually copied,
275            // never "there was more" — a full buffer means we cannot tell
276            // whether the real frame was exactly this size or the driver
277            // handed us a larger one truncated to fit. Since `MAX_CA_FRAME`
278            // already covers every legal TPDU, treat a full read as a
279            // truncated (and therefore corrupt) frame rather than silently
280            // returning it as complete.
281            return Err(io::Error::new(
282                io::ErrorKind::InvalidData,
283                "CA device frame filled the maximum-size scratch buffer; \
284                 it may have been truncated",
285            ));
286        }
287        // Strip the 2-byte link header; anything shorter has no TPDU.
288        let tpdu = frame.get(2..n).unwrap_or(&[]);
289        if tpdu.len() > buf.len() {
290            // The frame is already consumed from the device, so the TPDU cannot
291            // be re-read; handing the stack a truncated one as `Ok` would
292            // corrupt the link layer silently (the failure r10-W-2 removed on
293            // the device side). Report it instead.
294            return Err(DeviceOpError::wrap(
295                format!(
296                    "read ({} byte TPDU does not fit the caller's {} byte buffer)",
297                    tpdu.len(),
298                    buf.len()
299                ),
300                &self.label,
301                io::Error::new(
302                    io::ErrorKind::InvalidData,
303                    "TPDU larger than the read buffer; dropped, not truncated",
304                ),
305            ));
306        }
307        buf[..tpdu.len()].copy_from_slice(tpdu);
308        Ok(tpdu.len())
309    }
310
311    fn write(&mut self, buf: &[u8]) -> io::Result<()> {
312        // Prepend the `[slot, connection_id]` link header the driver expects.
313        let mut frame = Vec::with_capacity(buf.len() + LINK_HEADER_LEN);
314        frame.push(self.slot);
315        frame.push(Self::connection_id(buf));
316        frame.extend_from_slice(buf);
317        // The kernel's `dvb_ca_en50221_io_write` returns EINVAL while the slot
318        // is not in its RUNNING state (e.g. the CAM is still initialising
319        // after a CA_RESET), so name the frame in the error.
320        self.file.write_all(&frame).map_err(|e| {
321            DeviceOpError::wrap(
322                format!(
323                    "write ({} byte frame: slot {}, connection {})",
324                    frame.len(),
325                    frame[0],
326                    frame[1]
327                ),
328                &self.label,
329                e,
330            )
331        })
332    }
333
334    fn reset(&mut self) -> io::Result<()> {
335        ioctl::ca_reset(self.file.as_fd())
336            .map_err(|e| DeviceOpError::wrap("ioctl CA_RESET", &self.label, e))?;
337        // The module needs a moment to re-initialise before Create_T_C; the
338        // driver waits that out via `reset_settle` on its own clock rather
339        // than this call blocking the pump (audit r10-O-10).
340        Ok(())
341    }
342
343    fn reset_settle(&self) -> Duration {
344        self.reset_settle
345    }
346
347    fn slot_info(&mut self) -> io::Result<SlotInfo> {
348        let mut si = CaSlotInfo {
349            num: i32::from(self.slot),
350            typ: 0,
351            flags: 0,
352        };
353        if let Err(err) = ioctl::ca_get_slot_info(self.file.as_fd(), &mut si) {
354            // r10-W-3: only fall back for the specific errno the "doesn't
355            // implement CA_GET_SLOT_INFO" drivers (DD/cxd2099) return —
356            // EINVAL, or ENOTTY for a device node that doesn't support the
357            // ioctl at all; presence then shows via the TPDU handshake
358            // instead, so assume present+ready. Any OTHER error (EIO,
359            // ENODEV, EBADF, …) is a real fault and must be propagated, not
360            // masked as "the module is present and ready".
361            return match err.raw_os_error().map(Errno::from_raw_os_error) {
362                Some(Errno::INVAL) | Some(Errno::NOTTY) => Ok(SlotInfo {
363                    num: self.slot,
364                    module_ready: true,
365                    module_present: true,
366                }),
367                _ => Err(DeviceOpError::wrap(
368                    format!("ioctl CA_GET_SLOT_INFO (slot {})", self.slot),
369                    &self.label,
370                    err,
371                )),
372            };
373        }
374        Ok(SlotInfo {
375            num: si.num as u8,
376            module_ready: si.flags & CA_CI_MODULE_READY != 0,
377            module_present: si.flags & CA_CI_MODULE_PRESENT != 0,
378        })
379    }
380
381    fn poll(&mut self, timeout: Duration) -> io::Result<bool> {
382        poll_readable(&self.file, timeout)
383            .map_err(|e| DeviceOpError::wrap(format!("poll ({timeout:?})"), &self.label, e))
384    }
385}
386
387/// The file descriptor(s) behind a [`LinuxCiDataDevice`].
388#[derive(Debug)]
389enum CiEndpoints {
390    /// One `O_RDWR` fd used for both directions.
391    Duplex(File),
392    /// Two one-direction fds on the same node: an `O_WRONLY` fd for the
393    /// scrambled TS going in and an `O_RDONLY | O_NONBLOCK` fd for the
394    /// descrambled TS coming out.
395    Split { write: File, read: File },
396}
397
398/// A [`CiDataDevice`] backed by a Linux DVB CI TS data-plane device
399/// (`/dev/dvb/adapterN/ciM`). The host writes scrambled TS and reads the
400/// descrambled TS back; I/O is in whole 188-byte packets.
401///
402/// # Duplex versus split (Digital Devices CXD2099)
403/// Most drivers accept the node opened `O_RDWR`. The Digital Devices
404/// CXD2099 `ci0` (dddvb, Ubuntu 5.15 kernel, verified on hardware) rejects
405/// `O_RDWR` with `EINVAL` and only works as two one-direction descriptors.
406/// [`open`](Self::open) therefore tries `O_RDWR` first and falls back to the
407/// split open on `EINVAL` (and only `EINVAL`); [`open_split`](Self::open_split)
408/// / [`from_split`](Self::from_split) pick it directly.
409#[derive(Debug)]
410pub struct LinuxCiDataDevice {
411    io: CiEndpoints,
412    timings: CiDataTimings,
413    /// Device path for error context (see [`DeviceOpError`]).
414    label: String,
415}
416
417impl LinuxCiDataDevice {
418    /// Open `path` **non-blocking** (`O_NONBLOCK`) as a duplex (`O_RDWR`) CI
419    /// data-plane device.
420    ///
421    /// # Why non-blocking (#1066)
422    /// The kernel `ts_read()` on the real device sleeps
423    /// (`wait_event_interruptible`) until >=188 bytes are available; it never
424    /// returns `0` to signal "no more data right now" the way a mock's queue
425    /// does. [`CaDescrambler::feed_ts`](crate::descrambler::CaDescrambler::feed_ts)
426    /// loops `read` until it sees `0` to drain whatever the CAM has already
427    /// produced — on a *blocking* fd, the first call that drains the queue
428    /// blocks forever on the next read instead of returning, and the caller
429    /// can never feed more TS to unblock it (a permanent hang). Opening
430    /// `O_NONBLOCK` makes an empty read return `EWOULDBLOCK` immediately,
431    /// which [`read`](Self::read) maps to `Ok(0)` — the same "no more data"
432    /// signal the mock already gives, so the drain loop terminates. See
433    /// `tests::read_on_empty_device_returns_immediately_not_blocking` below,
434    /// which drives this exact function over a real blocking-capable FIFO.
435    fn open_path(path: &Path, timings: CiDataTimings) -> io::Result<Self> {
436        let file = OpenOptions::new()
437            .read(true)
438            .write(true)
439            .custom_flags(O_NONBLOCK)
440            .open(path)
441            .map_err(|e| DeviceOpError::wrap("open (O_RDWR|O_NONBLOCK)", &path_label(path), e))?;
442        Ok(Self {
443            io: CiEndpoints::Duplex(file),
444            timings,
445            label: path_label(path),
446        })
447    }
448
449    /// Open `path` as two one-direction descriptors: `O_RDONLY | O_NONBLOCK`
450    /// for reads (so an empty device returns `EWOULDBLOCK` — see
451    /// [`open_path`](Self::open_path) for why that matters) and `O_WRONLY` for
452    /// writes, left blocking exactly as the zenith host has always opened it
453    /// (verified on hardware: 150 s, 111k `feed_ts` calls, max 249 us, no
454    /// error). The read side is opened first so that on a FIFO stand-in the
455    /// write open finds a reader.
456    fn open_split_path(path: &Path, timings: CiDataTimings) -> io::Result<Self> {
457        let label = path_label(path);
458        let read = OpenOptions::new()
459            .read(true)
460            .custom_flags(O_NONBLOCK)
461            .open(path)
462            .map_err(|e| DeviceOpError::wrap("open (O_RDONLY|O_NONBLOCK)", &label, e))?;
463        let write = OpenOptions::new()
464            .write(true)
465            .open(path)
466            .map_err(|e| DeviceOpError::wrap("open (O_WRONLY)", &label, e))?;
467        Ok(Self {
468            io: CiEndpoints::Split { write, read },
469            timings,
470            label,
471        })
472    }
473
474    /// `O_RDWR` first, the split open only if that fails with `EINVAL`
475    /// (`open_duplex` is a parameter so the fallback is testable without a
476    /// device that rejects `O_RDWR`).
477    fn open_with(
478        path: &Path,
479        timings: CiDataTimings,
480        open_duplex: impl FnOnce(&Path) -> io::Result<Self>,
481    ) -> io::Result<Self> {
482        match open_duplex(path) {
483            Ok(dev) => Ok(dev),
484            Err(e) if DeviceOpError::errno_of(&e) == Some(Errno::INVAL.raw_os_error()) => {
485                Self::open_split_path(path, timings)
486            }
487            Err(e) => Err(e),
488        }
489    }
490
491    /// Open `/dev/dvb/adapter{adapter}/ci{ci}`: `O_RDWR | O_NONBLOCK`, and on
492    /// `EINVAL` (the Digital Devices CXD2099 `ci0` — see the type docs) the
493    /// [split open](Self::open_split). Any other error is returned as is.
494    pub fn open(adapter: u32, ci: u32, timings: CiDataTimings) -> io::Result<Self> {
495        let path = format!("/dev/dvb/adapter{adapter}/ci{ci}");
496        Self::open_with(Path::new(&path), timings, |p| Self::open_path(p, timings))
497    }
498
499    /// Open `/dev/dvb/adapter{adapter}/ci{ci}` as two one-direction
500    /// descriptors (write `O_WRONLY`, read `O_RDONLY | O_NONBLOCK`), for
501    /// drivers that reject `O_RDWR` (Digital Devices CXD2099).
502    pub fn open_split(adapter: u32, ci: u32, timings: CiDataTimings) -> io::Result<Self> {
503        let path = format!("/dev/dvb/adapter{adapter}/ci{ci}");
504        Self::open_split_path(Path::new(&path), timings)
505    }
506
507    /// Wrap an already-open CI data-plane device file. The caller is
508    /// responsible for having opened it `O_NONBLOCK` — see
509    /// `open_path` for why a blocking fd here hangs
510    /// `feed_ts` (#1066).
511    #[must_use]
512    pub fn from_file(file: File, timings: CiDataTimings) -> Self {
513        Self {
514            io: CiEndpoints::Duplex(file),
515            timings,
516            label: "CI data device (from_file)".to_owned(),
517        }
518    }
519
520    /// Wrap an already-open pair of one-direction descriptors: `write`
521    /// (`O_WRONLY`) and `read` (`O_RDONLY`). The caller is responsible for
522    /// having opened **`read` with `O_NONBLOCK`** — a blocking read fd makes
523    /// `feed_ts`'s drain loop hang (#1066) — see `open_path`.
524    #[must_use]
525    pub fn from_split(write: File, read: File, timings: CiDataTimings) -> Self {
526        Self {
527            io: CiEndpoints::Split { write, read },
528            timings,
529            label: "CI data device (from_split)".to_owned(),
530        }
531    }
532
533    fn write_file(&mut self) -> &mut File {
534        match &mut self.io {
535            CiEndpoints::Duplex(f) => f,
536            CiEndpoints::Split { write, .. } => write,
537        }
538    }
539
540    fn read_file(&mut self) -> &mut File {
541        match &mut self.io {
542            CiEndpoints::Duplex(f) => f,
543            CiEndpoints::Split { read, .. } => read,
544        }
545    }
546}
547
548/// Printable device path for [`DeviceOpError`].
549fn path_label(path: &Path) -> String {
550    path.display().to_string()
551}
552
553impl CiDataDevice for LinuxCiDataDevice {
554    fn write(&mut self, ts: &[u8]) -> io::Result<()> {
555        if !ts.len().is_multiple_of(TS_PACKET_SIZE) {
556            return Err(io::Error::new(
557                io::ErrorKind::InvalidInput,
558                "write not a multiple of 188 bytes",
559            ));
560        }
561        let label = self.label.clone();
562        let mut done = 0;
563        let mut deadline = None;
564        while done < ts.len() {
565            let end = ts.len().min(done + WRITE_CHUNK_PACKETS * TS_PACKET_SIZE);
566            let torn_packet_timeout = self.timings.torn_packet_timeout;
567            let n = write_whole_packets(self.write_file(), &ts[done..end], torn_packet_timeout)
568                .map_err(|e| {
569                    DeviceOpError::wrap(
570                        format!("write ({} of {} bytes)", done, ts.len()),
571                        &label,
572                        e,
573                    )
574                })?;
575            let want = end - done;
576            done += n;
577            if n > 0 {
578                deadline = None;
579            }
580            if n == want {
581                continue;
582            }
583            // The device is full (at a packet boundary). Wait, bounded, for it
584            // to drain; on timeout hand back the whole packets it did take so
585            // the caller can resume after the unsent tail instead of guessing.
586            let limit =
587                *deadline.get_or_insert_with(|| Instant::now() + self.timings.write_stall_timeout);
588            let left = limit.saturating_duration_since(Instant::now());
589            let writable = !left.is_zero()
590                && poll_writable(self.write_file(), left).map_err(|e| {
591                    DeviceOpError::wrap(format!("poll write ({left:?})"), &label, e)
592                })?;
593            if !writable {
594                return Err(io::Error::new(
595                    io::ErrorKind::WouldBlock,
596                    PartialWrite {
597                        written: done,
598                        requested: ts.len(),
599                        device: label,
600                    },
601                ));
602            }
603        }
604        Ok(())
605    }
606
607    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
608        if !buf.len().is_multiple_of(TS_PACKET_SIZE) {
609            return Err(io::Error::new(
610                io::ErrorKind::InvalidInput,
611                "read buffer not a multiple of 188 bytes",
612            ));
613        }
614        let cap = buf.len();
615        match self.read_file().read(buf) {
616            Ok(n) => Ok(n),
617            Err(e) if e.kind() == io::ErrorKind::WouldBlock => Ok(0),
618            Err(e) => {
619                let label = self.label.clone();
620                Err(DeviceOpError::wrap(
621                    format!("read (<= {cap} bytes)"),
622                    &label,
623                    e,
624                ))
625            }
626        }
627    }
628
629    fn poll(&mut self, timeout: Duration) -> io::Result<bool> {
630        let label = self.label.clone();
631        poll_readable(self.read_file(), timeout)
632            .map_err(|e| DeviceOpError::wrap(format!("poll ({timeout:?})"), &label, e))
633    }
634}
635
636#[cfg(test)]
637mod tests {
638    use super::*;
639
640    const TEST_TIMINGS: CiDataTimings = CiDataTimings {
641        write_stall_timeout: Duration::from_millis(50),
642        torn_packet_timeout: Duration::from_secs(2),
643    };
644    const TEST_RESET_SETTLE: Duration = Duration::from_millis(3000);
645    use std::sync::mpsc;
646
647    /// Create a fresh FIFO (named pipe) under the OS temp dir and return its
648    /// path. `mkfifo` + a FIFO's blocking-read semantics are POSIX/Linux —
649    /// matching why this whole module compiles only under
650    /// `target_os = "linux"` (crate doc) — and, unlike a Unix socketpair
651    /// wrapped in a test-defined `CiDataDevice` (flagged in review as not
652    /// biting), opening the FIFO through `LinuxCiDataDevice::open_path`
653    /// drives the actual production `open`/`read` code under test.
654    fn make_fifo() -> (test_fixtures::process::Scratch, std::path::PathBuf) {
655        let scratch = test_fixtures::process::scratch_dir("dvb-ci-runtime-c1-1066");
656        let path = scratch.join("fifo");
657        rustix::fs::mkfifoat(
658            rustix::fs::CWD,
659            &path,
660            rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR,
661        )
662        .expect("mkfifoat failed");
663        (scratch, path)
664    }
665
666    /// #1066: `open_path` must open `O_NONBLOCK`, so an empty read
667    /// returns `Ok(0)` promptly instead of blocking forever — the real bug
668    /// was `CaDescrambler::feed_ts`'s drain loop hanging on its second
669    /// `read`. A FIFO opened `O_RDWR` blocks on an empty read exactly like
670    /// the real `ciM` character device unless `O_NONBLOCK` is set, so this
671    /// is a faithful (if not identical) stand-in, unlike a socketpair with
672    /// its own test-defined `CiDataDevice` impl, which never calls the
673    /// production `open`/`read` at all.
674    ///
675    /// Removing `.custom_flags(O_NONBLOCK)` from `open_path` makes the
676    /// first `recv_timeout` below time out. Verified by hand: with that line
677    /// removed, `cargo test -p dvb-ci-runtime --all-features --locked
678    /// --target x86_64-unknown-linux-gnu` cannot be *run* on macOS at all
679    /// (this module only exists under `target_os = "linux"`, and macOS
680    /// cannot execute a Linux binary), so the removal was checked instead
681    /// with `cargo test -p dvb-ci-runtime --all-features --locked --target
682    /// x86_64-unknown-linux-gnu --no-run` (compiles either way) plus the
683    /// cross-clippy command from CLAUDE.md (lints clean either way — clippy
684    /// cannot see that the missing flag is a bug); real execution proof of
685    /// this specific assertion is Linux CI, which runs this test on every
686    /// push.
687    #[test]
688    fn read_on_empty_device_returns_immediately_not_blocking() {
689        let (_scratch, path) = make_fifo();
690        let mut dev = LinuxCiDataDevice::open_path(&path, TEST_TIMINGS).expect("open_path");
691        let mut writer = OpenOptions::new()
692            .write(true)
693            .open(&path)
694            .expect("open a second, writer-only handle on the same FIFO");
695
696        let (tx, rx) = mpsc::channel();
697        let (tx_go, rx_go) = mpsc::channel::<()>();
698        std::thread::spawn(move || {
699            let mut buf = [0u8; TS_PACKET_SIZE];
700            let r0 = dev.read(&mut buf).map(|n| (n, buf));
701            if tx.send(r0).is_err() {
702                return;
703            }
704            if rx_go.recv().is_err() {
705                return;
706            }
707
708            let r1 = dev.read(&mut buf).map(|n| (n, buf));
709            if tx.send(r1).is_err() {
710                return;
711            }
712            if rx_go.recv().is_err() {
713                return;
714            }
715
716            let r2 = dev.read(&mut buf).map(|n| (n, buf));
717            let _ = tx.send(r2);
718        });
719
720        // 1: empty device (writer end open, no data written yet) — must
721        // return `Ok(0)` promptly, not block.
722        let first = rx.recv_timeout(Duration::from_secs(1));
723        let Ok(Ok((n0, _))) = first else {
724            // The reader thread may be stuck in a blocking `read`; write a
725            // byte so it can still unblock and exit, then fail.
726            let _ = writer.write_all(&[0u8; TS_PACKET_SIZE]);
727            panic!(
728                "empty-device read did not return promptly (blocked past 1s) — \
729                 got {first:?}; this is the #1066 hang O_NONBLOCK fixes"
730            );
731        };
732        assert_eq!(n0, 0, "empty device must read 0 bytes");
733
734        // 2: write one full packet BEFORE letting the reader proceed, so
735        // there is no race between the write and the second `read`.
736        let mut packet = [0xAAu8; TS_PACKET_SIZE];
737        packet[0] = 0x47; // MPEG-2 TS sync byte — realism only, not checked by read().
738        writer.write_all(&packet).expect("write one packet");
739        tx_go.send(()).expect("reader thread must still be alive");
740
741        let (n1, buf1) = rx
742            .recv_timeout(Duration::from_secs(1))
743            .expect("reader thread must respond promptly")
744            .expect("read must not error");
745        assert_eq!(n1, TS_PACKET_SIZE, "must read exactly one packet's worth");
746        assert_eq!(
747            &buf1[..n1],
748            &packet[..],
749            "must read back the exact bytes written"
750        );
751
752        // 3: drained again — back to `Ok(0)`, not blocking.
753        tx_go.send(()).expect("reader thread must still be alive");
754        let (n2, _) = rx
755            .recv_timeout(Duration::from_secs(1))
756            .expect("empty-again read did not return promptly (blocked past 1s)")
757            .expect("read must not error");
758        assert_eq!(n2, 0, "device must read 0 again once drained");
759    }
760
761    /// A packet of recognisable bytes.
762    fn packet(fill: u8) -> [u8; TS_PACKET_SIZE] {
763        let mut p = [fill; TS_PACKET_SIZE];
764        p[0] = 0x47;
765        p
766    }
767
768    /// Run `f` on a thread and fail if it has not finished in `limit` - a
769    /// read that blocks forever (the #1066 hang) must fail the test, not hang
770    /// the suite. A stuck thread is unblocked through `unstick` so it can exit.
771    fn within<T: Send + 'static>(
772        limit: Duration,
773        unstick: impl FnOnce(),
774        f: impl FnOnce() -> T + Send + 'static,
775    ) -> T {
776        let (tx, rx) = mpsc::channel();
777        std::thread::spawn(move || {
778            let _ = tx.send(f());
779        });
780        match rx.recv_timeout(limit) {
781            Ok(v) => v,
782            Err(_) => {
783                unstick();
784                panic!("operation did not return within {limit:?} (blocked)");
785            }
786        }
787    }
788
789    /// CXD2099 `ci0` rejects `O_RDWR`; the device is two one-direction fds.
790    /// The FIFO is blocking-faithful: a read on an empty FIFO whose write end
791    /// is open never returns 0 (it blocks) unless the fd is `O_NONBLOCK`. A
792    /// `feed_ts`-style drain loop (`read` until `0`) over the split read side
793    /// must therefore terminate, deliver exactly what was written, and each
794    /// call must come back promptly.
795    #[test]
796    fn split_read_side_is_nonblocking_and_a_drain_loop_terminates() {
797        let (_scratch, path) = make_fifo();
798        // The open itself is bounded too: a blocking read-only open of a FIFO
799        // with no writer yet sleeps, which is the same hang in another place.
800        let open_path = path.clone();
801        let mut dev = within(
802            Duration::from_secs(2),
803            || {},
804            move || {
805                LinuxCiDataDevice::open_split_path(&open_path, TEST_TIMINGS).expect("split open")
806            },
807        );
808        // Loop the FIFO back: what the write fd writes, the read fd reads.
809        dev.write(&packet(0xA1)).expect("write packet 1");
810        dev.write(&packet(0xB2)).expect("write packet 2");
811
812        let drained = within(
813            Duration::from_secs(2),
814            || {},
815            move || {
816                let mut got = Vec::new();
817                let mut buf = [0u8; TS_PACKET_SIZE];
818                loop {
819                    let n = dev.read(&mut buf).expect("read");
820                    if n == 0 {
821                        break;
822                    }
823                    assert_eq!(n, TS_PACKET_SIZE);
824                    got.push(buf);
825                }
826                // And once more on the now-empty device: still prompt, still 0.
827                assert_eq!(dev.read(&mut buf).expect("read"), 0);
828                got
829            },
830        );
831        assert_eq!(drained, vec![packet(0xA1), packet(0xB2)]);
832    }
833
834    /// The control that proves the mock is blocking-faithful and the test
835    /// above bites: the same loopback with a read fd opened WITHOUT
836    /// `O_NONBLOCK` (what `from_split` documents as the caller's mistake)
837    /// blocks on the empty read instead of returning 0.
838    #[test]
839    fn split_with_a_blocking_read_fd_would_hang_the_drain_loop() {
840        let (_scratch, path) = make_fifo();
841        // Open the write end first (O_RDWR on a FIFO never blocks) so the
842        // blocking read-only open below finds a writer instead of waiting.
843        let write = OpenOptions::new()
844            .read(true)
845            .write(true)
846            .open(&path)
847            .expect("write open");
848        let read = OpenOptions::new()
849            .read(true)
850            .open(&path)
851            .expect("blocking read-only open");
852        // Keep a handle to unblock the stuck reader afterwards.
853        let unblock = write.try_clone().expect("clone write fd");
854        let mut dev = LinuxCiDataDevice::from_split(write, read, TEST_TIMINGS);
855        dev.write(&packet(0xC3)).expect("write");
856
857        let (tx, rx) = mpsc::channel();
858        std::thread::spawn(move || {
859            let mut buf = [0u8; TS_PACKET_SIZE];
860            let first = dev.read(&mut buf); // the written packet
861            let _ = tx.send(first);
862            let second = dev.read(&mut buf); // empty: a blocking fd sleeps here
863            let _ = tx.send(second);
864        });
865        assert_eq!(
866            rx.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(),
867            TS_PACKET_SIZE
868        );
869        assert!(
870            rx.recv_timeout(Duration::from_millis(400)).is_err(),
871            "a blocking read fd must NOT return on an empty FIFO - the mock is not blocking-faithful"
872        );
873        // Unblock the reader thread so the process can exit cleanly.
874        let mut unblock = unblock;
875        let _ = unblock.write_all(&packet(0xD4));
876    }
877
878    /// `open` falls back to the split open when `O_RDWR` fails with `EINVAL` -
879    /// and the fallback device really works (loopback through the FIFO).
880    #[test]
881    fn open_falls_back_to_split_on_einval_only() {
882        let (_scratch, path) = make_fifo();
883        let mut dev = LinuxCiDataDevice::open_with(&path, TEST_TIMINGS, |_| {
884            Err(io::Error::from_raw_os_error(Errno::INVAL.raw_os_error()))
885        })
886        .expect("EINVAL on O_RDWR must fall back to the split open");
887        assert!(matches!(dev.io, CiEndpoints::Split { .. }));
888        dev.write(&packet(0xE5)).expect("write");
889        let mut buf = [0u8; TS_PACKET_SIZE];
890        assert_eq!(dev.read(&mut buf).expect("read"), TS_PACKET_SIZE);
891        assert_eq!(buf, packet(0xE5));
892
893        // A wrapped EINVAL (what `open_path` produces) triggers it too.
894        let wrapped = LinuxCiDataDevice::open_with(&path, TEST_TIMINGS, |p| {
895            Err(DeviceOpError::wrap(
896                "open (O_RDWR|O_NONBLOCK)",
897                &path_label(p),
898                io::Error::from_raw_os_error(Errno::INVAL.raw_os_error()),
899            ))
900        })
901        .expect("wrapped EINVAL must fall back too");
902        assert!(matches!(wrapped.io, CiEndpoints::Split { .. }));
903
904        // Any other error is NOT papered over with a split open.
905        for errno in [
906            Errno::NOENT.raw_os_error(),
907            Errno::ACCESS.raw_os_error(),
908            Errno::BUSY.raw_os_error(),
909            Errno::NODEV.raw_os_error(),
910        ] {
911            let err = LinuxCiDataDevice::open_with(&path, TEST_TIMINGS, |_| {
912                Err(io::Error::from_raw_os_error(errno))
913            })
914            .expect_err("a non-EINVAL open error must propagate");
915            assert_eq!(DeviceOpError::errno_of(&err), Some(errno));
916        }
917    }
918
919    /// When `O_RDWR` works (the common case) `open_with` keeps the duplex fd.
920    #[test]
921    fn open_keeps_the_duplex_fd_when_rdwr_works() {
922        let (_scratch, path) = make_fifo();
923        let dev = LinuxCiDataDevice::open_with(&path, TEST_TIMINGS, |p| {
924            LinuxCiDataDevice::open_path(p, TEST_TIMINGS)
925        })
926        .expect("duplex open");
927        assert!(matches!(dev.io, CiEndpoints::Duplex(_)));
928    }
929
930    /// A failing device operation names the operation, the device and the
931    /// errno, keeps the original `ErrorKind`, and still answers the errno.
932    #[test]
933    fn device_errors_carry_operation_device_and_errno() {
934        let scratch = test_fixtures::process::scratch_dir("dvb-ci-runtime-h1-ctx");
935        let path = scratch.join("file");
936        // A read-only regular file: writing to it fails (EBADF on Linux).
937        std::fs::write(&path, b"x").expect("stage file");
938        let file = OpenOptions::new()
939            .read(true)
940            .open(&path)
941            .expect("open read-only");
942        let mut dev = LinuxCaDevice::from_file(file, 2, TEST_RESET_SETTLE);
943        let err = dev
944            .write(&[0xA0, 0x01, 0x01])
945            .expect_err("write to a read-only fd must fail");
946        let text = err.to_string();
947        assert!(
948            text.contains("write (5 byte frame: slot 2, connection 1)"),
949            "{text}"
950        );
951        assert!(text.contains("CA device (slot 2, from_file)"), "{text}");
952        assert!(text.contains("os error"), "{text}");
953        assert_eq!(
954            DeviceOpError::errno_of(&err),
955            Some(Errno::BADF.raw_os_error())
956        );
957        assert_eq!(
958            err.kind(),
959            io::Error::from_raw_os_error(Errno::BADF.raw_os_error()).kind()
960        );
961    }
962
963    /// r10-W-2: a kernel frame that exactly fills [`MAX_CA_FRAME`] must be
964    /// reported as an error (possible truncation), not silently accepted as
965    /// a complete TPDU. A regular file lets us stage exactly that many bytes
966    /// without needing real CI hardware.
967    #[test]
968    fn read_rejects_a_frame_that_fills_the_scratch_buffer() {
969        let scratch = test_fixtures::process::scratch_dir("dvb-ci-runtime-w2-fullframe");
970        let path = scratch.join("file");
971        std::fs::write(&path, vec![0xAAu8; MAX_CA_FRAME]).expect("stage a MAX_CA_FRAME-byte file");
972        let file = OpenOptions::new()
973            .read(true)
974            .write(true)
975            .open(&path)
976            .expect("open the staged file");
977        let mut dev = LinuxCaDevice::from_file(file, 0, TEST_RESET_SETTLE);
978        let mut buf = [0u8; 8192];
979        let err = dev
980            .read(&mut buf)
981            .expect_err("a full-buffer read must error");
982        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
983    }
984
985    /// REVIEW (failing): r10-W-2 sized the scratch frame so no legal TPDU is
986    /// truncated, but `read` then copies `min(tpdu.len(), buf.len())` into
987    /// the caller's buffer and returns `Ok` — a caller supplying a 4096-byte
988    /// buffer would then receive a 5000-byte TPDU silently truncated, the
989    /// exact failure r10-W-2 set out to remove.
990    #[test]
991    fn read_does_not_silently_truncate_a_tpdu_larger_than_the_callers_buffer() {
992        let scratch = test_fixtures::process::scratch_dir("dvb-ci-runtime-review-trunc");
993        let path = scratch.join("file");
994        let mut frame = vec![0x00, 0x01];
995        frame.extend(std::iter::repeat_n(0xAB, 5000));
996        std::fs::write(&path, &frame).expect("stage a 5000-byte TPDU frame");
997        let file = OpenOptions::new()
998            .read(true)
999            .write(true)
1000            .open(&path)
1001            .expect("open the staged file");
1002        let mut dev = LinuxCaDevice::from_file(file, 0, TEST_RESET_SETTLE);
1003        let mut buf = [0u8; 4096]; // a caller buffer smaller than the TPDU
1004        let r = dev.read(&mut buf);
1005        assert!(
1006            r.is_err(),
1007            "a 5000-byte TPDU read into a 4096-byte buffer must not be returned as Ok({:?})",
1008            r.ok()
1009        );
1010    }
1011
1012    /// REVIEW (failing): the duplex CI data fd is `O_NONBLOCK` (#1066), so
1013    /// `write_all` stops with `WouldBlock` after a *partial* write once the
1014    /// device buffer fills. The error carries no byte count, so the caller
1015    /// cannot resume, and the stream is left misaligned mid-TS-packet. A
1016    /// FIFO's 64 KiB buffer is not a multiple of 188, so 400 packets written
1017    /// at once leave a torn packet behind.
1018    #[test]
1019    fn duplex_write_never_leaves_a_partial_ts_packet_in_the_device() {
1020        let (_scratch, path) = make_fifo();
1021        let mut dev = LinuxCiDataDevice::open_path(&path, TEST_TIMINGS).expect("open_path");
1022        let mut reader = OpenOptions::new()
1023            .read(true)
1024            .custom_flags(O_NONBLOCK)
1025            .open(&path)
1026            .expect("second reader");
1027        let burst: Vec<u8> = (0..400).flat_map(|i| packet(i as u8)).collect();
1028        let res = dev.write(&burst);
1029        let mut got = Vec::new();
1030        let mut chunk = [0u8; 4096];
1031        loop {
1032            match reader.read(&mut chunk) {
1033                Ok(0) => break,
1034                Ok(n) => got.extend_from_slice(&chunk[..n]),
1035                Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
1036                Err(e) => panic!("{e}"),
1037            }
1038        }
1039        assert_eq!(
1040            got.len() % TS_PACKET_SIZE,
1041            0,
1042            "write returned {res:?} after putting {} bytes (not whole packets) on the device",
1043            got.len()
1044        );
1045    }
1046
1047    /// Sanity: an ordinary short frame still reads through unaffected.
1048    #[test]
1049    fn read_still_returns_short_frames_normally() {
1050        let scratch = test_fixtures::process::scratch_dir("dvb-ci-runtime-w2-shortframe");
1051        let path = scratch.join("file");
1052        // link header (slot, connection_id) + a 3-byte "TPDU".
1053        std::fs::write(&path, [0x00, 0x01, 0xDE, 0xAD, 0xBE]).expect("stage a short file");
1054        let file = OpenOptions::new()
1055            .read(true)
1056            .write(true)
1057            .open(&path)
1058            .expect("open the staged file");
1059        let mut dev = LinuxCaDevice::from_file(file, 0, TEST_RESET_SETTLE);
1060        let mut buf = [0u8; 16];
1061        let n = dev.read(&mut buf).expect("short read must succeed");
1062        assert_eq!(n, 3);
1063        assert_eq!(&buf[..3], &[0xDE, 0xAD, 0xBE]);
1064    }
1065
1066    /// r10-W-3: `CA_GET_SLOT_INFO` returning `ENOTTY` (the driver — or, here,
1067    /// a plain regular file standing in for one that doesn't support the
1068    /// ioctl at all — has no CI-slot ioctl handling) must still fall back to
1069    /// "present + ready", exactly as the documented EINVAL fallback did. A
1070    /// regular file is a faithful stand-in: `ioctl` on a non-device fd
1071    /// reliably returns `ENOTTY` on Linux, so this exercises the real
1072    /// `libc::ioctl` call and its errno branch, not a mocked one.
1073    #[test]
1074    fn slot_info_falls_back_on_enotty() {
1075        let scratch = test_fixtures::process::scratch_dir("dvb-ci-runtime-w3-slotinfo");
1076        let path = scratch.join("file");
1077        let file = OpenOptions::new()
1078            .read(true)
1079            .write(true)
1080            .create(true)
1081            .truncate(true)
1082            .open(&path)
1083            .expect("create a regular file to stand in for the CA device");
1084        let mut dev = LinuxCaDevice::from_file(file, 3, TEST_RESET_SETTLE);
1085        let info = dev.slot_info().expect("ENOTTY must fall back, not error");
1086        assert_eq!(info.num, 3);
1087        assert!(info.module_present);
1088        assert!(info.module_ready);
1089    }
1090    fn poll_file(file: &File, timeout: Duration) -> io::Result<bool> {
1091        poll_readable(file, timeout)
1092    }
1093
1094    /// `poll_readable` on an empty FIFO with a short timeout reports `false`
1095    /// after about that long; with data it reports `true` immediately.
1096    #[test]
1097    fn poll_readable_reports_data_and_honours_the_timeout() {
1098        let (_scratch, path) = make_fifo();
1099        let mut dev = LinuxCiDataDevice::open_path(&path, TEST_TIMINGS).expect("open_path");
1100        let mut writer = OpenOptions::new().write(true).open(&path).expect("writer");
1101
1102        let start = std::time::Instant::now();
1103        assert!(
1104            !dev.poll(Duration::from_millis(80)).unwrap(),
1105            "empty FIFO is not readable"
1106        );
1107        assert!(
1108            start.elapsed() >= Duration::from_millis(70),
1109            "poll returned before its timeout"
1110        );
1111
1112        writer.write_all(&[0x47; TS_PACKET_SIZE]).unwrap();
1113        let start = std::time::Instant::now();
1114        assert!(
1115            dev.poll(Duration::from_secs(5)).unwrap(),
1116            "data written: readable"
1117        );
1118        assert!(
1119            start.elapsed() < Duration::from_secs(4),
1120            "must return as soon as readable"
1121        );
1122    }
1123
1124    /// A zero timeout never blocks.
1125    #[test]
1126    fn poll_readable_zero_timeout_does_not_block() {
1127        let (_scratch, path) = make_fifo();
1128        let mut dev = LinuxCiDataDevice::open_path(&path, TEST_TIMINGS).expect("open_path");
1129        let _writer = OpenOptions::new().write(true).open(&path).expect("writer");
1130        let start = std::time::Instant::now();
1131        assert!(!dev.poll(Duration::ZERO).unwrap());
1132        assert!(start.elapsed() < Duration::from_millis(500));
1133    }
1134
1135    /// Sub-millisecond timeouts used to truncate to `poll(.., 0)` (returning
1136    /// at once); they must now sleep their true duration and never error.
1137    #[test]
1138    fn poll_readable_sub_millisecond_timeout_keeps_its_duration() {
1139        let (_scratch, path) = make_fifo();
1140        let mut dev = LinuxCiDataDevice::open_path(&path, TEST_TIMINGS).expect("open_path");
1141        let _writer = OpenOptions::new().write(true).open(&path).expect("writer");
1142        let start = std::time::Instant::now();
1143        assert!(!dev.poll(Duration::from_micros(300)).unwrap());
1144        assert!(
1145            start.elapsed() >= Duration::from_micros(250),
1146            "a 300 us timeout was truncated: returned after {:?}",
1147            start.elapsed()
1148        );
1149    }
1150
1151    /// Hang-up without data (writer closed) is not "readable" for this API:
1152    /// the old code tested `revents & POLLIN` only. The device itself opens
1153    /// the FIFO `O_RDWR` (it is its own writer, so no hang-up ever shows), so
1154    /// this drives `poll_readable` on a separate read-only descriptor, and
1155    /// proves with a raw `rustix::event::poll` that the kernel really reports POLLHUP
1156    /// there (otherwise the assertion would be vacuous).
1157    #[test]
1158    fn poll_readable_ignores_hangup_without_data() {
1159        let (_scratch, path) = make_fifo();
1160        let reader = OpenOptions::new()
1161            .read(true)
1162            .custom_flags(O_NONBLOCK)
1163            .open(&path)
1164            .expect("read-only O_NONBLOCK open");
1165        let writer = OpenOptions::new().write(true).open(&path).expect("writer");
1166        drop(writer); // POLLHUP on the read end, no POLLIN, no data
1167
1168        let mut raw = [PollFd::new(&reader, PollFlags::IN)];
1169        let zero = Timespec {
1170            tv_sec: 0,
1171            tv_nsec: 0,
1172        };
1173        let r = rustix::event::poll(&mut raw, Some(&zero)).expect("poll");
1174        assert_eq!(r, 1, "kernel must report an event");
1175        let revents = raw[0].revents();
1176        assert!(
1177            revents.contains(PollFlags::HUP) && !revents.contains(PollFlags::IN),
1178            "precondition: POLLHUP without POLLIN, got revents={revents:?}"
1179        );
1180
1181        assert!(!poll_file(&reader, Duration::from_millis(50)).unwrap());
1182    }
1183
1184    /// Our `CaSlotInfo` must match the kernel's `struct ca_slot_info`
1185    /// (`int num; int type; unsigned int flags;`) exactly, since the ioctl
1186    /// writes it through a raw pointer and the request number encodes its size.
1187    #[test]
1188    fn ca_slot_info_matches_kernel_layout() {
1189        assert_eq!(core::mem::size_of::<CaSlotInfo>(), KERNEL_CA_SLOT_INFO_SIZE);
1190        assert_eq!(
1191            core::mem::align_of::<CaSlotInfo>(),
1192            KERNEL_CA_SLOT_INFO_ALIGN
1193        );
1194    }
1195
1196    // r10-W-1: the request numbers the kernel's `dvb_ca_en50221` `ioctl`
1197    // handler dispatches on, per target architecture. Linux does not have one
1198    // `_IOC` layout: asm-generic targets (x86, arm, aarch64, riscv, s390x, ...)
1199    // use `dir << 30 | size << 16 | type << 8 | nr` with `_IOC_READ = 2`;
1200    // mips/powerpc/sparc use `dir << 29` (3 direction bits, 13 size bits) with
1201    // `_IOC_NONE = 1`, `_IOC_READ = 2`. The expected values are the well-known
1202    // ones for `uapi/linux/dvb/ca.h`'s `_IO('o', 128)` and
1203    // `_IOR('o', 130, ca_slot_info_t)` (12-byte struct). A hand-rolled
1204    // asm-generic encoding fails the second block.
1205    //
1206    // Compile-time asserts, so `cargo check --tests --target <arch>` verifies
1207    // an architecture whose test binary cannot be run on the build host.
1208    #[cfg(not(any(
1209        target_arch = "mips",
1210        target_arch = "mips32r6",
1211        target_arch = "mips64",
1212        target_arch = "mips64r6",
1213        target_arch = "powerpc",
1214        target_arch = "powerpc64",
1215        target_arch = "sparc",
1216        target_arch = "sparc64"
1217    )))]
1218    const _: () = {
1219        assert!(CA_RESET == 0x0000_6F80);
1220        assert!(CA_GET_SLOT_INFO == 0x800C_6F82);
1221    };
1222    #[cfg(any(
1223        target_arch = "mips",
1224        target_arch = "mips32r6",
1225        target_arch = "mips64",
1226        target_arch = "mips64r6",
1227        target_arch = "powerpc",
1228        target_arch = "powerpc64",
1229        target_arch = "sparc",
1230        target_arch = "sparc64"
1231    ))]
1232    const _: () = {
1233        assert!(CA_RESET == 0x2000_6F80);
1234        assert!(CA_GET_SLOT_INFO == 0x400C_6F82);
1235    };
1236}