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,
10 device,
11 drm::{
12 self,
13 driver::AllocImpl,
14 private::Sealed, //
15 },
16 error::from_err_ptr,
17 prelude::*,
18 sync::aref::{
19 ARef,
20 AlwaysRefCounted, //
21 },
22 types::{
23 NotThreadSafe,
24 Opaque, //
25 },
26 workqueue::{
27 HasDelayedWork,
28 HasWork,
29 Work,
30 WorkItem, //
31 }, //
32};
33use core::{
34 alloc::Layout,
35 cell::UnsafeCell,
36 marker::PhantomData,
37 mem,
38 ops::Deref,
39 ptr::{
40 self,
41 NonNull, //
42 },
43};
44
45#[cfg(CONFIG_DRM_LEGACY)]
46macro_rules! drm_legacy_fields {
47 ( $($field:ident: $val:expr),* $(,)? ) => {
48 bindings::drm_driver {
49 $( $field: $val ),*,
50 firstopen: None,
51 preclose: None,
52 dma_ioctl: None,
53 dma_quiescent: None,
54 context_dtor: None,
55 irq_handler: None,
56 irq_preinstall: None,
57 irq_postinstall: None,
58 irq_uninstall: None,
59 get_vblank_counter: None,
60 enable_vblank: None,
61 disable_vblank: None,
62 dev_priv_size: 0,
63 }
64 }
65}
66
67#[cfg(not(CONFIG_DRM_LEGACY))]
68macro_rules! drm_legacy_fields {
69 ( $($field:ident: $val:expr),* $(,)? ) => {
70 bindings::drm_driver {
71 $( $field: $val ),*
72 }
73 }
74}
75
76/// A trait implemented by all possible contexts a [`Device`] can be used in.
77///
78/// A [`Device`] can be in one of the following contexts:
79///
80/// - [`Normal`]: The general-purpose, reference-counted context. A [`Device`] in this context may
81/// or may not be registered with userspace.
82/// - [`Ioctl`]: The device has been registered with userspace at some point; used in ioctl
83/// dispatch context.
84/// - [`Registered`]: The device is currently registered with userspace and the parent bus device
85/// is bound.
86///
87/// Both `Device<T, Ioctl>` and `Device<T, Registered>` dereference to `Device<T>` ([`Normal`]),
88/// so any method available on a [`Normal`] device is also available in the other contexts.
89pub trait DeviceContext: Sealed + Send + Sync + 'static {}
90
91/// The general-purpose, reference-counted [`DeviceContext`].
92///
93/// A [`Device`] in this context may or may not be registered with userspace. This context is used
94/// for reference-counted device handles and during device setup via [`UnregisteredDevice`].
95///
96/// [`AlwaysRefCounted`] is only implemented for `Device<T, Normal>`, making this the required
97/// context for [`ARef`]-based device handles.
98pub struct Normal;
99
100impl Sealed for Normal {}
101impl DeviceContext for Normal {}
102
103/// The [`DeviceContext`] of a [`Device`] that is currently registered with userspace.
104///
105/// A [`Device`] in this context is guaranteed to be registered and its parent bus device is
106/// guaranteed to be bound. This is enforced at runtime by [`RegistrationGuard`], which holds a
107/// `drm_dev_enter()` / `drm_dev_exit()` SRCU critical section.
108///
109/// # Invariants
110///
111/// The parent bus device is bound for the duration of any reference to a `Device<T, Registered>`.
112pub struct Registered;
113
114impl Sealed for Registered {}
115impl DeviceContext for Registered {}
116
117/// The [`DeviceContext`] of a [`Device`] that has been registered with userspace previously.
118///
119/// A [`Device`] in this context has been registered at some point, but may be concurrently
120/// unregistering or already unregistered. `drm_dev_enter()` can guard against this, ensuring the
121/// device remains registered for the duration of the critical section.
122///
123/// # Invariants
124///
125/// A [`Device`] in this context has been registered with userspace via `drm_dev_register()` at
126/// some point.
127pub struct Ioctl;
128
129impl Sealed for Ioctl {}
130impl DeviceContext for Ioctl {}
131
132/// A [`Device`] which is known at compile-time to be unregistered with userspace.
133///
134/// This type allows performing operations which are only safe to do before userspace registration,
135/// and can be used to create a [`Registration`](drm::driver::Registration) once the driver is ready
136/// to register the device with userspace.
137///
138/// Since DRM device initialization must be single-threaded, this object is not thread-safe.
139///
140/// # Invariants
141///
142/// The device in `self.0` is guaranteed to be a newly created [`Device`] that has not yet been
143/// registered with userspace until this type is dropped.
144pub struct UnregisteredDevice<T: drm::Driver>(ARef<Device<T, Normal>>, NotThreadSafe);
145
146impl<T: drm::Driver> Deref for UnregisteredDevice<T> {
147 type Target = Device<T, Normal>;
148
149 fn deref(&self) -> &Self::Target {
150 &self.0
151 }
152}
153
154impl<T: drm::Driver> UnregisteredDevice<T> {
155 const fn compute_features() -> u32 {
156 let mut features = drm::driver::FEAT_GEM;
157
158 if T::FEAT_RENDER {
159 features |= drm::driver::FEAT_RENDER;
160 }
161
162 features
163 }
164
165 const VTABLE: bindings::drm_driver = drm_legacy_fields! {
166 load: None,
167 open: Some(drm::File::<T::File>::open_callback),
168 postclose: Some(drm::File::<T::File>::postclose_callback),
169 unload: None,
170 release: Some(Device::<T>::release),
171 master_set: None,
172 master_drop: None,
173 debugfs_init: None,
174
175 gem_create_object: T::Object::ALLOC_OPS.gem_create_object,
176 prime_handle_to_fd: T::Object::ALLOC_OPS.prime_handle_to_fd,
177 prime_fd_to_handle: T::Object::ALLOC_OPS.prime_fd_to_handle,
178 gem_prime_import: T::Object::ALLOC_OPS.gem_prime_import,
179 gem_prime_import_sg_table: T::Object::ALLOC_OPS.gem_prime_import_sg_table,
180 dumb_create: T::Object::ALLOC_OPS.dumb_create,
181 dumb_map_offset: T::Object::ALLOC_OPS.dumb_map_offset,
182
183 show_fdinfo: None,
184 fbdev_probe: None,
185
186 major: T::INFO.major,
187 minor: T::INFO.minor,
188 patchlevel: T::INFO.patchlevel,
189 name: crate::str::as_char_ptr_in_const_context(T::INFO.name).cast_mut(),
190 desc: crate::str::as_char_ptr_in_const_context(T::INFO.desc).cast_mut(),
191
192 driver_features: Self::compute_features(),
193 ioctls: T::IOCTLS.as_ptr(),
194 num_ioctls: T::IOCTLS.len() as i32,
195 fops: &Self::GEM_FOPS,
196 };
197
198 const GEM_FOPS: bindings::file_operations = drm::gem::create_fops();
199
200 /// Create a new `UnregisteredDevice` for a `drm::Driver`.
201 ///
202 /// This can be used to create a [`Registration`](kernel::drm::Registration).
203 pub fn new(
204 dev: &T::ParentDevice<device::Bound>,
205 data: impl PinInit<T::Data, Error>,
206 ) -> Result<Self> {
207 // `__drm_dev_alloc` uses `kmalloc()` to allocate memory, hence ensure a `kmalloc()`
208 // compatible `Layout`.
209 let layout = Kmalloc::aligned_layout(Layout::new::<Device<T, Normal>>());
210
211 // Use a temporary vtable without a `release` callback until `data` is initialized, so
212 // init failure can release the DRM device without dropping uninitialized fields.
213 let alloc_vtable = bindings::drm_driver {
214 release: None,
215 ..Self::VTABLE
216 };
217
218 // SAFETY:
219 // - `alloc_vtable` reference remains valid until no longer used,
220 // - `dev` is valid by its type invarants,
221 let raw_drm: *mut Device<T, Normal> = unsafe {
222 bindings::__drm_dev_alloc(
223 dev.as_ref().as_raw(),
224 &alloc_vtable,
225 layout.size(),
226 mem::offset_of!(Device<T, Normal>, dev),
227 )
228 }
229 .cast();
230 let raw_drm = NonNull::new(from_err_ptr(raw_drm)?).ok_or(ENOMEM)?;
231
232 // SAFETY: `raw_drm` is a valid pointer to `Self`, given that `__drm_dev_alloc` was
233 // successful.
234 let drm_dev = unsafe { Device::into_drm_device(raw_drm) };
235
236 // SAFETY: `raw_drm` is a valid pointer to `Self`.
237 let raw_data = unsafe { ptr::addr_of_mut!((*raw_drm.as_ptr()).data) };
238
239 // SAFETY:
240 // - `raw_data` is a valid pointer to uninitialized memory.
241 // - `raw_data` will not move until it is dropped.
242 unsafe { data.__pinned_init(raw_data) }.inspect_err(|_| {
243 // SAFETY: `__drm_dev_alloc()` was successful, hence `drm_dev` must be valid and the
244 // refcount must be non-zero.
245 unsafe { bindings::drm_dev_put(drm_dev) };
246 })?;
247
248 // SAFETY: `drm_dev` is still private to this function.
249 unsafe { (*drm_dev).driver = const { &Self::VTABLE } };
250
251 // SAFETY: `raw_drm` is valid; no concurrent access before registration.
252 unsafe { (*raw_drm.as_ptr()).registration_data = UnsafeCell::new(NonNull::dangling()) };
253
254 // SAFETY: The reference count is one, and now we take ownership of that reference as a
255 // `drm::Device`.
256 // INVARIANT: We just created the device above, but have yet to call `drm_dev_register`.
257 // `Self` cannot be copied or sent to another thread - ensuring that `drm_dev_register`
258 // won't be called during its lifetime and that the device is unregistered.
259 Ok(Self(unsafe { ARef::from_raw(raw_drm) }, NotThreadSafe))
260 }
261}
262
263/// A typed DRM device with a specific [`drm::Driver`] implementation and [`DeviceContext`].
264///
265/// A device in the [`Registered`] context is currently registered with userspace and its parent
266/// bus device is bound. The [`Normal`] context is the general-purpose, reference-counted context.
267///
268/// # Invariants
269///
270/// * `self.dev` is a valid instance of a `struct device`.
271/// * The data layout of `Self` remains the same across all implementations of `C`.
272/// * Any invariants for `C` also apply.
273#[repr(C)]
274pub struct Device<T: drm::Driver, C: DeviceContext = Normal> {
275 dev: Opaque<bindings::drm_device>,
276 data: T::Data,
277 pub(super) registration_data: UnsafeCell<NonNull<T::RegistrationData<'static>>>,
278 _ctx: PhantomData<C>,
279}
280
281impl<T: drm::Driver, C: DeviceContext> Device<T, C> {
282 pub(crate) fn as_raw(&self) -> *mut bindings::drm_device {
283 self.dev.get()
284 }
285
286 /// # Safety
287 ///
288 /// `ptr` must be a valid pointer to a `struct device` embedded in `Self`.
289 unsafe fn from_drm_device(ptr: *const bindings::drm_device) -> *mut Self {
290 // SAFETY: By the safety requirements of this function `ptr` is a valid pointer to a
291 // `struct drm_device` embedded in `Self`.
292 unsafe { crate::container_of!(Opaque::cast_from(ptr), Self, dev) }.cast_mut()
293 }
294
295 /// # Safety
296 ///
297 /// `ptr` must be a valid pointer to `Self`.
298 unsafe fn into_drm_device(ptr: NonNull<Self>) -> *mut bindings::drm_device {
299 // SAFETY: By the safety requirements of this function, `ptr` is a valid pointer to `Self`.
300 unsafe { &raw mut (*ptr.as_ptr()).dev }.cast()
301 }
302
303 /// Not intended to be called externally, except via declare_drm_ioctls!()
304 ///
305 /// # Safety
306 ///
307 /// * Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count,
308 /// i.e. it must be ensured that the reference count of the C `struct drm_device` `ptr` points
309 /// to can't drop to zero, for the duration of this function call and the entire duration when
310 /// the returned reference exists.
311 /// * Additionally, callers must ensure that the `struct device`, `ptr` is pointing to, is
312 /// embedded in `Self`.
313 /// * Callers promise that any type invariants of `C` will be upheld.
314 #[doc(hidden)]
315 pub unsafe fn from_raw<'a>(ptr: *const bindings::drm_device) -> &'a Self {
316 // SAFETY: By the safety requirements of this function `ptr` is a valid pointer to a
317 // `struct drm_device` embedded in `Self`.
318 let ptr = unsafe { Self::from_drm_device(ptr) };
319
320 // SAFETY: `ptr` is valid by the safety requirements of this function.
321 unsafe { &*ptr.cast() }
322 }
323
324 extern "C" fn release(ptr: *mut bindings::drm_device) {
325 // SAFETY: `ptr` is a valid pointer to a `struct drm_device` and embedded in `Self`.
326 let this = unsafe { Self::from_drm_device(ptr) };
327
328 // SAFETY:
329 // - When `release` runs it is guaranteed that there is no further access to `this`.
330 // - `this` is valid for dropping.
331 unsafe { core::ptr::drop_in_place(this) };
332 }
333
334 /// Change the [`DeviceContext`] for a [`Device`].
335 ///
336 /// # Safety
337 ///
338 /// The caller promises that `self` fulfills all of the guarantees provided by the given
339 /// [`DeviceContext`].
340 pub(crate) unsafe fn assume_ctx<NewCtx: DeviceContext>(&self) -> &Device<T, NewCtx> {
341 // SAFETY: The data layout is identical via our type invariants.
342 unsafe { mem::transmute(self) }
343 }
344}
345
346impl<T: drm::Driver> Device<T, Ioctl> {
347 /// Guard against the parent bus device being unbound.
348 ///
349 /// Returns a [`RegistrationGuard`] if the device has not been unplugged, [`None`] otherwise.
350 ///
351 /// While [`RegistrationGuard`] is held the parent device is guaranteed to be bound.
352 #[must_use]
353 pub fn registration_guard(&self) -> Option<RegistrationGuard<'_, T>> {
354 let mut idx: i32 = 0;
355 // SAFETY: `self.as_raw()` is a valid pointer to a `struct drm_device`.
356 if unsafe { bindings::drm_dev_enter(self.as_raw(), &mut idx) } {
357 // INVARIANT:
358 // - `idx` is the SRCU index from the successful `drm_dev_enter()` above.
359 // - The parent bus device is bound: `drm_dev_enter()` succeeded, meaning
360 // `drm_dev_unplug()` has not completed; since it is only called from
361 // `Registration::drop()` during parent unbind, the parent is still bound.
362 Some(RegistrationGuard {
363 // SAFETY: See INVARIANT above; the `Registered` context invariant holds.
364 dev: unsafe { self.assume_ctx() },
365 idx,
366 _not_send: NotThreadSafe,
367 })
368 } else {
369 None
370 }
371 }
372}
373
374/// A guard proving the DRM device is registered and the parent bus device is bound.
375///
376/// The guard dereferences to [`Device<T, Registered>`], providing access to the DRM device with
377/// the guarantee that the parent bus device is bound for the entire duration of the critical
378/// section.
379///
380/// Internally this is backed by a `drm_dev_enter()` / `drm_dev_exit()` SRCU critical section.
381///
382/// # Invariants
383///
384/// - `idx` is the SRCU read lock index returned by a successful `drm_dev_enter()` call.
385/// - The parent bus device of `dev` is bound for the lifetime of this guard.
386#[must_use]
387pub struct RegistrationGuard<'a, T: drm::Driver> {
388 dev: &'a Device<T, Registered>,
389 idx: i32,
390 _not_send: NotThreadSafe,
391}
392
393impl<T: drm::Driver> Device<T, Registered> {
394 /// Returns a reference to the registration data with lifetime shortened from `'static`.
395 ///
396 /// # Safety
397 ///
398 /// The returned reference must not be exposed to code that can choose a concrete lifetime for
399 /// it, as that would be unsound for types that are invariant over their lifetime parameter
400 /// (e.g. it must be passed through an HRTB-bounded closure).
401 #[inline]
402 unsafe fn registration_data_unchecked(&self) -> &T::RegistrationData<'_> {
403 // SAFETY:
404 // - `Registered` guarantees the parent bus device is bound, hence the pointer is valid.
405 // - The pointer cast from `Of<'static>` to `Of<'_>` is layout-compatible since lifetimes
406 // are erased at runtime.
407 // - Caller guarantees the reference is only used behind an HRTB, making the lifetime
408 // shortening sound regardless of variance.
409 unsafe { (*self.registration_data.get()).cast::<_>().as_ref() }
410 }
411
412 /// Access the registration data through a closure, with the lifetime tied to the closure
413 /// scope.
414 ///
415 /// The data is owned by [`Registration`](drm::Registration) and is guaranteed to remain valid
416 /// as long as the device is registered, since [`Registration`](drm::Registration)'s `drop`
417 /// calls `drm_dev_unplug()` which waits for all `drm_dev_enter()` critical sections to
418 /// complete.
419 #[inline]
420 pub fn registration_data_with<R, F>(&self, f: F) -> R
421 where
422 F: for<'a> FnOnce(&'a T::RegistrationData<'a>) -> R,
423 {
424 // SAFETY: `Registered` guarantees the device is registered and the parent bus device is
425 // bound. The closure's HRTB `for<'a>` prevents the caller from smuggling in references
426 // with a concrete short lifetime, satisfying the lifetime requirement of
427 // `registration_data_unchecked`.
428 f(unsafe { self.registration_data_unchecked() })
429 }
430}
431
432impl<T: drm::Driver> Deref for RegistrationGuard<'_, T> {
433 type Target = Device<T, Registered>;
434
435 #[inline]
436 fn deref(&self) -> &Self::Target {
437 self.dev
438 }
439}
440
441impl<T: drm::Driver> Drop for RegistrationGuard<'_, T> {
442 #[inline]
443 fn drop(&mut self) {
444 // SAFETY: `self.idx` was returned by a successful `drm_dev_enter()` call, as guaranteed
445 // by the type invariants of `RegistrationGuard`.
446 unsafe { bindings::drm_dev_exit(self.idx) };
447 }
448}
449
450impl<T: drm::Driver> Deref for Device<T> {
451 type Target = T::Data;
452
453 fn deref(&self) -> &Self::Target {
454 &self.data
455 }
456}
457
458impl<T: drm::Driver> Deref for Device<T, Registered> {
459 type Target = Device<T>;
460
461 #[inline]
462 fn deref(&self) -> &Self::Target {
463 // SAFETY: The caller holds a `Device<T, Registered>`, which guarantees all invariants
464 // of the weaker `Normal` context.
465 unsafe { self.assume_ctx() }
466 }
467}
468
469impl<T: drm::Driver> Deref for Device<T, Ioctl> {
470 type Target = Device<T>;
471
472 #[inline]
473 fn deref(&self) -> &Self::Target {
474 // SAFETY: The caller holds a `Device<T, Ioctl>`, which guarantees all invariants
475 // of the weaker `Normal` context.
476 unsafe { self.assume_ctx() }
477 }
478}
479
480// SAFETY: DRM device objects are always reference counted and the get/put functions
481// satisfy the requirements.
482unsafe impl<T: drm::Driver> AlwaysRefCounted for Device<T> {
483 fn inc_ref(&self) {
484 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
485 unsafe { bindings::drm_dev_get(self.as_raw()) };
486 }
487
488 unsafe fn dec_ref(obj: NonNull<Self>) {
489 // SAFETY: `obj` is a valid pointer to `Self`.
490 let drm_dev = unsafe { Self::into_drm_device(obj) };
491
492 // SAFETY: The safety requirements guarantee that the refcount is non-zero.
493 unsafe { bindings::drm_dev_put(drm_dev) };
494 }
495}
496
497impl<T: drm::Driver> AsRef<T::ParentDevice<device::Normal>> for Device<T> {
498 fn as_ref(&self) -> &T::ParentDevice<device::Normal> {
499 // SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid,
500 // which is guaranteed by the type invariant.
501 let dev = unsafe { device::Device::from_raw((*self.as_raw()).dev) };
502
503 // SAFETY: The DRM device was constructed in `UnregisteredDevice::new()` with a parent
504 // device of type `T::ParentDevice`, hence `dev` is contained in a `T::ParentDevice`.
505 unsafe { device::AsBusDevice::from_device(dev) }
506 }
507}
508
509impl<T: drm::Driver> AsRef<T::ParentDevice<device::Bound>> for Device<T, Registered> {
510 #[inline]
511 fn as_ref(&self) -> &T::ParentDevice<device::Bound> {
512 let dev = (**self).as_ref().as_ref();
513
514 // SAFETY: A `Device<T, Registered>` guarantees that the parent device is bound.
515 let dev = unsafe { dev.as_bound() };
516
517 // SAFETY: The DRM device was constructed in `UnregisteredDevice::new()` with a parent
518 // device of type `T::ParentDevice`, hence `dev` is contained in a `T::ParentDevice`.
519 unsafe { device::AsBusDevice::from_device(dev) }
520 }
521}
522
523// SAFETY: A `drm::Device` can be released from any thread.
524unsafe impl<T: drm::Driver, C: DeviceContext> Send for Device<T, C> {}
525
526// SAFETY: A `drm::Device` can be shared among threads because all immutable methods are protected
527// by the synchronization in `struct drm_device`.
528unsafe impl<T: drm::Driver, C: DeviceContext> Sync for Device<T, C> {}
529
530impl<T: drm::Driver, const ID: u64> WorkItem<ID> for Device<T>
531where
532 T::Data: WorkItem<ID, Pointer = ARef<Self>>,
533 T::Data: HasWork<Self, ID>,
534{
535 type Pointer = ARef<Self>;
536
537 fn run(ptr: ARef<Self>) {
538 T::Data::run(ptr);
539 }
540}
541
542// SAFETY:
543//
544// - `raw_get_work` and `work_container_of` return valid pointers by relying on
545// `T::Data::raw_get_work` and `container_of`. In particular, `T::Data` is
546// stored inline in `drm::Device`, so the `container_of` call is valid.
547//
548// - The two methods are true inverses of each other: given `ptr: *mut
549// Device<T, C>`, `raw_get_work` will return a `*mut Work<Device<T, C>, ID>` through
550// `T::Data::raw_get_work` and given a `ptr: *mut Work<Device<T, C>, ID>`,
551// `work_container_of` will return a `*mut Device<T, C>` through `container_of`.
552unsafe impl<T, C, const ID: u64> HasWork<Self, ID> for Device<T, C>
553where
554 T: drm::Driver,
555 T::Data: HasWork<Self, ID>,
556 C: DeviceContext,
557{
558 unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<Self, ID> {
559 // SAFETY: The caller promises that `ptr` points to a valid `Device<T, C>`.
560 let data_ptr = unsafe { &raw mut (*ptr).data };
561
562 // SAFETY: `data_ptr` is a valid pointer to `T::Data`.
563 unsafe { T::Data::raw_get_work(data_ptr) }
564 }
565
566 unsafe fn work_container_of(ptr: *mut Work<Self, ID>) -> *mut Self {
567 // SAFETY: The caller promises that `ptr` points at a `Work` field in
568 // `T::Data`.
569 let data_ptr = unsafe { T::Data::work_container_of(ptr) };
570
571 // SAFETY: `T::Data` is stored as the `data` field in `Device<T, C>`.
572 unsafe { crate::container_of!(data_ptr, Self, data) }
573 }
574}
575
576// SAFETY: Our `HasWork<T, ID>` implementation returns a `work_struct` that is
577// stored in the `work` field of a `delayed_work` with the same access rules as
578// the `work_struct` owing to the bound on `T::Data: HasDelayedWork<Device<T, C>,
579// ID>`, which requires that `T::Data::raw_get_work` return a `work_struct` that
580// is inside a `delayed_work`.
581unsafe impl<T, C, const ID: u64> HasDelayedWork<Self, ID> for Device<T, C>
582where
583 T: drm::Driver,
584 T::Data: HasDelayedWork<Self, ID>,
585 C: DeviceContext,
586{
587}