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