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