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