Skip to contentSkip to conversation

Rust bindings for gem shmem

PATCH Superseded Lyude Paul 3 participants 19 messages Apr 21 – Apr 27

Subsystems (5)

v12 of 21 Superseded Latest is v21 →

lore
Share & tools
lore

Lyude Paul

author
#0 lore raw

v12 cover Rust bindings for gem shmem

Most of this patch series has already been pushed upstream, this is just the second half of the patch series that has not been pushed yet + some additional changes which were required to implement changes requested by the mailing list. This patch series is originally from Asahi, previously posted by Daniel Almeida.

The previous version of the patch series can be found here:

	https://patchwork.freedesktop.org/series/164580/

Branch with patches applied available here
sure this builds:

https://gitlab.freedesktop.org/lyudess/linux/-/commits/rust/gem-shmem

This patch series applies on top of drm-rust-next

Lyude Paul (5):
rust: drm: gem: s/device::Device/Device/ for shmem.rs drm/gem/shmem: Introduce __drm_gem_shmem_free_sgt_locked() drm/gem/shmem: Export drm_gem_shmem_get_pages_sgt_locked()
rust: drm: gem: Introduce shmem::SGTable
rust: drm: gem: Add vmap functions to shmem bindings

 drivers/gpu/drm/drm_gem_shmem_helper.c |  48 ++-
 include/drm/drm_gem_shmem_helper.h     |   2 +
 rust/kernel/drm/gem/shmem.rs           | 557 ++++++++++++++++++++++++-
 3 files changed, 593 insertions(+), 14 deletions(-)

base-commit: a7a080bb4236ebe577b6776d940d1717912ff6dd

Signature · 1 line
2.53.0
author
#1 lore raw

PATCH v12 1/5 rust: drm: gem: s/device::Device/Device/ for shmem.rs

We're about to start explicitly mentioning kernel devices as well in this file, so this makes it easier to differentiate the two by allowing us to import device as kernel::device.

---
V11:
* Fix location of //

 rust/kernel/drm/gem/shmem.rs | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
rust/kernel/drm/gem/shmem.rs +5 -5
index d025fb0351954..11749c36e8695 100644
@@ -12,10 +12,10 @@
 use crate::{
     container_of,
     drm::{
-        device,
         driver,
         gem,
-        private::Sealed, //
+        private::Sealed,
+        Device, //
     },
     error::to_result,
     prelude::*,
@@ -108,7 +108,7 @@ fn as_raw_shmem(&self) -> *mut bindings::drm_gem_shmem_object {
     ///
     /// Additional config options can be specified using `config`.
     pub fn new(
-        dev: &device::Device<T::Driver>,
+        dev: &Device<T::Driver>,
         size: usize,
         config: ObjectConfig<'_, T>,
         args: T::Args,
@@ -150,9 +150,9 @@ pub fn new(
     }
 
     /// Returns the `Device` that owns this GEM object.
-    pub fn dev(&self) -> &device::Device<T::Driver> {
+    pub fn dev(&self) -> &Device<T::Driver> {
         // SAFETY: `dev` will have been initialized in `Self::new()` by `drm_gem_shmem_init()`.
-        unsafe { device::Device::from_raw((*self.as_raw()).dev) }
+        unsafe { Device::from_raw((*self.as_raw()).dev) }
     }
 
     extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) {
Signature · 1 line
2.53.0
author
#2 lore raw

PATCH v12 2/5 drm/gem/shmem: Introduce __drm_gem_shmem_free_sgt_locked()

In reply to Lyude Paul

One of the complications of trying to use the shmem helpers to create a scatterlist for shmem objects is that we need to be able to provide a guarantee that the driver cannot be unbound for the lifetime of the scatterlist.

The easiest way of handling this seems to be just hooking up an unmap operation to devres the first time we create a scatterlist, which allows us to still take advantage of gem shmem facilities without breaking that guarantee. To allow for this, we extract __drm_gem_shmem_free_sgt_locked()
- which allows a caller (e.g. the rust bindings) to manually unmap the sgt for a gem object as needed.

---
V10:
* Fix incorrect function name in documentation for __drm_gem_shmem_release_sgt_locked()

 drivers/gpu/drm/drm_gem_shmem_helper.c | 32 +++++++++++++++++++++-----
 include/drm/drm_gem_shmem_helper.h     |  1 +
 2 files changed, 27 insertions(+), 6 deletions(-)
drivers/gpu/drm/drm_gem_shmem_helper.c +26 -6
index 4500deef41278..d2c34a0e573a1 100644
@@ -158,6 +158,30 @@ struct drm_gem_shmem_object *drm_gem_shmem_create(struct drm_device *dev, size_t
 }
 EXPORT_SYMBOL_GPL(drm_gem_shmem_create);
 
+/**
+ * __drm_gem_shmem_release_sgt_locked - Unpin and DMA unmap pages, and release the
+ * cached scatter/gather table for an shmem GEM object.
+ * @shmem: shmem GEM object
+ *
+ * If the passed shmem object has an active scatter/gather table for driver
+ * usage, this function will unmap it and release the memory associated with it.
+ * It is the responsibility of the caller to ensure it holds the dma_resv_lock
+ * for this object.
+ *
+ * Drivers should not need to call this function themselves, it is mainly
+ * intended for usage in the Rust shmem bindings.
+ */
+void __drm_gem_shmem_free_sgt_locked(struct drm_gem_shmem_object *shmem)
+{
+	dma_resv_assert_held(shmem->base.resv);
+
+	dma_unmap_sgtable(shmem->base.dev->dev, shmem->sgt, DMA_BIDIRECTIONAL, 0);
+	sg_free_table(shmem->sgt);
+	kfree(shmem->sgt);
+	shmem->sgt = NULL;
+}
+EXPORT_SYMBOL_GPL(__drm_gem_shmem_free_sgt_locked);
+
 /**
  * drm_gem_shmem_release - Release resources associated with a shmem GEM object.
  * @shmem: shmem GEM object
@@ -176,12 +200,8 @@ void drm_gem_shmem_release(struct drm_gem_shmem_object *shmem)
 
 		drm_WARN_ON(obj->dev, refcount_read(&shmem->vmap_use_count));
 
-		if (shmem->sgt) {
-			dma_unmap_sgtable(obj->dev->dev, shmem->sgt,
-					  DMA_BIDIRECTIONAL, 0);
-			sg_free_table(shmem->sgt);
-			kfree(shmem->sgt);
-		}
+		if (shmem->sgt)
+			__drm_gem_shmem_free_sgt_locked(shmem);
 		if (shmem->pages)
 			drm_gem_shmem_put_pages_locked(shmem);
 
include/drm/drm_gem_shmem_helper.h +1 -0
index 5ccdae21b94a9..b2c23af628e1a 100644
@@ -111,6 +111,7 @@ int drm_gem_shmem_init(struct drm_device *dev, struct drm_gem_shmem_object *shme
 struct drm_gem_shmem_object *drm_gem_shmem_create(struct drm_device *dev, size_t size);
 void drm_gem_shmem_release(struct drm_gem_shmem_object *shmem);
 void drm_gem_shmem_free(struct drm_gem_shmem_object *shmem);
+void __drm_gem_shmem_free_sgt_locked(struct drm_gem_shmem_object *shmem);
 
 void drm_gem_shmem_put_pages_locked(struct drm_gem_shmem_object *shmem);
 int drm_gem_shmem_pin(struct drm_gem_shmem_object *shmem);
Signature · 1 line
2.53.0
#3 lore raw

Re: [PATCH v12 2/5] drm/gem/shmem: Introduce __drm_gem_shmem_free_sgt_locked()

Quoted 4 lines · Lyude Paul

+/**
+ * __drm_gem_shmem_release_sgt_locked - Unpin and DMA unmap pages, and release the
+ * cached scatter/gather table for an shmem GEM object.

It appears that I misnamed the function in this somehow still, so I will make note of this and make sure that it gets fixed in the next respin of this series

Quoted 26 lines

+ * @shmem: shmem GEM object
+ *
+ * If the passed shmem object has an active scatter/gather table for driver
+ * usage, this function will unmap it and release the memory associated with it.
+ * It is the responsibility of the caller to ensure it holds the dma_resv_lock
+ * for this object.
+ *
+ * Drivers should not need to call this function themselves, it is mainly
+ * intended for usage in the Rust shmem bindings.
+ */
+void __drm_gem_shmem_free_sgt_locked(struct drm_gem_shmem_object *shmem)

drivers/gpu/drm/drm_gem_shmem_helper.c +4 -0
+{
+	dma_resv_assert_held(shmem->base.resv);
+
+	dma_unmap_sgtable(shmem->base.dev->dev, shmem->sgt,

DMA_BIDIRECTIONAL, 0);

drivers/gpu/drm/drm_gem_shmem_helper.c +5 -0
+	sg_free_table(shmem->sgt);
+	kfree(shmem->sgt);
+	shmem->sgt = NULL;
+}
+EXPORT_SYMBOL_GPL(__drm_gem_shmem_free_sgt_locked);
author
#4 lore raw

PATCH v12 3/5 drm/gem/shmem: Export drm_gem_shmem_get_pages_sgt_locked()

In reply to Lyude Paul

We will need this for implementing a set of SGTable bindings in Rust for gem shmem objects, so that we can use the dma_resv lock to protect additional resources in the shmem object.

---
 drivers/gpu/drm/drm_gem_shmem_helper.c | 16 +++++++++++++++-
 include/drm/drm_gem_shmem_helper.h     |  1 +
 2 files changed, 16 insertions(+), 1 deletion(-)
drivers/gpu/drm/drm_gem_shmem_helper.c +15 -1
index d2c34a0e573a1..8003ede197eba 100644
@@ -786,12 +786,25 @@ struct sg_table *drm_gem_shmem_get_sg_table(struct drm_gem_shmem_object *shmem)
 }
 EXPORT_SYMBOL_GPL(drm_gem_shmem_get_sg_table);
 
-static struct sg_table *drm_gem_shmem_get_pages_sgt_locked(struct drm_gem_shmem_object *shmem)
+/**
+ * drm_gem_shmem_get_pages_sgt_locked - Under dma_resv lock, provide a scatter/gather table of
+ *				        pinned pages for an shmem GEM object.
+ * @shmem: shmem GEM object
+ *
+ * This function is the same as drm_gem_shmem_get_pages_sgt, except that the caller is expected to
+ * already hold the dma_resv lock for @shmem.
+ *
+ * Returns:
+ * A pointer to the scatter/gather table of pinned pages, or error pointer on failure.
+ */
+struct sg_table *drm_gem_shmem_get_pages_sgt_locked(struct drm_gem_shmem_object *shmem)
 {
 	struct drm_gem_object *obj = &shmem->base;
 	int ret;
 	struct sg_table *sgt;
 
+	dma_resv_assert_held(shmem->base.resv);
+
 	if (shmem->sgt)
 		return shmem->sgt;
 
@@ -822,6 +835,7 @@ static struct sg_table *drm_gem_shmem_get_pages_sgt_locked(struct drm_gem_shmem_
 	drm_gem_shmem_put_pages_locked(shmem);
 	return ERR_PTR(ret);
 }
+EXPORT_SYMBOL_GPL(drm_gem_shmem_get_pages_sgt_locked);
 
 /**
  * drm_gem_shmem_get_pages_sgt - Pin pages, dma map them, and return a
include/drm/drm_gem_shmem_helper.h +1 -0
index b2c23af628e1a..682207ce9d1b5 100644
@@ -138,6 +138,7 @@ void drm_gem_shmem_purge_locked(struct drm_gem_shmem_object *shmem);
 
 struct sg_table *drm_gem_shmem_get_sg_table(struct drm_gem_shmem_object *shmem);
 struct sg_table *drm_gem_shmem_get_pages_sgt(struct drm_gem_shmem_object *shmem);
+struct sg_table *drm_gem_shmem_get_pages_sgt_locked(struct drm_gem_shmem_object *shmem);
 
 void drm_gem_shmem_print_info(const struct drm_gem_shmem_object *shmem,
 			      struct drm_printer *p, unsigned int indent);
Signature · 1 line
2.53.0
author
#5 lore raw

PATCH v12 4/5 rust: drm: gem: Introduce shmem::SGTable

In reply to Lyude Paul

In order to do this, we need to be careful to ensure that any interface we expose for scatterlists ensures that any mappings created from one are destroyed on driver-unbind. To do this, we introduce a Devres resource into shmem::Object that we use in order to ensure that we release any SGTable mappings on driver-unbind. We store this in an UnsafeCell and protect access to it using the dma_resv lock that we already have from the shmem gem object, which is the same lock that currently protects drm_gem_object_shmem->sgt.

We also provide two different methods for acquiring an sg table:
self.sg_table(), and self.owned_sg_table(). The first function is for short-term uses of mapped SGTables, the second is for callers that need to hold onto the mapped SGTable for an extended period of time. The second variant uses Devres of course, whereas the first simply relies on rust's borrow checker to prevent driver-unbind when using the mapped SGTable.

---
V3:
* Rename OwnedSGTable to shmem::SGTable. Since the current version of the SGTable abstractions now has a Owned and Borrowed variant, I think renaming this to shmem::SGTable makes things less confusing. We do however, keep the name of owned_sg_table() as-is.
V4:
* Clarify safety comments for SGTable to explain why the object is thread-safe.
* Rename from SGTableRef to SGTable
V10:
* Use Devres in order to ensure that SGTables are revocable, and are unmapped on driver-unbind.
V11:
* s/create_sg_table()/get_sg_table()
* Get rid of extraneous ret = in shmem::Object::get_sg_table() V12:
* Actually move sgt_res in this patch and not the next one

 rust/kernel/drm/gem/shmem.rs | 192 ++++++++++++++++++++++++++++++++++-
 1 file changed, 190 insertions(+), 2 deletions(-)
rust/kernel/drm/gem/shmem.rs +190 -2
index 11749c36e8695..a477312c8a09b 100644
@@ -11,25 +11,38 @@
 
 use crate::{
     container_of,
+    device::{
+        self,
+        Bound, //
+    },
+    devres::*,
     drm::{
         driver,
         gem,
         private::Sealed,
         Device, //
     },
-    error::to_result,
+    error::{
+        from_err_ptr,
+        to_result, //
+    },
     prelude::*,
+    scatterlist,
     types::{
         ARef,
         Opaque, //
     }, //
 };
 use core::{
+    cell::UnsafeCell,
     ops::{
         Deref,
         DerefMut, //
     },
-    ptr::NonNull,
+    ptr::{
+        self,
+        NonNull, //
+    },
 };
 use gem::{
     BaseObjectPrivate,
@@ -61,6 +74,11 @@ pub struct ObjectConfig<'a, T: DriverObject> {
 #[repr(C)]
 #[pin_data]
 pub struct Object<T: DriverObject> {
+    /// Devres object for unmapping any SGTable on driver-unbind.
+    ///
+    /// This is protected by the object's dma_resv lock. It needs to be before `obj` to ensure that
+    /// it is destroyed before `obj` on `Drop`.
+    sgt_res: UnsafeCell<Option<Devres<SGTableMap<T>>>>,
     #[pin]
     obj: Opaque<bindings::drm_gem_shmem_object>,
     /// Parent object that owns this object's DMA reservation object.
@@ -117,6 +135,7 @@ pub fn new(
             try_pin_init!(Self {
                 obj <- Opaque::init_zeroed(),
                 parent_resv_obj: config.parent_resv_obj.map(|p| p.into()),
+                sgt_res: UnsafeCell::new(None),
                 inner <- T::new(dev, size, args),
             }),
             GFP_KERNEL,
@@ -176,6 +195,100 @@ extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) {
         // SAFETY: We're recovering the Kbox<> we created in gem_create_object()
         let _ = unsafe { KBox::from_raw(this) };
     }
+
+    // If necessary, create an SGTable for the gem object and register a Devres for it to ensure
+    // that it is unmapped on driver unbind.
+    fn get_sg_table<'a>(
+        &'a self,
+        dev: &'a device::Device<Bound>,
+    ) -> Result<&'a Devres<SGTableMap<T>>> {
+        let sgt_res_ptr = self.sgt_res.get();
+
+        // SAFETY: This lock is initialized throughout the lifetime of the gem object
+        unsafe { bindings::dma_resv_lock(self.raw_dma_resv(), ptr::null_mut()) };
+
+        // SAFETY: We just grabbed the lock required for reading this data above.
+        let sgt_res = unsafe { (*sgt_res_ptr).as_ref() };
+
+        let ret = if let Some(sgt_res) = sgt_res {
+            // We already have a Devres object for this sg table, return it
+            Ok(sgt_res)
+        } else {
+            // SAFETY: We grabbed the lock required for calling this function above */
+            let sgt = from_err_ptr(unsafe {
+                bindings::drm_gem_shmem_get_pages_sgt_locked(self.as_raw_shmem())
+            });
+
+            if let Err(e) = sgt {
+                Err(e)
+            } else {
+                // INVARIANT:
+                // - We called drm_gem_shmem_get_pages_sgt_locked above and checked that it
+                //   succeeded, fulfilling the invariant of SGTableRef that the object's `sgt` field
+                //   is initialized.
+                // - We store this Devres in the object itself and don't move it, ensuring that the
+                //   object it points to remains valid for the lifetime of the SGTableRef.
+                let devres = Devres::new(dev, init!(SGTableMap { obj: self.into() }));
+                match devres {
+                    Ok(devres) => {
+                        // SAFETY: We acquired the lock protecting this data above, making it safe
+                        // to write into here
+                        unsafe { (*sgt_res_ptr) = Some(devres) };
+
+                        // SAFETY: We just write Some() into *sgt_res_ptr above
+                        Ok(unsafe { (&*sgt_res_ptr).as_ref().unwrap_unchecked() })
+                    }
+                    Err(e) => {
+                        // We can't make sure that the pages for this object are unmapped on
+                        // driver-unbind, so we need to release the sgt
+                        // SAFETY:
+                        // - We grabbed the lock required for calling this function above
+                        // - We checked above that get_pages_sgt_locked() was successful
+                        unsafe { bindings::__drm_gem_shmem_free_sgt_locked(self.as_raw_shmem()) };
+
+                        Err(e)
+                    }
+                }
+            }
+        };
+
+        // SAFETY: We're releasing the lock that we grabbed above.
+        unsafe { bindings::dma_resv_unlock(self.raw_dma_resv()) };
+
+        ret
+    }
+
+    /// Creates (if necessary) and returns an immutable reference to a scatter-gather table of DMA
+    /// pages for this object.
+    ///
+    /// This will pin the object in memory.
+    #[inline]
+    pub fn sg_table<'a>(
+        &'a self,
+        dev: &'a device::Device<Bound>,
+    ) -> Result<&'a scatterlist::SGTable> {
+        let sgt = self.get_sg_table(dev)?;
+
+        Ok(sgt.access(dev)?.deref())
+    }
+
+    /// Creates (if necessary) and returns an owned reference to a scatter-gather table of DMA pages
+    /// for this object.
+    ///
+    /// This is the same as [`sg_table`](Self::sg_table), except that it instead returns an
+    /// [`shmem::SGTable`] which holds a reference to the associated gem object, instead of a
+    /// reference to an [`scatterlist::SGTable`].
+    ///
+    /// This will pin the object in memory.
+    ///
+    /// [`shmem::SGTable`]: SGTable
+    pub fn owned_sg_table(&self, dev: &device::Device<Bound>) -> Result<SGTable<T>> {
+        self.get_sg_table(dev)?;
+
+        // INVARIANT: We just ensured above that `self.sgt_res` is initialized with
+        // `Some(Devres<SGTableMap<T>>)`.
+        Ok(SGTable(self.into()))
+    }
 }
 
 impl<T: DriverObject> Deref for Object<T> {
@@ -226,3 +339,78 @@ impl<T: DriverObject> driver::AllocImpl for Object<T> {
         dumb_map_offset: None,
     };
 }
+
+/// A reference to a GEM object that is known to have a mapped [`SGTable`].
+///
+/// This is used by the Rust bindings with [`Devres`] in order to ensure that mappings for SGTables
+/// on GEM shmem objects are revoked on driver-unbind.
+///
+/// # Invariants
+///
+/// - `self.obj` always points to a valid GEM object.
+/// - This object is proof that `self.0.owner.sgt` has an initialized and valid SGTable.
+pub struct SGTableMap<T: DriverObject> {
+    obj: NonNull<Object<T>>,
+}
+
+impl<T: DriverObject> Deref for SGTableMap<T> {
+    type Target = scatterlist::SGTable;
+
+    fn deref(&self) -> &Self::Target {
+        // SAFETY:
+        // - The NonNull is guaranteed to be valid via our type invariants.
+        // - The sgt field is guaranteed to be initialized and valid via our type invariants.
+        unsafe { scatterlist::SGTable::from_raw((*self.obj.as_ref().as_raw_shmem()).sgt) }
+    }
+}
+
+impl<T: DriverObject> Drop for SGTableMap<T> {
+    fn drop(&mut self) {
+        // SAFETY: `obj` is always valid via our type invariants
+        let obj = unsafe { self.obj.as_ref() };
+
+        // SAFETY: The dma_resv for GEM objects is initialized throughout its lifetime
+        unsafe { bindings::dma_resv_lock(obj.raw_dma_resv(), ptr::null_mut()) };
+
+        // SAFETY: We acquired the lock needed for calling this function above
+        unsafe { bindings::__drm_gem_shmem_free_sgt_locked(obj.as_raw_shmem()) };
+
+        // SAFETY: We are releasing the lock we acquired above.
+        unsafe { bindings::dma_resv_unlock(obj.raw_dma_resv()) };
+    }
+}
+
+// SAFETY: The NonNull in SGTableRef is guaranteed valid by our type invariants, and the GEM object
+// it points to is guaranteed to be thread-safe.
+unsafe impl<T: DriverObject> Send for SGTableMap<T> {}
+// SAFETY: The NonNull in SGTableRef is guaranteed valid by our type invariants, and the GEM object
+// it points to is guaranteed to be thread-safe.
+unsafe impl<T: DriverObject> Sync for SGTableMap<T> {}
+
+/// An owned reference to a scatter-gather table of DMA address spans for a GEM shmem object.
+///
+/// This object holds an owned reference to the underlying GEM shmem object, ensuring that the
+/// [`scatterlist::SGTable`] referenced by this type remains valid for the lifetime of this object.
+///
+/// # Invariants
+///
+/// - This type is proof that `self.0.sgt_res` is initialized with a `Some(Devres<SGTableMap<T>>)`.
+/// - This object is only exposed in situations where we know the underlying `SGTable` will not be
+///   modified for the lifetime of this object. Thus, it is safe to send/access this type across
+///   threads.
+pub struct SGTable<T: DriverObject>(ARef<Object<T>>);
+
+// SAFETY: This object is thread-safe via our type invariants.
+unsafe impl<T: DriverObject> Send for SGTable<T> {}
+// SAFETY: This object is thread-safe via our type invariants.
+unsafe impl<T: DriverObject> Sync for SGTable<T> {}
+
+impl<T: DriverObject> Deref for SGTable<T> {
+    type Target = Devres<SGTableMap<T>>;
+
+    fn deref(&self) -> &Self::Target {
+        // SAFETY: `self.owner.sgt_res` is guaranteed to be initialized with
+        // `Some(Devres<SGTableMap<T>>)` via our type invariants
+        unsafe { (*self.0.sgt_res.get()).as_ref().unwrap_unchecked() }
+    }
+}
Signature · 1 line
2.53.0
#6 lore raw

Re: [PATCH v12 4/5] rust: drm: gem: Introduce shmem::SGTable

Hi Lyude,

Quoted 58 lines · Lyude Paul

In order to do this, we need to be careful to ensure that any interface we expose for scatterlists ensures that any mappings created from one are destroyed on driver-unbind. To do this, we introduce a Devres resource into shmem::Object that we use in order to ensure that we release any SGTable mappings on driver-unbind. We store this in an UnsafeCell and protect access to it using the dma_resv lock that we already have from the shmem gem object, which is the same lock that currently protects drm_gem_object_shmem->sgt.

We also provide two different methods for acquiring an sg table:
self.sg_table(), and self.owned_sg_table(). The first function is for short-term uses of mapped SGTables, the second is for callers that need to hold onto the mapped SGTable for an extended period of time. The second variant uses Devres of course, whereas the first simply relies on rust's borrow checker to prevent driver-unbind when using the mapped SGTable.

---
V3:
* Rename OwnedSGTable to shmem::SGTable. Since the current version of the SGTable abstractions now has a Owned and Borrowed variant, I think renaming this to shmem::SGTable makes things less confusing. We do however, keep the name of owned_sg_table() as-is.
V4:
* Clarify safety comments for SGTable to explain why the object is thread-safe.
* Rename from SGTableRef to SGTable
V10:
* Use Devres in order to ensure that SGTables are revocable, and are unmapped on driver-unbind.
V11:
* s/create_sg_table()/get_sg_table()
* Get rid of extraneous ret = in shmem::Object::get_sg_table() V12:
* Actually move sgt_res in this patch and not the next one

 rust/kernel/drm/gem/shmem.rs | 192 ++++++++++++++++++++++++++++++++++-
 1 file changed, 190 insertions(+), 2 deletions(-)
rust/kernel/drm/gem/shmem.rs +5 -0
index 11749c36e8695..a477312c8a09b 100644
@@ -11,25 +11,38 @@
 
 use crate::{
     container_of,
+    device::{
+        self,
+        Bound, //
+    },
+    devres::*,
     drm::{
         driver,
         gem,
         private::Sealed,
         Device, //

rust/kernel/drm/gem/shmem.rs line 32

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +5 -1
     },
-    error::to_result,
+    error::{
+        from_err_ptr,
+        to_result, //
+    },
     prelude::*,
+    scatterlist,
     types::{
         ARef,

This fails on master:

    error[E0432]: unresolved import `crate::sync::ARef`
      --> ../rust/kernel/drm/gem/shmem.rs:36:5
      |
    36 |     sync::ARef,
      |     ^^^^^^^^^^ no `ARef` in `sync`

Importing sync::aref::ARef seems to be the correct way now.

Quoted 18 lines
rust/kernel/drm/gem/shmem.rs +5 -1
         Opaque, //
     }, //
 };
 use core::{
+    cell::UnsafeCell,
     ops::{
         Deref,
         DerefMut, //
     },
-    ptr::NonNull,
+    ptr::{
+        self,
+        NonNull, //
+    },
 };
 use gem::{
     BaseObjectPrivate,

rust/kernel/drm/gem/shmem.rs pub struct ObjectConfig<'a, T: DriverObject> { · line 81

Quoted 8 lines
rust/kernel/drm/gem/shmem.rs +5 -0
@@ -61,6 +74,11 @@ pub struct ObjectConfig<'a, T: DriverObject> {
 #[repr(C)]
 #[pin_data]
 pub struct Object<T: DriverObject> {
+    /// Devres object for unmapping any SGTable on driver-unbind.
+    ///
+    /// This is protected by the object's dma_resv lock. It needs to be before `obj` to ensure that
+    /// it is destroyed before `obj` on `Drop`.
+    sgt_res: UnsafeCell<Option<Devres<SGTableMap<T>>>>,

I didn't like this UnsafeCell<Option> since the last time, but only figured how to replace it now:

sgt_res: SetOnce<Devres<SGTableMap<T>>>,

It's actually designed for that! And lets you remove at least one unsafe statement, while simplifying get_sg_table quite a bit. With the other suggestions I have below, here is my version of get_sg_table for reference:

    fn get_sg_table<'a>(
        &'a self,
        dev: &'a device::Device<Bound>,
    ) -> Result<&'a Devres<SGTableMap<T>>> {
        let _dma_resv = DmaResvGuard::new(self);

        if let Some(devres) = self.sgt_res.as_ref() {
            Ok(devres)
        } else {
            // Only called for the side-effect of populating the GEM SG table.
            // SAFETY: We grabbed the lock required for calling this function above.
            from_err_ptr(unsafe {
                bindings::drm_gem_shmem_get_pages_sgt_locked(self.as_raw_shmem())
            })?;

            // INVARIANT:
            // - We called drm_gem_shmem_get_pages_sgt_locked above and checked that it
            //   succeeded, fulfilling the invariant of `SGTableMap` that the object's `sgt` field
            //   is initialized.
            // - We store this Devres in the object itself and don't move it, ensuring that the
            //   object it points to remains valid for the lifetime of the `SGTableMap`.
            let devres =
                Devres::new(dev, init!(SGTableMap { obj: self.into() })).inspect_err(|_| {
                    // We can't make sure that the pages for this object are unmapped on
                    // driver-unbind, so we need to release the sgt
                    // SAFETY:
                    // - We grabbed the lock required for calling this function above
                    // - We checked above that get_pages_sgt_locked() was successful
                    unsafe { bindings::__drm_gem_shmem_free_sgt_locked(self.as_raw_shmem()) }
                })?;

            self.sgt_res.populate(devres);

            // PANIC: `populate` has just succeeded, guaranteeing that `sgt_res` is populated.
            Ok(self.sgt_res.as_ref().unwrap())
        }
    }

And if only we could populate the SetOnce with a impl Init<T, E>, then we could even remove the DMA reservation acquisition on the fast path, because SetOnce comes with its own locking and the DMA lock here is used outside of its intended scope. I'll try to push the necessary work for SetOnce and maybe we can do that as a follow-up patch.

Quoted 16 lines
rust/kernel/drm/gem/shmem.rs +2 -0
     #[pin]
     obj: Opaque<bindings::drm_gem_shmem_object>,
     /// Parent object that owns this object's DMA reservation object.
@@ -117,6 +135,7 @@ pub fn new(
             try_pin_init!(Self {
                 obj <- Opaque::init_zeroed(),
                 parent_resv_obj: config.parent_resv_obj.map(|p| p.into()),
+                sgt_res: UnsafeCell::new(None),
                 inner <- T::new(dev, size, args),
             }),
             GFP_KERNEL,
@@ -176,6 +195,100 @@ extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) {
         // SAFETY: We're recovering the Kbox<> we created in gem_create_object()
         let _ = unsafe { KBox::from_raw(this) };
     }
+

rust/kernel/drm/gem/shmem.rs extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) { · line 208

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +10 -0
+    // If necessary, create an SGTable for the gem object and register a Devres for it to ensure
+    // that it is unmapped on driver unbind.
+    fn get_sg_table<'a>(
+        &'a self,
+        dev: &'a device::Device<Bound>,
+    ) -> Result<&'a Devres<SGTableMap<T>>> {
+        let sgt_res_ptr = self.sgt_res.get();
+
+        // SAFETY: This lock is initialized throughout the lifetime of the gem object
+        unsafe { bindings::dma_resv_lock(self.raw_dma_resv(), ptr::null_mut()) };

There are 4 sites where we acquire and release the DMA resv lock, each of which require unsafe blocks and carrying the risk that we forget releasing the lock in the end. For this method in particular we need to jump through hoops a bit and store the return value into a temporary variable so we can unlock the DMA reservation.

Let's do ourselves a favor and implement a small, private guard type:

    struct DmaResvGuard<'a, T: DriverObject>(&'a Object<T>);

    impl<'a, T: DriverObject> DmaResvGuard<'a, T> {
        fn new(object: &'a Object<T>) -> Self {
            // SAFETY: This lock is initialized throughout the lifetime of `object`
            unsafe { bindings::dma_resv_lock(object.raw_dma_resv(), ptr::null_mut()) };

            Self(object)
        }
    }

    impl<'a, T> Drop for DmaResvGuard<'a, T>
    where
        T: DriverObject,
    {
        fn drop(&mut self) {
            // SAFETY: We are releasing the lock grabbed during the creation of this object.
            unsafe { bindings::dma_resv_unlock(self.0.raw_dma_resv()) };
        }
    }

There here you would just do

    let _dma_resv = DmaResvGuard::new(self);

and write the rest of the method without without having to worry about not returning early. It also let's you improve the flow of the code a bit, and requires less unsafe blocks overall.

I am not sure how much of the TODO at the beginning of the file this solves, but it should also make it easier to switch to something that acquires a reference to a Wwmutex.

Quoted 9 lines
rust/kernel/drm/gem/shmem.rs +9 -0
+
+        // SAFETY: We just grabbed the lock required for reading this data above.
+        let sgt_res = unsafe { (*sgt_res_ptr).as_ref() };
+
+        let ret = if let Some(sgt_res) = sgt_res {
+            // We already have a Devres object for this sg table, return it
+            Ok(sgt_res)
+        } else {
+            // SAFETY: We grabbed the lock required for calling this function above */

rust/kernel/drm/gem/shmem.rs extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) { · line 227

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +10 -0
+            let sgt = from_err_ptr(unsafe {
+                bindings::drm_gem_shmem_get_pages_sgt_locked(self.as_raw_shmem())
+            });
+
+            if let Err(e) = sgt {
+                Err(e)
+            } else {
+                // INVARIANT:
+                // - We called drm_gem_shmem_get_pages_sgt_locked above and checked that it
+                //   succeeded, fulfilling the invariant of SGTableRef that the object's `sgt` field

s/SGTableRef/SGTableMap? (several like this through the patch).

Quoted 71 lines
rust/kernel/drm/gem/shmem.rs +64 -0
+                //   is initialized.
+                // - We store this Devres in the object itself and don't move it, ensuring that the
+                //   object it points to remains valid for the lifetime of the SGTableRef.
+                let devres = Devres::new(dev, init!(SGTableMap { obj: self.into() }));
+                match devres {
+                    Ok(devres) => {
+                        // SAFETY: We acquired the lock protecting this data above, making it safe
+                        // to write into here
+                        unsafe { (*sgt_res_ptr) = Some(devres) };
+
+                        // SAFETY: We just write Some() into *sgt_res_ptr above
+                        Ok(unsafe { (&*sgt_res_ptr).as_ref().unwrap_unchecked() })
+                    }
+                    Err(e) => {
+                        // We can't make sure that the pages for this object are unmapped on
+                        // driver-unbind, so we need to release the sgt
+                        // SAFETY:
+                        // - We grabbed the lock required for calling this function above
+                        // - We checked above that get_pages_sgt_locked() was successful
+                        unsafe { bindings::__drm_gem_shmem_free_sgt_locked(self.as_raw_shmem()) };
+
+                        Err(e)
+                    }
+                }
+            }
+        };
+
+        // SAFETY: We're releasing the lock that we grabbed above.
+        unsafe { bindings::dma_resv_unlock(self.raw_dma_resv()) };
+
+        ret
+    }
+
+    /// Creates (if necessary) and returns an immutable reference to a scatter-gather table of DMA
+    /// pages for this object.
+    ///
+    /// This will pin the object in memory.
+    #[inline]
+    pub fn sg_table<'a>(
+        &'a self,
+        dev: &'a device::Device<Bound>,
+    ) -> Result<&'a scatterlist::SGTable> {
+        let sgt = self.get_sg_table(dev)?;
+
+        Ok(sgt.access(dev)?.deref())
+    }
+
+    /// Creates (if necessary) and returns an owned reference to a scatter-gather table of DMA pages
+    /// for this object.
+    ///
+    /// This is the same as [`sg_table`](Self::sg_table), except that it instead returns an
+    /// [`shmem::SGTable`] which holds a reference to the associated gem object, instead of a
+    /// reference to an [`scatterlist::SGTable`].
+    ///
+    /// This will pin the object in memory.
+    ///
+    /// [`shmem::SGTable`]: SGTable
+    pub fn owned_sg_table(&self, dev: &device::Device<Bound>) -> Result<SGTable<T>> {
+        self.get_sg_table(dev)?;
+
+        // INVARIANT: We just ensured above that `self.sgt_res` is initialized with
+        // `Some(Devres<SGTableMap<T>>)`.
+        Ok(SGTable(self.into()))
+    }
 }
 
 impl<T: DriverObject> Deref for Object<T> {
@@ -226,3 +339,78 @@ impl<T: DriverObject> driver::AllocImpl for Object<T> {
         dumb_map_offset: None,
     };
 }

rust/kernel/drm/gem/shmem.rs impl<T: DriverObject> driver::AllocImpl for Object<T> { · line 351

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +10 -0
+
+/// A reference to a GEM object that is known to have a mapped [`SGTable`].
+///
+/// This is used by the Rust bindings with [`Devres`] in order to ensure that mappings for SGTables
+/// on GEM shmem objects are revoked on driver-unbind.
+///
+/// # Invariants
+///
+/// - `self.obj` always points to a valid GEM object.
+/// - This object is proof that `self.0.owner.sgt` has an initialized and valid SGTable.

The comment mentions self.0 and "a valid SGTable", which don't seem to apply to this type.

Quoted 15 lines
rust/kernel/drm/gem/shmem.rs +15 -0
+pub struct SGTableMap<T: DriverObject> {
+    obj: NonNull<Object<T>>,
+}
+
+impl<T: DriverObject> Deref for SGTableMap<T> {
+    type Target = scatterlist::SGTable;
+
+    fn deref(&self) -> &Self::Target {
+        // SAFETY:
+        // - The NonNull is guaranteed to be valid via our type invariants.
+        // - The sgt field is guaranteed to be initialized and valid via our type invariants.
+        unsafe { scatterlist::SGTable::from_raw((*self.obj.as_ref().as_raw_shmem()).sgt) }
+    }
+}
+

rust/kernel/drm/gem/shmem.rs impl<T: DriverObject> driver::AllocImpl for Object<T> { · line 376

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +10 -0
+impl<T: DriverObject> Drop for SGTableMap<T> {
+    fn drop(&mut self) {
+        // SAFETY: `obj` is always valid via our type invariants
+        let obj = unsafe { self.obj.as_ref() };
+
+        // SAFETY: The dma_resv for GEM objects is initialized throughout its lifetime
+        unsafe { bindings::dma_resv_lock(obj.raw_dma_resv(), ptr::null_mut()) };
+
+        // SAFETY: We acquired the lock needed for calling this function above
+        unsafe { bindings::__drm_gem_shmem_free_sgt_locked(obj.as_raw_shmem()) };

For symmetry, I wanted to suggest moving the call to drm_gem_shmem_get_pages_sgt_locked to a (fallible) constructor of SGTableMap.

It's not only for cosmetic and code proximity reasons - once you bind the call to drm_gem_shmem_get_pages_sgt_locked to the successful creation of the SGTableMap object, you can remove the custom error path of get_sg_table that called __drm_gem_shmem_free_sgt_locked if Devres::new failed since the destructor of SGTableMap will now take care of this for us. This simplifies the last complex bit of get_sg_table.

The problem is that it would also normally require SGTableMap::new to acquire the DMA reservation lock in order to call drm_gem_shmem_get_pages_sgt_locked, but we already have it in get_sg_table.

If we stopped using the DMA reservation lock as a lock for population sgt_res and instead switched to a regular Mutex, we could then move the DMA reservation acquisition to the constructor, attain symmetry, and simplify get_sg_table to the point where it becomes trivial. That use is also fragile as the SGTableMap destructor acquires it, so we must be very careful to never drop it in get_sg_table.

I think that would be a good tradeoff for the time until we make SetOnce capable of being populated using an impl Init.

reviewer
#7 lore raw

Re: [PATCH v12 4/5] rust: drm: gem: Introduce shmem::SGTable

Quoted 156 lines · Alexandre Courbot

Hi Lyude,

Quoted 58 lines · Lyude Paul

In order to do this, we need to be careful to ensure that any interface we expose for scatterlists ensures that any mappings created from one are destroyed on driver-unbind. To do this, we introduce a Devres resource into shmem::Object that we use in order to ensure that we release any SGTable mappings on driver-unbind. We store this in an UnsafeCell and protect access to it using the dma_resv lock that we already have from the shmem gem object, which is the same lock that currently protects drm_gem_object_shmem->sgt.

We also provide two different methods for acquiring an sg table:
self.sg_table(), and self.owned_sg_table(). The first function is for short-term uses of mapped SGTables, the second is for callers that need to hold onto the mapped SGTable for an extended period of time. The second variant uses Devres of course, whereas the first simply relies on rust's borrow checker to prevent driver-unbind when using the mapped SGTable.

---
V3:
* Rename OwnedSGTable to shmem::SGTable. Since the current version of the SGTable abstractions now has a Owned and Borrowed variant, I think renaming this to shmem::SGTable makes things less confusing. We do however, keep the name of owned_sg_table() as-is.
V4:
* Clarify safety comments for SGTable to explain why the object is thread-safe.
* Rename from SGTableRef to SGTable
V10:
* Use Devres in order to ensure that SGTables are revocable, and are unmapped on driver-unbind.
V11:
* s/create_sg_table()/get_sg_table()
* Get rid of extraneous ret = in shmem::Object::get_sg_table() V12:
* Actually move sgt_res in this patch and not the next one

 rust/kernel/drm/gem/shmem.rs | 192 ++++++++++++++++++++++++++++++++++-
 1 file changed, 190 insertions(+), 2 deletions(-)
rust/kernel/drm/gem/shmem.rs +5 -0
index 11749c36e8695..a477312c8a09b 100644
@@ -11,25 +11,38 @@
 
 use crate::{
     container_of,
+    device::{
+        self,
+        Bound, //
+    },
+    devres::*,
     drm::{
         driver,
         gem,
         private::Sealed,
         Device, //

rust/kernel/drm/gem/shmem.rs line 32

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +5 -1
     },
-    error::to_result,
+    error::{
+        from_err_ptr,
+        to_result, //
+    },
     prelude::*,
+    scatterlist,
     types::{
         ARef,

This fails on master:

    error[E0432]: unresolved import `crate::sync::ARef`
      --> ../rust/kernel/drm/gem/shmem.rs:36:5
      |
    36 |     sync::ARef,
      |     ^^^^^^^^^^ no `ARef` in `sync`

Importing sync::aref::ARef seems to be the correct way now.

Quoted 18 lines
rust/kernel/drm/gem/shmem.rs +5 -1
         Opaque, //
     }, //
 };
 use core::{
+    cell::UnsafeCell,
     ops::{
         Deref,
         DerefMut, //
     },
-    ptr::NonNull,
+    ptr::{
+        self,
+        NonNull, //
+    },
 };
 use gem::{
     BaseObjectPrivate,

rust/kernel/drm/gem/shmem.rs pub struct ObjectConfig<'a, T: DriverObject> { · line 81

Quoted 8 lines
rust/kernel/drm/gem/shmem.rs +5 -0
@@ -61,6 +74,11 @@ pub struct ObjectConfig<'a, T: DriverObject> {
 #[repr(C)]
 #[pin_data]
 pub struct Object<T: DriverObject> {
+    /// Devres object for unmapping any SGTable on driver-unbind.
+    ///
+    /// This is protected by the object's dma_resv lock. It needs to be before `obj` to ensure that
+    /// it is destroyed before `obj` on `Drop`.
+    sgt_res: UnsafeCell<Option<Devres<SGTableMap<T>>>>,

I didn't like this UnsafeCell<Option> since the last time, but only figured how to replace it now:

sgt_res: SetOnce<Devres<SGTableMap<T>>>,

It's actually designed for that! And lets you remove at least one unsafe statement, while simplifying get_sg_table quite a bit. With the other suggestions I have below, here is my version of get_sg_table for reference:

    fn get_sg_table<'a>(
        &'a self,
        dev: &'a device::Device<Bound>,
    ) -> Result<&'a Devres<SGTableMap<T>>> {
        let _dma_resv = DmaResvGuard::new(self);

        if let Some(devres) = self.sgt_res.as_ref() {
            Ok(devres)
        } else {
            // Only called for the side-effect of populating the GEM SG table.
            // SAFETY: We grabbed the lock required for calling this function above.
            from_err_ptr(unsafe {
                bindings::drm_gem_shmem_get_pages_sgt_locked(self.as_raw_shmem())
            })?;

            // INVARIANT:
            // - We called drm_gem_shmem_get_pages_sgt_locked above and checked that it
            //   succeeded, fulfilling the invariant of `SGTableMap` that the object's `sgt` field
            //   is initialized.
            // - We store this Devres in the object itself and don't move it, ensuring that the
            //   object it points to remains valid for the lifetime of the `SGTableMap`.
            let devres =
                Devres::new(dev, init!(SGTableMap { obj: self.into() })).inspect_err(|_| {
                    // We can't make sure that the pages for this object are unmapped on
                    // driver-unbind, so we need to release the sgt
                    // SAFETY:
                    // - We grabbed the lock required for calling this function above
                    // - We checked above that get_pages_sgt_locked() was successful
                    unsafe { bindings::__drm_gem_shmem_free_sgt_locked(self.as_raw_shmem()) }
                })?;

            self.sgt_res.populate(devres);

            // PANIC: `populate` has just succeeded, guaranteeing that `sgt_res` is populated.
            Ok(self.sgt_res.as_ref().unwrap())
        }
    }
Quoted 5 lines

And if only we could populate the SetOnce with a impl Init<T, E>, then we could even remove the DMA reservation acquisition on the fast path, because SetOnce comes with its own locking and the DMA lock here is used outside of its intended scope. I'll try to push the necessary work for SetOnce and maybe we can do that as a follow-up patch.

I have this sitting in my once_wip branch for while
https://github.com/nbdd0121/linux/commits/once_wip/
(the specific commit that adds init support is
https://github.com/nbdd0121/linux/commit/4aabdbcf20b11626c253f203745b1d55c37ab2ee).

This was implemented for lazy revocable support which Alvin has picked up, see
https://lore.kernel.org/rust-for-linux/[email protected]/

Best,
Gary

#8 lore raw

Re: [PATCH v12 4/5] rust: drm: gem: Introduce shmem::SGTable

Quoted 163 lines · Gary Guo
Quoted 156 lines · Alexandre Courbot

Hi Lyude,

Quoted 58 lines · Lyude Paul

In order to do this, we need to be careful to ensure that any interface we expose for scatterlists ensures that any mappings created from one are destroyed on driver-unbind. To do this, we introduce a Devres resource into shmem::Object that we use in order to ensure that we release any SGTable mappings on driver-unbind. We store this in an UnsafeCell and protect access to it using the dma_resv lock that we already have from the shmem gem object, which is the same lock that currently protects drm_gem_object_shmem->sgt.

We also provide two different methods for acquiring an sg table:
self.sg_table(), and self.owned_sg_table(). The first function is for short-term uses of mapped SGTables, the second is for callers that need to hold onto the mapped SGTable for an extended period of time. The second variant uses Devres of course, whereas the first simply relies on rust's borrow checker to prevent driver-unbind when using the mapped SGTable.

---
V3:
* Rename OwnedSGTable to shmem::SGTable. Since the current version of the SGTable abstractions now has a Owned and Borrowed variant, I think renaming this to shmem::SGTable makes things less confusing. We do however, keep the name of owned_sg_table() as-is.
V4:
* Clarify safety comments for SGTable to explain why the object is thread-safe.
* Rename from SGTableRef to SGTable
V10:
* Use Devres in order to ensure that SGTables are revocable, and are unmapped on driver-unbind.
V11:
* s/create_sg_table()/get_sg_table()
* Get rid of extraneous ret = in shmem::Object::get_sg_table() V12:
* Actually move sgt_res in this patch and not the next one

 rust/kernel/drm/gem/shmem.rs | 192 ++++++++++++++++++++++++++++++++++-
 1 file changed, 190 insertions(+), 2 deletions(-)
rust/kernel/drm/gem/shmem.rs +5 -0
index 11749c36e8695..a477312c8a09b 100644
@@ -11,25 +11,38 @@
 
 use crate::{
     container_of,
+    device::{
+        self,
+        Bound, //
+    },
+    devres::*,
     drm::{
         driver,
         gem,
         private::Sealed,
         Device, //

rust/kernel/drm/gem/shmem.rs line 32

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +5 -1
     },
-    error::to_result,
+    error::{
+        from_err_ptr,
+        to_result, //
+    },
     prelude::*,
+    scatterlist,
     types::{
         ARef,

This fails on master:

    error[E0432]: unresolved import `crate::sync::ARef`
      --> ../rust/kernel/drm/gem/shmem.rs:36:5
      |
    36 |     sync::ARef,
      |     ^^^^^^^^^^ no `ARef` in `sync`

Importing sync::aref::ARef seems to be the correct way now.

Quoted 18 lines
rust/kernel/drm/gem/shmem.rs +5 -1
         Opaque, //
     }, //
 };
 use core::{
+    cell::UnsafeCell,
     ops::{
         Deref,
         DerefMut, //
     },
-    ptr::NonNull,
+    ptr::{
+        self,
+        NonNull, //
+    },
 };
 use gem::{
     BaseObjectPrivate,

rust/kernel/drm/gem/shmem.rs pub struct ObjectConfig<'a, T: DriverObject> { · line 81

Quoted 8 lines
rust/kernel/drm/gem/shmem.rs +5 -0
@@ -61,6 +74,11 @@ pub struct ObjectConfig<'a, T: DriverObject> {
 #[repr(C)]
 #[pin_data]
 pub struct Object<T: DriverObject> {
+    /// Devres object for unmapping any SGTable on driver-unbind.
+    ///
+    /// This is protected by the object's dma_resv lock. It needs to be before `obj` to ensure that
+    /// it is destroyed before `obj` on `Drop`.
+    sgt_res: UnsafeCell<Option<Devres<SGTableMap<T>>>>,

I didn't like this UnsafeCell<Option> since the last time, but only figured how to replace it now:

sgt_res: SetOnce<Devres<SGTableMap<T>>>,

It's actually designed for that! And lets you remove at least one unsafe statement, while simplifying get_sg_table quite a bit. With the other suggestions I have below, here is my version of get_sg_table for reference:

    fn get_sg_table<'a>(
        &'a self,
        dev: &'a device::Device<Bound>,
    ) -> Result<&'a Devres<SGTableMap<T>>> {
        let _dma_resv = DmaResvGuard::new(self);

        if let Some(devres) = self.sgt_res.as_ref() {
            Ok(devres)
        } else {
            // Only called for the side-effect of populating the GEM SG table.
            // SAFETY: We grabbed the lock required for calling this function above.
            from_err_ptr(unsafe {
                bindings::drm_gem_shmem_get_pages_sgt_locked(self.as_raw_shmem())
            })?;

            // INVARIANT:
            // - We called drm_gem_shmem_get_pages_sgt_locked above and checked that it
            //   succeeded, fulfilling the invariant of `SGTableMap` that the object's `sgt` field
            //   is initialized.
            // - We store this Devres in the object itself and don't move it, ensuring that the
            //   object it points to remains valid for the lifetime of the `SGTableMap`.
            let devres =
                Devres::new(dev, init!(SGTableMap { obj: self.into() })).inspect_err(|_| {
                    // We can't make sure that the pages for this object are unmapped on
                    // driver-unbind, so we need to release the sgt
                    // SAFETY:
                    // - We grabbed the lock required for calling this function above
                    // - We checked above that get_pages_sgt_locked() was successful
                    unsafe { bindings::__drm_gem_shmem_free_sgt_locked(self.as_raw_shmem()) }
                })?;

            self.sgt_res.populate(devres);

            // PANIC: `populate` has just succeeded, guaranteeing that `sgt_res` is populated.
            Ok(self.sgt_res.as_ref().unwrap())
        }
    }
Quoted 5 lines

And if only we could populate the SetOnce with a impl Init<T, E>, then we could even remove the DMA reservation acquisition on the fast path, because SetOnce comes with its own locking and the DMA lock here is used outside of its intended scope. I'll try to push the necessary work for SetOnce and maybe we can do that as a follow-up patch.

Quoted 7 lines

I have this sitting in my once_wip branch for while
https://github.com/nbdd0121/linux/commits/once_wip/
(the specific commit that adds init support is
https://github.com/nbdd0121/linux/commit/4aabdbcf20b11626c253f203745b1d55c37ab2ee).

This was implemented for lazy revocable support which Alvin has picked up, see
https://lore.kernel.org/rust-for-linux/[email protected]/

Haha that's pretty close to what I wrote to test the code. Do you have plans to send it soon?

reviewer
#9 lore raw

Re: [PATCH v12 4/5] rust: drm: gem: Introduce shmem::SGTable

Quoted 61 lines · Alexandre Courbot
Quoted 60 lines · Gary Guo
Quoted 48 lines · Alexandre Courbot

I didn't like this UnsafeCell<Option> since the last time, but only figured how to replace it now:

sgt_res: SetOnce<Devres<SGTableMap<T>>>,

It's actually designed for that! And lets you remove at least one unsafe statement, while simplifying get_sg_table quite a bit. With the other suggestions I have below, here is my version of get_sg_table for reference:

    fn get_sg_table<'a>(
        &'a self,
        dev: &'a device::Device<Bound>,
    ) -> Result<&'a Devres<SGTableMap<T>>> {
        let _dma_resv = DmaResvGuard::new(self);

        if let Some(devres) = self.sgt_res.as_ref() {
            Ok(devres)
        } else {
            // Only called for the side-effect of populating the GEM SG table.
            // SAFETY: We grabbed the lock required for calling this function above.
            from_err_ptr(unsafe {
                bindings::drm_gem_shmem_get_pages_sgt_locked(self.as_raw_shmem())
            })?;

            // INVARIANT:
            // - We called drm_gem_shmem_get_pages_sgt_locked above and checked that it
            //   succeeded, fulfilling the invariant of `SGTableMap` that the object's `sgt` field
            //   is initialized.
            // - We store this Devres in the object itself and don't move it, ensuring that the
            //   object it points to remains valid for the lifetime of the `SGTableMap`.
            let devres =
                Devres::new(dev, init!(SGTableMap { obj: self.into() })).inspect_err(|_| {
                    // We can't make sure that the pages for this object are unmapped on
                    // driver-unbind, so we need to release the sgt
                    // SAFETY:
                    // - We grabbed the lock required for calling this function above
                    // - We checked above that get_pages_sgt_locked() was successful
                    unsafe { bindings::__drm_gem_shmem_free_sgt_locked(self.as_raw_shmem()) }
                })?;

            self.sgt_res.populate(devres);

            // PANIC: `populate` has just succeeded, guaranteeing that `sgt_res` is populated.
            Ok(self.sgt_res.as_ref().unwrap())
        }
    }
Quoted 5 lines

And if only we could populate the SetOnce with a impl Init<T, E>, then we could even remove the DMA reservation acquisition on the fast path, because SetOnce comes with its own locking and the DMA lock here is used outside of its intended scope. I'll try to push the necessary work for SetOnce and maybe we can do that as a follow-up patch.

I have this sitting in my once_wip branch for while
https://github.com/nbdd0121/linux/commits/once_wip/
(the specific commit that adds init support is
https://github.com/nbdd0121/linux/commit/4aabdbcf20b11626c253f203745b1d55c37ab2ee).

Quoted 5 lines
Quoted 2 lines

This was implemented for lazy revocable support which Alvin has picked up, see
https://lore.kernel.org/rust-for-linux/[email protected]/

Haha that's pretty close to what I wrote to test the code. Do you have plans to send it soon?

I mean.. Alvin has already sent it?

If you (or someone else) want to carry the patch in another series, by all means.

Best,
Gary

#10 lore raw

Re: [PATCH v12 4/5] rust: drm: gem: Introduce shmem::SGTable

Quoted 65 lines · Gary Guo
Quoted 64 lines · Alexandre Courbot
Quoted 62 lines · Gary Guo
Quoted 48 lines · Alexandre Courbot

I didn't like this UnsafeCell<Option> since the last time, but only figured how to replace it now:

sgt_res: SetOnce<Devres<SGTableMap<T>>>,

It's actually designed for that! And lets you remove at least one unsafe statement, while simplifying get_sg_table quite a bit. With the other suggestions I have below, here is my version of get_sg_table for reference:

    fn get_sg_table<'a>(
        &'a self,
        dev: &'a device::Device<Bound>,
    ) -> Result<&'a Devres<SGTableMap<T>>> {
        let _dma_resv = DmaResvGuard::new(self);

        if let Some(devres) = self.sgt_res.as_ref() {
            Ok(devres)
        } else {
            // Only called for the side-effect of populating the GEM SG table.
            // SAFETY: We grabbed the lock required for calling this function above.
            from_err_ptr(unsafe {
                bindings::drm_gem_shmem_get_pages_sgt_locked(self.as_raw_shmem())
            })?;

            // INVARIANT:
            // - We called drm_gem_shmem_get_pages_sgt_locked above and checked that it
            //   succeeded, fulfilling the invariant of `SGTableMap` that the object's `sgt` field
            //   is initialized.
            // - We store this Devres in the object itself and don't move it, ensuring that the
            //   object it points to remains valid for the lifetime of the `SGTableMap`.
            let devres =
                Devres::new(dev, init!(SGTableMap { obj: self.into() })).inspect_err(|_| {
                    // We can't make sure that the pages for this object are unmapped on
                    // driver-unbind, so we need to release the sgt
                    // SAFETY:
                    // - We grabbed the lock required for calling this function above
                    // - We checked above that get_pages_sgt_locked() was successful
                    unsafe { bindings::__drm_gem_shmem_free_sgt_locked(self.as_raw_shmem()) }
                })?;

            self.sgt_res.populate(devres);

            // PANIC: `populate` has just succeeded, guaranteeing that `sgt_res` is populated.
            Ok(self.sgt_res.as_ref().unwrap())
        }
    }
Quoted 5 lines

And if only we could populate the SetOnce with a impl Init<T, E>, then we could even remove the DMA reservation acquisition on the fast path, because SetOnce comes with its own locking and the DMA lock here is used outside of its intended scope. I'll try to push the necessary work for SetOnce and maybe we can do that as a follow-up patch.

I have this sitting in my once_wip branch for while
https://github.com/nbdd0121/linux/commits/once_wip/
(the specific commit that adds init support is
https://github.com/nbdd0121/linux/commit/4aabdbcf20b11626c253f203745b1d55c37ab2ee).

This was implemented for lazy revocable support which Alvin has picked up, see
https://lore.kernel.org/rust-for-linux/[email protected]/

Quoted 6 lines
Quoted 2 lines

Haha that's pretty close to what I wrote to test the code. Do you have plans to send it soon?

I mean.. Alvin has already sent it?

If you (or someone else) want to carry the patch in another series, by all means.

My bad, it was late at night and my focus was a bit down.

It's perfect if Alvin keeps carrying this patch.

#11 lore raw

Re: [PATCH v12 4/5] rust: drm: gem: Introduce shmem::SGTable

In reply to Alexandre Courbot
Quoted 387 lines · Alexandre Courbot

Hi Lyude,

Quoted 58 lines · Lyude Paul

In order to do this, we need to be careful to ensure that any interface we expose for scatterlists ensures that any mappings created from one are destroyed on driver-unbind. To do this, we introduce a Devres resource into shmem::Object that we use in order to ensure that we release any SGTable mappings on driver-unbind. We store this in an UnsafeCell and protect access to it using the dma_resv lock that we already have from the shmem gem object, which is the same lock that currently protects drm_gem_object_shmem->sgt.

We also provide two different methods for acquiring an sg table:
self.sg_table(), and self.owned_sg_table(). The first function is for short-term uses of mapped SGTables, the second is for callers that need to hold onto the mapped SGTable for an extended period of time. The second variant uses Devres of course, whereas the first simply relies on rust's borrow checker to prevent driver-unbind when using the mapped SGTable.

---
V3:
* Rename OwnedSGTable to shmem::SGTable. Since the current version of the SGTable abstractions now has a Owned and Borrowed variant, I think renaming this to shmem::SGTable makes things less confusing. We do however, keep the name of owned_sg_table() as-is.
V4:
* Clarify safety comments for SGTable to explain why the object is thread-safe.
* Rename from SGTableRef to SGTable
V10:
* Use Devres in order to ensure that SGTables are revocable, and are unmapped on driver-unbind.
V11:
* s/create_sg_table()/get_sg_table()
* Get rid of extraneous ret = in shmem::Object::get_sg_table() V12:
* Actually move sgt_res in this patch and not the next one

 rust/kernel/drm/gem/shmem.rs | 192 ++++++++++++++++++++++++++++++++++-
 1 file changed, 190 insertions(+), 2 deletions(-)
rust/kernel/drm/gem/shmem.rs +5 -0
index 11749c36e8695..a477312c8a09b 100644
@@ -11,25 +11,38 @@
 
 use crate::{
     container_of,
+    device::{
+        self,
+        Bound, //
+    },
+    devres::*,
     drm::{
         driver,
         gem,
         private::Sealed,
         Device, //

rust/kernel/drm/gem/shmem.rs line 32

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +5 -1
     },
-    error::to_result,
+    error::{
+        from_err_ptr,
+        to_result, //
+    },
     prelude::*,
+    scatterlist,
     types::{
         ARef,

This fails on master:

    error[E0432]: unresolved import `crate::sync::ARef`
      --> ../rust/kernel/drm/gem/shmem.rs:36:5
      |
    36 |     sync::ARef,
      |     ^^^^^^^^^^ no `ARef` in `sync`

Importing sync::aref::ARef seems to be the correct way now.

Quoted 18 lines
rust/kernel/drm/gem/shmem.rs +5 -1
         Opaque, //
     }, //
 };
 use core::{
+    cell::UnsafeCell,
     ops::{
         Deref,
         DerefMut, //
     },
-    ptr::NonNull,
+    ptr::{
+        self,
+        NonNull, //
+    },
 };
 use gem::{
     BaseObjectPrivate,

rust/kernel/drm/gem/shmem.rs pub struct ObjectConfig<'a, T: DriverObject> { · line 81

Quoted 8 lines
rust/kernel/drm/gem/shmem.rs +5 -0
@@ -61,6 +74,11 @@ pub struct ObjectConfig<'a, T: DriverObject> {
 #[repr(C)]
 #[pin_data]
 pub struct Object<T: DriverObject> {
+    /// Devres object for unmapping any SGTable on driver-unbind.
+    ///
+    /// This is protected by the object's dma_resv lock. It needs to be before `obj` to ensure that
+    /// it is destroyed before `obj` on `Drop`.
+    sgt_res: UnsafeCell<Option<Devres<SGTableMap<T>>>>,

I didn't like this UnsafeCell<Option> since the last time, but only figured how to replace it now:

sgt_res: SetOnce<Devres<SGTableMap<T>>>,

It's actually designed for that! And lets you remove at least one unsafe statement, while simplifying get_sg_table quite a bit. With the other suggestions I have below, here is my version of get_sg_table for reference:

    fn get_sg_table<'a>(
        &'a self,
        dev: &'a device::Device<Bound>,
    ) -> Result<&'a Devres<SGTableMap<T>>> {
        let _dma_resv = DmaResvGuard::new(self);

        if let Some(devres) = self.sgt_res.as_ref() {
            Ok(devres)
        } else {
            // Only called for the side-effect of populating the GEM SG table.
            // SAFETY: We grabbed the lock required for calling this function above.
            from_err_ptr(unsafe {
                bindings::drm_gem_shmem_get_pages_sgt_locked(self.as_raw_shmem())
            })?;

            // INVARIANT:
            // - We called drm_gem_shmem_get_pages_sgt_locked above and checked that it
            //   succeeded, fulfilling the invariant of `SGTableMap` that the object's `sgt` field
            //   is initialized.
            // - We store this Devres in the object itself and don't move it, ensuring that the
            //   object it points to remains valid for the lifetime of the `SGTableMap`.
            let devres =
                Devres::new(dev, init!(SGTableMap { obj: self.into() })).inspect_err(|_| {
                    // We can't make sure that the pages for this object are unmapped on
                    // driver-unbind, so we need to release the sgt
                    // SAFETY:
                    // - We grabbed the lock required for calling this function above
                    // - We checked above that get_pages_sgt_locked() was successful
                    unsafe { bindings::__drm_gem_shmem_free_sgt_locked(self.as_raw_shmem()) }
                })?;

            self.sgt_res.populate(devres);

            // PANIC: `populate` has just succeeded, guaranteeing that `sgt_res` is populated.
            Ok(self.sgt_res.as_ref().unwrap())
        }
    }

And if only we could populate the SetOnce with a impl Init<T, E>, then we could even remove the DMA reservation acquisition on the fast path, because SetOnce comes with its own locking and the DMA lock here is used outside of its intended scope. I'll try to push the necessary work for SetOnce and maybe we can do that as a follow-up patch.

Quoted 16 lines
rust/kernel/drm/gem/shmem.rs +2 -0
     #[pin]
     obj: Opaque<bindings::drm_gem_shmem_object>,
     /// Parent object that owns this object's DMA reservation object.
@@ -117,6 +135,7 @@ pub fn new(
             try_pin_init!(Self {
                 obj <- Opaque::init_zeroed(),
                 parent_resv_obj: config.parent_resv_obj.map(|p| p.into()),
+                sgt_res: UnsafeCell::new(None),
                 inner <- T::new(dev, size, args),
             }),
             GFP_KERNEL,
@@ -176,6 +195,100 @@ extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) {
         // SAFETY: We're recovering the Kbox<> we created in gem_create_object()
         let _ = unsafe { KBox::from_raw(this) };
     }
+

rust/kernel/drm/gem/shmem.rs extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) { · line 208

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +10 -0
+    // If necessary, create an SGTable for the gem object and register a Devres for it to ensure
+    // that it is unmapped on driver unbind.
+    fn get_sg_table<'a>(
+        &'a self,
+        dev: &'a device::Device<Bound>,
+    ) -> Result<&'a Devres<SGTableMap<T>>> {
+        let sgt_res_ptr = self.sgt_res.get();
+
+        // SAFETY: This lock is initialized throughout the lifetime of the gem object
+        unsafe { bindings::dma_resv_lock(self.raw_dma_resv(), ptr::null_mut()) };

There are 4 sites where we acquire and release the DMA resv lock, each of which require unsafe blocks and carrying the risk that we forget releasing the lock in the end. For this method in particular we need to jump through hoops a bit and store the return value into a temporary variable so we can unlock the DMA reservation.

Let's do ourselves a favor and implement a small, private guard type:

    struct DmaResvGuard<'a, T: DriverObject>(&'a Object<T>);

    impl<'a, T: DriverObject> DmaResvGuard<'a, T> {
        fn new(object: &'a Object<T>) -> Self {
            // SAFETY: This lock is initialized throughout the lifetime of `object`
            unsafe { bindings::dma_resv_lock(object.raw_dma_resv(), ptr::null_mut()) };

            Self(object)
        }
    }

    impl<'a, T> Drop for DmaResvGuard<'a, T>
    where
        T: DriverObject,
    {
        fn drop(&mut self) {
            // SAFETY: We are releasing the lock grabbed during the creation of this object.
            unsafe { bindings::dma_resv_unlock(self.0.raw_dma_resv()) };
        }
    }

There here you would just do

    let _dma_resv = DmaResvGuard::new(self);

and write the rest of the method without without having to worry about not returning early. It also let's you improve the flow of the code a bit, and requires less unsafe blocks overall.

I am not sure how much of the TODO at the beginning of the file this solves, but it should also make it easier to switch to something that acquires a reference to a Wwmutex.

Quoted 9 lines
rust/kernel/drm/gem/shmem.rs +9 -0
+
+        // SAFETY: We just grabbed the lock required for reading this data above.
+        let sgt_res = unsafe { (*sgt_res_ptr).as_ref() };
+
+        let ret = if let Some(sgt_res) = sgt_res {
+            // We already have a Devres object for this sg table, return it
+            Ok(sgt_res)
+        } else {
+            // SAFETY: We grabbed the lock required for calling this function above */

rust/kernel/drm/gem/shmem.rs extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) { · line 227

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +10 -0
+            let sgt = from_err_ptr(unsafe {
+                bindings::drm_gem_shmem_get_pages_sgt_locked(self.as_raw_shmem())
+            });
+
+            if let Err(e) = sgt {
+                Err(e)
+            } else {
+                // INVARIANT:
+                // - We called drm_gem_shmem_get_pages_sgt_locked above and checked that it
+                //   succeeded, fulfilling the invariant of SGTableRef that the object's `sgt` field

s/SGTableRef/SGTableMap? (several like this through the patch).

Quoted 71 lines
rust/kernel/drm/gem/shmem.rs +64 -0
+                //   is initialized.
+                // - We store this Devres in the object itself and don't move it, ensuring that the
+                //   object it points to remains valid for the lifetime of the SGTableRef.
+                let devres = Devres::new(dev, init!(SGTableMap { obj: self.into() }));
+                match devres {
+                    Ok(devres) => {
+                        // SAFETY: We acquired the lock protecting this data above, making it safe
+                        // to write into here
+                        unsafe { (*sgt_res_ptr) = Some(devres) };
+
+                        // SAFETY: We just write Some() into *sgt_res_ptr above
+                        Ok(unsafe { (&*sgt_res_ptr).as_ref().unwrap_unchecked() })
+                    }
+                    Err(e) => {
+                        // We can't make sure that the pages for this object are unmapped on
+                        // driver-unbind, so we need to release the sgt
+                        // SAFETY:
+                        // - We grabbed the lock required for calling this function above
+                        // - We checked above that get_pages_sgt_locked() was successful
+                        unsafe { bindings::__drm_gem_shmem_free_sgt_locked(self.as_raw_shmem()) };
+
+                        Err(e)
+                    }
+                }
+            }
+        };
+
+        // SAFETY: We're releasing the lock that we grabbed above.
+        unsafe { bindings::dma_resv_unlock(self.raw_dma_resv()) };
+
+        ret
+    }
+
+    /// Creates (if necessary) and returns an immutable reference to a scatter-gather table of DMA
+    /// pages for this object.
+    ///
+    /// This will pin the object in memory.
+    #[inline]
+    pub fn sg_table<'a>(
+        &'a self,
+        dev: &'a device::Device<Bound>,
+    ) -> Result<&'a scatterlist::SGTable> {
+        let sgt = self.get_sg_table(dev)?;
+
+        Ok(sgt.access(dev)?.deref())
+    }
+
+    /// Creates (if necessary) and returns an owned reference to a scatter-gather table of DMA pages
+    /// for this object.
+    ///
+    /// This is the same as [`sg_table`](Self::sg_table), except that it instead returns an
+    /// [`shmem::SGTable`] which holds a reference to the associated gem object, instead of a
+    /// reference to an [`scatterlist::SGTable`].
+    ///
+    /// This will pin the object in memory.
+    ///
+    /// [`shmem::SGTable`]: SGTable
+    pub fn owned_sg_table(&self, dev: &device::Device<Bound>) -> Result<SGTable<T>> {
+        self.get_sg_table(dev)?;
+
+        // INVARIANT: We just ensured above that `self.sgt_res` is initialized with
+        // `Some(Devres<SGTableMap<T>>)`.
+        Ok(SGTable(self.into()))
+    }
 }
 
 impl<T: DriverObject> Deref for Object<T> {
@@ -226,3 +339,78 @@ impl<T: DriverObject> driver::AllocImpl for Object<T> {
         dumb_map_offset: None,
     };
 }

rust/kernel/drm/gem/shmem.rs impl<T: DriverObject> driver::AllocImpl for Object<T> { · line 351

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +10 -0
+
+/// A reference to a GEM object that is known to have a mapped [`SGTable`].
+///
+/// This is used by the Rust bindings with [`Devres`] in order to ensure that mappings for SGTables
+/// on GEM shmem objects are revoked on driver-unbind.
+///
+/// # Invariants
+///
+/// - `self.obj` always points to a valid GEM object.
+/// - This object is proof that `self.0.owner.sgt` has an initialized and valid SGTable.

The comment mentions self.0 and "a valid SGTable", which don't seem to apply to this type.

Quoted 15 lines
rust/kernel/drm/gem/shmem.rs +15 -0
+pub struct SGTableMap<T: DriverObject> {
+    obj: NonNull<Object<T>>,
+}
+
+impl<T: DriverObject> Deref for SGTableMap<T> {
+    type Target = scatterlist::SGTable;
+
+    fn deref(&self) -> &Self::Target {
+        // SAFETY:
+        // - The NonNull is guaranteed to be valid via our type invariants.
+        // - The sgt field is guaranteed to be initialized and valid via our type invariants.
+        unsafe { scatterlist::SGTable::from_raw((*self.obj.as_ref().as_raw_shmem()).sgt) }
+    }
+}
+

rust/kernel/drm/gem/shmem.rs impl<T: DriverObject> driver::AllocImpl for Object<T> { · line 376

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +10 -0
+impl<T: DriverObject> Drop for SGTableMap<T> {
+    fn drop(&mut self) {
+        // SAFETY: `obj` is always valid via our type invariants
+        let obj = unsafe { self.obj.as_ref() };
+
+        // SAFETY: The dma_resv for GEM objects is initialized throughout its lifetime
+        unsafe { bindings::dma_resv_lock(obj.raw_dma_resv(), ptr::null_mut()) };
+
+        // SAFETY: We acquired the lock needed for calling this function above
+        unsafe { bindings::__drm_gem_shmem_free_sgt_locked(obj.as_raw_shmem()) };

For symmetry, I wanted to suggest moving the call to drm_gem_shmem_get_pages_sgt_locked to a (fallible) constructor of SGTableMap.

It's not only for cosmetic and code proximity reasons - once you bind the call to drm_gem_shmem_get_pages_sgt_locked to the successful creation of the SGTableMap object, you can remove the custom error path of get_sg_table that called __drm_gem_shmem_free_sgt_locked if Devres::new failed since the destructor of SGTableMap will now take care of this for us. This simplifies the last complex bit of get_sg_table.

The problem is that it would also normally require SGTableMap::new to acquire the DMA reservation lock in order to call drm_gem_shmem_get_pages_sgt_locked, but we already have it in get_sg_table.

If we stopped using the DMA reservation lock as a lock for population sgt_res and instead switched to a regular Mutex, we could then move the DMA reservation acquisition to the constructor, attain symmetry, and simplify get_sg_table to the point where it becomes trivial. That use is also fragile as the SGTableMap destructor acquires it, so we must be very careful to never drop it in get_sg_table.

Quoted 2 lines

I think that would be a good tradeoff for the time until we make SetOnce capable of being populated using an impl Init.

Another benefit (I guess) of using a dedicated lock is that you could also call drm_gem_shmem_get_pages_sgt, removing the need for patch 3.

#12 lore raw

Re: [PATCH v12 4/5] rust: drm: gem: Introduce shmem::SGTable

In reply to Alexandre Courbot
Quoted 10 lines · Alexandre Courbot

This fails on master:

    error[E0432]: unresolved import crate::sync::ARef --> ../rust/kernel/drm/gem/shmem.rs:36:5 |
    36 |     sync::ARef,
      |     ^^^^^^^^^^ no ARef in sync

Importing sync::aref::ARef seems to be the correct way now.

FWIW: as I mentioned in the cover letter, this series applies against drm-rust-next - not master.

#13 lore raw

Re: [PATCH v12 4/5] rust: drm: gem: Introduce shmem::SGTable

In reply to Alexandre Courbot
Quoted 35 lines · Alexandre Courbot

There are 4 sites where we acquire and release the DMA resv lock, each
of which require unsafe blocks and carrying the risk that we forget releasing the lock in the end. For this method in particular we need to
jump through hoops a bit and store the return value into a temporary variable so we can unlock the DMA reservation.

Let's do ourselves a favor and implement a small, private guard type:

    struct DmaResvGuard<'a, T: DriverObject>(&'a Object<T>);

    impl<'a, T: DriverObject> DmaResvGuard<'a, T> {
        fn new(object: &'a Object<T>) -> Self {
            // SAFETY: This lock is initialized throughout the lifetime of object
            unsafe { bindings::dma_resv_lock(object.raw_dma_resv(), ptr::null_mut()) };

            Self(object)
        }
    }

    impl<'a, T> Drop for DmaResvGuard<'a, T>
    where
        T: DriverObject,
    {
        fn drop(&mut self) {
            // SAFETY: We are releasing the lock grabbed during the creation of this object.
            unsafe { bindings::dma_resv_unlock(self.0.raw_dma_resv()) };
        }
    }

Quoted 3 lines

There here you would just do

    let _dma_resv = DmaResvGuard::new(self);

I thought of doing this but lost track of how many times I was actually grabbing this lock…
BTW - want me to just give you authorship on the patch for adding DmaResvGuard? Since on my branch I've pretty much only just added two inline annotations, it's otherwise identical to what you wrote here.

#14 lore raw

Re: [PATCH v12 4/5] rust: drm: gem: Introduce shmem::SGTable

Quoted 39 lines · lyude
Quoted 37 lines · Alexandre Courbot

There are 4 sites where we acquire and release the DMA resv lock, each
of which require unsafe blocks and carrying the risk that we forget releasing the lock in the end. For this method in particular we need to
jump through hoops a bit and store the return value into a temporary variable so we can unlock the DMA reservation.

Let's do ourselves a favor and implement a small, private guard type:

    struct DmaResvGuard<'a, T: DriverObject>(&'a Object<T>);

    impl<'a, T: DriverObject> DmaResvGuard<'a, T> {
        fn new(object: &'a Object<T>) -> Self {
            // SAFETY: This lock is initialized throughout the lifetime of object
            unsafe { bindings::dma_resv_lock(object.raw_dma_resv(), ptr::null_mut()) };

            Self(object)
        }
    }

    impl<'a, T> Drop for DmaResvGuard<'a, T>
    where
        T: DriverObject,
    {
        fn drop(&mut self) {
            // SAFETY: We are releasing the lock grabbed during the creation of this object.
            unsafe { bindings::dma_resv_unlock(self.0.raw_dma_resv()) };
        }
    }

There here you would just do

Quoted 7 lines
Quoted 1 line

    let _dma_resv = DmaResvGuard::new(self);

I thought of doing this but lost track of how many times I was actually grabbing this lock…
BTW - want me to just give you authorship on the patch for adding DmaResvGuard? Since on my branch I've pretty much only just added two inline annotations, it's otherwise identical to what you wrote here.

You should remain author since I didn't formally send a patch - but if the code remains that close, and you are comfortable with it, then a Co-authored-by would be appreciated. Feel free to also add my

#15 lore raw

Re: [PATCH v12 4/5] rust: drm: gem: Introduce shmem::SGTable

In reply to Lyude Paul

On Wed Apr 22, 2026 at 8:52 AM JST, Lyude Paul wrote:
<snip>

rust/kernel/drm/gem/shmem.rs extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) { · line 203

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +6 -0
@@ -176,6 +195,100 @@ extern "C" fn free_callback(obj: *mut bindings::drm_gem_object) {
         // SAFETY: We're recovering the Kbox<> we created in gem_create_object()
         let _ = unsafe { KBox::from_raw(this) };
     }
+
+    // If necessary, create an SGTable for the gem object and register a Devres for it to ensure
+    // that it is unmapped on driver unbind.
+    fn get_sg_table<'a>(
+        &'a self,
+        dev: &'a device::Device<Bound>,

Just noticed that the caller can technically pass a different dev from the one the buffer will be mapped onto, potentially linking the Devres (and thus the device mapping) to a completely unrelated lifetime.

I.e. dev is only used to create the Devres, while drm_gem_shmem_get_pages_sgt_locked uses the object's device pointer to create the mapping. We need to add the check ensuring that the two point to the same device:

    let expected = self.dev().as_ref().as_raw();
    if dev.as_raw() != expected {
        return Err(EINVAL);
    }

Ideally we could do without the dev argument altogether, but that's our only guarantee that the device is bound, so I don't think we can do without this runtime check.

I think it's also worth mentioning in the documentations of sg_table and owned_sg_table which device is expected.

author
#16 lore raw

PATCH v12 5/5 rust: drm: gem: Add vmap functions to shmem bindings

In reply to Lyude Paul

One of the more obvious use cases for gem shmem objects is the ability to create mappings into their contents. So, let's hook this up in our rust bindings.

Similar to how we handle SGTables, we make sure there's two different types of mappings: owned mappings (kernel::drm::gem::shmem::VMap) and borrowed mappings (kernel::drm::gem::shmem::VMapRef).

---
V7:
* Switch over to the new iosys map bindings that use the Io trait V8:
* Get rid of iosys_map bindings for now, only support non-iomem types
* s/as_shmem()/as_raw_shmem()
V9:
* Get rid of some outdated comments I missed
* Add missing SIZE check to raw_vmap()
* Add a proper unit test that ensures that we actually validate SIZE at compile-time.
Turns out it takes only 34 lines to make a boilerplate DRM driver for a kunit test :)
* Add unit tests
* Add some missing #[inline]s
V10:
* Correct issue with iomem error path
We previously called raw_vunmap() if we got an iomem allocation, but raw_vunmap() was written such that it assumed all allocations were sysmem allocations. Fix this by just making raw_vunmap() accept a iosys_map.
V11:
* Use Alexandre's clever solution to remove the macros we were using for maintaining two different VMap types.
* Change the order of items in Object<T> to ensure that sgt_res is always dropped before obj.
* Fix typo in Object.raw_vmap()

 rust/kernel/drm/gem/shmem.rs | 355 +++++++++++++++++++++++++++++++++++
 1 file changed, 355 insertions(+)
rust/kernel/drm/gem/shmem.rs +355 -0
index a477312c8a09b..b96de8d33141d 100644
@@ -26,6 +26,11 @@
         from_err_ptr,
         to_result, //
     },
+    io::{
+        Io,
+        IoCapable,
+        IoKnownSize, //
+    },
     prelude::*,
     scatterlist,
     types::{
@@ -35,6 +40,11 @@
 };
 use core::{
     cell::UnsafeCell,
+    ffi::c_void,
+    mem::{
+        self,
+        MaybeUninit, //
+    },
     ops::{
         Deref,
         DerefMut, //
@@ -45,6 +55,7 @@
     },
 };
 use gem::{
+    BaseObject,
     BaseObjectPrivate,
     DriverObject,
     IntoGEMObject, //
@@ -289,6 +300,84 @@ pub fn owned_sg_table(&self, dev: &device::Device<Bound>) -> Result<SGTable<T>>
         // `Some(Devres<SGTableMap<T>>)`.
         Ok(SGTable(self.into()))
     }
+
+    /// Attempt to create a vmap from the gem object, and confirm the size of said vmap.
+    fn raw_vmap(&self, min_size: usize) -> Result<*mut c_void> {
+        if self.size() < min_size {
+            return Err(ENOSPC);
+        }
+
+        let mut map: MaybeUninit<bindings::iosys_map> = MaybeUninit::uninit();
+
+        // SAFETY: drm_gem_shmem_vmap can be called with the DMA reservation lock held
+        to_result(unsafe {
+            // TODO: see top of file
+            bindings::dma_resv_lock(self.raw_dma_resv(), ptr::null_mut());
+            let ret = bindings::drm_gem_shmem_vmap_locked(self.as_raw_shmem(), map.as_mut_ptr());
+            bindings::dma_resv_unlock(self.raw_dma_resv());
+            ret
+        })?;
+
+        // SAFETY: The call to drm_gem_shmem_vmap_locked succeeded above, so we are guaranteed that
+        // map is properly initialized.
+        let map = unsafe { map.assume_init() };
+
+        // XXX: We don't currently support iomem allocations
+        if map.is_iomem {
+            // SAFETY:
+            // - The vmap operation above succeeded, guaranteeing that `map` points to a valid
+            //   memory mapping.
+            // - We checked that this is an iomem allocation, making it safe to read vaddr_iomem
+            unsafe { self.raw_vunmap(map) };
+
+            Err(ENOTSUPP)
+        } else {
+            // SAFETY: We checked that this is not an iomem allocation, making it safe to read vaddr
+            Ok(unsafe { map.__bindgen_anon_1.vaddr })
+        }
+    }
+
+    /// Unmap a vmap from the gem object.
+    ///
+    /// # Safety
+    ///
+    /// - The caller promises that `map` is a valid vmap on this gem object.
+    /// - The caller promises that the memory pointed to by map will no longer be accesed through
+    ///   this instance.
+    unsafe fn raw_vunmap(&self, mut map: bindings::iosys_map) {
+        let resv = self.raw_dma_resv();
+
+        // SAFETY:
+        // - This function is safe to call with the DMA reservation lock held
+        // - Our `ARef` is proof that the underlying gem object here is initialized and thus safe to
+        //   dereference.
+        unsafe {
+            // TODO: see top of file
+            bindings::dma_resv_lock(resv, ptr::null_mut());
+            bindings::drm_gem_shmem_vunmap_locked(self.as_raw_shmem(), &mut map);
+            bindings::dma_resv_unlock(resv);
+        }
+    }
+
+    /// Creates and returns a virtual kernel memory mapping for this object.
+    #[inline]
+    pub fn vmap<const SIZE: usize>(&self) -> Result<VMapRef<'_, T, SIZE>> {
+        Ok(VMap {
+            // INVARIANT: `raw_vmap()` checks that the gem object is at least as large as `SIZE`.
+            addr: self.raw_vmap(SIZE)?,
+            owner: self,
+        })
+    }
+
+    /// Creates and returns an owned reference to a virtual kernel memory mapping for this object.
+    #[inline]
+    pub fn owned_vmap<const SIZE: usize>(&self) -> Result<VMapOwned<T, SIZE>> {
+        Ok(VMap {
+            // INVARIANT: `raw_vmap()` checks that the gem object is at least as large as `SIZE`.
+            addr: self.raw_vmap(SIZE)?,
+            owner: self.into(),
+        })
+    }
 }
 
 impl<T: DriverObject> Deref for Object<T> {
@@ -387,6 +476,155 @@ unsafe impl<T: DriverObject> Send for SGTableMap<T> {}
 // it points to is guaranteed to be thread-safe.
 unsafe impl<T: DriverObject> Sync for SGTableMap<T> {}
 
+macro_rules! impl_vmap_io_capable {
+    ($impl:ident, $ty:ty) => {
+        impl<D, R, const SIZE: usize> IoCapable<$ty> for $impl<D, R, SIZE>
+        where
+            D: DriverObject,
+            R: Deref<Target = Object<D>>,
+        {
+            #[inline(always)]
+            unsafe fn io_read(&self, address: usize) -> $ty {
+                let ptr = address as *mut $ty;
+
+                // SAFETY: The safety contract of `io_read` guarantees that address is a valid
+                // address within the bounds of `Self` of at least the size of $ty, and is properly
+                // aligned.
+                unsafe { ptr::read(ptr) }
+            }
+
+            #[inline(always)]
+            unsafe fn io_write(&self, value: $ty, address: usize) {
+                let ptr = address as *mut $ty;
+
+                // SAFETY: The safety contract of `io_write` guarantees that address is a valid
+                // address within the bounds of `Self` of at least the size of $ty, and is properly
+                // aligned.
+                unsafe { ptr::write(ptr, value) }
+            }
+        }
+    };
+}
+
+/// A reference to a virtual mapping for an shmem-based GEM object in kernel address space.
+///
+/// # Invariants
+///
+/// - The size of `owner` is >= SIZE.
+/// - The memory pointed to by addr remains valid at least until this object is dropped.
+pub struct VMap<D, R, const SIZE: usize = 0>
+where
+    D: DriverObject,
+    R: Deref<Target = Object<D>>,
+{
+    addr: *mut c_void,
+    owner: R,
+}
+
+/// An alias type for a reference to a shmem-based GEM object's VMap.
+pub type VMapRef<'a, D, const SIZE: usize = 0> = VMap<D, &'a Object<D>, SIZE>;
+
+/// An alias type for an owned reference to a shmem-based GEM object's VMap.
+pub type VMapOwned<D, const SIZE: usize = 0> = VMap<D, ARef<Object<D>>, SIZE>;
+
+impl<D, R, const SIZE: usize> VMap<D, R, SIZE>
+where
+    D: DriverObject,
+    R: Deref<Target = Object<D>>,
+{
+    /// Borrows a reference to the object that owns this virtual mapping.
+    #[inline(always)]
+    pub fn owner(&self) -> &Object<D> {
+        &self.owner
+    }
+}
+
+impl<D, R, const SIZE: usize> Drop for VMap<D, R, SIZE>
+where
+    D: DriverObject,
+    R: Deref<Target = Object<D>>,
+{
+    #[inline(always)]
+    fn drop(&mut self) {
+        // SAFETY:
+        // - Our existence is proof that this map was previously created using self.owner.
+        // - Since we are in Drop, we are guaranteed that no one will access the memory
+        //   through this mapping after calling this.
+        unsafe {
+            self.owner.raw_vunmap(bindings::iosys_map {
+                is_iomem: false,
+                __bindgen_anon_1: bindings::iosys_map__bindgen_ty_1 { vaddr: self.addr },
+            })
+        };
+    }
+}
+
+impl<D, R, const SIZE: usize> Io for VMap<D, R, SIZE>
+where
+    D: DriverObject,
+    R: Deref<Target = Object<D>>,
+{
+    #[inline(always)]
+    fn addr(&self) -> usize {
+        self.addr as usize
+    }
+
+    #[inline(always)]
+    fn maxsize(&self) -> usize {
+        self.owner.size()
+    }
+}
+
+impl<D, R, const SIZE: usize> IoKnownSize for VMap<D, R, SIZE>
+where
+    D: DriverObject,
+    R: Deref<Target = Object<D>>,
+{
+    const MIN_SIZE: usize = SIZE;
+}
+
+impl_vmap_io_capable!(VMap, u8);
+impl_vmap_io_capable!(VMap, u16);
+impl_vmap_io_capable!(VMap, u32);
+#[cfg(CONFIG_64BIT)]
+impl_vmap_io_capable!(VMap, u64);
+
+impl<D: DriverObject, const SIZE: usize> Clone for VMapOwned<D, SIZE> {
+    #[inline]
+    fn clone(&self) -> Self {
+        // SAFETY: We have a successful vmap already, so this can't fail.
+        unsafe { self.owner.owned_vmap().unwrap_unchecked() }
+    }
+}
+
+impl<'a, D: DriverObject, const SIZE: usize> Clone for VMapRef<'a, D, SIZE> {
+    #[inline]
+    fn clone(&self) -> Self {
+        // SAFETY: We have a successful vmap already, so this can't fail.
+        unsafe { self.owner.vmap().unwrap_unchecked() }
+    }
+}
+
+impl<'a, D: DriverObject, const SIZE: usize> From<VMapRef<'a, D, SIZE>> for VMapOwned<D, SIZE> {
+    #[inline]
+    fn from(value: VMapRef<'a, D, SIZE>) -> Self {
+        let this = Self {
+            addr: value.addr,
+            owner: value.owner.into(),
+        };
+
+        mem::forget(value);
+        this
+    }
+}
+
+// SAFETY: VMap is thread-safe, and the fact that this VMap has an owned reference to the object
+// means this object will remain valid until dropped.
+unsafe impl<D: DriverObject, const SIZE: usize> Send for VMapOwned<D, SIZE> {}
+// SAFETY: VMap is thread-safe, and the fact that this VMap has an owned reference to the object
+// means this object will remain valid until dropped.
+unsafe impl<D: DriverObject, const SIZE: usize> Sync for VMapOwned<D, SIZE> {}
+
 /// An owned reference to a scatter-gather table of DMA address spans for a GEM shmem object.
 ///
 /// This object holds an owned reference to the underlying GEM shmem object, ensuring that the
@@ -414,3 +652,120 @@ fn deref(&self) -> &Self::Target {
         unsafe { (*self.0.sgt_res.get()).as_ref().unwrap_unchecked() }
     }
 }
+
+#[kunit_tests(rust_drm_gem_shmem)]
+mod tests {
+    use super::*;
+    use crate::{
+        drm,
+        faux,
+        page::PAGE_SIZE, //
+    };
+
+    // The bare minimum needed to create a fake drm driver for kunit
+
+    #[pin_data]
+    struct KunitData {}
+    struct KunitDriver;
+    struct KunitFile;
+    #[pin_data]
+    struct KunitObject {}
+
+    const INFO: drm::DriverInfo = drm::DriverInfo {
+        major: 0,
+        minor: 0,
+        patchlevel: 0,
+        name: c"kunit",
+        desc: c"Kunit",
+    };
+
+    impl drm::file::DriverFile for KunitFile {
+        type Driver = KunitDriver;
+
+        fn open(_dev: &drm::Device<KunitDriver>) -> Result<Pin<KBox<Self>>> {
+            Ok(KBox::new(Self, GFP_KERNEL)?.into())
+        }
+    }
+
+    impl gem::DriverObject for KunitObject {
+        type Driver = KunitDriver;
+        type Args = ();
+
+        fn new(
+            _dev: &drm::Device<KunitDriver>,
+            _size: usize,
+            _args: Self::Args,
+        ) -> impl PinInit<Self, Error> {
+            try_pin_init!(KunitObject {})
+        }
+    }
+
+    #[vtable]
+    impl drm::Driver for KunitDriver {
+        type Data = KunitData;
+        type File = KunitFile;
+        type Object = Object<KunitObject>;
+
+        const INFO: drm::DriverInfo = INFO;
+        const IOCTLS: &'static [drm::ioctl::DrmIoctlDescriptor] = &[];
+    }
+
+    fn create_drm_dev() -> Result<(faux::Registration, ARef<drm::Device<KunitDriver>>)> {
+        // Create a faux DRM device so we can test gem object creation.
+        let data = try_pin_init!(KunitData {});
+        let dev = faux::Registration::new(c"Kunit", None)?;
+        let drm = drm::Device::<KunitDriver>::new(dev.as_ref(), data)?;
+
+        Ok((dev, drm))
+    }
+
+    #[test]
+    fn compile_time_vmap_sizes() -> Result {
+        let (_dev, drm) = create_drm_dev()?;
+
+        // Create a gem object to test with
+        let cfg_ = ObjectConfig::<KunitObject> {
+            map_wc: false,
+            parent_resv_obj: None,
+        };
+        let obj = Object::<KunitObject>::new(&drm, PAGE_SIZE, cfg_, ())?;
+
+        // Try creating a normal vmap
+        obj.vmap::<PAGE_SIZE>()?;
+
+        // Try creating a vmap that's smaller then the size we specified
+        obj.vmap::<{ PAGE_SIZE - 100 }>()?;
+
+        // Make sure creating a vmap that's too large fails
+        assert!(obj.vmap::<{ PAGE_SIZE + 200 }>().is_err());
+
+        Ok(())
+    }
+
+    #[test]
+    fn vmap_io() -> Result {
+        let (_dev, drm) = create_drm_dev()?;
+
+        // Create a gem object to test with
+        let cfg_ = ObjectConfig::<KunitObject> {
+            map_wc: false,
+            parent_resv_obj: None,
+        };
+        let obj = Object::<KunitObject>::new(&drm, PAGE_SIZE, cfg_, ())?;
+
+        let vmap = obj.vmap::<PAGE_SIZE>()?;
+
+        vmap.write8(0xDE, 0x0);
+        assert_eq!(vmap.read8(0x0), 0xDE);
+        vmap.write32(0xFFFFFFFF, 0x20);
+
+        assert_eq!(vmap.read32(0x20), 0xFFFFFFFF);
+
+        assert_eq!(vmap.read8(0x20), 0xFF);
+        assert_eq!(vmap.read8(0x21), 0xFF);
+        assert_eq!(vmap.read8(0x22), 0xFF);
+        assert_eq!(vmap.read8(0x23), 0xFF);
+
+        Ok(())
+    }
+}
Signature · 1 line
2.53.0
#17 lore raw

Re: [PATCH v12 5/5] rust: drm: gem: Add vmap functions to shmem bindings

Quoted 27 lines · Lyude Paul

One of the more obvious use cases for gem shmem objects is the ability to create mappings into their contents. So, let's hook this up in our rust bindings.

Similar to how we handle SGTables, we make sure there's two different types of mappings: owned mappings (kernel::drm::gem::shmem::VMap) and borrowed mappings (kernel::drm::gem::shmem::VMapRef).

---
V7:
* Switch over to the new iosys map bindings that use the Io trait V8:
* Get rid of iosys_map bindings for now, only support non-iomem types
* s/as_shmem()/as_raw_shmem()
V9:
* Get rid of some outdated comments I missed
* Add missing SIZE check to raw_vmap()
* Add a proper unit test that ensures that we actually validate SIZE at compile-time.
Turns out it takes only 34 lines to make a boilerplate DRM driver for a kunit test :)
* Add unit tests
* Add some missing #[inline]s
V10:
* Correct issue with iomem error path

Quoted 8 lines

We previously called raw_vunmap() if we got an iomem allocation, but raw_vunmap() was written such that it assumed all allocations were sysmem allocations. Fix this by just making raw_vunmap() accept a iosys_map.
V11:
* Use Alexandre's clever solution to remove the macros we were using for maintaining two different VMap types.
* Change the order of items in Object<T> to ensure that sgt_res is always dropped before obj.

I am not sure this is enough to solve the double-free issue - although my GEM knowledge is lacking, so please take this with a grain of salt.

Take an object where we called sg_table, so the SGT has been created.

When the object is dropped by DRM, free_callback is first called. It calls drm_gem_shmem_release, which frees the SGT.

Then, the Drop implementation of Object is called, and sgt_res is dropped... which attempts to free the SGT again.

I haven't tested that and rely only on a quick look at the code and my partial understanding, but the correct fix appears to be to clearing sgt_res in free_callback.

Quoted 56 lines

* Fix typo in Object.raw_vmap()

 rust/kernel/drm/gem/shmem.rs | 355 +++++++++++++++++++++++++++++++++++
 1 file changed, 355 insertions(+)
rust/kernel/drm/gem/shmem.rs +22 -0
index a477312c8a09b..b96de8d33141d 100644
@@ -26,6 +26,11 @@
         from_err_ptr,
         to_result, //
     },
+    io::{
+        Io,
+        IoCapable,
+        IoKnownSize, //
+    },
     prelude::*,
     scatterlist,
     types::{
@@ -35,6 +40,11 @@
 };
 use core::{
     cell::UnsafeCell,
+    ffi::c_void,
+    mem::{
+        self,
+        MaybeUninit, //
+    },
     ops::{
         Deref,
         DerefMut, //
@@ -45,6 +55,7 @@
     },
 };
 use gem::{
+    BaseObject,
     BaseObjectPrivate,
     DriverObject,
     IntoGEMObject, //
@@ -289,6 +300,84 @@ pub fn owned_sg_table(&self, dev: &device::Device<Bound>) -> Result<SGTable<T>>
         // `Some(Devres<SGTableMap<T>>)`.
         Ok(SGTable(self.into()))
     }
+
+    /// Attempt to create a vmap from the gem object, and confirm the size of said vmap.
+    fn raw_vmap(&self, min_size: usize) -> Result<*mut c_void> {
+        if self.size() < min_size {
+            return Err(ENOSPC);
+        }
+
+        let mut map: MaybeUninit<bindings::iosys_map> = MaybeUninit::uninit();
+
+        // SAFETY: drm_gem_shmem_vmap can be called with the DMA reservation lock held
+        to_result(unsafe {

rust/kernel/drm/gem/shmem.rs pub fn owned_sg_table(&self, dev: &device::Device<Bound>) -> Result<SGTable<T>> · line 323

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +10 -0
+            // TODO: see top of file
+            bindings::dma_resv_lock(self.raw_dma_resv(), ptr::null_mut());
+            let ret = bindings::drm_gem_shmem_vmap_locked(self.as_raw_shmem(), map.as_mut_ptr());
+            bindings::dma_resv_unlock(self.raw_dma_resv());
+            ret
+        })?;
+
+        // SAFETY: The call to drm_gem_shmem_vmap_locked succeeded above, so we are guaranteed that
+        // map is properly initialized.
+        let map = unsafe { map.assume_init() };

With the DMA reservation guard I suggested in the previous patch, this can become

    let map = {
        let mut map: MaybeUninit<bindings::iosys_map> = MaybeUninit::uninit();
        let _dma_resv = DmaResvGuard::new(self);

        // SAFETY: drm_gem_shmem_vmap can be called with the DMA reservation lock held
        to_result(unsafe {
            bindings::drm_gem_shmem_vmap_locked(self.as_raw_shmem(), map.as_mut_ptr())
        })?;

        // SAFETY: The call to drm_gem_shmem_vmap_locked succeeded above, so we are guaranteed that
        // map is properly initialized.
        unsafe { map.assume_init() }
    };
Quoted 47 lines
rust/kernel/drm/gem/shmem.rs +47 -0
+
+        // XXX: We don't currently support iomem allocations
+        if map.is_iomem {
+            // SAFETY:
+            // - The vmap operation above succeeded, guaranteeing that `map` points to a valid
+            //   memory mapping.
+            // - We checked that this is an iomem allocation, making it safe to read vaddr_iomem
+            unsafe { self.raw_vunmap(map) };
+
+            Err(ENOTSUPP)
+        } else {
+            // SAFETY: We checked that this is not an iomem allocation, making it safe to read vaddr
+            Ok(unsafe { map.__bindgen_anon_1.vaddr })
+        }
+    }
+
+    /// Unmap a vmap from the gem object.
+    ///
+    /// # Safety
+    ///
+    /// - The caller promises that `map` is a valid vmap on this gem object.
+    /// - The caller promises that the memory pointed to by map will no longer be accesed through
+    ///   this instance.
+    unsafe fn raw_vunmap(&self, mut map: bindings::iosys_map) {
+        let resv = self.raw_dma_resv();
+
+        // SAFETY:
+        // - This function is safe to call with the DMA reservation lock held
+        // - Our `ARef` is proof that the underlying gem object here is initialized and thus safe to
+        //   dereference.
+        unsafe {
+            // TODO: see top of file
+            bindings::dma_resv_lock(resv, ptr::null_mut());
+            bindings::drm_gem_shmem_vunmap_locked(self.as_raw_shmem(), &mut map);
+            bindings::dma_resv_unlock(resv);
+        }
+    }
+
+    /// Creates and returns a virtual kernel memory mapping for this object.
+    #[inline]
+    pub fn vmap<const SIZE: usize>(&self) -> Result<VMapRef<'_, T, SIZE>> {
+        Ok(VMap {
+            // INVARIANT: `raw_vmap()` checks that the gem object is at least as large as `SIZE`.
+            addr: self.raw_vmap(SIZE)?,
+            owner: self,
+        })
+    }

rust/kernel/drm/gem/shmem.rs pub fn owned_sg_table(&self, dev: &device::Device<Bound>) -> Result<SGTable<T>> · line 380

Quoted 10 lines
rust/kernel/drm/gem/shmem.rs +10 -0
+
+    /// Creates and returns an owned reference to a virtual kernel memory mapping for this object.
+    #[inline]
+    pub fn owned_vmap<const SIZE: usize>(&self) -> Result<VMapOwned<T, SIZE>> {
+        Ok(VMap {
+            // INVARIANT: `raw_vmap()` checks that the gem object is at least as large as `SIZE`.
+            addr: self.raw_vmap(SIZE)?,
+            owner: self.into(),
+        })
+    }

You can factor out some of the code into a generic private method:

    fn make_vmap<R, const SIZE: usize>(&self, owner: R) -> Result<VMap<T, R, SIZE>>
    where
        R: Deref<Target = Object<T>>,
    {
        Ok(VMap {
            // INVARIANT: `raw_vmap()` checks that the gem object is at least as large as `SIZE`.
            addr: self.raw_vmap(SIZE)?,
            owner,
        })
    }

    /// Creates and returns a virtual kernel memory mapping for this object.
    #[inline]
    pub fn vmap<const SIZE: usize>(&self) -> Result<VMapRef<'_, T, SIZE>> {
        self.make_vmap(self)
    }

    /// Creates and returns an owned reference to a virtual kernel memory mapping for this object.
    #[inline]
    pub fn owned_vmap<const SIZE: usize>(&self) -> Result<VMapOwned<T, SIZE>> {
        self.make_vmap(self.into())
    }

It doesn't result in less LoCs, but reduces duplication and removes one INVARIANT statement.

#18 lore raw

Re: [PATCH v12 5/5] rust: drm: gem: Add vmap functions to shmem bindings

Quoted 13 lines · Alexandre Courbot
Quoted 1 line

   dropped before obj.

I am not sure this is enough to solve the double-free issue - although my GEM
knowledge is lacking, so please take this with a grain of salt.

Take an object where we called sg_table, so the SGT has been created.

When the object is dropped by DRM, free_callback is first called. It
calls drm_gem_shmem_release, which frees the SGT.

Quoted 8 lines

Then, the Drop implementation of Object is called, and sgt_res is
dropped... which attempts to free the SGT again.

I haven't tested that and rely only on a quick look at the code and my
partial understanding, but the correct fix appears to be to clearing sgt_res in free_callback.

Whoops! No you're right, and so is Deborah (she mentioned this previously, but when reading through it I completely forgot that free_callback() was in the picture). We can't clear SetOnce, but we can use mem::take() which should be essentially the same thing. Will fix in the next respin