forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB0563cbfTahinli2 months ago824 commits

hwproc.rs729 lines, 27.7 KiBHistoryRawDownload
1//! The hardware encoder, held in a **child process**.
2//!
3//! Every entry point of the plugin catches unwinds ([`crate::hw`]), and that
4//! guarantee has a floor it cannot reach: Mesa's VA-API drivers run their own C
5//! worker threads, and `radeonsi` calls libc `abort()` from
6//! `amdgpu_ctx_set_sw_reset_status` when the video ring resets under it
7//! (measured 2026-08-13, mesa 26.1.6, `vcn_unified_0` hung during an AV1 encode
8//! submission). A foreign thread's `abort()` is not an unwind and no
9//! `catch_unwind` in this address space can see it, so the editor died with the
10//! driver and took the export -- and the session -- with it.
11//!
12//! So the driver is not in this address space any more. `HwEncoder` here is a
13//! handle on a child running `hw-encode-child`, which is the one process that
14//! `dlopen`s the plugin and therefore the only one a driver may kill. When it
15//! dies -- by `abort()`, by any signal, or by going quiet past
16//! [`Remote::deadline`] -- the parent sees a closed socket or a timed-out read,
17//! reaps the child, and reports a [`Lost`]. The export then
18//! runs again on the software encoder ([`crate::export::start`]), or refuses in
19//! words where a person picked the GPU by name.
20//!
21//! Two things cross between the processes and neither is a picture copied down a
22//! pipe. Pictures that live in memory are written into a shared anonymous file
23//! (`memfd`, mapped in both), so a frame costs one `memcpy` and a 10-byte
24//! message. Pictures still on the GPU never move at all: the DRM-PRIME
25//! descriptors travel as file descriptors over `SCM_RIGHTS`, so the zero-copy
26//! export path stays zero-copy across the process boundary.
27
28use std::ffi::c_void;
29use std::io::Read;
30use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
31use std::os::unix::net::UnixStream;
32use std::path::PathBuf;
33use std::process::{Child, Command, Stdio};
34use std::time::Duration;
35
36use crate::colorspace::{ColorDescription, Matrix, Transfer};
37use crate::hw::VhDma;
38
39/// The words every "the child is gone" error carries, for the person reading
40/// the log; what *decides* anything is [`Lost`], never this text.
41pub const HW_LOST: &str = "the hardware encoder process";
42
43/// The error a dead child carries.
44///
45/// A type and not a phrase. [`is_lost`] is what commits a whole export to being
46/// written again from the first frame ([`crate::export::start`]), and matching
47/// on words handed that decision to any future error whose message happened to
48/// mention the child -- a silent re-encode of a feature film, caused by a
49/// wording. Nothing outside this module can make one.
50#[derive(Debug)]
51pub struct Lost(String);
52
53impl std::fmt::Display for Lost {
54 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 f.write_str(&self.0)
56 }
57}
58
59impl std::error::Error for Lost {}
60
61/// Whether an error is one: a driver that took its process down, rather than a
62/// picture this engine got wrong.
63pub fn is_lost(error: &crate::Error) -> bool {
64 error.downcast_ref::<Lost>().is_some()
65}
66
67/// The helper's file name; it is built into the same directory as the editor.
68const BIN: &str = "hw-encode-child";
69
70/// Which encoder the child opens. Sent as argv, so the child needs no protocol
71/// before it has one.
72#[derive(Clone, Copy, PartialEq, Eq)]
73pub enum Seat {
74 H264,
75 Intra,
76 Av1,
77 Hevc,
78}
79
80impl Seat {
81 pub fn code(self) -> u8 {
82 match self {
83 Self::H264 => 0,
84 Self::Intra => 1,
85 Self::Av1 => 2,
86 Self::Hevc => 3,
87 }
88 }
89
90 pub fn from_code(code: u8) -> Option<Self> {
91 Some(match code {
92 0 => Self::H264,
93 1 => Self::Intra,
94 2 => Self::Av1,
95 3 => Self::Hevc,
96 _ => return None,
97 })
98 }
99}
100
101/// Everything an open needs, in one place because it travels as argv and comes
102/// back as a struct on the other side.
103#[derive(Clone, Copy)]
104pub struct Open {
105 pub seat: Seat,
106 pub width: u32,
107 pub height: u32,
108 pub fps_num: u32,
109 pub fps_den: u32,
110 pub bitrate: u64,
111 /// What the sequence header will say the samples mean. Only the HEVC seat
112 /// takes one; the others ignore it.
113 pub colour: ColorDescription,
114}
115
116impl Open {
117 fn argv(&self) -> Vec<String> {
118 let (matrix, transfer) = (
119 match self.colour.matrix {
120 Matrix::Bt709 => 0,
121 Matrix::Bt601 => 1,
122 Matrix::Bt2020Ncl => 2,
123 },
124 match self.colour.transfer {
125 Transfer::Sdr => 0,
126 Transfer::Pq => 1,
127 Transfer::Hlg => 2,
128 },
129 );
130 [
131 u32::from(self.seat.code()),
132 self.width,
133 self.height,
134 self.fps_num,
135 self.fps_den,
136 matrix,
137 transfer,
138 u32::from(self.colour.full_range),
139 ]
140 .iter()
141 .map(u32::to_string)
142 .chain(std::iter::once(self.bitrate.to_string()))
143 .collect()
144 }
145
146 /// The other half of [`Open::argv`], in the child.
147 pub fn from_argv(args: &[String]) -> Option<Self> {
148 let n = |i: usize| args.get(i)?.parse::<u32>().ok();
149 Some(Self {
150 seat: Seat::from_code(u8::try_from(n(0)?).ok()?)?,
151 width: n(1)?,
152 height: n(2)?,
153 fps_num: n(3)?,
154 fps_den: n(4)?,
155 bitrate: args.get(8)?.parse().ok()?,
156 colour: ColorDescription {
157 matrix: match n(5)? {
158 0 => Matrix::Bt709,
159 1 => Matrix::Bt601,
160 _ => Matrix::Bt2020Ncl,
161 },
162 transfer: match n(6)? {
163 0 => Transfer::Sdr,
164 1 => Transfer::Pq,
165 _ => Transfer::Hlg,
166 },
167 full_range: n(7)? != 0,
168 },
169 })
170 }
171
172 /// How many bytes one packed I420 picture of this size takes -- the size of
173 /// the shared mapping, decided once at the open because the export feeds one
174 /// canvas size for the whole file.
175 pub fn frame_bytes(&self) -> usize {
176 let (w, h) = (self.width as usize, self.height as usize);
177 w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))
178 }
179}
180
181// Requests, parent to child.
182pub const T_ENCODE: u8 = 1;
183pub const T_DMA: u8 = 2;
184pub const T_DRAIN: u8 = 3;
185pub const T_GEOM: u8 = 4;
186// Replies, child to parent.
187pub const R_NONE: u8 = 0;
188pub const R_AU: u8 = 1;
189pub const R_ERR: u8 = 2;
190
191/// A `memfd` mapped into this process: the staging buffer one picture is written
192/// into and read out of without either side owning the other's memory.
193pub struct Shm {
194 ptr: *mut u8,
195 len: usize,
196}
197
198impl Shm {
199 /// Creates one of `len` bytes, returning it mapped plus the descriptor to
200 /// hand the other process.
201 pub fn create(len: usize) -> std::io::Result<(Self, OwnedFd)> {
202 // SAFETY: a NUL-terminated name and a flag word, which is the whole of
203 // this call's contract; the descriptor it returns is ours.
204 let fd = unsafe { libc::memfd_create(c"edith-hwenc".as_ptr(), libc::MFD_CLOEXEC) };
205 if fd < 0 {
206 return Err(std::io::Error::last_os_error());
207 }
208 // SAFETY: `fd` is a fresh descriptor nothing else holds.
209 let file = unsafe { std::fs::File::from_raw_fd(fd) };
210 file.set_len(len as u64)?;
211 let shm = Self::map(fd, len)?;
212 Ok((shm, OwnedFd::from(file)))
213 }
214
215 /// Maps a descriptor the other process created.
216 pub fn map(fd: RawFd, len: usize) -> std::io::Result<Self> {
217 // SAFETY: a shared mapping of a descriptor that is open for the call;
218 // the kernel picks the address and the length is the file's own.
219 let ptr = unsafe {
220 libc::mmap(
221 std::ptr::null_mut(),
222 len,
223 libc::PROT_READ | libc::PROT_WRITE,
224 libc::MAP_SHARED,
225 fd,
226 0,
227 )
228 };
229 if ptr == libc::MAP_FAILED {
230 return Err(std::io::Error::last_os_error());
231 }
232 Ok(Self {
233 ptr: ptr.cast(),
234 len,
235 })
236 }
237
238 /// A mapping of nothing, for the moment between spawning a child and
239 /// learning which buffer it made.
240 fn empty() -> Self {
241 Self {
242 ptr: std::ptr::null_mut(),
243 len: 0,
244 }
245 }
246
247 /// The mapping as bytes. Both processes see the same store, and the protocol
248 /// -- one request, one reply, never overlapping -- is what keeps only one of
249 /// them looking at a time.
250 pub fn bytes(&mut self) -> &mut [u8] {
251 // SAFETY: the mapping is `len` bytes long and lives as long as `self`.
252 unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
253 }
254}
255
256impl Drop for Shm {
257 fn drop(&mut self) {
258 if self.len == 0 {
259 return;
260 }
261 // SAFETY: the pair of the `mmap` above, unmapped exactly once.
262 unsafe { libc::munmap(self.ptr.cast(), self.len) };
263 }
264}
265
266// The mapping is used from one thread at a time (the export worker), as the
267// session it belongs to is.
268unsafe impl Send for Shm {}
269
270/// Sends one message with its file descriptors attached.
271///
272/// `MSG_NOSIGNAL` is the point of writing this by hand rather than
273/// [`Write::write_all`]: a child that has just died leaves a socket whose next
274/// write raises `SIGPIPE`, and a crash-containment path that kills the editor
275/// with a signal of its own would be no containment at all.
276pub fn send_msg(sock: &UnixStream, bytes: &[u8], fds: &[RawFd]) -> std::io::Result<()> {
277 debug_assert!(!bytes.is_empty(), "ancillary data rides on a real byte");
278 let mut iov = libc::iovec {
279 iov_base: bytes.as_ptr() as *mut c_void,
280 iov_len: bytes.len(),
281 };
282 // Two descriptors is the most anything here sends (a two-object NV12
283 // buffer); 64 bytes covers the header, the payload and the alignment.
284 let mut control = [0u8; 64];
285 // SAFETY: every pointer below is into a local that outlives the call, the
286 // control buffer is larger than the `CMSG_SPACE` written into
287 // `msg_controllen`, and the descriptors are open for the duration.
288 let sent = unsafe {
289 let mut msg: libc::msghdr = std::mem::zeroed();
290 msg.msg_iov = &mut iov;
291 msg.msg_iovlen = 1;
292 if !fds.is_empty() {
293 let payload = (std::mem::size_of::<RawFd>() * fds.len()) as u32;
294 msg.msg_control = control.as_mut_ptr().cast();
295 msg.msg_controllen = libc::CMSG_SPACE(payload) as _;
296 let cmsg = libc::CMSG_FIRSTHDR(&msg);
297 (*cmsg).cmsg_level = libc::SOL_SOCKET;
298 (*cmsg).cmsg_type = libc::SCM_RIGHTS;
299 (*cmsg).cmsg_len = libc::CMSG_LEN(payload) as _;
300 std::ptr::copy_nonoverlapping(
301 fds.as_ptr(),
302 libc::CMSG_DATA(cmsg).cast::<RawFd>(),
303 fds.len(),
304 );
305 }
306 libc::sendmsg(sock.as_raw_fd(), &msg, libc::MSG_NOSIGNAL)
307 };
308 match sent {
309 n if n < 0 => Err(std::io::Error::last_os_error()),
310 // Messages here are tens of bytes and a socket buffer is kilobytes, so a
311 // short send means the peer is gone rather than that we should loop.
312 n if n as usize != bytes.len() => Err(std::io::Error::new(
313 std::io::ErrorKind::WriteZero,
314 "short send",
315 )),
316 _ => Ok(()),
317 }
318}
319
320/// Reads the one byte a message's descriptors ride on, and those descriptors.
321///
322/// Ancillary data attaches to a position in the byte stream, so the tag is read
323/// with `recvmsg` and everything after it with an ordinary read.
324pub fn recv_tag(sock: &UnixStream) -> std::io::Result<(u8, Vec<OwnedFd>)> {
325 let mut byte = [0u8; 1];
326 let mut iov = libc::iovec {
327 iov_base: byte.as_mut_ptr().cast(),
328 iov_len: 1,
329 };
330 let mut control = [0u8; 64];
331 let mut fds = Vec::new();
332 // SAFETY: as `send` -- locals that outlive the call and a control buffer
333 // whose length is what `msg_controllen` claims. Every descriptor the kernel
334 // writes there is ours, and is taken by an `OwnedFd` exactly once.
335 let got = unsafe {
336 let mut msg: libc::msghdr = std::mem::zeroed();
337 msg.msg_iov = &mut iov;
338 msg.msg_iovlen = 1;
339 msg.msg_control = control.as_mut_ptr().cast();
340 msg.msg_controllen = control.len() as _;
341 let got = libc::recvmsg(sock.as_raw_fd(), &mut msg, libc::MSG_CMSG_CLOEXEC);
342 if got > 0 {
343 let mut cmsg = libc::CMSG_FIRSTHDR(&msg);
344 while !cmsg.is_null() {
345 if (*cmsg).cmsg_level == libc::SOL_SOCKET && (*cmsg).cmsg_type == libc::SCM_RIGHTS {
346 let bytes = (*cmsg).cmsg_len as usize - libc::CMSG_LEN(0) as usize;
347 let data = libc::CMSG_DATA(cmsg).cast::<RawFd>();
348 for i in 0..bytes / std::mem::size_of::<RawFd>() {
349 fds.push(OwnedFd::from_raw_fd(data.add(i).read_unaligned()));
350 }
351 }
352 cmsg = libc::CMSG_NXTHDR(&msg, cmsg);
353 }
354 }
355 got
356 };
357 match got {
358 n if n < 0 => Err(std::io::Error::last_os_error()),
359 0 => Err(std::io::Error::new(
360 std::io::ErrorKind::UnexpectedEof,
361 "peer closed",
362 )),
363 _ => Ok((byte[0], fds)),
364 }
365}
366
367/// One access unit, or the child's own error, read off the socket.
368fn read_reply(sock: &mut UnixStream, au: &mut Vec<u8>) -> std::io::Result<Option<Result<(), String>>> {
369 let (tag, _) = recv_tag(sock)?;
370 if tag == R_NONE {
371 return Ok(None);
372 }
373 let mut len = [0u8; 4];
374 sock.read_exact(&mut len)?;
375 let len = u32::from_le_bytes(len) as usize;
376 au.clear();
377 au.resize(len, 0);
378 sock.read_exact(au)?;
379 Ok(Some(match tag {
380 R_AU => Ok(()),
381 _ => Err(String::from_utf8_lossy(au).into_owned()),
382 }))
383}
384
385/// Where the helper lives: told outright, or beside the running executable --
386/// which is `target/<profile>/` for the editor and one directory up from
387/// `deps/` for a test binary.
388fn child_bin() -> Option<PathBuf> {
389 if let Some(pinned) = std::env::var_os("VE_HW_CHILD_BIN") {
390 return Some(PathBuf::from(pinned));
391 }
392 let exe = std::env::current_exe().ok()?;
393 let dir = exe.parent()?.to_path_buf();
394 [dir.join(BIN), dir.parent()?.join(BIN)]
395 .into_iter()
396 .find(|candidate| candidate.is_file())
397}
398
399/// Whether an isolated encoder can be had at all -- a helper to run. `false`
400/// leaves the caller on the in-process seat, which is what a build that did not
401/// produce the helper has always had.
402pub fn available() -> bool {
403 child_bin().is_some()
404}
405
406/// The test-only stand-in seat: a child that opens no driver at all, so the
407/// containment paths below can be exercised on a machine whose GPU is wedged --
408/// which is the only machine where they matter and the only one where the real
409/// trigger cannot be pulled.
410pub fn faked() -> bool {
411 std::env::var_os("VE_HW_TEST_FAKE").is_some()
412}
413
414/// A hardware encode session living in another process.
415pub struct Remote {
416 child: Child,
417 sock: UnixStream,
418 shm: Shm,
419 open: Open,
420 /// The last access unit, owned here: the child's buffer is in the child.
421 au: Vec<u8>,
422 /// Set the moment the child is known gone, so every later call refuses in
423 /// the same words instead of blocking on a socket nobody holds.
424 lost: Option<String>,
425 /// The slowest call this child has answered, and how many it has answered
426 /// at all: what [`Remote::deadline`] measures its patience against.
427 slowest: Duration,
428 answered: u32,
429}
430
431/// How many answered calls it takes before the wait stops being the configured
432/// ceiling and becomes this encoder's own measure, how much slower than its
433/// slowest answer a call may be before it is a wedge, and the least it is ever
434/// given.
435///
436/// The ceiling has to be generous -- an encoder opening on a 4K frame is not a
437/// dead one -- and the export spends every second of it on a child that will
438/// never answer again: the file is owed the software encoder and the wait is
439/// pure delay before it starts. The window is what shrinks, not the ceiling.
440/// Once a child has answered [`CALIBRATE`] calls, the machine has said how long
441/// its own frames take, and eight times the slowest of them (never under
442/// [`FLOOR`]) contains a wedge in two or three seconds rather than fifteen,
443/// while a slow open still gets the whole ceiling and is never killed for
444/// being slow. The editor is live throughout either way -- the wait is on the
445/// export's own thread and the card goes on repainting -- so what this buys is
446/// the delay, not the window.
447const CALIBRATE: u32 = 8;
448const SLACK: u32 = 8;
449const FLOOR: Duration = Duration::from_secs(2);
450
451impl Remote {
452 /// How long the child may take over one call before it is treated as hung.
453 /// A wedged ring does not always `abort()` -- it can simply stop -- and a
454 /// timeout is the only thing that tells those apart from a slow frame.
455 fn timeout() -> Duration {
456 let ms = std::env::var("VE_HW_TIMEOUT_MS")
457 .ok()
458 .and_then(|v| v.parse().ok())
459 .unwrap_or(15_000);
460 Duration::from_millis(ms)
461 }
462
463 /// How long the *next* call may take: the ceiling until this child has
464 /// shown what its frames cost, then its own slowest answer with room to
465 /// spare ([`CALIBRATE`]).
466 fn deadline(&self) -> Duration {
467 let ceiling = Self::timeout();
468 match self.answered >= CALIBRATE {
469 true => ceiling.min((self.slowest * SLACK).max(FLOOR)),
470 false => ceiling,
471 }
472 }
473
474 /// Starts a child on this seat. `None` is the plugin's own "no" carried
475 /// across the process boundary -- no driver, no entrypoint, a size refused
476 /// -- and the caller takes the software encoder exactly as it always did.
477 pub fn spawn(open: Open) -> Option<Self> {
478 let bin = child_bin()?;
479 let (mine, theirs) = UnixStream::pair().ok()?;
480 mine.set_read_timeout(Some(Self::timeout())).ok()?;
481 // The socket is the child's stdin, which is how it crosses `exec`
482 // without a `pre_exec` of our own. Its stdout and stderr stay ours, so
483 // whatever the driver prints is still in the editor's log.
484 let child = Command::new(bin)
485 .args(open.argv())
486 .stdin(Stdio::from(OwnedFd::from(theirs)))
487 .spawn()
488 .ok()?;
489 let mut remote = Self {
490 child,
491 sock: mine,
492 // Replaced by the child's own mapping below; a zero-length one
493 // allocates nothing and keeps the field non-optional.
494 shm: Shm::empty(),
495 open,
496 au: Vec::new(),
497 lost: None,
498 slowest: Duration::ZERO,
499 answered: 0,
500 };
501 // The child answers once its encoder is open: a byte, and with it the
502 // descriptor of the staging buffer it made for this session's size.
503 match recv_tag(&remote.sock) {
504 Ok((1, fds)) if fds.len() == 1 => {
505 remote.shm = Shm::map(fds[0].as_raw_fd(), open.frame_bytes()).ok()?;
506 Some(remote)
507 }
508 // Anything else is "no seat here", including a child that died
509 // opening the driver -- which is the crash this whole module exists
510 // for, and it costs an export nothing but the software encoder.
511 _ => None,
512 }
513 }
514
515 /// What the child's encoder codes in, or `None` where it has no zero-copy
516 /// door.
517 ///
518 /// The two `None`s are not the same thing and only one of them is an
519 /// answer. A child that *says* it has no door costs the caller a read-back
520 /// and nothing else; a child that does not answer at all is gone, and is
521 /// reaped right here -- otherwise the next picture would spend a whole
522 /// second timeout discovering what this call already knows.
523 pub fn dma_geometry(&mut self) -> Option<(u32, u32)> {
524 self.request(&[T_GEOM], &[]).ok()?;
525 let mut buf = [0u8; 8];
526 let answered = match recv_tag(&self.sock) {
527 Ok((R_AU, _)) => self.sock.read_exact(&mut buf).map(|()| true),
528 Ok(_) => Ok(false),
529 Err(e) => Err(e),
530 };
531 match answered {
532 Ok(true) => Some((
533 u32::from_le_bytes(buf[..4].try_into().ok()?),
534 u32::from_le_bytes(buf[4..].try_into().ok()?),
535 )),
536 Ok(false) => None,
537 Err(e) => {
538 self.bury(&e.to_string());
539 None
540 }
541 }
542 }
543
544 /// Feeds one packed I420 picture through the shared mapping.
545 pub fn encode(
546 &mut self,
547 y: &[u8],
548 u: &[u8],
549 v: &[u8],
550 width: u32,
551 height: u32,
552 force_key: bool,
553 ) -> crate::Result<Option<&[u8]>> {
554 let total = y.len() + u.len() + v.len();
555 if total > self.shm.len {
556 return Err(format!(
557 "a {width}x{height} picture does not fit the staging buffer opened for {}x{}",
558 self.open.width, self.open.height
559 )
560 .into());
561 }
562 let bytes = self.shm.bytes();
563 bytes[..y.len()].copy_from_slice(y);
564 bytes[y.len()..y.len() + u.len()].copy_from_slice(u);
565 bytes[y.len() + u.len()..total].copy_from_slice(v);
566 let mut msg = vec![T_ENCODE];
567 msg.extend_from_slice(&width.to_le_bytes());
568 msg.extend_from_slice(&height.to_le_bytes());
569 msg.push(u8::from(force_key));
570 self.round_trip(&msg, &[])
571 }
572
573 /// Feeds one picture the decoder left on the GPU. The descriptors go over
574 /// with the message, so the buffer itself never moves.
575 pub fn encode_dma(&mut self, dma: &VhDma, force_key: bool) -> crate::Result<Option<&[u8]>> {
576 let fds: Vec<RawFd> = dma.fd.iter().copied().filter(|&fd| fd >= 0).collect();
577 let mut msg = vec![T_DMA];
578 msg.extend_from_slice(&dma.fourcc.to_le_bytes());
579 msg.extend_from_slice(&dma.modifier.to_le_bytes());
580 for value in [
581 dma.coded_width,
582 dma.coded_height,
583 dma.width,
584 dma.height,
585 dma.offset[0],
586 dma.offset[1],
587 dma.stride[0],
588 dma.stride[1],
589 ] {
590 msg.extend_from_slice(&value.to_le_bytes());
591 }
592 msg.push(fds.len() as u8);
593 msg.push(u8::from(force_key));
594 self.round_trip(&msg, &fds)
595 }
596
597 /// Flushes the child's encoder; call until it answers `None`.
598 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
599 self.round_trip(&[T_DRAIN], &[])
600 }
601
602 /// One request and its reply, which is every call above: the child is fed,
603 /// then read, and anything that is not an answer is the child being gone.
604 fn round_trip(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result<Option<&[u8]>> {
605 // Set per call, because what it may be is measured from the calls
606 // before it ([`deadline`]).
607 let _ = self.sock.set_read_timeout(Some(self.deadline()));
608 let started = std::time::Instant::now();
609 self.request(msg, fds)?;
610 let mut au = std::mem::take(&mut self.au);
611 let read = read_reply(&mut self.sock, &mut au);
612 self.au = au;
613 if read.is_ok() {
614 self.slowest = self.slowest.max(started.elapsed());
615 self.answered += 1;
616 }
617 // Every "no access unit" leaves through a `return`, so the borrow of the
618 // buffer below is the only one alive when it is taken.
619 match read {
620 Ok(None) => return Ok(None),
621 Ok(Some(Ok(()))) => {}
622 // The child's *own* refusal: it is alive and said no, so this is an
623 // ordinary encode error and the process stays as it is.
624 Ok(Some(Err(message))) => return Err(message.into()),
625 Err(e) => return Err(self.bury(&e.to_string())),
626 }
627 Ok(Some(&self.au))
628 }
629
630 fn request(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result<()> {
631 if let Some(gone) = &self.lost {
632 return Err(Lost(gone.clone()).into());
633 }
634 match send_msg(&self.sock, msg, fds) {
635 Ok(()) => Ok(()),
636 Err(e) => Err(self.bury(&e.to_string())),
637 }
638 }
639
640 /// Reaps the child and remembers why, so no later call waits on it. Kills
641 /// first: the child may be *stuck* rather than dead, which is the hang this
642 /// timeout exists to contain, and a stuck child is never waited for.
643 fn bury(&mut self, why: &str) -> crate::Error {
644 let _ = self.child.kill();
645 let status = self.child.wait().ok();
646 // The two shapes a wedged ring takes, told apart by who did the
647 // killing: a driver that called `abort()` leaves its own signal, while
648 // a child that merely stopped answering is still holding `SIGKILL` from
649 // the line above and the read's own timeout is the real reason.
650 let how = match status.and_then(|s| std::os::unix::process::ExitStatusExt::signal(&s)) {
651 Some(libc::SIGKILL) | None => format!("stopped answering ({why}) and was killed"),
652 Some(signal) => format!("was killed by signal {signal}"),
653 };
654 let message = format!("{HW_LOST} {how}; the driver took it down and not the editor");
655 self.lost = Some(message.clone());
656 Lost(message).into()
657 }
658}
659
660impl Drop for Remote {
661 fn drop(&mut self) {
662 // Nothing is pending -- the export drains before it drops -- and a
663 // signal is the one exit a wedged child is guaranteed to take.
664 if self.lost.is_none() {
665 let _ = self.child.kill();
666 let _ = self.child.wait();
667 }
668 }
669}
670
671// As the in-process session: one thread at a time (the export worker).
672unsafe impl Send for Remote {}
673
674#[cfg(test)]
675mod tests {
676 use super::*;
677
678 /// Descriptors really cross the socket, and the mapping really is shared:
679 /// the two halves of the frame hand-off, checked without a driver.
680 #[test]
681 fn a_mapping_and_its_descriptor_cross_a_socket() {
682 let (a, b) = UnixStream::pair().expect("socketpair");
683 let (mut mine, fd) = Shm::create(64).expect("memfd");
684 mine.bytes()[..5].copy_from_slice(b"hello");
685 send_msg(&a, &[7u8], &[fd.as_raw_fd()]).expect("send");
686 let (tag, fds) = recv_tag(&b).expect("recv");
687 assert_eq!(tag, 7);
688 assert_eq!(fds.len(), 1, "the descriptor came over");
689 let mut theirs = Shm::map(fds[0].as_raw_fd(), 64).expect("map the received descriptor");
690 assert_eq!(&theirs.bytes()[..5], b"hello", "one store, two mappings");
691 theirs.bytes()[0] = b'j';
692 assert_eq!(&mine.bytes()[..5], b"jello", "and it is shared both ways");
693 }
694
695 /// A dead peer must come back as an error, never as a `SIGPIPE` that kills
696 /// the process doing the sending -- the whole point of `MSG_NOSIGNAL`.
697 #[test]
698 fn sending_to_a_closed_socket_errors_instead_of_signalling() {
699 let (a, b) = UnixStream::pair().expect("socketpair");
700 drop(b);
701 assert!(send_msg(&a, &[1u8, 2, 3], &[]).is_err());
702 }
703
704 /// The open crosses to the child as text and comes back the same struct.
705 #[test]
706 fn an_open_round_trips_through_argv() {
707 let open = Open {
708 seat: Seat::Hevc,
709 width: 1920,
710 height: 1080,
711 fps_num: 30000,
712 fps_den: 1001,
713 bitrate: 12_345_678,
714 colour: ColorDescription {
715 matrix: Matrix::Bt2020Ncl,
716 transfer: Transfer::Pq,
717 full_range: true,
718 },
719 };
720 let back = Open::from_argv(&open.argv()).expect("parse");
721 assert!(back.seat == Seat::Hevc);
722 assert_eq!(
723 (back.width, back.height, back.fps_num, back.fps_den, back.bitrate),
724 (1920, 1080, 30000, 1001, 12_345_678)
725 );
726 assert_eq!(back.colour, open.colour);
727 assert_eq!(back.frame_bytes(), 1920 * 1080 * 3 / 2);
728 }
729}