1 // SPDX-License-Identifier: GPL-2.0 OR MIT 2 3 //! DRM GEM API 4 //! 5 //! C header: [`include/drm/drm_gem.h`](srctree/include/drm/drm_gem.h) 6 7 use crate::{ 8 bindings, 9 drm::{ 10 self, 11 driver::{ 12 AllocImpl, 13 AllocOps, // 14 }, 15 }, 16 error::to_result, 17 prelude::*, 18 sync::aref::{ 19 ARef, 20 AlwaysRefCounted, // 21 }, 22 types::Opaque, 23 }; 24 use core::{ 25 ops::Deref, 26 ptr::NonNull, // 27 }; 28 29 /// A macro for implementing [`AlwaysRefCounted`] for any GEM object type. 30 /// 31 /// Since all GEM objects use the same refcounting scheme. 32 #[macro_export] 33 macro_rules! impl_aref_for_gem_obj { 34 ( 35 impl $( <$( $tparam_id:ident ),+> )? for $type:ty 36 $( 37 where 38 $( $bind_param:path : $bind_trait:path ),+ 39 )? 40 ) => { 41 // SAFETY: All GEM objects are refcounted. 42 unsafe impl $( <$( $tparam_id ),+> )? $crate::sync::aref::AlwaysRefCounted for $type 43 where 44 Self: IntoGEMObject, 45 $( $( $bind_param : $bind_trait ),+ )? 46 { 47 fn inc_ref(&self) { 48 // SAFETY: The existence of a shared reference guarantees that the refcount is 49 // non-zero. 50 unsafe { bindings::drm_gem_object_get(self.as_raw()) }; 51 } 52 53 unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) { 54 // SAFETY: `obj` is a valid pointer to an `Object<T>`. 55 let obj = unsafe { obj.as_ref() }.as_raw(); 56 57 // SAFETY: The safety requirements guarantee that the refcount is non-zero. 58 unsafe { bindings::drm_gem_object_put(obj) }; 59 } 60 } 61 }; 62 } 63 64 /// A type alias for retrieving a [`Driver`]s [`DriverFile`] implementation from its 65 /// [`DriverObject`] implementation. 66 /// 67 /// [`Driver`]: drm::Driver 68 /// [`DriverFile`]: drm::file::DriverFile 69 pub type DriverFile<T> = drm::File<<<T as DriverObject>::Driver as drm::Driver>::File>; 70 71 /// GEM object functions, which must be implemented by drivers. 72 pub trait DriverObject: Sync + Send + Sized { 73 /// Parent `Driver` for this object. 74 type Driver: drm::Driver; 75 76 /// The data type to use for passing arguments to [`DriverObject::new`]. 77 type Args; 78 79 /// Create a new driver data object for a GEM object of a given size. 80 fn new( 81 dev: &drm::Device<Self::Driver>, 82 size: usize, 83 args: Self::Args, 84 ) -> impl PinInit<Self, Error>; 85 86 /// Open a new handle to an existing object, associated with a File. 87 fn open(_obj: &<Self::Driver as drm::Driver>::Object, _file: &DriverFile<Self>) -> Result { 88 Ok(()) 89 } 90 91 /// Close a handle to an existing object, associated with a File. 92 fn close(_obj: &<Self::Driver as drm::Driver>::Object, _file: &DriverFile<Self>) {} 93 } 94 95 /// Trait that represents a GEM object subtype 96 pub trait IntoGEMObject: Sized + super::private::Sealed + AlwaysRefCounted { 97 /// Returns a reference to the raw `drm_gem_object` structure, which must be valid as long as 98 /// this owning object is valid. 99 fn as_raw(&self) -> *mut bindings::drm_gem_object; 100 101 /// Converts a pointer to a `struct drm_gem_object` into a reference to `Self`. 102 /// 103 /// # Safety 104 /// 105 /// - `self_ptr` must be a valid pointer to `Self`. 106 /// - The caller promises that holding the immutable reference returned by this function does 107 /// not violate rust's data aliasing rules and remains valid throughout the lifetime of `'a`. 108 unsafe fn from_raw<'a>(self_ptr: *mut bindings::drm_gem_object) -> &'a Self; 109 } 110 111 extern "C" fn open_callback<T: DriverObject>( 112 raw_obj: *mut bindings::drm_gem_object, 113 raw_file: *mut bindings::drm_file, 114 ) -> core::ffi::c_int { 115 // SAFETY: `open_callback` is only ever called with a valid pointer to a `struct drm_file`. 116 let file = unsafe { DriverFile::<T>::from_raw(raw_file) }; 117 118 // SAFETY: `open_callback` is specified in the AllocOps structure for `DriverObject<T>`, 119 // ensuring that `raw_obj` is contained within a `DriverObject<T>` 120 let obj = unsafe { <<T::Driver as drm::Driver>::Object as IntoGEMObject>::from_raw(raw_obj) }; 121 122 match T::open(obj, file) { 123 Err(e) => e.to_errno(), 124 Ok(()) => 0, 125 } 126 } 127 128 extern "C" fn close_callback<T: DriverObject>( 129 raw_obj: *mut bindings::drm_gem_object, 130 raw_file: *mut bindings::drm_file, 131 ) { 132 // SAFETY: `open_callback` is only ever called with a valid pointer to a `struct drm_file`. 133 let file = unsafe { DriverFile::<T>::from_raw(raw_file) }; 134 135 // SAFETY: `close_callback` is specified in the AllocOps structure for `Object<T>`, ensuring 136 // that `raw_obj` is indeed contained within a `Object<T>`. 137 let obj = unsafe { <<T::Driver as drm::Driver>::Object as IntoGEMObject>::from_raw(raw_obj) }; 138 139 T::close(obj, file); 140 } 141 142 impl<T: DriverObject> IntoGEMObject for Object<T> { 143 fn as_raw(&self) -> *mut bindings::drm_gem_object { 144 self.obj.get() 145 } 146 147 unsafe fn from_raw<'a>(self_ptr: *mut bindings::drm_gem_object) -> &'a Self { 148 // SAFETY: `obj` is guaranteed to be in an `Object<T>` via the safety contract of this 149 // function 150 unsafe { &*crate::container_of!(Opaque::cast_from(self_ptr), Object<T>, obj) } 151 } 152 } 153 154 /// Base operations shared by all GEM object classes 155 pub trait BaseObject: IntoGEMObject { 156 /// Returns the size of the object in bytes. 157 fn size(&self) -> usize { 158 // SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `struct drm_gem_object`. 159 unsafe { (*self.as_raw()).size } 160 } 161 162 /// Creates a new handle for the object associated with a given `File` 163 /// (or returns an existing one). 164 fn create_handle<D, F>(&self, file: &drm::File<F>) -> Result<u32> 165 where 166 Self: AllocImpl<Driver = D>, 167 D: drm::Driver<Object = Self, File = F>, 168 F: drm::file::DriverFile<Driver = D>, 169 { 170 let mut handle: u32 = 0; 171 // SAFETY: The arguments are all valid per the type invariants. 172 to_result(unsafe { 173 bindings::drm_gem_handle_create(file.as_raw().cast(), self.as_raw(), &mut handle) 174 })?; 175 Ok(handle) 176 } 177 178 /// Looks up an object by its handle for a given `File`. 179 fn lookup_handle<D, F>(file: &drm::File<F>, handle: u32) -> Result<ARef<Self>> 180 where 181 Self: AllocImpl<Driver = D>, 182 D: drm::Driver<Object = Self, File = F>, 183 F: drm::file::DriverFile<Driver = D>, 184 { 185 // SAFETY: The arguments are all valid per the type invariants. 186 let ptr = unsafe { bindings::drm_gem_object_lookup(file.as_raw().cast(), handle) }; 187 if ptr.is_null() { 188 return Err(ENOENT); 189 } 190 191 // SAFETY: 192 // - A `drm::Driver` can only have a single `File` implementation. 193 // - `file` uses the same `drm::Driver` as `Self`. 194 // - Therefore, we're guaranteed that `ptr` must be a gem object embedded within `Self`. 195 // - And we check if the pointer is null befoe calling from_raw(), ensuring that `ptr` is a 196 // valid pointer to an initialized `Self`. 197 let obj = unsafe { Self::from_raw(ptr) }; 198 199 // SAFETY: 200 // - We take ownership of the reference of `drm_gem_object_lookup()`. 201 // - Our `NonNull` comes from an immutable reference, thus ensuring it is a valid pointer to 202 // `Self`. 203 Ok(unsafe { ARef::from_raw(obj.into()) }) 204 } 205 206 /// Creates an mmap offset to map the object from userspace. 207 fn create_mmap_offset(&self) -> Result<u64> { 208 // SAFETY: The arguments are valid per the type invariant. 209 to_result(unsafe { bindings::drm_gem_create_mmap_offset(self.as_raw()) })?; 210 211 // SAFETY: The arguments are valid per the type invariant. 212 Ok(unsafe { bindings::drm_vma_node_offset_addr(&raw mut (*self.as_raw()).vma_node) }) 213 } 214 } 215 216 impl<T: IntoGEMObject> BaseObject for T {} 217 218 /// Crate-private base operations shared by all GEM object classes. 219 #[expect(unused)] 220 pub(crate) trait BaseObjectPrivate: IntoGEMObject { 221 /// Return a pointer to this object's dma_resv. 222 fn raw_dma_resv(&self) -> *mut bindings::dma_resv { 223 // SAFETY: `self.as_raw()` always returns a valid pointer to the base DRM GEM object. 224 unsafe { (*self.as_raw()).resv } 225 } 226 } 227 228 impl<T: IntoGEMObject> BaseObjectPrivate for T {} 229 230 /// A base GEM object. 231 /// 232 /// # Invariants 233 /// 234 /// - `self.obj` is a valid instance of a `struct drm_gem_object`. 235 #[repr(C)] 236 #[pin_data] 237 pub struct Object<T: DriverObject + Send + Sync> { 238 obj: Opaque<bindings::drm_gem_object>, 239 #[pin] 240 data: T, 241 } 242 243 impl<T: DriverObject> Object<T> { 244 const OBJECT_FUNCS: bindings::drm_gem_object_funcs = bindings::drm_gem_object_funcs { 245 free: Some(Self::free_callback), 246 open: Some(open_callback::<T>), 247 close: Some(close_callback::<T>), 248 print_info: None, 249 export: None, 250 pin: None, 251 unpin: None, 252 get_sg_table: None, 253 vmap: None, 254 vunmap: None, 255 mmap: None, 256 status: None, 257 vm_ops: core::ptr::null_mut(), 258 evict: None, 259 rss: None, 260 }; 261 262 /// Create a new GEM object. 263 pub fn new(dev: &drm::Device<T::Driver>, size: usize, args: T::Args) -> Result<ARef<Self>> { 264 let obj: Pin<KBox<Self>> = KBox::pin_init( 265 try_pin_init!(Self { 266 obj: Opaque::new(bindings::drm_gem_object::default()), 267 data <- T::new(dev, size, args), 268 }), 269 GFP_KERNEL, 270 )?; 271 272 // SAFETY: `obj.as_raw()` is guaranteed to be valid by the initialization above. 273 unsafe { (*obj.as_raw()).funcs = &Self::OBJECT_FUNCS }; 274 275 // SAFETY: The arguments are all valid per the type invariants. 276 to_result(unsafe { bindings::drm_gem_object_init(dev.as_raw(), obj.obj.get(), size) })?; 277 278 // SAFETY: We will never move out of `Self` as `ARef<Self>` is always treated as pinned. 279 let ptr = KBox::into_raw(unsafe { Pin::into_inner_unchecked(obj) }); 280 281 // SAFETY: `ptr` comes from `KBox::into_raw` and hence can't be NULL. 282 let ptr = unsafe { NonNull::new_unchecked(ptr) }; 283 284 // SAFETY: We take over the initial reference count from `drm_gem_object_init()`. 285 Ok(unsafe { ARef::from_raw(ptr) }) 286 } 287 288 /// Returns the `Device` that owns this GEM object. 289 pub fn dev(&self) -> &drm::Device<T::Driver> { 290 // SAFETY: 291 // - `struct drm_gem_object.dev` is initialized and valid for as long as the GEM 292 // object lives. 293 // - The device we used for creating the gem object is passed as &drm::Device<T::Driver> to 294 // Object::<T>::new(), so we know that `T::Driver` is the right generic parameter to use 295 // here. 296 unsafe { drm::Device::from_raw((*self.as_raw()).dev) } 297 } 298 299 fn as_raw(&self) -> *mut bindings::drm_gem_object { 300 self.obj.get() 301 } 302 303 extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) { 304 let ptr: *mut Opaque<bindings::drm_gem_object> = obj.cast(); 305 306 // SAFETY: All of our objects are of type `Object<T>`. 307 let this = unsafe { crate::container_of!(ptr, Self, obj) }; 308 309 // SAFETY: The C code only ever calls this callback with a valid pointer to a `struct 310 // drm_gem_object`. 311 unsafe { bindings::drm_gem_object_release(obj) }; 312 313 // SAFETY: All of our objects are allocated via `KBox`, and we're in the 314 // free callback which guarantees this object has zero remaining references, 315 // so we can drop it. 316 let _ = unsafe { KBox::from_raw(this) }; 317 } 318 } 319 320 impl_aref_for_gem_obj!(impl<T> for Object<T> where T: DriverObject); 321 322 impl<T: DriverObject> super::private::Sealed for Object<T> {} 323 324 impl<T: DriverObject> Deref for Object<T> { 325 type Target = T; 326 327 fn deref(&self) -> &Self::Target { 328 &self.data 329 } 330 } 331 332 impl<T: DriverObject> AllocImpl for Object<T> { 333 type Driver = T::Driver; 334 335 const ALLOC_OPS: AllocOps = AllocOps { 336 gem_create_object: None, 337 prime_handle_to_fd: None, 338 prime_fd_to_handle: None, 339 gem_prime_import: None, 340 gem_prime_import_sg_table: None, 341 dumb_create: None, 342 dumb_map_offset: None, 343 }; 344 } 345 346 pub(super) const fn create_fops() -> bindings::file_operations { 347 let mut fops: bindings::file_operations = pin_init::zeroed(); 348 349 fops.owner = core::ptr::null_mut(); 350 fops.open = Some(bindings::drm_open); 351 fops.release = Some(bindings::drm_release); 352 fops.unlocked_ioctl = Some(bindings::drm_ioctl); 353 #[cfg(CONFIG_COMPAT)] 354 { 355 fops.compat_ioctl = Some(bindings::drm_compat_ioctl); 356 } 357 fops.poll = Some(bindings::drm_poll); 358 fops.read = Some(bindings::drm_read); 359 fops.llseek = Some(bindings::noop_llseek); 360 fops.mmap = Some(bindings::drm_gem_mmap); 361 fops.fop_flags = bindings::FOP_UNSIGNED_OFFSET; 362 363 fops 364 } 365