forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBef5832fTahinli3 months ago597 commits

hw-encode-child.rs262 lines, 10.0 KiBHistoryRawDownload
1//! The process that holds the video driver, and therefore the process a video
2//! driver is allowed to kill.
3//!
4//! It is started by [`engine::hwproc::Remote::spawn`] with the encode session's
5//! parameters as argv and one end of a socket pair as its standard input. It
6//! opens the plugin's encoder in *this* address space, hands the parent a shared
7//! anonymous file to stage pictures in, and then answers one request at a time
8//! until the socket closes. Nothing else lives here: no project, no muxer, no
9//! window -- so an `abort()` out of Mesa's own worker thread costs the editor a
10//! reply and a fallback rather than the session.
11//!
12//! Three environment variables exist only for the tests that prove that, and
13//! each is read here and nowhere else, so an editor without them set runs the
14//! path it always ran:
15//!
16//! * `VE_HW_TEST_FAKE` -- open a stand-in seat that touches no driver, so the
17//! containment paths can be exercised on a machine whose GPU is wedged (which
18//! is the only machine where they matter). Refuses to open unless one of the
19//! two below is set with it, so it can never be a silently empty encoder.
20//! * `VE_HW_TEST_ABORT=<init|drain|N>` -- call `abort()` from a worker thread of
21//! our own, before opening, at the first drain, or before coding picture `N`.
22//! A foreign C thread's `abort()` is what really happened on 2026-08-13; this
23//! is the same shape without a hung ring.
24//! * `VE_HW_TEST_HANG=<init|drain|N>` -- stop answering at that same point,
25//! without dying, which is the other half of a wedged ring.
26
27use std::io::{Read, Write};
28use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd};
29use std::os::unix::net::UnixStream;
30
31use engine::hw::{DmaFrame, LocalEncoder, VhDma};
32use engine::hwproc::{Open, R_AU, R_ERR, R_NONE, Shm, T_DMA, T_DRAIN, T_ENCODE, T_GEOM, recv_tag, send_msg};
33
34/// Where the encoder actually is: the plugin's, or the test stand-in that opens
35/// no driver at all.
36enum Seat {
37 Real(LocalEncoder),
38 Fake,
39}
40
41impl Seat {
42 fn dma_geometry(&self) -> Option<(u32, u32)> {
43 match self {
44 Self::Real(encoder) => encoder.dma_geometry(),
45 // Nothing to import into, so the parent stages pictures instead --
46 // which is the path the containment tests want anyway.
47 Self::Fake => None,
48 }
49 }
50}
51
52/// One of the three injection points, named the same way in all three variables.
53#[derive(PartialEq, Eq)]
54enum At {
55 Init,
56 Drain,
57 Frame(u32),
58}
59
60fn injected(var: &str) -> Option<At> {
61 let value = std::env::var(var).ok()?;
62 Some(match value.as_str() {
63 "init" => At::Init,
64 "drain" => At::Drain,
65 _ => At::Frame(value.parse().ok()?),
66 })
67}
68
69/// The driver's own way of dying, reproduced: `abort()` called from a thread
70/// that is not the one running the encode, because that is where
71/// `amdgpu_ctx_set_sw_reset_status` calls it from and because a `catch_unwind`
72/// around the encode call is exactly what cannot see it.
73fn die() {
74 std::thread::spawn(|| {
75 // SAFETY: `abort` takes nothing, returns never, and is the whole point.
76 unsafe { libc::abort() }
77 });
78 loop {
79 std::thread::park();
80 }
81}
82
83/// ...and the other half: alive, holding the socket open, answering nothing.
84fn hang() -> ! {
85 loop {
86 std::thread::park();
87 }
88}
89
90fn reached(point: &At) {
91 if injected("VE_HW_TEST_ABORT").as_ref() == Some(point) {
92 die();
93 }
94 if injected("VE_HW_TEST_HANG").as_ref() == Some(point) {
95 hang();
96 }
97}
98
99fn main() {
100 let args: Vec<String> = std::env::args().skip(1).collect();
101 let Some(open) = Open::from_argv(&args) else {
102 eprintln!("hw-encode-child: bad arguments");
103 std::process::exit(2);
104 };
105 // SAFETY: the parent handed this process one end of a socket pair as its
106 // standard input and holds the other; nothing else in this process reads
107 // descriptor 0.
108 let mut sock = unsafe { UnixStream::from_raw_fd(0) };
109
110 reached(&At::Init);
111 let seat = match std::env::var_os("VE_HW_TEST_FAKE").is_some() {
112 // A stand-in that no test forgot to arm: without an injection point it
113 // would be an encoder producing nothing, and that is a hang of its own
114 // kind rather than a test.
115 true => match injected("VE_HW_TEST_ABORT").is_some() || injected("VE_HW_TEST_HANG").is_some()
116 {
117 true => Some(Seat::Fake),
118 false => None,
119 },
120 false => LocalEncoder::open_seat(open).map(Seat::Real),
121 };
122 let Some(mut seat) = seat else {
123 // The plugin's own "no", carried back as a byte: no driver, no
124 // entrypoint, a size refused. The parent takes the software encoder.
125 let _ = sock.write_all(&[0u8]);
126 std::process::exit(1);
127 };
128
129 // The staging buffer for pictures that live in memory: made here because
130 // this side knows the session's size, and handed over with the "yes".
131 let (mut shm, fd) = match Shm::create(open.frame_bytes()) {
132 Ok(pair) => pair,
133 Err(e) => {
134 eprintln!("hw-encode-child: no staging buffer: {e}");
135 let _ = sock.write_all(&[0u8]);
136 std::process::exit(1);
137 }
138 };
139 if send_msg(&sock, &[1u8], &[fd.as_raw_fd()]).is_err() {
140 std::process::exit(1);
141 }
142 drop(fd);
143
144 let mut coded = 0u32;
145 loop {
146 let Ok((tag, fds)) = recv_tag(&sock) else {
147 // The parent is gone (it closed, or it died): there is nothing left
148 // to encode for.
149 return;
150 };
151 match tag {
152 T_GEOM => match seat.dma_geometry() {
153 Some((width, height)) => {
154 let mut reply = vec![R_AU];
155 reply.extend_from_slice(&width.to_le_bytes());
156 reply.extend_from_slice(&height.to_le_bytes());
157 let _ = sock.write_all(&reply);
158 }
159 None => {
160 let _ = sock.write_all(&[R_NONE]);
161 }
162 },
163 T_ENCODE => {
164 let mut head = [0u8; 9];
165 if sock.read_exact(&mut head).is_err() {
166 return;
167 }
168 reached(&At::Frame(coded));
169 coded += 1;
170 let width = u32::from_le_bytes(head[0..4].try_into().expect("four bytes"));
171 let height = u32::from_le_bytes(head[4..8].try_into().expect("four bytes"));
172 let force_key = head[8] != 0;
173 let (w, h) = (width as usize, height as usize);
174 let chroma = w.div_ceil(2) * h.div_ceil(2);
175 let answer = match &mut seat {
176 Seat::Real(encoder) => {
177 let bytes = shm.bytes();
178 let (y, rest) = bytes.split_at(w * h);
179 let (u, rest) = rest.split_at(chroma);
180 encoder.encode(y, u, &rest[..chroma], width, height, force_key)
181 }
182 Seat::Fake => Ok(None),
183 };
184 if !reply(&mut sock, answer) {
185 return;
186 }
187 }
188 T_DMA => {
189 let mut head = [0u8; 46];
190 if sock.read_exact(&mut head).is_err() {
191 return;
192 }
193 reached(&At::Frame(coded));
194 coded += 1;
195 let u32_at = |offset: usize| {
196 u32::from_le_bytes(head[offset..offset + 4].try_into().expect("four bytes"))
197 };
198 let mut desc = VhDma {
199 fourcc: u32_at(0),
200 modifier: u64::from_le_bytes(head[4..12].try_into().expect("eight bytes")),
201 coded_width: u32_at(12),
202 coded_height: u32_at(16),
203 width: u32_at(20),
204 height: u32_at(24),
205 offset: [u32_at(28), u32_at(32)],
206 stride: [u32_at(36), u32_at(40)],
207 fd: [-1, -1],
208 };
209 if fds.len() != head[44] as usize || fds.is_empty() {
210 let _ = write_error(&mut sock, "a buffer arrived without its descriptors");
211 continue;
212 }
213 // Ownership passes to the frame, which closes them: the parent
214 // kept its own copies and these are ours.
215 for (slot, fd) in desc.fd.iter_mut().zip(fds) {
216 *slot = fd.into_raw_fd();
217 }
218 let frame = DmaFrame::from_desc(desc);
219 let answer = match &mut seat {
220 Seat::Real(encoder) => encoder.encode_dma(&frame, head[45] != 0),
221 Seat::Fake => Ok(None),
222 };
223 if !reply(&mut sock, answer) {
224 return;
225 }
226 }
227 T_DRAIN => {
228 reached(&At::Drain);
229 let answer = match &mut seat {
230 Seat::Real(encoder) => encoder.drain(),
231 Seat::Fake => Ok(None),
232 };
233 if !reply(&mut sock, answer) {
234 return;
235 }
236 }
237 _ => return,
238 }
239 }
240}
241
242/// Writes one answer back. `false` means the parent is gone and this process has
243/// nothing left to do.
244fn reply(sock: &mut UnixStream, answer: engine::Result<Option<&[u8]>>) -> bool {
245 match answer {
246 Ok(None) => sock.write_all(&[R_NONE]).is_ok(),
247 Ok(Some(au)) => {
248 let mut head = vec![R_AU];
249 head.extend_from_slice(&(au.len() as u32).to_le_bytes());
250 sock.write_all(&head).is_ok() && sock.write_all(au).is_ok()
251 }
252 // The encoder's own refusal, not a death: the parent raises it as the
253 // export error it is and this process stays open.
254 Err(e) => write_error(sock, &e.to_string()),
255 }
256}
257
258fn write_error(sock: &mut UnixStream, message: &str) -> bool {
259 let mut head = vec![R_ERR];
260 head.extend_from_slice(&(message.len() as u32).to_le_bytes());
261 sock.write_all(&head).is_ok() && sock.write_all(message.as_bytes()).is_ok()
262}