// SPDX-License-Identifier: GPL-2.0 OR MIT12//! DRM GEM API3//!4//! C header: [`include/drm/drm_gem.h`](srctree/include/drm/drm_gem.h)56use crate::{7alloc::flags::*,8bindings, drm,9drm::driver::{AllocImpl, AllocOps},10error::{to_result, Result},11prelude::*,12sync::aref::{ARef, AlwaysRefCounted},13types::Opaque,14};15use core::{ops::Deref, ptr::NonNull};1617/// A type alias for retrieving a [`Driver`]s [`DriverFile`] implementation from its18/// [`DriverObject`] implementation.19///20/// [`Driver`]: drm::Driver21/// [`DriverFile`]: drm::file::DriverFile22pub type DriverFile<T> = drm::File<<<T as DriverObject>::Driver as drm::Driver>::File>;2324/// GEM object functions, which must be implemented by drivers.25pub trait DriverObject: Sync + Send + Sized {26/// Parent `Driver` for this object.27type Driver: drm::Driver;2829/// Create a new driver data object for a GEM object of a given size.30fn new(dev: &drm::Device<Self::Driver>, size: usize) -> impl PinInit<Self, Error>;3132/// Open a new handle to an existing object, associated with a File.33fn open(_obj: &<Self::Driver as drm::Driver>::Object, _file: &DriverFile<Self>) -> Result {34Ok(())35}3637/// Close a handle to an existing object, associated with a File.38fn close(_obj: &<Self::Driver as drm::Driver>::Object, _file: &DriverFile<Self>) {}39}4041/// Trait that represents a GEM object subtype42pub trait IntoGEMObject: Sized + super::private::Sealed + AlwaysRefCounted {43/// Returns a reference to the raw `drm_gem_object` structure, which must be valid as long as44/// this owning object is valid.45fn as_raw(&self) -> *mut bindings::drm_gem_object;4647/// Converts a pointer to a `struct drm_gem_object` into a reference to `Self`.48///49/// # Safety50///51/// - `self_ptr` must be a valid pointer to `Self`.52/// - The caller promises that holding the immutable reference returned by this function does53/// not violate rust's data aliasing rules and remains valid throughout the lifetime of `'a`.54unsafe fn from_raw<'a>(self_ptr: *mut bindings::drm_gem_object) -> &'a Self;55}5657// SAFETY: All gem objects are refcounted.58unsafe impl<T: IntoGEMObject> AlwaysRefCounted for T {59fn inc_ref(&self) {60// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.61unsafe { bindings::drm_gem_object_get(self.as_raw()) };62}6364unsafe fn dec_ref(obj: NonNull<Self>) {65// SAFETY: We either hold the only refcount on `obj`, or one of many - meaning that no one66// else could possibly hold a mutable reference to `obj` and thus this immutable reference67// is safe.68let obj = unsafe { obj.as_ref() }.as_raw();6970// SAFETY:71// - The safety requirements guarantee that the refcount is non-zero.72// - We hold no references to `obj` now, making it safe for us to potentially deallocate it.73unsafe { bindings::drm_gem_object_put(obj) };74}75}7677extern "C" fn open_callback<T: DriverObject>(78raw_obj: *mut bindings::drm_gem_object,79raw_file: *mut bindings::drm_file,80) -> core::ffi::c_int {81// SAFETY: `open_callback` is only ever called with a valid pointer to a `struct drm_file`.82let file = unsafe { DriverFile::<T>::from_raw(raw_file) };8384// SAFETY: `open_callback` is specified in the AllocOps structure for `DriverObject<T>`,85// ensuring that `raw_obj` is contained within a `DriverObject<T>`86let obj = unsafe { <<T::Driver as drm::Driver>::Object as IntoGEMObject>::from_raw(raw_obj) };8788match T::open(obj, file) {89Err(e) => e.to_errno(),90Ok(()) => 0,91}92}9394extern "C" fn close_callback<T: DriverObject>(95raw_obj: *mut bindings::drm_gem_object,96raw_file: *mut bindings::drm_file,97) {98// SAFETY: `open_callback` is only ever called with a valid pointer to a `struct drm_file`.99let file = unsafe { DriverFile::<T>::from_raw(raw_file) };100101// SAFETY: `close_callback` is specified in the AllocOps structure for `Object<T>`, ensuring102// that `raw_obj` is indeed contained within a `Object<T>`.103let obj = unsafe { <<T::Driver as drm::Driver>::Object as IntoGEMObject>::from_raw(raw_obj) };104105T::close(obj, file);106}107108impl<T: DriverObject> IntoGEMObject for Object<T> {109fn as_raw(&self) -> *mut bindings::drm_gem_object {110self.obj.get()111}112113unsafe fn from_raw<'a>(self_ptr: *mut bindings::drm_gem_object) -> &'a Self {114// SAFETY: `obj` is guaranteed to be in an `Object<T>` via the safety contract of this115// function116unsafe { &*crate::container_of!(Opaque::cast_from(self_ptr), Object<T>, obj) }117}118}119120/// Base operations shared by all GEM object classes121pub trait BaseObject: IntoGEMObject {122/// Returns the size of the object in bytes.123fn size(&self) -> usize {124// SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `struct drm_gem_object`.125unsafe { (*self.as_raw()).size }126}127128/// Creates a new handle for the object associated with a given `File`129/// (or returns an existing one).130fn create_handle<D, F>(&self, file: &drm::File<F>) -> Result<u32>131where132Self: AllocImpl<Driver = D>,133D: drm::Driver<Object = Self, File = F>,134F: drm::file::DriverFile<Driver = D>,135{136let mut handle: u32 = 0;137// SAFETY: The arguments are all valid per the type invariants.138to_result(unsafe {139bindings::drm_gem_handle_create(file.as_raw().cast(), self.as_raw(), &mut handle)140})?;141Ok(handle)142}143144/// Looks up an object by its handle for a given `File`.145fn lookup_handle<D, F>(file: &drm::File<F>, handle: u32) -> Result<ARef<Self>>146where147Self: AllocImpl<Driver = D>,148D: drm::Driver<Object = Self, File = F>,149F: drm::file::DriverFile<Driver = D>,150{151// SAFETY: The arguments are all valid per the type invariants.152let ptr = unsafe { bindings::drm_gem_object_lookup(file.as_raw().cast(), handle) };153if ptr.is_null() {154return Err(ENOENT);155}156157// SAFETY:158// - A `drm::Driver` can only have a single `File` implementation.159// - `file` uses the same `drm::Driver` as `Self`.160// - Therefore, we're guaranteed that `ptr` must be a gem object embedded within `Self`.161// - And we check if the pointer is null befoe calling from_raw(), ensuring that `ptr` is a162// valid pointer to an initialized `Self`.163let obj = unsafe { Self::from_raw(ptr) };164165// SAFETY:166// - We take ownership of the reference of `drm_gem_object_lookup()`.167// - Our `NonNull` comes from an immutable reference, thus ensuring it is a valid pointer to168// `Self`.169Ok(unsafe { ARef::from_raw(obj.into()) })170}171172/// Creates an mmap offset to map the object from userspace.173fn create_mmap_offset(&self) -> Result<u64> {174// SAFETY: The arguments are valid per the type invariant.175to_result(unsafe { bindings::drm_gem_create_mmap_offset(self.as_raw()) })?;176177// SAFETY: The arguments are valid per the type invariant.178Ok(unsafe { bindings::drm_vma_node_offset_addr(&raw mut (*self.as_raw()).vma_node) })179}180}181182impl<T: IntoGEMObject> BaseObject for T {}183184/// A base GEM object.185///186/// Invariants187///188/// - `self.obj` is a valid instance of a `struct drm_gem_object`.189/// - `self.dev` is always a valid pointer to a `struct drm_device`.190#[repr(C)]191#[pin_data]192pub struct Object<T: DriverObject + Send + Sync> {193obj: Opaque<bindings::drm_gem_object>,194dev: NonNull<drm::Device<T::Driver>>,195#[pin]196data: T,197}198199impl<T: DriverObject> Object<T> {200const OBJECT_FUNCS: bindings::drm_gem_object_funcs = bindings::drm_gem_object_funcs {201free: Some(Self::free_callback),202open: Some(open_callback::<T>),203close: Some(close_callback::<T>),204print_info: None,205export: None,206pin: None,207unpin: None,208get_sg_table: None,209vmap: None,210vunmap: None,211mmap: None,212status: None,213vm_ops: core::ptr::null_mut(),214evict: None,215rss: None,216};217218/// Create a new GEM object.219pub fn new(dev: &drm::Device<T::Driver>, size: usize) -> Result<ARef<Self>> {220let obj: Pin<KBox<Self>> = KBox::pin_init(221try_pin_init!(Self {222obj: Opaque::new(bindings::drm_gem_object::default()),223data <- T::new(dev, size),224// INVARIANT: The drm subsystem guarantees that the `struct drm_device` will live225// as long as the GEM object lives.226dev: dev.into(),227}),228GFP_KERNEL,229)?;230231// SAFETY: `obj.as_raw()` is guaranteed to be valid by the initialization above.232unsafe { (*obj.as_raw()).funcs = &Self::OBJECT_FUNCS };233234// SAFETY: The arguments are all valid per the type invariants.235to_result(unsafe { bindings::drm_gem_object_init(dev.as_raw(), obj.obj.get(), size) })?;236237// SAFETY: We never move out of `Self`.238let ptr = KBox::into_raw(unsafe { Pin::into_inner_unchecked(obj) });239240// SAFETY: `ptr` comes from `KBox::into_raw` and hence can't be NULL.241let ptr = unsafe { NonNull::new_unchecked(ptr) };242243// SAFETY: We take over the initial reference count from `drm_gem_object_init()`.244Ok(unsafe { ARef::from_raw(ptr) })245}246247/// Returns the `Device` that owns this GEM object.248pub fn dev(&self) -> &drm::Device<T::Driver> {249// SAFETY: The DRM subsystem guarantees that the `struct drm_device` will live as long as250// the GEM object lives, hence the pointer must be valid.251unsafe { self.dev.as_ref() }252}253254fn as_raw(&self) -> *mut bindings::drm_gem_object {255self.obj.get()256}257258extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) {259let ptr: *mut Opaque<bindings::drm_gem_object> = obj.cast();260261// SAFETY: All of our objects are of type `Object<T>`.262let this = unsafe { crate::container_of!(ptr, Self, obj) };263264// SAFETY: The C code only ever calls this callback with a valid pointer to a `struct265// drm_gem_object`.266unsafe { bindings::drm_gem_object_release(obj) };267268// SAFETY: All of our objects are allocated via `KBox`, and we're in the269// free callback which guarantees this object has zero remaining references,270// so we can drop it.271let _ = unsafe { KBox::from_raw(this) };272}273}274275impl<T: DriverObject> super::private::Sealed for Object<T> {}276277impl<T: DriverObject> Deref for Object<T> {278type Target = T;279280fn deref(&self) -> &Self::Target {281&self.data282}283}284285impl<T: DriverObject> AllocImpl for Object<T> {286type Driver = T::Driver;287288const ALLOC_OPS: AllocOps = AllocOps {289gem_create_object: None,290prime_handle_to_fd: None,291prime_fd_to_handle: None,292gem_prime_import: None,293gem_prime_import_sg_table: None,294dumb_create: None,295dumb_map_offset: None,296};297}298299pub(super) const fn create_fops() -> bindings::file_operations {300// SAFETY: As by the type invariant, it is safe to initialize `bindings::file_operations`301// zeroed.302let mut fops: bindings::file_operations = unsafe { core::mem::zeroed() };303304fops.owner = core::ptr::null_mut();305fops.open = Some(bindings::drm_open);306fops.release = Some(bindings::drm_release);307fops.unlocked_ioctl = Some(bindings::drm_ioctl);308#[cfg(CONFIG_COMPAT)]309{310fops.compat_ioctl = Some(bindings::drm_compat_ioctl);311}312fops.poll = Some(bindings::drm_poll);313fops.read = Some(bindings::drm_read);314fops.llseek = Some(bindings::noop_llseek);315fops.mmap = Some(bindings::drm_gem_mmap);316fops.fop_flags = bindings::FOP_UNSIGNED_OFFSET;317318fops319}320321322