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