kernel/drm/
device.rs

1// SPDX-License-Identifier: GPL-2.0 OR MIT
2
3//! DRM device.
4//!
5//! C header: [`include/linux/drm/drm_device.h`](srctree/include/linux/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};
18
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: T::INFO.name.as_char_ptr().cast_mut(),
87        desc: T::INFO.desc.as_char_ptr().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    unsafe fn from_drm_device(ptr: *const bindings::drm_device) -> *mut Self {
146        // SAFETY: By the safety requirements of this function `ptr` is a valid pointer to a
147        // `struct drm_device` embedded in `Self`.
148        unsafe { crate::container_of!(Opaque::cast_from(ptr), Self, dev) }.cast_mut()
149    }
150
151    /// # Safety
152    ///
153    /// `ptr` must be a valid pointer to `Self`.
154    unsafe fn into_drm_device(ptr: NonNull<Self>) -> *mut bindings::drm_device {
155        // SAFETY: By the safety requirements of this function, `ptr` is a valid pointer to `Self`.
156        unsafe { &raw mut (*ptr.as_ptr()).dev }.cast()
157    }
158
159    /// Not intended to be called externally, except via declare_drm_ioctls!()
160    ///
161    /// # Safety
162    ///
163    /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
164    /// i.e. it must be ensured that the reference count of the C `struct drm_device` `ptr` points
165    /// to can't drop to zero, for the duration of this function call and the entire duration when
166    /// the returned reference exists.
167    ///
168    /// Additionally, callers must ensure that the `struct device`, `ptr` is pointing to, is
169    /// embedded in `Self`.
170    #[doc(hidden)]
171    pub unsafe fn from_raw<'a>(ptr: *const bindings::drm_device) -> &'a Self {
172        // SAFETY: By the safety requirements of this function `ptr` is a valid pointer to a
173        // `struct drm_device` embedded in `Self`.
174        let ptr = unsafe { Self::from_drm_device(ptr) };
175
176        // SAFETY: `ptr` is valid by the safety requirements of this function.
177        unsafe { &*ptr.cast() }
178    }
179
180    extern "C" fn release(ptr: *mut bindings::drm_device) {
181        // SAFETY: `ptr` is a valid pointer to a `struct drm_device` and embedded in `Self`.
182        let this = unsafe { Self::from_drm_device(ptr) };
183
184        // SAFETY:
185        // - When `release` runs it is guaranteed that there is no further access to `this`.
186        // - `this` is valid for dropping.
187        unsafe { core::ptr::drop_in_place(this) };
188    }
189}
190
191impl<T: drm::Driver> Deref for Device<T> {
192    type Target = T::Data;
193
194    fn deref(&self) -> &Self::Target {
195        &self.data
196    }
197}
198
199// SAFETY: DRM device objects are always reference counted and the get/put functions
200// satisfy the requirements.
201unsafe impl<T: drm::Driver> AlwaysRefCounted for Device<T> {
202    fn inc_ref(&self) {
203        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
204        unsafe { bindings::drm_dev_get(self.as_raw()) };
205    }
206
207    unsafe fn dec_ref(obj: NonNull<Self>) {
208        // SAFETY: `obj` is a valid pointer to `Self`.
209        let drm_dev = unsafe { Self::into_drm_device(obj) };
210
211        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
212        unsafe { bindings::drm_dev_put(drm_dev) };
213    }
214}
215
216impl<T: drm::Driver> AsRef<device::Device> for Device<T> {
217    fn as_ref(&self) -> &device::Device {
218        // SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid,
219        // which is guaranteed by the type invariant.
220        unsafe { device::Device::from_raw((*self.as_raw()).dev) }
221    }
222}
223
224// SAFETY: A `drm::Device` can be released from any thread.
225unsafe impl<T: drm::Driver> Send for Device<T> {}
226
227// SAFETY: A `drm::Device` can be shared among threads because all immutable methods are protected
228// by the synchronization in `struct drm_device`.
229unsafe impl<T: drm::Driver> Sync for Device<T> {}