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