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