kernel/drm/gem/
mod.rs

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
7use 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};
15use core::{mem, ops::Deref, ptr::NonNull};
16
17/// GEM object functions, which must be implemented by drivers.
18pub trait BaseDriverObject<T: BaseObject>: Sync + Send + Sized {
19    /// Create a new driver data object for a GEM object of a given size.
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.
23    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.
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
39pub 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.
45    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`.
54    unsafe fn as_ref<'a>(self_ptr: *mut bindings::drm_gem_object) -> &'a Self;
55}
56
57// SAFETY: All gem objects are refcounted.
58unsafe impl<T: IntoGEMObject> AlwaysRefCounted for T {
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
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.
78pub trait DriverObject: BaseDriverObject<Object<Self>> {
79    /// Parent `Driver` for this object.
80    type Driver: drm::Driver;
81}
82
83extern "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>::as_ref(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>::as_ref(raw_obj)
95    };
96
97    match T::open(obj, file) {
98        Err(e) => e.to_errno(),
99        Ok(()) => 0,
100    }
101}
102
103extern "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>::as_ref(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>::as_ref(raw_obj)
115    };
116
117    T::close(obj, file);
118}
119
120impl<T: DriverObject> IntoGEMObject for Object<T> {
121    type Driver = T::Driver;
122
123    fn as_raw(&self) -> *mut bindings::drm_gem_object {
124        self.obj.get()
125    }
126
127    unsafe fn as_ref<'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!(self_ptr, Object<T>, obj) }
131    }
132}
133
134/// Base operations shared by all GEM object classes
135pub trait BaseObject: IntoGEMObject {
136    /// Returns the size of the object in bytes.
137    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).
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`.
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 as_ref(), ensuring that `ptr` is a
172        //   valid pointer to an initialized `Self`.
173        let obj = unsafe { Self::as_ref(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.
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
192impl<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]
202pub 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
209impl<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.
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.
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
267    fn as_raw(&self) -> *mut bindings::drm_gem_object {
268        self.obj.get()
269    }
270
271    extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) {
272        // SAFETY: All of our objects are of type `Object<T>`.
273        let this = unsafe { crate::container_of!(obj, Self, obj) }.cast_mut();
274
275        // SAFETY: The C code only ever calls this callback with a valid pointer to a `struct
276        // drm_gem_object`.
277        unsafe { bindings::drm_gem_object_release(obj) };
278
279        // SAFETY: All of our objects are allocated via `KBox`, and we're in the
280        // free callback which guarantees this object has zero remaining references,
281        // so we can drop it.
282        let _ = unsafe { KBox::from_raw(this) };
283    }
284}
285
286impl<T: DriverObject> super::private::Sealed for Object<T> {}
287
288impl<T: DriverObject> Deref for Object<T> {
289    type Target = T;
290
291    fn deref(&self) -> &Self::Target {
292        &self.data
293    }
294}
295
296impl<T: DriverObject> AllocImpl for Object<T> {
297    const ALLOC_OPS: AllocOps = AllocOps {
298        gem_create_object: None,
299        prime_handle_to_fd: None,
300        prime_fd_to_handle: None,
301        gem_prime_import: None,
302        gem_prime_import_sg_table: None,
303        dumb_create: None,
304        dumb_map_offset: None,
305    };
306}
307
308pub(super) const fn create_fops() -> bindings::file_operations {
309    // SAFETY: As by the type invariant, it is safe to initialize `bindings::file_operations`
310    // zeroed.
311    let mut fops: bindings::file_operations = unsafe { core::mem::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}