Skip to main content

kernel/drm/
device.rs

1// SPDX-License-Identifier: GPL-2.0 OR MIT
2
3//! DRM device.
4//!
5//! C header: [`include/drm/drm_device.h`](srctree/include/drm/drm_device.h)
6
7use crate::{
8    alloc::allocator::Kmalloc,
9    bindings,
10    device,
11    drm::{
12        self,
13        driver::AllocImpl, //
14    },
15    error::from_err_ptr,
16    prelude::*,
17    sync::aref::{
18        ARef,
19        AlwaysRefCounted, //
20    },
21    types::Opaque, //
22};
23use core::{
24    alloc::Layout,
25    mem,
26    ops::Deref,
27    ptr::{
28        self,
29        NonNull, //
30    },
31};
32
33#[cfg(CONFIG_DRM_LEGACY)]
34macro_rules! drm_legacy_fields {
35    ( $($field:ident: $val:expr),* $(,)? ) => {
36        bindings::drm_driver {
37            $( $field: $val ),*,
38            firstopen: None,
39            preclose: None,
40            dma_ioctl: None,
41            dma_quiescent: None,
42            context_dtor: None,
43            irq_handler: None,
44            irq_preinstall: None,
45            irq_postinstall: None,
46            irq_uninstall: None,
47            get_vblank_counter: None,
48            enable_vblank: None,
49            disable_vblank: None,
50            dev_priv_size: 0,
51        }
52    }
53}
54
55#[cfg(not(CONFIG_DRM_LEGACY))]
56macro_rules! drm_legacy_fields {
57    ( $($field:ident: $val:expr),* $(,)? ) => {
58        bindings::drm_driver {
59            $( $field: $val ),*
60        }
61    }
62}
63
64/// A typed DRM device with a specific `drm::Driver` implementation.
65///
66/// The device is always reference-counted.
67///
68/// # Invariants
69///
70/// `self.dev` is a valid instance of a `struct device`.
71#[repr(C)]
72pub struct Device<T: drm::Driver> {
73    dev: Opaque<bindings::drm_device>,
74    data: T::Data,
75}
76
77impl<T: drm::Driver> Device<T> {
78    const VTABLE: bindings::drm_driver = drm_legacy_fields! {
79        load: None,
80        open: Some(drm::File::<T::File>::open_callback),
81        postclose: Some(drm::File::<T::File>::postclose_callback),
82        unload: None,
83        release: Some(Self::release),
84        master_set: None,
85        master_drop: None,
86        debugfs_init: None,
87        gem_create_object: T::Object::ALLOC_OPS.gem_create_object,
88        prime_handle_to_fd: T::Object::ALLOC_OPS.prime_handle_to_fd,
89        prime_fd_to_handle: T::Object::ALLOC_OPS.prime_fd_to_handle,
90        gem_prime_import: T::Object::ALLOC_OPS.gem_prime_import,
91        gem_prime_import_sg_table: T::Object::ALLOC_OPS.gem_prime_import_sg_table,
92        dumb_create: T::Object::ALLOC_OPS.dumb_create,
93        dumb_map_offset: T::Object::ALLOC_OPS.dumb_map_offset,
94        show_fdinfo: None,
95        fbdev_probe: None,
96
97        major: T::INFO.major,
98        minor: T::INFO.minor,
99        patchlevel: T::INFO.patchlevel,
100        name: crate::str::as_char_ptr_in_const_context(T::INFO.name).cast_mut(),
101        desc: crate::str::as_char_ptr_in_const_context(T::INFO.desc).cast_mut(),
102
103        driver_features: drm::driver::FEAT_GEM,
104        ioctls: T::IOCTLS.as_ptr(),
105        num_ioctls: T::IOCTLS.len() as i32,
106        fops: &Self::GEM_FOPS,
107    };
108
109    const GEM_FOPS: bindings::file_operations = drm::gem::create_fops();
110
111    /// Create a new `drm::Device` for a `drm::Driver`.
112    pub fn new(dev: &device::Device, data: impl PinInit<T::Data, Error>) -> Result<ARef<Self>> {
113        // `__drm_dev_alloc` uses `kmalloc()` to allocate memory, hence ensure a `kmalloc()`
114        // compatible `Layout`.
115        let layout = Kmalloc::aligned_layout(Layout::new::<Self>());
116
117        // SAFETY:
118        // - `VTABLE`, as a `const` is pinned to the read-only section of the compilation,
119        // - `dev` is valid by its type invarants,
120        let raw_drm: *mut Self = unsafe {
121            bindings::__drm_dev_alloc(
122                dev.as_raw(),
123                &Self::VTABLE,
124                layout.size(),
125                mem::offset_of!(Self, dev),
126            )
127        }
128        .cast();
129        let raw_drm = NonNull::new(from_err_ptr(raw_drm)?).ok_or(ENOMEM)?;
130
131        // SAFETY: `raw_drm` is a valid pointer to `Self`.
132        let raw_data = unsafe { ptr::addr_of_mut!((*raw_drm.as_ptr()).data) };
133
134        // SAFETY:
135        // - `raw_data` is a valid pointer to uninitialized memory.
136        // - `raw_data` will not move until it is dropped.
137        unsafe { data.__pinned_init(raw_data) }.inspect_err(|_| {
138            // SAFETY: `raw_drm` is a valid pointer to `Self`, given that `__drm_dev_alloc` was
139            // successful.
140            let drm_dev = unsafe { Self::into_drm_device(raw_drm) };
141
142            // SAFETY: `__drm_dev_alloc()` was successful, hence `drm_dev` must be valid and the
143            // refcount must be non-zero.
144            unsafe { bindings::drm_dev_put(drm_dev) };
145        })?;
146
147        // SAFETY: The reference count is one, and now we take ownership of that reference as a
148        // `drm::Device`.
149        Ok(unsafe { ARef::from_raw(raw_drm) })
150    }
151
152    pub(crate) fn as_raw(&self) -> *mut bindings::drm_device {
153        self.dev.get()
154    }
155
156    /// # Safety
157    ///
158    /// `ptr` must be a valid pointer to a `struct device` embedded in `Self`.
159    unsafe fn from_drm_device(ptr: *const bindings::drm_device) -> *mut Self {
160        // SAFETY: By the safety requirements of this function `ptr` is a valid pointer to a
161        // `struct drm_device` embedded in `Self`.
162        unsafe { crate::container_of!(Opaque::cast_from(ptr), Self, dev) }.cast_mut()
163    }
164
165    /// # Safety
166    ///
167    /// `ptr` must be a valid pointer to `Self`.
168    unsafe fn into_drm_device(ptr: NonNull<Self>) -> *mut bindings::drm_device {
169        // SAFETY: By the safety requirements of this function, `ptr` is a valid pointer to `Self`.
170        unsafe { &raw mut (*ptr.as_ptr()).dev }.cast()
171    }
172
173    /// Not intended to be called externally, except via declare_drm_ioctls!()
174    ///
175    /// # Safety
176    ///
177    /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
178    /// i.e. it must be ensured that the reference count of the C `struct drm_device` `ptr` points
179    /// to can't drop to zero, for the duration of this function call and the entire duration when
180    /// the returned reference exists.
181    ///
182    /// Additionally, callers must ensure that the `struct device`, `ptr` is pointing to, is
183    /// embedded in `Self`.
184    #[doc(hidden)]
185    pub unsafe fn from_raw<'a>(ptr: *const bindings::drm_device) -> &'a Self {
186        // SAFETY: By the safety requirements of this function `ptr` is a valid pointer to a
187        // `struct drm_device` embedded in `Self`.
188        let ptr = unsafe { Self::from_drm_device(ptr) };
189
190        // SAFETY: `ptr` is valid by the safety requirements of this function.
191        unsafe { &*ptr.cast() }
192    }
193
194    extern "C" fn release(ptr: *mut bindings::drm_device) {
195        // SAFETY: `ptr` is a valid pointer to a `struct drm_device` and embedded in `Self`.
196        let this = unsafe { Self::from_drm_device(ptr) };
197
198        // SAFETY:
199        // - When `release` runs it is guaranteed that there is no further access to `this`.
200        // - `this` is valid for dropping.
201        unsafe { core::ptr::drop_in_place(this) };
202    }
203}
204
205impl<T: drm::Driver> Deref for Device<T> {
206    type Target = T::Data;
207
208    fn deref(&self) -> &Self::Target {
209        &self.data
210    }
211}
212
213// SAFETY: DRM device objects are always reference counted and the get/put functions
214// satisfy the requirements.
215unsafe impl<T: drm::Driver> AlwaysRefCounted for Device<T> {
216    fn inc_ref(&self) {
217        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
218        unsafe { bindings::drm_dev_get(self.as_raw()) };
219    }
220
221    unsafe fn dec_ref(obj: NonNull<Self>) {
222        // SAFETY: `obj` is a valid pointer to `Self`.
223        let drm_dev = unsafe { Self::into_drm_device(obj) };
224
225        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
226        unsafe { bindings::drm_dev_put(drm_dev) };
227    }
228}
229
230impl<T: drm::Driver> AsRef<device::Device> for Device<T> {
231    fn as_ref(&self) -> &device::Device {
232        // SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid,
233        // which is guaranteed by the type invariant.
234        unsafe { device::Device::from_raw((*self.as_raw()).dev) }
235    }
236}
237
238// SAFETY: A `drm::Device` can be released from any thread.
239unsafe impl<T: drm::Driver> Send for Device<T> {}
240
241// SAFETY: A `drm::Device` can be shared among threads because all immutable methods are protected
242// by the synchronization in `struct drm_device`.
243unsafe impl<T: drm::Driver> Sync for Device<T> {}