gpu_display/
gpu_display_android.rs

1// Copyright 2024 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::collections::HashMap;
6use std::ffi::c_char;
7use std::ffi::CStr;
8use std::ffi::CString;
9use std::os::fd::AsFd;
10use std::os::fd::AsRawFd;
11use std::panic::catch_unwind;
12use std::process::abort;
13use std::ptr::NonNull;
14use std::rc::Rc;
15use std::slice;
16use std::sync::Arc;
17use std::sync::RwLock;
18
19use anyhow::bail;
20use anyhow::Context;
21use base::error;
22use base::AsRawDescriptor;
23use base::Event;
24use base::RawDescriptor;
25use base::VolatileSlice;
26use rutabaga_gfx::AhbInfo;
27use sync::Waitable;
28use vm_control::gpu::DisplayParameters;
29
30use crate::DisplayExternalResourceImport;
31use crate::DisplayT;
32use crate::FlipToExtraInfo;
33use crate::GpuDisplayError;
34use crate::GpuDisplayFramebuffer;
35use crate::GpuDisplayResult;
36use crate::GpuDisplaySurface;
37use crate::SemaphoreTimepoint;
38use crate::SurfaceType;
39use crate::SysDisplayT;
40
41// Opaque blob
42#[repr(C)]
43pub(crate) struct AndroidDisplayContext {
44    _data: [u8; 0],
45    _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
46}
47
48// Opaque blob
49#[repr(C)]
50pub(crate) struct AndroidDisplaySurface {
51    _data: [u8; 0],
52    _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
53}
54
55// Opaque blob
56#[repr(C)]
57pub(crate) struct AHardwareBuffer {
58    _data: [u8; 0],
59    _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
60}
61
62// Should be the same as ANativeWindow_Buffer in android/native_window.h
63// Note that this struct is part of NDK; guaranteed to be stable, so we use it directly across the
64// FFI.
65#[repr(C)]
66pub(crate) struct ANativeWindow_Buffer {
67    width: i32,
68    height: i32,
69    stride: i32, // in number of pixels, NOT bytes
70    format: i32,
71    bits: *mut u8,
72    reserved: [u32; 6],
73}
74
75pub(crate) type ErrorCallback = unsafe extern "C" fn(message: *const c_char);
76
77extern "C" {
78    /// Constructs an AndroidDisplayContext for this backend. This awlays returns a valid (ex:
79    /// non-null) handle to the context. The `name` parameter is from crosvm commandline and the
80    /// client of crosvm will use it to locate and communicate to the AndroidDisplayContext. For
81    /// example, this can be a path to UNIX domain socket where a RPC binder server listens on.
82    /// `error_callback` is a function pointer to an error reporting function, and will be used by
83    /// this and other functions below when something goes wrong. The returned context should be
84    /// destroyed by calling `destroy_android_display_context` if this backend is no longer in use.
85    fn create_android_display_context(
86        name: *const c_char,
87        error_callback: ErrorCallback,
88    ) -> *mut AndroidDisplayContext;
89
90    /// Destroys the AndroidDisplayContext created from `create_android_display_context`.
91    fn destroy_android_display_context(self_: *mut AndroidDisplayContext);
92
93    /// Creates an Android Surface (which is also called as Window) of given size. If the surface
94    /// can't be created for whatever reason, null pointer is returned, in which case we shouldn't
95    /// proceed further.
96    fn create_android_surface(
97        ctx: *mut AndroidDisplayContext,
98        width: u32,
99        height: u32,
100        for_cursor: bool,
101    ) -> *mut AndroidDisplaySurface;
102
103    /// Destroys the Android surface created from `create_android_surface`.
104    #[allow(dead_code)]
105    fn destroy_android_surface(
106        ctx: *mut AndroidDisplayContext,
107        surface: *mut AndroidDisplaySurface,
108    );
109
110    /// Obtains one buffer from the given Android Surface. The information about the buffer (buffer
111    /// address, size, stride, etc) is reported via the `ANativeWindow_Buffer` struct. It shouldn't
112    /// be null. The size of the buffer is guaranteed to be bigger than (width * stride * 4) bytes.
113    /// This function locks the buffer for the client, which means the caller has the exclusive
114    /// access to the buffer until it is returned back to Android display stack (surfaceflinger) by
115    /// calling `post_android_surface_buffer`. This function may fail (in which case false is
116    /// returned), then the caller shouldn't try to read `out_buffer` or use the buffer in any way.
117    fn get_android_surface_buffer(
118        ctx: *mut AndroidDisplayContext,
119        surface: *mut AndroidDisplaySurface,
120        out_buffer: *mut ANativeWindow_Buffer,
121    ) -> bool;
122
123    fn set_android_surface_position(ctx: *mut AndroidDisplayContext, x: u32, y: u32);
124
125    /// Posts the buffer obtained from `get_android_surface_buffer` to the Android display system
126    /// so that it can be displayed on the screen. Once this is called, the caller shouldn't use
127    /// the buffer any more.
128    fn post_android_surface_buffer(
129        ctx: *mut AndroidDisplayContext,
130        surface: *mut AndroidDisplaySurface,
131    );
132
133    /// Creates an AHardwareBuffer from `ahb_info` and returns an owned reference to it, or null on
134    /// failure. The buffer keeps its own copies of the file descriptors, so `ahb_info` does not
135    /// need to outlive the call. The returned buffer must be released with
136    /// `android_display_release_buffer`.
137    fn android_display_import_buffer(
138        ctx: *mut AndroidDisplayContext,
139        ahb_info: *const AHardwareBufferInfo,
140    ) -> *mut AHardwareBuffer;
141
142    /// Presents a buffer returned by `android_display_import_buffer` on the given surface.
143    /// Presenting the same buffer object for the same guest resource lets the Android display
144    /// stack reuse its per-buffer caches instead of re-importing the buffer on every flip.
145    fn android_display_flip_to_imported(
146        ctx: *mut AndroidDisplayContext,
147        surface: *mut AndroidDisplaySurface,
148        ahb: *mut AHardwareBuffer,
149    );
150
151    /// Releases a buffer returned by `android_display_import_buffer`.
152    fn android_display_release_buffer(ahb: *mut AHardwareBuffer);
153}
154
155unsafe extern "C" fn error_callback(message: *const c_char) {
156    catch_unwind(|| {
157        error!(
158            "{}",
159            // SAFETY: message is null terminated
160            unsafe { CStr::from_ptr(message) }.to_string_lossy()
161        )
162    })
163    .unwrap_or_else(|_| abort())
164}
165
166struct AndroidDisplayContextWrapper(NonNull<AndroidDisplayContext>);
167
168impl Drop for AndroidDisplayContextWrapper {
169    fn drop(&mut self) {
170        // SAFETY: this object is constructed from create_android_display_context
171        unsafe { destroy_android_display_context(self.0.as_ptr()) };
172    }
173}
174
175impl Default for ANativeWindow_Buffer {
176    fn default() -> Self {
177        Self {
178            width: 0,
179            height: 0,
180            stride: 0,
181            format: 0,
182            bits: std::ptr::null_mut(),
183            reserved: [0u32; 6],
184        }
185    }
186}
187
188impl From<ANativeWindow_Buffer> for GpuDisplayFramebuffer<'_> {
189    fn from(anb: ANativeWindow_Buffer) -> Self {
190        // TODO: check anb.format to see if it's ARGB8888?
191        // TODO: infer bpp from anb.format?
192        const BYTES_PER_PIXEL: u32 = 4;
193        let stride_bytes = BYTES_PER_PIXEL * u32::try_from(anb.stride).unwrap();
194        let buffer_size = stride_bytes * u32::try_from(anb.height).unwrap();
195        let buffer =
196            // SAFETY: get_android_surface_buffer guarantees that bits points to a valid buffer and
197            // the buffer remains available until post_android_surface_buffer is called.
198            unsafe { slice::from_raw_parts_mut(anb.bits, buffer_size.try_into().unwrap()) };
199        Self::new(VolatileSlice::new(buffer), stride_bytes, BYTES_PER_PIXEL)
200    }
201}
202
203#[repr(C)]
204pub struct AHardwareBufferInfo {
205    pub num_fds: usize,
206    pub fds_ptr: *const i32,
207    pub metadata_len: usize,
208    pub metadata_ptr: *const u8,
209}
210
211/// An owned reference to an AHardwareBuffer created by `android_display_import_buffer`.
212///
213/// Keeping one buffer object per imported guest resource, instead of recreating it on every flip,
214/// gives the buffer a stable identity so the Android display stack can cache it.
215struct ImportedBuffer(NonNull<AHardwareBuffer>);
216
217impl ImportedBuffer {
218    fn import(context: &AndroidDisplayContextWrapper, info: &AhbInfo) -> anyhow::Result<Self> {
219        let fds: Vec<i32> = info.fds.iter().map(|fd| fd.as_fd().as_raw_fd()).collect();
220        let ahb_info = AHardwareBufferInfo {
221            num_fds: fds.len(),
222            fds_ptr: fds.as_ptr(),
223            metadata_len: info.metadata.len(),
224            metadata_ptr: info.metadata.as_ptr(),
225        };
226        // SAFETY: context is an opaque handle. `ahb_info` and the memory it points to outlive the
227        // call, and `android_display_import_buffer` does not retain them.
228        let ahb = unsafe { android_display_import_buffer(context.0.as_ptr(), &ahb_info) };
229        NonNull::new(ahb)
230            .map(ImportedBuffer)
231            .context("failed to import AHardwareBuffer")
232    }
233}
234
235impl Drop for ImportedBuffer {
236    fn drop(&mut self) {
237        // SAFETY: the buffer was returned by `android_display_import_buffer` and is released
238        // exactly once.
239        unsafe { android_display_release_buffer(self.0.as_ptr()) };
240    }
241}
242
243// The key is an import id.
244type AHardwareBufferImportMap = HashMap<u32, ImportedBuffer>;
245
246struct AndroidSurface {
247    context: Rc<AndroidDisplayContextWrapper>,
248    surface: NonNull<AndroidDisplaySurface>,
249    ahb_import_map: Arc<RwLock<AHardwareBufferImportMap>>,
250}
251
252impl GpuDisplaySurface for AndroidSurface {
253    fn framebuffer(&mut self) -> Option<GpuDisplayFramebuffer> {
254        let mut anb = ANativeWindow_Buffer::default();
255        // SAFETY: context and surface are opaque handles and buf is used as the out parameter to
256        // hold the return values.
257        let success = unsafe {
258            get_android_surface_buffer(
259                self.context.0.as_ptr(),
260                self.surface.as_ptr(),
261                &mut anb as *mut ANativeWindow_Buffer,
262            )
263        };
264        if success {
265            Some(anb.into())
266        } else {
267            None
268        }
269    }
270
271    fn flip(&mut self) {
272        // SAFETY: context and surface are opaque handles.
273        unsafe { post_android_surface_buffer(self.context.0.as_ptr(), self.surface.as_ptr()) }
274    }
275
276    fn set_position(&mut self, x: u32, y: u32) {
277        // SAFETY: context is an opaque handle.
278        unsafe { set_android_surface_position(self.context.0.as_ptr(), x, y) };
279    }
280
281    fn flip_to(
282        &mut self,
283        import_id: u32,
284        _acquire_timepoint: Option<SemaphoreTimepoint>,
285        _release_timepoint: Option<SemaphoreTimepoint>,
286        _extra_info: Option<FlipToExtraInfo>,
287    ) -> anyhow::Result<Waitable> {
288        let ahb_import_map = self.ahb_import_map.read().expect("failed to get a lock");
289        let buffer = ahb_import_map
290            .get(&import_id)
291            .ok_or(GpuDisplayError::InvalidImportId)?;
292        // SAFETY: context and surface are opaque handles, and the buffer stays alive for the
293        // duration of the call. `android_display_flip_to_imported` takes its own references.
294        unsafe {
295            android_display_flip_to_imported(
296                self.context.0.as_ptr(),
297                self.surface.as_ptr(),
298                buffer.0.as_ptr(),
299            )
300        };
301        Ok(Waitable::signaled())
302    }
303}
304
305pub struct DisplayAndroid {
306    context: Rc<AndroidDisplayContextWrapper>,
307    /// This event is never triggered and is used solely to fulfill AsRawDescriptor.
308    event: Event,
309    // The key is a surface id.
310    surface_ahbs_map: HashMap<u32, Arc<RwLock<AHardwareBufferImportMap>>>,
311}
312
313impl DisplayAndroid {
314    pub fn new(name: &str) -> GpuDisplayResult<DisplayAndroid> {
315        let name = CString::new(name).unwrap();
316        let context = NonNull::new(
317            // SAFETY: service_name is not leaked outside of this function
318            unsafe { create_android_display_context(name.as_ptr(), error_callback) },
319        )
320        .ok_or(GpuDisplayError::Unsupported)?;
321        let context = AndroidDisplayContextWrapper(context);
322        let event = Event::new().map_err(|_| GpuDisplayError::CreateEvent)?;
323        Ok(DisplayAndroid {
324            context: context.into(),
325            event,
326            surface_ahbs_map: HashMap::new(),
327        })
328    }
329}
330
331impl DisplayT for DisplayAndroid {
332    fn create_surface(
333        &mut self,
334        parent_surface_id: Option<u32>,
335        surface_id: u32,
336        _scanout_id: Option<u32>,
337        display_params: &DisplayParameters,
338        _surf_type: SurfaceType,
339    ) -> GpuDisplayResult<Box<dyn GpuDisplaySurface>> {
340        let (requested_width, requested_height) = display_params.get_virtual_display_size();
341        // SAFETY: context is an opaque handle.
342        let surface = NonNull::new(unsafe {
343            create_android_surface(
344                self.context.0.as_ptr(),
345                requested_width,
346                requested_height,
347                parent_surface_id.is_some(),
348            )
349        })
350        .ok_or(GpuDisplayError::CreateSurface)?;
351        let ahb_import_map = self.surface_ahbs_map.entry(surface_id).or_default();
352
353        Ok(Box::new(AndroidSurface {
354            context: self.context.clone(),
355            surface,
356            ahb_import_map: Arc::clone(ahb_import_map),
357        }))
358    }
359
360    fn release_surface(&mut self, surface_id: u32) {
361        self.surface_ahbs_map.remove(&surface_id);
362    }
363
364    fn import_resource(
365        &mut self,
366        import_id: u32,
367        surface_id: u32,
368        external_display_resource: DisplayExternalResourceImport,
369    ) -> anyhow::Result<()> {
370        let DisplayExternalResourceImport::AHardwareBuffer { info } = external_display_resource
371        else {
372            bail!("gpu_display_android only supports AHardwareBufferInfo imports");
373        };
374        let buffer = ImportedBuffer::import(&self.context, &info)?;
375
376        {
377            let mut ahbs = self
378                .surface_ahbs_map
379                .entry(surface_id)
380                .or_default()
381                .write()
382                .expect("failed to get a lock");
383            ahbs.insert(import_id, buffer);
384        }
385        Ok(())
386    }
387
388    fn release_import(&mut self, surface_id: u32, import_id: u32) {
389        if let Some(ahbs) = self.surface_ahbs_map.get(&surface_id) {
390            ahbs.write()
391                .expect("failed to get a lock")
392                .remove(&import_id);
393        }
394    }
395}
396
397impl SysDisplayT for DisplayAndroid {}
398
399impl AsRawDescriptor for DisplayAndroid {
400    fn as_raw_descriptor(&self) -> RawDescriptor {
401        self.event.as_raw_descriptor()
402    }
403}
404
405// These tests rely on the stub native interface, which tracks imported buffers.
406#[cfg(all(test, feature = "android_display_stub"))]
407mod tests {
408    use std::mem::ManuallyDrop;
409
410    use super::*;
411    use crate::gpu_display_android_stub::flipped_buffers;
412    use crate::gpu_display_android_stub::imported_buffer_count;
413    use crate::gpu_display_android_stub::live_imported_buffers;
414    use crate::gpu_display_android_stub::reset_test_state;
415
416    fn create_test_display() -> ManuallyDrop<DisplayAndroid> {
417        reset_test_state();
418        ManuallyDrop::new(DisplayAndroid {
419            context: Rc::new(AndroidDisplayContextWrapper(NonNull::dangling())),
420            event: Event::new().unwrap(),
421            surface_ahbs_map: HashMap::new(),
422        })
423    }
424
425    fn import(display: &mut DisplayAndroid, surface_id: u32, import_id: u32) {
426        display
427            .import_resource(
428                import_id,
429                surface_id,
430                DisplayExternalResourceImport::AHardwareBuffer {
431                    info: AhbInfo {
432                        fds: Vec::new(),
433                        metadata: Vec::new(),
434                    },
435                },
436            )
437            .unwrap();
438    }
439
440    #[test]
441    fn release_import_releases_buffer_and_ignores_released_surface() {
442        let mut display = create_test_display();
443        let surface_id = 1;
444        let import_id = 2;
445
446        import(&mut display, surface_id, import_id);
447        assert!(display.surface_ahbs_map[&surface_id]
448            .read()
449            .unwrap()
450            .contains_key(&import_id));
451        assert_eq!(live_imported_buffers(), 1);
452
453        display.release_import(surface_id, import_id);
454        assert!(!display.surface_ahbs_map[&surface_id]
455            .read()
456            .unwrap()
457            .contains_key(&import_id));
458        assert_eq!(live_imported_buffers(), 0);
459
460        // Releasing an import for an already released or nonexistent surface should be a no-op
461        // and must not insert an empty entry into `surface_ahbs_map`.
462        display.release_surface(surface_id);
463        display.release_import(surface_id, import_id);
464        assert!(!display.surface_ahbs_map.contains_key(&surface_id));
465    }
466
467    #[test]
468    fn release_surface_releases_all_imported_buffers() {
469        let mut display = create_test_display();
470        import(&mut display, 1, 10);
471        import(&mut display, 1, 11);
472        import(&mut display, 2, 20);
473        assert_eq!(live_imported_buffers(), 3);
474
475        display.release_surface(1);
476        assert_eq!(live_imported_buffers(), 1);
477        display.release_surface(2);
478        assert_eq!(live_imported_buffers(), 0);
479    }
480
481    #[test]
482    fn flip_to_reuses_imported_buffer() {
483        let mut display = create_test_display();
484        let surface_id = 1;
485        import(&mut display, surface_id, 10);
486        import(&mut display, surface_id, 11);
487        assert_eq!(imported_buffer_count(), 2);
488
489        let mut surface = AndroidSurface {
490            context: display.context.clone(),
491            surface: NonNull::dangling(),
492            ahb_import_map: Arc::clone(&display.surface_ahbs_map[&surface_id]),
493        };
494        for import_id in [10, 11, 10, 11] {
495            surface.flip_to(import_id, None, None, None).unwrap();
496        }
497        assert!(surface.flip_to(12, None, None, None).is_err());
498
499        // Flipping never imports again, and each import id always maps to the same buffer.
500        assert_eq!(imported_buffer_count(), 2);
501        let flipped = flipped_buffers();
502        assert_eq!(flipped.len(), 4);
503        assert_ne!(flipped[0], flipped[1]);
504        assert_eq!(flipped[0], flipped[2]);
505        assert_eq!(flipped[1], flipped[3]);
506
507        drop(surface);
508        display.release_surface(surface_id);
509        assert_eq!(live_imported_buffers(), 0);
510    }
511}