Skip to contentSkip to conversation

Rust bindings for KMS + RVKMS

RFC Superseded Lyude Paul 2 participants 12 messages Mar 22, 2024 – Apr 29, 2024

Subsystems (4)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Lyude Paul

author
#0 lore raw

cover Rust bindings for KMS + RVKMS

Hi everyone! I mentioned a little while ago that I've been working on porting vkms over to rust so that we could come up with a set of rust KMS bindings for the nova driver to be able to have a modesetting driver written in rust. This driver currently doesn't really do much, but it does load and register a modesetting device!

I wanted to send this early on so that people could take a look and tell me if there's anything I've overlooked so far. As well, I've written up a high level overview of how the interface works - along with my reasoning for a lot of the design choices here. I'm sure things will change a bit as I figure out what we really need while porting rvkms, but I'm hoping this is pretty close to what the final set of bindings are going to look like.

Note: not all of the patches required for building this have been included. I've just included the kms/rvkms bits here, but the full branch can be found here:

https://gitlab.freedesktop.org/lyudess/linux/-/commits/rvkms-03222024

So, the overview!

# Modesetting objects and atomic states

A general overview of the interface: so far we have the following traits for drivers to implement:

* DriverConnector
* DriverCrtc
* DriverPlane
* DriverEncoder

Each one of these modesetting objects also has a typed container that can be used to refer to it by drivers: Connector<T>, Plane<T>, etc. Each typed container has only two members (not counting phantoms). Using Crtc<T> as an example:

/// A typed KMS CRTC with a specific driver.
#[repr(C)]
#[pin_data]

pub struct Crtc<T: DriverCrtc> {
    // The FFI drm_crtc object
    pub(super) crtc: Opaque<bindings::drm_crtc>,
    /// The driver's private inner data
    #[pin]
    inner: T,
    #[pin]
    _p: PhantomPinned,
}

The first member is an Opaque<> container containing the FFI struct for the modesetting object, and the second inner contains the implementing driver's private data for the modesetting object. Each modesetting object container can be coerced (through Deref<>) into an immutable reference to inner to make accessing driver-private data easy. This allows subclassing of modesetting objects in a similar manner to what we currently do in C.

The main difference is that modesetting objects are immutable to drivers (as in, drivers can only get immutable references to these objects). The reason for this is that while it's common for drivers to stick their own private data in objects, pretty much all of this data falls into one of these categories:

* Static driver data which is assigned during driver init. In our abstraction, this assignment will happen in each modesetting object's T::new() function - where the driver can use each modesetting object trait's Args type to specify a data type containing such data which will be passed to T::new(). This should always be available through immutable references.
* Modesetting state for drivers which needs to be kept track of independently of the atomic state. As the name entails, all data in this category is assumed to only be accessible within a modesetting context - which itself ensures synchronization. At some point we will implement a container type for this, which only provides a &mut reference once the caller provides proof that we're in an atomic modesetting context and thus - are the only ones who could possibly hold a mutable reference.
* Miscellaneous driver state, which may need to be accessed both inside and outside of the atomic modesetting context. We will provide no container type for this, and it will be up to the driver to provide an appropriate container that ensures synchronization and hands out mutable references as needed. A simple example of such a container would be Mutex<T>.

# Opaque modesetting objects

This is something I haven't written up code for yet because we haven't run into any use for it, but presumably we will eventually. Basically:
since we have driver subclassing through types like Connector<T> which the main DRM device trait doesn't need to know about - it is technically possible for us to have multiple different implementations of a modesetting object (for instance, a driver could have two DriverConnector implementations for different types of display connectors). At first I thought this might be too complicated, but I don't think it is! To support this, we would use a similar solution to what the GEM bindings currently do - by providing an opaque version of each modesetting object which only can be used for operations common across different implementations of that object. This Opaque struct could then be fallibly converted to its more qualified type, and we can ensure type safety here by simply using each implementation's vtable pointer (all of which should be 'static) to tell whether an opaque object matches the qualified type the driver is expecting. Here's some example psuedocode to give you an idea:

```
let drm_dev: drm::device::Device<Driver>; /* initialized elsewhere */

type Plane = drm::kms::plane::Plane<DriverPlane>;

for plane in drm_dev.iter_planes().filter_map(Plane::from_opaque) {
  // ... do something
}
```

We'd only really need to use these opaque types in situations where we can't guarantee type invariance, like iterating a list of multiple impls of modesetting objects. So, that more or less just means "anywhere outside of a DRM callback" (callbacks can ensure type invariance since each type has its own vtable).

# Atomic states for modesetting objects

For objects with atomic states, these traits are also implemented by the driver and allow subclassing as well - but with a few differences:

* ConnectorState
* CrtcState
* PlaneState

The main difference is that unlike with modesetting objects, atomic states are initially* considered mutable objects. This is mainly since contexts like atomic_check can satisfy rust's data aliasing rules, and it's just a lot easier for drivers to be able to get &mut references to these easily. It is likely that we may expose these objects later on through Pin<&mut> - since we don't want to allow them to move as certain drivers will do things like storing work structs in their states. I haven't gotten this far in the code yet though!

# Helpers

VKMS does not actually use drm_plane_state! Instead, it actually uses a GEM provided atomic state helper and the drm_shadow_plane_struct - which contains a drm_plane_state. And this is only a single example of such a helper, as a number of other ones which change the struct type a driver uses exist. So, how do we actually handle this in our bindings? Well, by shamelessly copying what the GEM bindings do!

For modesetting objects where we want to also support the use of a helper that comes with it's own modesetting object/atomic state struct, we can follow another trait pattern. Using PlaneState<T> and shadow planes as an example: we can introduce a sealed trait named IntoPlaneState. This trait will represent any object in rust which contains a drm_plane_state - along with providing a set of functions that can be implemented to tell rust how to translate the object into a drm_plane_state, along with providing methods for invoking any other DRM functions that might be different for a helper. In the patch series I've posted, I've included some of the WIP code for handling shadow planes in this manner.

# The initially* mutable global atomic state

I have some WIP code written up for this, but nothing very complete quite yet as we haven't yet needed to manually instantiate an atomic state yet. But in some of the code I wrote up, I noticed some funny gotchas.

The main drm_atomic_state structure is refcounted - which means multiple references to an atomic state can exist at once. This complicates things just a bit - as rust's data aliasing rules only allow for one mutable reference to an object to exist at a time. My current plan for handling this is to extend the kernel's ARef<T> type to also include a UniqueARef<T> type. This is basically the same as the kernel's UniqueArc<T> type, but for already refcounted objects - which will allow a caller mutable access to the underlying object so long as it's the only one holding a ref to it. Sharing references to the atomic state requires will require converting away from the UniqueARef. I think this should be enough, since drivers shouldn't really be making any changes to a state after the atomic check phase - so only having immutable references after that point should be good enough to make everyone happy.

# Modesetting object lifetimes, ModesetObject and StaticModesetObject

I think sima may have tried to warn me about this, because this was definitely a strange bit to figure out. There are two main types of modesetting objects in the kernel: refcounted modesetting objects, and non-refcounted modesetting objects. Reference counted objects are easy:
we just implement the kernel's AlwaysRefCounted trait for them. Non-refcounted modesetting objects are weirder, as they share the lifetime of the device. This was one of the other big reasons we have to always expose modesetting objects through immutable references giving driver ownership over these structs would imply the driver could drop them before the drm device has been dropped which would cause UB. I originally considered having modesetting objects live in Arc<> internally to workaround this, but decided against it as this would mean we could make a non-refcounted modesetting object outlive it's device - which could also cause UB if a driver tried to do a modesetting operation with said object.

I'd _really_ love to figure out how to handle this with references and lifetimes, as right now we currently tie the lifetime of a modesetting object's reference to the lifetime of the reference to the DRM device that created it - but this isn't currently enough to store those references in a driver's private data as I can't figure out how to tell the compiler "this reference is valid for as long as you hold an ARef for the DRM device". Which brings us to ModesetObject and StaticModesetObject. ModesetObject is a simple trait implemented by all DRM modesetting objects, which provides access to functions common across them (such as fetching the DRM device associated with a modesetting object). StaticModesetObject is a supertrait of ModesetObject which essentially marks a modesetting object as not having a refcount. We then provide KmsRef<T> which can be used to retrieve a "owned" reference to a modesetting object which can be stored in device state. This owned reference is simply a pointer to the modesetting object, along with an owned refcount for that object's parent device - which should ensure that the modesetting object is initialized and valid for as long as a KmsRef<> is held. I'm open for better ideas to solve this though :).

# BFLs

Unfortunately KMS has a few BFLs. In particular, drm_device.mode_config.mutex is one such BFL that protects anything related to hotplugging state (and probably a few other things?). In rust, data races are considered UB - so we need to be careful to ensure that any safe bindings we expose take care to be thread safe. Since rust usually represents locks as container types (e.g. Mutex<T>), but we have to deal with a BFL, we need a different solution that we can use to represent critical sections under this BFL. This brings us to ModeConfigGuard and ConnectorGuard.

In rust, upon acquiring access to a mutex - you're given a "Guard" object which will release its respective lock once its dropped, and ModeConfigGuard is our version of this. ModeConfigGuards can either be "owned" or "borrowed". "Owned" means the rust code acquired the lock itself and thus - the lock must be dropped when the guard goes out of scope. "Borrowed" guards can only be created using unsafe functions, and are basically simply a promise that the mode config lock is held for the entire scope in which the ModeConfigGuard is alive. Borrowed guards are really only something that will be used on the FFI side of things for callbacks like drm_connector.get_modes() - where we know that the mode_config_lock was acquired prior to our get_modes() callback being invoked by DRM.

ConnectorGuard is basically just a helpful extension of this that can be instantiated cheaply from a ModeConfigGuard, and it basically just provides access to methods for individual connectors that can only happen under the mode_config lock. You can see an example of this in rust/kernel/drm/kms/connector.rs and drivers/gpu/drm/rvkms/connector.rs. Keep in mind we currently don't have an implementation of an owned ModeConfigGuard, as no use for one has arisen in rvkms quite yet.

Note: I did (and still am) considering using the kernel's already-made LockedBy<> type - however, this seems rather difficult to do considering that the BFL and connector live in different structs - and those structs are FFI structs. I shoud look a bit closer at some point soon though. As well, I expect the semantics around how this type works might change slightly - as I'd also like to see if we can represent the difference between owned and borrowed guards such that no checks need to be done at runtime.

# Actually registering a modesetting device

This part is still very much in flux I think, and it's worth explaining why. Currently from the DRM bindings we inherited from Asahi, the lifetime of a DRM device's registration is represented by drm::drv::Registration<T>. Unsurprisingly, the purpose of this is that once the Registration<T> object is dropped - the DRM device is unregistered. There's some complications around this though.

The big one is that modesetting initialization is single threaded. This should be fine, but, currently (following how Asahi's driver does this) we ensure automatic reg/unreg by sticking the Registration<T> object in our registration device data (see device::Data<T, U, V> for an explanation of what this means). And that would also be fine, except for the fact that said device data has to be thread safe. This means it needs Send/Sync, which also means we basically have to treat the registration as multi-threaded despite the fact it really should never actually be happening in multiple threads. We also have a RegistrationInfo struct i had to come up with, which provides access to an atomic boolean that tracks whether or not we've actually registered the device. This part was only needed because while DRM does have a variable for tracking this in drm_device already, the Registration<T> object is created before registration actually happens - so it needs a thread-safe way of knowing whether or not it needs to unregister the device upon being dropped.

The other thing I haven't been able to figure out: a way of safely gating global modesetting device functions so that they only can be used on DRM devices that support KMS (an example of one such function - drm_mode_config_reset()). Since the callbacks for modesetting devices and the rest of DRM live in the same struct, the same struct is used for both cases - even though it's entirely possible to have a drm_device without KMS support and thus without an initialized mode_config struct. This would be very nice to figure out, because I assume there's likely to be UB if a non-KMS device attempts to do KMS-like operations on itself. Currently, a modesetting device indicates it has KMS in my branch by doing two things:

* Setting FEAT_MODESET and FEAT_ATOMIC in drm::drv::Driver::FEATURES
* Passing a ModeConfigInfo struct to drm::drv::Registration::register(), containing various misc. information drivers usually populate in mode_config

Figuring out how to gate these to only KMS-supporting devices would likely mean moving the global modesetting callbacks we need to support into a different trait that's only implemented by KMS drivers - but I'm not quite sure how to do that cleanly yet.

# Other issues/hacks

* Currently, a DRM driver's vtable and file operations table are not static. I totally think we can (and should) make this static by making drm::gem::create_fops() a const fn, and also turning DriverOps's constructors into const fns. The current blocker for this is that Default::default() is not const, along with mem::zeroed() - giving us no way of creating a zero-initialized struct at compile-time. Coincidentally, mem::zeroed() actually becomes const in rust 1.75 - so once the kernel updates its rust version we should be able to fix this.
* There is a leak somewhere? Unloading rvkms currently leaves behind a few DRI directories, I'm not totally sure why yet - but I think this may be an issue with the DRM bindings themselves.
* bindgen doesn't understand fourcc, and probably a number of other similar files. So we're going to need some nasty hacks to expose these.
* I'm sure there's bits of code that need cleaning up, but I figured it was more important to start getting feedback on all of this first :).

Lyude Paul (4):
WIP: rust: Add basic KMS bindings
WIP: drm: Introduce rvkms
rust/drm/kms: Extract PlaneState<T> into IntoPlaneState
WIP: rust/drm/kms: Add ShadowPlaneState<T>

 drivers/gpu/drm/Kconfig                  |   2 +
 drivers/gpu/drm/Makefile                 |   1 +
 drivers/gpu/drm/rvkms/Kconfig            |   3 +
 drivers/gpu/drm/rvkms/Makefile           |   1 +
 drivers/gpu/drm/rvkms/connector.rs       |  55 +++
 drivers/gpu/drm/rvkms/crtc.rs            |  40 +++
 drivers/gpu/drm/rvkms/encoder.rs         |  26 ++
 drivers/gpu/drm/rvkms/file.rs            |  22 ++
 drivers/gpu/drm/rvkms/gem.rs             |  32 ++
 drivers/gpu/drm/rvkms/output.rs          |  72 ++++
 drivers/gpu/drm/rvkms/plane.rs           |  42 +++
 drivers/gpu/drm/rvkms/rvkms.rs           | 146 ++++++++
 rust/bindings/bindings_helper.h          |   6 +
 rust/helpers.c                           |  17 +
 rust/kernel/drm/device.rs                |   2 +
 rust/kernel/drm/drv.rs                   | 115 ++++++-
 rust/kernel/drm/kms.rs                   | 147 +++++++++
 rust/kernel/drm/kms/connector.rs         | 404 +++++++++++++++++++++++
 rust/kernel/drm/kms/crtc.rs              | 300 +++++++++++++++++
 rust/kernel/drm/kms/encoder.rs           | 175 ++++++++++
 rust/kernel/drm/kms/gem_atomic_helper.rs |  48 +++
 rust/kernel/drm/kms/plane.rs             | 339 +++++++++++++++++++
 rust/kernel/drm/mod.rs                   |   1 +
 23 files changed, 1980 insertions(+), 16 deletions(-)
 create mode 100644 drivers/gpu/drm/rvkms/Kconfig
 create mode 100644 drivers/gpu/drm/rvkms/Makefile
 create mode 100644 drivers/gpu/drm/rvkms/connector.rs
 create mode 100644 drivers/gpu/drm/rvkms/crtc.rs
 create mode 100644 drivers/gpu/drm/rvkms/encoder.rs
 create mode 100644 drivers/gpu/drm/rvkms/file.rs
 create mode 100644 drivers/gpu/drm/rvkms/gem.rs
 create mode 100644 drivers/gpu/drm/rvkms/output.rs
 create mode 100644 drivers/gpu/drm/rvkms/plane.rs
 create mode 100644 drivers/gpu/drm/rvkms/rvkms.rs
 create mode 100644 rust/kernel/drm/kms.rs
 create mode 100644 rust/kernel/drm/kms/connector.rs
 create mode 100644 rust/kernel/drm/kms/crtc.rs
 create mode 100644 rust/kernel/drm/kms/encoder.rs
 create mode 100644 rust/kernel/drm/kms/gem_atomic_helper.rs
 create mode 100644 rust/kernel/drm/kms/plane.rs
Signature · 1 line
2.43.0
author
#1 lore raw

PATCH 1/4 WIP: rust: Add basic KMS bindings

---
 rust/bindings/bindings_helper.h  |   4 +
 rust/helpers.c                   |  17 ++
 rust/kernel/drm/device.rs        |   2 +
 rust/kernel/drm/drv.rs           | 115 +++++++--
 rust/kernel/drm/kms.rs           | 146 +++++++++++
 rust/kernel/drm/kms/connector.rs | 404 +++++++++++++++++++++++++++++++
 rust/kernel/drm/kms/crtc.rs      | 300 +++++++++++++++++++++++
 rust/kernel/drm/kms/encoder.rs   | 175 +++++++++++++
 rust/kernel/drm/kms/plane.rs     | 300 +++++++++++++++++++++++
 rust/kernel/drm/mod.rs           |   1 +
 10 files changed, 1448 insertions(+), 16 deletions(-)
 create mode 100644 rust/kernel/drm/kms.rs
 create mode 100644 rust/kernel/drm/kms/connector.rs
 create mode 100644 rust/kernel/drm/kms/crtc.rs
 create mode 100644 rust/kernel/drm/kms/encoder.rs
 create mode 100644 rust/kernel/drm/kms/plane.rs
rust/bindings/bindings_helper.h +4 -0
index a712efecdb1a9..5856afbe6e8f6 100644
@@ -6,12 +6,16 @@
  * Sorted alphabetically.
  */
 
+#include <drm/drm_atomic_helper.h>
 #include <drm/drm_device.h>
 #include <drm/drm_drv.h>
+#include <drm/drm_edid.h>
 #include <drm/drm_file.h>
 #include <drm/drm_gem.h>
+#include <drm/drm_gem_framebuffer_helper.h>
 #include <drm/drm_gem_shmem_helper.h>
 #include <drm/drm_ioctl.h>
+#include <drm/drm_probe_helper.h>
 #include <kunit/test.h>
 #include <linux/device.h>
 #include <linux/dma-resv.h>
rust/helpers.c +17 -0
index 69fc66164c785..bf9b299f4597f 100644
@@ -20,6 +20,7 @@
  * Sorted alphabetically.
  */
 
+#include <drm/drm_connector.h>
 #include <drm/drm_gem.h>
 #include <drm/drm_gem_shmem_helper.h>
 #include <kunit/test-bug.h>
@@ -284,6 +285,22 @@ int rust_helper_drm_gem_shmem_object_mmap(struct drm_gem_object *obj, struct vm_
 EXPORT_SYMBOL_GPL(rust_helper_drm_gem_shmem_object_mmap);
 
 #endif
+
+#ifdef CONFIG_DRM_KMS_HELPER
+
+void rust_helper_drm_connector_get(struct drm_connector *connector)
+{
+	drm_connector_get(connector);
+}
+EXPORT_SYMBOL_GPL(rust_helper_drm_connector_get);
+
+void rust_helper_drm_connector_put(struct drm_connector *connector)
+{
+	drm_connector_put(connector);
+}
+EXPORT_SYMBOL_GPL(rust_helper_drm_connector_put);
+
+#endif /* CONFIG_DRM_KMS_HELPER */
 #endif
 
 void rust_helper_pci_set_drvdata(struct pci_dev *pdev, void *data)
rust/kernel/drm/device.rs +2 -0
index 6176e2e879d0b..07bc8ed50eae0 100644
@@ -20,6 +20,8 @@ pub struct Device<T: drm::drv::Driver> {
 }
 
 impl<T: drm::drv::Driver> Device<T> {
+    pub const HAS_KMS: bool = T::FEATURES & drm::drv::FEAT_MODESET != 0;
+
     #[allow(dead_code, clippy::mut_from_ref)]
     pub(crate) unsafe fn raw_mut(&self) -> &mut bindings::drm_device {
         unsafe { &mut *self.drm.get() }
rust/kernel/drm/drv.rs +99 -16

176 lines not on this page · raw message

rust/kernel/drm/kms.rs new file +146 -0

146 lines not on this page · raw message

rust/kernel/drm/kms/connector.rs new file +404 -0

404 lines not on this page · raw message

rust/kernel/drm/kms/crtc.rs new file +300 -0

300 lines not on this page · raw message

rust/kernel/drm/kms/encoder.rs new file +175 -0

175 lines not on this page · raw message

rust/kernel/drm/kms/plane.rs new file +300 -0

300 lines not on this page · raw message

rust/kernel/drm/mod.rs +1 -0
index 2c12dbd181997..049ae675cb9b1 100644
@@ -8,3 +8,4 @@
 pub mod fourcc;
 pub mod gem;
 pub mod ioctl;
+pub mod kms;
Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH 1/4] WIP: rust: Add basic KMS bindings

Hi,

I just took a quick look and commented on the things that stuck out to me. Some general things:
- several unsafe blocks have missing SAFETY comments,
- missing documentation and examples.

Quoted 13 lines · Lyude Paul
---
 rust/bindings/bindings_helper.h  |   4 +
 rust/helpers.c                   |  17 ++
 rust/kernel/drm/device.rs        |   2 +
 rust/kernel/drm/drv.rs           | 115 +++++++--
 rust/kernel/drm/kms.rs           | 146 +++++++++++
 rust/kernel/drm/kms/connector.rs | 404 +++++++++++++++++++++++++++++++
 rust/kernel/drm/kms/crtc.rs      | 300 +++++++++++++++++++++++
 rust/kernel/drm/kms/encoder.rs   | 175 +++++++++++++
 rust/kernel/drm/kms/plane.rs     | 300 +++++++++++++++++++++++
 rust/kernel/drm/mod.rs           |   1 +
 10 files changed, 1448 insertions(+), 16 deletions(-)

Please try to break this up into smaller patches. It makes review a lot easier!

[...]

Quoted 33 lines
rust/kernel/drm/kms.rs new file +27 -0
new file mode 100644
index 0000000000000..b55d14415367a
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: GPL-2.0 OR MIT
+
+//! KMS driver abstractions for rust.
+
+pub mod connector;
+pub mod crtc;
+pub mod encoder;
+pub mod plane;
+
+use crate::{
+    drm::{drv, device::Device},
+    prelude::*,
+    types::ARef,
+    private::Sealed
+};
+use core::{
+    ops::Deref,
+    ptr,
+};
+use bindings;
+
+#[derive(Copy, Clone)]
+pub struct ModeConfigInfo {
+    /// The minimum (w, h) resolution this driver can support
+    pub min_resolution: (i32, i32),
+    /// The maximum (w, h) resolution this driver can support
+    pub max_resolution: (i32, i32),

rust/kernel/drm/kms.rs line 37

Quoted 10 lines
rust/kernel/drm/kms.rs new file +10 -0
+    /// The maximum (w, h) cursor size this driver can support
+    pub max_cursor: (u32, u32),
+    /// The preferred depth for dumb ioctls
+    pub preferred_depth: u32,
+}
+
+// TODO: I am not totally sure about this. Ideally, I'd like a nice way of hiding KMS-specific
+// functions for DRM drivers which don't implement KMS - so that we don't have to have a bunch of
+// random modesetting functions all over the DRM device trait. But, unfortunately I don't know of
+// any nice way of doing that yet :(

I don't follow, can't you put the KMS specific functions into the KmsDriver trait?

Quoted 20 lines
rust/kernel/drm/kms.rs new file +20 -0
+
+/// An atomic KMS driver implementation
+pub trait KmsDriver: drv::Driver { }
+
+impl<T: KmsDriver> Device<T> {
+    pub fn mode_config_reset(&self) {
+        // SAFETY: The previous build assertion ensures this can only be called for devices with KMS
+        // support, which means mode_config is initialized
+        unsafe { bindings::drm_mode_config_reset(self.drm.get()) }
+    }
+}
+
+/// Main trait for a modesetting object in DRM
+pub trait ModeObject: Sealed + Send + Sync {
+    /// The parent driver for this ModeObject
+    type Driver: KmsDriver;
+
+    /// Return the `drv::Device` for this `ModeObject`
+    fn drm_dev(&self) -> &Device<Self::Driver>;
+}

[...]

Quoted 59 lines
rust/kernel/drm/kms/connector.rs new file +53 -0
new file mode 100644
index 0000000000000..88dfa946d306b
@@ -0,0 +1,404 @@
+// SPDX-License-Identifier: GPL-2.0 OR MIT
+
+//! Rust bindings for DRM connectors
+
+use crate::{
+    bindings,
+    sync::ArcBorrow,
+    drm::{
+        drv::{Driver, FEAT_MODESET},
+        device::Device,
+    },
+    types::{AlwaysRefCounted, Opaque, ARef},
+    prelude::*,
+    init::Zeroable,
+    error::{to_result, from_result},
+    build_error,
+};
+use core::{
+    marker::PhantomPinned,
+    ptr::null_mut,
+    mem,
+    ptr::{self, NonNull},
+    ffi::*,
+    ops::Deref,
+};
+use super::{
+    ModeObject,
+    ModeConfigGuard,
+    encoder::{Encoder, DriverEncoder},
+    KmsDriver,
+};
+use macros::pin_data;
+
+// XXX: This is :\, figure out a better way at some point?
+pub use bindings::{
+    DRM_MODE_CONNECTOR_Unknown,
+    DRM_MODE_CONNECTOR_VGA,
+    DRM_MODE_CONNECTOR_DVII,
+    DRM_MODE_CONNECTOR_DVID,
+    DRM_MODE_CONNECTOR_DVIA,
+    DRM_MODE_CONNECTOR_Composite,
+    DRM_MODE_CONNECTOR_SVIDEO,
+    DRM_MODE_CONNECTOR_LVDS,
+    DRM_MODE_CONNECTOR_Component,
+    DRM_MODE_CONNECTOR_9PinDIN,
+    DRM_MODE_CONNECTOR_DisplayPort,
+    DRM_MODE_CONNECTOR_HDMIA,
+    DRM_MODE_CONNECTOR_HDMIB,
+    DRM_MODE_CONNECTOR_TV,
+    DRM_MODE_CONNECTOR_eDP,
+    DRM_MODE_CONNECTOR_VIRTUAL,
+    DRM_MODE_CONNECTOR_DSI,
+    DRM_MODE_CONNECTOR_DPI,

rust/kernel/drm/kms/connector.rs line 63

Quoted 10 lines
rust/kernel/drm/kms/connector.rs new file +10 -0
+    DRM_MODE_CONNECTOR_WRITEBACK,
+    DRM_MODE_CONNECTOR_SPI,
+    DRM_MODE_CONNECTOR_USB,
+};
+
+/// A DRM connector implementation
+pub trait DriverConnector: Send + Sync + Sized {
+    /// The return type of the new() function. Should be `impl PinInit<Self, Error>`.
+    /// TODO: Remove this when return_position_impl_trait_in_trait is stable.
+    type Initializer: PinInit<Self, Error>;

This has been stabilized in 1.75.0, so now you should be able to write

     fn new(dev: &Device<Self::Driver>, args: Self::Args) -> impl PinInit<Self, Error>;
Quoted 20 lines
rust/kernel/drm/kms/connector.rs new file +20 -0
+
+    /// The data type to use for passing incoming arguments for new `Connector<T>` instances
+    /// Drivers which don't care about this can just use `()`
+    type Args;
+
+    /// The parent driver for this DRM connector implementation
+    type Driver: KmsDriver;
+
+    /// The atomic state implementation for this DRM connector implementation
+    type State: DriverConnectorState;
+
+    /// Create a new instance of the private driver data struct for this connector in-place
+    fn new(dev: &Device<Self::Driver>, args: Self::Args) -> Self::Initializer;
+
+    /// Retrieve a list of available display modes for this connector
+    fn get_modes<'a>(
+        connector: ConnectorGuard<'a, Self>,
+        guard: &ModeConfigGuard<'a, Self::Driver>
+    ) -> i32;
+}

[...]

Quoted 35 lines
rust/kernel/drm/kms/crtc.rs new file +29 -0
new file mode 100644
index 0000000000000..3d072028a4884
@@ -0,0 +1,300 @@
+// SPDX-License-Identifier: GPL-2.0 OR MIT
+
+//! KMS driver abstractions for rust.
+
+use super::{
+    plane::*,
+    ModeObject,
+    StaticModeObject,
+    KmsDriver
+};
+use crate::{
+    bindings,
+    drm::{drv::Driver, device::Device},
+    device,
+    prelude::*,
+    types::Opaque,
+    init::Zeroable,
+    sync::Arc,
+    error::to_result,
+};
+use core::{
+    cell::UnsafeCell,
+    marker::PhantomPinned,
+    ptr::{null, null_mut},
+    ops::Deref,
+};
+use macros::vtable;
+
+/// A typed KMS CRTC with a specific driver.

rust/kernel/drm/kms/crtc.rs line 39

Quoted 10 lines
rust/kernel/drm/kms/crtc.rs new file +10 -0
+#[repr(C)]
+#[pin_data]
+pub struct Crtc<T: DriverCrtc> {
+    // The FFI drm_crtc object
+    pub(super) crtc: Opaque<bindings::drm_crtc>,
+    /// The driver's private inner data
+    #[pin]
+    inner: T,
+    #[pin]
+    _p: PhantomPinned,

Instead of adding this field, you can mark the crtc field above as #[pin]. This is because of 0b4e3b6f6b79 ("rust: types: make Opaque be !Unpin").

Signature · 2 lines
Cheers,
Benno
Quoted 21 lines
rust/kernel/drm/kms/crtc.rs new file +21 -0
+}
+
+/// KMS CRTC object functions, which must be implemented by drivers.
+pub trait DriverCrtc: Send + Sync + Sized {
+    /// The return type of the new() function. Should be `impl PinInit<Self, Error>`.
+    /// TODO: Remove this when return_position_impl_trait_in_trait is stable.
+    type Initializer: PinInit<Self, Error>;
+
+    /// The data type to use for passing incoming arguments for new `Crtc<T>` instances
+    /// Drivers which don't care about this can just use `()`
+    type Args;
+
+    /// The parent driver implementation
+    type Driver: KmsDriver;
+
+    /// The type for this driver's drm_crtc_state implementation
+    type State: DriverCrtcState;
+
+    /// Create a new CRTC for this driver
+    fn new(device: &Device<Self::Driver>, args: Self::Args) -> Self::Initializer;
+}
author
#3 lore raw

Re: [PATCH 1/4] WIP: rust: Add basic KMS bindings

Quoted 6 lines · Benno Lossin

Hi,

I just took a quick look and commented on the things that stuck out to me. Some general things:
- several unsafe blocks have missing SAFETY comments,
- missing documentation and examples.

This is really early on - so I had wanted to post a WIP before I actually wrote up everything to make sure I'm going in the right direction (I'm certainly not planning on leaving things undocumented when this is actually ready for submission :).

Quoted 17 lines · Lyude Paul
Quoted 13 lines

---
 rust/bindings/bindings_helper.h  |   4 + rust/helpers.c                   |  17 ++ rust/kernel/drm/device.rs        |   2 + rust/kernel/drm/drv.rs           | 115 +++++++-- rust/kernel/drm/kms.rs           | 146 +++++++++++ rust/kernel/drm/kms/connector.rs | 404
+++++++++++++++++++++++++++++++
 rust/kernel/drm/kms/crtc.rs      | 300 +++++++++++++++++++++++ rust/kernel/drm/kms/encoder.rs   | 175 +++++++++++++ rust/kernel/drm/kms/plane.rs     | 300 +++++++++++++++++++++++ rust/kernel/drm/mod.rs           |   1 +

Quoted 1 line
 10 files changed, 1448 insertions(+), 16 deletions(-)
Quoted 2 lines

Please try to break this up into smaller patches. It makes review a lot easier!

I'll definitely try to do that next time!

Quoted 44 lines

[...]

Quoted 41 lines
rust/kernel/drm/kms.rs new file +34 -0
new file mode 100644
index 0000000000000..b55d14415367a
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: GPL-2.0 OR MIT
+
+//! KMS driver abstractions for rust.
+
+pub mod connector;
+pub mod crtc;
+pub mod encoder;
+pub mod plane;
+
+use crate::{
+    drm::{drv, device::Device},
+    prelude::*,
+    types::ARef,
+    private::Sealed
+};
+use core::{
+    ops::Deref,
+    ptr,
+};
+use bindings;
+
+#[derive(Copy, Clone)]
+pub struct ModeConfigInfo {
+    /// The minimum (w, h) resolution this driver can support
+    pub min_resolution: (i32, i32),
+    /// The maximum (w, h) resolution this driver can support
+    pub max_resolution: (i32, i32),
+    /// The maximum (w, h) cursor size this driver can support
+    pub max_cursor: (u32, u32),
+    /// The preferred depth for dumb ioctls
+    pub preferred_depth: u32,
+}
+
+// TODO: I am not totally sure about this. Ideally, I'd like a

nice way of hiding KMS-specific

Quoted 8 lines
Quoted 5 lines

+// functions for DRM drivers which don't implement KMS - so that we don't have to have a bunch of
+// random modesetting functions all over the DRM device trait. But, unfortunately I don't know of
+// any nice way of doing that yet :(

I don't follow, can't you put the KMS specific functions into the KmsDriver trait?

I can, lol. I realized how that would work a little while after writing this, so I'm not quite sure where my confusion was with this - so I'll fix this on the next version I send out.

Quoted 101 lines
Quoted 22 lines
rust/kernel/drm/kms.rs new file +7 -0
+
+/// An atomic KMS driver implementation
+pub trait KmsDriver: drv::Driver { }
+
+impl<T: KmsDriver> Device<T> {
+    pub fn mode_config_reset(&self) {
+        // SAFETY: The previous build assertion ensures this can

only be called for devices with KMS
+        // support, which means mode_config is initialized +        unsafe { bindings::drm_mode_config_reset(self.drm.get()) } +    }

rust/kernel/drm/kms.rs new file +10 -0
+}
+
+/// Main trait for a modesetting object in DRM
+pub trait ModeObject: Sealed + Send + Sync {
+    /// The parent driver for this ModeObject
+    type Driver: KmsDriver;
+
+    /// Return the `drv::Device` for this `ModeObject`
+    fn drm_dev(&self) -> &Device<Self::Driver>;
+}

[...]

Quoted 68 lines
rust/kernel/drm/kms/connector.rs new file +61 -0
new file mode 100644
index 0000000000000..88dfa946d306b
@@ -0,0 +1,404 @@
+// SPDX-License-Identifier: GPL-2.0 OR MIT
+
+//! Rust bindings for DRM connectors
+
+use crate::{
+    bindings,
+    sync::ArcBorrow,
+    drm::{
+        drv::{Driver, FEAT_MODESET},
+        device::Device,
+    },
+    types::{AlwaysRefCounted, Opaque, ARef},
+    prelude::*,
+    init::Zeroable,
+    error::{to_result, from_result},
+    build_error,
+};
+use core::{
+    marker::PhantomPinned,
+    ptr::null_mut,
+    mem,
+    ptr::{self, NonNull},
+    ffi::*,
+    ops::Deref,
+};
+use super::{
+    ModeObject,
+    ModeConfigGuard,
+    encoder::{Encoder, DriverEncoder},
+    KmsDriver,
+};
+use macros::pin_data;
+
+// XXX: This is :\, figure out a better way at some point?
+pub use bindings::{
+    DRM_MODE_CONNECTOR_Unknown,
+    DRM_MODE_CONNECTOR_VGA,
+    DRM_MODE_CONNECTOR_DVII,
+    DRM_MODE_CONNECTOR_DVID,
+    DRM_MODE_CONNECTOR_DVIA,
+    DRM_MODE_CONNECTOR_Composite,
+    DRM_MODE_CONNECTOR_SVIDEO,
+    DRM_MODE_CONNECTOR_LVDS,
+    DRM_MODE_CONNECTOR_Component,
+    DRM_MODE_CONNECTOR_9PinDIN,
+    DRM_MODE_CONNECTOR_DisplayPort,
+    DRM_MODE_CONNECTOR_HDMIA,
+    DRM_MODE_CONNECTOR_HDMIB,
+    DRM_MODE_CONNECTOR_TV,
+    DRM_MODE_CONNECTOR_eDP,
+    DRM_MODE_CONNECTOR_VIRTUAL,
+    DRM_MODE_CONNECTOR_DSI,
+    DRM_MODE_CONNECTOR_DPI,
+    DRM_MODE_CONNECTOR_WRITEBACK,
+    DRM_MODE_CONNECTOR_SPI,
+    DRM_MODE_CONNECTOR_USB,
+};
+
+/// A DRM connector implementation
+pub trait DriverConnector: Send + Sync + Sized {
+    /// The return type of the new() function. Should be `impl
Quoted 4 lines

PinInit<Self, Error>`.
+    /// TODO: Remove this when return_position_impl_trait_in_trait is stable.
+    type Initializer: PinInit<Self, Error>;

This has been stabilized in 1.75.0, so now you should be able to write

Quoted 2 lines

     fn new(dev: &Device<Self::Driver>, args: Self::Args) -> impl PinInit<Self, Error>;

Ack for this and the below comment as well!

Quoted 81 lines
Quoted 26 lines

+
+    /// The data type to use for passing incoming arguments for new Connector<T> instances
+    /// Drivers which don't care about this can just use () +    type Args;

rust/kernel/drm/kms/connector.rs new file +5 -0
+
+    /// The parent driver for this DRM connector implementation
+    type Driver: KmsDriver;
+
+    /// The atomic state implementation for this DRM connector

implementation
+    type State: DriverConnectorState;
+
+    /// Create a new instance of the private driver data struct for this connector in-place
+    fn new(dev: &Device<Self::Driver>, args: Self::Args) -> Self::Initializer;
+
+    /// Retrieve a list of available display modes for this connector
+    fn get_modes<'a>(
+        connector: ConnectorGuard<'a, Self>,
+        guard: &ModeConfigGuard<'a, Self::Driver>
+    ) -> i32;
+}

[...]

Quoted 36 lines
rust/kernel/drm/kms/crtc.rs new file +29 -0
new file mode 100644
index 0000000000000..3d072028a4884
@@ -0,0 +1,300 @@
+// SPDX-License-Identifier: GPL-2.0 OR MIT
+
+//! KMS driver abstractions for rust.
+
+use super::{
+    plane::*,
+    ModeObject,
+    StaticModeObject,
+    KmsDriver
+};
+use crate::{
+    bindings,
+    drm::{drv::Driver, device::Device},
+    device,
+    prelude::*,
+    types::Opaque,
+    init::Zeroable,
+    sync::Arc,
+    error::to_result,
+};
+use core::{
+    cell::UnsafeCell,
+    marker::PhantomPinned,
+    ptr::{null, null_mut},
+    ops::Deref,
+};
+use macros::vtable;
+
+/// A typed KMS CRTC with a specific driver.

rust/kernel/drm/kms/crtc.rs line 39

Quoted 10 lines
rust/kernel/drm/kms/crtc.rs new file +10 -0
+#[repr(C)]
+#[pin_data]
+pub struct Crtc<T: DriverCrtc> {
+    // The FFI drm_crtc object
+    pub(super) crtc: Opaque<bindings::drm_crtc>,
+    /// The driver's private inner data
+    #[pin]
+    inner: T,
+    #[pin]
+    _p: PhantomPinned,

Instead of adding this field, you can mark the crtc field above as #[pin]. This is because of 0b4e3b6f6b79 ("rust: types: make Opaque
be !Unpin").

Signature · 3 lines
Cheers,
 Lyude Paul (she/her)
 Software Engineer at Red Hat
#4 lore raw

Re: [PATCH 1/4] WIP: rust: Add basic KMS bindings

Quoted 8 lines · Lyude Paul
Quoted 6 lines · Benno Lossin

Hi,

I just took a quick look and commented on the things that stuck out to me. Some general things:
- several unsafe blocks have missing SAFETY comments,
- missing documentation and examples.

Quoted 4 lines

This is really early on - so I had wanted to post a WIP before I actually wrote up everything to make sure I'm going in the right direction (I'm certainly not planning on leaving things undocumented when this is actually ready for submission :).

No worries, I just wanted to point out everything that I found.

One thing that I missed was your "RFC WIP" in your cover letter. I think that it's a good idea to put "RFC" onto every patch, that way people without context immediately know that it is not yet ready.

Signature · 2 lines
Cheers,
Benno
author
#5 lore raw

PATCH 2/4 WIP: drm: Introduce rvkms

In reply to Lyude Paul

This introduces a work in progress port of the VKMS driver to rust to provide a user of the kernel's new rust bindings for KMS drivers! This driver is very incomplete, I'm not even sure if it loads right now without crashing (but it did at one point, and I'll be checking very soon!).

Squash into rvkms introduction

---
 drivers/gpu/drm/Kconfig            |   2 +
 drivers/gpu/drm/Makefile           |   1 +
 drivers/gpu/drm/rvkms/Kconfig      |   3 +
 drivers/gpu/drm/rvkms/Makefile     |   1 +
 drivers/gpu/drm/rvkms/connector.rs |  55 +++++++++++
 drivers/gpu/drm/rvkms/crtc.rs      |  40 ++++++++
 drivers/gpu/drm/rvkms/encoder.rs   |  26 +++++
 drivers/gpu/drm/rvkms/file.rs      |  22 +++++
 drivers/gpu/drm/rvkms/gem.rs       |  32 +++++++
 drivers/gpu/drm/rvkms/output.rs    |  72 ++++++++++++++
 drivers/gpu/drm/rvkms/plane.rs     |  39 ++++++++
 drivers/gpu/drm/rvkms/rvkms.rs     | 146 +++++++++++++++++++++++++++++
 12 files changed, 439 insertions(+)
 create mode 100644 drivers/gpu/drm/rvkms/Kconfig
 create mode 100644 drivers/gpu/drm/rvkms/Makefile
 create mode 100644 drivers/gpu/drm/rvkms/connector.rs
 create mode 100644 drivers/gpu/drm/rvkms/crtc.rs
 create mode 100644 drivers/gpu/drm/rvkms/encoder.rs
 create mode 100644 drivers/gpu/drm/rvkms/file.rs
 create mode 100644 drivers/gpu/drm/rvkms/gem.rs
 create mode 100644 drivers/gpu/drm/rvkms/output.rs
 create mode 100644 drivers/gpu/drm/rvkms/plane.rs
 create mode 100644 drivers/gpu/drm/rvkms/rvkms.rs
drivers/gpu/drm/Kconfig +2 -0
index c7edba18a6f09..48c140f943356 100644
@@ -275,6 +275,8 @@ source "drivers/gpu/drm/amd/amdgpu/Kconfig"
 
 source "drivers/gpu/drm/nouveau/Kconfig"
 
+source "drivers/gpu/drm/rvkms/Kconfig"
+
 source "drivers/gpu/drm/i915/Kconfig"
 
 source "drivers/gpu/drm/xe/Kconfig"
drivers/gpu/drm/Makefile +1 -0
index 104b42df2e956..91a18c8290fa4 100644
@@ -143,6 +143,7 @@ obj-$(CONFIG_DRM_VMWGFX)+= vmwgfx/
 obj-$(CONFIG_DRM_VGEM)	+= vgem/
 obj-$(CONFIG_DRM_VKMS)	+= vkms/
 obj-$(CONFIG_DRM_NOUVEAU) +=nouveau/
+obj-$(CONFIG_DRM_RVKMS) += rvkms/
 obj-$(CONFIG_DRM_EXYNOS) +=exynos/
 obj-$(CONFIG_DRM_ROCKCHIP) +=rockchip/
 obj-$(CONFIG_DRM_GMA500) += gma500/
drivers/gpu/drm/rvkms/Kconfig new file +3 -0
new file mode 100644
index 0000000000000..d888aa4ffc84c
@@ -0,0 +1,3 @@
+config DRM_RVKMS
+        tristate "Rust VKMS PoC driver (EXPERIMENTAL)"
+        depends on RUST && DRM && DRM_GEM_SHMEM_HELPER
drivers/gpu/drm/rvkms/Makefile new file +1 -0
new file mode 100644
index 0000000000000..18e06fc3343c6
@@ -0,0 +1 @@
+obj-$(CONFIG_DRM_RVKMS) += rvkms.o
drivers/gpu/drm/rvkms/connector.rs new file +55 -0

55 lines not on this page · raw message

drivers/gpu/drm/rvkms/crtc.rs new file +40 -0
new file mode 100644
index 0000000000000..2998f288b88e6
@@ -0,0 +1,40 @@
+// TODO: License and stuff
+// Contain's rvkms's drm_crtc implementation
+use core::marker::PhantomPinned;
+use super::RvkmsDriver;
+use kernel::{
+    prelude::*,
+    drm::{
+        device::Device,
+        kms::crtc,
+    },
+};
+
+pub(crate) type Crtc = crtc::Crtc<DriverCrtc>;
+
+#[pin_data]
+pub(crate) struct DriverCrtc {
+    #[pin]
+    _p: PhantomPinned
+}
+
+impl crtc::DriverCrtc for DriverCrtc {
+    type Initializer = impl PinInit<Self, Error>;
+
+    type Args = ();
+
+    type State = CrtcState;
+
+    type Driver = RvkmsDriver;
+
+    fn new(device: &Device<Self::Driver>, args: Self::Args) -> Self::Initializer {
+        try_pin_init!(Self { _p: PhantomPinned })
+    }
+}
+
+#[derive(Clone, Default)]
+pub(crate) struct CrtcState;
+
+impl crtc::DriverCrtcState for CrtcState {
+    type Crtc = DriverCrtc;
+}
drivers/gpu/drm/rvkms/encoder.rs new file +26 -0
new file mode 100644
index 0000000000000..72d8b43d9107e
@@ -0,0 +1,26 @@
+use core::marker::PhantomPinned;
+use kernel::{
+    drm::{device::Device, kms},
+    prelude::*
+};
+use crate::RvkmsDriver;
+
+#[pin_data]
+pub(crate) struct DriverEncoder {
+    #[pin]
+    _p: PhantomPinned,
+}
+
+pub(crate) type Encoder = kms::encoder::Encoder<DriverEncoder>;
+
+impl kms::encoder::DriverEncoder for DriverEncoder {
+    type Initializer = impl PinInit<Self, Error>;
+
+    type Driver = RvkmsDriver;
+
+    type Args = ();
+
+    fn new(device: &Device<Self::Driver>, args: Self::Args) -> Self::Initializer {
+        try_pin_init!(Self { _p: PhantomPinned })
+    }
+}
drivers/gpu/drm/rvkms/file.rs new file +22 -0
new file mode 100644
index 0000000000000..24b1b53b78238
@@ -0,0 +1,22 @@
+use super::RvkmsDriver;
+
+use kernel::{
+    drm::{
+        self,
+        device::Device as DrmDevice
+    },
+    prelude::*,
+};
+use core::option::*;
+
+pub(crate) struct File();
+
+impl drm::file::DriverFile for File {
+    type Driver = RvkmsDriver;
+
+    fn open(device: &DrmDevice<Self::Driver>) -> Result<Pin<Box<Self>>> {
+        pr_info!("Someone opened a file! But I do not yet know which one...\n");
+
+        Ok(Box::into_pin(Box::try_new(Self())?))
+    }
+}
drivers/gpu/drm/rvkms/gem.rs new file +32 -0
new file mode 100644
index 0000000000000..b789a1c2170c7
@@ -0,0 +1,32 @@
+use crate::{RvkmsDriver, RvkmsDevice};
+use core::sync::atomic::{AtomicU64, Ordering};
+use kernel::{
+    drm::{self, gem},
+    prelude::*,
+};
+
+static GEM_ID: AtomicU64 = AtomicU64::new(0);
+
+/// GEM Object implementation
+#[pin_data]
+pub(crate) struct DriverObject {
+    /// ID for debugging
+    id: u64,
+}
+
+pub(crate) type Object = gem::shmem::Object<DriverObject>;
+
+impl gem::BaseDriverObject<Object> for DriverObject {
+    type Initializer = impl PinInit<Self, Error>;
+
+    fn new(dev: &RvkmsDevice, size: usize) -> Self::Initializer {
+        let id = GEM_ID.fetch_add(1, Ordering::Relaxed);
+
+        pr_debug!("DriverObject::new id={id}\n");
+        DriverObject { id }
+    }
+}
+
+impl gem::shmem::DriverObject for DriverObject {
+    type Driver = RvkmsDriver;
+}
drivers/gpu/drm/rvkms/output.rs new file +72 -0

72 lines not on this page · raw message

drivers/gpu/drm/rvkms/plane.rs new file +39 -0
new file mode 100644
index 0000000000000..54c4bbda64d8e
@@ -0,0 +1,39 @@
+use core::marker::PhantomPinned;
+use super::RvkmsDriver;
+use kernel::{
+    prelude::*,
+    drm::{
+        device::Device,
+        kms::plane::{self, DriverPlaneState},
+    },
+};
+
+#[pin_data]
+pub(crate) struct DriverPlane {
+    #[pin]
+    _p: PhantomPinned,
+}
+
+pub(crate) type Plane = plane::Plane<DriverPlane>;
+pub(crate) type PlaneState = plane::PlaneState<RvkmsPlaneState>;
+
+impl plane::DriverPlane for DriverPlane {
+    type Initializer = impl PinInit<Self, Error>;
+
+    type State = RvkmsPlaneState;
+
+    type Driver = RvkmsDriver;
+
+    type Args = ();
+
+    fn new(device: &Device<Self::Driver>, args: Self::Args) -> Self::Initializer {
+        try_pin_init!(Self { _p: PhantomPinned })
+    }
+}
+
+#[derive(Clone, Default)]
+pub(crate) struct RvkmsPlaneState;
+
+impl DriverPlaneState for RvkmsPlaneState {
+    type Plane = DriverPlane;
+}
drivers/gpu/drm/rvkms/rvkms.rs new file +146 -0

146 lines not on this page · raw message

Signature · 1 line
2.43.0
#6 lore raw

Re: [PATCH 2/4] WIP: drm: Introduce rvkms

Quoted 18 lines · Lyude Paul
drivers/gpu/drm/rvkms/connector.rs new file +12 -0
new file mode 100644
index 0000000000000..40f84d38437ee
@@ -0,0 +1,55 @@
+// TODO: License and stuff
+// Contain's rvkms's drm_connector implementation
+
+use super::{RvkmsDriver, RvkmsDevice, MAX_RES, DEFAULT_RES};
+use kernel::{
+    prelude::*,
+    drm::{
+        device::Device,
+        kms::{
+            connector::{self, ConnectorGuard},
+            ModeConfigGuard
+        }

drivers/gpu/drm/rvkms/connector.rs line 22

Quoted 10 lines
drivers/gpu/drm/rvkms/connector.rs new file +10 -0
+    },
+    prelude::*
+};
+use core::marker::PhantomPinned;
+
+#[pin_data]
+pub(crate) struct DriverConnector {
+    #[pin]
+    _p: PhantomPinned
+}

This struct does not need to be annotated with #[pin_data], this should just work:

pub(crate) struct DriverConnector;

drivers/gpu/drm/rvkms/connector.rs line 35

Quoted 13 lines
drivers/gpu/drm/rvkms/connector.rs new file +13 -0
+
+pub(crate) type Connector = connector::Connector<DriverConnector>;
+
+impl connector::DriverConnector for DriverConnector {
+    type Initializer = impl PinInit<Self, Error>;
+
+    type State = ConnectorState;
+
+    type Driver = RvkmsDriver;
+
+    type Args = ();
+
+    fn new(dev: &Device<Self::Driver>, args: Self::Args) -> Self::Initializer {

And then here just return Self.

This works, since there is a blanket impl PinInit<T, E> for T.

Looking at how you use this API, I am not sure if you actually need pin-init for the type that implements DriverConnector. Do you need to store eg Mutex<T> or something else that needs pin-init in here in a more complex driver?

Signature · 2 lines
Cheers,
Benno
Quoted 20 lines
drivers/gpu/drm/rvkms/connector.rs new file +20 -0
+        try_pin_init!(Self { _p: PhantomPinned })
+    }
+
+    fn get_modes(
+        connector: ConnectorGuard<'_, Self>,
+        _guard: &ModeConfigGuard<'_, Self::Driver>
+    ) -> i32 {
+        let count = connector.add_modes_noedid(MAX_RES);
+
+        connector.set_preferred_mode(DEFAULT_RES);
+        count
+    }
+}
+
+#[derive(Clone, Default)]
+pub(crate) struct ConnectorState;
+
+impl connector::DriverConnectorState for ConnectorState {
+    type Connector = DriverConnector;
+}
author
#7 lore raw

Re: [PATCH 2/4] WIP: drm: Introduce rvkms

Quoted 53 lines · Benno Lossin
Quoted 19 lines · Lyude Paul
drivers/gpu/drm/rvkms/connector.rs new file +12 -0
new file mode 100644
index 0000000000000..40f84d38437ee
@@ -0,0 +1,55 @@
+// TODO: License and stuff
+// Contain's rvkms's drm_connector implementation
+
+use super::{RvkmsDriver, RvkmsDevice, MAX_RES, DEFAULT_RES};
+use kernel::{
+    prelude::*,
+    drm::{
+        device::Device,
+        kms::{
+            connector::{self, ConnectorGuard},
+            ModeConfigGuard
+        }

drivers/gpu/drm/rvkms/connector.rs line 22

Quoted 10 lines
drivers/gpu/drm/rvkms/connector.rs new file +10 -0
+    },
+    prelude::*
+};
+use core::marker::PhantomPinned;
+
+#[pin_data]
+pub(crate) struct DriverConnector {
+    #[pin]
+    _p: PhantomPinned
+}

This struct does not need to be annotated with #[pin_data], this should just work:

pub(crate) struct DriverConnector;

Quoted 13 lines
drivers/gpu/drm/rvkms/connector.rs new file +13 -0
+
+pub(crate) type Connector = connector::Connector<DriverConnector>;
+
+impl connector::DriverConnector for DriverConnector {
+    type Initializer = impl PinInit<Self, Error>;
+
+    type State = ConnectorState;
+
+    type Driver = RvkmsDriver;
+
+    type Args = ();
+
+    fn new(dev: &Device<Self::Driver>, args: Self::Args) ->
Quoted 1 line

Self::Initializer {

And then here just return Self.

Quoted 6 lines

This works, since there is a blanket impl PinInit<T, E> for T.

Looking at how you use this API, I am not sure if you actually need pin-init for the type that implements DriverConnector. Do you need to store eg Mutex<T> or something else that needs pin-init in here in a more complex driver?

Most likely yes - a lot of drivers have various private locks contained within their subclassed mode objects. I'm not sure we will in rvkms's connector since vkms doesn't really do much with connectors - but we at a minimum be using pinned types (spinlocks and hrtimers) in our DriverCrtc implementation once I've started implementing support for vblanks[1]

[1]
https://www.kernel.org/doc/html/v6.9-rc5/gpu/drm-kms.html?highlight=vblank#vertical-blanking

In nova (the main reason I'm working on rvkms in the first place), we'll definitely have locks in our connectors and possibly other types.

Quoted 1 line
Signature · 3 lines
Cheers,
 Lyude Paul (she/her)
 Software Engineer at Red Hat
#8 lore raw

Re: [PATCH 2/4] WIP: drm: Introduce rvkms

Quoted 33 lines · Lyude Paul
Quoted 18 lines · Benno Lossin
Quoted 13 lines · Lyude Paul
drivers/gpu/drm/rvkms/connector.rs new file +13 -0
+
+pub(crate) type Connector = connector::Connector<DriverConnector>;
+
+impl connector::DriverConnector for DriverConnector {
+    type Initializer = impl PinInit<Self, Error>;
+
+    type State = ConnectorState;
+
+    type Driver = RvkmsDriver;
+
+    type Args = ();
+
+    fn new(dev: &Device<Self::Driver>, args: Self::Args) ->
Quoted 1 line

Self::Initializer {

And then here just return Self.

Quoted 6 lines

This works, since there is a blanket impl PinInit<T, E> for T.

Looking at how you use this API, I am not sure if you actually need pin-init for the type that implements DriverConnector. Do you need to store eg Mutex<T> or something else that needs pin-init in here in a more complex driver?

Most likely yes - a lot of drivers have various private locks contained within their subclassed mode objects. I'm not sure we will in rvkms's connector since vkms doesn't really do much with connectors - but we at a minimum be using pinned types (spinlocks and hrtimers) in our DriverCrtc implementation once I've started implementing support for vblanks[1]

Quoted 5 lines

[1]
https://www.kernel.org/doc/html/v6.9-rc5/gpu/drm-kms.html?highlight=vblank#vertical-blanking

In nova (the main reason I'm working on rvkms in the first place), we'll definitely have locks in our connectors and possibly other types.

I see, in that case it would be a good idea to either have an RFC of the nova driver (or something else that needs pinned types) as motivation for why it needs to be pin-initialized.

Signature · 2 lines
Cheers,
Benno
author
#9 lore raw

Re: [PATCH 2/4] WIP: drm: Introduce rvkms

Quoted 43 lines · Benno Lossin
Quoted 42 lines · Lyude Paul
Quoted 19 lines · Benno Lossin
Quoted 14 lines · Lyude Paul
(quoted diff) +2 -0
+
+pub(crate) type Connector =

connector::Connector<DriverConnector>;

drivers/gpu/drm/rvkms/connector.rs new file +11 -0
+
+impl connector::DriverConnector for DriverConnector {
+    type Initializer = impl PinInit<Self, Error>;
+
+    type State = ConnectorState;
+
+    type Driver = RvkmsDriver;
+
+    type Args = ();
+
+    fn new(dev: &Device<Self::Driver>, args: Self::Args) ->
Quoted 1 line

Self::Initializer {

And then here just return Self.

Quoted 7 lines

This works, since there is a blanket impl PinInit<T, E> for T.

Looking at how you use this API, I am not sure if you actually need
pin-init for the type that implements DriverConnector. Do you need to store eg Mutex<T> or something else that needs pin-init in here in a more complex driver?

Most likely yes - a lot of drivers have various private locks contained
within their subclassed mode objects. I'm not sure we will in rvkms's
connector since vkms doesn't really do much with connectors - but we at
a minimum be using pinned types (spinlocks and hrtimers) in our DriverCrtc implementation once I've started implementing support for
vblanks[1]

[1]
https://www.kernel.org/doc/html/v6.9-rc5/gpu/drm-kms.html?highlight=vblank#vertical-blanking

Quoted 7 lines
Quoted 3 lines

In nova (the main reason I'm working on rvkms in the first place), we'll definitely have locks in our connectors and possibly other types.

I see, in that case it would be a good idea to either have an RFC of the nova driver (or something else that needs pinned types) as motivation for why it needs to be pin-initialized.

I mean - I'll happily include this with the RFC of nova if nova is ready at that point, but the purpose of rvkms is to exercise enough of this API to justify merging it :P - and I think it's a lot likely rvkm is probably going to be ready well before nova gets to the point of modesetting. And we will definitely have some uses of pinned types in rvkms once the driver's ready for submission.

Quoted 1 line
Signature · 3 lines
Cheers,
 Lyude Paul (she/her)
 Software Engineer at Red Hat
author
#10 lore raw

PATCH 3/4 rust/drm/kms: Extract PlaneState<T> into IntoPlaneState

In reply to Lyude Paul

DRM actually has a number of helpers that wrap drm_plane_state, one of which is actually needed by VKMS - drm_shadow_plane_state.

So, let's start preparing to write bindings for this by first extracting PlaneState<T> into the IntoPlaneState trait - which all DRM structs which wrap drm_plane_state will implement. This is basically the same idea as the GEM ops - but for plane states.

---
 drivers/gpu/drm/rvkms/plane.rs |   2 +-
 rust/kernel/drm/kms/plane.rs   | 165 ++++++++++++++++++++-------------
 2 files changed, 103 insertions(+), 64 deletions(-)
drivers/gpu/drm/rvkms/plane.rs +1 -1
index 54c4bbda64d8e..d98a1f7bf79e2 100644
@@ -20,7 +20,7 @@ pub(crate) struct DriverPlane {
 impl plane::DriverPlane for DriverPlane {
     type Initializer = impl PinInit<Self, Error>;
 
-    type State = RvkmsPlaneState;
+    type State = PlaneState;
 
     type Driver = RvkmsDriver;
 
rust/kernel/drm/kms/plane.rs +102 -63

229 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#11 lore raw

PATCH 4/4 WIP: rust/drm/kms: Add ShadowPlaneState<T>

In reply to Lyude Paul
---
 drivers/gpu/drm/rvkms/plane.rs           |  7 +++-
 rust/bindings/bindings_helper.h          |  2 +
 rust/kernel/drm/kms.rs                   |  1 +
 rust/kernel/drm/kms/gem_atomic_helper.rs | 48 ++++++++++++++++++++++++
 4 files changed, 56 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/drm/kms/gem_atomic_helper.rs
drivers/gpu/drm/rvkms/plane.rs +5 -2
index d98a1f7bf79e2..5fb1b63842929 100644
@@ -4,7 +4,10 @@
     prelude::*,
     drm::{
         device::Device,
-        kms::plane::{self, DriverPlaneState},
+        kms::{
+            plane::{self, DriverPlaneState},
+            gem_atomic_helper::ShadowPlaneState,
+        }
     },
 };
 
@@ -15,7 +18,7 @@ pub(crate) struct DriverPlane {
 }
 
 pub(crate) type Plane = plane::Plane<DriverPlane>;
-pub(crate) type PlaneState = plane::PlaneState<RvkmsPlaneState>;
+pub(crate) type PlaneState = ShadowPlaneState<RvkmsPlaneState>;
 
 impl plane::DriverPlane for DriverPlane {
     type Initializer = impl PinInit<Self, Error>;
rust/bindings/bindings_helper.h +2 -0
index 5856afbe6e8f6..73a5eb00e8625 100644
@@ -12,6 +12,8 @@
 #include <drm/drm_edid.h>
 #include <drm/drm_file.h>
 #include <drm/drm_gem.h>
+#include <drm/drm_gem_atomic_helper.h>
+#include <drm/drm_gem_framebuffer_helper.h>
 #include <drm/drm_gem_framebuffer_helper.h>
 #include <drm/drm_gem_shmem_helper.h>
 #include <drm/drm_ioctl.h>
rust/kernel/drm/kms.rs +1 -0
index b55d14415367a..14f4c3842ada0 100644
@@ -6,6 +6,7 @@
 pub mod crtc;
 pub mod encoder;
 pub mod plane;
+pub mod gem_atomic_helper;
 
 use crate::{
     drm::{drv, device::Device},
rust/kernel/drm/kms/gem_atomic_helper.rs new file +48 -0

48 lines not on this page · raw message

Signature · 1 line
2.43.0