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