xref: /linux/rust/kernel/drm/gem/mod.rs (revision 38f7e5450ebfc6f2e046a249a3f629ea7bec8c31)
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     /// 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 /// A base GEM object.
219 ///
220 /// # Invariants
221 ///
222 /// - `self.obj` is a valid instance of a `struct drm_gem_object`.
223 #[repr(C)]
224 #[pin_data]
225 pub struct Object<T: DriverObject + Send + Sync> {
226     obj: Opaque<bindings::drm_gem_object>,
227     #[pin]
228     data: T,
229 }
230 
231 impl<T: DriverObject> Object<T> {
232     const OBJECT_FUNCS: bindings::drm_gem_object_funcs = bindings::drm_gem_object_funcs {
233         free: Some(Self::free_callback),
234         open: Some(open_callback::<T>),
235         close: Some(close_callback::<T>),
236         print_info: None,
237         export: None,
238         pin: None,
239         unpin: None,
240         get_sg_table: None,
241         vmap: None,
242         vunmap: None,
243         mmap: None,
244         status: None,
245         vm_ops: core::ptr::null_mut(),
246         evict: None,
247         rss: None,
248     };
249 
250     /// Create a new GEM object.
251     pub fn new(dev: &drm::Device<T::Driver>, size: usize, args: T::Args) -> Result<ARef<Self>> {
252         let obj: Pin<KBox<Self>> = KBox::pin_init(
253             try_pin_init!(Self {
254                 obj: Opaque::new(bindings::drm_gem_object::default()),
255                 data <- T::new(dev, size, args),
256             }),
257             GFP_KERNEL,
258         )?;
259 
260         // SAFETY: `obj.as_raw()` is guaranteed to be valid by the initialization above.
261         unsafe { (*obj.as_raw()).funcs = &Self::OBJECT_FUNCS };
262 
263         // SAFETY: The arguments are all valid per the type invariants.
264         to_result(unsafe { bindings::drm_gem_object_init(dev.as_raw(), obj.obj.get(), size) })?;
265 
266         // SAFETY: We will never move out of `Self` as `ARef<Self>` is always treated as pinned.
267         let ptr = KBox::into_raw(unsafe { Pin::into_inner_unchecked(obj) });
268 
269         // SAFETY: `ptr` comes from `KBox::into_raw` and hence can't be NULL.
270         let ptr = unsafe { NonNull::new_unchecked(ptr) };
271 
272         // SAFETY: We take over the initial reference count from `drm_gem_object_init()`.
273         Ok(unsafe { ARef::from_raw(ptr) })
274     }
275 
276     /// Returns the `Device` that owns this GEM object.
277     pub fn dev(&self) -> &drm::Device<T::Driver> {
278         // SAFETY:
279         // - `struct drm_gem_object.dev` is initialized and valid for as long as the GEM
280         //   object lives.
281         // - The device we used for creating the gem object is passed as &drm::Device<T::Driver> to
282         //   Object::<T>::new(), so we know that `T::Driver` is the right generic parameter to use
283         //   here.
284         unsafe { drm::Device::from_raw((*self.as_raw()).dev) }
285     }
286 
287     fn as_raw(&self) -> *mut bindings::drm_gem_object {
288         self.obj.get()
289     }
290 
291     extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) {
292         let ptr: *mut Opaque<bindings::drm_gem_object> = obj.cast();
293 
294         // SAFETY: All of our objects are of type `Object<T>`.
295         let this = unsafe { crate::container_of!(ptr, Self, obj) };
296 
297         // SAFETY: The C code only ever calls this callback with a valid pointer to a `struct
298         // drm_gem_object`.
299         unsafe { bindings::drm_gem_object_release(obj) };
300 
301         // SAFETY: All of our objects are allocated via `KBox`, and we're in the
302         // free callback which guarantees this object has zero remaining references,
303         // so we can drop it.
304         let _ = unsafe { KBox::from_raw(this) };
305     }
306 }
307 
308 impl_aref_for_gem_obj!(impl<T> for Object<T> where T: DriverObject);
309 
310 impl<T: DriverObject> super::private::Sealed for Object<T> {}
311 
312 impl<T: DriverObject> Deref for Object<T> {
313     type Target = T;
314 
315     fn deref(&self) -> &Self::Target {
316         &self.data
317     }
318 }
319 
320 impl<T: DriverObject> AllocImpl for Object<T> {
321     type Driver = T::Driver;
322 
323     const ALLOC_OPS: AllocOps = AllocOps {
324         gem_create_object: None,
325         prime_handle_to_fd: None,
326         prime_fd_to_handle: None,
327         gem_prime_import: None,
328         gem_prime_import_sg_table: None,
329         dumb_create: None,
330         dumb_map_offset: None,
331     };
332 }
333 
334 pub(super) const fn create_fops() -> bindings::file_operations {
335     let mut fops: bindings::file_operations = pin_init::zeroed();
336 
337     fops.owner = core::ptr::null_mut();
338     fops.open = Some(bindings::drm_open);
339     fops.release = Some(bindings::drm_release);
340     fops.unlocked_ioctl = Some(bindings::drm_ioctl);
341     #[cfg(CONFIG_COMPAT)]
342     {
343         fops.compat_ioctl = Some(bindings::drm_compat_ioctl);
344     }
345     fops.poll = Some(bindings::drm_poll);
346     fops.read = Some(bindings::drm_read);
347     fops.llseek = Some(bindings::noop_llseek);
348     fops.mmap = Some(bindings::drm_gem_mmap);
349     fops.fop_flags = bindings::FOP_UNSIGNED_OFFSET;
350 
351     fops
352 }
353