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