devices/virtio/vhost_user_backend/gpu/sys/
linux.rs

1// Copyright 2022 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::cell::RefCell;
6use std::collections::BTreeMap;
7use std::path::PathBuf;
8use std::rc::Rc;
9use std::sync::Arc;
10
11use anyhow::bail;
12use anyhow::Context;
13use argh::FromArgs;
14use base::clone_descriptor;
15use base::error;
16use base::safe_descriptor_from_cmdline_fd;
17use base::RawDescriptor;
18use base::SafeDescriptor;
19use base::Tube;
20use base::UnixSeqpacketListener;
21use base::UnlinkUnixSeqpacketListener;
22use cros_async::AsyncTube;
23use cros_async::AsyncWrapper;
24use cros_async::Executor;
25use cros_async::IoSource;
26use hypervisor::ProtectionType;
27use sync::Mutex;
28use vm_control::gpu::GpuControlResult;
29use vm_control::VmRequest;
30use vm_control::VmResponse;
31
32use crate::sys::linux::parse_wayland_sock;
33use crate::virtio;
34use crate::virtio::gpu;
35use crate::virtio::gpu::ProcessDisplayResult;
36use crate::virtio::vhost_user_backend::gpu::GpuBackend;
37use crate::virtio::vhost_user_backend::BackendConnection;
38use crate::virtio::Gpu;
39use crate::virtio::GpuDisplayParameters;
40use crate::virtio::GpuParameters;
41use crate::virtio::Interrupt;
42
43async fn run_display(
44    display: IoSource<AsyncWrapper<SafeDescriptor>>,
45    state: Rc<RefCell<gpu::Frontend>>,
46) {
47    loop {
48        if let Err(e) = display.wait_readable().await {
49            error!(
50                "Failed to wait for display context to become readable: {}",
51                e
52            );
53            break;
54        }
55
56        match state.borrow_mut().process_display() {
57            ProcessDisplayResult::Error(e) => {
58                error!("Failed to process display events: {}", e);
59                break;
60            }
61            ProcessDisplayResult::CloseRequested => break,
62            ProcessDisplayResult::Success => {}
63        }
64    }
65}
66
67async fn run_resource_bridge(tube: IoSource<Tube>, state: Rc<RefCell<gpu::Frontend>>) {
68    loop {
69        if let Err(e) = tube.wait_readable().await {
70            error!(
71                "Failed to wait for resource bridge tube to become readable: {}",
72                e
73            );
74            break;
75        }
76
77        if let Err(e) = state.borrow_mut().process_resource_bridge(tube.as_source()) {
78            error!("Failed to process resource bridge: {:#}", e);
79            break;
80        }
81    }
82}
83
84/// The frontend state and interrupt of the running device, shared with the GPU control socket
85/// handlers.
86///
87/// The handlers live as long as the process while the frontend only exists while the device is
88/// running, so this is `None` until `start_platform_workers()` and again after the device stops.
89pub type SharedGpuControlState = Rc<RefCell<Option<(Rc<RefCell<gpu::Frontend>>, Interrupt)>>>;
90
91/// Handles a single GPU control request. Kept non-`async` so that the `state` borrow cannot be
92/// held across an await point.
93fn process_gpu_control_request(state: &SharedGpuControlState, req: VmRequest) -> VmResponse {
94    let VmRequest::GpuCommand(cmd) = req else {
95        return VmResponse::Err(base::Error::new(libc::EINVAL));
96    };
97
98    let state = state.borrow();
99    let Some((frontend, interrupt)) = state.as_ref() else {
100        // The device isn't running: not started yet, reset, or suspended.
101        return VmResponse::Err(base::Error::new(libc::ENODEV));
102    };
103
104    let res = frontend.borrow_mut().process_gpu_control_command(cmd);
105    if let GpuControlResult::DisplaysUpdated = &res {
106        interrupt.signal_config_changed();
107    }
108    VmResponse::GpuResponse(res)
109}
110
111async fn run_gpu_control_command_handler(tube: AsyncTube, state: SharedGpuControlState) {
112    loop {
113        let req = match tube.next::<VmRequest>().await {
114            Ok(req) => req,
115            Err(_) => break,
116        };
117
118        let resp = process_gpu_control_request(&state, req);
119
120        if let Err(e) = tube.send(resp).await {
121            error!("GPU control socket failed to send response: {:#}", e);
122            break;
123        }
124    }
125}
126
127async fn run_gpu_control_listener(
128    ex: Executor,
129    listener: IoSource<AsyncWrapper<UnlinkUnixSeqpacketListener>>,
130    state: SharedGpuControlState,
131) {
132    loop {
133        if let Err(e) = listener.wait_readable().await {
134            error!("Failed to wait for control socket: {:#}", e);
135            break;
136        }
137        match listener.as_source().accept() {
138            Ok(stream) => match Tube::try_from(stream) {
139                Ok(tube) => match AsyncTube::new(&ex, tube) {
140                    Ok(async_tube) => {
141                        // The handler never references the frontend state across an await point,
142                        // so it doesn't need to be cancelled on reset; it exits when the client
143                        // disconnects.
144                        ex.spawn_local(run_gpu_control_command_handler(async_tube, state.clone()))
145                            .detach();
146                    }
147                    Err(e) => {
148                        error!("Failed to create AsyncTube for control socket: {:#}", e);
149                    }
150                },
151                Err(e) => {
152                    error!("Failed to create Tube for gpu control: {:#}", e);
153                }
154            },
155            Err(e)
156                if e.kind() == std::io::ErrorKind::WouldBlock
157                    || e.kind() == std::io::ErrorKind::Interrupted =>
158            {
159                continue;
160            }
161            Err(e) => {
162                error!("Failed to accept gpu control connection: {:#}", e);
163                break;
164            }
165        }
166    }
167}
168
169impl GpuBackend {
170    pub fn start_platform_workers(&mut self, interrupt: Interrupt) -> anyhow::Result<()> {
171        let state = self
172            .state
173            .as_ref()
174            .context("frontend state wasn't set")?
175            .clone();
176
177        // Start handling the resource bridges.
178        for bridge in self.resource_bridges.lock().drain(..) {
179            let tube = self
180                .ex
181                .async_from(bridge)
182                .context("failed to create async tube")?;
183            let task = self
184                .ex
185                .spawn_local(run_resource_bridge(tube, state.clone()));
186            self.platform_worker_tx
187                .unbounded_send(task)
188                .context("sending the run_resource_bridge task")?;
189        }
190
191        // Start handling the display.
192        let display = clone_descriptor(&*state.borrow_mut().display().borrow())
193            .map(AsyncWrapper::new)
194            .context("failed to clone inner WaitContext for gpu display")
195            .and_then(|ctx| {
196                self.ex
197                    .async_from(ctx)
198                    .context("failed to create async WaitContext")
199            })?;
200
201        let task = self.ex.spawn_local(run_display(display, state.clone()));
202        self.platform_worker_tx
203            .unbounded_send(task)
204            .context("sending the run_display task")?;
205
206        // Publish the state for the GPU control socket handlers, which are spawned once for the
207        // lifetime of the process. Cleared again in `stop_non_queue_workers()`.
208        self.gpu_control_state
209            .borrow_mut()
210            .replace((state, interrupt));
211
212        Ok(())
213    }
214}
215fn gpu_parameters_from_str(input: &str) -> Result<GpuParameters, String> {
216    serde_json::from_str(input).map_err(|e| e.to_string())
217}
218
219#[derive(FromArgs)]
220/// GPU device
221#[argh(subcommand, name = "gpu")]
222pub struct Options {
223    #[argh(option, arg_name = "PATH", hidden_help)]
224    /// deprecated - please use --socket-path instead
225    socket: Option<String>,
226    #[argh(option, arg_name = "PATH")]
227    /// path to the vhost-user socket to bind to.
228    /// If this flag is set, --fd cannot be specified.
229    socket_path: Option<String>,
230    #[argh(option, arg_name = "FD")]
231    /// file descriptor of a connected vhost-user socket.
232    /// If this flag is set, --socket-path cannot be specified.
233    fd: Option<RawDescriptor>,
234
235    #[argh(option, from_str_fn(parse_wayland_sock), arg_name = "PATH[,name=NAME]")]
236    /// path to one or more Wayland sockets. The unnamed socket is
237    /// used for displaying virtual screens while the named ones are used for IPC
238    wayland_sock: Vec<(String, PathBuf)>,
239    #[argh(option, arg_name = "PATH")]
240    /// path to one or more bridge sockets for communicating with
241    /// other graphics devices (wayland, video, etc)
242    resource_bridge: Vec<String>,
243    #[argh(option, arg_name = "DISPLAY")]
244    /// X11 display name to use
245    x_display: Option<String>,
246    #[argh(option, arg_name = "PATH")]
247    /// path to the control socket to listen on for GPU commands
248    control_socket_path: Option<PathBuf>,
249    #[argh(option, arg_name = "FD")]
250    /// file descriptor of a connected GPU render server socket
251    render_server_fd: Option<RawDescriptor>,
252    #[argh(
253        option,
254        from_str_fn(gpu_parameters_from_str),
255        default = "Default::default()",
256        arg_name = "JSON"
257    )]
258    /// a JSON object of virtio-gpu parameters
259    params: GpuParameters,
260}
261
262pub fn run_gpu_device(opts: Options) -> anyhow::Result<()> {
263    let Options {
264        x_display,
265        control_socket_path,
266        render_server_fd,
267        params: mut gpu_parameters,
268        resource_bridge,
269        socket,
270        socket_path,
271        fd,
272        wayland_sock,
273    } = opts;
274
275    if fd.is_some() && fd == render_server_fd {
276        bail!("--fd and --render-server-fd cannot refer to the same descriptor");
277    }
278
279    let rutabaga_server_descriptor = render_server_fd
280        .map(|raw_fd| {
281            safe_descriptor_from_cmdline_fd(&raw_fd)
282                .context("failed to validate --render-server-fd")
283        })
284        .transpose()?;
285
286    // Standalone vhost-user GPU device runs out-of-process, so external_blob must be enforced
287    // to allow blobs to be exported to descriptors for sharing with the hypervisor or host display.
288    gpu_parameters.external_blob = true;
289
290    let channels: BTreeMap<_, _> = wayland_sock.into_iter().collect();
291
292    let resource_bridge_listeners = resource_bridge
293        .into_iter()
294        .map(|p| {
295            UnixSeqpacketListener::bind(&p)
296                .map(UnlinkUnixSeqpacketListener)
297                .with_context(|| format!("failed to bind socket at path {p}"))
298        })
299        .collect::<anyhow::Result<Vec<_>>>()?;
300
301    if gpu_parameters.display_params.is_empty() {
302        gpu_parameters
303            .display_params
304            .push(GpuDisplayParameters::default());
305    }
306
307    let ex = Executor::new().context("failed to create executor")?;
308
309    // We don't know the order in which other devices are going to connect to the resource bridges
310    // so start listening for all of them on separate threads. Any devices that connect after the
311    // gpu device starts its queues will not have its resource bridges processed. In practice this
312    // should be fine since the devices that use the resource bridge always try to connect to the
313    // gpu device before handling messages from the VM.
314    let resource_bridges = Arc::new(Mutex::new(Vec::with_capacity(
315        resource_bridge_listeners.len(),
316    )));
317    for listener in resource_bridge_listeners {
318        let resource_bridges = Arc::clone(&resource_bridges);
319        ex.spawn_blocking(move || match listener.accept() {
320            Ok(stream) => resource_bridges
321                .lock()
322                .push(Tube::try_from(stream).unwrap()),
323            Err(e) => {
324                let path = listener
325                    .path()
326                    .unwrap_or_else(|_| PathBuf::from("{unknown}"));
327                error!(
328                    "Failed to accept resource bridge connection for socket {}: {}",
329                    path.display(),
330                    e
331                );
332            }
333        })
334        .detach();
335    }
336
337    // TODO(b/232344535): Read side of the tube is ignored currently.
338    // Complete the implementation by polling `exit_evt_rdtube` and
339    // kill the sibling VM.
340    let (exit_evt_wrtube, _) =
341        Tube::directional_pair().context("failed to create vm event tube")?;
342
343    let (gpu_control_tube, _) = Tube::pair().context("failed to create gpu control tube")?;
344
345    let mut display_backends = vec![
346        virtio::DisplayBackend::X(x_display),
347        virtio::DisplayBackend::Stub,
348    ];
349    #[cfg(feature = "android_display")]
350    if let Some(service_name) = &gpu_parameters.android_display_service {
351        display_backends.insert(0, virtio::DisplayBackend::Android(service_name.to_string()));
352    }
353    if let Some(p) = channels.get("") {
354        display_backends.insert(0, virtio::DisplayBackend::Wayland(Some(p.to_owned())));
355    }
356
357    // These are only used when there is an input device.
358    let event_devices = Vec::new();
359
360    let base_features = virtio::base_features(ProtectionType::Unprotected);
361
362    let conn = BackendConnection::from_opts(socket.as_deref(), socket_path.as_deref(), fd)?;
363
364    let gpu = Rc::new(RefCell::new(Gpu::new(
365        exit_evt_wrtube,
366        gpu_control_tube,
367        Vec::new(), // resource_bridges, handled separately by us
368        display_backends,
369        &gpu_parameters,
370        rutabaga_server_descriptor,
371        event_devices,
372        base_features,
373        &channels,
374        /* gpu_cgroup_path */
375        None,
376    )));
377
378    // The control socket is tied to the lifetime of this process, not of the device: the guest may
379    // reset the device, reboot, reload the driver or suspend, and the socket must keep working.
380    let gpu_control_state: SharedGpuControlState = Rc::new(RefCell::new(None));
381
382    let control_listener_task = if let Some(path) = &control_socket_path {
383        let listener = UnixSeqpacketListener::bind(path)
384            .map(UnlinkUnixSeqpacketListener)
385            .with_context(|| format!("failed to bind control socket at path {}", path.display()))?;
386        listener
387            .set_nonblocking(true)
388            .context("failed to set nonblocking for control socket")?;
389        let async_listener = ex
390            .async_from(AsyncWrapper::new(listener))
391            .context("failed to create async control socket listener")?;
392        Some(ex.spawn_local(run_gpu_control_listener(
393            ex.clone(),
394            async_listener,
395            gpu_control_state.clone(),
396        )))
397    } else {
398        None
399    };
400
401    let (platform_worker_tx, platform_worker_rx) = futures::channel::mpsc::unbounded();
402    let backend = GpuBackend {
403        ex: ex.clone(),
404        gpu,
405        resource_bridges,
406        state: None,
407        fence_state: Default::default(),
408        queue_workers: Default::default(),
409        platform_worker_rx,
410        platform_worker_tx,
411        shmem_mapper: Arc::new(Mutex::new(None)),
412        gpu_control_state,
413    };
414
415    // Run until the backend is finished.
416    let res = ex.run_until(conn.run_backend(backend, &ex));
417
418    if let Some(task) = control_listener_task {
419        let _ = ex.run_until(task.cancel());
420    }
421
422    // Process any tasks from the backend's destructor.
423    let _ = ex.run_until(async {});
424
425    res?
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    #[test]
433    fn parse_render_server_fd_option() {
434        let opts = Options::from_args(&["gpu"], &["--render-server-fd", "42"]).unwrap();
435        assert_eq!(opts.render_server_fd, Some(42));
436
437        let opts_default = Options::from_args(&["gpu"], &[]).unwrap();
438        assert_eq!(opts_default.render_server_fd, None);
439    }
440
441    #[test]
442    fn reject_duplicate_fd_and_render_server_fd() {
443        let opts =
444            Options::from_args(&["gpu"], &["--fd", "42", "--render-server-fd", "42"]).unwrap();
445        let err = run_gpu_device(opts).unwrap_err();
446        assert!(err
447            .to_string()
448            .contains("--fd and --render-server-fd cannot refer to the same descriptor"));
449    }
450
451    #[test]
452    fn reject_invalid_render_server_fd() {
453        let opts = Options::from_args(
454            &["gpu"],
455            &[
456                "--resource-bridge",
457                "/nonexistent/render_server_fd_test.sock",
458                "--render-server-fd",
459                "-1",
460            ],
461        )
462        .unwrap();
463        let err = run_gpu_device(opts).unwrap_err();
464        assert!(err
465            .to_string()
466            .contains("failed to validate --render-server-fd"));
467    }
468}