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