devices/virtio/gpu/
virtio_gpu.rs

1// Copyright 2020 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 as Map;
7use std::collections::BTreeSet as Set;
8use std::io::IoSliceMut;
9use std::num::NonZeroU32;
10use std::path::PathBuf;
11use std::rc::Rc;
12use std::result::Result;
13use std::sync::atomic::AtomicU64;
14use std::sync::atomic::Ordering;
15use std::sync::Arc;
16
17use anyhow::Context;
18use base::error;
19use base::FromRawDescriptor;
20use base::IntoRawDescriptor;
21use base::Protection;
22use base::SafeDescriptor;
23use base::VolatileSlice;
24use gpu_display::*;
25use hypervisor::MemCacheType;
26use libc::c_void;
27use rutabaga_gfx::Resource3DInfo;
28use rutabaga_gfx::ResourceCreate3D;
29use rutabaga_gfx::ResourceCreateBlob;
30use rutabaga_gfx::Rutabaga;
31use rutabaga_gfx::RutabagaDescriptor;
32#[cfg(windows)]
33use rutabaga_gfx::RutabagaError;
34use rutabaga_gfx::RutabagaFence;
35use rutabaga_gfx::RutabagaFromRawDescriptor;
36use rutabaga_gfx::RutabagaHandle;
37use rutabaga_gfx::RutabagaIntoRawDescriptor;
38use rutabaga_gfx::RutabagaIovec;
39use rutabaga_gfx::RutabagaMagmaHandle;
40#[cfg(windows)]
41use rutabaga_gfx::RutabagaUnsupported;
42use rutabaga_gfx::Transfer3D;
43use rutabaga_gfx::RUTABAGA_HANDLE_TYPE_MEM_DMABUF;
44use rutabaga_gfx::RUTABAGA_HANDLE_TYPE_MEM_OPAQUE_FD;
45use rutabaga_gfx::RUTABAGA_MAP_ACCESS_MASK;
46use rutabaga_gfx::RUTABAGA_MAP_ACCESS_READ;
47use rutabaga_gfx::RUTABAGA_MAP_ACCESS_RW;
48use rutabaga_gfx::RUTABAGA_MAP_ACCESS_WRITE;
49use rutabaga_gfx::RUTABAGA_MAP_CACHE_CACHED;
50use rutabaga_gfx::RUTABAGA_MAP_CACHE_MASK;
51use serde::Deserialize;
52use serde::Serialize;
53use sync::Mutex;
54use vm_control::gpu::DisplayMode;
55use vm_control::gpu::DisplayParameters;
56use vm_control::gpu::GpuControlCommand;
57use vm_control::gpu::GpuControlResult;
58use vm_control::gpu::MouseMode;
59use vm_control::VmMemorySource;
60use vm_memory::udmabuf::UdmabufDriver;
61use vm_memory::udmabuf::UdmabufDriverTrait;
62use vm_memory::GuestAddress;
63use vm_memory::GuestMemory;
64
65use super::protocol::virtio_gpu_rect;
66use super::protocol::GpuResponse;
67use super::protocol::GpuResponse::*;
68use super::protocol::GpuResponsePlaneInfo;
69use super::protocol::VirtioGpuResult;
70use super::protocol::VIRTIO_GPU_BLOB_FLAG_CREATE_GUEST_HANDLE;
71use super::protocol::VIRTIO_GPU_BLOB_FLAG_USE_MAPPABLE;
72use super::protocol::VIRTIO_GPU_BLOB_MEM_HOST3D;
73use super::VirtioScanoutBlobData;
74use crate::virtio::gpu::edid::DisplayInfo;
75use crate::virtio::gpu::edid::EdidBytes;
76use crate::virtio::gpu::snapshot::pack_directory_to_snapshot;
77use crate::virtio::gpu::snapshot::unpack_snapshot_to_directory;
78use crate::virtio::gpu::snapshot::DirectorySnapshot;
79use crate::virtio::gpu::GpuDisplayParameters;
80use crate::virtio::gpu::VIRTIO_GPU_MAX_SCANOUTS;
81use crate::virtio::resource_bridge::BufferInfo;
82use crate::virtio::resource_bridge::PlaneInfo;
83use crate::virtio::resource_bridge::ResourceInfo;
84use crate::virtio::resource_bridge::ResourceResponse;
85use crate::virtio::SharedMemoryMapper;
86
87pub fn to_rutabaga_descriptor(s: SafeDescriptor) -> RutabagaDescriptor {
88    // SAFETY:
89    // Safe because we own the SafeDescriptor at this point.
90    unsafe { RutabagaDescriptor::from_raw_descriptor(s.into_raw_descriptor()) }
91}
92
93fn to_safe_descriptor(r: RutabagaDescriptor) -> SafeDescriptor {
94    // SAFETY:
95    // Safe because we own the SafeDescriptor at this point.
96    unsafe { SafeDescriptor::from_raw_descriptor(r.into_raw_descriptor()) }
97}
98
99struct VirtioGpuResource {
100    resource_id: u32,
101    width: u32,
102    height: u32,
103    size: u64,
104    shmem_offset: Option<u64>,
105    scanout_data: Option<VirtioScanoutBlobData>,
106    /// Maps display `surface_id` to `import_id`.
107    display_import: Map<u32, u32>,
108    rutabaga_external_mapping: bool,
109    guest_cpu_mappable: bool,
110
111    // Only saved for snapshotting, so that we can re-attach backing iovecs with the correct new
112    // host addresses.
113    backing_iovecs: Option<Vec<(GuestAddress, usize)>>,
114}
115
116#[derive(Serialize, Deserialize)]
117struct VirtioGpuResourceSnapshot {
118    resource_id: u32,
119    width: u32,
120    height: u32,
121    size: u64,
122
123    backing_iovecs: Option<Vec<(GuestAddress, usize)>>,
124    shmem_offset: Option<u64>,
125    scanout_data: Option<VirtioScanoutBlobData>,
126    guest_cpu_mappable: bool,
127}
128
129impl VirtioGpuResource {
130    /// Creates a new VirtioGpuResource with the given metadata.  Width and height are used by the
131    /// display, while size is useful for hypervisor mapping.
132    pub fn new(
133        resource_id: u32,
134        width: u32,
135        height: u32,
136        size: u64,
137        guest_cpu_mappable: bool,
138    ) -> VirtioGpuResource {
139        VirtioGpuResource {
140            resource_id,
141            width,
142            height,
143            size,
144            shmem_offset: None,
145            scanout_data: None,
146            display_import: Map::new(),
147            rutabaga_external_mapping: false,
148            guest_cpu_mappable,
149            backing_iovecs: None,
150        }
151    }
152
153    fn snapshot(&self) -> VirtioGpuResourceSnapshot {
154        // Only the 2D backend is fully supported and it doesn't use these fields. 3D is WIP.
155        assert!(self.display_import.is_empty());
156
157        VirtioGpuResourceSnapshot {
158            resource_id: self.resource_id,
159            width: self.width,
160            height: self.height,
161            size: self.size,
162            backing_iovecs: self.backing_iovecs.clone(),
163            shmem_offset: self.shmem_offset,
164            scanout_data: self.scanout_data,
165            guest_cpu_mappable: self.guest_cpu_mappable,
166        }
167    }
168
169    fn restore(s: VirtioGpuResourceSnapshot) -> Self {
170        let mut resource = VirtioGpuResource::new(
171            s.resource_id,
172            s.width,
173            s.height,
174            s.size,
175            s.guest_cpu_mappable,
176        );
177        resource.backing_iovecs = s.backing_iovecs;
178        resource.scanout_data = s.scanout_data;
179        resource
180    }
181}
182
183struct VirtioGpuScanout {
184    width: u32,
185    height: u32,
186    scanout_type: SurfaceType,
187    // If this scanout is a primary scanout, the scanout id.
188    scanout_id: Option<u32>,
189    // If this scanout is a primary scanout, the display properties.
190    display_params: Option<GpuDisplayParameters>,
191    // If this scanout is a cursor scanout, the scanout that this is cursor is overlayed onto.
192    parent_surface_id: Option<u32>,
193
194    surface_id: Option<u32>,
195    parent_scanout_id: Option<u32>,
196
197    resource_id: Option<NonZeroU32>,
198    position: Option<(u32, u32)>,
199}
200
201#[derive(Serialize, Deserialize)]
202struct VirtioGpuScanoutSnapshot {
203    width: u32,
204    height: u32,
205    scanout_type: SurfaceType,
206    scanout_id: Option<u32>,
207    display_params: Option<GpuDisplayParameters>,
208
209    // The surface IDs aren't guest visible. Instead of storing them and then having to fix up
210    // `gpu_display` internals, we'll allocate new ones on restore. So, we just need to store
211    // whether a surface was allocated and the parent's scanout ID.
212    has_surface: bool,
213    parent_scanout_id: Option<u32>,
214
215    resource_id: Option<NonZeroU32>,
216    position: Option<(u32, u32)>,
217}
218
219impl VirtioGpuScanout {
220    fn new_primary(scanout_id: u32, params: GpuDisplayParameters) -> VirtioGpuScanout {
221        let (width, height) = params.get_virtual_display_size();
222        VirtioGpuScanout {
223            width,
224            height,
225            scanout_type: SurfaceType::Scanout,
226            scanout_id: Some(scanout_id),
227            display_params: Some(params),
228            parent_surface_id: None,
229            surface_id: None,
230            parent_scanout_id: None,
231            resource_id: None,
232            position: None,
233        }
234    }
235
236    fn new_cursor() -> VirtioGpuScanout {
237        // Per virtio spec: "The mouse cursor image is a normal resource, except that it must be
238        // 64x64 in size."
239        VirtioGpuScanout {
240            width: 64,
241            height: 64,
242            scanout_type: SurfaceType::Cursor,
243            scanout_id: None,
244            display_params: None,
245            parent_surface_id: None,
246            surface_id: None,
247            parent_scanout_id: None,
248            resource_id: None,
249            position: None,
250        }
251    }
252
253    fn snapshot(&self) -> VirtioGpuScanoutSnapshot {
254        VirtioGpuScanoutSnapshot {
255            width: self.width,
256            height: self.height,
257            has_surface: self.surface_id.is_some(),
258            resource_id: self.resource_id,
259            scanout_type: self.scanout_type,
260            scanout_id: self.scanout_id,
261            display_params: self.display_params.clone(),
262            parent_scanout_id: self.parent_scanout_id,
263            position: self.position,
264        }
265    }
266
267    fn restore(
268        &mut self,
269        snapshot: VirtioGpuScanoutSnapshot,
270        parent_surface_id: Option<u32>,
271        display: &Rc<RefCell<GpuDisplay>>,
272    ) -> VirtioGpuResult {
273        // Scanouts are mainly controlled by the host, we just need to make sure it looks same,
274        // restore the resource_id association, and create a surface in the display.
275
276        assert_eq!(self.width, snapshot.width);
277        assert_eq!(self.height, snapshot.height);
278        assert_eq!(self.scanout_type, snapshot.scanout_type);
279        assert_eq!(self.scanout_id, snapshot.scanout_id);
280        assert_eq!(self.display_params, snapshot.display_params);
281
282        self.resource_id = snapshot.resource_id;
283        if snapshot.has_surface {
284            self.create_surface(display, parent_surface_id, None)?;
285        } else {
286            self.release_surface(display);
287        }
288        if let Some((x, y)) = snapshot.position {
289            self.set_position(display, x, y)?;
290        }
291
292        Ok(OkNoData)
293    }
294
295    fn create_surface(
296        &mut self,
297        display: &Rc<RefCell<GpuDisplay>>,
298        new_parent_surface_id: Option<u32>,
299        new_scanout_rect: Option<virtio_gpu_rect>,
300    ) -> VirtioGpuResult {
301        let mut need_to_create = false;
302
303        if self.surface_id.is_none() {
304            need_to_create = true;
305        }
306
307        if self.parent_surface_id != new_parent_surface_id {
308            self.parent_surface_id = new_parent_surface_id;
309            need_to_create = true;
310        }
311
312        if let Some(new_scanout_rect) = new_scanout_rect {
313            // The guest may request a new scanout size when modesetting happens (i.e. display
314            // resolution change). Detect when that happens and re-allocate a surface with the new
315            // size.
316            //
317            // Note that we do NOT update |self.display_params|, which is sourced from user input
318            // (initial display parameters), and (as of the time of writing) only matters to EDID
319            // information. EDID info shall remain the same for a given display even if the active
320            // resolution has changed.
321            let new_width = new_scanout_rect.width.to_native();
322            let new_height = new_scanout_rect.height.to_native();
323            if !(self.width == new_width && self.height == new_height) {
324                self.width = new_width;
325                self.height = new_height;
326                need_to_create = true;
327            }
328        }
329
330        if !need_to_create {
331            return Ok(OkNoData);
332        }
333
334        self.release_surface(display);
335
336        let mut display = display.borrow_mut();
337
338        let display_params = match self.display_params.clone() {
339            Some(mut params) => {
340                // The sizes in |self.display_params| doesn't necessarily match the requested
341                // surface size (see above note about when guest modesetting happens). Always
342                // override display mode to match the requested size.
343                params.mode = DisplayMode::Windowed(self.width, self.height);
344                params
345            }
346            None => {
347                DisplayParameters::default_with_mode(DisplayMode::Windowed(self.width, self.height))
348            }
349        };
350        let surface_id = display.create_surface(
351            self.parent_surface_id,
352            self.scanout_id,
353            &display_params,
354            self.scanout_type,
355        )?;
356
357        self.surface_id = Some(surface_id);
358
359        Ok(OkNoData)
360    }
361
362    fn release_surface(&mut self, display: &Rc<RefCell<GpuDisplay>>) {
363        if let Some(surface_id) = self.surface_id {
364            display.borrow_mut().release_surface(surface_id);
365        }
366
367        self.surface_id = None;
368    }
369
370    fn set_mouse_mode(
371        &mut self,
372        display: &Rc<RefCell<GpuDisplay>>,
373        mouse_mode: MouseMode,
374    ) -> VirtioGpuResult {
375        if let Some(surface_id) = self.surface_id {
376            display
377                .borrow_mut()
378                .set_mouse_mode(surface_id, mouse_mode)?;
379        }
380        Ok(OkNoData)
381    }
382
383    fn set_position(
384        &mut self,
385        display: &Rc<RefCell<GpuDisplay>>,
386        x: u32,
387        y: u32,
388    ) -> VirtioGpuResult {
389        if let Some(surface_id) = self.surface_id {
390            display.borrow_mut().set_position(surface_id, x, y)?;
391            self.position = Some((x, y));
392        }
393        Ok(OkNoData)
394    }
395
396    fn commit(&self, display: &Rc<RefCell<GpuDisplay>>) -> VirtioGpuResult {
397        if let Some(surface_id) = self.surface_id {
398            display.borrow_mut().commit(surface_id)?;
399        }
400        Ok(OkNoData)
401    }
402
403    fn flush(
404        &mut self,
405        display: &Rc<RefCell<GpuDisplay>>,
406        resource: &mut VirtioGpuResource,
407        rutabaga: &mut Rutabaga,
408    ) -> VirtioGpuResult {
409        let surface_id = match self.surface_id {
410            Some(id) => id,
411            _ => return Ok(OkNoData),
412        };
413
414        if let Some(import_id) =
415            VirtioGpuScanout::import_resource_to_display(display, surface_id, resource, rutabaga)
416        {
417            display
418                .borrow_mut()
419                .flip_to(surface_id, import_id, None, None, None)
420                .map_err(|e| {
421                    error!("flip_to failed: {:#}", e);
422                    ErrUnspec
423                })?;
424            return Ok(OkNoData);
425        }
426
427        // Import failed, fall back to a copy.
428        let mut display = display.borrow_mut();
429
430        // Prevent overwriting a buffer that is currently being used by the compositor.
431        if display.next_buffer_in_use(surface_id) {
432            return Ok(OkNoData);
433        }
434
435        let fb = display
436            .framebuffer_region(surface_id, 0, 0, self.width, self.height)
437            .ok_or(ErrUnspec)?;
438
439        let mut transfer = Transfer3D::new_2d(0, 0, self.width, self.height, 0);
440        transfer.stride = fb.stride();
441        let fb_slice = fb.as_volatile_slice();
442        let buf = IoSliceMut::new(
443            // SAFETY: trivially safe
444            unsafe { std::slice::from_raw_parts_mut(fb_slice.as_mut_ptr(), fb_slice.size()) },
445        );
446        rutabaga.transfer_read(0, resource.resource_id, transfer, Some(buf))?;
447
448        display.flip(surface_id);
449        Ok(OkNoData)
450    }
451
452    fn import_resource_to_display(
453        display: &Rc<RefCell<GpuDisplay>>,
454        surface_id: u32,
455        resource: &mut VirtioGpuResource,
456        rutabaga: &mut Rutabaga,
457    ) -> Option<u32> {
458        if let Some(&import_id) = resource.display_import.get(&surface_id) {
459            return Some(import_id);
460        }
461        let blob = rutabaga.export_blob(resource.resource_id).ok()?;
462
463        let handle = match blob {
464            RutabagaHandle::AhbInfo(info) => {
465                let import_id = display
466                    .borrow_mut()
467                    .import_resource(
468                        surface_id,
469                        DisplayExternalResourceImport::AHardwareBuffer { info },
470                    )
471                    .ok()?;
472                resource.display_import.insert(surface_id, import_id);
473                return Some(import_id);
474            }
475            other => RutabagaMagmaHandle::try_from(other).ok()?,
476        };
477        if handle.handle_type != rutabaga_gfx::RUTABAGA_HANDLE_TYPE_MEM_DMABUF {
478            return None;
479        }
480        let dmabuf = to_safe_descriptor(handle.os_handle);
481
482        let (width, height, format, stride, offset, modifier) = match resource.scanout_data {
483            Some(data) => (
484                data.width,
485                data.height,
486                data.drm_format,
487                data.strides[0],
488                data.offsets[0],
489                0,
490            ),
491            None => {
492                let query = rutabaga.resource3d_info(resource.resource_id).ok()?;
493                (
494                    resource.width,
495                    resource.height,
496                    query.drm_fourcc,
497                    query.strides[0],
498                    query.offsets[0],
499                    query.modifier,
500                )
501            }
502        };
503
504        let import_id = display
505            .borrow_mut()
506            .import_resource(
507                surface_id,
508                DisplayExternalResourceImport::Dmabuf {
509                    descriptor: &dmabuf,
510                    offset,
511                    stride,
512                    modifiers: modifier,
513                    width,
514                    height,
515                    fourcc: format,
516                },
517            )
518            .ok()?;
519        resource.display_import.insert(surface_id, import_id);
520        Some(import_id)
521    }
522}
523
524/// Pending state of the `VIRTIO_GPU_EVENT_DISPLAY` config event.
525///
526/// The guest reads `events_read`, queries the display info and then writes `events_clear`. A
527/// display change landing between that read and write must stay pending, or the guest never learns
528/// about it. So the event is a generation counter, and `events_clear` only acknowledges the
529/// generation the guest saw in `events_read`.
530#[derive(Default)]
531pub struct DisplayEvent {
532    /// Incremented on every display change.
533    generation: AtomicU64,
534    /// Generation current when the guest last read `events_read`.
535    observed: AtomicU64,
536    /// Generation last acknowledged by the guest through `events_clear`.
537    acked: AtomicU64,
538}
539
540impl DisplayEvent {
541    /// Records a display change to report to the guest.
542    pub fn signal(&self) {
543        self.generation.fetch_add(1, Ordering::SeqCst);
544    }
545
546    /// Returns whether there is a display change the guest has not acknowledged.
547    pub fn is_pending(&self) -> bool {
548        self.generation.load(Ordering::SeqCst) != self.acked.load(Ordering::SeqCst)
549    }
550
551    /// Records the current generation for a later `events_clear` and returns whether it is
552    /// pending (called when the guest reads `events_read`). Both come from a single load of the
553    /// generation, so the guest acknowledges exactly the state reported to it.
554    pub fn observe_and_is_pending(&self) -> bool {
555        let generation = self.generation.load(Ordering::SeqCst);
556        self.observed.store(generation, Ordering::SeqCst);
557        generation != self.acked.load(Ordering::SeqCst)
558    }
559
560    /// Acknowledges up to the generation last seen by `observe_and_is_pending` (called when the
561    /// guest writes `VIRTIO_GPU_EVENT_DISPLAY` to `events_clear`).
562    pub fn acknowledge_observed(&self) {
563        self.acked
564            .fetch_max(self.observed.load(Ordering::SeqCst), Ordering::SeqCst);
565    }
566
567    /// Restores the pending state from a snapshot, which only stores a `bool`.
568    ///
569    /// When `pending` is `true`, `observed` stays behind `generation`, so an `events_clear` in
570    /// flight across snapshot/restore does not drop the event.
571    fn set_pending(&self, pending: bool) {
572        if pending == self.is_pending() {
573            return;
574        }
575        if pending {
576            self.signal();
577        } else {
578            let generation = self.generation.load(Ordering::SeqCst);
579            self.observed.store(generation, Ordering::SeqCst);
580            self.acked.store(generation, Ordering::SeqCst);
581        }
582    }
583}
584
585/// Handles functionality related to displays, input events and hypervisor memory management.
586pub struct VirtioGpu {
587    display: Rc<RefCell<GpuDisplay>>,
588    scanouts: Map<u32, VirtioGpuScanout>,
589    scanouts_updated: Arc<DisplayEvent>,
590    cursor_scanout: VirtioGpuScanout,
591    mapper: Arc<Mutex<Option<Box<dyn SharedMemoryMapper>>>>,
592    rutabaga: Rutabaga,
593    resources: Map<u32, VirtioGpuResource>,
594    external_blob: bool,
595    fixed_blob_mapping: bool,
596    udmabuf_driver: Option<UdmabufDriver>,
597    snapshot_scratch_directory: Option<PathBuf>,
598    deferred_snapshot_load: Option<VirtioGpuSnapshot>,
599}
600
601// Only the 2D mode is supported. Notes on `VirtioGpu` fields:
602//
603//   * display: re-initialized from scratch using the scanout snapshots
604//   * scanouts: snapshot'd
605//   * scanouts_updated: snapshot'd
606//   * cursor_scanout: snapshot'd
607//   * mapper: not needed for 2d mode
608//   * rutabaga: re-initialized from scatch using the resource snapshots
609//   * resources: snapshot'd
610//   * external_blob: not needed for 2d mode
611//   * udmabuf_driver: not needed for 2d mode
612#[derive(Serialize, Deserialize)]
613pub struct VirtioGpuSnapshot {
614    scanouts: Map<u32, VirtioGpuScanoutSnapshot>,
615    scanouts_updated: bool,
616    cursor_scanout: VirtioGpuScanoutSnapshot,
617    rutabaga: DirectorySnapshot,
618    resources: Map<u32, VirtioGpuResourceSnapshot>,
619}
620
621#[derive(Serialize, Deserialize)]
622struct RutabagaResourceSnapshotSerializable {
623    resource_id: u32,
624
625    width: u32,
626    height: u32,
627    host_mem_size: usize,
628
629    backing_iovecs: Option<Vec<(GuestAddress, usize)>>,
630    component_mask: u8,
631    size: u64,
632}
633
634fn sglist_to_rutabaga_iovecs(
635    vecs: &[(GuestAddress, usize)],
636    mem: &GuestMemory,
637) -> Result<Vec<RutabagaIovec>, ()> {
638    if vecs
639        .iter()
640        .any(|&(addr, len)| mem.get_slice_at_addr(addr, len).is_err())
641    {
642        return Err(());
643    }
644
645    let mut rutabaga_iovecs: Vec<RutabagaIovec> = Vec::new();
646    for &(addr, len) in vecs {
647        let slice = mem.get_slice_at_addr(addr, len).unwrap();
648        rutabaga_iovecs.push(RutabagaIovec {
649            base: slice.as_mut_ptr() as *mut c_void,
650            len,
651        });
652    }
653    Ok(rutabaga_iovecs)
654}
655
656pub enum ProcessDisplayResult {
657    Success,
658    CloseRequested,
659    Error(GpuDisplayError),
660}
661
662impl VirtioGpu {
663    /// Creates a new instance of the VirtioGpu state tracker.
664    pub fn new(
665        display: GpuDisplay,
666        display_params: Vec<GpuDisplayParameters>,
667        display_event: Arc<DisplayEvent>,
668        rutabaga: Rutabaga,
669        mapper: Arc<Mutex<Option<Box<dyn SharedMemoryMapper>>>>,
670        external_blob: bool,
671        fixed_blob_mapping: bool,
672        udmabuf: bool,
673        snapshot_scratch_directory: Option<PathBuf>,
674    ) -> Option<VirtioGpu> {
675        let mut udmabuf_driver = None;
676        if udmabuf {
677            udmabuf_driver = Some(
678                UdmabufDriver::new()
679                    .map_err(|e| error!("failed to initialize udmabuf: {}", e))
680                    .ok()?,
681            );
682        }
683
684        let scanouts = display_params
685            .iter()
686            .enumerate()
687            .map(|(display_index, display_param)| {
688                (
689                    display_index as u32,
690                    VirtioGpuScanout::new_primary(display_index as u32, display_param.clone()),
691                )
692            })
693            .collect::<Map<_, _>>();
694        let cursor_scanout = VirtioGpuScanout::new_cursor();
695
696        Some(VirtioGpu {
697            display: Rc::new(RefCell::new(display)),
698            scanouts,
699            scanouts_updated: display_event,
700            cursor_scanout,
701            mapper,
702            rutabaga,
703            resources: Default::default(),
704            external_blob,
705            fixed_blob_mapping,
706            udmabuf_driver,
707            deferred_snapshot_load: None,
708            snapshot_scratch_directory,
709        })
710    }
711
712    /// Imports the event device
713    pub fn import_event_device(&mut self, event_device: EventDevice) -> VirtioGpuResult {
714        let mut display = self.display.borrow_mut();
715        let _event_device_id = display.import_event_device(event_device)?;
716        Ok(OkNoData)
717    }
718
719    /// Gets a reference to the display passed into `new`.
720    pub fn display(&mut self) -> &Rc<RefCell<GpuDisplay>> {
721        &self.display
722    }
723
724    /// Gets the list of supported display resolutions as a slice of `(width, height, enabled)`
725    /// tuples.
726    pub fn display_info(&self) -> Vec<(u32, u32, bool)> {
727        (0..VIRTIO_GPU_MAX_SCANOUTS)
728            .map(|scanout_id| scanout_id as u32)
729            .map(|scanout_id| {
730                self.scanouts
731                    .get(&scanout_id)
732                    .map_or((0, 0, false), |scanout| {
733                        (scanout.width, scanout.height, true)
734                    })
735            })
736            .collect::<Vec<_>>()
737    }
738
739    // Connects new displays to the device.
740    fn add_displays(&mut self, displays: Vec<DisplayParameters>) -> GpuControlResult {
741        let requested_num_scanouts = self.scanouts.len() + displays.len();
742        if requested_num_scanouts > VIRTIO_GPU_MAX_SCANOUTS {
743            return GpuControlResult::TooManyDisplays {
744                allowed: VIRTIO_GPU_MAX_SCANOUTS,
745                requested: requested_num_scanouts,
746            };
747        }
748
749        let mut available_scanout_ids = (0..VIRTIO_GPU_MAX_SCANOUTS)
750            .map(|s| s as u32)
751            .collect::<Set<u32>>();
752
753        self.scanouts.keys().for_each(|scanout_id| {
754            available_scanout_ids.remove(scanout_id);
755        });
756
757        for display_params in displays.into_iter() {
758            let new_scanout_id = *available_scanout_ids.iter().next().unwrap();
759            available_scanout_ids.remove(&new_scanout_id);
760
761            self.scanouts.insert(
762                new_scanout_id,
763                VirtioGpuScanout::new_primary(new_scanout_id, display_params),
764            );
765        }
766
767        self.scanouts_updated.signal();
768
769        GpuControlResult::DisplaysUpdated
770    }
771
772    /// Returns the list of displays currently connected to the device.
773    fn list_displays(&self) -> GpuControlResult {
774        GpuControlResult::DisplayList {
775            displays: self
776                .scanouts
777                .iter()
778                .filter_map(|(scanout_id, scanout)| {
779                    scanout
780                        .display_params
781                        .as_ref()
782                        .cloned()
783                        .map(|display_params| (*scanout_id, display_params))
784                })
785                .collect(),
786        }
787    }
788
789    /// Removes the specified displays from the device.
790    fn remove_displays(&mut self, display_ids: Vec<u32>) -> GpuControlResult {
791        for display_id in display_ids {
792            if let Some(mut scanout) = self.scanouts.remove(&display_id) {
793                // Release the cursor along with the display it is on.
794                if self.cursor_scanout.parent_scanout_id == Some(display_id) {
795                    self.cursor_scanout.release_surface(&self.display);
796                    self.cursor_scanout.resource_id = None;
797                    self.cursor_scanout.parent_scanout_id = None;
798                }
799                scanout.release_surface(&self.display);
800            } else {
801                return GpuControlResult::NoSuchDisplay { display_id };
802            }
803        }
804
805        self.scanouts_updated.signal();
806        GpuControlResult::DisplaysUpdated
807    }
808
809    fn set_display_mouse_mode(
810        &mut self,
811        display_id: u32,
812        mouse_mode: MouseMode,
813    ) -> GpuControlResult {
814        match self.scanouts.get_mut(&display_id) {
815            Some(scanout) => match scanout.set_mouse_mode(&self.display, mouse_mode) {
816                Ok(_) => GpuControlResult::DisplayMouseModeSet,
817                Err(e) => GpuControlResult::ErrString(e.to_string()),
818            },
819            None => GpuControlResult::NoSuchDisplay { display_id },
820        }
821    }
822
823    /// Performs the given command to interact with or modify the device.
824    pub fn process_gpu_control_command(&mut self, cmd: GpuControlCommand) -> GpuControlResult {
825        match cmd {
826            GpuControlCommand::AddDisplays { displays } => self.add_displays(displays),
827            GpuControlCommand::ListDisplays => self.list_displays(),
828            GpuControlCommand::RemoveDisplays { display_ids } => self.remove_displays(display_ids),
829            GpuControlCommand::SetDisplayMouseMode {
830                display_id,
831                mouse_mode,
832            } => self.set_display_mouse_mode(display_id, mouse_mode),
833        }
834    }
835
836    /// Processes the internal `display` events and returns `true` if any display was closed.
837    pub fn process_display(&mut self) -> ProcessDisplayResult {
838        let mut display = self.display.borrow_mut();
839        let result = display.dispatch_events();
840        match result {
841            Ok(_) => (),
842            Err(e) => {
843                error!("failed to dispatch events: {}", e);
844                return ProcessDisplayResult::Error(e);
845            }
846        }
847
848        for scanout in self.scanouts.values() {
849            let close_requested = scanout
850                .surface_id
851                .map(|surface_id| display.close_requested(surface_id))
852                .unwrap_or(false);
853
854            if close_requested {
855                return ProcessDisplayResult::CloseRequested;
856            }
857        }
858
859        ProcessDisplayResult::Success
860    }
861
862    /// Sets the given resource id as the source of scanout to the display.
863    pub fn set_scanout(
864        &mut self,
865        scanout_rect: virtio_gpu_rect,
866        scanout_id: u32,
867        resource_id: u32,
868        scanout_data: Option<VirtioScanoutBlobData>,
869    ) -> VirtioGpuResult {
870        self.update_scanout_resource(
871            SurfaceType::Scanout,
872            Some(scanout_rect),
873            scanout_id,
874            scanout_data,
875            resource_id,
876        )
877    }
878
879    /// If the resource is the scanout resource, flush it to the display.
880    pub fn flush_resource(&mut self, resource_id: u32) -> VirtioGpuResult {
881        if resource_id == 0 {
882            return Ok(OkNoData);
883        }
884
885        #[cfg(windows)]
886        match self.rutabaga.resource_flush(resource_id) {
887            Ok(_) => return Ok(OkNoData),
888            Err(RutabagaError::MagmaGpuError(RutabagaUnsupported)) => {}
889            Err(e) => return Err(ErrRutabaga(e)),
890        }
891
892        let resource = self
893            .resources
894            .get_mut(&resource_id)
895            .ok_or(ErrInvalidResourceId)?;
896
897        // `resource_id` has already been verified to be non-zero
898        let resource_id = match NonZeroU32::new(resource_id) {
899            Some(id) => Some(id),
900            None => return Ok(OkNoData),
901        };
902
903        for scanout in self.scanouts.values_mut() {
904            if scanout.resource_id == resource_id {
905                scanout.flush(&self.display, resource, &mut self.rutabaga)?;
906            }
907        }
908        if self.cursor_scanout.resource_id == resource_id {
909            self.cursor_scanout
910                .flush(&self.display, resource, &mut self.rutabaga)?;
911        }
912
913        Ok(OkNoData)
914    }
915
916    /// Updates the cursor's memory to the given resource_id, and sets its position to the given
917    /// coordinates.
918    pub fn update_cursor(
919        &mut self,
920        resource_id: u32,
921        scanout_id: u32,
922        x: u32,
923        y: u32,
924    ) -> VirtioGpuResult {
925        self.update_scanout_resource(SurfaceType::Cursor, None, scanout_id, None, resource_id)?;
926        if resource_id == 0 {
927            // The cursor is disabled, or it is on another scanout and must not move.
928            return Ok(OkNoData);
929        }
930
931        self.cursor_scanout.set_position(&self.display, x, y)?;
932
933        self.flush_resource(resource_id)
934    }
935
936    /// Moves the cursor's position to the given coordinates.
937    pub fn move_cursor(&mut self, _scanout_id: u32, x: u32, y: u32) -> VirtioGpuResult {
938        self.cursor_scanout.set_position(&self.display, x, y)?;
939        self.cursor_scanout.commit(&self.display)?;
940        Ok(OkNoData)
941    }
942
943    /// Returns a uuid for the resource.
944    pub fn resource_assign_uuid(&self, resource_id: u32) -> VirtioGpuResult {
945        if !self.resources.contains_key(&resource_id) {
946            return Err(ErrInvalidResourceId);
947        }
948
949        // TODO(stevensd): use real uuids once the virtio wayland protocol is updated to
950        // handle more than 32 bits. For now, the virtwl driver knows that the uuid is
951        // actually just the resource id.
952        let mut uuid: [u8; 16] = [0; 16];
953        for (idx, byte) in resource_id.to_be_bytes().iter().enumerate() {
954            uuid[12 + idx] = *byte;
955        }
956        Ok(OkResourceUuid { uuid })
957    }
958
959    /// If supported, export the resource with the given `resource_id` to a file.
960    pub fn export_resource(&mut self, resource_id: u32) -> ResourceResponse {
961        let handle = match self.rutabaga.export_blob(resource_id) {
962            Ok(handle) => {
963                let Ok(handle) = RutabagaMagmaHandle::try_from(handle) else {
964                    return ResourceResponse::Invalid;
965                };
966                to_safe_descriptor(handle.os_handle)
967            }
968            Err(_) => return ResourceResponse::Invalid,
969        };
970
971        let q = match self.rutabaga.resource3d_info(resource_id) {
972            Ok(query) => query,
973            Err(_) => return ResourceResponse::Invalid,
974        };
975
976        // Use tracked `guest_cpu_mappable` from `VirtioGpuResource` because `rutabaga` has
977        // deprecated and unimplemented the `guest_cpu_mappable` method.
978        let guest_cpu_mappable = self
979            .resources
980            .get(&resource_id)
981            .map(|r| r.guest_cpu_mappable)
982            .unwrap_or(false);
983
984        ResourceResponse::Resource(ResourceInfo::Buffer(BufferInfo {
985            handle,
986            planes: [
987                PlaneInfo {
988                    offset: q.offsets[0],
989                    stride: q.strides[0],
990                },
991                PlaneInfo {
992                    offset: q.offsets[1],
993                    stride: q.strides[1],
994                },
995                PlaneInfo {
996                    offset: q.offsets[2],
997                    stride: q.strides[2],
998                },
999                PlaneInfo {
1000                    offset: q.offsets[3],
1001                    stride: q.strides[3],
1002                },
1003            ],
1004            modifier: q.modifier,
1005            guest_cpu_mappable,
1006        }))
1007    }
1008
1009    /// If supported, export the fence with the given `fence_id` to a file.
1010    pub fn export_fence(&mut self, fence_id: u64) -> ResourceResponse {
1011        match self.rutabaga.export_fence(fence_id) {
1012            Ok(handle) => ResourceResponse::Resource(ResourceInfo::Fence {
1013                handle: to_safe_descriptor(handle.os_handle),
1014            }),
1015            Err(_) => ResourceResponse::Invalid,
1016        }
1017    }
1018
1019    /// Gets rutabaga's capset information associated with `index`.
1020    pub fn get_capset_info(&self, index: u32) -> VirtioGpuResult {
1021        if let Ok((capset_id, version, size)) = self.rutabaga.get_capset_info(index) {
1022            Ok(OkCapsetInfo {
1023                capset_id,
1024                version,
1025                size,
1026            })
1027        } else {
1028            // Any capset_id > 63 is invalid according to the virtio-gpu spec, so we can
1029            // intentionally poison the capset without stalling the guest kernel driver.
1030            base::warn!(
1031                "virtio-gpu get_capset_info(index={}) failed. intentionally poisoning response",
1032                index
1033            );
1034            Ok(OkCapsetInfo {
1035                capset_id: u32::MAX,
1036                version: 0,
1037                size: 0,
1038            })
1039        }
1040    }
1041
1042    /// Gets a capset from rutabaga.
1043    pub fn get_capset(&self, capset_id: u32, version: u32) -> VirtioGpuResult {
1044        let capset = self.rutabaga.get_capset(capset_id, version)?;
1045        Ok(OkCapset(capset))
1046    }
1047
1048    /// Forces rutabaga to use it's default context.
1049    pub fn force_ctx_0(&self) {
1050        self.rutabaga.force_ctx_0()
1051    }
1052
1053    /// Creates a fence with the RutabagaFence that can be used to determine when the previous
1054    /// command completed.
1055    pub fn create_fence(&mut self, rutabaga_fence: RutabagaFence) -> VirtioGpuResult {
1056        self.rutabaga.create_fence(rutabaga_fence)?;
1057        Ok(OkNoData)
1058    }
1059
1060    /// Polls the Rutabaga backend.
1061    pub fn event_poll(&self) {
1062        self.rutabaga.event_poll();
1063    }
1064
1065    /// Gets a pollable eventfd that signals the device to wakeup and poll the
1066    /// Rutabaga backend.
1067    pub fn poll_descriptor(&self) -> Option<SafeDescriptor> {
1068        self.rutabaga.poll_descriptor().map(to_safe_descriptor)
1069    }
1070
1071    /// Creates a 3D resource with the given properties and resource_id.
1072    pub fn resource_create_3d(
1073        &mut self,
1074        resource_id: u32,
1075        resource_create_3d: ResourceCreate3D,
1076    ) -> VirtioGpuResult {
1077        self.rutabaga
1078            .resource_create_3d(resource_id, resource_create_3d)?;
1079
1080        let resource = VirtioGpuResource::new(
1081            resource_id,
1082            resource_create_3d.width,
1083            resource_create_3d.height,
1084            0,
1085            false,
1086        );
1087
1088        // Rely on rutabaga to check for duplicate resource ids.
1089        self.resources.insert(resource_id, resource);
1090        Ok(self.result_from_query(resource_id))
1091    }
1092
1093    /// Attaches backing memory to the given resource, represented by a `Vec` of `(address, size)`
1094    /// tuples in the guest's physical address space. Converts to RutabagaIovec from the memory
1095    /// mapping.
1096    pub fn attach_backing(
1097        &mut self,
1098        resource_id: u32,
1099        mem: &GuestMemory,
1100        vecs: Vec<(GuestAddress, usize)>,
1101    ) -> VirtioGpuResult {
1102        let resource = self
1103            .resources
1104            .get_mut(&resource_id)
1105            .ok_or(ErrInvalidResourceId)?;
1106
1107        let rutabaga_iovecs = sglist_to_rutabaga_iovecs(&vecs[..], mem).map_err(|_| ErrUnspec)?;
1108        self.rutabaga.attach_backing(resource_id, rutabaga_iovecs)?;
1109        resource.backing_iovecs = Some(vecs);
1110        Ok(OkNoData)
1111    }
1112
1113    /// Detaches any previously attached iovecs from the resource.
1114    pub fn detach_backing(&mut self, resource_id: u32) -> VirtioGpuResult {
1115        let resource = self
1116            .resources
1117            .get_mut(&resource_id)
1118            .ok_or(ErrInvalidResourceId)?;
1119
1120        self.rutabaga.detach_backing(resource_id)?;
1121        resource.backing_iovecs = None;
1122        Ok(OkNoData)
1123    }
1124
1125    /// Releases guest kernel reference on the resource.
1126    pub fn unref_resource(&mut self, resource_id: u32) -> VirtioGpuResult {
1127        let resource = self
1128            .resources
1129            .remove(&resource_id)
1130            .ok_or(ErrInvalidResourceId)?;
1131
1132        let mut display = self.display.borrow_mut();
1133        for (surface_id, import_id) in resource.display_import {
1134            display.release_import(surface_id, import_id);
1135        }
1136
1137        if let Some(shmem_offset) = resource.shmem_offset {
1138            if let Some(mapper) = self.mapper.lock().as_mut() {
1139                if let Err(e) = mapper.remove_mapping(shmem_offset) {
1140                    error!("failed to remove memory mapping: {:#}", e);
1141                }
1142            }
1143        }
1144
1145        if resource.rutabaga_external_mapping {
1146            self.rutabaga.unmap(resource_id)?;
1147        }
1148
1149        self.rutabaga.unref_resource(resource_id)?;
1150        Ok(OkNoData)
1151    }
1152
1153    /// Copies data to host resource from the attached iovecs. Can also be used to flush caches.
1154    pub fn transfer_write(
1155        &mut self,
1156        ctx_id: u32,
1157        resource_id: u32,
1158        transfer: Transfer3D,
1159    ) -> VirtioGpuResult {
1160        self.rutabaga
1161            .transfer_write(ctx_id, resource_id, transfer, None)?;
1162        Ok(OkNoData)
1163    }
1164
1165    /// Copies data from the host resource to:
1166    ///    1) To the optional volatile slice
1167    ///    2) To the host resource's attached iovecs
1168    ///
1169    /// Can also be used to invalidate caches.
1170    pub fn transfer_read(
1171        &mut self,
1172        ctx_id: u32,
1173        resource_id: u32,
1174        transfer: Transfer3D,
1175        buf: Option<VolatileSlice>,
1176    ) -> VirtioGpuResult {
1177        let buf = buf.map(|vs| {
1178            IoSliceMut::new(
1179                // SAFETY: trivially safe
1180                unsafe { std::slice::from_raw_parts_mut(vs.as_mut_ptr(), vs.size()) },
1181            )
1182        });
1183        self.rutabaga
1184            .transfer_read(ctx_id, resource_id, transfer, buf)?;
1185        Ok(OkNoData)
1186    }
1187
1188    /// Creates a blob resource using rutabaga.
1189    pub fn resource_create_blob(
1190        &mut self,
1191        ctx_id: u32,
1192        resource_id: u32,
1193        resource_create_blob: ResourceCreateBlob,
1194        vecs: Vec<(GuestAddress, usize)>,
1195        mem: &GuestMemory,
1196    ) -> VirtioGpuResult {
1197        let mut descriptor = None;
1198        let mut rutabaga_iovecs = None;
1199
1200        if resource_create_blob.blob_flags & VIRTIO_GPU_BLOB_FLAG_CREATE_GUEST_HANDLE != 0 {
1201            descriptor = match self.udmabuf_driver {
1202                Some(ref driver) => Some(driver.create_udmabuf(mem, &vecs[..])?),
1203                None => return Err(ErrUnspec),
1204            }
1205        } else if resource_create_blob.blob_mem != VIRTIO_GPU_BLOB_MEM_HOST3D {
1206            rutabaga_iovecs =
1207                Some(sglist_to_rutabaga_iovecs(&vecs[..], mem).map_err(|_| ErrUnspec)?);
1208        }
1209
1210        self.rutabaga.resource_create_blob(
1211            ctx_id,
1212            resource_id,
1213            resource_create_blob,
1214            rutabaga_iovecs,
1215            descriptor.map(|descriptor| {
1216                RutabagaMagmaHandle {
1217                    os_handle: to_rutabaga_descriptor(descriptor),
1218                    handle_type: RUTABAGA_HANDLE_TYPE_MEM_DMABUF,
1219                }
1220                .into()
1221            }),
1222        )?;
1223
1224        let guest_cpu_mappable =
1225            (resource_create_blob.blob_flags & VIRTIO_GPU_BLOB_FLAG_USE_MAPPABLE) != 0;
1226        let resource = VirtioGpuResource::new(
1227            resource_id,
1228            0,
1229            0,
1230            resource_create_blob.size,
1231            guest_cpu_mappable,
1232        );
1233
1234        // Rely on rutabaga to check for duplicate resource ids.
1235        self.resources.insert(resource_id, resource);
1236        Ok(self.result_from_query(resource_id))
1237    }
1238
1239    /// Uses the hypervisor to map the rutabaga blob resource.
1240    ///
1241    /// When sandboxing is disabled, external_blob is unset and opaque fds are mapped by
1242    /// rutabaga as ExternalMapping.
1243    /// When sandboxing is enabled, external_blob is set and opaque fds must be mapped in the
1244    /// hypervisor process by Vulkano using metadata provided by Rutabaga::vulkan_info().
1245    pub fn resource_map_blob(
1246        &mut self,
1247        resource_id: u32,
1248        offset: u64,
1249    ) -> anyhow::Result<GpuResponse> {
1250        let resource = self
1251            .resources
1252            .get_mut(&resource_id)
1253            .with_context(|| format!("can't find the resource with id {resource_id}"))
1254            .context(ErrInvalidResourceId)?;
1255
1256        let map_info = self
1257            .rutabaga
1258            .map_info(resource_id)
1259            .context("failed to retrieve the map info for the resource")
1260            .context(ErrUnspec)?;
1261
1262        let mut source: Option<VmMemorySource> = None;
1263        if let Ok(export) = self.rutabaga.export_blob(resource_id) {
1264            let export = RutabagaMagmaHandle::try_from(export)
1265                .context("failed to retrieve the handle info")
1266                .context(ErrUnspec)?;
1267            // Prefer descriptor handling even in the presence `vulkan_info` to avoid
1268            // the need for a vulkan instance in the main crosvm process.
1269            if export.handle_type != RUTABAGA_HANDLE_TYPE_MEM_OPAQUE_FD {
1270                source = Some(VmMemorySource::Descriptor {
1271                    descriptor: to_safe_descriptor(export.os_handle),
1272                    offset: 0,
1273                    size: resource.size,
1274                });
1275            } else if let Ok(vulkan_info) = self.rutabaga.vulkan_info(resource_id) {
1276                source = Some(VmMemorySource::Vulkan {
1277                    descriptor: to_safe_descriptor(export.os_handle),
1278                    handle_type: export.handle_type,
1279                    memory_idx: vulkan_info.memory_idx,
1280                    device_uuid: vulkan_info.device_id.device_uuid,
1281                    driver_uuid: vulkan_info.device_id.driver_uuid,
1282                    size: resource.size,
1283                });
1284            }
1285        }
1286
1287        // fallback to ExternalMapping via rutabaga if sandboxing (hence external_blob) and fixed
1288        // mapping are both disabled as neither is currently compatible.
1289        if source.is_none() {
1290            anyhow::ensure!(
1291                !self.external_blob,
1292                "can't fallback to external mapping with external blob enabled"
1293            );
1294            anyhow::ensure!(
1295                !self.fixed_blob_mapping,
1296                "can't fallback to external mapping with fixed blob mapping enabled"
1297            );
1298
1299            let mapping = self.rutabaga.map(resource_id).map_err(|e| {
1300                anyhow::anyhow!("failed to map via rutabaga").context(GpuResponse::ErrRutabaga(e))
1301            })?;
1302            // resources mapped via rutabaga must also be marked for unmap via rutabaga.
1303            resource.rutabaga_external_mapping = true;
1304            source = Some(VmMemorySource::ExternalMapping {
1305                ptr: mapping.ptr,
1306                size: mapping.size,
1307            });
1308        };
1309
1310        let prot = match map_info & RUTABAGA_MAP_ACCESS_MASK {
1311            RUTABAGA_MAP_ACCESS_READ => Protection::read(),
1312            RUTABAGA_MAP_ACCESS_WRITE => Protection::write(),
1313            RUTABAGA_MAP_ACCESS_RW => Protection::read_write(),
1314            access_flags => {
1315                return Err(anyhow::anyhow!(
1316                    "unrecognized access flags {:#x}",
1317                    access_flags
1318                ))
1319                .context(ErrUnspec)
1320            }
1321        };
1322
1323        let cache = if cfg!(feature = "noncoherent-dma")
1324            && map_info & RUTABAGA_MAP_CACHE_MASK != RUTABAGA_MAP_CACHE_CACHED
1325        {
1326            MemCacheType::CacheNonCoherent
1327        } else {
1328            MemCacheType::CacheCoherent
1329        };
1330
1331        self.mapper
1332            .lock()
1333            .as_mut()
1334            .expect("No backend request connection found")
1335            .add_mapping(source.unwrap(), offset, prot, cache)
1336            .context("failed to add the memory mapping")
1337            .context(ErrUnspec)?;
1338
1339        resource.shmem_offset = Some(offset);
1340        // Access flags not a part of the virtio-gpu spec.
1341        Ok(OkMapInfo {
1342            map_info: map_info & RUTABAGA_MAP_CACHE_MASK,
1343        })
1344    }
1345
1346    /// Uses the hypervisor to unmap the blob resource.
1347    pub fn resource_unmap_blob(&mut self, resource_id: u32) -> VirtioGpuResult {
1348        let resource = self
1349            .resources
1350            .get_mut(&resource_id)
1351            .ok_or(ErrInvalidResourceId)?;
1352
1353        let shmem_offset = resource.shmem_offset.ok_or(ErrUnspec)?;
1354        self.mapper
1355            .lock()
1356            .as_mut()
1357            .expect("No backend request connection found")
1358            .remove_mapping(shmem_offset)
1359            .map_err(|_| ErrUnspec)?;
1360        resource.shmem_offset = None;
1361
1362        if resource.rutabaga_external_mapping {
1363            self.rutabaga.unmap(resource_id)?;
1364            resource.rutabaga_external_mapping = false;
1365        }
1366
1367        Ok(OkNoData)
1368    }
1369
1370    /// Gets the EDID for the specified scanout ID. If that scanout is not enabled, it would return
1371    /// the EDID of a default display.
1372    pub fn get_edid(&self, scanout_id: u32) -> VirtioGpuResult {
1373        let display_info = match self.scanouts.get(&scanout_id) {
1374            Some(scanout) => {
1375                // Primary scanouts should always have display params.
1376                let params = scanout.display_params.as_ref().unwrap();
1377                DisplayInfo::new(params)
1378            }
1379            None => DisplayInfo::new(&Default::default()),
1380        };
1381        EdidBytes::new(&display_info)
1382    }
1383
1384    /// Creates a rutabaga context.
1385    pub fn create_context(
1386        &mut self,
1387        ctx_id: u32,
1388        context_init: u32,
1389        context_name: Option<&str>,
1390    ) -> VirtioGpuResult {
1391        self.rutabaga
1392            .create_context(ctx_id, context_init, context_name)?;
1393        Ok(OkNoData)
1394    }
1395
1396    /// Destroys a rutabaga context.
1397    pub fn destroy_context(&mut self, ctx_id: u32) -> VirtioGpuResult {
1398        self.rutabaga.destroy_context(ctx_id)?;
1399        Ok(OkNoData)
1400    }
1401
1402    /// Attaches a resource to a rutabaga context.
1403    pub fn context_attach_resource(&mut self, ctx_id: u32, resource_id: u32) -> VirtioGpuResult {
1404        self.rutabaga.context_attach_resource(ctx_id, resource_id)?;
1405        Ok(OkNoData)
1406    }
1407
1408    /// Detaches a resource from a rutabaga context.
1409    pub fn context_detach_resource(&mut self, ctx_id: u32, resource_id: u32) -> VirtioGpuResult {
1410        self.rutabaga.context_detach_resource(ctx_id, resource_id)?;
1411        Ok(OkNoData)
1412    }
1413
1414    /// Submits a command buffer to a rutabaga context.
1415    pub fn submit_command(
1416        &mut self,
1417        ctx_id: u32,
1418        commands: &mut [u8],
1419        fence_ids: &[u64],
1420    ) -> VirtioGpuResult {
1421        self.rutabaga.submit_command(ctx_id, commands, fence_ids)?;
1422        Ok(OkNoData)
1423    }
1424
1425    // Non-public function -- no doc comment needed!
1426    fn result_from_query(&mut self, resource_id: u32) -> GpuResponse {
1427        match self.rutabaga.resource3d_info(resource_id) {
1428            Ok(query) => {
1429                let mut plane_info = Vec::with_capacity(4);
1430                for plane_index in 0..4 {
1431                    plane_info.push(GpuResponsePlaneInfo {
1432                        stride: query.strides[plane_index],
1433                        offset: query.offsets[plane_index],
1434                    });
1435                }
1436                let format_modifier = query.modifier;
1437                OkResourcePlaneInfo {
1438                    format_modifier,
1439                    plane_info,
1440                }
1441            }
1442            Err(_) => OkNoData,
1443        }
1444    }
1445
1446    fn update_scanout_resource(
1447        &mut self,
1448        scanout_type: SurfaceType,
1449        scanout_rect: Option<virtio_gpu_rect>,
1450        scanout_id: u32,
1451        scanout_data: Option<VirtioScanoutBlobData>,
1452        resource_id: u32,
1453    ) -> VirtioGpuResult {
1454        if scanout_id as usize >= VIRTIO_GPU_MAX_SCANOUTS {
1455            return Err(ErrInvalidScanoutId);
1456        }
1457
1458        // Virtio spec: "The driver can use resource_id = 0 to disable a scanout."
1459        //
1460        // This does not require the scanout to still exist: the guest may disable a scanout after
1461        // the host has already removed the display, e.g. while handling a display hotplug.
1462        if resource_id == 0 {
1463            let scanout = match scanout_type {
1464                // All scanouts share one cursor, so only disable it from the scanout it is on.
1465                SurfaceType::Cursor => Some(&mut self.cursor_scanout)
1466                    .filter(|cursor| cursor.parent_scanout_id == Some(scanout_id)),
1467                SurfaceType::Scanout => self.scanouts.get_mut(&scanout_id),
1468            };
1469            if let Some(scanout) = scanout {
1470                // Ignore any initial set_scanout(..., resource_id: 0) calls.
1471                if scanout.resource_id.take().is_some() {
1472                    scanout.release_surface(&self.display);
1473                }
1474                scanout.parent_scanout_id = None;
1475            }
1476            return Ok(OkNoData);
1477        }
1478
1479        let scanout: &mut VirtioGpuScanout;
1480        let mut scanout_parent_surface_id = None;
1481
1482        match scanout_type {
1483            SurfaceType::Cursor => {
1484                let parent_scanout_id = scanout_id;
1485
1486                scanout_parent_surface_id = self
1487                    .scanouts
1488                    .get(&parent_scanout_id)
1489                    .ok_or(ErrInvalidScanoutId)
1490                    .map(|parent_scanout| parent_scanout.surface_id)?;
1491
1492                scanout = &mut self.cursor_scanout;
1493            }
1494            SurfaceType::Scanout => {
1495                scanout = self
1496                    .scanouts
1497                    .get_mut(&scanout_id)
1498                    .ok_or(ErrInvalidScanoutId)?;
1499            }
1500        };
1501
1502        let resource = self
1503            .resources
1504            .get_mut(&resource_id)
1505            .ok_or(ErrInvalidResourceId)?;
1506
1507        // Ensure scanout has a display surface.
1508        match scanout_type {
1509            SurfaceType::Cursor => {
1510                if let Some(scanout_parent_surface_id) = scanout_parent_surface_id {
1511                    scanout.create_surface(
1512                        &self.display,
1513                        Some(scanout_parent_surface_id),
1514                        scanout_rect,
1515                    )?;
1516                }
1517            }
1518            SurfaceType::Scanout => {
1519                scanout.create_surface(&self.display, None, scanout_rect)?;
1520            }
1521        }
1522
1523        let info = scanout_data.map(|scanout_data| Resource3DInfo {
1524            width: scanout_data.width,
1525            height: scanout_data.height,
1526            drm_fourcc: scanout_data.drm_format,
1527            strides: scanout_data.strides,
1528            offsets: scanout_data.offsets,
1529            modifier: 0,
1530        });
1531
1532        let _ = self.rutabaga.set_scanout(scanout_id, resource_id, info);
1533
1534        resource.scanout_data = scanout_data;
1535
1536        // `resource_id` has already been verified to be non-zero
1537        let resource_id = match NonZeroU32::new(resource_id) {
1538            Some(id) => id,
1539            None => return Ok(OkNoData),
1540        };
1541        scanout.resource_id = Some(resource_id);
1542        if scanout_type == SurfaceType::Cursor {
1543            scanout.parent_scanout_id = Some(scanout_id);
1544        }
1545
1546        Ok(OkNoData)
1547    }
1548
1549    pub fn suspend(&self) -> anyhow::Result<()> {
1550        self.rutabaga
1551            .suspend()
1552            .context("failed to suspend rutabaga")
1553    }
1554
1555    pub fn snapshot(&self) -> anyhow::Result<VirtioGpuSnapshot> {
1556        let snapshot_directory_tempdir = if let Some(dir) = &self.snapshot_scratch_directory {
1557            tempfile::tempdir_in(dir).with_context(|| {
1558                format!(
1559                    "failed to create tempdir in {} for gpu rutabaga snapshot",
1560                    dir.display()
1561                )
1562            })?
1563        } else {
1564            tempfile::tempdir().context("failed to create tempdir for gpu rutabaga snapshot")?
1565        };
1566        let snapshot_directory = snapshot_directory_tempdir.path();
1567
1568        Ok(VirtioGpuSnapshot {
1569            scanouts: self
1570                .scanouts
1571                .iter()
1572                .map(|(i, s)| (*i, s.snapshot()))
1573                .collect(),
1574            scanouts_updated: self.scanouts_updated.is_pending(),
1575            cursor_scanout: self.cursor_scanout.snapshot(),
1576            rutabaga: {
1577                self.rutabaga
1578                    .snapshot(snapshot_directory)
1579                    .context("failed to snapshot rutabaga")?;
1580
1581                pack_directory_to_snapshot(snapshot_directory).with_context(|| {
1582                    format!(
1583                        "failed to pack rutabaga snapshot from {}",
1584                        snapshot_directory.display()
1585                    )
1586                })?
1587            },
1588            resources: self
1589                .resources
1590                .iter()
1591                .map(|(i, r)| (*i, r.snapshot()))
1592                .collect(),
1593        })
1594    }
1595
1596    pub fn restore(&mut self, snapshot: VirtioGpuSnapshot) -> anyhow::Result<()> {
1597        self.deferred_snapshot_load = Some(snapshot);
1598        Ok(())
1599    }
1600
1601    pub fn resume(&mut self, mem: &GuestMemory) -> anyhow::Result<()> {
1602        if let Some(snapshot) = self.deferred_snapshot_load.take() {
1603            assert!(self.scanouts.keys().eq(snapshot.scanouts.keys()));
1604            for (i, s) in snapshot.scanouts.into_iter() {
1605                self.scanouts
1606                    .get_mut(&i)
1607                    .unwrap()
1608                    .restore(
1609                        s,
1610                        // Only the cursor scanout can have a parent.
1611                        None,
1612                        &self.display,
1613                    )
1614                    .context("failed to restore scanouts")?;
1615            }
1616            self.scanouts_updated.set_pending(snapshot.scanouts_updated);
1617
1618            let cursor_parent_surface_id = snapshot
1619                .cursor_scanout
1620                .parent_scanout_id
1621                .and_then(|i| self.scanouts.get(&i).unwrap().surface_id);
1622            self.cursor_scanout
1623                .restore(
1624                    snapshot.cursor_scanout,
1625                    cursor_parent_surface_id,
1626                    &self.display,
1627                )
1628                .context("failed to restore cursor scanout")?;
1629
1630            let snapshot_directory_tempdir = if let Some(dir) = &self.snapshot_scratch_directory {
1631                tempfile::tempdir_in(dir).with_context(|| {
1632                    format!(
1633                        "failed to create tempdir in {} for gpu rutabaga snapshot",
1634                        dir.display()
1635                    )
1636                })?
1637            } else {
1638                tempfile::tempdir().context("failed to create tempdir for gpu rutabaga snapshot")?
1639            };
1640            let snapshot_directory = snapshot_directory_tempdir.path();
1641
1642            unpack_snapshot_to_directory(snapshot_directory, snapshot.rutabaga).with_context(
1643                || {
1644                    format!(
1645                        "failed to unpack rutabaga snapshot to {}",
1646                        snapshot_directory.display()
1647                    )
1648                },
1649            )?;
1650            self.rutabaga
1651                .restore(snapshot_directory)
1652                .context("failed to restore rutabaga")?;
1653
1654            for (id, s) in snapshot.resources.into_iter() {
1655                let backing_iovecs = s.backing_iovecs.clone();
1656                let shmem_offset = s.shmem_offset;
1657                self.resources.insert(id, VirtioGpuResource::restore(s));
1658                if let Some(backing_iovecs) = backing_iovecs {
1659                    self.attach_backing(id, mem, backing_iovecs)
1660                        .context("failed to restore resource backing")?;
1661                }
1662                if let Some(shmem_offset) = shmem_offset {
1663                    self.resource_map_blob(id, shmem_offset)
1664                        .context("failed to restore resource mapping")?;
1665                }
1666            }
1667        }
1668
1669        self.rutabaga.resume().context("failed to resume rutabaga")
1670    }
1671}
1672
1673#[cfg(all(test, unix))]
1674mod tests {
1675    use base::SharedMemory;
1676    use cros_async::MemRegion;
1677    use rutabaga_gfx::RutabagaBuilder;
1678    use rutabaga_gfx::RutabagaComponentType;
1679    use rutabaga_gfx::RutabagaFenceHandler;
1680    use rutabaga_gfx::RUTABAGA_CAPSET_CROSS_DOMAIN;
1681    use smallvec::smallvec;
1682
1683    use super::*;
1684    use crate::virtio::gpu::protocol::virtio_gpu_cmd_submit;
1685    use crate::virtio::gpu::protocol::virtio_gpu_resource_attach_backing;
1686    use crate::virtio::gpu::protocol::virtio_gpu_resource_create_blob;
1687    use crate::virtio::gpu::protocol::GpuCommand;
1688    use crate::virtio::gpu::FenceState;
1689    use crate::virtio::gpu::Frontend;
1690    use crate::virtio::gpu::VIRTIO_GPU_BLOB_FLAG_USE_SHAREABLE;
1691    use crate::virtio::gpu::VIRTIO_GPU_BLOB_MEM_GUEST;
1692    use crate::virtio::Reader;
1693
1694    fn new_test_virtio_gpu() -> VirtioGpu {
1695        let display = GpuDisplay::open_stub().unwrap();
1696        let display_params = vec![
1697            GpuDisplayParameters::default_with_mode(DisplayMode::Windowed(800, 600)),
1698            GpuDisplayParameters::default_with_mode(DisplayMode::Windowed(800, 600)),
1699        ];
1700        let rutabaga = RutabagaBuilder::new(
1701            1 << RUTABAGA_CAPSET_CROSS_DOMAIN,
1702            RutabagaFenceHandler::new(|_| {}),
1703        )
1704        .set_default_component(RutabagaComponentType::CrossDomain)
1705        .build()
1706        .unwrap();
1707        VirtioGpu::new(
1708            display,
1709            display_params,
1710            Arc::new(DisplayEvent::default()),
1711            rutabaga,
1712            Arc::new(Mutex::new(None)),
1713            /* external_blob= */ false,
1714            /* fixed_blob_mapping= */ false,
1715            /* udmabuf= */ false,
1716            /* snapshot_scratch_directory= */ None,
1717        )
1718        .unwrap()
1719    }
1720
1721    fn create_exportable_resource(virtio_gpu: &mut VirtioGpu, resource_id: u32) {
1722        let ctx_id = 1;
1723        let query_ring_id = 100;
1724        let mut ring_buf = vec![0u8; 4096];
1725        virtio_gpu.rutabaga.create_context(ctx_id, 0, None).unwrap();
1726        virtio_gpu
1727            .rutabaga
1728            .resource_create_blob(
1729                0,
1730                query_ring_id,
1731                ResourceCreateBlob {
1732                    blob_mem: VIRTIO_GPU_BLOB_MEM_GUEST,
1733                    blob_flags: VIRTIO_GPU_BLOB_FLAG_USE_MAPPABLE,
1734                    blob_id: 0,
1735                    size: ring_buf.len() as u64,
1736                },
1737                Some(vec![RutabagaIovec {
1738                    base: ring_buf.as_mut_ptr() as *mut c_void,
1739                    len: ring_buf.len(),
1740                }]),
1741                None,
1742            )
1743            .unwrap();
1744        virtio_gpu
1745            .rutabaga
1746            .context_attach_resource(ctx_id, query_ring_id)
1747            .unwrap();
1748
1749        // Submit CrossDomainInitV1 (cmd=1, size=20) + CrossDomainGetImageRequirements (cmd=2,
1750        // size=24).
1751        let cmd_words: [u32; 11] = [
1752            1 | (20 << 16),
1753            0,
1754            query_ring_id,
1755            0,
1756            0,
1757            2 | (24 << 16),
1758            0,
1759            800,
1760            600,
1761            0x34325258,
1762            1 << 4,
1763        ];
1764        let mut cmd_bytes: Vec<u8> = cmd_words.iter().flat_map(|w| w.to_le_bytes()).collect();
1765        virtio_gpu
1766            .rutabaga
1767            .submit_command(ctx_id, &mut cmd_bytes, &[])
1768            .unwrap();
1769        let req_size = u64::from_le_bytes(ring_buf[40..48].try_into().unwrap());
1770        let req_blob_id = u32::from_le_bytes(ring_buf[48..52].try_into().unwrap());
1771
1772        let shm = SharedMemory::new("test_scanout_blob", req_size).unwrap();
1773        let handle = RutabagaMagmaHandle {
1774            os_handle: to_rutabaga_descriptor(shm.into()),
1775            handle_type: RUTABAGA_HANDLE_TYPE_MEM_DMABUF,
1776        }
1777        .into();
1778        virtio_gpu
1779            .rutabaga
1780            .resource_create_blob(
1781                ctx_id,
1782                resource_id,
1783                ResourceCreateBlob {
1784                    blob_mem: VIRTIO_GPU_BLOB_MEM_HOST3D,
1785                    blob_flags: VIRTIO_GPU_BLOB_FLAG_USE_SHAREABLE,
1786                    blob_id: req_blob_id as u64,
1787                    size: req_size,
1788                },
1789                None,
1790                Some(handle),
1791            )
1792            .unwrap();
1793        let resource = VirtioGpuResource::new(resource_id, 800, 600, req_size, false);
1794        virtio_gpu.resources.insert(resource_id, resource);
1795    }
1796
1797    fn scanout_rect(width: u32, height: u32) -> virtio_gpu_rect {
1798        virtio_gpu_rect {
1799            x: 0.into(),
1800            y: 0.into(),
1801            width: width.into(),
1802            height: height.into(),
1803        }
1804    }
1805
1806    #[test]
1807    fn scanout_surface_update_reimports_resource() {
1808        let mut virtio_gpu = new_test_virtio_gpu();
1809        let resource_id = 1;
1810        create_exportable_resource(&mut virtio_gpu, resource_id);
1811
1812        virtio_gpu
1813            .set_scanout(scanout_rect(800, 600), 0, resource_id, None)
1814            .unwrap();
1815        let surface_id_1 = virtio_gpu.scanouts[&0].surface_id.unwrap();
1816
1817        virtio_gpu.flush_resource(resource_id).unwrap();
1818        let import_id_1 = virtio_gpu.resources[&resource_id].display_import[&surface_id_1];
1819
1820        // Flushing again on the same surface reuses the existing import.
1821        virtio_gpu.flush_resource(resource_id).unwrap();
1822        assert_eq!(
1823            virtio_gpu.resources[&resource_id].display_import[&surface_id_1],
1824            import_id_1
1825        );
1826
1827        // Changing the scanout resolution recreates the surface with a new surface_id and
1828        // triggers a new resource import on flush.
1829        virtio_gpu
1830            .set_scanout(scanout_rect(1024, 768), 0, resource_id, None)
1831            .unwrap();
1832        let surface_id_2 = virtio_gpu.scanouts[&0].surface_id.unwrap();
1833        assert_ne!(surface_id_1, surface_id_2);
1834
1835        virtio_gpu.flush_resource(resource_id).unwrap();
1836        let import_id_2 = virtio_gpu.resources[&resource_id].display_import[&surface_id_2];
1837        assert_ne!(import_id_1, import_id_2);
1838
1839        // Flushing the same resource on a second scanout imports it for that scanout's surface
1840        // without evicting the first scanout's import.
1841        virtio_gpu
1842            .set_scanout(scanout_rect(800, 600), 1, resource_id, None)
1843            .unwrap();
1844        let surface_id_3 = virtio_gpu.scanouts[&1].surface_id.unwrap();
1845        virtio_gpu.flush_resource(resource_id).unwrap();
1846        let import_id_3 = virtio_gpu.resources[&resource_id].display_import[&surface_id_3];
1847        assert_eq!(
1848            virtio_gpu.resources[&resource_id]
1849                .display_import
1850                .get(&surface_id_2),
1851            Some(&import_id_2)
1852        );
1853
1854        virtio_gpu.unref_resource(resource_id).unwrap();
1855        assert!(virtio_gpu
1856            .display
1857            .borrow_mut()
1858            .flip_to(surface_id_1, import_id_1, None, None, None)
1859            .is_err());
1860        assert!(virtio_gpu
1861            .display
1862            .borrow_mut()
1863            .flip_to(surface_id_2, import_id_2, None, None, None)
1864            .is_err());
1865        assert!(virtio_gpu
1866            .display
1867            .borrow_mut()
1868            .flip_to(surface_id_3, import_id_3, None, None, None)
1869            .is_err());
1870    }
1871
1872    #[test]
1873    fn unref_resource_releases_display_imports() {
1874        let mut virtio_gpu = new_test_virtio_gpu();
1875        let resource_id = 1;
1876        create_exportable_resource(&mut virtio_gpu, resource_id);
1877
1878        virtio_gpu
1879            .set_scanout(scanout_rect(800, 600), 0, resource_id, None)
1880            .unwrap();
1881        let surface_id_1 = virtio_gpu.scanouts[&0].surface_id.unwrap();
1882        virtio_gpu
1883            .set_scanout(scanout_rect(800, 600), 1, resource_id, None)
1884            .unwrap();
1885        let surface_id_2 = virtio_gpu.scanouts[&1].surface_id.unwrap();
1886
1887        virtio_gpu.flush_resource(resource_id).unwrap();
1888        let import_id_1 = virtio_gpu.resources[&resource_id].display_import[&surface_id_1];
1889        let import_id_2 = virtio_gpu.resources[&resource_id].display_import[&surface_id_2];
1890
1891        assert!(virtio_gpu
1892            .display
1893            .borrow_mut()
1894            .flip_to(surface_id_1, import_id_1, None, None, None)
1895            .is_ok());
1896        assert!(virtio_gpu
1897            .display
1898            .borrow_mut()
1899            .flip_to(surface_id_2, import_id_2, None, None, None)
1900            .is_ok());
1901
1902        virtio_gpu.unref_resource(resource_id).unwrap();
1903
1904        assert!(virtio_gpu
1905            .display
1906            .borrow_mut()
1907            .flip_to(surface_id_1, import_id_1, None, None, None)
1908            .is_err());
1909        assert!(virtio_gpu
1910            .display
1911            .borrow_mut()
1912            .flip_to(surface_id_2, import_id_2, None, None, None)
1913            .is_err());
1914    }
1915
1916    fn create_test_frontend() -> Frontend {
1917        Frontend::new(
1918            new_test_virtio_gpu(),
1919            Arc::new(Mutex::new(FenceState::default())),
1920        )
1921    }
1922
1923    fn create_test_reader(mem: &GuestMemory) -> Reader {
1924        Reader::new_from_regions(mem, smallvec![MemRegion { offset: 0, len: 16 }])
1925    }
1926
1927    #[test]
1928    fn process_gpu_command_resource_attach_backing_oversized() {
1929        let mut frontend = create_test_frontend();
1930        let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap();
1931        let mut reader = create_test_reader(&mem);
1932        let cmd = GpuCommand::ResourceAttachBacking(virtio_gpu_resource_attach_backing {
1933            nr_entries: u32::MAX.into(),
1934            ..Default::default()
1935        });
1936        let res = frontend.process_gpu_command(&mem, cmd, &mut reader);
1937        assert!(matches!(res, Err(GpuResponse::ErrUnspec)));
1938    }
1939
1940    #[test]
1941    fn process_gpu_command_cmd_submit_3d_oversized() {
1942        let mut frontend = create_test_frontend();
1943        let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap();
1944        let mut reader = create_test_reader(&mem);
1945        let cmd = GpuCommand::CmdSubmit3d(virtio_gpu_cmd_submit {
1946            size: u32::MAX.into(),
1947            ..Default::default()
1948        });
1949        let res = frontend.process_gpu_command(&mem, cmd, &mut reader);
1950        assert!(matches!(res, Err(GpuResponse::ErrInvalidParameter)));
1951    }
1952
1953    #[test]
1954    fn process_gpu_command_cmd_submit_3d_empty_reader_nonzero_size() {
1955        let mut frontend = create_test_frontend();
1956        let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap();
1957        let mut reader = Reader::new_from_regions(&mem, smallvec![]);
1958        let cmd = GpuCommand::CmdSubmit3d(virtio_gpu_cmd_submit {
1959            size: 16.into(),
1960            ..Default::default()
1961        });
1962        let res = frontend.process_gpu_command(&mem, cmd, &mut reader);
1963        assert!(matches!(res, Err(GpuResponse::ErrInvalidParameter)));
1964    }
1965
1966    #[test]
1967    fn process_gpu_command_cmd_submit_3d_zero_size() {
1968        let mut frontend = create_test_frontend();
1969        let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap();
1970        for mut reader in [
1971            Reader::new_from_regions(&mem, smallvec![]),
1972            create_test_reader(&mem),
1973        ] {
1974            let cmd = GpuCommand::CmdSubmit3d(virtio_gpu_cmd_submit {
1975                size: 0.into(),
1976                ..Default::default()
1977            });
1978            let res = frontend.process_gpu_command(&mem, cmd, &mut reader);
1979            assert!(matches!(res, Ok(GpuResponse::OkNoData)));
1980        }
1981    }
1982
1983    #[test]
1984    fn process_gpu_command_resource_create_blob_oversized() {
1985        let mut frontend = create_test_frontend();
1986        let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap();
1987        let mut reader = create_test_reader(&mem);
1988        let cmd = GpuCommand::ResourceCreateBlob(virtio_gpu_resource_create_blob {
1989            nr_entries: u32::MAX.into(),
1990            ..Default::default()
1991        });
1992        let res = frontend.process_gpu_command(&mem, cmd, &mut reader);
1993        assert!(matches!(res, Err(GpuResponse::ErrUnspec)));
1994    }
1995
1996    #[test]
1997    fn display_event_clear_acknowledges_only_observed_changes() {
1998        let event = DisplayEvent::default();
1999        assert!(!event.is_pending());
2000
2001        event.signal();
2002        assert!(event.observe_and_is_pending());
2003        // A display change lands after the guest read `events_read` but before it wrote
2004        // `events_clear`.
2005        event.signal();
2006        event.acknowledge_observed();
2007        assert!(event.is_pending());
2008
2009        assert!(event.observe_and_is_pending());
2010        event.acknowledge_observed();
2011        assert!(!event.is_pending());
2012        assert!(!event.observe_and_is_pending());
2013
2014        // Clearing without reading first does not acknowledge anything.
2015        event.signal();
2016        event.acknowledge_observed();
2017        assert!(event.is_pending());
2018    }
2019
2020    #[test]
2021    fn display_event_set_pending() {
2022        let event = DisplayEvent::default();
2023        event.set_pending(true);
2024        assert!(event.is_pending());
2025        event.set_pending(true);
2026        assert!(event.observe_and_is_pending());
2027        event.acknowledge_observed();
2028        assert!(!event.is_pending());
2029
2030        event.signal();
2031        event.set_pending(false);
2032        assert!(!event.is_pending());
2033    }
2034
2035    #[test]
2036    fn display_hotplug_during_events_clear_stays_pending() {
2037        let mut virtio_gpu = new_test_virtio_gpu();
2038        let event = virtio_gpu.scanouts_updated.clone();
2039
2040        // Resize the display by adding the new display before removing the old one.
2041        assert!(matches!(
2042            virtio_gpu.process_gpu_control_command(GpuControlCommand::AddDisplays {
2043                displays: vec![DisplayParameters::default_with_mode(DisplayMode::Windowed(
2044                    1024, 768,
2045                ))],
2046            }),
2047            GpuControlResult::DisplaysUpdated
2048        ));
2049        assert!(event.observe_and_is_pending());
2050        assert!(matches!(
2051            virtio_gpu.process_gpu_control_command(GpuControlCommand::RemoveDisplays {
2052                display_ids: vec![0],
2053            }),
2054            GpuControlResult::DisplaysUpdated
2055        ));
2056        event.acknowledge_observed();
2057        assert!(event.is_pending());
2058
2059        assert!(event.observe_and_is_pending());
2060        assert_eq!(
2061            virtio_gpu.display_info()[..3],
2062            [(0, 0, false), (800, 600, true), (1024, 768, true)]
2063        );
2064        event.acknowledge_observed();
2065        assert!(!event.is_pending());
2066    }
2067
2068    #[test]
2069    fn disable_removed_scanout() {
2070        let mut virtio_gpu = new_test_virtio_gpu();
2071        let resource_id = 1;
2072        create_exportable_resource(&mut virtio_gpu, resource_id);
2073
2074        virtio_gpu
2075            .set_scanout(scanout_rect(800, 600), 0, resource_id, None)
2076            .unwrap();
2077        assert!(virtio_gpu.scanouts[&0].surface_id.is_some());
2078        assert!(matches!(
2079            virtio_gpu.process_gpu_control_command(GpuControlCommand::RemoveDisplays {
2080                display_ids: vec![0],
2081            }),
2082            GpuControlResult::DisplaysUpdated
2083        ));
2084
2085        // The guest disables the scanout of a display the host already removed.
2086        virtio_gpu
2087            .set_scanout(scanout_rect(0, 0), 0, 0, None)
2088            .unwrap();
2089
2090        // Disabling a scanout that never existed is also a no-op.
2091        virtio_gpu
2092            .set_scanout(scanout_rect(0, 0), 5, 0, None)
2093            .unwrap();
2094
2095        // A scanout id the device never reports is rejected.
2096        assert!(matches!(
2097            virtio_gpu.set_scanout(scanout_rect(0, 0), VIRTIO_GPU_MAX_SCANOUTS as u32, 0, None),
2098            Err(ErrInvalidScanoutId)
2099        ));
2100
2101        // Enabling a removed scanout is still rejected.
2102        assert!(matches!(
2103            virtio_gpu.set_scanout(scanout_rect(800, 600), 0, resource_id, None),
2104            Err(ErrInvalidScanoutId)
2105        ));
2106
2107        // The remaining scanout keeps working.
2108        virtio_gpu
2109            .set_scanout(scanout_rect(800, 600), 1, resource_id, None)
2110            .unwrap();
2111        assert!(virtio_gpu.scanouts[&1].surface_id.is_some());
2112    }
2113
2114    #[test]
2115    fn disable_cursor_only_from_its_scanout() {
2116        let mut virtio_gpu = new_test_virtio_gpu();
2117        let resource_id = 1;
2118        create_exportable_resource(&mut virtio_gpu, resource_id);
2119
2120        // The guest moves the cursor from display 0 to display 1, then disables the cursor plane
2121        // of display 0.
2122        virtio_gpu
2123            .update_scanout_resource(SurfaceType::Cursor, None, 0, None, resource_id)
2124            .unwrap();
2125        assert_eq!(virtio_gpu.cursor_scanout.parent_scanout_id, Some(0));
2126        virtio_gpu
2127            .update_scanout_resource(SurfaceType::Cursor, None, 1, None, resource_id)
2128            .unwrap();
2129        assert_eq!(virtio_gpu.cursor_scanout.parent_scanout_id, Some(1));
2130        virtio_gpu.update_cursor(0, 0, 0, 0).unwrap();
2131
2132        // The cursor stays on display 1.
2133        assert_eq!(virtio_gpu.cursor_scanout.parent_scanout_id, Some(1));
2134        assert!(virtio_gpu.cursor_scanout.resource_id.is_some());
2135
2136        // Disabling it from display 1 works.
2137        virtio_gpu.update_cursor(0, 1, 0, 0).unwrap();
2138        assert_eq!(virtio_gpu.cursor_scanout.parent_scanout_id, None);
2139        assert!(virtio_gpu.cursor_scanout.resource_id.is_none());
2140    }
2141
2142    #[test]
2143    fn remove_display_releases_its_cursor() {
2144        let mut virtio_gpu = new_test_virtio_gpu();
2145        let resource_id = 1;
2146        create_exportable_resource(&mut virtio_gpu, resource_id);
2147
2148        // Removing a display the cursor is not on keeps the cursor.
2149        virtio_gpu
2150            .update_scanout_resource(SurfaceType::Cursor, None, 1, None, resource_id)
2151            .unwrap();
2152        assert!(matches!(
2153            virtio_gpu.process_gpu_control_command(GpuControlCommand::RemoveDisplays {
2154                display_ids: vec![0],
2155            }),
2156            GpuControlResult::DisplaysUpdated
2157        ));
2158        assert_eq!(virtio_gpu.cursor_scanout.parent_scanout_id, Some(1));
2159        assert!(virtio_gpu.cursor_scanout.resource_id.is_some());
2160
2161        // Removing the display the cursor is on releases the cursor.
2162        assert!(matches!(
2163            virtio_gpu.process_gpu_control_command(GpuControlCommand::RemoveDisplays {
2164                display_ids: vec![1],
2165            }),
2166            GpuControlResult::DisplaysUpdated
2167        ));
2168        assert_eq!(virtio_gpu.cursor_scanout.parent_scanout_id, None);
2169        assert!(virtio_gpu.cursor_scanout.resource_id.is_none());
2170
2171        // The guest then disables the cursor plane of the removed display.
2172        virtio_gpu.update_cursor(0, 1, 0, 0).unwrap();
2173    }
2174}