// SPDX-License-Identifier: GPL-2.012//! DRM GEM shmem helper objects3//!4//! C header: [`include/linux/drm/drm_gem_shmem_helper.h`](srctree/include/drm/drm_gem_shmem_helper.h)56// TODO:7// - There are a number of spots here that manually acquire/release the DMA reservation lock using8// dma_resv_(un)lock(). In the future we should add support for ww mutex, expose a method to9// acquire a reference to the WwMutex, and then use that directly instead of the C functions here.1011use crate::{12container_of,13drm::{14device,15driver,16gem,17private::Sealed, //18},19error::to_result,20prelude::*,21types::{22ARef,23Opaque, //24}, //25};26use core::{27ops::{28Deref,29DerefMut, //30},31ptr::NonNull,32};33use gem::{34BaseObjectPrivate,35DriverObject,36IntoGEMObject, //37};3839/// A struct for controlling the creation of shmem-backed GEM objects.40///41/// This is used with [`Object::new()`] to control various properties that can only be set when42/// initially creating a shmem-backed GEM object.43#[derive(Default)]44pub struct ObjectConfig<'a, T: DriverObject> {45/// Whether to set the write-combine map flag.46pub map_wc: bool,4748/// Reuse the DMA reservation from another GEM object.49///50/// The newly created [`Object`] will hold an owned refcount to `parent_resv_obj` if specified.51pub parent_resv_obj: Option<&'a Object<T>>,52}5354/// A shmem-backed GEM object.55///56/// # Invariants57///58/// `obj` contains a valid initialized `struct drm_gem_shmem_object` for the lifetime of this59/// object.60#[repr(C)]61#[pin_data]62pub struct Object<T: DriverObject> {63#[pin]64obj: Opaque<bindings::drm_gem_shmem_object>,65/// Parent object that owns this object's DMA reservation object.66parent_resv_obj: Option<ARef<Object<T>>>,67#[pin]68inner: T,69}7071super::impl_aref_for_gem_obj!(impl<T> for Object<T> where T: DriverObject);7273// SAFETY: All GEM objects are thread-safe.74unsafe impl<T: DriverObject> Send for Object<T> {}7576// SAFETY: All GEM objects are thread-safe.77unsafe impl<T: DriverObject> Sync for Object<T> {}7879impl<T: DriverObject> Object<T> {80/// `drm_gem_object_funcs` vtable suitable for GEM shmem objects.81const VTABLE: bindings::drm_gem_object_funcs = bindings::drm_gem_object_funcs {82free: Some(Self::free_callback),83open: Some(super::open_callback::<T>),84close: Some(super::close_callback::<T>),85print_info: Some(bindings::drm_gem_shmem_object_print_info),86export: None,87pin: Some(bindings::drm_gem_shmem_object_pin),88unpin: Some(bindings::drm_gem_shmem_object_unpin),89get_sg_table: Some(bindings::drm_gem_shmem_object_get_sg_table),90vmap: Some(bindings::drm_gem_shmem_object_vmap),91vunmap: Some(bindings::drm_gem_shmem_object_vunmap),92mmap: Some(bindings::drm_gem_shmem_object_mmap),93status: None,94rss: None,95#[allow(unused_unsafe, reason = "Safe since Rust 1.82.0")]96// SAFETY: `drm_gem_shmem_vm_ops` is a valid, static const on the C side.97vm_ops: unsafe { &raw const bindings::drm_gem_shmem_vm_ops },98evict: None,99};100101/// Return a raw pointer to the embedded drm_gem_shmem_object.102fn as_raw_shmem(&self) -> *mut bindings::drm_gem_shmem_object {103self.obj.get()104}105106/// Create a new shmem-backed DRM object of the given size.107///108/// Additional config options can be specified using `config`.109pub fn new(110dev: &device::Device<T::Driver>,111size: usize,112config: ObjectConfig<'_, T>,113args: T::Args,114) -> Result<ARef<Self>> {115let new: Pin<KBox<Self>> = KBox::try_pin_init(116try_pin_init!(Self {117obj <- Opaque::init_zeroed(),118parent_resv_obj: config.parent_resv_obj.map(|p| p.into()),119inner <- T::new(dev, size, args),120}),121GFP_KERNEL,122)?;123124// SAFETY: `obj.as_raw()` is guaranteed to be valid by the initialization above.125unsafe { (*new.as_raw()).funcs = &Self::VTABLE };126127// SAFETY: The arguments are all valid via the type invariants.128to_result(unsafe { bindings::drm_gem_shmem_init(dev.as_raw(), new.as_raw_shmem(), size) })?;129130// SAFETY: We never move out of `self`.131let new = KBox::into_raw(unsafe { Pin::into_inner_unchecked(new) });132133// SAFETY: We're taking over the owned refcount from `drm_gem_shmem_init`.134let obj = unsafe { ARef::from_raw(NonNull::new_unchecked(new)) };135136// Start filling out values from `config`137if let Some(parent_resv) = config.parent_resv_obj {138// SAFETY: We have yet to expose the new gem object outside of this function, so it is139// safe to modify this field.140unsafe { (*obj.obj.get()).base.resv = parent_resv.raw_dma_resv() };141}142143// SAFETY: We have yet to expose this object outside of this function, so we're guaranteed144// to have exclusive access - thus making this safe to hold a mutable reference to.145let shmem = unsafe { &mut *obj.as_raw_shmem() };146shmem.set_map_wc(config.map_wc);147148Ok(obj)149}150151/// Returns the `Device` that owns this GEM object.152pub fn dev(&self) -> &device::Device<T::Driver> {153// SAFETY: `dev` will have been initialized in `Self::new()` by `drm_gem_shmem_init()`.154unsafe { device::Device::from_raw((*self.as_raw()).dev) }155}156157extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) {158// SAFETY:159// - DRM always passes a valid gem object here160// - We used drm_gem_shmem_create() in our create_gem_object callback, so we know that161// `obj` is contained within a drm_gem_shmem_object162let this = unsafe { container_of!(obj, bindings::drm_gem_shmem_object, base) };163164// SAFETY:165// - We're in free_callback - so this function is safe to call.166// - We won't be using the gem resources on `this` after this call.167unsafe { bindings::drm_gem_shmem_release(this) };168169// SAFETY:170// - We verified above that `obj` is valid, which makes `this` valid171// - This function is set in AllocOps, so we know that `this` is contained within a172// `Object<T>`173let this = unsafe { container_of!(Opaque::cast_from(this), Self, obj) }.cast_mut();174175// SAFETY: We're recovering the Kbox<> we created in gem_create_object()176let _ = unsafe { KBox::from_raw(this) };177}178}179180impl<T: DriverObject> Deref for Object<T> {181type Target = T;182183fn deref(&self) -> &Self::Target {184&self.inner185}186}187188impl<T: DriverObject> DerefMut for Object<T> {189fn deref_mut(&mut self) -> &mut Self::Target {190&mut self.inner191}192}193194impl<T: DriverObject> Sealed for Object<T> {}195196impl<T: DriverObject> gem::IntoGEMObject for Object<T> {197fn as_raw(&self) -> *mut bindings::drm_gem_object {198// SAFETY:199// - Our immutable reference is proof that this is safe to dereference.200// - `obj` is always a valid drm_gem_shmem_object via our type invariants.201unsafe { &raw mut (*self.obj.get()).base }202}203204unsafe fn from_raw<'a>(obj: *mut bindings::drm_gem_object) -> &'a Object<T> {205// SAFETY: The safety contract of from_gem_obj() guarantees that `obj` is contained within206// `Self`207unsafe {208let obj = Opaque::cast_from(container_of!(obj, bindings::drm_gem_shmem_object, base));209210&*container_of!(obj, Object<T>, obj)211}212}213}214215impl<T: DriverObject> driver::AllocImpl for Object<T> {216type Driver = T::Driver;217218const ALLOC_OPS: driver::AllocOps = driver::AllocOps {219gem_create_object: None,220prime_handle_to_fd: None,221prime_fd_to_handle: None,222gem_prime_import: None,223gem_prime_import_sg_table: Some(bindings::drm_gem_shmem_prime_import_sg_table),224dumb_create: Some(bindings::drm_gem_shmem_dumb_create),225dumb_map_offset: None,226};227}228229230