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,
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};
28use core::{
29 alloc::Layout,
30 mem,
31 ops::Deref,
32 ptr::{
33 self,
34 NonNull, //
35 },
36};
37
38#[cfg(CONFIG_DRM_LEGACY)]
39macro_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))]
61macro_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)]
77pub struct Device<T: drm::Driver> {
78 dev: Opaque<bindings::drm_device>,
79 data: T::Data,
80}
81
82impl<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 // Use a temporary vtable without a `release` callback until `data` is initialized, so
123 // init failure can release the DRM device without dropping uninitialized fields.
124 let alloc_vtable = bindings::drm_driver {
125 release: None,
126 ..Self::VTABLE
127 };
128
129 // SAFETY:
130 // - `alloc_vtable` reference remains valid until no longer used,
131 // - `dev` is valid by its type invarants,
132 let raw_drm: *mut Self = unsafe {
133 bindings::__drm_dev_alloc(
134 dev.as_raw(),
135 &alloc_vtable,
136 layout.size(),
137 mem::offset_of!(Self, dev),
138 )
139 }
140 .cast();
141 let raw_drm = NonNull::new(from_err_ptr(raw_drm)?).ok_or(ENOMEM)?;
142
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: `raw_drm` is a valid pointer to `Self`.
148 let raw_data = unsafe { ptr::addr_of_mut!((*raw_drm.as_ptr()).data) };
149
150 // SAFETY:
151 // - `raw_data` is a valid pointer to uninitialized memory.
152 // - `raw_data` will not move until it is dropped.
153 unsafe { data.__pinned_init(raw_data) }.inspect_err(|_| {
154 // SAFETY: `__drm_dev_alloc()` was successful, hence `drm_dev` must be valid and the
155 // refcount must be non-zero.
156 unsafe { bindings::drm_dev_put(drm_dev) };
157 })?;
158
159 // SAFETY: `drm_dev` is still private to this function.
160 unsafe { (*drm_dev).driver = const { &Self::VTABLE } };
161
162 // SAFETY: The reference count is one, and now we take ownership of that reference as a
163 // `drm::Device`.
164 Ok(unsafe { ARef::from_raw(raw_drm) })
165 }
166
167 pub(crate) fn as_raw(&self) -> *mut bindings::drm_device {
168 self.dev.get()
169 }
170
171 /// # Safety
172 ///
173 /// `ptr` must be a valid pointer to a `struct device` embedded in `Self`.
174 unsafe fn from_drm_device(ptr: *const bindings::drm_device) -> *mut Self {
175 // SAFETY: By the safety requirements of this function `ptr` is a valid pointer to a
176 // `struct drm_device` embedded in `Self`.
177 unsafe { crate::container_of!(Opaque::cast_from(ptr), Self, dev) }.cast_mut()
178 }
179
180 /// # Safety
181 ///
182 /// `ptr` must be a valid pointer to `Self`.
183 unsafe fn into_drm_device(ptr: NonNull<Self>) -> *mut bindings::drm_device {
184 // SAFETY: By the safety requirements of this function, `ptr` is a valid pointer to `Self`.
185 unsafe { &raw mut (*ptr.as_ptr()).dev }.cast()
186 }
187
188 /// Not intended to be called externally, except via declare_drm_ioctls!()
189 ///
190 /// # Safety
191 ///
192 /// Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
193 /// i.e. it must be ensured that the reference count of the C `struct drm_device` `ptr` points
194 /// to can't drop to zero, for the duration of this function call and the entire duration when
195 /// the returned reference exists.
196 ///
197 /// Additionally, callers must ensure that the `struct device`, `ptr` is pointing to, is
198 /// embedded in `Self`.
199 #[doc(hidden)]
200 pub unsafe fn from_raw<'a>(ptr: *const bindings::drm_device) -> &'a Self {
201 // SAFETY: By the safety requirements of this function `ptr` is a valid pointer to a
202 // `struct drm_device` embedded in `Self`.
203 let ptr = unsafe { Self::from_drm_device(ptr) };
204
205 // SAFETY: `ptr` is valid by the safety requirements of this function.
206 unsafe { &*ptr.cast() }
207 }
208
209 extern "C" fn release(ptr: *mut bindings::drm_device) {
210 // SAFETY: `ptr` is a valid pointer to a `struct drm_device` and embedded in `Self`.
211 let this = unsafe { Self::from_drm_device(ptr) };
212
213 // SAFETY:
214 // - When `release` runs it is guaranteed that there is no further access to `this`.
215 // - `this` is valid for dropping.
216 unsafe { core::ptr::drop_in_place(this) };
217 }
218}
219
220impl<T: drm::Driver> Deref for Device<T> {
221 type Target = T::Data;
222
223 fn deref(&self) -> &Self::Target {
224 &self.data
225 }
226}
227
228// SAFETY: DRM device objects are always reference counted and the get/put functions
229// satisfy the requirements.
230unsafe impl<T: drm::Driver> AlwaysRefCounted for Device<T> {
231 fn inc_ref(&self) {
232 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
233 unsafe { bindings::drm_dev_get(self.as_raw()) };
234 }
235
236 unsafe fn dec_ref(obj: NonNull<Self>) {
237 // SAFETY: `obj` is a valid pointer to `Self`.
238 let drm_dev = unsafe { Self::into_drm_device(obj) };
239
240 // SAFETY: The safety requirements guarantee that the refcount is non-zero.
241 unsafe { bindings::drm_dev_put(drm_dev) };
242 }
243}
244
245impl<T: drm::Driver> AsRef<device::Device> for Device<T> {
246 fn as_ref(&self) -> &device::Device {
247 // SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid,
248 // which is guaranteed by the type invariant.
249 unsafe { device::Device::from_raw((*self.as_raw()).dev) }
250 }
251}
252
253// SAFETY: A `drm::Device` can be released from any thread.
254unsafe impl<T: drm::Driver> Send for Device<T> {}
255
256// SAFETY: A `drm::Device` can be shared among threads because all immutable methods are protected
257// by the synchronization in `struct drm_device`.
258unsafe impl<T: drm::Driver> Sync for Device<T> {}
259
260impl<T, const ID: u64> WorkItem<ID> for Device<T>
261where
262 T: drm::Driver,
263 T::Data: WorkItem<ID, Pointer = ARef<Device<T>>>,
264 T::Data: HasWork<Device<T>, ID>,
265{
266 type Pointer = ARef<Device<T>>;
267
268 fn run(ptr: ARef<Device<T>>) {
269 T::Data::run(ptr);
270 }
271}
272
273// SAFETY:
274//
275// - `raw_get_work` and `work_container_of` return valid pointers by relying on
276// `T::Data::raw_get_work` and `container_of`. In particular, `T::Data` is
277// stored inline in `drm::Device`, so the `container_of` call is valid.
278//
279// - The two methods are true inverses of each other: given `ptr: *mut
280// Device<T>`, `raw_get_work` will return a `*mut Work<Device<T>, ID>` through
281// `T::Data::raw_get_work` and given a `ptr: *mut Work<Device<T>, ID>`,
282// `work_container_of` will return a `*mut Device<T>` through `container_of`.
283unsafe impl<T, const ID: u64> HasWork<Device<T>, ID> for Device<T>
284where
285 T: drm::Driver,
286 T::Data: HasWork<Device<T>, ID>,
287{
288 unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<Device<T>, ID> {
289 // SAFETY: The caller promises that `ptr` points to a valid `Device<T>`.
290 let data_ptr = unsafe { &raw mut (*ptr).data };
291
292 // SAFETY: `data_ptr` is a valid pointer to `T::Data`.
293 unsafe { T::Data::raw_get_work(data_ptr) }
294 }
295
296 unsafe fn work_container_of(ptr: *mut Work<Device<T>, ID>) -> *mut Self {
297 // SAFETY: The caller promises that `ptr` points at a `Work` field in
298 // `T::Data`.
299 let data_ptr = unsafe { T::Data::work_container_of(ptr) };
300
301 // SAFETY: `T::Data` is stored as the `data` field in `Device<T>`.
302 unsafe { crate::container_of!(data_ptr, Self, data) }
303 }
304}
305
306// SAFETY: Our `HasWork<T, ID>` implementation returns a `work_struct` that is
307// stored in the `work` field of a `delayed_work` with the same access rules as
308// the `work_struct` owing to the bound on `T::Data: HasDelayedWork<Device<T>,
309// ID>`, which requires that `T::Data::raw_get_work` return a `work_struct` that
310// is inside a `delayed_work`.
311unsafe impl<T, const ID: u64> HasDelayedWork<Device<T>, ID> for Device<T>
312where
313 T: drm::Driver,
314 T::Data: HasDelayedWork<Device<T>, ID>,
315{
316}