forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

child.rs555 lines, 20.8 KiBHistoryRawDownload
1//! The hardware child: the one process that opens a video driver.
2//!
3//! `hw-child` is started by `engine::hw` (decode and caps) and
4//! `engine::hwproc` (encode) with a mode as its first argument and one end of a
5//! socket pair as its standard input. It holds the socket until the parent
6//! closes it, and then it exits; the parent's `PR_SET_PDEATHSIG` covers the
7//! other way round, so neither side outlives the other.
8//!
9//! Modes:
10//!
11//! * `caps` -- answers the driver's capability query and exits.
12//! * `decode <path> <target_sample>` -- opens the file for decode at the sample
13//! and then answers one request at a time (see the wire below).
14//! * `encode <open argv...>` -- opens one encode seat and answers one request at
15//! a time, exactly as the encode half of [`engine::hwproc`] describes.
16//!
17//! Replies use [`engine::hwproc::send_reply`]: a tag byte that carries any
18//! descriptors, then `u32` length and body for `R_AU` and `R_ERR`. A
19//! decode session's pictures are packed I420 in a shared memfd (the staging
20//! buffer) or, when the encoder can take them in place, DRM-PRIME buffers sent
21//! as descriptors. Nothing else crosses the socket.
22//!
23//! Decode wire, after the open reply (`R_AU`, the 36-byte meta from
24//! [`engine::hw::meta_to_wire`], with the staging memfd attached):
25//!
26//! * `T_NEXT` (no body) answers `R_NONE` at end of stream, `R_ERR` with the
27//! message on failure, or `R_AU` with `K_PIXELS` + `w` + `h` (u32 LE each),
28//! the picture in the staging buffer. The staging fd rides on the reply
29//! again only when the buffer had to grow.
30//! * `T_NEXT_DMA` (body: coded width, coded height, width, height as u32 LE)
31//! answers the same, except that the picture may come back as `K_DMA` + the
32//! descriptor of [`engine::hwproc::DMA_BODY`], with one or two DRM-PRIME
33//! descriptors riding on the tag byte.
34//! * `T_SEEK` (body: 1-based target sample, u32 LE) answers `R_AU` with an
35//! empty body or `R_ERR`.
36//!
37//! The child answers exactly one reply per request and never two at once. Any
38//! request tag it does not know, or a socket that closes, ends the process.
39//!
40//! Three environment variables exist only for the tests that prove the
41//! containment, and are read here and nowhere else (encode mode only):
42//!
43//! * `VE_HW_TEST_FAKE` -- open a stand-in seat that touches no driver. Refuses
44//! to open unless one of the two below is set with it.
45//! * `VE_HW_TEST_ABORT=<init|drain|N>` -- `abort()` from a thread of our own at
46//! that point.
47//! * `VE_HW_TEST_HANG=<init|drain|N>` -- stop answering at that point.
48
49use std::ffi::OsString;
50use std::io::{Read, Write};
51use std::os::fd::{AsFd, AsRawFd, OwnedFd, RawFd};
52use std::os::unix::net::UnixStream;
53use std::path::PathBuf;
54
55use engine::hw::{DmaFrame, VhDma, meta_to_wire};
56use engine::hwproc::{
57 DMA_BODY, K_DMA, K_PIXELS, K_PIXELS16, Open, R_AU, R_ERR, R_NONE, Shm, T_DMA, T_DRAIN, T_ENCODE, T_ENCODE16, T_GEOM,
58 T_NEXT, T_NEXT_DMA, T_NEXT_DMA16, T_NEXT_WIDE, T_SEEK, die_with_parent, recv_tag, send_msg, send_reply,
59};
60
61use crate::enc_ec::EcEncSession;
62use crate::{OpenSession, VA_FOURCC_NV12, VA_FOURCC_P010, query_caps};
63
64/// The entry point of the `hw-child` binary.
65pub fn main() {
66 die_with_parent();
67 let mut args = std::env::args_os().skip(1);
68 let mode = args.next().unwrap_or_default();
69 let rest: Vec<OsString> = args.collect();
70 // The socket is the child's standard input, as the parent made it. A second
71 // descriptor for the same socket is taken, so standard input stays as is.
72 let stdin = std::io::stdin();
73 let Ok(sock_fd) = stdin.as_fd().try_clone_to_owned() else {
74 eprintln!("hw-child: no socket on standard input");
75 std::process::exit(2);
76 };
77 let mut sock = UnixStream::from(sock_fd);
78 match mode.to_str() {
79 Some("caps") => caps(&mut sock),
80 Some("decode") => decode(&mut sock, &rest),
81 Some("encode") => encode(&mut sock, &rest),
82 _ => {
83 eprintln!("hw-child: bad arguments");
84 std::process::exit(2);
85 }
86 }
87}
88
89/// Answers the capability query: decode, encode and 10-bit decode, each a u32
90/// LE, or `R_NONE` where there is no display to ask.
91fn caps(sock: &mut UnixStream) {
92 let _ = match query_caps() {
93 Some(caps) => {
94 let mut body = Vec::with_capacity(12);
95 for word in [caps.decode, caps.encode, caps.decode_10bit] {
96 body.extend_from_slice(&word.to_le_bytes());
97 }
98 send_reply(sock, R_AU, &body, &[])
99 }
100 None => send_reply(sock, R_NONE, &[], &[]),
101 };
102}
103
104/// Bytes of one packed I420 picture of this size.
105fn frame_len(width: u32, height: u32) -> usize {
106 let (w, h) = (width as usize, height as usize);
107 w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))
108}
109
110/// The shared buffer pictures are staged in, and how many bytes it holds.
111struct Staging {
112 shm: Shm,
113 capacity: usize,
114}
115
116/// Decode mode: open, announce, then serve requests until the socket closes.
117fn decode(sock: &mut UnixStream, args: &[OsString]) {
118 let [path, target] = args else {
119 eprintln!("hw-child: decode takes a path and a sample");
120 std::process::exit(2);
121 };
122 let Some(target) = target.to_str().and_then(|t| t.parse::<u32>().ok()) else {
123 eprintln!("hw-child: bad sample");
124 std::process::exit(2);
125 };
126 let path = PathBuf::from(path);
127 let Some(mut session) = OpenSession::open_at(&path, target) else {
128 let _ = send_reply(sock, R_NONE, &[], &[]);
129 return;
130 };
131 let meta = session.meta();
132 let (shm, fd) = match Shm::create(frame_len(meta.width, meta.height)) {
133 Ok(pair) => pair,
134 Err(e) => {
135 eprintln!("hw-child: no staging buffer: {e}");
136 let _ = send_reply(sock, R_NONE, &[], &[]);
137 return;
138 }
139 };
140 let capacity = frame_len(meta.width, meta.height);
141 if send_reply(sock, R_AU, &meta_to_wire(meta), &[fd.as_raw_fd()]).is_err() {
142 return;
143 }
144 drop(fd);
145 let mut staging = Staging { shm, capacity };
146 let mut ahead: Option<Result<bool, String>> = None;
147 let mut wide_run = 0u32;
148 loop {
149 let Ok((tag, _)) = recv_tag(sock) else {
150 // The parent closed the socket: nothing left to decode for.
151 return;
152 };
153 if tag != T_NEXT_WIDE {
154 wide_run = 0;
155 }
156 if tag == T_NEXT_DMA16
157 && let Some(pumped) = ahead.take()
158 {
159 let mut body = [0u8; 16];
160 if sock.read_exact(&mut body).is_err() || answer(sock, &mut session, &mut staging, pumped).is_err() {
161 return;
162 }
163 continue;
164 }
165 if ahead.is_some() && tag != T_NEXT_WIDE {
166 ahead = None;
167 if tag != T_SEEK {
168 if send_reply(sock, R_ERR, b"a wide picture was decoded ahead; only T_NEXT_WIDE or T_SEEK may follow", &[]).is_err() {
169 return;
170 }
171 continue;
172 }
173 }
174 let answered = match tag {
175 T_NEXT_WIDE => {
176 session.set_wide(true);
177 let pumped = ahead.take().unwrap_or_else(|| session.next_frame(None));
178 let answered = answer(sock, &mut session, &mut staging, pumped);
179 wide_run += 1;
180 if answered.is_ok() && wide_run >= 2 {
181 ahead = Some(session.next_frame(None));
182 }
183 session.set_wide(false);
184 answered
185 }
186 T_NEXT | T_NEXT_DMA | T_NEXT_DMA16 => {
187 let want = match tag {
188 T_NEXT_DMA | T_NEXT_DMA16 => {
189 let mut body = [0u8; 16];
190 if sock.read_exact(&mut body).is_err() {
191 return;
192 }
193 let word = |i: usize| {
194 u32::from_le_bytes(body[4 * i..4 * i + 4].try_into().expect("four bytes"))
195 };
196 Some(VhDma {
197 fourcc: if tag == T_NEXT_DMA16 { VA_FOURCC_P010 } else { VA_FOURCC_NV12 },
198 coded_width: word(0),
199 coded_height: word(1),
200 width: word(2),
201 height: word(3),
202 ..VhDma::default()
203 })
204 }
205 _ => None,
206 };
207 let wide = tag == T_NEXT_DMA16;
208 session.set_wide(wide);
209 let answered = frame(sock, &mut session, &mut staging, want);
210 session.set_wide(false);
211 answered
212 }
213 T_SEEK => {
214 let mut body = [0u8; 4];
215 if sock.read_exact(&mut body).is_err() {
216 return;
217 }
218 match session.seek_to(u32::from_le_bytes(body)) {
219 Ok(()) => send_reply(sock, R_AU, &[], &[]),
220 Err(e) => send_reply(sock, R_ERR, e.as_bytes(), &[]),
221 }
222 }
223 _ => return,
224 };
225 if answered.is_err() {
226 return;
227 }
228 }
229}
230
231/// Pumps one picture and sends it: as a DRM-PRIME buffer when the session left
232/// one on the GPU, otherwise as packed I420 in the staging buffer.
233fn frame(
234 sock: &mut UnixStream,
235 session: &mut OpenSession,
236 staging: &mut Staging,
237 want: Option<VhDma>,
238) -> std::io::Result<()> {
239 let pumped = session.next_frame(want);
240 answer(sock, session, staging, pumped)
241}
242
243fn answer(
244 sock: &mut UnixStream,
245 session: &mut OpenSession,
246 staging: &mut Staging,
247 pumped: Result<bool, String>,
248) -> std::io::Result<()> {
249 match pumped {
250 Ok(false) => send_reply(sock, R_NONE, &[], &[]),
251 Err(e) => send_reply(sock, R_ERR, e.as_bytes(), &[]),
252 Ok(true) => match session.take_dma() {
253 Some((desc, fds)) => send_dma(sock, &desc, &fds),
254 None => send_pixels(sock, session, staging),
255 },
256 }
257}
258
259/// `K_DMA`, the descriptor, and the buffer's descriptors on the tag byte.
260fn send_dma(sock: &mut UnixStream, desc: &VhDma, fds: &[OwnedFd]) -> std::io::Result<()> {
261 let mut body = Vec::with_capacity(1 + DMA_BODY);
262 body.push(K_DMA);
263 body.extend_from_slice(&desc.fourcc.to_le_bytes());
264 body.extend_from_slice(&desc.modifier.to_le_bytes());
265 for value in [
266 desc.coded_width,
267 desc.coded_height,
268 desc.width,
269 desc.height,
270 desc.offset[0],
271 desc.offset[1],
272 desc.stride[0],
273 desc.stride[1],
274 ] {
275 body.extend_from_slice(&value.to_le_bytes());
276 }
277 body.push(fds.len() as u8);
278 let raw: Vec<RawFd> = fds.iter().map(AsRawFd::as_raw_fd).collect();
279 send_reply(sock, R_AU, &body, &raw)
280}
281
282/// Writes the picture into the staging buffer, growing it first when it must,
283/// and answers `K_PIXELS` with its size. A grown buffer's descriptor rides on
284/// the reply so the parent maps the new one.
285fn send_pixels(
286 sock: &mut UnixStream,
287 session: &OpenSession,
288 staging: &mut Staging,
289) -> std::io::Result<()> {
290 let (picture, w, h, wide) = session.picture();
291 let needed: usize = picture.iter().map(|p| p.len()).sum();
292 let grown = if needed > staging.capacity {
293 let (shm, fd) = Shm::create(needed)?;
294 staging.shm = shm;
295 staging.capacity = needed;
296 Some(fd)
297 } else {
298 None
299 };
300 staging.shm.write_picture(&picture)?;
301 let mut body = Vec::with_capacity(9);
302 body.push(if wide { K_PIXELS16 } else { K_PIXELS });
303 body.extend_from_slice(&w.to_le_bytes());
304 body.extend_from_slice(&h.to_le_bytes());
305 let attach: Vec<RawFd> = grown.iter().map(AsRawFd::as_raw_fd).collect();
306 send_reply(sock, R_AU, &body, &attach)
307}
308
309/// Encode mode: open the seat, hand back the staging buffer, then serve encode
310/// requests until the socket closes.
311fn encode(sock: &mut UnixStream, args: &[OsString]) {
312 let strings: Option<Vec<String>> = args.iter().map(|a| a.to_str().map(str::to_owned)).collect();
313 let Some(open) = strings.as_deref().and_then(Open::from_argv) else {
314 eprintln!("hw-child: bad arguments");
315 std::process::exit(2);
316 };
317
318 reached(&At::Init);
319 let seat = match std::env::var_os("VE_HW_TEST_FAKE").is_some() {
320 // A stand-in that no test forgot to arm: without an injection point it
321 // would be an encoder producing nothing, and that is a hang of its own
322 // kind rather than a test.
323 true => match injected("VE_HW_TEST_ABORT").is_some() || injected("VE_HW_TEST_HANG").is_some()
324 {
325 true => Some(Seat::Fake),
326 false => None,
327 },
328 false => crate::open_encoder(&open).map(|encoder| Seat::Real(Box::new(encoder))),
329 };
330 let Some(mut seat) = seat else {
331 // The driver's own "no", carried back as a byte: the parent takes the
332 // software encoder.
333 let _ = std::io::Write::write_all(sock, &[0u8]);
334 std::process::exit(1);
335 };
336
337 // The staging buffer for pictures that live in memory: made here because
338 // this side knows the session's size, and handed over with the "yes".
339 let (shm, fd) = match Shm::create(open.frame_bytes()) {
340 Ok(pair) => pair,
341 Err(e) => {
342 eprintln!("hw-child: no staging buffer: {e}");
343 let _ = std::io::Write::write_all(sock, &[0u8]);
344 std::process::exit(1);
345 }
346 };
347 if send_msg(sock, &[1u8], &[fd.as_raw_fd()]).is_err() {
348 std::process::exit(1);
349 }
350 drop(fd);
351
352 let mut coded = 0u32;
353 loop {
354 let Ok((tag, fds)) = recv_tag(sock) else {
355 // The parent is gone: there is nothing left to encode for.
356 return;
357 };
358 match tag {
359 T_GEOM => match seat.dma_geometry() {
360 Some((width, height)) => {
361 let mut reply = vec![R_AU];
362 reply.extend_from_slice(&width.to_le_bytes());
363 reply.extend_from_slice(&height.to_le_bytes());
364 let _ = sock.write_all(&reply);
365 }
366 None => {
367 let _ = sock.write_all(&[R_NONE]);
368 }
369 },
370 T_ENCODE => {
371 let mut head = [0u8; 9];
372 if sock.read_exact(&mut head).is_err() {
373 return;
374 }
375 reached(&At::Frame(coded));
376 coded += 1;
377 let width = u32::from_le_bytes(head[0..4].try_into().expect("four bytes"));
378 let height = u32::from_le_bytes(head[4..8].try_into().expect("four bytes"));
379 let force_key = head[8] != 0;
380 let (w, h) = (width as usize, height as usize);
381 let chroma = w.div_ceil(2) * h.div_ceil(2);
382 let answer = match &mut seat {
383 Seat::Real(encoder) => match shm.read_bytes(w * h + 2 * chroma) {
384 Ok(frame) => {
385 let (y, rest) = frame.split_at(w * h);
386 let (u, rest) = rest.split_at(chroma);
387 encoder
388 .encode(y, u, &rest[..chroma], force_key)
389 .map(|()| encoder.next_au())
390 }
391 Err(e) => Err(format!("cannot read the staging buffer: {e}")),
392 },
393 Seat::Fake => Ok(None),
394 };
395 if !reply(sock, answer) {
396 return;
397 }
398 }
399 T_ENCODE16 => {
400 let mut head = [0u8; 9];
401 if sock.read_exact(&mut head).is_err() {
402 return;
403 }
404 reached(&At::Frame(coded));
405 coded += 1;
406 let width = u32::from_le_bytes(head[0..4].try_into().expect("four bytes"));
407 let height = u32::from_le_bytes(head[4..8].try_into().expect("four bytes"));
408 let force_key = head[8] != 0;
409 let (w, h) = (width as usize, height as usize);
410 let chroma = w.div_ceil(2) * h.div_ceil(2);
411 let answer = match &mut seat {
412 Seat::Real(encoder) => match (
413 shm.read_u16(0, w * h),
414 shm.read_u16(2 * w * h, chroma),
415 shm.read_u16(2 * (w * h + chroma), chroma),
416 ) {
417 (Ok(y), Ok(u), Ok(v)) => {
418 encoder
419 .encode16_owned(y, u, v, force_key)
420 .map(|()| encoder.next_au())
421 }
422 (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => Err(format!("cannot read the staging buffer: {e}")),
423 },
424 Seat::Fake => Ok(None),
425 };
426 if !reply(sock, answer) {
427 return;
428 }
429 }
430 T_DMA => {
431 let mut head = [0u8; 46];
432 if sock.read_exact(&mut head).is_err() {
433 return;
434 }
435 reached(&At::Frame(coded));
436 coded += 1;
437 let u32_at = |offset: usize| {
438 u32::from_le_bytes(head[offset..offset + 4].try_into().expect("four bytes"))
439 };
440 let desc = VhDma {
441 fourcc: u32_at(0),
442 modifier: u64::from_le_bytes(head[4..12].try_into().expect("eight bytes")),
443 coded_width: u32_at(12),
444 coded_height: u32_at(16),
445 width: u32_at(20),
446 height: u32_at(24),
447 offset: [u32_at(28), u32_at(32)],
448 stride: [u32_at(36), u32_at(40)],
449 };
450 if fds.len() != head[44] as usize || fds.is_empty() {
451 if send_reply(sock, R_ERR, b"a buffer arrived without its descriptors", &[])
452 .is_err()
453 {
454 return;
455 }
456 continue;
457 }
458 // The descriptors are ours from here: the parent kept its own.
459 let frame = DmaFrame { desc, fds };
460 let answer = match &mut seat {
461 Seat::Real(encoder) => encoder
462 .encode_dma(&frame, head[45] != 0)
463 .map(|()| encoder.next_au()),
464 Seat::Fake => Ok(None),
465 };
466 if !reply(sock, answer) {
467 return;
468 }
469 }
470 T_DRAIN => {
471 reached(&At::Drain);
472 let answer = match &mut seat {
473 Seat::Real(encoder) => encoder.flush().map(|()| encoder.next_au()),
474 Seat::Fake => Ok(None),
475 };
476 if !reply(sock, answer) {
477 return;
478 }
479 }
480 _ => return,
481 }
482 }
483}
484
485/// Where the encoder is: the driver's, or the test stand-in that opens none.
486enum Seat {
487 Real(Box<EcEncSession>),
488 Fake,
489}
490
491impl Seat {
492 fn dma_geometry(&self) -> Option<(u32, u32)> {
493 match self {
494 Self::Real(encoder) => encoder.coded_size(),
495 // Nothing to import into, so the parent stages pictures instead.
496 Self::Fake => None,
497 }
498 }
499}
500
501/// One of the three injection points, named the same way in all three variables.
502#[derive(PartialEq, Eq)]
503enum At {
504 Init,
505 Drain,
506 Frame(u32),
507}
508
509fn injected(var: &str) -> Option<At> {
510 let value = std::env::var(var).ok()?;
511 Some(match value.as_str() {
512 "init" => At::Init,
513 "drain" => At::Drain,
514 _ => At::Frame(value.parse().ok()?),
515 })
516}
517
518/// The driver's own way of dying, reproduced: `abort()` from a thread that is
519/// not the one running the encode, which is where Mesa calls it from.
520fn die() {
521 std::thread::spawn(|| {
522 std::process::abort();
523 });
524 loop {
525 std::thread::park();
526 }
527}
528
529/// ...and the other half: alive, holding the socket open, answering nothing.
530fn hang() -> ! {
531 loop {
532 std::thread::park();
533 }
534}
535
536fn reached(point: &At) {
537 if injected("VE_HW_TEST_ABORT").as_ref() == Some(point) {
538 die();
539 }
540 if injected("VE_HW_TEST_HANG").as_ref() == Some(point) {
541 hang();
542 }
543}
544
545/// Writes one encode answer. `false` means the parent is gone.
546fn reply(sock: &mut UnixStream, answer: Result<Option<&[u8]>, String>) -> bool {
547 let sent = match answer {
548 Ok(None) => send_reply(sock, R_NONE, &[], &[]),
549 Ok(Some(au)) => send_reply(sock, R_AU, au, &[]),
550 // The encoder's own refusal, not a death: the parent raises it as the
551 // export error it is and this process stays open.
552 Err(e) => send_reply(sock, R_ERR, e.as_bytes(), &[]),
553 };
554 sent.is_ok()
555}