linux/rust/kernel/drm/gem/mod.rs
Linus Torvalds ec7714e494 Rust changes for v6.16
Toolchain and infrastructure:
 
  - KUnit '#[test]'s:
 
    - Support KUnit-mapped 'assert!' macros.
 
      The support that landed last cycle was very basic, and the
      'assert!' macros panicked since they were the standard library
      ones. Now, they are mapped to the KUnit ones in a similar way to
      how is done for doctests, reusing the infrastructure there.
 
      With this, a failing test like:
 
          #[test]
          fn my_first_test() {
              assert_eq!(42, 43);
          }
 
      will report:
 
          # my_first_test: ASSERTION FAILED at rust/kernel/lib.rs:251
          Expected 42 == 43 to be true, but is false
          # my_first_test.speed: normal
          not ok 1 my_first_test
 
    - Support tests with checked 'Result' return types.
 
      The return value of test functions that return a 'Result' will be
      checked, thus one can now easily catch errors when e.g. using the
      '?' operator in tests.
 
      With this, a failing test like:
 
          #[test]
          fn my_test() -> Result {
              f()?;
              Ok(())
          }
 
      will report:
 
          # my_test: ASSERTION FAILED at rust/kernel/lib.rs:321
          Expected is_test_result_ok(my_test()) to be true, but is false
          # my_test.speed: normal
          not ok 1 my_test
 
    - Add 'kunit_tests' to the prelude.
 
  - Clarify the remaining language unstable features in use.
 
  - Compile 'core' with edition 2024 for Rust >= 1.87.
 
  - Workaround 'bindgen' issue with forward references to 'enum' types.
 
  - objtool: relax slice condition to cover more 'noreturn' functions.
 
  - Use absolute paths in macros referencing 'core' and 'kernel' crates.
 
  - Skip '-mno-fdpic' flag for bindgen in GCC 32-bit arm builds.
 
  - Clean some 'doc_markdown' lint hits -- we may enable it later on.
 
 'kernel' crate:
 
  - 'alloc' module:
 
    - 'Box': support for type coercion, e.g. 'Box<T>' to 'Box<dyn U>' if
      'T' implements 'U'.
 
    - 'Vec': implement new methods (prerequisites for nova-core and
      binder): 'truncate', 'resize', 'clear', 'pop',
      'push_within_capacity' (with new error type 'PushError'),
      'drain_all', 'retain', 'remove' (with new error type
      'RemoveError'), insert_within_capacity' (with new error type
      'InsertError').
 
      In addition, simplify 'push' using 'spare_capacity_mut', split
      'set_len' into 'inc_len' and 'dec_len', add type invariant
      'len <= capacity' and simplify 'truncate' using 'dec_len'.
 
  - 'time' module:
 
    - Morph the Rust hrtimer subsystem into the Rust timekeeping
      subsystem, covering delay, sleep, timekeeping, timers. This new
      subsystem has all the relevant timekeeping C maintainers listed in
      the entry.
 
    - Replace 'Ktime' with 'Delta' and 'Instant' types to represent a
      duration of time and a point in time.
 
    - Temporarily add 'Ktime' to 'hrtimer' module to allow 'hrtimer' to
      delay converting to 'Instant' and 'Delta'.
 
  - 'xarray' module:
 
    - Add a Rust abstraction for the 'xarray' data structure. This
      abstraction allows Rust code to leverage the 'xarray' to store
      types that implement 'ForeignOwnable'. This support is a dependency
      for memory backing feature of the Rust null block driver, which is
      waiting to be merged.
 
    - Set up an entry in 'MAINTAINERS' for the XArray Rust support.
      Patches will go to the new Rust XArray tree and then via the Rust
      subsystem tree for now.
 
    - Allow 'ForeignOwnable' to carry information about the pointed-to
      type. This helps asserting alignment requirements for the pointer
      passed to the foreign language.
 
  - 'container_of!': retain pointer mut-ness and add a compile-time check
    of the type of the first parameter ('$field_ptr').
 
  - Support optional message in 'static_assert!'.
 
  - Add C FFI types (e.g. 'c_int') to the prelude.
 
  - 'str' module: simplify KUnit tests 'format!' macro, convert
    'rusttest' tests into KUnit, take advantage of the '-> Result'
    support in KUnit '#[test]'s.
 
  - 'list' module: add examples for 'List', fix path of 'assert_pinned!'
    (so far unused macro rule).
 
  - 'workqueue' module: remove 'HasWork::OFFSET'.
 
  - 'page' module: add 'inline' attribute.
 
 'macros' crate:
 
  - 'module' macro: place 'cleanup_module()' in '.exit.text' section.
 
 'pin-init' crate:
 
  - Add 'Wrapper<T>' trait for creating pin-initializers for wrapper
    structs with a structurally pinned value such as 'UnsafeCell<T>' or
    'MaybeUninit<T>'.
 
  - Add 'MaybeZeroable' derive macro to try to derive 'Zeroable', but
    not error if not all fields implement it. This is needed to derive
    'Zeroable' for all bindgen-generated structs.
 
  - Add 'unsafe fn cast_[pin_]init()' functions to unsafely change the
    initialized type of an initializer. These are utilized by the
    'Wrapper<T>' implementations.
 
  - Add support for visibility in 'Zeroable' derive macro.
 
  - Add support for 'union's in 'Zeroable' derive macro.
 
  - Upstream dev news: streamline CI, fix some bugs. Add new workflows
    to check if the user-space version and the one in the kernel tree
    have diverged. Use the issues tab [1] to track them, which should
    help folks report and diagnose issues w.r.t. 'pin-init' better.
 
      [1] https://github.com/rust-for-linux/pin-init/issues
 
 Documentation:
 
  - Testing: add docs on the new KUnit '#[test]' tests.
 
  - Coding guidelines: explain that '///' vs. '//' applies to private
    items too. Add section on C FFI types.
 
  - Quick Start guide: update Ubuntu instructions and split them into
    "25.04" and "24.04 LTS and older".
 
 And a few other cleanups and improvements.
 -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCgAdFiEEPjU5OPd5QIZ9jqqOGXyLc2htIW0FAmhBAvYACgkQGXyLc2ht
 IW3qvA/+KRTCYKcI6JyUT9TdhRmaaMsQ0/5j6Kx4CfRQPZTSWsXyBEU75yEIZUQD
 SUGQFwmMAYeAKQD1SumFCRy973VzUO45DyKM+7vuVhKN1ZjnAtv63+31C3UFATlA
 8Tm3GCqQEGKl4IER7xI3D/vpZA5FOv+GotjNieF3O9FpHDCvV/JQScq9I2oXQPCt
 17kRLww/DTfpf4qiLmxmxHn6nCsbecdfEce1kfjk3nNuE6B2tPf+ddYOwunLEvkB
 LA4Cr6T1Cy1ovRQgxg9Pdkl/0Rta0tFcsKt1LqPgjR+n95stsHgAzbyMGuUKoeZx
 u2R2pwlrJt6Xe4CEZgTIRfYWgF81qUzdcPuflcSMDCpH0nTep74A2lIiWUHWZSh4
 LbPh7r90Q8YwGKVJiWqLfHUmQBnmTEm3D2gydSExPKJXSzB4Rbv4w4fPF3dhzMtC
 4+KvmHKIojFkAdTLt+5rkKipJGo/rghvQvaQr9JOu+QO4vfhkesB4pUWC4sZd9A9
 GJBP97ynWAsXGGaeaaSli0b851X+VE/WIDOmPMselbA3rVADChE6HsJnY/wVVeWK
 jupvAhUExSczDPCluGv8T9EVXvv6+fg3bB5pD6R01NNJe6iE/LIDQ5Gj5rg4qahM
 EFzMgPj6hMt5McvWI8q1/ym0bzdeC2/cmaV6E14hvphAZoORUKI=
 =JRqL
 -----END PGP SIGNATURE-----

Merge tag 'rust-6.16' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux

Pull Rust updates from Miguel Ojeda:
 "Toolchain and infrastructure:

   - KUnit '#[test]'s:

      - Support KUnit-mapped 'assert!' macros.

        The support that landed last cycle was very basic, and the
        'assert!' macros panicked since they were the standard library
        ones. Now, they are mapped to the KUnit ones in a similar way to
        how is done for doctests, reusing the infrastructure there.

        With this, a failing test like:

            #[test]
            fn my_first_test() {
                assert_eq!(42, 43);
            }

        will report:

            # my_first_test: ASSERTION FAILED at rust/kernel/lib.rs:251
            Expected 42 == 43 to be true, but is false
            # my_first_test.speed: normal
            not ok 1 my_first_test

      - Support tests with checked 'Result' return types.

        The return value of test functions that return a 'Result' will
        be checked, thus one can now easily catch errors when e.g. using
        the '?' operator in tests.

        With this, a failing test like:

            #[test]
            fn my_test() -> Result {
                f()?;
                Ok(())
            }

        will report:

            # my_test: ASSERTION FAILED at rust/kernel/lib.rs:321
            Expected is_test_result_ok(my_test()) to be true, but is false
            # my_test.speed: normal
            not ok 1 my_test

      - Add 'kunit_tests' to the prelude.

   - Clarify the remaining language unstable features in use.

   - Compile 'core' with edition 2024 for Rust >= 1.87.

   - Workaround 'bindgen' issue with forward references to 'enum' types.

   - objtool: relax slice condition to cover more 'noreturn' functions.

   - Use absolute paths in macros referencing 'core' and 'kernel'
     crates.

   - Skip '-mno-fdpic' flag for bindgen in GCC 32-bit arm builds.

   - Clean some 'doc_markdown' lint hits -- we may enable it later on.

  'kernel' crate:

   - 'alloc' module:

      - 'Box': support for type coercion, e.g. 'Box<T>' to 'Box<dyn U>'
        if 'T' implements 'U'.

      - 'Vec': implement new methods (prerequisites for nova-core and
        binder): 'truncate', 'resize', 'clear', 'pop',
        'push_within_capacity' (with new error type 'PushError'),
        'drain_all', 'retain', 'remove' (with new error type
        'RemoveError'), insert_within_capacity' (with new error type
        'InsertError').

        In addition, simplify 'push' using 'spare_capacity_mut', split
        'set_len' into 'inc_len' and 'dec_len', add type invariant 'len
        <= capacity' and simplify 'truncate' using 'dec_len'.

   - 'time' module:

      - Morph the Rust hrtimer subsystem into the Rust timekeeping
        subsystem, covering delay, sleep, timekeeping, timers. This new
        subsystem has all the relevant timekeeping C maintainers listed
        in the entry.

      - Replace 'Ktime' with 'Delta' and 'Instant' types to represent a
        duration of time and a point in time.

      - Temporarily add 'Ktime' to 'hrtimer' module to allow 'hrtimer'
        to delay converting to 'Instant' and 'Delta'.

   - 'xarray' module:

      - Add a Rust abstraction for the 'xarray' data structure. This
        abstraction allows Rust code to leverage the 'xarray' to store
        types that implement 'ForeignOwnable'. This support is a
        dependency for memory backing feature of the Rust null block
        driver, which is waiting to be merged.

      - Set up an entry in 'MAINTAINERS' for the XArray Rust support.
        Patches will go to the new Rust XArray tree and then via the
        Rust subsystem tree for now.

      - Allow 'ForeignOwnable' to carry information about the pointed-to
        type. This helps asserting alignment requirements for the
        pointer passed to the foreign language.

   - 'container_of!': retain pointer mut-ness and add a compile-time
     check of the type of the first parameter ('$field_ptr').

   - Support optional message in 'static_assert!'.

   - Add C FFI types (e.g. 'c_int') to the prelude.

   - 'str' module: simplify KUnit tests 'format!' macro, convert
     'rusttest' tests into KUnit, take advantage of the '-> Result'
     support in KUnit '#[test]'s.

   - 'list' module: add examples for 'List', fix path of
     'assert_pinned!' (so far unused macro rule).

   - 'workqueue' module: remove 'HasWork::OFFSET'.

   - 'page' module: add 'inline' attribute.

  'macros' crate:

   - 'module' macro: place 'cleanup_module()' in '.exit.text' section.

  'pin-init' crate:

   - Add 'Wrapper<T>' trait for creating pin-initializers for wrapper
     structs with a structurally pinned value such as 'UnsafeCell<T>' or
     'MaybeUninit<T>'.

   - Add 'MaybeZeroable' derive macro to try to derive 'Zeroable', but
     not error if not all fields implement it. This is needed to derive
     'Zeroable' for all bindgen-generated structs.

   - Add 'unsafe fn cast_[pin_]init()' functions to unsafely change the
     initialized type of an initializer. These are utilized by the
     'Wrapper<T>' implementations.

   - Add support for visibility in 'Zeroable' derive macro.

   - Add support for 'union's in 'Zeroable' derive macro.

   - Upstream dev news: streamline CI, fix some bugs. Add new workflows
     to check if the user-space version and the one in the kernel tree
     have diverged. Use the issues tab [1] to track them, which should
     help folks report and diagnose issues w.r.t. 'pin-init' better.

       [1] https://github.com/rust-for-linux/pin-init/issues

  Documentation:

   - Testing: add docs on the new KUnit '#[test]' tests.

   - Coding guidelines: explain that '///' vs. '//' applies to private
     items too. Add section on C FFI types.

   - Quick Start guide: update Ubuntu instructions and split them into
     "25.04" and "24.04 LTS and older".

  And a few other cleanups and improvements"

* tag 'rust-6.16' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux: (78 commits)
  rust: list: Fix typo `much` in arc.rs
  rust: check type of `$ptr` in `container_of!`
  rust: workqueue: remove HasWork::OFFSET
  rust: retain pointer mut-ness in `container_of!`
  Documentation: rust: testing: add docs on the new KUnit `#[test]` tests
  Documentation: rust: rename `#[test]`s to "`rusttest` host tests"
  rust: str: take advantage of the `-> Result` support in KUnit `#[test]`'s
  rust: str: simplify KUnit tests `format!` macro
  rust: str: convert `rusttest` tests into KUnit
  rust: add `kunit_tests` to the prelude
  rust: kunit: support checked `-> Result`s in KUnit `#[test]`s
  rust: kunit: support KUnit-mapped `assert!` macros in `#[test]`s
  rust: make section names plural
  rust: list: fix path of `assert_pinned!`
  rust: compile libcore with edition 2024 for 1.87+
  rust: dma: add missing Markdown code span
  rust: task: add missing Markdown code spans and intra-doc links
  rust: pci: fix docs related to missing Markdown code spans
  rust: alloc: add missing Markdown code span
  rust: alloc: add missing Markdown code spans
  ...
2025-06-04 21:18:37 -07:00

332 lines
12 KiB
Rust

// SPDX-License-Identifier: GPL-2.0 OR MIT
//! DRM GEM API
//!
//! C header: [`include/linux/drm/drm_gem.h`](srctree/include/linux/drm/drm_gem.h)
use crate::{
alloc::flags::*,
bindings, drm,
drm::driver::{AllocImpl, AllocOps},
error::{to_result, Result},
prelude::*,
types::{ARef, AlwaysRefCounted, Opaque},
};
use core::{mem, ops::Deref, ptr::NonNull};
/// GEM object functions, which must be implemented by drivers.
pub trait BaseDriverObject<T: BaseObject>: Sync + Send + Sized {
/// Create a new driver data object for a GEM object of a given size.
fn new(dev: &drm::Device<T::Driver>, size: usize) -> impl PinInit<Self, Error>;
/// Open a new handle to an existing object, associated with a File.
fn open(
_obj: &<<T as IntoGEMObject>::Driver as drm::Driver>::Object,
_file: &drm::File<<<T as IntoGEMObject>::Driver as drm::Driver>::File>,
) -> Result {
Ok(())
}
/// Close a handle to an existing object, associated with a File.
fn close(
_obj: &<<T as IntoGEMObject>::Driver as drm::Driver>::Object,
_file: &drm::File<<<T as IntoGEMObject>::Driver as drm::Driver>::File>,
) {
}
}
/// Trait that represents a GEM object subtype
pub trait IntoGEMObject: Sized + super::private::Sealed + AlwaysRefCounted {
/// Owning driver for this type
type Driver: drm::Driver;
/// Returns a reference to the raw `drm_gem_object` structure, which must be valid as long as
/// this owning object is valid.
fn as_raw(&self) -> *mut bindings::drm_gem_object;
/// Converts a pointer to a `struct drm_gem_object` into a reference to `Self`.
///
/// # Safety
///
/// - `self_ptr` must be a valid pointer to `Self`.
/// - The caller promises that holding the immutable reference returned by this function does
/// not violate rust's data aliasing rules and remains valid throughout the lifetime of `'a`.
unsafe fn as_ref<'a>(self_ptr: *mut bindings::drm_gem_object) -> &'a Self;
}
// SAFETY: All gem objects are refcounted.
unsafe impl<T: IntoGEMObject> AlwaysRefCounted for T {
fn inc_ref(&self) {
// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
unsafe { bindings::drm_gem_object_get(self.as_raw()) };
}
unsafe fn dec_ref(obj: NonNull<Self>) {
// SAFETY: We either hold the only refcount on `obj`, or one of many - meaning that no one
// else could possibly hold a mutable reference to `obj` and thus this immutable reference
// is safe.
let obj = unsafe { obj.as_ref() }.as_raw();
// SAFETY:
// - The safety requirements guarantee that the refcount is non-zero.
// - We hold no references to `obj` now, making it safe for us to potentially deallocate it.
unsafe { bindings::drm_gem_object_put(obj) };
}
}
/// Trait which must be implemented by drivers using base GEM objects.
pub trait DriverObject: BaseDriverObject<Object<Self>> {
/// Parent `Driver` for this object.
type Driver: drm::Driver;
}
extern "C" fn open_callback<T: BaseDriverObject<U>, U: BaseObject>(
raw_obj: *mut bindings::drm_gem_object,
raw_file: *mut bindings::drm_file,
) -> core::ffi::c_int {
// SAFETY: `open_callback` is only ever called with a valid pointer to a `struct drm_file`.
let file = unsafe {
drm::File::<<<U as IntoGEMObject>::Driver as drm::Driver>::File>::as_ref(raw_file)
};
// SAFETY: `open_callback` is specified in the AllocOps structure for `Object<T>`, ensuring that
// `raw_obj` is indeed contained within a `Object<T>`.
let obj = unsafe {
<<<U as IntoGEMObject>::Driver as drm::Driver>::Object as IntoGEMObject>::as_ref(raw_obj)
};
match T::open(obj, file) {
Err(e) => e.to_errno(),
Ok(()) => 0,
}
}
extern "C" fn close_callback<T: BaseDriverObject<U>, U: BaseObject>(
raw_obj: *mut bindings::drm_gem_object,
raw_file: *mut bindings::drm_file,
) {
// SAFETY: `open_callback` is only ever called with a valid pointer to a `struct drm_file`.
let file = unsafe {
drm::File::<<<U as IntoGEMObject>::Driver as drm::Driver>::File>::as_ref(raw_file)
};
// SAFETY: `close_callback` is specified in the AllocOps structure for `Object<T>`, ensuring
// that `raw_obj` is indeed contained within a `Object<T>`.
let obj = unsafe {
<<<U as IntoGEMObject>::Driver as drm::Driver>::Object as IntoGEMObject>::as_ref(raw_obj)
};
T::close(obj, file);
}
impl<T: DriverObject> IntoGEMObject for Object<T> {
type Driver = T::Driver;
fn as_raw(&self) -> *mut bindings::drm_gem_object {
self.obj.get()
}
unsafe fn as_ref<'a>(self_ptr: *mut bindings::drm_gem_object) -> &'a Self {
let self_ptr: *mut Opaque<bindings::drm_gem_object> = self_ptr.cast();
// SAFETY: `obj` is guaranteed to be in an `Object<T>` via the safety contract of this
// function
unsafe { &*crate::container_of!(self_ptr, Object<T>, obj) }
}
}
/// Base operations shared by all GEM object classes
pub trait BaseObject: IntoGEMObject {
/// Returns the size of the object in bytes.
fn size(&self) -> usize {
// SAFETY: `self.as_raw()` is guaranteed to be a pointer to a valid `struct drm_gem_object`.
unsafe { (*self.as_raw()).size }
}
/// Creates a new handle for the object associated with a given `File`
/// (or returns an existing one).
fn create_handle(
&self,
file: &drm::File<<<Self as IntoGEMObject>::Driver as drm::Driver>::File>,
) -> Result<u32> {
let mut handle: u32 = 0;
// SAFETY: The arguments are all valid per the type invariants.
to_result(unsafe {
bindings::drm_gem_handle_create(file.as_raw().cast(), self.as_raw(), &mut handle)
})?;
Ok(handle)
}
/// Looks up an object by its handle for a given `File`.
fn lookup_handle(
file: &drm::File<<<Self as IntoGEMObject>::Driver as drm::Driver>::File>,
handle: u32,
) -> Result<ARef<Self>> {
// SAFETY: The arguments are all valid per the type invariants.
let ptr = unsafe { bindings::drm_gem_object_lookup(file.as_raw().cast(), handle) };
if ptr.is_null() {
return Err(ENOENT);
}
// SAFETY:
// - A `drm::Driver` can only have a single `File` implementation.
// - `file` uses the same `drm::Driver` as `Self`.
// - Therefore, we're guaranteed that `ptr` must be a gem object embedded within `Self`.
// - And we check if the pointer is null befoe calling as_ref(), ensuring that `ptr` is a
// valid pointer to an initialized `Self`.
let obj = unsafe { Self::as_ref(ptr) };
// SAFETY:
// - We take ownership of the reference of `drm_gem_object_lookup()`.
// - Our `NonNull` comes from an immutable reference, thus ensuring it is a valid pointer to
// `Self`.
Ok(unsafe { ARef::from_raw(obj.into()) })
}
/// Creates an mmap offset to map the object from userspace.
fn create_mmap_offset(&self) -> Result<u64> {
// SAFETY: The arguments are valid per the type invariant.
to_result(unsafe { bindings::drm_gem_create_mmap_offset(self.as_raw()) })?;
// SAFETY: The arguments are valid per the type invariant.
Ok(unsafe { bindings::drm_vma_node_offset_addr(&raw mut (*self.as_raw()).vma_node) })
}
}
impl<T: IntoGEMObject> BaseObject for T {}
/// A base GEM object.
///
/// Invariants
///
/// - `self.obj` is a valid instance of a `struct drm_gem_object`.
/// - `self.dev` is always a valid pointer to a `struct drm_device`.
#[repr(C)]
#[pin_data]
pub struct Object<T: DriverObject + Send + Sync> {
obj: Opaque<bindings::drm_gem_object>,
dev: NonNull<drm::Device<T::Driver>>,
#[pin]
data: T,
}
impl<T: DriverObject> Object<T> {
/// The size of this object's structure.
pub const SIZE: usize = mem::size_of::<Self>();
const OBJECT_FUNCS: bindings::drm_gem_object_funcs = bindings::drm_gem_object_funcs {
free: Some(Self::free_callback),
open: Some(open_callback::<T, Object<T>>),
close: Some(close_callback::<T, Object<T>>),
print_info: None,
export: None,
pin: None,
unpin: None,
get_sg_table: None,
vmap: None,
vunmap: None,
mmap: None,
status: None,
vm_ops: core::ptr::null_mut(),
evict: None,
rss: None,
};
/// Create a new GEM object.
pub fn new(dev: &drm::Device<T::Driver>, size: usize) -> Result<ARef<Self>> {
let obj: Pin<KBox<Self>> = KBox::pin_init(
try_pin_init!(Self {
obj: Opaque::new(bindings::drm_gem_object::default()),
data <- T::new(dev, size),
// INVARIANT: The drm subsystem guarantees that the `struct drm_device` will live
// as long as the GEM object lives.
dev: dev.into(),
}),
GFP_KERNEL,
)?;
// SAFETY: `obj.as_raw()` is guaranteed to be valid by the initialization above.
unsafe { (*obj.as_raw()).funcs = &Self::OBJECT_FUNCS };
// SAFETY: The arguments are all valid per the type invariants.
to_result(unsafe { bindings::drm_gem_object_init(dev.as_raw(), obj.obj.get(), size) })?;
// SAFETY: We never move out of `Self`.
let ptr = KBox::into_raw(unsafe { Pin::into_inner_unchecked(obj) });
// SAFETY: `ptr` comes from `KBox::into_raw` and hence can't be NULL.
let ptr = unsafe { NonNull::new_unchecked(ptr) };
// SAFETY: We take over the initial reference count from `drm_gem_object_init()`.
Ok(unsafe { ARef::from_raw(ptr) })
}
/// Returns the `Device` that owns this GEM object.
pub fn dev(&self) -> &drm::Device<T::Driver> {
// SAFETY: The DRM subsystem guarantees that the `struct drm_device` will live as long as
// the GEM object lives, hence the pointer must be valid.
unsafe { self.dev.as_ref() }
}
fn as_raw(&self) -> *mut bindings::drm_gem_object {
self.obj.get()
}
extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) {
let ptr: *mut Opaque<bindings::drm_gem_object> = obj.cast();
// SAFETY: All of our objects are of type `Object<T>`.
let this = unsafe { crate::container_of!(ptr, Self, obj) };
// SAFETY: The C code only ever calls this callback with a valid pointer to a `struct
// drm_gem_object`.
unsafe { bindings::drm_gem_object_release(obj) };
// SAFETY: All of our objects are allocated via `KBox`, and we're in the
// free callback which guarantees this object has zero remaining references,
// so we can drop it.
let _ = unsafe { KBox::from_raw(this) };
}
}
impl<T: DriverObject> super::private::Sealed for Object<T> {}
impl<T: DriverObject> Deref for Object<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<T: DriverObject> AllocImpl for Object<T> {
const ALLOC_OPS: AllocOps = AllocOps {
gem_create_object: None,
prime_handle_to_fd: None,
prime_fd_to_handle: None,
gem_prime_import: None,
gem_prime_import_sg_table: None,
dumb_create: None,
dumb_map_offset: None,
};
}
pub(super) const fn create_fops() -> bindings::file_operations {
// SAFETY: As by the type invariant, it is safe to initialize `bindings::file_operations`
// zeroed.
let mut fops: bindings::file_operations = unsafe { core::mem::zeroed() };
fops.owner = core::ptr::null_mut();
fops.open = Some(bindings::drm_open);
fops.release = Some(bindings::drm_release);
fops.unlocked_ioctl = Some(bindings::drm_ioctl);
#[cfg(CONFIG_COMPAT)]
{
fops.compat_ioctl = Some(bindings::drm_compat_ioctl);
}
fops.poll = Some(bindings::drm_poll);
fops.read = Some(bindings::drm_read);
fops.llseek = Some(bindings::noop_llseek);
fops.mmap = Some(bindings::drm_gem_mmap);
fops.fop_flags = bindings::FOP_UNSIGNED_OFFSET;
fops
}