Skip to main content

kernel/drm/
driver.rs

1// SPDX-License-Identifier: GPL-2.0 OR MIT
2
3//! DRM driver core.
4//!
5//! C header: [`include/drm/drm_drv.h`](srctree/include/drm/drm_drv.h)
6
7use crate::{
8    bindings,
9    device,
10    drm,
11    error::to_result,
12    prelude::*,
13    sync::aref::ARef, //
14};
15use core::{
16    marker::PhantomPinned,
17    ptr::NonNull, //
18};
19
20/// Driver use the GEM memory manager. This should be set for all modern drivers.
21pub(crate) const FEAT_GEM: u32 = bindings::drm_driver_feature_DRIVER_GEM;
22/// Driver supports render nodes, i.e.: /dev/dri/renderDXX devices.
23pub(crate) const FEAT_RENDER: u32 = bindings::drm_driver_feature_DRIVER_RENDER;
24
25/// Information data for a DRM Driver.
26pub struct DriverInfo {
27    /// Driver major version.
28    pub major: i32,
29    /// Driver minor version.
30    pub minor: i32,
31    /// Driver patchlevel version.
32    pub patchlevel: i32,
33    /// Driver name.
34    pub name: &'static CStr,
35    /// Driver description.
36    pub desc: &'static CStr,
37}
38
39/// Internal memory management operation set, normally created by memory managers (e.g. GEM).
40pub struct AllocOps {
41    pub(crate) gem_create_object: Option<
42        unsafe extern "C" fn(
43            dev: *mut bindings::drm_device,
44            size: usize,
45        ) -> *mut bindings::drm_gem_object,
46    >,
47    pub(crate) prime_handle_to_fd: Option<
48        unsafe extern "C" fn(
49            dev: *mut bindings::drm_device,
50            file_priv: *mut bindings::drm_file,
51            handle: u32,
52            flags: u32,
53            prime_fd: *mut core::ffi::c_int,
54        ) -> core::ffi::c_int,
55    >,
56    pub(crate) prime_fd_to_handle: Option<
57        unsafe extern "C" fn(
58            dev: *mut bindings::drm_device,
59            file_priv: *mut bindings::drm_file,
60            prime_fd: core::ffi::c_int,
61            handle: *mut u32,
62        ) -> core::ffi::c_int,
63    >,
64    pub(crate) gem_prime_import: Option<
65        unsafe extern "C" fn(
66            dev: *mut bindings::drm_device,
67            dma_buf: *mut bindings::dma_buf,
68        ) -> *mut bindings::drm_gem_object,
69    >,
70    pub(crate) gem_prime_import_sg_table: Option<
71        unsafe extern "C" fn(
72            dev: *mut bindings::drm_device,
73            attach: *mut bindings::dma_buf_attachment,
74            sgt: *mut bindings::sg_table,
75        ) -> *mut bindings::drm_gem_object,
76    >,
77    pub(crate) dumb_create: Option<
78        unsafe extern "C" fn(
79            file_priv: *mut bindings::drm_file,
80            dev: *mut bindings::drm_device,
81            args: *mut bindings::drm_mode_create_dumb,
82        ) -> core::ffi::c_int,
83    >,
84    pub(crate) dumb_map_offset: Option<
85        unsafe extern "C" fn(
86            file_priv: *mut bindings::drm_file,
87            dev: *mut bindings::drm_device,
88            handle: u32,
89            offset: *mut u64,
90        ) -> core::ffi::c_int,
91    >,
92}
93
94/// Trait for memory manager implementations. Implemented internally.
95pub trait AllocImpl: super::private::Sealed + drm::gem::IntoGEMObject {
96    /// The [`Driver`] implementation for this [`AllocImpl`].
97    type Driver: drm::Driver;
98
99    /// The C callback operations for this memory manager.
100    const ALLOC_OPS: AllocOps;
101}
102
103/// The DRM `Driver` trait.
104///
105/// This trait must be implemented by drivers in order to create a `struct drm_device` and `struct
106/// drm_driver` to be registered in the DRM subsystem.
107#[vtable]
108pub trait Driver {
109    /// Context data associated with the DRM driver
110    type Data: Sync + Send;
111
112    /// Data owned by the [`Registration`] and accessible within a
113    /// [`RegistrationGuard`](drm::RegistrationGuard) critical section via
114    /// [`Device::registration_data_with()`](drm::Device::registration_data_with).
115    ///
116    /// The lifetime parameter is tied to the [`Registration`] scope, which is enclosed in the
117    /// parent bus device binding scope but may be shorter.
118    type RegistrationData<'a>: Send + Sync + 'a;
119
120    /// The type used to manage memory for this driver.
121    type Object: AllocImpl;
122
123    /// The type used to represent a DRM File (client)
124    type File: drm::file::DriverFile;
125
126    /// The bus device type of the parent device that the DRM device is associated with.
127    type ParentDevice<Ctx: device::DeviceContext>: device::AsBusDevice<Ctx>;
128
129    /// Driver metadata
130    const INFO: DriverInfo;
131
132    /// IOCTL list. See `kernel::drm::ioctl::declare_drm_ioctls!{}`.
133    const IOCTLS: &'static [drm::ioctl::DrmIoctlDescriptor];
134
135    /// Sets the `DRIVER_RENDER` feature for this driver.
136    ///
137    /// When enabled, the driver exposes `/dev/dri/renderDXX` render nodes to
138    /// userspace. The render node is an alternate low-privilege way to access
139    /// the driver, which is enforced on a per-ioctl level. Userspace processes
140    /// that open the render node can only invoke ioctls explicitly listed as
141    /// usable from the render node (i.e. marked DRM_RENDER_ALLOW), whereas
142    /// userspace processes using the master node can invoke any ioctl.
143    const FEAT_RENDER: bool = false;
144}
145
146/// The registration type of a `drm::Device`.
147///
148/// Once the `Registration` structure is dropped, the device is unregistered.
149#[pin_data(PinnedDrop)]
150pub struct Registration<'a, T: Driver> {
151    drm: ARef<drm::Device<T>>,
152    #[pin]
153    data: T::RegistrationData<'a>,
154    /// Even if `T::RegistrationData` is `Unpin`, the registration must not be moved because a
155    /// pointer to `data` is stored in the DRM device.
156    #[pin]
157    _pin: PhantomPinned,
158}
159
160impl<'a, T: Driver> Registration<'a, T> {
161    /// Register a new [`UnregisteredDevice`](drm::UnregisteredDevice) with userspace.
162    ///
163    /// # Safety
164    ///
165    /// The caller must not `mem::forget()` the returned [`Registration`] or otherwise prevent its
166    /// [`Drop`] implementation from running, since the registration data may contain borrowed
167    /// references that become invalid after `'a` ends.
168    pub unsafe fn new<E>(
169        dev: &'a device::Device<device::Bound>,
170        drm: drm::UnregisteredDevice<T>,
171        data: impl PinInit<T::RegistrationData<'a>, E>,
172    ) -> impl PinInit<Self, Error>
173    where
174        Error: From<E>,
175    {
176        try_pin_init!(Self {
177            _: {
178                let parent = drm.as_ref();
179                if parent.as_ref().as_raw() != dev.as_raw() {
180                    return Err(EINVAL);
181                }
182            },
183
184            data <- data,
185            drm: (&*drm).into(),
186            _pin: PhantomPinned,
187
188            _: {
189                // Store the registration data pointer in the device before registration, so
190                // that it is visible once ioctls can be called.
191                let ptr: NonNull<T::RegistrationData<'static>> =
192                    NonNull::from(data.as_ref().get_ref()).cast();
193
194                // SAFETY: No concurrent access; the device is not yet registered.
195                unsafe { *drm.registration_data.get() = ptr };
196
197                // SAFETY: `drm` is a valid, initialized but not yet registered DRM device.
198                let ret = unsafe { bindings::drm_dev_register(drm.as_raw(), 0) };
199                to_result(ret).inspect_err(|_| {
200                    // SAFETY: `drm_dev_register()` synchronizes SRCU on failure, so no
201                    // concurrent access to `registration_data` is possible at this point.
202                    unsafe { *drm.registration_data.get() = NonNull::dangling() };
203                })?;
204            },
205        })
206    }
207
208    /// Returns a reference to the `Device` instance for this registration.
209    pub fn device(&self) -> &drm::Device<T> {
210        &self.drm
211    }
212}
213
214// SAFETY: `Registration` doesn't offer any methods or access to fields when shared between
215// threads, hence it's safe to share it.
216unsafe impl<T: Driver> Sync for Registration<'_, T> {}
217
218// SAFETY: Registration with and unregistration from the DRM subsystem can happen from any thread.
219unsafe impl<T: Driver> Send for Registration<'_, T> {}
220
221#[pinned_drop]
222impl<T: Driver> PinnedDrop for Registration<'_, T> {
223    fn drop(self: Pin<&mut Self>) {
224        // Use `drm_dev_unplug` rather than `drm_dev_unregister` to ensure that existing
225        // `drm_dev_enter()` critical sections complete before unregistration proceeds. This
226        // is required for the safety of `RegistrationGuard`, which relies on the SRCU barrier in
227        // `drm_dev_unplug()` to guarantee that the parent device is still bound within the
228        // critical section.
229        //
230        // SAFETY: Safe by the invariant of `ARef<drm::Device<T>>`. The existence of this
231        // `Registration` also guarantees that this `drm::Device` is actually registered.
232        unsafe { bindings::drm_dev_unplug(self.drm.as_raw()) };
233        // After drm_dev_unplug(), the SRCU barrier guarantees that all RegistrationGuard critical
234        // sections have completed, so no one holds a reference to reg_data anymore.
235        // reg_data is dropped here automatically.
236    }
237}