1 // SPDX-License-Identifier: GPL-2.0 2 3 //! DRM GEM shmem helper objects 4 //! 5 //! C header: [`include/linux/drm/drm_gem_shmem_helper.h`](srctree/include/drm/drm_gem_shmem_helper.h) 6 7 // TODO: 8 // - There are a number of spots here that manually acquire/release the DMA reservation lock using 9 // dma_resv_(un)lock(). In the future we should add support for ww mutex, expose a method to 10 // acquire a reference to the WwMutex, and then use that directly instead of the C functions here. 11 12 use crate::{ 13 container_of, 14 device::{ 15 self, 16 Bound, // 17 }, 18 devres::*, 19 drm::{ 20 driver, 21 gem, 22 private::Sealed, 23 Device, // 24 }, 25 error::{ 26 from_err_ptr, 27 to_result, // 28 }, 29 io::{ 30 IoBase, 31 Region, 32 SysMem, 33 SysMemBackend, // 34 }, 35 prelude::*, 36 scatterlist, 37 sync::{ 38 aref::ARef, 39 new_mutex, 40 Mutex, 41 SetOnce, // 42 }, 43 types::{ 44 NotThreadSafe, 45 Opaque, // 46 }, 47 }; 48 use core::{ 49 ffi::c_void, 50 mem::{ 51 ManuallyDrop, 52 MaybeUninit, // 53 }, 54 ops::{ 55 Deref, 56 DerefMut, // 57 }, 58 ptr::{ 59 self, 60 NonNull, // 61 }, 62 }; 63 use gem::{ 64 BaseObject, 65 BaseObjectPrivate, 66 DriverObject, 67 IntoGEMObject, // 68 }; 69 70 /// A struct for controlling the creation of shmem-backed GEM objects. 71 /// 72 /// This is used with [`Object::new()`] to control various properties that can only be set when 73 /// initially creating a shmem-backed GEM object. 74 pub struct ObjectConfig<'a, T: DriverObject> { 75 /// Whether to set the write-combine map flag. 76 pub map_wc: bool, 77 78 /// Reuse the DMA reservation from another GEM object. 79 /// 80 /// The newly created [`Object`] will hold an owned refcount to `parent_resv_obj` if specified. 81 pub parent_resv_obj: Option<&'a Object<T>>, 82 } 83 84 impl<'a, T: DriverObject> Default for ObjectConfig<'a, T> { 85 #[inline(always)] 86 fn default() -> Self { 87 Self { 88 map_wc: false, 89 parent_resv_obj: None, 90 } 91 } 92 } 93 94 /// A shmem-backed GEM object. 95 /// 96 /// # Invariants 97 /// 98 /// - `obj` contains a valid initialized `struct drm_gem_shmem_object` for the lifetime of this 99 /// object. 100 #[repr(C)] 101 #[pin_data] 102 pub struct Object<T: DriverObject> { 103 #[pin] 104 obj: Opaque<bindings::drm_gem_shmem_object>, 105 /// Parent object that owns this object's DMA reservation object. 106 parent_resv_obj: Option<ARef<Object<T>>>, 107 /// Devres object for unmapping any SGTable on driver-unbind. 108 sgt_res: ManuallyDrop<SetOnce<Devres<SGTableMap<T>>>>, 109 #[pin] 110 /// Lock for protecting initialization of `sgt_res`. 111 sgt_lock: Mutex<()>, 112 #[pin] 113 inner: T, 114 } 115 116 super::impl_aref_for_gem_obj! { 117 impl<T> for Object<T> 118 where 119 T: DriverObject 120 } 121 122 // SAFETY: All GEM objects are thread-safe. 123 unsafe impl<T: DriverObject> Send for Object<T> {} 124 125 // SAFETY: All GEM objects are thread-safe. 126 unsafe impl<T: DriverObject> Sync for Object<T> {} 127 128 impl<T: DriverObject> Object<T> { 129 /// `drm_gem_object_funcs` vtable suitable for GEM shmem objects. 130 const VTABLE: bindings::drm_gem_object_funcs = bindings::drm_gem_object_funcs { 131 free: Some(Self::free_callback), 132 open: Some(super::open_callback::<T>), 133 close: Some(super::close_callback::<T>), 134 print_info: Some(bindings::drm_gem_shmem_object_print_info), 135 pin: Some(bindings::drm_gem_shmem_object_pin), 136 unpin: Some(bindings::drm_gem_shmem_object_unpin), 137 get_sg_table: Some(bindings::drm_gem_shmem_object_get_sg_table), 138 vmap: Some(bindings::drm_gem_shmem_object_vmap), 139 vunmap: Some(bindings::drm_gem_shmem_object_vunmap), 140 mmap: Some(bindings::drm_gem_shmem_object_mmap), 141 #[allow(unused_unsafe, reason = "Safe since Rust 1.82.0")] 142 // SAFETY: `drm_gem_shmem_vm_ops` is a valid, static const on the C side. 143 vm_ops: unsafe { &raw const bindings::drm_gem_shmem_vm_ops }, 144 ..pin_init::zeroed() 145 }; 146 147 /// Return a raw pointer to the embedded drm_gem_shmem_object. 148 fn as_raw_shmem(&self) -> *mut bindings::drm_gem_shmem_object { 149 self.obj.get() 150 } 151 152 /// Returns the `Device` that owns this GEM object. 153 pub fn dev(&self) -> &Device<T::Driver> { 154 // SAFETY: `dev` will have been initialized in `Self::new()` by `drm_gem_shmem_init()`. 155 unsafe { Device::from_raw((*self.as_raw()).dev) } 156 } 157 158 extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) { 159 // SAFETY: 160 // - DRM always passes a valid gem object here 161 // - We used drm_gem_shmem_create() in our create_gem_object callback, so we know that 162 // `obj` is contained within a drm_gem_shmem_object 163 let base = unsafe { container_of!(obj, bindings::drm_gem_shmem_object, base) }; 164 165 // SAFETY: 166 // - We verified above that `obj` is valid, which makes `this` valid 167 // - This function is set in AllocOps, so we know that `this` is contained within an 168 // `Object<T>` 169 let this = unsafe { container_of!(Opaque::cast_from(base), Self, obj) }.cast_mut(); 170 171 // We need to drop `sgt_res` first, since doing so requires that the GEM object is still 172 // alive. 173 // SAFETY: 174 // - We verified above that `this` is valid. 175 // - We are in free_callback, guaranteeing we have exclusive access to `this` and that 176 // `sgt_res` will not be used after dropping it here. 177 unsafe { ManuallyDrop::drop(&mut (*this).sgt_res) }; 178 179 // SAFETY: 180 // - We're in free_callback - so this function is safe to call. 181 // - We won't be using the gem resources on `this` after this call. 182 unsafe { bindings::drm_gem_shmem_release(base) }; 183 184 // SAFETY: We're recovering the Kbox<> we created in gem_create_object() 185 let _ = unsafe { KBox::from_raw(this) }; 186 } 187 188 /// Attempt to create a vmap from the gem object, and confirm the size of said vmap. 189 fn make_vmap<'a, R, const SIZE: usize>(&'a self) -> Result<VMap<T, R, SIZE>> 190 where 191 R: Deref<Target = Self> + From<&'a Self>, 192 { 193 // INVARIANT: We check here that the gem object is at least as large as `SIZE`. 194 if self.size() < SIZE { 195 return Err(ENOSPC); 196 } 197 198 let mut map: MaybeUninit<bindings::iosys_map> = MaybeUninit::uninit(); 199 let guard = DmaResvGuard::new(self); 200 201 // SAFETY: `drm_gem_shmem_vmap()` can be called with the DMA reservation lock held. 202 to_result(unsafe { 203 bindings::drm_gem_shmem_vmap_locked(self.as_raw_shmem(), map.as_mut_ptr()) 204 })?; 205 206 // Drop the guard explicitly here, since we may need to call `raw_vunmap()` (which 207 // re-acquires the lock). 208 drop(guard); 209 210 // SAFETY: The call to `drm_gem_shmem_vmap_locked()` succeeded above, so we are guaranteed 211 // that map is properly initialized. 212 let map = unsafe { map.assume_init() }; 213 214 // XXX: We don't currently support iomem allocations 215 if map.is_iomem { 216 // SAFETY: The vmap operation above succeeded, guaranteeing that `map` points to a valid 217 // memory mapping. 218 unsafe { self.raw_vunmap(map) }; 219 220 Err(ENOTSUPP) 221 } else { 222 Ok(VMap { 223 // INVARIANT: `addr` remains valid for as long as `owner` does, which extends to the 224 // lifetime of `VMap` itself. 225 // SAFETY: We checked that this is not an iomem allocation, making it safe to read 226 // vaddr. 227 addr: unsafe { map.__bindgen_anon_1.vaddr }, 228 owner: self.into(), 229 }) 230 } 231 } 232 233 /// Unmap a vmap from the gem object. 234 /// 235 /// # Safety 236 /// 237 /// - The caller promises that `map` is a valid vmap on this gem object. 238 /// - The caller promises that the memory pointed to by map will no longer be accesed through 239 /// this instance. 240 unsafe fn raw_vunmap(&self, mut map: bindings::iosys_map) { 241 let _guard = DmaResvGuard::new(self); 242 243 // SAFETY: 244 // - This function is safe to call with the DMA reservation lock held. 245 // - The caller promises that `map` is a valid vmap on this gem object. 246 unsafe { bindings::drm_gem_shmem_vunmap_locked(self.as_raw_shmem(), &mut map) }; 247 } 248 249 /// Creates and returns a virtual kernel memory mapping for this object. 250 #[inline] 251 pub fn vmap<const SIZE: usize>(&self) -> Result<VMapRef<'_, T, SIZE>> { 252 self.make_vmap() 253 } 254 255 /// Creates (if necessary) and returns an immutable reference to a scatter-gather table of DMA 256 /// pages for this object. 257 /// 258 /// This will pin the object in memory. It is expected that `dev` should be a pointer to the 259 /// same [`device::Device`] which `self` belongs to, otherwise this function will return 260 /// `Err(EINVAL)`. 261 pub fn sg_table<'a>( 262 &'a self, 263 dev: &'a device::Device<Bound>, 264 ) -> Result<&'a scatterlist::SGTable> { 265 let parent = self.dev().as_ref(); 266 if dev.as_raw() != parent.as_ref().as_raw() { 267 return Err(EINVAL); 268 } 269 270 let sgt_res = 'out: { 271 // Fast path: sgt_res is already initialized 272 if let Some(sgt_res) = self.sgt_res.as_ref() { 273 break 'out sgt_res; 274 } 275 276 // Slow path: Grab the lock and see if we need to initialize sgt_res. 277 let _guard = self.sgt_lock.lock(); 278 279 // If someone initialized it while we were waiting, we can exit early. 280 if let Some(sgt_res) = self.sgt_res.as_ref() { 281 break 'out sgt_res; 282 } 283 284 // If not, finish initializing and return. `populate()` cannot return false, as 285 // `sgt_res` must be unpopulated, and we must hold `sgt_lock` to reach this point. 286 self.sgt_res 287 .populate(Devres::new(dev, SGTableMap::new(self))?); 288 289 // SAFETY: We just populated sgt_res above. 290 unsafe { self.sgt_res.as_ref().unwrap_unchecked() } 291 }; 292 293 Ok(sgt_res.access(dev)?) 294 } 295 296 /// Create a new shmem-backed DRM object of the given size. 297 /// 298 /// Additional config options can be specified using `config`. 299 pub fn new( 300 dev: &Device<T::Driver>, 301 size: usize, 302 config: ObjectConfig<'_, T>, 303 args: T::Args, 304 ) -> Result<ARef<Self>> { 305 let new: Pin<KBox<Self>> = KBox::try_pin_init( 306 try_pin_init!(Self { 307 obj <- Opaque::init_zeroed(), 308 parent_resv_obj: config.parent_resv_obj.map(|p| p.into()), 309 sgt_res: ManuallyDrop::new(SetOnce::new()), 310 sgt_lock <- new_mutex!(()), 311 inner <- T::new(dev, size, args), 312 }), 313 GFP_KERNEL, 314 )?; 315 316 // SAFETY: `obj.as_raw()` is guaranteed to be valid by the initialization above. 317 unsafe { (*new.as_raw()).funcs = &Self::VTABLE }; 318 319 // SAFETY: The arguments are all valid via the type invariants. 320 to_result(unsafe { bindings::drm_gem_shmem_init(dev.as_raw(), new.as_raw_shmem(), size) })?; 321 322 // SAFETY: We never move out of `self`. 323 let new = KBox::into_raw(unsafe { Pin::into_inner_unchecked(new) }); 324 325 // SAFETY: We're taking over the owned refcount from `drm_gem_shmem_init`. 326 let obj = unsafe { ARef::from_raw(NonNull::new_unchecked(new)) }; 327 328 // Start filling out values from `config` 329 if let Some(parent_resv) = config.parent_resv_obj { 330 // SAFETY: We have yet to expose the new gem object outside of this function, so it is 331 // safe to modify this field. 332 unsafe { (*obj.obj.get()).base.resv = parent_resv.raw_dma_resv() }; 333 } 334 335 // SAFETY: We have yet to expose this object outside of this function, so we're guaranteed 336 // to have exclusive access - thus making this safe to hold a mutable reference to. 337 let shmem = unsafe { &mut *obj.as_raw_shmem() }; 338 shmem.set_map_wc(config.map_wc); 339 340 Ok(obj) 341 } 342 343 /// Creates and returns an owned reference to a virtual kernel memory mapping for this object. 344 #[inline] 345 pub fn owned_vmap<const SIZE: usize>(&self) -> Result<VMapOwned<T, SIZE>> { 346 self.make_vmap() 347 } 348 } 349 350 impl<T: DriverObject> Deref for Object<T> { 351 type Target = T; 352 353 fn deref(&self) -> &Self::Target { 354 &self.inner 355 } 356 } 357 358 impl<T: DriverObject> DerefMut for Object<T> { 359 fn deref_mut(&mut self) -> &mut Self::Target { 360 &mut self.inner 361 } 362 } 363 364 impl<T: DriverObject> Sealed for Object<T> {} 365 366 impl<T: DriverObject> gem::IntoGEMObject for Object<T> { 367 fn as_raw(&self) -> *mut bindings::drm_gem_object { 368 // SAFETY: 369 // - Our immutable reference is proof that this is safe to dereference. 370 // - `obj` is always a valid drm_gem_shmem_object via our type invariants. 371 unsafe { &raw mut (*self.obj.get()).base } 372 } 373 374 unsafe fn from_raw<'a>(obj: *mut bindings::drm_gem_object) -> &'a Self { 375 // SAFETY: The safety contract of from_gem_obj() guarantees that `obj` is contained within 376 // `Self` 377 unsafe { 378 let obj = Opaque::cast_from(container_of!(obj, bindings::drm_gem_shmem_object, base)); 379 380 &*container_of!(obj, Self, obj) 381 } 382 } 383 } 384 385 impl<T: DriverObject> driver::AllocImpl for Object<T> { 386 type Driver = T::Driver; 387 388 const ALLOC_OPS: driver::AllocOps = driver::AllocOps { 389 gem_create_object: None, 390 prime_handle_to_fd: None, 391 prime_fd_to_handle: None, 392 gem_prime_import: None, 393 gem_prime_import_sg_table: Some(bindings::drm_gem_shmem_prime_import_sg_table), 394 dumb_create: Some(bindings::drm_gem_shmem_dumb_create), 395 dumb_map_offset: None, 396 }; 397 } 398 399 /// Private helper-type for holding the `dma_resv` object for a GEM shmem object. 400 /// 401 /// When this is dropped, the `dma_resv` lock is dropped as well. 402 /// 403 // TODO: This should be replace with a WwMutex equivalent once we have such bindings in the kernel. 404 struct DmaResvGuard<'a, T: DriverObject>(&'a Object<T>, NotThreadSafe); 405 406 impl<'a, T: DriverObject> DmaResvGuard<'a, T> { 407 #[inline] 408 fn new(obj: &'a Object<T>) -> Self { 409 // SAFETY: This lock is initialized throughout the lifetime of `object`. 410 unsafe { bindings::dma_resv_lock(obj.raw_dma_resv(), ptr::null_mut()) }; 411 412 Self(obj, NotThreadSafe) 413 } 414 } 415 416 impl<'a, T: DriverObject> Drop for DmaResvGuard<'a, T> { 417 #[inline] 418 fn drop(&mut self) { 419 // SAFETY: We are releasing the lock grabbed during the creation of this object. 420 unsafe { bindings::dma_resv_unlock(self.0.raw_dma_resv()) }; 421 } 422 } 423 424 /// A reference to a virtual mapping for an shmem-based GEM object in kernel address space. 425 /// 426 /// # Invariants 427 /// 428 /// - The size of `owner` is >= SIZE. 429 /// - The memory pointed to by `addr` remains valid at least until this object is dropped. 430 pub struct VMap<D, R, const SIZE: usize = 0> 431 where 432 D: DriverObject, 433 R: Deref<Target = Object<D>>, 434 { 435 addr: *mut c_void, 436 owner: R, 437 } 438 439 /// An alias type for a reference to a shmem-based GEM object's VMap. 440 pub type VMapRef<'a, D, const SIZE: usize = 0> = VMap<D, &'a Object<D>, SIZE>; 441 442 /// An alias type for an owned reference to a shmem-based GEM object's VMap. 443 pub type VMapOwned<D, const SIZE: usize = 0> = VMap<D, ARef<Object<D>>, SIZE>; 444 445 impl<D, R, const SIZE: usize> VMap<D, R, SIZE> 446 where 447 D: DriverObject, 448 R: Deref<Target = Object<D>>, 449 { 450 /// Borrows a reference to the object that owns this virtual mapping. 451 #[inline] 452 pub fn owner(&self) -> &Object<D> { 453 &self.owner 454 } 455 } 456 457 impl<'a, D, R, const SIZE: usize> IoBase<'a> for &'a VMap<D, R, SIZE> 458 where 459 D: DriverObject, 460 R: Deref<Target = Object<D>>, 461 { 462 type Backend = SysMemBackend; 463 type Target = Region<SIZE>; 464 465 #[inline] 466 fn as_view(self) -> SysMem<'a, Region<SIZE>> { 467 let ptr = Region::ptr_from_raw_parts_mut(self.addr.cast(), self.owner.size()); 468 469 // SAFETY: Per type invariants of `VMap`: 470 // - `addr .. addr + owner.size()` is a valid kernel accessible memory region. 471 // - `addr` is page-aligned, which satisfies `Region`'s 4-byte alignment requirement. 472 // - The memory remains valid until this `VMap` is dropped; since `self` is `&'a VMap`, 473 // the borrow prevents the `VMap` from being dropped for the lifetime `'a`. 474 unsafe { SysMem::new(ptr) } 475 } 476 } 477 478 impl<D, R, const SIZE: usize> Drop for VMap<D, R, SIZE> 479 where 480 D: DriverObject, 481 R: Deref<Target = Object<D>>, 482 { 483 #[inline] 484 fn drop(&mut self) { 485 // SAFETY: 486 // - Our existence is proof that this map was previously created using self.owner. 487 // - Since we are in Drop, we are guaranteed that no one will access the memory 488 // through this mapping after calling this. 489 unsafe { 490 self.owner.raw_vunmap(bindings::iosys_map { 491 is_iomem: false, 492 __bindgen_anon_1: bindings::iosys_map__bindgen_ty_1 { vaddr: self.addr }, 493 }) 494 }; 495 } 496 } 497 498 // SAFETY: `addr` points to a valid memory address for as long as `owner` exists, meaning that so 499 // long as `owner` is `Send` so is `VMap`. 500 unsafe impl<D, R, const SIZE: usize> Send for VMap<D, R, SIZE> 501 where 502 D: DriverObject, 503 R: Deref<Target = Object<D>> + Send, 504 { 505 } 506 507 // SAFETY: `addr` points to a valid memory address for as long as `owner` exists, meaning that so 508 // long as `owner` is `Sync` so is `VMap`. 509 unsafe impl<D, R, const SIZE: usize> Sync for VMap<D, R, SIZE> 510 where 511 D: DriverObject, 512 R: Deref<Target = Object<D>> + Sync, 513 { 514 } 515 516 /// A reference to a GEM object that is known to have a mapped [`SGTable`]. 517 /// 518 /// This is used by the Rust bindings with [`Devres`] in order to ensure that mappings for SGTables 519 /// on GEM shmem objects are revoked on driver-unbind. 520 /// 521 /// # Invariants 522 /// 523 /// - `self.obj` always points to a valid GEM object. 524 /// - This object is proof that `self.obj.owner.sgt_res` has an initialized and valid pointer to an 525 /// [`SGTable`]. 526 /// 527 /// [`SGTable`]: scatterlist::SGTable 528 pub struct SGTableMap<T: DriverObject> { 529 obj: NonNull<Object<T>>, 530 } 531 532 impl<T: DriverObject> Deref for SGTableMap<T> { 533 type Target = scatterlist::SGTable; 534 535 fn deref(&self) -> &Self::Target { 536 // SAFETY: 537 // - The NonNull is guaranteed to be valid via our type invariants. 538 // - The sgt field is guaranteed to be initialized and valid via our type invariants. 539 unsafe { scatterlist::SGTable::from_raw((*self.obj.as_ref().as_raw_shmem()).sgt) } 540 } 541 } 542 543 impl<T: DriverObject> Drop for SGTableMap<T> { 544 fn drop(&mut self) { 545 // SAFETY: `obj` is always valid via our type invariants 546 let obj = unsafe { self.obj.as_ref() }; 547 let _lock = DmaResvGuard::new(obj); 548 549 // SAFETY: We acquired the lock needed for calling this function above 550 unsafe { bindings::__drm_gem_shmem_free_sgt_locked(obj.as_raw_shmem()) }; 551 } 552 } 553 554 impl<T: DriverObject> SGTableMap<T> { 555 fn new(obj: &Object<T>) -> impl Init<Self, Error> { 556 // INVARIANT: 557 // - We call drm_gem_shmem_get_pages_sgt below and check whether or not it succeeds, 558 // fulfilling the invariant of SGTableMap that the object's `sgt` field is initialized. 559 // SAFETY: 560 // - `obj` is fully initialized, making this function safe to call. 561 from_err_ptr(unsafe { bindings::drm_gem_shmem_get_pages_sgt(obj.as_raw_shmem()) })?; 562 563 Ok(Self { obj: obj.into() }) 564 } 565 } 566 567 // SAFETY: The NonNull in SGTableMap is guaranteed valid by our type invariants, and the GEM object 568 // it points to is guaranteed to be thread-safe. 569 unsafe impl<T: DriverObject> Send for SGTableMap<T> {} 570 // SAFETY: The NonNull in SGTableMap is guaranteed valid by our type invariants, and the GEM object 571 // it points to is guaranteed to be thread-safe. 572 unsafe impl<T: DriverObject> Sync for SGTableMap<T> {} 573 574 #[kunit_tests(rust_drm_gem_shmem)] 575 mod tests { 576 use super::*; 577 use crate::{ 578 drm::{ 579 self, 580 UnregisteredDevice, // 581 }, 582 faux, 583 io::Io, 584 page::PAGE_SIZE, // 585 }; 586 587 // The bare minimum needed to create a fake drm driver for kunit 588 589 #[pin_data] 590 struct KunitData {} 591 struct KunitDriver; 592 struct KunitFile; 593 #[pin_data] 594 struct KunitObject {} 595 596 const INFO: drm::DriverInfo = drm::DriverInfo { 597 major: 0, 598 minor: 0, 599 patchlevel: 0, 600 name: c"kunit", 601 desc: c"Kunit", 602 }; 603 604 impl drm::file::DriverFile for KunitFile { 605 type Driver = KunitDriver; 606 607 fn open(_dev: &drm::Device<KunitDriver>) -> Result<Pin<KBox<Self>>> { 608 Ok(KBox::new(Self, GFP_KERNEL)?.into()) 609 } 610 } 611 612 impl gem::DriverObject for KunitObject { 613 type Driver = KunitDriver; 614 type Args = (); 615 616 fn new( 617 _dev: &drm::Device<KunitDriver>, 618 _size: usize, 619 _args: Self::Args, 620 ) -> impl PinInit<Self, Error> { 621 try_pin_init!(KunitObject {}) 622 } 623 } 624 625 #[vtable] 626 impl drm::Driver for KunitDriver { 627 type Data = KunitData; 628 type RegistrationData<'a> = (); 629 type File = KunitFile; 630 type Object = Object<KunitObject>; 631 type ParentDevice<Ctx: device::DeviceContext> = faux::Device<Ctx>; 632 633 const INFO: drm::DriverInfo = INFO; 634 const IOCTLS: &'static [drm::ioctl::DrmIoctlDescriptor] = &[]; 635 } 636 637 fn create_drm_dev() -> Result<(faux::Registration, UnregisteredDevice<KunitDriver>)> { 638 // Create a faux DRM device so we can test gem object creation. 639 let data = try_pin_init!(KunitData {}); 640 let reg = faux::Registration::new(c"Kunit", None)?; 641 let fdev = reg.as_ref(); 642 let drm = UnregisteredDevice::new(fdev, data)?; 643 644 Ok((reg, drm)) 645 } 646 647 #[test] 648 fn compile_time_vmap_sizes() -> Result { 649 let (_dev, drm) = create_drm_dev()?; 650 651 let obj = Object::<KunitObject>::new(&drm, PAGE_SIZE, ObjectConfig::default(), ())?; 652 653 // Try creating a normal vmap 654 obj.vmap::<PAGE_SIZE>()?; 655 656 // Try creating a vmap that's smaller then the size we specified 657 let vmap = obj.vmap::<{ PAGE_SIZE - 100 }>()?; 658 659 // Verify the owner matches 660 assert!(ptr::eq(vmap.owner(), obj.deref())); 661 662 // Verify the size matches the actual object size 663 assert_eq!(vmap.size(), PAGE_SIZE); 664 665 // Make sure creating a vmap that's too large fails 666 assert!(obj.vmap::<{ PAGE_SIZE + 200 }>().is_err()); 667 668 Ok(()) 669 } 670 671 #[test] 672 fn vmap_io() -> Result { 673 let (_dev, drm) = create_drm_dev()?; 674 675 let obj = Object::<KunitObject>::new(&drm, PAGE_SIZE, ObjectConfig::default(), ())?; 676 677 let vmap = obj.vmap::<PAGE_SIZE>()?; 678 679 vmap.write8(0xDE, 0x0); 680 assert_eq!(vmap.read8(0x0), 0xDE); 681 vmap.write32(0xFEDCBA98, 0x20); 682 683 assert_eq!(vmap.read32(0x20), 0xFEDCBA98); 684 685 // Ensure the ordering in memory is correct 686 let expected = 0xFEDCBA98_u32.to_ne_bytes().into_iter(); 687 for (offset, expected) in (0x20..=0x23).zip(expected) { 688 assert_eq!(vmap.try_read8(offset).unwrap(), expected); 689 } 690 691 Ok(()) 692 } 693 694 // TODO: I would love to actually test the success paths of sg_table(), but that would require 695 // also implementing dummy dma_ops so that trying to create a mapping doesn't explode. So, leave 696 // that for someone else. 697 698 // Ensures that passing the wrong device to sg_table() fails as we expect, and also ensure it 699 // skips initializing `sgt_res` since we could otherwise create `sgt_res` with the wrong device 700 // bound to it. 701 #[test] 702 fn fail_sg_table_on_wrong_dev() -> Result { 703 let (_dev, drm) = create_drm_dev()?; 704 let reg = faux::Registration::new(c"EvilKunit", None)?; 705 let wrong_dev = reg.as_ref(); 706 707 let obj = Object::<KunitObject>::new(&drm, PAGE_SIZE, ObjectConfig::default(), ())?; 708 709 assert_eq!(obj.sg_table(wrong_dev.as_ref()).err().unwrap(), EINVAL); 710 711 // If sgt_res was not initialized mistakenly with the wrong device, this should still fail. 712 assert_eq!(obj.sg_table(wrong_dev.as_ref()).err().unwrap(), EINVAL); 713 714 // TODO: Someday, we should test that creating an sg_table here still succeeds. 715 716 Ok(()) 717 } 718 } 719