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