Skip to contentSkip to conversation

gpu: nova-core: prepare GpuMm for shared access

PATCH Applied Danilo Krummrich 2 participants 8 messages Nov 26 – Dec 1

Subsystems (4)
lore
Share & tools
lore

Danilo Krummrich

author maintainer
#0 lore raw

cover gpu: nova-core: prepare GpuMm for shared access

Give PRAMIN independent locking so GpuMm can be accessed through shared references. Initialize GpuMm in place so PRAMIN and TLB can be embedded directly, eliminating their separate heap allocations.

Danilo Krummrich (4):
gpu: nova-core: mm: serialize PRAMIN access
gpu: nova-core: mm: use shared references to GpuMm
gpu: nova-core: mm: initialize GpuMm in place
gpu: nova-core: mm: remove SharedPramin

 drivers/gpu/nova-core/gpu.rs               | 18 ++++----
 drivers/gpu/nova-core/mm.rs                | 42 ++++++++++++------
 drivers/gpu/nova-core/mm/bar_user.rs       | 45 +++++++++++--------
 drivers/gpu/nova-core/mm/pagetable/map.rs  | 50 +++++++++++-----------
 drivers/gpu/nova-core/mm/pagetable/walk.rs |  6 +--
 drivers/gpu/nova-core/mm/vmm.rs            | 10 ++---
 6 files changed, 98 insertions(+), 73 deletions(-)

base-commit: 94c9ad2fd7a15f58782c50e471397d1efe6b6363

Signature · 1 line
2.56.1
author maintainer
#1 lore raw

PATCH 1/4 gpu: nova-core: mm: serialize PRAMIN access

PRAMIN window selection and access must be serialized so that the window cannot move while it is in use. Give PRAMIN its own synchronization, independent of its GpuMm container, so sharing the memory manager does not require serializing unrelated VRAM allocation and TLB operations.

Keep the lock across page table walks and update batches to avoid acquiring it separately for every entry.

---
 drivers/gpu/nova-core/mm.rs                | 21 ++++++++----
 drivers/gpu/nova-core/mm/bar_user.rs       | 39 ++++++++++++++--------
 drivers/gpu/nova-core/mm/pagetable/map.rs  | 34 +++++++++----------
 drivers/gpu/nova-core/mm/pagetable/walk.rs |  2 +-
 drivers/gpu/nova-core/mm/pramin.rs         | 34 +++++++++++++++++++
 5 files changed, 91 insertions(+), 39 deletions(-)
drivers/gpu/nova-core/mm.rs +14 -7
index f53886f9ed91..bbe23dc6351f 100644
@@ -72,11 +72,11 @@ macro_rules! impl_pfn_bounded {
 ///
 /// Provides centralized ownership of memory management resources:
 /// - [`GpuBuddy`] allocator for VRAM page table allocation.
-/// - [`pramin::Pramin`] for direct VRAM access.
+/// - [`pramin::SharedPramin`] for direct VRAM access.
 /// - [`Tlb`] manager for translation buffer flush operations.
 pub(crate) struct GpuMm<'gpu> {
     buddy: GpuBuddy,
-    pramin: pramin::Pramin<'gpu>,
+    pramin: Pin<KBox<pramin::SharedPramin<'gpu>>>,
     tlb: Pin<KBox<Tlb<'gpu>>>,
 }
 
@@ -94,7 +94,10 @@ pub(crate) fn new(
 
         Ok(Self {
             buddy: GpuBuddy::new(buddy_params)?,
-            pramin: pramin::Pramin::new(bar, chipset, vram_region)?,
+            pramin: KBox::pin_init(
+                pramin::SharedPramin::new(bar, chipset, vram_region),
+                GFP_KERNEL,
+            )?,
             tlb: KBox::pin_init(Tlb::new(bar), GFP_KERNEL)?,
         })
     }
@@ -104,9 +107,11 @@ pub(crate) fn buddy(&self) -> &GpuBuddy {
         &self.buddy
     }
 
-    /// Access the [`pramin::Pramin`].
-    fn pramin_mut(&mut self) -> &mut pramin::Pramin<'gpu> {
-        &mut self.pramin
+    /// Runs `f` with exclusive access to the PRAMIN window.
+    ///
+    /// Do not perform reclaimable allocations in `f`.
+    fn with_pramin_locked<R>(&self, f: impl FnOnce(&mut pramin::Pramin<'_>) -> R) -> R {
+        self.pramin.with_locked(f)
     }
 
     /// Access the [`Tlb`] manager.
@@ -329,7 +334,9 @@ pub(crate) fn run(
             return Ok(());
         };
 
-        pramin::selftest::run(dev, mm.pramin_mut(), VramAddress::from_raw(base))?;
+        mm.with_pramin_locked(|pramin| {
+            pramin::selftest::run(dev, pramin, VramAddress::from_raw(base))
+        })?;
         bar_user::run_self_test(dev, mm, bar_user, bar1_pdb, chipset)
     }
 }
drivers/gpu/nova-core/mm/bar_user.rs +25 -14
index 2e8bd2a8ed91..f25ead64bf53 100644
@@ -213,7 +213,12 @@ pub(crate) fn run_self_test(
     let pdb_addr = VramAddress::from_raw(bar1_pdb);
 
     // Check if initial page tables are in VRAM.
-    if crate::mm::pagetable::check_pdb_valid(mm.pramin_mut(), pdb_addr, chipset).is_err() {
+    if mm
+        .with_pramin_locked(|pramin| {
+            crate::mm::pagetable::check_pdb_valid(pramin, pdb_addr, chipset)
+        })
+        .is_err()
+    {
         dev_info!(dev, "MM: Self-test SKIPPED - no valid VRAM page tables\n");
         return Ok(());
     }
@@ -246,10 +251,13 @@ pub(crate) fn run_self_test(
     let vram_read_addr = test_vram + 0x100;
 
     // Test 1: Write via PRAMIN, read via BAR1.
-    mm.pramin_mut()
-        .window_at::<u32>(vram_read_addr)?
-        .view()
-        .write_val(PATTERN_PRAMIN);
+    mm.with_pramin_locked(|pramin| -> Result {
+        pramin
+            .window_at::<u32>(vram_read_addr)?
+            .view()
+            .write_val(PATTERN_PRAMIN);
+        Ok(())
+    })?;
 
     // Read back via BAR1 aperture.
     let bar1_value = bar1.try_read32(bar1_read_offset)?;
@@ -353,11 +361,11 @@ pub(crate) fn run_self_test(
 
             bar1.try_write32(PATTERN_BAR1, page_bar1_off)?;
 
-            let pramin_val = mm
-                .pramin_mut()
-                .window_at::<u32>(VramAddress::from_raw(page_phys))?
-                .view()
-                .read_val();
+            let pramin_val = mm.with_pramin_locked(|pramin| {
+                pramin
+                    .window_at::<u32>(VramAddress::from_raw(page_phys))
+                    .map(|window| window.view().read_val())
+            })?;
 
             if pramin_val != PATTERN_BAR1 {
                 dev_err!(
@@ -392,10 +400,13 @@ pub(crate) fn run_self_test(
     let access = bar_user.map(mm, &[test_pfn], true)?;
 
     // Write pattern via PRAMIN, read via BarUserAccess.
-    mm.pramin_mut()
-        .window_at::<u32>(test_vram)?
-        .view()
-        .write_val(PATTERN_BAR1);
+    mm.with_pramin_locked(|pramin| -> Result {
+        pramin
+            .window_at::<u32>(test_vram)?
+            .view()
+            .write_val(PATTERN_BAR1);
+        Ok(())
+    })?;
 
     let readback = access.try_read32(0)?;
     let test4_passed = if readback == PATTERN_BAR1 {
drivers/gpu/nova-core/mm/pagetable/map.rs +17 -17
index f7774b9cc972..ba23cd3c2b25 100644
@@ -96,12 +96,13 @@ fn alloc_and_zero_page(mm: &mut GpuMm<'_>, level: PageTableLevel) -> Result<Prep
         let page_vram = VramAddress::from_raw(blocks.iter().next().ok_or(ENOMEM)?.offset());
 
         // Zero via PRAMIN.
-        let window = mm
-            .pramin_mut()
-            .window_at::<[u64; PAGE_SIZE / 8]>(page_vram)?;
-        for i in 0..PAGE_SIZE / 8 {
-            io_write!(window.view(), [build: i], 0);
-        }
+        mm.with_pramin_locked(|pramin| -> Result {
+            let window = pramin.window_at::<[u64; PAGE_SIZE / 8]>(page_vram)?;
+            for i in 0..PAGE_SIZE / 8 {
+                io_write!(window.view(), [build: i], 0);
+            }
+            Ok(())
+        })?;
 
         Ok(PreparedPtPage {
             alloc: blocks,
@@ -121,16 +122,16 @@ fn ensure_single_pte_path(
         let max_iter = 2 * M::PDE_LEVELS.len();
 
         for _ in 0..max_iter {
-            let result = self
-                .walker
-                .walk_pde_levels(mm.pramin_mut(), vfn, |install_addr| {
+            let result = mm.with_pramin_locked(|pramin| {
+                self.walker.walk_pde_levels(pramin, vfn, |install_addr| {
                     pt_pages.get(&install_addr).and_then(|p| {
                         p.alloc
                             .iter()
                             .next()
                             .map(|b| VramAddress::from_raw(b.offset()))
                     })
-                })?;
+                })
+            })?;
 
             match result {
                 WalkPdeResult::Complete { .. } => {
@@ -199,9 +200,7 @@ pub(super) fn install_mappings(
         pfns: &[Pfn],
         writable: bool,
     ) -> Result {
-        {
-            let pramin = mm.pramin_mut();
-
+        mm.with_pramin_locked(|pramin| -> Result {
             // Drain prepared PT pages, install all pending PDEs.
             let mut cursor = pt_pages.cursor_front_mut();
             while let Some(c) = cursor {
@@ -242,7 +241,8 @@ pub(super) fn install_mappings(
                     }
                 }
             }
-        }
+            Ok(())
+        })?;
 
         // Flush TLB.
         mm.tlb().flush(self.pdb_addr)
@@ -257,8 +257,7 @@ pub(super) fn invalidate_ptes(
     ) -> Result {
         let invalid_pte = M::Pte::invalid();
 
-        {
-            let pramin = mm.pramin_mut();
+        mm.with_pramin_locked(|pramin| -> Result {
             for i in 0..num_pages {
                 let i_u64: u64 = i.into_safe_cast();
                 let vfn = Vfn::new(vfn_start.raw() + i_u64);
@@ -273,7 +272,8 @@ pub(super) fn invalidate_ptes(
                     }
                 }
             }
-        }
+            Ok(())
+        })?;
 
         mm.tlb().flush(self.pdb_addr)
     }
drivers/gpu/nova-core/mm/pagetable/walk.rs +1 -1
index 76c1729971f5..899c61888756 100644
@@ -172,7 +172,7 @@ pub(super) fn walk_pde_levels(
     ///
     /// Returns [`WalkResult::PageTableMissing`] if intermediate tables don't exist.
     pub(super) fn walk_to_pte_lookup(&self, mm: &mut GpuMm<'_>, vfn: Vfn) -> Result<WalkResult> {
-        self.walk_to_pte_lookup_with_window(mm.pramin_mut(), vfn)
+        mm.with_pramin_locked(|pramin| self.walk_to_pte_lookup_with_window(pramin, vfn))
     }
 
     /// Walk to PTE using a caller-provided PRAMIN manager (lookup only).
drivers/gpu/nova-core/mm/pramin.rs +34 -0
index c83b1681d241..841289d7bccc 100644
@@ -13,6 +13,7 @@
         Io,
         Mmio, //
     },
+    new_mutex,
     prelude::*,
     ptr::{
         Alignable,
@@ -22,6 +23,7 @@
         SizeConstants,
         SZ_1M, //
     },
+    sync::Mutex, //
 };
 
 use crate::{
@@ -54,6 +56,38 @@
     PRAMIN: PraminWindow @ 0x700000;
 }
 
+/// A [`Pramin`] shared between users, serialized by a mutex.
+#[pin_data]
+pub(super) struct SharedPramin<'gpu>
+where
+    // Hide the mutex's invariant resource lifetime so `SharedPramin` remains covariant.
+    exists<'res>: 'gpu,
+{
+    #[pin]
+    #[uses('res: invariant)]
+    inner: Mutex<Pramin<'res>>,
+}
+
+impl<'gpu> SharedPramin<'gpu> {
+    /// Creates the shared window manager for the given VRAM region.
+    pub(super) fn new(
+        bar: Bar0<'gpu>,
+        chipset: Chipset,
+        vram_range: Range<VramAddress>,
+    ) -> impl PinInit<Self, Error> {
+        try_pin_init!(Self {
+            inner <- new_mutex!(Pramin::new(bar, chipset, vram_range)?, "pramin"),
+        })
+    }
+
+    /// Runs `f` with exclusive access to the PRAMIN window.
+    ///
+    /// Do not perform reclaimable allocations in `f`.
+    pub(super) fn with_locked<R>(&self, f: impl FnOnce(&mut Pramin<'_>) -> R) -> R {
+        self.with_inner(|inner| f(&mut inner.lock()))
+    }
+}
+
 /// Owner of the PRAMIN window state.
 ///
 /// [`Pramin::window_at()`] repositions the window as needed and returns a typed MMIO view into
Signature · 1 line
2.56.1
#2 lore raw

Re: [PATCH 1/4] gpu: nova-core: mm: serialize PRAMIN access

Quoted 22 lines · Danilo Krummrich

PRAMIN window selection and access must be serialized so that the window cannot move while it is in use. Give PRAMIN its own synchronization, independent of its GpuMm container, so sharing the memory manager does not require serializing unrelated VRAM allocation and TLB operations.

Keep the lock across page table walks and update batches to avoid acquiring it separately for every entry.

---
 drivers/gpu/nova-core/mm.rs                | 21 ++++++++----
 drivers/gpu/nova-core/mm/bar_user.rs       | 39 ++++++++++++++--------
 drivers/gpu/nova-core/mm/pagetable/map.rs  | 34 +++++++++----------
 drivers/gpu/nova-core/mm/pagetable/walk.rs |  2 +-
 drivers/gpu/nova-core/mm/pramin.rs         | 34 +++++++++++++++++++
 5 files changed, 91 insertions(+), 39 deletions(-)
drivers/gpu/nova-core/mm.rs +0 -0
index f53886f9ed91..bbe23dc6351f 100644

drivers/gpu/nova-core/mm.rs macro_rules! impl_pfn_bounded { · line 79

Quoted 10 lines
drivers/gpu/nova-core/mm.rs +2 -2
@@ -72,11 +72,11 @@ macro_rules! impl_pfn_bounded {
 ///
 /// Provides centralized ownership of memory management resources:
 /// - [`GpuBuddy`] allocator for VRAM page table allocation.
-/// - [`pramin::Pramin`] for direct VRAM access.
+/// - [`pramin::SharedPramin`] for direct VRAM access.
 /// - [`Tlb`] manager for translation buffer flush operations.
 pub(crate) struct GpuMm<'gpu> {
     buddy: GpuBuddy,
-    pramin: pramin::Pramin<'gpu>,
+    pramin: Pin<KBox<pramin::SharedPramin<'gpu>>>,

Nice, this is probably going to remove the SharedGpuMm I introduced (and hated) in the vGPU series. :)

A couple of comments below.

<...>

Quoted 24 lines

index f7774b9cc972..ba23cd3c2b25 100644

drivers/gpu/nova-core/mm/pagetable/map.rs +7 -6
@@ -96,12 +96,13 @@ fn alloc_and_zero_page(mm: &mut GpuMm<'_>, level: PageTableLevel) -> Result<Prep
         let page_vram = VramAddress::from_raw(blocks.iter().next().ok_or(ENOMEM)?.offset());
 
         // Zero via PRAMIN.
-        let window = mm
-            .pramin_mut()
-            .window_at::<[u64; PAGE_SIZE / 8]>(page_vram)?;
-        for i in 0..PAGE_SIZE / 8 {
-            io_write!(window.view(), [build: i], 0);
-        }
+        mm.with_pramin_locked(|pramin| -> Result {
+            let window = pramin.window_at::<[u64; PAGE_SIZE / 8]>(page_vram)?;
+            for i in 0..PAGE_SIZE / 8 {
+                io_write!(window.view(), [build: i], 0);
+            }
+            Ok(())
+        })?;
 
         Ok(PreparedPtPage {
             alloc: blocks,

drivers/gpu/nova-core/mm/pagetable/map.rs fn ensure_single_pte_path( · line 125

Quoted 7 lines
drivers/gpu/nova-core/mm/pagetable/map.rs +1 -3
@@ -121,16 +122,16 @@ fn ensure_single_pte_path(
         let max_iter = 2 * M::PDE_LEVELS.len();
 
         for _ in 0..max_iter {
-            let result = self
-                .walker
-                .walk_pde_levels(mm.pramin_mut(), vfn, |install_addr| {
+            let result = mm.with_pramin_locked(|pramin| {

nit: With this the method-level doccomment should be about the PRAMIN lock being released instead of the borrow.

<...>

Quoted 41 lines
drivers/gpu/nova-core/mm/pramin.rs +19 -0
index c83b1681d241..841289d7bccc 100644
@@ -13,6 +13,7 @@
         Io,
         Mmio, //
     },
+    new_mutex,
     prelude::*,
     ptr::{
         Alignable,
@@ -22,6 +23,7 @@
         SizeConstants,
         SZ_1M, //
     },
+    sync::Mutex, //
 };
 
 use crate::{
@@ -54,6 +56,38 @@
     PRAMIN: PraminWindow @ 0x700000;
 }
 
+/// A [`Pramin`] shared between users, serialized by a mutex.
+#[pin_data]
+pub(super) struct SharedPramin<'gpu>
+where
+    // Hide the mutex's invariant resource lifetime so `SharedPramin` remains covariant.
+    exists<'res>: 'gpu,
+{
+    #[pin]
+    #[uses('res: invariant)]
+    inner: Mutex<Pramin<'res>>,
+}
+
+impl<'gpu> SharedPramin<'gpu> {
+    /// Creates the shared window manager for the given VRAM region.
+    pub(super) fn new(
+        bar: Bar0<'gpu>,
+        chipset: Chipset,

drivers/gpu/nova-core/mm/pramin.rs line 85

Quoted 10 lines
drivers/gpu/nova-core/mm/pramin.rs +10 -0
+        vram_range: Range<VramAddress>,
+    ) -> impl PinInit<Self, Error> {
+        try_pin_init!(Self {
+            inner <- new_mutex!(Pramin::new(bar, chipset, vram_range)?, "pramin"),
+        })
+    }
+
+    /// Runs `f` with exclusive access to the PRAMIN window.
+    ///
+    /// Do not perform reclaimable allocations in `f`.

A little elaboration on why (deadlocks in the fence signaling path) would be nice here. Something similar to what Tlb::lock has maybe, and maybe we should also put that information into some module-level paragraph that we can refer to instead of repeating it as it is relevant in several places.

author maintainer
#3 lore raw

PATCH 2/4 gpu: nova-core: mm: use shared references to GpuMm

In reply to Danilo Krummrich

The components owned by GpuMm now provide their own synchronization.

Accept shared references to the memory manager so independent users can access these resources without requiring a lock around the container.

---
 drivers/gpu/nova-core/gpu.rs               | 13 ++++++-------
 drivers/gpu/nova-core/mm.rs                |  2 +-
 drivers/gpu/nova-core/mm/bar_user.rs       |  6 +++---
 drivers/gpu/nova-core/mm/pagetable/map.rs  | 16 ++++++++--------
 drivers/gpu/nova-core/mm/pagetable/walk.rs |  4 ++--
 drivers/gpu/nova-core/mm/vmm.rs            | 10 +++++-----
 6 files changed, 25 insertions(+), 26 deletions(-)
drivers/gpu/nova-core/gpu.rs +6 -7
index 8ab1687847ff..39e57e724a71 100644
@@ -613,18 +613,17 @@ pub(crate) fn wait_gfw_boot_completion(
 
     /// Runs self-tests on the constructed [`Gpu`], logging failures without failing probe.
     #[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
-    pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device<device::Bound>) {
-        let this = self.project();
+    pub(crate) fn run_selftests(&self, pdev: &pci::Device<device::Bound>) {
         let dev = pdev.as_ref();
-        let regions = &this.gsp_static_info.usable_fb_regions;
+        let regions = &self.gsp_static_info.usable_fb_regions;
 
         if let Err(err) = crate::mm::selftest::run(
             dev,
-            this.mm,
+            &self.mm,
             regions,
-            &this.bar_user,
-            this.gsp_static_info.bar1_pde_base,
-            this.spec.chipset,
+            &self.bar_user,
+            self.gsp_static_info.bar1_pde_base,
+            self.spec.chipset,
         ) {
             dev_err!(dev, "self-tests failed: {:?}\n", err);
         }
drivers/gpu/nova-core/mm.rs +1 -1
index bbe23dc6351f..30a394424e12 100644
@@ -311,7 +311,7 @@ pub(crate) mod selftest {
     /// Run MM subsystem self-tests during probe.
     pub(crate) fn run(
         dev: &device::Device<device::Bound>,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         usable_fb_regions: &[Range<u64>],
         bar_user: &bar_user::BarUser<'_>,
         bar1_pdb: u64,
drivers/gpu/nova-core/mm/bar_user.rs +3 -3
index f25ead64bf53..483129d3d0f7 100644
@@ -61,7 +61,7 @@ pub(crate) fn new(
     /// Map physical pages to a contiguous BAR1 virtual range.
     pub(crate) fn map(
         &self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         pfns: &[Pfn],
         writable: bool,
     ) -> Result<BarUserAccess<'_>> {
@@ -91,7 +91,7 @@ pub(crate) struct BarUserAccess<'a> {
 #[expect(dead_code)]
 impl BarUserAccess<'_> {
     /// Tear down the BAR1 mapping.
-    pub(crate) fn release(mut self, mm: &mut GpuMm<'_>) -> Result {
+    pub(crate) fn release(mut self, mm: &GpuMm<'_>) -> Result {
         let mapped = self.mapped.take().ok_or(EINVAL)?;
         let mut vmm = self.bar_user.vmm.lock();
         vmm.unmap_pages(mm, mapped)?;
@@ -183,7 +183,7 @@ fn drop(&mut self) {
 #[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
 pub(crate) fn run_self_test(
     dev: &device::Device<device::Bound>,
-    mm: &mut GpuMm<'_>,
+    mm: &GpuMm<'_>,
     bar_user: &BarUser<'_>,
     bar1_pdb: u64,
     chipset: Chipset,
drivers/gpu/nova-core/mm/pagetable/map.rs +8 -8
index ba23cd3c2b25..22e44386423f 100644
@@ -82,7 +82,7 @@ pub(super) fn new(pdb_addr: VramAddress) -> Self {
     }
 
     /// Allocate and zero a physical page table page.
-    fn alloc_and_zero_page(mm: &mut GpuMm<'_>, level: PageTableLevel) -> Result<PreparedPtPage> {
+    fn alloc_and_zero_page(mm: &GpuMm<'_>, level: PageTableLevel) -> Result<PreparedPtPage> {
         let blocks = KBox::pin_init(
             mm.buddy().alloc_blocks(
                 GpuBuddyAllocMode::Simple,
@@ -115,7 +115,7 @@ fn alloc_and_zero_page(mm: &mut GpuMm<'_>, level: PageTableLevel) -> Result<Prep
     /// The mutable PRAMIN borrow ends before each allocation.
     fn ensure_single_pte_path(
         &self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         vfn: Vfn,
         pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
     ) -> Result {
@@ -168,7 +168,7 @@ fn ensure_single_pte_path(
     /// per-VFN to prepare pages for all missing PDEs.
     pub(super) fn prepare_map(
         &self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         vfn_start: Vfn,
         num_pages: usize,
         page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
@@ -193,7 +193,7 @@ pub(super) fn prepare_map(
     /// Drains `pt_pages` and moves allocations into `page_table_allocs`.
     pub(super) fn install_mappings(
         &self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
         page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
         vfn_start: Vfn,
@@ -251,7 +251,7 @@ pub(super) fn install_mappings(
     /// Invalidate PTEs for a range and flush TLB.
     pub(super) fn invalidate_ptes(
         &self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         vfn_start: Vfn,
         num_pages: usize,
     ) -> Result {
@@ -308,7 +308,7 @@ pub(in crate::mm) fn new(pdb_addr: VramAddress, version: MmuVersion) -> Self {
     /// Prepare page table resources for a mapping.
     pub(in crate::mm) fn prepare_map(
         &self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         vfn_start: Vfn,
         num_pages: usize,
         page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
@@ -323,7 +323,7 @@ pub(in crate::mm) fn prepare_map(
     /// Install prepared PDEs and write PTEs, then flush TLB.
     pub(in crate::mm) fn install_mappings(
         &self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
         page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
         vfn_start: Vfn,
@@ -339,7 +339,7 @@ pub(in crate::mm) fn install_mappings(
     /// Invalidate PTEs for a range and flush TLB.
     pub(in crate::mm) fn invalidate_ptes(
         &self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         vfn_start: Vfn,
         num_pages: usize,
     ) -> Result {
drivers/gpu/nova-core/mm/pagetable/walk.rs +2 -2
index 899c61888756..59a011148455 100644
@@ -171,7 +171,7 @@ pub(super) fn walk_pde_levels(
     /// Walk to PTE for lookup only (no allocation).
     ///
     /// Returns [`WalkResult::PageTableMissing`] if intermediate tables don't exist.
-    pub(super) fn walk_to_pte_lookup(&self, mm: &mut GpuMm<'_>, vfn: Vfn) -> Result<WalkResult> {
+    pub(super) fn walk_to_pte_lookup(&self, mm: &GpuMm<'_>, vfn: Vfn) -> Result<WalkResult> {
         mm.with_pramin_locked(|pramin| self.walk_to_pte_lookup_with_window(pramin, vfn))
     }
 
@@ -238,7 +238,7 @@ pub(in crate::mm) fn new(pdb_addr: VramAddress, version: MmuVersion) -> Self {
     }
 
     /// Walk to PTE for lookup.
-    pub(in crate::mm) fn walk_to_pte(&self, mm: &mut GpuMm<'_>, vfn: Vfn) -> Result<WalkResult> {
+    pub(in crate::mm) fn walk_to_pte(&self, mm: &GpuMm<'_>, vfn: Vfn) -> Result<WalkResult> {
         pt_walk_dispatch!(self, walk_to_pte_lookup(mm, vfn))
     }
 }
drivers/gpu/nova-core/mm/vmm.rs +5 -5
index 51b500a27233..c8258e579f8b 100644
@@ -204,7 +204,7 @@ fn free_vfn(&self, vfn: Vfn) {
     }
 
     /// Read the [`Pfn`] for a mapped [`Vfn`] if one is mapped.
-    pub(super) fn read_mapping(&self, mm: &mut GpuMm<'_>, vfn: Vfn) -> Result<Option<Pfn>> {
+    pub(super) fn read_mapping(&self, mm: &GpuMm<'_>, vfn: Vfn) -> Result<Option<Pfn>> {
         match self.pt_walk.walk_to_pte(mm, vfn)? {
             WalkResult::Mapped { pfn, .. } => Ok(Some(pfn)),
             WalkResult::Unmapped { .. } | WalkResult::PageTableMissing => Ok(None),
@@ -220,7 +220,7 @@ pub(super) fn read_mapping(&self, mm: &mut GpuMm<'_>, vfn: Vfn) -> Result<Option
     /// to call outside the fence signalling critical path.
     pub(crate) fn prepare_map(
         &mut self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         num_pages: usize,
         va_range: Option<Range<u64>>,
     ) -> Result<PreparedMapping> {
@@ -254,7 +254,7 @@ pub(crate) fn prepare_map(
     /// Installs all prepared PDEs and writes PTEs into the page table, then flushes TLB.
     pub(crate) fn execute_map(
         &mut self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         prepared: PreparedMapping,
         pfns: &[Pfn],
         writable: bool,
@@ -297,7 +297,7 @@ pub(crate) fn execute_map(
     /// [`Vmm::execute_map()`] will be called separately.
     pub(crate) fn map_pages(
         &mut self,
-        mm: &mut GpuMm<'_>,
+        mm: &GpuMm<'_>,
         pfns: &[Pfn],
         va_range: Option<Range<u64>>,
         writable: bool,
@@ -324,7 +324,7 @@ pub(crate) fn map_pages(
     }
 
     /// Unmap all pages in a [`MappedRange`] with a single TLB flush.
-    pub(crate) fn unmap_pages(&mut self, mm: &mut GpuMm<'_>, range: MappedRange) -> Result {
+    pub(crate) fn unmap_pages(&mut self, mm: &GpuMm<'_>, range: MappedRange) -> Result {
         let result = self
             .pt_map
             .invalidate_ptes(mm, range.vfn_start, range.num_pages);
Signature · 1 line
2.56.1
author maintainer
#4 lore raw

PATCH 3/4 gpu: nova-core: mm: initialize GpuMm in place

In reply to Danilo Krummrich

The PRAMIN and TLB managers require stable addresses for their mutexes.

Pin-initialize GpuMm so they can be embedded directly instead of allocating each separately.

---
 drivers/gpu/nova-core/gpu.rs |  5 +++--
 drivers/gpu/nova-core/mm.rs  | 20 ++++++++++----------
 2 files changed, 13 insertions(+), 12 deletions(-)
drivers/gpu/nova-core/gpu.rs +3 -2
index 39e57e724a71..2f0399100885 100644
@@ -399,6 +399,7 @@ pub(crate) struct Gpu<'gpu> {
     ///
     /// Must be kept declared *before* `gsp_resources`, so that its components are dropped while
     /// the GSP is still operational.
+    #[pin]
     mm: GpuMm<'gpu>,
     /// BAR1 user interface for CPU access to GPU virtual memory.
     #[pin]
@@ -562,7 +563,7 @@ pub(crate) fn new<'a>(
             },
 
             // Create GPU memory manager owning memory management resources.
-            mm: {
+            mm <- {
                 let usable_vram = gsp_static_info.usable_fb_regions.first().ok_or(ENODEV)?;
                 let buddy_params = GpuBuddyParams {
                     base_offset: usable_vram.start,
@@ -575,7 +576,7 @@ pub(crate) fn new<'a>(
                     gsp_resources.spec.chipset,
                     buddy_params,
                     VramAddress::from_raw(gsp_static_info.total_fb_end),
-                )?
+                )
             },
 
             // Create BAR1 user interface for CPU access to GPU virtual memory.
drivers/gpu/nova-core/mm.rs +10 -10
index 30a394424e12..94c6f425c867 100644
@@ -74,10 +74,13 @@ macro_rules! impl_pfn_bounded {
 /// - [`GpuBuddy`] allocator for VRAM page table allocation.
 /// - [`pramin::SharedPramin`] for direct VRAM access.
 /// - [`Tlb`] manager for translation buffer flush operations.
+#[pin_data]
 pub(crate) struct GpuMm<'gpu> {
     buddy: GpuBuddy,
-    pramin: Pin<KBox<pramin::SharedPramin<'gpu>>>,
-    tlb: Pin<KBox<Tlb<'gpu>>>,
+    #[pin]
+    pramin: pramin::SharedPramin<'gpu>,
+    #[pin]
+    tlb: Tlb<'gpu>,
 }
 
 impl<'gpu> GpuMm<'gpu> {
@@ -87,18 +90,15 @@ pub(crate) fn new(
         chipset: Chipset,
         buddy_params: GpuBuddyParams,
         total_fb_end: VramAddress,
-    ) -> Result<Self> {
+    ) -> impl PinInit<Self, Error> {
         // PRAMIN covers all physical VRAM (including GSP-reserved areas
         // above the usable region, e.g. the BAR1 page directory).
         let vram_region = VramAddress::ZERO..total_fb_end;
 
-        Ok(Self {
+        try_pin_init!(Self {
             buddy: GpuBuddy::new(buddy_params)?,
-            pramin: KBox::pin_init(
-                pramin::SharedPramin::new(bar, chipset, vram_region),
-                GFP_KERNEL,
-            )?,
-            tlb: KBox::pin_init(Tlb::new(bar), GFP_KERNEL)?,
+            pramin <- pramin::SharedPramin::new(bar, chipset, vram_region),
+            tlb <- Tlb::new(bar),
         })
     }
 
@@ -116,7 +116,7 @@ fn with_pramin_locked<R>(&self, f: impl FnOnce(&mut pramin::Pramin<'_>) -> R) ->
 
     /// Access the [`Tlb`] manager.
     pub(crate) fn tlb(&self) -> &Tlb<'gpu> {
-        self.tlb.as_ref().get_ref()
+        &self.tlb
     }
 }
 
Signature · 1 line
2.56.1
author maintainer
#5 lore raw

PATCH 4/4 gpu: nova-core: mm: remove SharedPramin

In reply to Danilo Krummrich

SharedPramin was introduced as a temporary wrapper so its mutex could be pin-initialized separately while GpuMm remained movable. This allowed PRAMIN locking to remove the need for mutable GpuMm references before converting GpuMm itself to pin initialization.

Now that GpuMm is pin-initialized, it can embed Mutex<Pramin> directly and hide the mutex's invariant resource lifetime itself. Remove the temporary wrapper.

---
 drivers/gpu/nova-core/mm.rs        | 19 +++++++++++------
 drivers/gpu/nova-core/mm/pramin.rs | 34 ------------------------------
 2 files changed, 13 insertions(+), 40 deletions(-)
drivers/gpu/nova-core/mm.rs +13 -6
index 94c6f425c867..7aa8906d2cb2 100644
@@ -44,13 +44,15 @@ macro_rules! impl_pfn_bounded {
         GpuBuddy,
         GpuBuddyParams, //
     },
+    new_mutex,
     num::Bounded,
     prelude::*,
     ptr::{
         Alignable,
         Alignment, //
     },
-    sizes::SZ_4K, //
+    sizes::SZ_4K,
+    sync::Mutex, //
 };
 
 use crate::{
@@ -72,13 +74,18 @@ macro_rules! impl_pfn_bounded {
 ///
 /// Provides centralized ownership of memory management resources:
 /// - [`GpuBuddy`] allocator for VRAM page table allocation.
-/// - [`pramin::SharedPramin`] for direct VRAM access.
+/// - [`pramin::Pramin`] for direct VRAM access.
 /// - [`Tlb`] manager for translation buffer flush operations.
 #[pin_data]
-pub(crate) struct GpuMm<'gpu> {
+pub(crate) struct GpuMm<'gpu>
+where
+    // Hide the mutex's invariant resource lifetime so `GpuMm` remains covariant.
+    exists<'res>: 'gpu,
+{
     buddy: GpuBuddy,
     #[pin]
-    pramin: pramin::SharedPramin<'gpu>,
+    #[uses('res: invariant)]
+    pramin: Mutex<pramin::Pramin<'res>>,
     #[pin]
     tlb: Tlb<'gpu>,
 }
@@ -97,7 +104,7 @@ pub(crate) fn new(
 
         try_pin_init!(Self {
             buddy: GpuBuddy::new(buddy_params)?,
-            pramin <- pramin::SharedPramin::new(bar, chipset, vram_region),
+            pramin <- new_mutex!(pramin::Pramin::new(bar, chipset, vram_region)?, "pramin"),
             tlb <- Tlb::new(bar),
         })
     }
@@ -111,7 +118,7 @@ pub(crate) fn buddy(&self) -> &GpuBuddy {
     ///
     /// Do not perform reclaimable allocations in `f`.
     fn with_pramin_locked<R>(&self, f: impl FnOnce(&mut pramin::Pramin<'_>) -> R) -> R {
-        self.pramin.with_locked(f)
+        self.with_pramin(|pramin| f(&mut pramin.lock()))
     }
 
     /// Access the [`Tlb`] manager.
drivers/gpu/nova-core/mm/pramin.rs +0 -34
index 841289d7bccc..c83b1681d241 100644
@@ -13,7 +13,6 @@
         Io,
         Mmio, //
     },
-    new_mutex,
     prelude::*,
     ptr::{
         Alignable,
@@ -23,7 +22,6 @@
         SizeConstants,
         SZ_1M, //
     },
-    sync::Mutex, //
 };
 
 use crate::{
@@ -56,38 +54,6 @@
     PRAMIN: PraminWindow @ 0x700000;
 }
 
-/// A [`Pramin`] shared between users, serialized by a mutex.
-#[pin_data]
-pub(super) struct SharedPramin<'gpu>
-where
-    // Hide the mutex's invariant resource lifetime so `SharedPramin` remains covariant.
-    exists<'res>: 'gpu,
-{
-    #[pin]
-    #[uses('res: invariant)]
-    inner: Mutex<Pramin<'res>>,
-}
-
-impl<'gpu> SharedPramin<'gpu> {
-    /// Creates the shared window manager for the given VRAM region.
-    pub(super) fn new(
-        bar: Bar0<'gpu>,
-        chipset: Chipset,
-        vram_range: Range<VramAddress>,
-    ) -> impl PinInit<Self, Error> {
-        try_pin_init!(Self {
-            inner <- new_mutex!(Pramin::new(bar, chipset, vram_range)?, "pramin"),
-        })
-    }
-
-    /// Runs `f` with exclusive access to the PRAMIN window.
-    ///
-    /// Do not perform reclaimable allocations in `f`.
-    pub(super) fn with_locked<R>(&self, f: impl FnOnce(&mut Pramin<'_>) -> R) -> R {
-        self.with_inner(|inner| f(&mut inner.lock()))
-    }
-}
-
 /// Owner of the PRAMIN window state.
 ///
 /// [`Pramin::window_at()`] repositions the window as needed and returns a typed MMIO view into
Signature · 1 line
2.56.1
maintainer Reviewed-by on the v1 series
#6 lore raw
In reply to Danilo Krummrich
Quoted 9 lines · Danilo Krummrich

Give PRAMIN independent locking so GpuMm can be accessed through shared references. Initialize GpuMm in place so PRAMIN and TLB can be embedded directly, eliminating their separate heap allocations.

Danilo Krummrich (4):
gpu: nova-core: mm: serialize PRAMIN access
gpu: nova-core: mm: use shared references to GpuMm
gpu: nova-core: mm: initialize GpuMm in place
gpu: nova-core: mm: remove SharedPramin

Thanks, this is going to improve the vGPU code quite a bit.

The series,

author maintainer Applied
#7 lore raw
In reply to Danilo Krummrich
Quoted 1 line · Danilo Krummrich

[PATCH 0/4] gpu: nova-core: prepare GpuMm for shared access

Applied, thanks!

Branch: drm-rust-next
Tree: https://gitlab.freedesktop.org/drm/rust/kernel.git

[1/4] gpu: nova-core: mm: serialize PRAMIN access
commit: 7ababc20f587

[ Update the PRAMIN comments to refer to lock release and explain the
rationale behind the existing restriction on reclaimable allocations.
- Danilo ]

[2/4] gpu: nova-core: mm: use shared references to GpuMm

      commit: e12d79a3482e
[3/4] gpu: nova-core: mm: initialize GpuMm in place
      commit: 6065956b4e47
[4/4] gpu: nova-core: mm: remove SharedPramin
      commit: 73a8f8366b23

The patches will appear in the next linux-next integration (typically within 24 hours on weekdays).

The patches are queued up for the upcoming merge window for the next major kernel release.