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