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