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, 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 }; 33 use core::{ 34 alloc::Layout, 35 marker::PhantomData, 36 mem, 37 ops::Deref, 38 ptr::{ 39 self, 40 NonNull, // 41 }, 42 }; 43 44 #[cfg(CONFIG_DRM_LEGACY)] 45 macro_rules! drm_legacy_fields { 46 ( $($field:ident: $val:expr),* $(,)? ) => { 47 bindings::drm_driver { 48 $( $field: $val ),*, 49 firstopen: None, 50 preclose: None, 51 dma_ioctl: None, 52 dma_quiescent: None, 53 context_dtor: None, 54 irq_handler: None, 55 irq_preinstall: None, 56 irq_postinstall: None, 57 irq_uninstall: None, 58 get_vblank_counter: None, 59 enable_vblank: None, 60 disable_vblank: None, 61 dev_priv_size: 0, 62 } 63 } 64 } 65 66 #[cfg(not(CONFIG_DRM_LEGACY))] 67 macro_rules! drm_legacy_fields { 68 ( $($field:ident: $val:expr),* $(,)? ) => { 69 bindings::drm_driver { 70 $( $field: $val ),* 71 } 72 } 73 } 74 75 /// A trait implemented by all possible contexts a [`Device`] can be used in. 76 /// 77 /// Setting up a new [`Device`] is a multi-stage process. Each step of the process that a user 78 /// interacts with in Rust has a respective [`DeviceContext`] typestate. For example, 79 /// `Device<T, Registered>` would be a [`Device`] that reached the [`Registered`] [`DeviceContext`]. 80 /// 81 /// Each stage of this process is described below: 82 /// 83 /// ```text 84 /// 1 2 3 85 /// +--------------+ +------------------+ +-----------------------+ 86 /// |Device created| → |Device initialized| → |Registered w/ userspace| 87 /// +--------------+ +------------------+ +-----------------------+ 88 /// (Uninit) (Registered) 89 /// ``` 90 /// 91 /// 1. The [`Device`] is in the [`Uninit`] context and is not guaranteed to be initialized or 92 /// registered with userspace. Only a limited subset of DRM core functionality is available. 93 /// 2. The [`Device`] is guaranteed to be fully initialized, but is not guaranteed to be registered 94 /// with userspace. All DRM core functionality which doesn't interact with userspace is 95 /// available. We currently don't have a context for representing this. 96 /// 3. The [`Device`] is guaranteed to be fully initialized, and is guaranteed to have been 97 /// registered with userspace at some point - thus putting it in the [`Registered`] context. 98 /// 99 /// An important caveat of [`DeviceContext`] which must be kept in mind: when used as a typestate 100 /// for a reference type, it can only guarantee that a [`Device`] reached a particular stage in the 101 /// initialization process _at the time the reference was taken_. No guarantee is made in regards to 102 /// what stage of the process the [`Device`] is currently in. This means for instance that a 103 /// `&Device<T, Uninit>` may actually be registered with userspace, it just wasn't known to be 104 /// registered at the time the reference was taken. 105 pub trait DeviceContext: Sealed + Send + Sync {} 106 107 /// The [`DeviceContext`] of a [`Device`] that was registered with userspace at some point. 108 /// 109 /// This represents a [`Device`] which is guaranteed to have been registered with userspace at 110 /// some point in time. Such a DRM device is guaranteed to have been fully-initialized. 111 /// 112 /// Note: A device in this context is not guaranteed to remain registered with userspace for its 113 /// entire lifetime, as this is impossible to guarantee at compile-time. 114 /// 115 /// # Invariants 116 /// 117 /// A [`Device`] in this [`DeviceContext`] is guaranteed to have been registered with userspace 118 /// at some point in time. 119 pub struct Registered; 120 121 impl Sealed for Registered {} 122 impl DeviceContext for Registered {} 123 124 /// The [`DeviceContext`] of a [`Device`] that may be unregistered and partly uninitialized. 125 /// 126 /// A [`Device`] in this context is only guaranteed to be partly initialized, and may or may not 127 /// be registered with userspace. Thus operations which depend on the [`Device`] being fully 128 /// initialized, or which depend on the [`Device`] being registered with userspace are not 129 /// available through this [`DeviceContext`]. 130 /// 131 /// A [`Device`] in this context can be used to create a 132 /// [`Registration`](drm::driver::Registration). 133 pub struct Uninit; 134 135 impl Sealed for Uninit {} 136 impl DeviceContext for Uninit {} 137 138 /// A [`Device`] which is known at compile-time to be unregistered with userspace. 139 /// 140 /// This type allows performing operations which are only safe to do before userspace registration, 141 /// and can be used to create a [`Registration`](drm::driver::Registration) once the driver is ready 142 /// to register the device with userspace. 143 /// 144 /// Since DRM device initialization must be single-threaded, this object is not thread-safe. 145 /// 146 /// # Invariants 147 /// 148 /// The device in `self.0` is guaranteed to be a newly created [`Device`] that has not yet been 149 /// registered with userspace until this type is dropped. 150 pub struct UnregisteredDevice<T: drm::Driver>(ARef<Device<T, Uninit>>, NotThreadSafe); 151 152 impl<T: drm::Driver> Deref for UnregisteredDevice<T> { 153 type Target = Device<T, Uninit>; 154 155 fn deref(&self) -> &Self::Target { 156 &self.0 157 } 158 } 159 160 impl<T: drm::Driver> UnregisteredDevice<T> { 161 const fn compute_features() -> u32 { 162 let mut features = drm::driver::FEAT_GEM; 163 164 if T::FEAT_RENDER { 165 features |= drm::driver::FEAT_RENDER; 166 } 167 168 features 169 } 170 171 const VTABLE: bindings::drm_driver = drm_legacy_fields! { 172 load: None, 173 open: Some(drm::File::<T::File>::open_callback), 174 postclose: Some(drm::File::<T::File>::postclose_callback), 175 unload: None, 176 release: Some(Device::<T>::release), 177 master_set: None, 178 master_drop: None, 179 debugfs_init: None, 180 181 // Ignore the Uninit DeviceContext below. It is only provided because it is required by the 182 // compiler, and it is not actually used by these functions. 183 gem_create_object: T::Object::<Uninit>::ALLOC_OPS.gem_create_object, 184 prime_handle_to_fd: T::Object::<Uninit>::ALLOC_OPS.prime_handle_to_fd, 185 prime_fd_to_handle: T::Object::<Uninit>::ALLOC_OPS.prime_fd_to_handle, 186 gem_prime_import: T::Object::<Uninit>::ALLOC_OPS.gem_prime_import, 187 gem_prime_import_sg_table: T::Object::<Uninit>::ALLOC_OPS.gem_prime_import_sg_table, 188 dumb_create: T::Object::<Uninit>::ALLOC_OPS.dumb_create, 189 dumb_map_offset: T::Object::<Uninit>::ALLOC_OPS.dumb_map_offset, 190 191 show_fdinfo: None, 192 fbdev_probe: None, 193 194 major: T::INFO.major, 195 minor: T::INFO.minor, 196 patchlevel: T::INFO.patchlevel, 197 name: crate::str::as_char_ptr_in_const_context(T::INFO.name).cast_mut(), 198 desc: crate::str::as_char_ptr_in_const_context(T::INFO.desc).cast_mut(), 199 200 driver_features: Self::compute_features(), 201 ioctls: T::IOCTLS.as_ptr(), 202 num_ioctls: T::IOCTLS.len() as i32, 203 fops: &Self::GEM_FOPS, 204 }; 205 206 const GEM_FOPS: bindings::file_operations = 207 drm::gem::create_fops(crate::module::this_module::<T::OwnerModule>().as_ptr()); 208 209 /// Create a new `UnregisteredDevice` for a `drm::Driver`. 210 /// 211 /// This can be used to create a [`Registration`](kernel::drm::Registration). 212 pub fn new(dev: &device::Device, data: impl PinInit<T::Data, Error>) -> Result<Self> { 213 // `__drm_dev_alloc` uses `kmalloc()` to allocate memory, hence ensure a `kmalloc()` 214 // compatible `Layout`. 215 let layout = Kmalloc::aligned_layout(Layout::new::<Device<T, Uninit>>()); 216 217 // Use a temporary vtable without a `release` callback until `data` is initialized, so 218 // init failure can release the DRM device without dropping uninitialized fields. 219 let alloc_vtable = bindings::drm_driver { 220 release: None, 221 ..Self::VTABLE 222 }; 223 224 // SAFETY: 225 // - `alloc_vtable` reference remains valid until no longer used, 226 // - `dev` is valid by its type invarants, 227 let raw_drm: *mut Device<T, Uninit> = unsafe { 228 bindings::__drm_dev_alloc( 229 dev.as_raw(), 230 &alloc_vtable, 231 layout.size(), 232 mem::offset_of!(Device<T, Uninit>, dev), 233 ) 234 } 235 .cast(); 236 let raw_drm = NonNull::new(from_err_ptr(raw_drm)?).ok_or(ENOMEM)?; 237 238 // SAFETY: `raw_drm` is a valid pointer to `Self`, given that `__drm_dev_alloc` was 239 // successful. 240 let drm_dev = unsafe { Device::into_drm_device(raw_drm) }; 241 242 // SAFETY: `raw_drm` is a valid pointer to `Self`. 243 let raw_data = unsafe { ptr::addr_of_mut!((*raw_drm.as_ptr()).data) }; 244 245 // SAFETY: 246 // - `raw_data` is a valid pointer to uninitialized memory. 247 // - `raw_data` will not move until it is dropped. 248 unsafe { pin_init::raw_try_init(raw_data, data) }.inspect_err(|_| { 249 // SAFETY: `__drm_dev_alloc()` was successful, hence `drm_dev` must be valid and the 250 // refcount must be non-zero. 251 unsafe { bindings::drm_dev_put(drm_dev) }; 252 })?; 253 254 // SAFETY: `drm_dev` is still private to this function. 255 unsafe { (*drm_dev).driver = const { &Self::VTABLE } }; 256 257 // SAFETY: The reference count is one, and now we take ownership of that reference as a 258 // `drm::Device`. 259 // INVARIANT: We just created the device above, but have yet to call `drm_dev_register`. 260 // `Self` cannot be copied or sent to another thread - ensuring that `drm_dev_register` 261 // won't be called during its lifetime and that the device is unregistered. 262 Ok(Self(unsafe { ARef::from_raw(raw_drm) }, NotThreadSafe)) 263 } 264 } 265 266 /// A typed DRM device with a specific [`drm::Driver`] implementation and [`DeviceContext`]. 267 /// 268 /// Since DRM devices can be used before being fully initialized and registered with userspace, `C` 269 /// represents the furthest [`DeviceContext`] we can guarantee that this [`Device`] has reached. 270 /// 271 /// Keep in mind: this means that an unregistered device can still have the registration state 272 /// [`Registered`] as long as it was registered with userspace once in the past, and that the 273 /// behavior of such a device is still well-defined. Additionally, a device with the registration 274 /// state [`Uninit`] simply does not have a guaranteed registration state at compile time, and could 275 /// be either registered or unregistered. Since there is no way to guarantee a long-lived reference 276 /// to an unregistered device would remain unregistered, we do not provide a [`DeviceContext`] for 277 /// this. 278 /// 279 /// # Invariants 280 /// 281 /// * `self.dev` is a valid instance of a `struct device`. 282 /// * The data layout of `Self` remains the same across all implementations of `C`. 283 /// * Any invariants for `C` also apply. 284 #[repr(C)] 285 pub struct Device<T: drm::Driver, C: DeviceContext = Registered> { 286 dev: Opaque<bindings::drm_device>, 287 data: T::Data, 288 _ctx: PhantomData<C>, 289 } 290 291 impl<T: drm::Driver, C: DeviceContext> Device<T, C> { 292 pub(crate) fn as_raw(&self) -> *mut bindings::drm_device { 293 self.dev.get() 294 } 295 296 /// # Safety 297 /// 298 /// `ptr` must be a valid pointer to a `struct device` embedded in `Self`. 299 unsafe fn from_drm_device(ptr: *const bindings::drm_device) -> *mut Self { 300 // SAFETY: By the safety requirements of this function `ptr` is a valid pointer to a 301 // `struct drm_device` embedded in `Self`. 302 unsafe { crate::container_of!(Opaque::cast_from(ptr), Self, dev) }.cast_mut() 303 } 304 305 /// # Safety 306 /// 307 /// `ptr` must be a valid pointer to `Self`. 308 unsafe fn into_drm_device(ptr: NonNull<Self>) -> *mut bindings::drm_device { 309 // SAFETY: By the safety requirements of this function, `ptr` is a valid pointer to `Self`. 310 unsafe { &raw mut (*ptr.as_ptr()).dev }.cast() 311 } 312 313 /// Not intended to be called externally, except via declare_drm_ioctls!() 314 /// 315 /// # Safety 316 /// 317 /// * Callers must ensure that `ptr` is valid, non-null, and has a non-zero reference count, 318 /// i.e. it must be ensured that the reference count of the C `struct drm_device` `ptr` points 319 /// to can't drop to zero, for the duration of this function call and the entire duration when 320 /// the returned reference exists. 321 /// * Additionally, callers must ensure that the `struct device`, `ptr` is pointing to, is 322 /// embedded in `Self`. 323 /// * Callers promise that any type invariants of `C` will be upheld. 324 #[doc(hidden)] 325 pub unsafe fn from_raw<'a>(ptr: *const bindings::drm_device) -> &'a Self { 326 // SAFETY: By the safety requirements of this function `ptr` is a valid pointer to a 327 // `struct drm_device` embedded in `Self`. 328 let ptr = unsafe { Self::from_drm_device(ptr) }; 329 330 // SAFETY: `ptr` is valid by the safety requirements of this function. 331 unsafe { &*ptr.cast() } 332 } 333 334 extern "C" fn release(ptr: *mut bindings::drm_device) { 335 // SAFETY: `ptr` is a valid pointer to a `struct drm_device` and embedded in `Self`. 336 let this = unsafe { Self::from_drm_device(ptr) }; 337 338 // SAFETY: 339 // - When `release` runs it is guaranteed that there is no further access to `this`. 340 // - `this` is valid for dropping. 341 unsafe { core::ptr::drop_in_place(this) }; 342 } 343 344 /// Change the [`DeviceContext`] for a [`Device`]. 345 /// 346 /// # Safety 347 /// 348 /// The caller promises that `self` fulfills all of the guarantees provided by the given 349 /// [`DeviceContext`]. 350 pub(crate) unsafe fn assume_ctx<NewCtx: DeviceContext>(&self) -> &Device<T, NewCtx> { 351 // SAFETY: The data layout is identical via our type invariants. 352 unsafe { mem::transmute(self) } 353 } 354 } 355 356 impl<T: drm::Driver, C: DeviceContext> Deref for Device<T, C> { 357 type Target = T::Data; 358 359 fn deref(&self) -> &Self::Target { 360 &self.data 361 } 362 } 363 364 // SAFETY: DRM device objects are always reference counted and the get/put functions 365 // satisfy the requirements. 366 unsafe impl<T: drm::Driver, C: DeviceContext> AlwaysRefCounted for Device<T, C> { 367 fn inc_ref(&self) { 368 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. 369 unsafe { bindings::drm_dev_get(self.as_raw()) }; 370 } 371 372 unsafe fn dec_ref(obj: NonNull<Self>) { 373 // SAFETY: `obj` is a valid pointer to `Self`. 374 let drm_dev = unsafe { Self::into_drm_device(obj) }; 375 376 // SAFETY: The safety requirements guarantee that the refcount is non-zero. 377 unsafe { bindings::drm_dev_put(drm_dev) }; 378 } 379 } 380 381 impl<T: drm::Driver, C: DeviceContext> AsRef<device::Device> for Device<T, C> { 382 fn as_ref(&self) -> &device::Device { 383 // SAFETY: `bindings::drm_device::dev` is valid as long as the DRM device itself is valid, 384 // which is guaranteed by the type invariant. 385 unsafe { device::Device::from_raw((*self.as_raw()).dev) } 386 } 387 } 388 389 // SAFETY: A `drm::Device` can be released from any thread. 390 unsafe impl<T: drm::Driver, C: DeviceContext> Send for Device<T, C> {} 391 392 // SAFETY: A `drm::Device` can be shared among threads because all immutable methods are protected 393 // by the synchronization in `struct drm_device`. 394 unsafe impl<T: drm::Driver, C: DeviceContext> Sync for Device<T, C> {} 395 396 impl<T, C, const ID: u64> WorkItem<ID> for Device<T, C> 397 where 398 T: drm::Driver, 399 T::Data: WorkItem<ID, Pointer = ARef<Self>>, 400 T::Data: HasWork<Self, ID>, 401 C: DeviceContext, 402 { 403 type Pointer = ARef<Self>; 404 405 fn run(ptr: ARef<Self>) { 406 T::Data::run(ptr); 407 } 408 } 409 410 // SAFETY: 411 // 412 // - `raw_get_work` and `work_container_of` return valid pointers by relying on 413 // `T::Data::raw_get_work` and `container_of`. In particular, `T::Data` is 414 // stored inline in `drm::Device`, so the `container_of` call is valid. 415 // 416 // - The two methods are true inverses of each other: given `ptr: *mut 417 // Device<T, C>`, `raw_get_work` will return a `*mut Work<Device<T, C>, ID>` through 418 // `T::Data::raw_get_work` and given a `ptr: *mut Work<Device<T, C>, ID>`, 419 // `work_container_of` will return a `*mut Device<T, C>` through `container_of`. 420 unsafe impl<T, C, const ID: u64> HasWork<Self, ID> for Device<T, C> 421 where 422 T: drm::Driver, 423 T::Data: HasWork<Self, ID>, 424 C: DeviceContext, 425 { 426 unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<Self, ID> { 427 // SAFETY: The caller promises that `ptr` points to a valid `Device<T, C>`. 428 let data_ptr = unsafe { &raw mut (*ptr).data }; 429 430 // SAFETY: `data_ptr` is a valid pointer to `T::Data`. 431 unsafe { T::Data::raw_get_work(data_ptr) } 432 } 433 434 unsafe fn work_container_of(ptr: *mut Work<Self, ID>) -> *mut Self { 435 // SAFETY: The caller promises that `ptr` points at a `Work` field in 436 // `T::Data`. 437 let data_ptr = unsafe { T::Data::work_container_of(ptr) }; 438 439 // SAFETY: `T::Data` is stored as the `data` field in `Device<T, C>`. 440 unsafe { crate::container_of!(data_ptr, Self, data) } 441 } 442 } 443 444 // SAFETY: Our `HasWork<T, ID>` implementation returns a `work_struct` that is 445 // stored in the `work` field of a `delayed_work` with the same access rules as 446 // the `work_struct` owing to the bound on `T::Data: HasDelayedWork<Device<T, C>, 447 // ID>`, which requires that `T::Data::raw_get_work` return a `work_struct` that 448 // is inside a `delayed_work`. 449 unsafe impl<T, C, const ID: u64> HasDelayedWork<Self, ID> for Device<T, C> 450 where 451 T: drm::Driver, 452 T::Data: HasDelayedWork<Self, ID>, 453 C: DeviceContext, 454 { 455 } 456