* [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping
@ 2026-09-09 3:59 Eliot Courtney
2026-09-09 3:59 ` [PATCH 01/16] gpu: nova-core: mm: Add common types for virtual memory management Eliot Courtney
` (16 more replies)
0 siblings, 17 replies; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes, Zhi Wang
I am reposting Joel Fernandes's original series [1]. The rebase adapts
the patches to recent changes in the rust infra, like HRT lifetimes. It
also adapts to the changes I posted in [2]. It keeps Joel's design and
patch split.
From Joel's original cover letter:
This series introduces page-table types and a Virtual Memory Manager (VMM)
for the nova-core driver, plus a BAR1 user (with selftests) layered on top.
The page-table layer uses trait-based generics (PteOps, PdeOps, DualPdeOps,
MmuConfig) to dispatch between MMU v2 and v3 formats. The Vmm tracks
virtual-address ranges with a maple tree, and the BAR1 user exposes mapped
CPU access to VRAM through a small allocation API exercised by the selftests.
This series depends on Joel's maple tree Send and Sync patch [3] and his
PCI resource_flags() accessor [4], which I am reposting separately.
This series is based on drm-rust-next.
[1] https://lore.kernel.org/all/20260518181126.2493572-1-joelagnelf@nvidia.com/
[2] https://lore.kernel.org/all/20260827-pramin-split-v3-0-24b24d7afc52@nvidia.com/
[3] https://lore.kernel.org/all/20260511143604.3848176-1-joelagnelf@nvidia.com/
[4] https://lore.kernel.org/all/20260518180342.2387845-2-joelagnelf@nvidia.com/
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
Joel Fernandes (16):
gpu: nova-core: mm: Add common types for virtual memory management
gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm
gpu: nova-core: mm: Add common types for all page table formats
gpu: nova-core: mm: pagetable: Add PteOps trait
gpu: nova-core: mm: pagetable: Add PdeOps trait
gpu: nova-core: mm: pagetable: Add DualPdeOps trait
gpu: nova-core: mm: Add MMU v2 page table types
gpu: nova-core: mm: Add MMU v3 page table types
gpu: nova-core: mm: pagetable: Add MmuConfig trait
gpu: nova-core: mm: Add page table walker for MMU v2/v3
gpu: nova-core: mm: Add Virtual Memory Manager
gpu: nova-core: mm: Add virtual address range tracking to VMM
gpu: nova-core: mm: Add multi-page mapping API to VMM
gpu: nova-core: Add BAR1 aperture type and size constant
gpu: nova-core: mm: Add BAR1 user interface
gpu: nova-core: mm: Add BAR1 memory management self-tests
drivers/gpu/nova-core/Kconfig | 1 +
drivers/gpu/nova-core/driver.rs | 45 ++-
drivers/gpu/nova-core/gpu.rs | 68 ++++-
drivers/gpu/nova-core/gsp/commands.rs | 3 +
drivers/gpu/nova-core/gsp/fw/commands.rs | 8 +
drivers/gpu/nova-core/mm.rs | 177 +++++++++++-
drivers/gpu/nova-core/mm/bar_user.rs | 422 +++++++++++++++++++++++++++++
drivers/gpu/nova-core/mm/pagetable.rs | 422 +++++++++++++++++++++++++++++
drivers/gpu/nova-core/mm/pagetable/map.rs | 342 +++++++++++++++++++++++
drivers/gpu/nova-core/mm/pagetable/ver2.rs | 271 ++++++++++++++++++
drivers/gpu/nova-core/mm/pagetable/ver3.rs | 417 ++++++++++++++++++++++++++++
drivers/gpu/nova-core/mm/pagetable/walk.rs | 244 +++++++++++++++++
drivers/gpu/nova-core/mm/tlb.rs | 120 ++++++++
drivers/gpu/nova-core/mm/vmm.rs | 346 +++++++++++++++++++++++
drivers/gpu/nova-core/regs.rs | 68 +++++
15 files changed, 2937 insertions(+), 17 deletions(-)
---
base-commit: e6a2c988ed96a5a3af51ed97ecba980521bf2fc0
change-id: 20260805-mmrebase-113582afb003
prerequisite-change-id: 20260907-maple-tree-send-sync-a1479d1ab302:v2
prerequisite-patch-id: 81d532949891e2dd846cca5c420e4ba32e9161a7
prerequisite-change-id: 20260907-pci-resource-flags-b7addba0b34f:v1
prerequisite-patch-id: bdd1c2eb4adbedf1c53f1be61ea958743d2a2660
Best regards,
--
Eliot Courtney <ecourtney@nvidia.com>
^ permalink raw reply [flat|nested] 34+ messages in thread
* [PATCH 01/16] gpu: nova-core: mm: Add common types for virtual memory management
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 3:59 ` [PATCH 02/16] gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm Eliot Courtney
` (15 subsequent siblings)
16 siblings, 0 replies; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Add common virtual memory memory management types: `PAGE_SIZE` constant,
`VirtualAddress` bitfield type, `Vfn` (Virtual Frame Number) type, `Pfn`
(Physical Frame Number) type.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: restore Pfn and its VramAddress conversions on the raw API]
[ecourtney: make dead_code expect unconditional until the self-tests patch]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm.rs | 142 +++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 141 insertions(+), 1 deletion(-)
diff --git a/drivers/gpu/nova-core/mm.rs b/drivers/gpu/nova-core/mm.rs
index 9e4338c7c393..4234ba4d596a 100644
--- a/drivers/gpu/nova-core/mm.rs
+++ b/drivers/gpu/nova-core/mm.rs
@@ -3,7 +3,34 @@
//! Memory management subsystems.
-#![cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))]
+#![expect(dead_code)]
+
+/// Implements `From` conversions between a frame-number type and `Bounded<u64, N>`.
+///
+/// Each MMU version module should invoke this for the specific bit widths used by that version's
+/// PTE/PDE bitfield definitions.
+macro_rules! impl_frame_number_bounded {
+ ($type:ty, $bits:literal) => {
+ impl From<Bounded<u64, $bits>> for $type {
+ fn from(val: Bounded<u64, $bits>) -> Self {
+ Self::new(val.get())
+ }
+ }
+
+ impl From<$type> for Bounded<u64, $bits> {
+ fn from(v: $type) -> Self {
+ Bounded::from_expr(v.raw() & ::kernel::bits::genmask_u64(0..=($bits - 1)))
+ }
+ }
+ };
+}
+
+/// Implements `From` conversions between [`Pfn`] and `Bounded<u64, N>` for bitfield interop.
+macro_rules! impl_pfn_bounded {
+ ($bits:literal) => {
+ impl_frame_number_bounded!(Pfn, $bits);
+ };
+}
use core::{
fmt::LowerHex,
@@ -11,12 +38,15 @@
};
use kernel::{
+ bitfield,
fmt,
+ num::Bounded,
prelude::*,
ptr::{
Alignable,
Alignment, //
},
+ sizes::SZ_4K, //
};
use crate::{
@@ -58,6 +88,9 @@ fn pramin_mut(&mut self) -> &mut pramin::Pramin<'gpu> {
}
}
+/// Page size in bytes (4 KiB).
+pub(crate) const PAGE_SIZE: usize = SZ_4K;
+
/// Physical VRAM address in GPU video memory.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
@@ -124,6 +157,113 @@ fn sub(self, rhs: Self) -> Self::Output {
}
}
+impl From<Pfn> for VramAddress {
+ fn from(pfn: Pfn) -> Self {
+ Self::from_raw(pfn.raw() << 12)
+ }
+}
+
+bitfield! {
+ /// Virtual address in GPU address space.
+ pub(crate) struct VirtualAddress(u64) {
+ /// Offset within 4KB page.
+ 11:0 offset;
+ /// Virtual frame number.
+ 63:12 frame_number => Vfn;
+ }
+}
+
+impl VirtualAddress {
+ /// Create a new virtual address from a raw value.
+ pub(crate) const fn new(addr: u64) -> Self {
+ Self::from_raw(addr)
+ }
+}
+
+impl From<Vfn> for VirtualAddress {
+ fn from(vfn: Vfn) -> Self {
+ Self::zeroed().with_frame_number(vfn)
+ }
+}
+
+/// Physical Frame Number.
+///
+/// Represents a physical page in VRAM.
+#[repr(transparent)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub(crate) struct Pfn(u64);
+
+impl Pfn {
+ /// Create a new PFN from a frame number.
+ pub(crate) const fn new(frame_number: u64) -> Self {
+ Self(frame_number)
+ }
+
+ /// Get the raw frame number.
+ pub(crate) const fn raw(self) -> u64 {
+ self.0
+ }
+}
+
+impl From<VramAddress> for Pfn {
+ fn from(addr: VramAddress) -> Self {
+ Self::new(addr.into_raw() >> 12)
+ }
+}
+
+impl From<u64> for Pfn {
+ fn from(val: u64) -> Self {
+ Self(val)
+ }
+}
+
+impl From<Pfn> for u64 {
+ fn from(pfn: Pfn) -> Self {
+ pfn.0
+ }
+}
+
+impl_pfn_bounded!(52);
+
+/// Virtual Frame Number.
+///
+/// Represents a virtual page in GPU address space.
+#[repr(transparent)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub(crate) struct Vfn(u64);
+
+impl Vfn {
+ /// Create a new VFN from a frame number.
+ pub(crate) const fn new(frame_number: u64) -> Self {
+ Self(frame_number)
+ }
+
+ /// Get the raw frame number.
+ pub(crate) const fn raw(self) -> u64 {
+ self.0
+ }
+}
+
+impl From<VirtualAddress> for Vfn {
+ fn from(addr: VirtualAddress) -> Self {
+ addr.frame_number()
+ }
+}
+
+impl From<u64> for Vfn {
+ fn from(val: u64) -> Self {
+ Self(val)
+ }
+}
+
+impl From<Vfn> for u64 {
+ fn from(vfn: Vfn) -> Self {
+ vfn.0
+ }
+}
+
+impl_frame_number_bounded!(Vfn, 52);
+
#[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
pub(crate) mod selftest {
use core::ops::Range;
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 02/16] gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
2026-09-09 3:59 ` [PATCH 01/16] gpu: nova-core: mm: Add common types for virtual memory management Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:09 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 03/16] gpu: nova-core: mm: Add common types for all page table formats Eliot Courtney
` (14 subsequent siblings)
16 siblings, 1 reply; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Extend GpuMm with the remaining two memory-management components:
- Buddy allocator for VRAM allocation.
- TLB manager for translation buffer operations.
PRAMIN was added in an earlier commit; this completes the centralized
ownership model with accessor methods for each component.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: rebase GpuMm for borrowed BAR0, pin Tlb, write regs directly]
[ecourtney: size the buddy from the first usable FB region, drop dev_info]
[ecourtney: update for the VramAddress raw API and typed register base]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/Kconfig | 1 +
drivers/gpu/nova-core/gpu.rs | 27 +++++++--
drivers/gpu/nova-core/mm.rs | 24 ++++++++
drivers/gpu/nova-core/mm/tlb.rs | 120 ++++++++++++++++++++++++++++++++++++++++
drivers/gpu/nova-core/regs.rs | 68 +++++++++++++++++++++++
5 files changed, 234 insertions(+), 6 deletions(-)
diff --git a/drivers/gpu/nova-core/Kconfig b/drivers/gpu/nova-core/Kconfig
index cb7f0b00f796..1934f17baa8b 100644
--- a/drivers/gpu/nova-core/Kconfig
+++ b/drivers/gpu/nova-core/Kconfig
@@ -5,6 +5,7 @@ config NOVA_CORE
depends on RUST
depends on !CPU_BIG_ENDIAN
select AUXILIARY_BUS
+ select GPU_BUDDY
select RUST_FW_LOADER_ABSTRACTIONS
default n
help
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index a52a3d4d86af..b797472279d3 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -6,11 +6,16 @@
device,
dma::Device,
fmt,
+ gpu::buddy::GpuBuddyParams,
io::Io,
num::Bounded,
pci,
prelude::*,
- sizes::SizeConstants, //
+ ptr::Alignment,
+ sizes::{
+ SizeConstants,
+ SZ_4K, //
+ },
};
use crate::{
@@ -422,11 +427,21 @@ pub(crate) fn new<'a>(
},
// Create GPU memory manager owning memory management resources.
- mm: GpuMm::new(
- bar,
- gsp_resources.spec.chipset,
- VramAddress::from_raw(gsp_static_info.total_fb_end),
- )?,
+ mm: {
+ let usable_vram = gsp_static_info.usable_fb_regions.first().ok_or(ENODEV)?;
+ let buddy_params = GpuBuddyParams {
+ base_offset: usable_vram.start,
+ size: usable_vram.end - usable_vram.start,
+ chunk_size: Alignment::new::<SZ_4K>(),
+ };
+
+ GpuMm::new(
+ bar,
+ gsp_resources.spec.chipset,
+ buddy_params,
+ VramAddress::from_raw(gsp_static_info.total_fb_end),
+ )?
+ },
})
}
diff --git a/drivers/gpu/nova-core/mm.rs b/drivers/gpu/nova-core/mm.rs
index 4234ba4d596a..202bb8f8ebed 100644
--- a/drivers/gpu/nova-core/mm.rs
+++ b/drivers/gpu/nova-core/mm.rs
@@ -40,6 +40,10 @@ macro_rules! impl_pfn_bounded {
use kernel::{
bitfield,
fmt,
+ gpu::buddy::{
+ GpuBuddy,
+ GpuBuddyParams, //
+ },
num::Bounded,
prelude::*,
ptr::{
@@ -54,16 +58,23 @@ macro_rules! impl_pfn_bounded {
gpu::Chipset, //
};
+pub(crate) use tlb::Tlb;
+
mod hal;
mod pramin;
mod regs;
+pub(super) mod tlb;
/// GPU Memory Manager - owns all core MM components.
///
/// Provides centralized ownership of memory management resources:
+/// - [`GpuBuddy`] allocator for VRAM page table allocation.
/// - [`pramin::Pramin`] for direct VRAM access.
+/// - [`Tlb`] manager for translation buffer flush operations.
pub(crate) struct GpuMm<'gpu> {
+ buddy: GpuBuddy,
pramin: pramin::Pramin<'gpu>,
+ tlb: Pin<KBox<Tlb<'gpu>>>,
}
impl<'gpu> GpuMm<'gpu> {
@@ -71,6 +82,7 @@ impl<'gpu> GpuMm<'gpu> {
pub(crate) fn new(
bar: Bar0<'gpu>,
chipset: Chipset,
+ buddy_params: GpuBuddyParams,
total_fb_end: VramAddress,
) -> Result<Self> {
// PRAMIN covers all physical VRAM (including GSP-reserved areas
@@ -78,14 +90,26 @@ pub(crate) fn new(
let vram_region = VramAddress::ZERO..total_fb_end;
Ok(Self {
+ buddy: GpuBuddy::new(buddy_params)?,
pramin: pramin::Pramin::new(bar, chipset, vram_region)?,
+ tlb: KBox::pin_init(Tlb::new(bar), GFP_KERNEL)?,
})
}
+ /// Access the [`GpuBuddy`] allocator.
+ pub(crate) fn buddy(&self) -> &GpuBuddy {
+ &self.buddy
+ }
+
/// Access the [`pramin::Pramin`].
fn pramin_mut(&mut self) -> &mut pramin::Pramin<'gpu> {
&mut self.pramin
}
+
+ /// Access the [`Tlb`] manager.
+ pub(crate) fn tlb(&self) -> &Tlb<'gpu> {
+ self.tlb.as_ref().get_ref()
+ }
}
/// Page size in bytes (4 KiB).
diff --git a/drivers/gpu/nova-core/mm/tlb.rs b/drivers/gpu/nova-core/mm/tlb.rs
new file mode 100644
index 000000000000..cc862e8159a1
--- /dev/null
+++ b/drivers/gpu/nova-core/mm/tlb.rs
@@ -0,0 +1,120 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! TLB (Translation Lookaside Buffer) flush support for GPU MMU.
+//!
+//! After modifying page table entries, the GPU's TLB must be flushed to
+//! ensure the new mappings take effect. This module provides TLB flush
+//! functionality for virtual memory managers.
+//!
+//! # Examples
+//!
+//! ```ignore
+//! use crate::mm::tlb::Tlb;
+//!
+//! fn page_table_update(tlb: &Tlb, pdb_addr: VramAddress) -> Result<()> {
+//! // ... modify page tables ...
+//!
+//! // Flush TLB to make changes visible (polls for completion).
+//! tlb.flush(pdb_addr)?;
+//!
+//! Ok(())
+//! }
+//! ```
+
+use kernel::{
+ io::poll::read_poll_timeout,
+ io::Io,
+ new_mutex,
+ prelude::*,
+ sync::Mutex,
+ time::Delta, //
+};
+
+use crate::{
+ bounded_enum,
+ driver::Bar0,
+ mm::VramAddress,
+ regs, //
+};
+
+bounded_enum! {
+ /// TLB invalidation acknowledgment scope.
+ ///
+ /// Controls how far the hardware waits for the invalidation to propagate
+ /// before clearing the `trigger` bit of `NV_TLB_FLUSH_CTRL`.
+ #[derive(Debug, Copy, Clone, PartialEq, Eq)]
+ pub(crate) enum TlbAckMode with TryFrom<Bounded<u32, 2>> {
+ /// Fire-and-forget: no acknowledgment required.
+ None = 0,
+ /// Wait for acknowledgment from all consumers, including remote GPUs
+ /// reachable over NVLink.
+ ///
+ /// Globally is strictly required only during unmap or permission
+ /// tightening, because the backing memory may be reassigned after the
+ /// flush returns and a stale TLB entry could let the GPU access freed
+ /// memory. For new mapping or relaxing permissions, a stale entry would
+ /// merely cause a redundant fault and retry, so [`TlbAckMode::None`]
+ /// would suffice.
+ Globally = 1,
+ /// Wait for acknowledgment from consumers within the local NVLink
+ /// fabric node only; skip cross-node ack.
+ Intranode = 2,
+ }
+}
+
+/// TLB manager for GPU translation buffer operations.
+#[pin_data]
+pub(crate) struct Tlb<'gpu> {
+ bar: Bar0<'gpu>,
+ /// TLB flush serialization lock: This lock is designed to be acquired during
+ /// the DMA fence signalling critical path. It should NEVER be held across any
+ /// reclaimable CPU memory allocations because the memory reclaim path can
+ /// call `dma_fence_wait()` (when implemented), which would deadlock if lock held.
+ #[pin]
+ lock: Mutex<()>,
+}
+
+impl<'gpu> Tlb<'gpu> {
+ /// Create a new TLB manager.
+ pub(super) fn new(bar: Bar0<'gpu>) -> impl PinInit<Self> {
+ pin_init!(Self {
+ bar,
+ lock <- new_mutex!((), "tlb_flush"),
+ })
+ }
+
+ /// Flush the GPU TLB for a specific page directory base.
+ ///
+ /// This invalidates all TLB entries associated with the given PDB address.
+ /// Must be called after modifying page table entries to ensure the GPU sees
+ /// the updated mappings.
+ pub(super) fn flush(&self, pdb_addr: VramAddress) -> Result {
+ let _guard = self.lock.lock();
+
+ // Write PDB address.
+ self.bar.write_reg(regs::NV_TLB_FLUSH_PDB_LO::from_pdb_addr(
+ pdb_addr.into_raw(),
+ ));
+ self.bar.write_reg(regs::NV_TLB_FLUSH_PDB_HI::from_pdb_addr(
+ pdb_addr.into_raw(),
+ ));
+
+ // Trigger flush.
+ self.bar.write_reg(
+ regs::NV_TLB_FLUSH_CTRL::zeroed()
+ .with_all_va(true)
+ .with_ack(TlbAckMode::None)
+ .with_trigger(true),
+ );
+
+ // Poll for completion.
+ read_poll_timeout(
+ || Ok(self.bar.read(regs::NV_TLB_FLUSH_CTRL)),
+ |ctrl: ®s::NV_TLB_FLUSH_CTRL| !ctrl.trigger(),
+ Delta::ZERO,
+ Delta::from_secs(2),
+ )?;
+
+ Ok(())
+ }
+}
diff --git a/drivers/gpu/nova-core/regs.rs b/drivers/gpu/nova-core/regs.rs
index bf1f3a97c632..9978fb2803b0 100644
--- a/drivers/gpu/nova-core/regs.rs
+++ b/drivers/gpu/nova-core/regs.rs
@@ -10,6 +10,7 @@
sizes::SizeConstants,
time, //
};
+use pin_init::Zeroable;
use crate::{
driver::NovaRegisters,
@@ -26,6 +27,7 @@
PFalconRegisters,
PeregrineCoreSelect, //
},
+ mm::tlb::TlbAckMode, //
};
// PBUS
@@ -471,3 +473,69 @@ pub(crate) mod gb202 {
}
}
}
+
+// MMU TLB
+
+register! {
+ base: NovaRegisters;
+
+ /// TLB flush register: PDB address lower bits.
+ pub(crate) NV_TLB_FLUSH_PDB_LO(u32) @ 0x00b830a0 {
+ /// PDB address bits [39:8].
+ 31:0 pdb_lo => u32;
+ }
+
+ /// TLB flush register: PDB address higher bits.
+ pub(crate) NV_TLB_FLUSH_PDB_HI(u32) @ 0x00b830a4 {
+ /// PDB address bits [47:40].
+ 7:0 pdb_hi => u8;
+ }
+
+ /// TLB flush control register.
+ pub(crate) NV_TLB_FLUSH_CTRL(u32) @ 0x00b830b0 {
+ /// Invalidate every VA in the PDB selected by `NV_TLB_FLUSH_PDB_LO/HI`.
+ 0:0 all_va => bool;
+ /// Invalidate TLBs for all PDBs (ignores `NV_TLB_FLUSH_PDB_LO/HI`).
+ 1:1 all_pdb => bool;
+ /// Restrict the flush to the HUB MMU's TLBs; skip broadcasting to the
+ /// per-GPC L2 TLBs.
+ ///
+ /// The GPU MMU has a two-level TLB hierarchy:
+ /// 1. The *HUB MMU* sits at the top and serves memory requests from
+ /// "host-side" engines: the host/channel interface, copy engines,
+ /// display, and BAR1/BAR2 accesses.
+ /// 2. Each GPC (Graphics Processing Cluster — the block that houses
+ /// shader cores / SMs) has its own L2 TLB that serves requests from
+ /// the compute and graphics engines inside the cluster.
+ ///
+ /// When set, only the HUB TLBs are invalidated. This is a performance
+ /// optimization for flushes that only affect HUB-side mappings (e.g.
+ /// BAR1/BAR2 windows), where fanning the invalidation out to every
+ /// GPC's L2 TLB would be wasted work. Must be false when flushing
+ /// mappings that may be cached by compute/graphics engines.
+ 2:2 hubtlb_only => bool;
+ /// Invalidation acknowledgment scope. See [`TlbAckMode`] for details.
+ 8:7 ack ?=> TlbAckMode;
+ /// Write 1 to kick off the flush. Hardware clears this bit when the
+ /// flush completes; reads as 1 while the flush is in progress.
+ 31:31 trigger => bool;
+ }
+}
+
+impl NV_TLB_FLUSH_PDB_LO {
+ /// Create a register value from a PDB address.
+ ///
+ /// Extracts bits [39:8] of the address and shifts it right by 8 bits.
+ pub(crate) fn from_pdb_addr(addr: u64) -> Self {
+ Self::zeroed().with_pdb_lo(((addr >> 8) & 0xFFFF_FFFF) as u32)
+ }
+}
+
+impl NV_TLB_FLUSH_PDB_HI {
+ /// Create a register value from a PDB address.
+ ///
+ /// Extracts bits [47:40] of the address and shifts it right by 40 bits.
+ pub(crate) fn from_pdb_addr(addr: u64) -> Self {
+ Self::zeroed().with_pdb_hi(((addr >> 40) & 0xFF) as u8)
+ }
+}
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 03/16] gpu: nova-core: mm: Add common types for all page table formats
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
2026-09-09 3:59 ` [PATCH 01/16] gpu: nova-core: mm: Add common types for virtual memory management Eliot Courtney
2026-09-09 3:59 ` [PATCH 02/16] gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 3:59 ` [PATCH 04/16] gpu: nova-core: mm: pagetable: Add PteOps trait Eliot Courtney
` (13 subsequent siblings)
16 siblings, 0 replies; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Add common page table types shared between MMU v2 and v3. These types
are hardware-agnostic and used by both MMU versions.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm.rs | 1 +
drivers/gpu/nova-core/mm/pagetable.rs | 158 ++++++++++++++++++++++++++++++++++
2 files changed, 159 insertions(+)
diff --git a/drivers/gpu/nova-core/mm.rs b/drivers/gpu/nova-core/mm.rs
index 202bb8f8ebed..377cc9d44702 100644
--- a/drivers/gpu/nova-core/mm.rs
+++ b/drivers/gpu/nova-core/mm.rs
@@ -61,6 +61,7 @@ macro_rules! impl_pfn_bounded {
pub(crate) use tlb::Tlb;
mod hal;
+pub(super) mod pagetable;
mod pramin;
mod regs;
pub(super) mod tlb;
diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
new file mode 100644
index 000000000000..ed0f3d731c63
--- /dev/null
+++ b/drivers/gpu/nova-core/mm/pagetable.rs
@@ -0,0 +1,158 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Common page table types shared between MMU v2 and v3.
+//!
+//! This module provides foundational types used by both MMU versions:
+//! - Page table level hierarchy
+//! - Memory aperture types for PDEs and PTEs
+
+#![expect(dead_code)]
+
+use kernel::num::Bounded;
+
+use crate::gpu::Architecture;
+
+/// Extracts the page table index at a given level from a virtual address.
+pub(super) trait VaLevelIndex {
+ /// Return the page table index at `level` for this virtual address.
+ fn level_index(&self, level: u64) -> u64;
+}
+
+/// MMU version enumeration.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum MmuVersion {
+ /// MMU v2 for Turing/Ampere/Ada.
+ V2,
+ /// MMU v3 for Hopper and later.
+ V3,
+}
+
+impl From<Architecture> for MmuVersion {
+ fn from(arch: Architecture) -> Self {
+ match arch {
+ Architecture::Turing | Architecture::Ampere | Architecture::Ada => Self::V2,
+ Architecture::Hopper | Architecture::BlackwellGB10x | Architecture::BlackwellGB20x => {
+ Self::V3
+ }
+ }
+ }
+}
+
+/// Page Table Level hierarchy for MMU v2/v3.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum PageTableLevel {
+ /// Level 0 - Page Directory Base (root).
+ Pdb,
+ /// Level 1 - Intermediate page directory.
+ L1,
+ /// Level 2 - Intermediate page directory.
+ L2,
+ /// Level 3 - Intermediate page directory or dual PDE (version-dependent).
+ L3,
+ /// Level 4 - PTE level for v2, intermediate page directory for v3.
+ L4,
+ /// Level 5 - PTE level used for MMU v3 only.
+ L5,
+}
+
+impl PageTableLevel {
+ /// Number of entries per page table (512 for 4KB pages).
+ pub(super) const ENTRIES_PER_TABLE: usize = 512;
+
+ /// Get the next level in the hierarchy.
+ pub(super) const fn next(&self) -> Option<PageTableLevel> {
+ match self {
+ Self::Pdb => Some(Self::L1),
+ Self::L1 => Some(Self::L2),
+ Self::L2 => Some(Self::L3),
+ Self::L3 => Some(Self::L4),
+ Self::L4 => Some(Self::L5),
+ Self::L5 => None,
+ }
+ }
+
+ /// Convert level to index.
+ pub(super) const fn as_index(&self) -> u64 {
+ match self {
+ Self::Pdb => 0,
+ Self::L1 => 1,
+ Self::L2 => 2,
+ Self::L3 => 3,
+ Self::L4 => 4,
+ Self::L5 => 5,
+ }
+ }
+}
+
+/// Memory aperture for Page Table Entries (`PTE`s).
+///
+/// Determines which memory region the `PTE` points to.
+#[repr(u8)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub(super) enum AperturePte {
+ /// Local video memory (VRAM).
+ #[default]
+ VideoMemory = 0,
+ /// Peer GPU's video memory.
+ PeerMemory = 1,
+ /// System memory with cache coherence.
+ SystemCoherent = 2,
+ /// System memory without cache coherence.
+ SystemNonCoherent = 3,
+}
+
+// TODO[FPRI]: Replace with `#[derive(FromPrimitive)]` when available.
+impl From<Bounded<u64, 2>> for AperturePte {
+ fn from(val: Bounded<u64, 2>) -> Self {
+ match *val {
+ 0 => Self::VideoMemory,
+ 1 => Self::PeerMemory,
+ 2 => Self::SystemCoherent,
+ 3 => Self::SystemNonCoherent,
+ _ => Self::VideoMemory,
+ }
+ }
+}
+
+// TODO[FPRI]: Replace with `#[derive(ToPrimitive)]` when available.
+impl From<AperturePte> for Bounded<u64, 2> {
+ fn from(val: AperturePte) -> Self {
+ Bounded::from_expr(val as u64 & 0x3)
+ }
+}
+
+/// Memory aperture for Page Directory Entries (`PDE`s).
+///
+/// Note: For `PDE`s, `Invalid` (0) means the entry is not valid.
+#[repr(u8)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub(super) enum AperturePde {
+ /// Invalid/unused entry.
+ #[default]
+ Invalid = 0,
+ /// Page table is in video memory.
+ VideoMemory = 1,
+ /// Page table is in system memory with coherence.
+ SystemCoherent = 2,
+ /// Page table is in system memory without coherence.
+ SystemNonCoherent = 3,
+}
+
+// TODO[FPRI]: Replace with `#[derive(FromPrimitive)]` when available.
+impl From<Bounded<u64, 2>> for AperturePde {
+ fn from(val: Bounded<u64, 2>) -> Self {
+ match *val {
+ 1 => Self::VideoMemory,
+ 2 => Self::SystemCoherent,
+ 3 => Self::SystemNonCoherent,
+ _ => Self::Invalid,
+ }
+ }
+}
+
+// TODO[FPRI]: Replace with `#[derive(ToPrimitive)]` when available.
+impl From<AperturePde> for Bounded<u64, 2> {
+ fn from(val: AperturePde) -> Self {
+ Bounded::from_expr(val as u64 & 0x3)
+ }
+}
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 04/16] gpu: nova-core: mm: pagetable: Add PteOps trait
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (2 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 03/16] gpu: nova-core: mm: Add common types for all page table formats Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:07 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 05/16] gpu: nova-core: mm: pagetable: Add PdeOps trait Eliot Courtney
` (12 subsequent siblings)
16 siblings, 1 reply; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Introduce a trait for GPU Page Table Entries (PTEs). New
`read()`/`write()` helpers are provided that go through a
`Pramin`).
The forthcoming MMU v2, v3 PTE structs will each implement `PteOps`,
allowing the later page-table walker and mapper to call PTE operations.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: replace PraminWindow accesses with typed MMIO views]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm/pagetable.rs | 46 ++++++++++++++++++++++++++++++++++-
1 file changed, 45 insertions(+), 1 deletion(-)
diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
index ed0f3d731c63..a23370b4b62d 100644
--- a/drivers/gpu/nova-core/mm/pagetable.rs
+++ b/drivers/gpu/nova-core/mm/pagetable.rs
@@ -8,9 +8,18 @@
#![expect(dead_code)]
-use kernel::num::Bounded;
+use kernel::{
+ io::Io,
+ num::Bounded,
+ prelude::*, //
+};
use crate::gpu::Architecture;
+use crate::mm::{
+ pramin,
+ Pfn,
+ VramAddress, //
+};
/// Extracts the page table index at a given level from a virtual address.
pub(super) trait VaLevelIndex {
@@ -84,6 +93,41 @@ pub(super) const fn as_index(&self) -> u64 {
}
}
+// Trait abstractions for page table operations.
+
+/// Operations on Page Table Entries (`PTE`s).
+pub(super) trait PteOps: Copy + core::fmt::Debug + Into<u64> {
+ /// Create a `PTE` from a raw `u64` value.
+ fn from_raw(val: u64) -> Self;
+
+ /// Create an invalid `PTE`.
+ fn invalid() -> Self;
+
+ /// Create a valid `PTE` for the given memory aperture.
+ fn new(aperture: AperturePte, pfn: Pfn, writable: bool) -> Self;
+
+ /// Check if this `PTE` is valid.
+ fn is_valid(&self) -> bool;
+
+ /// Get the physical frame number.
+ fn frame_number(&self) -> Pfn;
+
+ /// Read a `PTE` from VRAM.
+ fn read(pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result<Self> {
+ let val = pramin.window_at::<u64>(addr)?.view().read_val();
+ Ok(Self::from_raw(val))
+ }
+
+ /// Write this `PTE` to VRAM.
+ fn write(&self, pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result {
+ pramin
+ .window_at::<u64>(addr)?
+ .view()
+ .write_val((*self).into());
+ Ok(())
+ }
+}
+
/// Memory aperture for Page Table Entries (`PTE`s).
///
/// Determines which memory region the `PTE` points to.
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 05/16] gpu: nova-core: mm: pagetable: Add PdeOps trait
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (3 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 04/16] gpu: nova-core: mm: pagetable: Add PteOps trait Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:08 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 06/16] gpu: nova-core: mm: pagetable: Add DualPdeOps trait Eliot Courtney
` (11 subsequent siblings)
16 siblings, 1 reply; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Introduce a trait for GPU Page Directory Entries
(PDEs). Default `read()`/`write()` helpers via a `Pramin` are
provided.
The forthcoming MMU v2, v3 PDE structs will each implement `PdeOps`,
allowing the later page-table walker and mapper to call PDE operations.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: replace PraminWindow accesses with typed MMIO views]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm/pagetable.rs | 41 +++++++++++++++++++++++++++++++++++
1 file changed, 41 insertions(+)
diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
index a23370b4b62d..14436fa6adf0 100644
--- a/drivers/gpu/nova-core/mm/pagetable.rs
+++ b/drivers/gpu/nova-core/mm/pagetable.rs
@@ -128,6 +128,47 @@ fn write(&self, pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result {
}
}
+/// Operations on Page Directory Entries (`PDE`s).
+pub(super) trait PdeOps: Copy + core::fmt::Debug + Into<u64> {
+ /// Create a `PDE` from a raw `u64` value.
+ fn from_raw(val: u64) -> Self;
+
+ /// Create a valid `PDE` pointing to a page table in the given aperture.
+ fn new(aperture: AperturePde, table_pfn: Pfn) -> Self;
+
+ /// Create an invalid `PDE`.
+ fn invalid() -> Self;
+
+ /// Check if this `PDE` is valid.
+ fn is_valid(&self) -> bool;
+
+ /// Get the memory aperture of this `PDE`.
+ fn aperture(&self) -> AperturePde;
+
+ /// Get the VRAM address of the page table.
+ fn table_vram_address(&self) -> VramAddress;
+
+ /// Read a `PDE` from VRAM.
+ fn read(pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result<Self> {
+ let val = pramin.window_at::<u64>(addr)?.view().read_val();
+ Ok(Self::from_raw(val))
+ }
+
+ /// Write this `PDE` to VRAM.
+ fn write(&self, pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result {
+ pramin
+ .window_at::<u64>(addr)?
+ .view()
+ .write_val((*self).into());
+ Ok(())
+ }
+
+ /// Check if this `PDE` is valid and points to video memory.
+ fn is_valid_vram(&self) -> bool {
+ self.is_valid() && self.aperture() == AperturePde::VideoMemory
+ }
+}
+
/// Memory aperture for Page Table Entries (`PTE`s).
///
/// Determines which memory region the `PTE` points to.
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 06/16] gpu: nova-core: mm: pagetable: Add DualPdeOps trait
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (4 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 05/16] gpu: nova-core: mm: pagetable: Add PdeOps trait Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 3:59 ` [PATCH 07/16] gpu: nova-core: mm: Add MMU v2 page table types Eliot Courtney
` (10 subsequent siblings)
16 siblings, 0 replies; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Introduce a trait for 128-bit Dual Page Directory Entries. The
`read()`/`write()` helpers issue two 64-bit accesses through a
`Pramin` to load/store the 128-bit value.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: replace PraminWindow accesses with typed MMIO views]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm/pagetable.rs | 41 +++++++++++++++++++++++++++++++++++
1 file changed, 41 insertions(+)
diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
index 14436fa6adf0..550145d56e3d 100644
--- a/drivers/gpu/nova-core/mm/pagetable.rs
+++ b/drivers/gpu/nova-core/mm/pagetable.rs
@@ -169,6 +169,47 @@ fn is_valid_vram(&self) -> bool {
}
}
+/// Operations on Dual Page Directory Entries (128-bit `DualPde`s).
+pub(super) trait DualPdeOps: Copy + core::fmt::Debug {
+ /// Create a `DualPde` from raw 128-bit value (two `u64`s).
+ fn from_raw(big: u64, small: u64) -> Self;
+
+ /// Create a `DualPde` with only the small page table pointer set.
+ fn new_small(table_pfn: Pfn) -> Self;
+
+ /// Check if the small page table pointer is valid.
+ fn has_small(&self) -> bool;
+
+ /// Get the small page table VRAM address.
+ fn small_vram_address(&self) -> VramAddress;
+
+ /// Get the raw `u64` value of the big PDE.
+ fn big_raw_u64(&self) -> u64;
+
+ /// Get the raw `u64` value of the small PDE.
+ fn small_raw_u64(&self) -> u64;
+
+ /// Read a dual PDE (128-bit) from VRAM.
+ fn read(pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result<Self> {
+ let lo = pramin.window_at::<u64>(addr)?.view().read_val();
+ let hi = pramin.window_at::<u64>(addr + 8)?.view().read_val();
+ Ok(Self::from_raw(lo, hi))
+ }
+
+ /// Write this dual PDE (128-bit) to VRAM.
+ fn write(&self, pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result {
+ pramin
+ .window_at::<u64>(addr)?
+ .view()
+ .write_val(self.big_raw_u64());
+ pramin
+ .window_at::<u64>(addr + 8)?
+ .view()
+ .write_val(self.small_raw_u64());
+ Ok(())
+ }
+}
+
/// Memory aperture for Page Table Entries (`PTE`s).
///
/// Determines which memory region the `PTE` points to.
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 07/16] gpu: nova-core: mm: Add MMU v2 page table types
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (5 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 06/16] gpu: nova-core: mm: pagetable: Add DualPdeOps trait Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:12 ` sashiko-bot
2026-09-09 18:43 ` Danilo Krummrich
2026-09-09 3:59 ` [PATCH 08/16] gpu: nova-core: mm: Add MMU v3 " Eliot Courtney
` (9 subsequent siblings)
16 siblings, 2 replies; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Add page table entry and directory structures for MMU version 2 used by
Hopper and later GPUs. The `Pte`, `Pde`, and `DualPde` types each
implement the `PteOps`, `PdeOps`, and `DualPdeOps` traits introduced
earlier in the series, providing the version-agnostic API used by the
forthcoming page-table walker and mapper.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm/pagetable.rs | 2 +
drivers/gpu/nova-core/mm/pagetable/ver2.rs | 271 +++++++++++++++++++++++++++++
2 files changed, 273 insertions(+)
diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
index 550145d56e3d..df8e7e7d7327 100644
--- a/drivers/gpu/nova-core/mm/pagetable.rs
+++ b/drivers/gpu/nova-core/mm/pagetable.rs
@@ -8,6 +8,8 @@
#![expect(dead_code)]
+pub(super) mod ver2;
+
use kernel::{
io::Io,
num::Bounded,
diff --git a/drivers/gpu/nova-core/mm/pagetable/ver2.rs b/drivers/gpu/nova-core/mm/pagetable/ver2.rs
new file mode 100644
index 000000000000..089e5cc2bfc3
--- /dev/null
+++ b/drivers/gpu/nova-core/mm/pagetable/ver2.rs
@@ -0,0 +1,271 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! MMU v2 page table types for Turing, Ampere and Ada GPUs.
+//!
+//! This module defines MMU version 2 specific types (Turing, Ampere and Ada GPUs).
+//!
+//! Bit field layouts derived from the NVIDIA OpenRM documentation:
+//! `open-gpu-kernel-modules/src/common/inc/swref/published/turing/tu102/dev_mmu.h`
+
+#![allow(dead_code)]
+
+use kernel::bitfield;
+use kernel::num::Bounded;
+use pin_init::Zeroable;
+
+use super::{
+ AperturePde,
+ AperturePte,
+ DualPdeOps,
+ PageTableLevel,
+ PdeOps,
+ PteOps,
+ VaLevelIndex, //
+};
+use crate::mm::{
+ Pfn,
+ VirtualAddress,
+ VramAddress, //
+};
+
+// Bounded to version 2 Pfn bitfield conversions:
+// 25 bits for video memory frame numbers (bits 32:8).
+impl_pfn_bounded!(25);
+// 46 bits for system memory frame numbers (bits 53:8).
+impl_pfn_bounded!(46);
+
+bitfield! {
+ /// MMU v2 49-bit virtual address layout.
+ pub(super) struct VirtualAddressV2(u64) {
+ /// Page offset [11:0].
+ 11:0 offset;
+ /// PT index [20:12].
+ 20:12 pt_idx;
+ /// PDE0 index [28:21].
+ 28:21 pde0_idx;
+ /// PDE1 index [37:29].
+ 37:29 pde1_idx;
+ /// PDE2 index [46:38].
+ 46:38 pde2_idx;
+ /// PDE3 index [48:47].
+ 48:47 pde3_idx;
+ }
+}
+
+impl VirtualAddressV2 {
+ /// Create a [`VirtualAddressV2`] from a [`VirtualAddress`].
+ pub(super) fn new(va: VirtualAddress) -> Self {
+ Self::from_raw(va.into_raw())
+ }
+}
+
+impl VaLevelIndex for VirtualAddressV2 {
+ fn level_index(&self, level: u64) -> u64 {
+ match level {
+ 0 => *self.pde3_idx(),
+ 1 => *self.pde2_idx(),
+ 2 => *self.pde1_idx(),
+ 3 => *self.pde0_idx(),
+ 4 => *self.pt_idx(),
+ _ => 0,
+ }
+ }
+}
+
+/// `PDE` levels for MMU v2 (5-level hierarchy: `PDB` -> `L1` -> `L2` -> `L3` -> `L4`).
+pub(super) const PDE_LEVELS: &[PageTableLevel] = &[
+ PageTableLevel::Pdb,
+ PageTableLevel::L1,
+ PageTableLevel::L2,
+ PageTableLevel::L3,
+];
+
+/// `PTE` level for MMU v2.
+pub(super) const PTE_LEVEL: PageTableLevel = PageTableLevel::L4;
+
+/// Dual `PDE` level for MMU v2 (128-bit entries).
+pub(super) const DUAL_PDE_LEVEL: PageTableLevel = PageTableLevel::L3;
+
+// Page Table Entry (PTE) for MMU v2 - 64-bit entry at level 4.
+bitfield! {
+ /// Page Table Entry for MMU v2.
+ pub(in crate::mm) struct Pte(u64) {
+ /// Entry is valid.
+ 0:0 valid;
+ /// Memory aperture type.
+ 2:1 aperture => AperturePte;
+ /// Volatile (bypass L2 cache).
+ 3:3 volatile;
+ /// Encryption enabled (Confidential Computing).
+ 4:4 encrypted;
+ /// Privileged access only.
+ 5:5 privilege;
+ /// Write protection.
+ 6:6 read_only;
+ /// Atomic operations disabled.
+ 7:7 atomic_disable;
+ /// Frame number for system memory.
+ 53:8 frame_number_sys => Pfn;
+ /// Frame number for video memory.
+ 32:8 frame_number_vid => Pfn;
+ /// Peer GPU ID for peer memory (0-7).
+ 35:33 peer_id;
+ /// Compression tag line bits.
+ 53:36 comptagline;
+ /// Surface kind/format.
+ 63:56 kind;
+ }
+}
+
+impl PteOps for Pte {
+ fn from_raw(val: u64) -> Self {
+ Self::from_raw(val)
+ }
+
+ fn invalid() -> Self {
+ Self::zeroed()
+ }
+
+ fn new(aperture: AperturePte, pfn: Pfn, writable: bool) -> Self {
+ let base = Self::zeroed()
+ .with_valid(true)
+ .with_aperture(aperture)
+ .with_read_only(!writable);
+ match aperture {
+ AperturePte::VideoMemory => base.with_frame_number_vid(pfn),
+ // Sysmem PTEs use VOL=1 to bypass L2 for cache coherency.
+ AperturePte::SystemCoherent => base.with_frame_number_sys(pfn).with_volatile(true),
+ AperturePte::PeerMemory | AperturePte::SystemNonCoherent => {
+ kernel::pr_warn!("MMU v2 PTE aperture {:?} not supported\n", aperture);
+ Self::invalid()
+ }
+ }
+ }
+
+ fn is_valid(&self) -> bool {
+ self.valid().into_bool()
+ }
+
+ fn frame_number(&self) -> Pfn {
+ match self.aperture() {
+ AperturePte::VideoMemory => self.frame_number_vid(),
+ _ => self.frame_number_sys(),
+ }
+ }
+}
+
+// Page Directory Entry (PDE) for MMU v2 - 64-bit entry at levels 0-2.
+bitfield! {
+ /// Page Directory Entry for MMU v2.
+ pub(in crate::mm) struct Pde(u64) {
+ /// Valid bit (inverted logic).
+ 0:0 valid_inverted;
+ /// Memory aperture type.
+ 2:1 aperture => AperturePde;
+ /// Volatile (bypass L2 cache).
+ 3:3 volatile;
+ /// Disable Address Translation Services.
+ 5:5 no_ats;
+ /// Table frame number for system memory.
+ 53:8 table_frame_sys => Pfn;
+ /// Table frame number for video memory.
+ 32:8 table_frame_vid => Pfn;
+ /// Peer GPU ID (0-7).
+ 35:33 peer_id;
+ }
+}
+
+impl PdeOps for Pde {
+ fn from_raw(val: u64) -> Self {
+ Self::from_raw(val)
+ }
+
+ fn new(aperture: AperturePde, table_pfn: Pfn) -> Self {
+ let base = Self::zeroed()
+ .with_valid_inverted(false) // 0 = valid
+ .with_aperture(aperture);
+ match aperture {
+ AperturePde::VideoMemory => base.with_table_frame_vid(table_pfn),
+ // Sysmem PTEs use VOL=1 to bypass L2 for cache coherency.
+ AperturePde::SystemCoherent => base.with_table_frame_sys(table_pfn).with_volatile(true),
+ AperturePde::Invalid | AperturePde::SystemNonCoherent => {
+ kernel::pr_warn!("MMU v2 PDE aperture {:?} not supported\n", aperture);
+ Self::invalid()
+ }
+ }
+ }
+
+ fn invalid() -> Self {
+ Self::zeroed()
+ .with_valid_inverted(true)
+ .with_aperture(AperturePde::Invalid)
+ }
+
+ fn is_valid(&self) -> bool {
+ !self.valid_inverted().into_bool() && self.aperture() != AperturePde::Invalid
+ }
+
+ fn aperture(&self) -> AperturePde {
+ Pde::aperture(*self)
+ }
+
+ fn table_vram_address(&self) -> VramAddress {
+ debug_assert!(
+ Pde::aperture(*self) == AperturePde::VideoMemory,
+ "table_vram_address called on non-VRAM PDE (aperture: {:?})",
+ Pde::aperture(*self)
+ );
+ VramAddress::from(self.table_frame_vid())
+ }
+}
+
+/// Dual `PDE` at Level 3 - 128-bit entry of Large/Small Page Table pointers.
+///
+/// The dual `PDE` supports both large (64KB) and small (4KB) page tables.
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub(in crate::mm) struct DualPde {
+ /// Large/Big Page Table pointer (lower 64 bits).
+ pub(super) big: Pde,
+ /// Small Page Table pointer (upper 64 bits).
+ pub(super) small: Pde,
+}
+
+impl DualPde {
+ /// Check if the big page table pointer is valid.
+ fn has_big(&self) -> bool {
+ PdeOps::is_valid(&self.big)
+ }
+}
+
+impl DualPdeOps for DualPde {
+ fn from_raw(big: u64, small: u64) -> Self {
+ Self {
+ big: PdeOps::from_raw(big),
+ small: PdeOps::from_raw(small),
+ }
+ }
+
+ fn new_small(table_pfn: Pfn) -> Self {
+ Self {
+ big: PdeOps::from_raw(0),
+ small: PdeOps::new(AperturePde::VideoMemory, table_pfn),
+ }
+ }
+
+ fn has_small(&self) -> bool {
+ PdeOps::is_valid(&self.small)
+ }
+
+ fn small_vram_address(&self) -> VramAddress {
+ PdeOps::table_vram_address(&self.small)
+ }
+
+ fn big_raw_u64(&self) -> u64 {
+ self.big.into_raw()
+ }
+
+ fn small_raw_u64(&self) -> u64 {
+ self.small.into_raw()
+ }
+}
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 08/16] gpu: nova-core: mm: Add MMU v3 page table types
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (6 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 07/16] gpu: nova-core: mm: Add MMU v2 page table types Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 3:59 ` [PATCH 09/16] gpu: nova-core: mm: pagetable: Add MmuConfig trait Eliot Courtney
` (8 subsequent siblings)
16 siblings, 0 replies; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Add page table entry and directory structures for MMU version 3 used by
Hopper and later GPUs. The `Pte`, `Pde`, and `DualPde` types each
implement the `PteOps`, `PdeOps`, and `DualPdeOps` traits introduced
earlier in the series, providing the version-agnostic API used by the
forthcoming page-table walker and mapper.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: update for the VramAddress raw API, apply rustfmt]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm/pagetable.rs | 1 +
drivers/gpu/nova-core/mm/pagetable/ver3.rs | 417 +++++++++++++++++++++++++++++
2 files changed, 418 insertions(+)
diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
index df8e7e7d7327..128bfc0d277a 100644
--- a/drivers/gpu/nova-core/mm/pagetable.rs
+++ b/drivers/gpu/nova-core/mm/pagetable.rs
@@ -9,6 +9,7 @@
#![expect(dead_code)]
pub(super) mod ver2;
+pub(super) mod ver3;
use kernel::{
io::Io,
diff --git a/drivers/gpu/nova-core/mm/pagetable/ver3.rs b/drivers/gpu/nova-core/mm/pagetable/ver3.rs
new file mode 100644
index 000000000000..80c06463de88
--- /dev/null
+++ b/drivers/gpu/nova-core/mm/pagetable/ver3.rs
@@ -0,0 +1,417 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! MMU v3 page table types for Hopper and later GPUs.
+//!
+//! This module defines MMU version 3 specific types (Hopper and later GPUs).
+//!
+//! Key differences from MMU v2:
+//! - Unified 40-bit address field for all apertures (v2 had separate sys/vid fields).
+//! - PCF (Page Classification Field) replaces separate privilege/RO/atomic/cache bits.
+//! - KIND field is 4 bits (not 8).
+//! - IS_PTE bit in PDE to support large pages directly.
+//! - No COMPTAGLINE field (compression handled differently in v3).
+//! - No separate ENCRYPTED bit.
+//!
+//! Bit field layouts derived from the NVIDIA OpenRM documentation:
+//! `open-gpu-kernel-modules/src/common/inc/swref/published/hopper/gh100/dev_mmu.h`
+
+#![allow(dead_code)]
+
+use kernel::bitfield;
+use kernel::num::Bounded;
+use kernel::prelude::*;
+use pin_init::Zeroable;
+
+use super::{
+ AperturePde,
+ AperturePte,
+ DualPdeOps,
+ PageTableLevel,
+ PdeOps,
+ PteOps,
+ VaLevelIndex, //
+};
+use crate::mm::{
+ Pfn,
+ VirtualAddress,
+ VramAddress, //
+};
+
+// Bounded to version 3 Pfn conversion.
+impl_pfn_bounded!(40);
+
+bitfield! {
+ /// MMU v3 57-bit virtual address layout.
+ pub(super) struct VirtualAddressV3(u64) {
+ /// Page offset [11:0].
+ 11:0 offset;
+ /// PT index [20:12].
+ 20:12 pt_idx;
+ /// PDE0 index [28:21].
+ 28:21 pde0_idx;
+ /// PDE1 index [37:29].
+ 37:29 pde1_idx;
+ /// PDE2 index [46:38].
+ 46:38 pde2_idx;
+ /// PDE3 index [55:47].
+ 55:47 pde3_idx;
+ /// PDE4 index [56].
+ 56:56 pde4_idx;
+ }
+}
+
+impl VirtualAddressV3 {
+ /// Create a [`VirtualAddressV3`] from a [`VirtualAddress`].
+ pub(super) fn new(va: VirtualAddress) -> Self {
+ Self::from_raw(va.into_raw())
+ }
+}
+
+impl VaLevelIndex for VirtualAddressV3 {
+ fn level_index(&self, level: u64) -> u64 {
+ match level {
+ 0 => *self.pde4_idx(),
+ 1 => *self.pde3_idx(),
+ 2 => *self.pde2_idx(),
+ 3 => *self.pde1_idx(),
+ 4 => *self.pde0_idx(),
+ 5 => *self.pt_idx(),
+ _ => 0,
+ }
+ }
+}
+
+/// PDE levels for MMU v3 (6-level hierarchy).
+pub(super) const PDE_LEVELS: &[PageTableLevel] = &[
+ PageTableLevel::Pdb,
+ PageTableLevel::L1,
+ PageTableLevel::L2,
+ PageTableLevel::L3,
+ PageTableLevel::L4,
+];
+
+/// PTE level for MMU v3.
+pub(super) const PTE_LEVEL: PageTableLevel = PageTableLevel::L5;
+
+/// Dual PDE level for MMU v3 (128-bit entries).
+pub(super) const DUAL_PDE_LEVEL: PageTableLevel = PageTableLevel::L4;
+
+bitfield! {
+ /// Page Classification Field for PTEs (5 bits) in MMU v3.
+ pub(in crate::mm) struct PtePcf(u8) {
+ /// Bypass L2 cache (0=cached, 1=bypass).
+ 0:0 uncached;
+ /// Access counting disabled (0=enabled, 1=disabled).
+ 1:1 acd;
+ /// Read-only access (0=read-write, 1=read-only).
+ 2:2 read_only;
+ /// Atomics disabled (0=enabled, 1=disabled).
+ 3:3 no_atomic;
+ /// Privileged access only (0=regular, 1=privileged).
+ 4:4 privileged;
+ }
+}
+
+impl PtePcf {
+ /// Create PCF for read-write mapping (cached, no atomics, regular mode).
+ fn rw() -> Self {
+ Self::zeroed().with_no_atomic(true)
+ }
+
+ /// Create PCF for read-only mapping (cached, no atomics, regular mode).
+ fn ro() -> Self {
+ Self::zeroed().with_read_only(true).with_no_atomic(true)
+ }
+
+ /// Get the raw `u8` value.
+ fn raw_u8(&self) -> u8 {
+ self.into_raw()
+ }
+}
+
+impl From<Bounded<u64, 5>> for PtePcf {
+ fn from(val: Bounded<u64, 5>) -> Self {
+ Self::from_raw(u8::from(val))
+ }
+}
+
+impl From<PtePcf> for Bounded<u64, 5> {
+ fn from(pcf: PtePcf) -> Self {
+ Bounded::from_expr(u64::from(pcf.into_raw()) & 0x1F)
+ }
+}
+
+bitfield! {
+ /// Page Classification Field for PDEs (3 bits) in MMU v3.
+ ///
+ /// Controls Address Translation Services (ATS) and caching.
+ pub(in crate::mm) struct PdePcf(u8) {
+ /// Bypass L2 cache (0=cached, 1=bypass).
+ 0:0 uncached;
+ /// ATS disabled (0=enabled, 1=disabled).
+ 1:1 no_ats;
+ }
+}
+
+impl PdePcf {
+ /// Create PCF for cached mapping with ATS enabled (default).
+ fn cached() -> Self {
+ Self::zeroed()
+ }
+
+ /// Get the raw `u8` value.
+ fn raw_u8(&self) -> u8 {
+ self.into_raw()
+ }
+}
+
+impl From<Bounded<u64, 3>> for PdePcf {
+ fn from(val: Bounded<u64, 3>) -> Self {
+ Self::from_raw(u8::from(val))
+ }
+}
+
+impl From<PdePcf> for Bounded<u64, 3> {
+ fn from(pcf: PdePcf) -> Self {
+ Bounded::from_expr(u64::from(pcf.into_raw()) & 0x7)
+ }
+}
+
+bitfield! {
+ /// Page Table Entry for MMU v3.
+ pub(in crate::mm) struct Pte(u64) {
+ /// Entry is valid.
+ 0:0 valid;
+ /// Memory aperture type.
+ 2:1 aperture => AperturePte;
+ /// Page Classification Field.
+ 7:3 pcf => PtePcf;
+ /// Surface kind (4 bits, 0x0=pitch, 0xF=invalid).
+ 11:8 kind;
+ /// Physical frame number (for all apertures).
+ 51:12 frame_number => Pfn;
+ /// Peer GPU ID for peer memory (0-7).
+ 63:61 peer_id;
+ }
+}
+
+impl PteOps for Pte {
+ fn from_raw(val: u64) -> Self {
+ Self::from_raw(val)
+ }
+
+ fn invalid() -> Self {
+ Self::zeroed()
+ }
+
+ fn new(aperture: AperturePte, pfn: Pfn, writable: bool) -> Self {
+ let pcf = match (aperture, writable) {
+ (AperturePte::VideoMemory, true) => PtePcf::rw(),
+ (AperturePte::VideoMemory, false) => PtePcf::ro(),
+ // Sysmem PTEs use uncached+no_atomic PCF for cache coherency.
+ (AperturePte::SystemCoherent, true) => {
+ PtePcf::zeroed().with_uncached(true).with_no_atomic(true)
+ }
+ (AperturePte::SystemCoherent, false) => PtePcf::zeroed()
+ .with_uncached(true)
+ .with_no_atomic(true)
+ .with_read_only(true),
+ (AperturePte::PeerMemory | AperturePte::SystemNonCoherent, _) => {
+ kernel::pr_warn!("MMU v3 PTE aperture {:?} not supported\n", aperture);
+ return Self::invalid();
+ }
+ };
+ Self::zeroed()
+ .with_valid(true)
+ .with_aperture(aperture)
+ .with_pcf(pcf)
+ .with_frame_number(pfn)
+ }
+
+ fn is_valid(&self) -> bool {
+ self.valid().into_bool()
+ }
+
+ fn frame_number(&self) -> Pfn {
+ Pte::frame_number(*self)
+ }
+}
+
+bitfield! {
+ /// Page Directory Entry for MMU v3 (Hopper+).
+ ///
+ /// ## Note
+ ///
+ /// v3 uses a unified 40-bit address field (v2 had separate sys/vid address fields).
+ pub(in crate::mm) struct Pde(u64) {
+ /// Entry is a PTE (0=PDE, 1=large page PTE).
+ 0:0 is_pte;
+ /// Memory aperture type.
+ 2:1 aperture => AperturePde;
+ /// Page Classification Field (3 bits for PDE).
+ 5:3 pcf => PdePcf;
+ /// Table frame number (40-bit unified address).
+ 51:12 table_frame => Pfn;
+ }
+}
+
+impl PdeOps for Pde {
+ fn from_raw(val: u64) -> Self {
+ Self::from_raw(val)
+ }
+
+ fn new(aperture: AperturePde, table_pfn: Pfn) -> Self {
+ match aperture {
+ AperturePde::VideoMemory => Self::zeroed()
+ .with_is_pte(false)
+ .with_aperture(aperture)
+ .with_table_frame(table_pfn),
+ AperturePde::Invalid | AperturePde::SystemCoherent | AperturePde::SystemNonCoherent => {
+ kernel::pr_warn!("MMU v3 PDE aperture {:?} not supported\n", aperture);
+ Self::invalid()
+ }
+ }
+ }
+
+ fn invalid() -> Self {
+ Self::zeroed().with_aperture(AperturePde::Invalid)
+ }
+
+ fn is_valid(&self) -> bool {
+ Pde::aperture(*self) != AperturePde::Invalid
+ }
+
+ fn aperture(&self) -> AperturePde {
+ Pde::aperture(*self)
+ }
+
+ fn table_vram_address(&self) -> VramAddress {
+ debug_assert!(
+ Pde::aperture(*self) == AperturePde::VideoMemory,
+ "table_vram_address called on non-VRAM PDE (aperture: {:?})",
+ Pde::aperture(*self)
+ );
+ VramAddress::from(self.table_frame())
+ }
+}
+
+bitfield! {
+ /// Big Page Table pointer in Dual PDE (MMU v3).
+ ///
+ /// 64-bit lower word of the 128-bit Dual PDE.
+ pub(super) struct DualPdeBig(u64) {
+ /// Entry is a PTE (for large pages).
+ 0:0 is_pte;
+ /// Memory aperture type.
+ 2:1 aperture => AperturePde;
+ /// Page Classification Field.
+ 5:3 pcf => PdePcf;
+ /// Table frame (table address 256-byte aligned).
+ 51:8 table_frame;
+ }
+}
+
+impl DualPdeBig {
+ /// Create an invalid big page table pointer.
+ fn invalid() -> Self {
+ Self::zeroed().with_aperture(AperturePde::Invalid)
+ }
+
+ /// Create a valid big PDE pointing to a page table in the given aperture.
+ fn new(aperture: AperturePde, table_addr: VramAddress) -> Result<Self> {
+ // Big page table addresses must be 256-byte aligned (shift 8).
+ if table_addr.into_raw() & 0xFF != 0 {
+ return Err(EINVAL);
+ }
+ let table_frame = Bounded::from_expr(table_addr.into_raw() >> 8);
+ match aperture {
+ AperturePde::VideoMemory => Ok(Self::zeroed()
+ .with_is_pte(false)
+ .with_aperture(aperture)
+ .with_table_frame(table_frame)),
+ AperturePde::Invalid | AperturePde::SystemCoherent | AperturePde::SystemNonCoherent => {
+ kernel::pr_warn!("MMU v3 DualPdeBig aperture {:?} not supported\n", aperture);
+ Ok(Self::invalid())
+ }
+ }
+ }
+
+ /// Check if this big PDE is valid.
+ fn is_valid(&self) -> bool {
+ self.aperture() != AperturePde::Invalid
+ }
+
+ /// Get the VRAM address of the big page table.
+ fn table_vram_address(&self) -> VramAddress {
+ debug_assert!(
+ self.aperture() == AperturePde::VideoMemory,
+ "table_vram_address called on non-VRAM DualPdeBig (aperture: {:?})",
+ self.aperture()
+ );
+ VramAddress::from_raw(*self.table_frame() << 8)
+ }
+}
+
+/// Dual PDE at Level 4 for MMU v3 - 128-bit entry.
+///
+/// Contains both big (64KB) and small (4KB) page table pointers:
+/// - Lower 64 bits: Big Page Table pointer.
+/// - Upper 64 bits: Small Page Table pointer.
+///
+/// ## Note
+///
+/// The big and small page table pointers have different address layouts:
+/// - Big address = field value << 8 (256-byte alignment).
+/// - Small address = field value << 12 (4KB alignment).
+///
+/// This is why `DualPdeBig` is a separate type from `Pde`.
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub(in crate::mm) struct DualPde {
+ /// Big Page Table pointer.
+ pub(super) big: DualPdeBig,
+ /// Small Page Table pointer.
+ pub(super) small: Pde,
+}
+
+// SAFETY: Both `DualPdeBig` and `Pde` fields are `Zeroable` (bitfield types are Zeroable).
+unsafe impl Zeroable for DualPde {}
+
+impl DualPde {
+ /// Check if the big page table pointer is valid.
+ fn has_big(&self) -> bool {
+ self.big.is_valid()
+ }
+}
+
+impl DualPdeOps for DualPde {
+ fn from_raw(big: u64, small: u64) -> Self {
+ Self {
+ big: DualPdeBig::from_raw(big),
+ small: PdeOps::from_raw(small),
+ }
+ }
+
+ fn new_small(table_pfn: Pfn) -> Self {
+ Self {
+ big: DualPdeBig::invalid(),
+ small: PdeOps::new(AperturePde::VideoMemory, table_pfn),
+ }
+ }
+
+ fn has_small(&self) -> bool {
+ PdeOps::is_valid(&self.small)
+ }
+
+ fn small_vram_address(&self) -> VramAddress {
+ PdeOps::table_vram_address(&self.small)
+ }
+
+ fn big_raw_u64(&self) -> u64 {
+ self.big.into_raw()
+ }
+
+ fn small_raw_u64(&self) -> u64 {
+ self.small.into_raw()
+ }
+}
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 09/16] gpu: nova-core: mm: pagetable: Add MmuConfig trait
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (7 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 08/16] gpu: nova-core: mm: Add MMU v3 " Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:12 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 10/16] gpu: nova-core: mm: Add page table walker for MMU v2/v3 Eliot Courtney
` (7 subsequent siblings)
16 siblings, 1 reply; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Introduce `MmuConfig`, the trait that ties the entry-operation traits
(`PteOps`, `PdeOps`, `DualPdeOps`) together with the version-specific
constants and helpers.
`MmuV2` and `MmuV3` are zero-sized marker structs that implement
`MmuConfig` for Turing/Ampere/Ada and Hopper/Blackwell respectively.
Dispatch is fully resolved at compile time through these markers, so
version-specific code is selected without runtime overhead and without
wrapper enums.
This enables version-agnostic page-table operations while keeping
version-specific implementation details encapsulated in the `ver2` and
`ver3` modules.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm/pagetable.rs | 109 ++++++++++++++++++++++++++++++++++
1 file changed, 109 insertions(+)
diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
index 128bfc0d277a..d88499ed3d56 100644
--- a/drivers/gpu/nova-core/mm/pagetable.rs
+++ b/drivers/gpu/nova-core/mm/pagetable.rs
@@ -21,6 +21,7 @@
use crate::mm::{
pramin,
Pfn,
+ VirtualAddress,
VramAddress, //
};
@@ -213,6 +214,114 @@ fn write(&self, pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result {
}
}
+/// MMU configuration trait -- encodes version-specific constants and types.
+pub(super) trait MmuConfig: 'static {
+ /// Page Table Entry type.
+ type Pte: PteOps;
+ /// Page Directory Entry type.
+ type Pde: PdeOps;
+ /// Dual Page Directory Entry type (128-bit).
+ type DualPde: DualPdeOps;
+
+ /// PDE levels (excluding PTE level) for page table walking.
+ const PDE_LEVELS: &'static [PageTableLevel];
+ /// PTE level for this MMU version.
+ const PTE_LEVEL: PageTableLevel;
+ /// Dual PDE level (128-bit entries) for this MMU version.
+ const DUAL_PDE_LEVEL: PageTableLevel;
+
+ /// Get the number of entries per page table page for a given level.
+ fn entries_per_page(level: PageTableLevel) -> usize;
+
+ /// Extract the page table index at `level` from `va`.
+ fn level_index(va: VirtualAddress, level: u64) -> u64;
+
+ /// Get the entry size in bytes for a given level.
+ fn entry_size(level: PageTableLevel) -> usize {
+ if level == Self::DUAL_PDE_LEVEL {
+ 16 // 128-bit dual PDE
+ } else {
+ 8 // 64-bit PDE/PTE
+ }
+ }
+
+ /// Compute upper bound on page table pages needed for `num_virt_pages`.
+ ///
+ /// Walks from PTE level up through PDE levels, accumulating the tree.
+ fn pt_pages_upper_bound(num_virt_pages: usize) -> usize {
+ let mut total = 0;
+
+ // PTE pages at the leaf level.
+ let pte_epp = Self::entries_per_page(Self::PTE_LEVEL);
+ let mut pages_at_level = num_virt_pages.div_ceil(pte_epp);
+ total += pages_at_level;
+
+ // Walk PDE levels bottom-up (reverse of PDE_LEVELS).
+ for &level in Self::PDE_LEVELS.iter().rev() {
+ let epp = Self::entries_per_page(level);
+
+ // How many pages at this level do we need to point to
+ // the previous pages_at_level?
+ pages_at_level = pages_at_level.div_ceil(epp);
+ total += pages_at_level;
+ }
+
+ total
+ }
+}
+
+/// Marker struct for MMU v2 (Turing/Ampere/Ada).
+pub(super) struct MmuV2;
+
+impl MmuConfig for MmuV2 {
+ type Pte = ver2::Pte;
+ type Pde = ver2::Pde;
+ type DualPde = ver2::DualPde;
+
+ const PDE_LEVELS: &'static [PageTableLevel] = ver2::PDE_LEVELS;
+ const PTE_LEVEL: PageTableLevel = ver2::PTE_LEVEL;
+ const DUAL_PDE_LEVEL: PageTableLevel = ver2::DUAL_PDE_LEVEL;
+
+ fn entries_per_page(level: PageTableLevel) -> usize {
+ // TODO: Calculate these values from the bitfield dynamically
+ // instead of hardcoding them.
+ match level {
+ PageTableLevel::Pdb => 4, // PD3 root: bits [48:47] = 2 bits
+ PageTableLevel::L3 => 256, // PD0 dual: bits [28:21] = 8 bits
+ _ => 512, // PD2, PD1, PT: 9 bits each
+ }
+ }
+
+ fn level_index(va: VirtualAddress, level: u64) -> u64 {
+ ver2::VirtualAddressV2::new(va).level_index(level)
+ }
+}
+
+/// Marker struct for MMU v3 (Hopper and later).
+pub(super) struct MmuV3;
+
+impl MmuConfig for MmuV3 {
+ type Pte = ver3::Pte;
+ type Pde = ver3::Pde;
+ type DualPde = ver3::DualPde;
+
+ const PDE_LEVELS: &'static [PageTableLevel] = ver3::PDE_LEVELS;
+ const PTE_LEVEL: PageTableLevel = ver3::PTE_LEVEL;
+ const DUAL_PDE_LEVEL: PageTableLevel = ver3::DUAL_PDE_LEVEL;
+
+ fn entries_per_page(level: PageTableLevel) -> usize {
+ match level {
+ PageTableLevel::Pdb => 2, // PDE4 root: bit [56] = 1 bit, 2 entries
+ PageTableLevel::L4 => 256, // PDE0 dual: bits [28:21] = 8 bits
+ _ => 512, // PDE3, PDE2, PDE1, PT: 9 bits each
+ }
+ }
+
+ fn level_index(va: VirtualAddress, level: u64) -> u64 {
+ ver3::VirtualAddressV3::new(va).level_index(level)
+ }
+}
+
/// Memory aperture for Page Table Entries (`PTE`s).
///
/// Determines which memory region the `PTE` points to.
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 10/16] gpu: nova-core: mm: Add page table walker for MMU v2/v3
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (8 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 09/16] gpu: nova-core: mm: pagetable: Add MmuConfig trait Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:07 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 11/16] gpu: nova-core: mm: Add Virtual Memory Manager Eliot Courtney
` (6 subsequent siblings)
16 siblings, 1 reply; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Add the page table walker implementation that traverses the page table
hierarchy for both MMU v2 (5-level) and MMU v3 (6-level) to resolve
virtual addresses to physical addresses or find PTE locations.
Currently only v2 has been tested (nova-core currently boots pre-hopper)
with some initial preparatory work done for v3.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: take mutable GpuMm and Pramin, not a bound device and window]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm/pagetable.rs | 1 +
drivers/gpu/nova-core/mm/pagetable/walk.rs | 244 +++++++++++++++++++++++++++++
2 files changed, 245 insertions(+)
diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
index d88499ed3d56..99145846daed 100644
--- a/drivers/gpu/nova-core/mm/pagetable.rs
+++ b/drivers/gpu/nova-core/mm/pagetable.rs
@@ -10,6 +10,7 @@
pub(super) mod ver2;
pub(super) mod ver3;
+pub(super) mod walk;
use kernel::{
io::Io,
diff --git a/drivers/gpu/nova-core/mm/pagetable/walk.rs b/drivers/gpu/nova-core/mm/pagetable/walk.rs
new file mode 100644
index 000000000000..76c1729971f5
--- /dev/null
+++ b/drivers/gpu/nova-core/mm/pagetable/walk.rs
@@ -0,0 +1,244 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Page table walker implementation for NVIDIA GPUs.
+//!
+//! This module provides page table walking functionality for MMU v2 and v3.
+//! The walker traverses the page table hierarchy to resolve virtual addresses
+//! to physical addresses or to find PTE locations.
+//!
+//! # Page Table Hierarchy
+//!
+//! ## MMU v2 (Turing/Ampere/Ada) - 5 levels
+//!
+//! ```text
+//! +-------+ +-------+ +-------+ +---------+ +-------+
+//! | PDB |---->| L1 |---->| L2 |---->| L3 Dual |---->| L4 |
+//! | (L0) | | | | | | PDE | | (PTE) |
+//! +-------+ +-------+ +-------+ +---------+ +-------+
+//! 64-bit 64-bit 64-bit 128-bit 64-bit
+//! PDE PDE PDE (big+small) PTE
+//! ```
+//!
+//! ## MMU v3 (Hopper+) - 6 levels
+//!
+//! ```text
+//! +-------+ +-------+ +-------+ +-------+ +---------+ +-------+
+//! | PDB |---->| L1 |---->| L2 |---->| L3 |---->| L4 Dual |---->| L5 |
+//! | (L0) | | | | | | | | PDE | | (PTE) |
+//! +-------+ +-------+ +-------+ +-------+ +---------+ +-------+
+//! 64-bit 64-bit 64-bit 64-bit 128-bit 64-bit
+//! PDE PDE PDE PDE (big+small) PTE
+//! ```
+//!
+//! # Result of a page table walk
+//!
+//! The walker returns a [`WalkResult`] indicating the outcome.
+
+use core::marker::PhantomData;
+
+use kernel::prelude::*;
+
+use super::{
+ DualPdeOps,
+ MmuConfig,
+ MmuV2,
+ MmuV3,
+ MmuVersion,
+ PageTableLevel,
+ PdeOps,
+ PteOps, //
+};
+use crate::{
+ mm::{
+ pramin,
+ GpuMm,
+ Pfn,
+ Vfn,
+ VirtualAddress,
+ VramAddress, //
+ },
+ num::{
+ IntoSafeCast, //
+ },
+};
+
+/// Result of walking to a PTE.
+#[derive(Debug, Clone, Copy)]
+pub(in crate::mm) enum WalkResult {
+ /// Intermediate page tables are missing (only returned in lookup mode).
+ PageTableMissing,
+ /// PTE exists but is invalid (page not mapped).
+ Unmapped { pte_addr: VramAddress },
+ /// PTE exists and is valid (page is mapped).
+ Mapped { pte_addr: VramAddress, pfn: Pfn },
+}
+
+/// Result of walking PDE levels only.
+///
+/// Returned by [`PtWalkInner::walk_pde_levels()`] to indicate whether all PDE
+/// levels resolved or a PDE is missing.
+#[derive(Debug, Clone, Copy)]
+pub(in crate::mm) enum WalkPdeResult {
+ /// All PDE levels resolved -- returns PTE page table address.
+ Complete {
+ /// VRAM address of the PTE-level page table.
+ pte_table: VramAddress,
+ },
+ /// A PDE is missing and no prepared page was provided by the closure.
+ Missing {
+ /// PDE slot address in the parent page table (where to install).
+ install_addr: VramAddress,
+ /// The page table level that is missing.
+ level: PageTableLevel,
+ },
+}
+
+/// Page table walker.
+pub(in crate::mm) struct PtWalkInner<M: MmuConfig> {
+ pdb_addr: VramAddress,
+ _phantom: PhantomData<M>,
+}
+
+impl<M: MmuConfig> PtWalkInner<M> {
+ /// Calculate the VRAM address of an entry within a page table.
+ fn entry_addr(table: VramAddress, level: PageTableLevel, index: u64) -> VramAddress {
+ let entry_size: u64 = M::entry_size(level).into_safe_cast();
+ table + index * entry_size
+ }
+
+ /// Create a new page table walker.
+ pub(super) fn new(pdb_addr: VramAddress) -> Self {
+ Self {
+ pdb_addr,
+ _phantom: PhantomData,
+ }
+ }
+
+ /// Walk PDE levels with closure-based resolution for missing PDEs.
+ ///
+ /// Traverses all PDE levels for the MMU version. At each level, reads the PDE.
+ /// If valid, extracts the child table address and continues. If missing, calls
+ /// `resolve_prepared(install_addr)` to resolve the missing PDE.
+ pub(super) fn walk_pde_levels(
+ &self,
+ pramin: &mut pramin::Pramin<'_>,
+ vfn: Vfn,
+ resolve_prepared: impl Fn(VramAddress) -> Option<VramAddress>,
+ ) -> Result<WalkPdeResult> {
+ let va = VirtualAddress::from(vfn);
+ let mut cur_table = self.pdb_addr;
+
+ for &level in M::PDE_LEVELS {
+ let idx = M::level_index(va, level.as_index());
+ let install_addr = Self::entry_addr(cur_table, level, idx);
+
+ if level == M::DUAL_PDE_LEVEL {
+ // 128-bit dual PDE with big+small page table pointers.
+ let dpde = M::DualPde::read(pramin, install_addr)?;
+ if dpde.has_small() {
+ cur_table = dpde.small_vram_address();
+ continue;
+ }
+ } else {
+ // Regular 64-bit PDE. Use `is_valid_vram()` because
+ // `table_vram_address()` only reads the VRAM frame-number
+ // bitfield; system-memory PDEs store the address in a
+ // different (wider) field and would be silently truncated.
+ let pde = M::Pde::read(pramin, install_addr)?;
+ if pde.is_valid_vram() {
+ cur_table = pde.table_vram_address();
+ continue;
+ }
+ }
+
+ // PDE missing in HW. Ask caller for resolution.
+ if let Some(prepared_addr) = resolve_prepared(install_addr) {
+ cur_table = prepared_addr;
+ continue;
+ }
+
+ return Ok(WalkPdeResult::Missing {
+ install_addr,
+ level,
+ });
+ }
+
+ Ok(WalkPdeResult::Complete {
+ pte_table: cur_table,
+ })
+ }
+
+ /// 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> {
+ self.walk_to_pte_lookup_with_window(mm.pramin_mut(), vfn)
+ }
+
+ /// Walk to PTE using a caller-provided PRAMIN manager (lookup only).
+ pub(super) fn walk_to_pte_lookup_with_window(
+ &self,
+ pramin: &mut pramin::Pramin<'_>,
+ vfn: Vfn,
+ ) -> Result<WalkResult> {
+ match self.walk_pde_levels(pramin, vfn, |_| None)? {
+ WalkPdeResult::Complete { pte_table } => {
+ Self::read_pte_at_level(pramin, vfn, pte_table)
+ }
+ WalkPdeResult::Missing { .. } => Ok(WalkResult::PageTableMissing),
+ }
+ }
+
+ /// Read the PTE at the PTE level given the PTE table address.
+ fn read_pte_at_level(
+ pramin: &mut pramin::Pramin<'_>,
+ vfn: Vfn,
+ pte_table: VramAddress,
+ ) -> Result<WalkResult> {
+ let va = VirtualAddress::from(vfn);
+ let pte_level = M::PTE_LEVEL;
+ let pte_idx = M::level_index(va, pte_level.as_index());
+ let pte_addr = Self::entry_addr(pte_table, pte_level, pte_idx);
+ let pte = M::Pte::read(pramin, pte_addr)?;
+
+ if pte.is_valid() {
+ return Ok(WalkResult::Mapped {
+ pte_addr,
+ pfn: pte.frame_number(),
+ });
+ }
+ Ok(WalkResult::Unmapped { pte_addr })
+ }
+}
+
+macro_rules! pt_walk_dispatch {
+ ($self:expr, $method:ident ( $($arg:expr),* $(,)? )) => {
+ match $self {
+ PtWalk::V2(inner) => inner.$method($($arg),*),
+ PtWalk::V3(inner) => inner.$method($($arg),*),
+ }
+ };
+}
+
+/// Page table walker dispatch.
+pub(in crate::mm) enum PtWalk {
+ /// MMU v2 (Turing/Ampere/Ada).
+ V2(PtWalkInner<MmuV2>),
+ /// MMU v3 (Hopper+).
+ V3(PtWalkInner<MmuV3>),
+}
+
+impl PtWalk {
+ /// Create a new page table walker for the given MMU version.
+ pub(in crate::mm) fn new(pdb_addr: VramAddress, version: MmuVersion) -> Self {
+ match version {
+ MmuVersion::V2 => Self::V2(PtWalkInner::<MmuV2>::new(pdb_addr)),
+ MmuVersion::V3 => Self::V3(PtWalkInner::<MmuV3>::new(pdb_addr)),
+ }
+ }
+
+ /// Walk to PTE for lookup.
+ pub(in crate::mm) fn walk_to_pte(&self, mm: &mut GpuMm<'_>, vfn: Vfn) -> Result<WalkResult> {
+ pt_walk_dispatch!(self, walk_to_pte_lookup(mm, vfn))
+ }
+}
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 11/16] gpu: nova-core: mm: Add Virtual Memory Manager
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (9 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 10/16] gpu: nova-core: mm: Add page table walker for MMU v2/v3 Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 3:59 ` [PATCH 12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM Eliot Courtney
` (5 subsequent siblings)
16 siblings, 0 replies; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Add the Virtual Memory Manager (VMM) infrastructure for GPU address
space management. Each Vmm instance manages a single address space
identified by its Page Directory Base (PDB) address, used for Channel,
BAR1 and BAR2 mappings.
Mapping APIs and virtual address range tracking are added in later
commits.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: pass mutable GpuMm to mapping lookup]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm.rs | 1 +
drivers/gpu/nova-core/mm/vmm.rs | 58 +++++++++++++++++++++++++++++++++++++++++
2 files changed, 59 insertions(+)
diff --git a/drivers/gpu/nova-core/mm.rs b/drivers/gpu/nova-core/mm.rs
index 377cc9d44702..2cf37254fbb9 100644
--- a/drivers/gpu/nova-core/mm.rs
+++ b/drivers/gpu/nova-core/mm.rs
@@ -65,6 +65,7 @@ macro_rules! impl_pfn_bounded {
mod pramin;
mod regs;
pub(super) mod tlb;
+pub(super) mod vmm;
/// GPU Memory Manager - owns all core MM components.
///
diff --git a/drivers/gpu/nova-core/mm/vmm.rs b/drivers/gpu/nova-core/mm/vmm.rs
new file mode 100644
index 000000000000..a7911efb65a0
--- /dev/null
+++ b/drivers/gpu/nova-core/mm/vmm.rs
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Virtual Memory Manager for NVIDIA GPU page table management.
+//!
+//! The [`Vmm`] provides high-level page mapping and unmapping operations for GPU
+//! virtual address spaces (Channels, BAR1, BAR2). It wraps the page table walker
+//! and handles TLB flushing after modifications.
+
+use kernel::{
+ gpu::buddy::AllocatedBlocks,
+ prelude::*, //
+};
+
+use crate::mm::{
+ pagetable::{
+ walk::{PtWalk, WalkResult},
+ MmuVersion, //
+ },
+ GpuMm,
+ Pfn,
+ Vfn,
+ VramAddress, //
+};
+
+/// Virtual Memory Manager for a GPU address space.
+///
+/// Each [`Vmm`] instance manages a single address space identified by its Page
+/// Directory Base (`PDB`) address. The [`Vmm`] is used for Channel, BAR1 and
+/// BAR2 mappings.
+pub(crate) struct Vmm {
+ /// Page Directory Base address for this address space.
+ pdb_addr: VramAddress,
+ /// MMU version used for page table layout.
+ mmu_version: MmuVersion,
+ /// Page table allocations required for mappings.
+ page_table_allocs: KVec<Pin<KBox<AllocatedBlocks>>>,
+}
+
+impl Vmm {
+ /// Create a new [`Vmm`] for the given Page Directory Base address.
+ pub(crate) fn new(pdb_addr: VramAddress, mmu_version: MmuVersion) -> Result<Self> {
+ Ok(Self {
+ pdb_addr,
+ mmu_version,
+ page_table_allocs: KVec::new(),
+ })
+ }
+
+ /// 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>> {
+ let walker = PtWalk::new(self.pdb_addr, self.mmu_version);
+
+ match walker.walk_to_pte(mm, vfn)? {
+ WalkResult::Mapped { pfn, .. } => Ok(Some(pfn)),
+ WalkResult::Unmapped { .. } | WalkResult::PageTableMissing => Ok(None),
+ }
+ }
+}
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (10 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 11/16] gpu: nova-core: mm: Add Virtual Memory Manager Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:18 ` sashiko-bot
2026-09-09 19:32 ` Danilo Krummrich
2026-09-09 3:59 ` [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API " Eliot Courtney
` (4 subsequent siblings)
16 siblings, 2 replies; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Add virtual address range tracking to the VMM using a maple tree
allocator. This enables contiguous virtual address range allocation
for mappings.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm/vmm.rs | 83 ++++++++++++++++++++++++++++++++++++-----
1 file changed, 74 insertions(+), 9 deletions(-)
diff --git a/drivers/gpu/nova-core/mm/vmm.rs b/drivers/gpu/nova-core/mm/vmm.rs
index a7911efb65a0..0bcae29db4f2 100644
--- a/drivers/gpu/nova-core/mm/vmm.rs
+++ b/drivers/gpu/nova-core/mm/vmm.rs
@@ -8,18 +8,27 @@
use kernel::{
gpu::buddy::AllocatedBlocks,
+ maple_tree::MapleTreeAlloc,
prelude::*, //
};
-use crate::mm::{
- pagetable::{
- walk::{PtWalk, WalkResult},
- MmuVersion, //
+use core::ops::Range;
+
+use crate::{
+ mm::{
+ pagetable::{
+ walk::{PtWalk, WalkResult},
+ MmuVersion, //
+ },
+ GpuMm,
+ Pfn,
+ Vfn,
+ VramAddress,
+ PAGE_SIZE, //
+ },
+ num::{
+ IntoSafeCast, //
},
- GpuMm,
- Pfn,
- Vfn,
- VramAddress, //
};
/// Virtual Memory Manager for a GPU address space.
@@ -34,18 +43,74 @@ pub(crate) struct Vmm {
mmu_version: MmuVersion,
/// Page table allocations required for mappings.
page_table_allocs: KVec<Pin<KBox<AllocatedBlocks>>>,
+ /// Maple tree allocator for virtual address range tracking.
+ virt_alloc: Pin<KBox<MapleTreeAlloc<()>>>,
+ /// Total number of pages in the virtual address space.
+ va_pages: usize,
}
impl Vmm {
/// Create a new [`Vmm`] for the given Page Directory Base address.
- pub(crate) fn new(pdb_addr: VramAddress, mmu_version: MmuVersion) -> Result<Self> {
+ ///
+ /// The [`Vmm`] will manage a virtual address space of `va_size` bytes.
+ pub(crate) fn new(
+ pdb_addr: VramAddress,
+ mmu_version: MmuVersion,
+ va_size: u64,
+ ) -> Result<Self> {
+ let page_size: u64 = PAGE_SIZE.into_safe_cast();
+ let va_pages: usize = (va_size / page_size).into_safe_cast();
+ let virt_alloc = KBox::pin_init(MapleTreeAlloc::<()>::new(), GFP_KERNEL)?;
+
Ok(Self {
pdb_addr,
mmu_version,
page_table_allocs: KVec::new(),
+ virt_alloc,
+ va_pages,
})
}
+ /// Allocate a contiguous virtual frame number range.
+ ///
+ /// # Arguments
+ ///
+ /// - `num_pages`: Number of pages to allocate.
+ /// - `va_range`: `None` = allocate anywhere, `Some(range)` = constrain allocation to the given
+ /// range.
+ fn alloc_vfn_range(&self, num_pages: usize, va_range: Option<Range<u64>>) -> Result<Vfn> {
+ let page_size: u64 = PAGE_SIZE.into_safe_cast();
+
+ let start_vfn = match va_range {
+ Some(r) => {
+ let num_pages_u64: u64 = num_pages.into_safe_cast();
+ let size = num_pages_u64.checked_mul(page_size).ok_or(EOVERFLOW)?;
+ let range_size = r.end.checked_sub(r.start).ok_or(EOVERFLOW)?;
+ if range_size != size {
+ return Err(EINVAL);
+ }
+ let start_vfn: usize = (r.start / page_size).into_safe_cast();
+ let end_vfn: usize = (r.end / page_size).into_safe_cast();
+ self.virt_alloc
+ .insert_range(start_vfn..end_vfn, (), GFP_KERNEL)?;
+ start_vfn
+ }
+ None => self
+ .virt_alloc
+ .alloc_range(num_pages, (), ..self.va_pages, GFP_KERNEL)?,
+ };
+
+ Ok(Vfn::new(start_vfn.into_safe_cast()))
+ }
+
+ /// Free a virtual frame number range back to the maple tree.
+ fn free_vfn(&self, vfn: Vfn) {
+ let vfn_index: usize = vfn.raw().into_safe_cast();
+ if self.virt_alloc.erase(vfn_index).is_none() {
+ kernel::pr_warn!("free_vfn: VFN {} not found in maple tree\n", vfn_index);
+ }
+ }
+
/// 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>> {
let walker = PtWalk::new(self.pdb_addr, self.mmu_version);
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API to VMM
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (11 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:17 ` sashiko-bot
` (2 more replies)
2026-09-09 3:59 ` [PATCH 14/16] gpu: nova-core: Add BAR1 aperture type and size constant Eliot Courtney
` (3 subsequent siblings)
16 siblings, 3 replies; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Add the page table mapping and unmapping API to the Virtual Memory
Manager, implementing a two-phase prepare/execute model suitable for
use both inside and outside the DMA fence signalling critical path.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: pass mutable GpuMm, replace window guards with scoped borrows]
[ecourtney: use current raw address helpers, drop stale expects]
[ecourtney: zero page table pages through one PRAMIN view]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/mm/pagetable.rs | 1 +
drivers/gpu/nova-core/mm/pagetable/map.rs | 342 ++++++++++++++++++++++++++++++
drivers/gpu/nova-core/mm/vmm.rs | 260 +++++++++++++++++++++--
3 files changed, 584 insertions(+), 19 deletions(-)
diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
index 99145846daed..ffc69fbdb067 100644
--- a/drivers/gpu/nova-core/mm/pagetable.rs
+++ b/drivers/gpu/nova-core/mm/pagetable.rs
@@ -8,6 +8,7 @@
#![expect(dead_code)]
+pub(super) mod map;
pub(super) mod ver2;
pub(super) mod ver3;
pub(super) mod walk;
diff --git a/drivers/gpu/nova-core/mm/pagetable/map.rs b/drivers/gpu/nova-core/mm/pagetable/map.rs
new file mode 100644
index 000000000000..21fc66e7c62c
--- /dev/null
+++ b/drivers/gpu/nova-core/mm/pagetable/map.rs
@@ -0,0 +1,342 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Page table mapping operations for NVIDIA GPUs.
+
+use core::marker::PhantomData;
+
+use kernel::{
+ gpu::buddy::{
+ AllocatedBlocks,
+ GpuBuddyAllocFlags,
+ GpuBuddyAllocMode, //
+ },
+ io::io_write,
+ prelude::*,
+ ptr::Alignment,
+ rbtree::{RBTree, RBTreeNode},
+ sizes::SZ_4K, //
+};
+
+use super::{
+ walk::{
+ PtWalkInner,
+ WalkPdeResult,
+ WalkResult, //
+ },
+ AperturePde,
+ AperturePte,
+ DualPdeOps,
+ MmuConfig,
+ MmuV2,
+ MmuV3,
+ MmuVersion,
+ PageTableLevel,
+ PdeOps,
+ PteOps, //
+};
+use crate::{
+ mm::{
+ GpuMm,
+ Pfn,
+ Vfn,
+ VramAddress,
+ PAGE_SIZE, //
+ },
+ num::{
+ IntoSafeCast, //
+ },
+};
+
+/// A pre-allocated and zeroed page table page.
+///
+/// Created during the mapping prepare phase and consumed during the execute phase.
+/// Stored in an [`RBTree`] keyed by the PDE slot address (`install_addr`).
+pub(in crate::mm) struct PreparedPtPage {
+ /// The allocated and zeroed page table page.
+ pub(in crate::mm) alloc: Pin<KBox<AllocatedBlocks>>,
+ /// Page table level -- needed to determine if this PT page is for a dual PDE.
+ pub(in crate::mm) level: PageTableLevel,
+}
+
+/// Page table mapper.
+pub(in crate::mm) struct PtMapInner<M: MmuConfig> {
+ walker: PtWalkInner<M>,
+ pdb_addr: VramAddress,
+ _phantom: PhantomData<M>,
+}
+
+impl<M: MmuConfig> PtMapInner<M> {
+ /// Create a new [`PtMapInner`].
+ pub(super) fn new(pdb_addr: VramAddress) -> Self {
+ Self {
+ walker: PtWalkInner::<M>::new(pdb_addr),
+ pdb_addr,
+ _phantom: PhantomData,
+ }
+ }
+
+ /// Allocate and zero a physical page table page.
+ fn alloc_and_zero_page(mm: &mut GpuMm<'_>, level: PageTableLevel) -> Result<PreparedPtPage> {
+ let blocks = KBox::pin_init(
+ mm.buddy().alloc_blocks(
+ GpuBuddyAllocMode::Simple,
+ SZ_4K.into_safe_cast(),
+ Alignment::new::<SZ_4K>(),
+ GpuBuddyAllocFlags::default(),
+ ),
+ GFP_KERNEL,
+ )?;
+
+ 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);
+ }
+
+ Ok(PreparedPtPage {
+ alloc: blocks,
+ level,
+ })
+ }
+
+ /// Ensure all intermediate page table pages exist for a single VFN.
+ ///
+ /// The mutable PRAMIN borrow ends before each allocation.
+ fn ensure_single_pte_path(
+ &self,
+ mm: &mut GpuMm<'_>,
+ vfn: Vfn,
+ pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
+ ) -> Result {
+ 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| {
+ pt_pages.get(&install_addr).and_then(|p| {
+ p.alloc
+ .iter()
+ .next()
+ .map(|b| VramAddress::from_raw(b.offset()))
+ })
+ })?;
+
+ match result {
+ WalkPdeResult::Complete { .. } => {
+ return Ok(());
+ }
+ WalkPdeResult::Missing {
+ install_addr,
+ level,
+ } => {
+ let page = Self::alloc_and_zero_page(mm, level)?;
+ let node = RBTreeNode::new(install_addr, page, GFP_KERNEL)?;
+ let old = pt_pages.insert(node);
+ if old.is_some() {
+ kernel::pr_warn_once!(
+ "VMM: duplicate install_addr in pt_pages (internal consistency error)\n"
+ );
+ return Err(EIO);
+ }
+ }
+ }
+ }
+
+ kernel::pr_warn!(
+ "VMM: ensure_pte_path: loop exhausted after {} iters (VFN {:?})\n",
+ max_iter,
+ vfn
+ );
+ Err(EIO)
+ }
+
+ /// Prepare page table resources for mapping `num_pages` pages starting at `vfn_start`.
+ ///
+ /// Reserves capacity in `page_table_allocs`, then walks the hierarchy
+ /// per-VFN to prepare pages for all missing PDEs.
+ pub(super) fn prepare_map(
+ &self,
+ mm: &mut GpuMm<'_>,
+ vfn_start: Vfn,
+ num_pages: usize,
+ page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
+ pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
+ ) -> Result {
+ // Pre-reserve so install_mappings() can use push_within_capacity (no alloc
+ // in fence signalling critical path).
+ let pt_upper_bound = M::pt_pages_upper_bound(num_pages);
+ page_table_allocs.reserve(pt_upper_bound, GFP_KERNEL)?;
+
+ // Walk the hierarchy per-VFN to prepare pages for all missing PDEs.
+ for i in 0..num_pages {
+ let i_u64: u64 = i.into_safe_cast();
+ let vfn = Vfn::new(vfn_start.raw() + i_u64);
+ self.ensure_single_pte_path(mm, vfn, pt_pages)?;
+ }
+ Ok(())
+ }
+
+ /// Install prepared PDEs and write PTEs, then flush TLB.
+ ///
+ /// Drains `pt_pages` and moves allocations into `page_table_allocs`.
+ pub(super) fn install_mappings(
+ &self,
+ mm: &mut GpuMm<'_>,
+ pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
+ page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
+ vfn_start: Vfn,
+ pfns: &[Pfn],
+ writable: bool,
+ ) -> Result {
+ {
+ let pramin = mm.pramin_mut();
+
+ // Drain prepared PT pages, install all pending PDEs.
+ let mut cursor = pt_pages.cursor_front_mut();
+ while let Some(c) = cursor {
+ let (next, node) = c.remove_current();
+ let (install_addr, page) = node.to_key_value();
+ let page_vram =
+ VramAddress::from_raw(page.alloc.iter().next().ok_or(ENOMEM)?.offset());
+
+ if page.level == M::DUAL_PDE_LEVEL {
+ let new_dpde = M::DualPde::new_small(Pfn::from(page_vram));
+ new_dpde.write(pramin, install_addr)?;
+ } else {
+ let new_pde = M::Pde::new(AperturePde::VideoMemory, Pfn::from(page_vram));
+ new_pde.write(pramin, install_addr)?;
+ }
+
+ page_table_allocs
+ .push_within_capacity(page.alloc)
+ .map_err(|_| ENOMEM)?;
+
+ cursor = next;
+ }
+
+ // Write PTEs (all PDEs now installed in HW).
+ for (i, &pfn) in pfns.iter().enumerate() {
+ let i_u64: u64 = i.into_safe_cast();
+ let vfn = Vfn::new(vfn_start.raw() + i_u64);
+ let result = self.walker.walk_to_pte_lookup_with_window(pramin, vfn)?;
+
+ match result {
+ WalkResult::Unmapped { pte_addr } | WalkResult::Mapped { pte_addr, .. } => {
+ let pte = M::Pte::new(AperturePte::VideoMemory, pfn, writable);
+ pte.write(pramin, pte_addr)?;
+ }
+ WalkResult::PageTableMissing => {
+ kernel::pr_warn_once!("VMM: page table missing for VFN {vfn:?}\n");
+ return Err(EIO);
+ }
+ }
+ }
+ }
+
+ // Flush TLB.
+ mm.tlb().flush(self.pdb_addr)
+ }
+
+ /// Invalidate PTEs for a range and flush TLB.
+ pub(super) fn invalidate_ptes(
+ &self,
+ mm: &mut GpuMm<'_>,
+ vfn_start: Vfn,
+ num_pages: usize,
+ ) -> Result {
+ let invalid_pte = M::Pte::invalid();
+
+ {
+ let pramin = mm.pramin_mut();
+ for i in 0..num_pages {
+ let i_u64: u64 = i.into_safe_cast();
+ let vfn = Vfn::new(vfn_start.raw() + i_u64);
+ let result = self.walker.walk_to_pte_lookup_with_window(pramin, vfn)?;
+
+ match result {
+ WalkResult::Mapped { pte_addr, .. } | WalkResult::Unmapped { pte_addr } => {
+ invalid_pte.write(pramin, pte_addr)?;
+ }
+ WalkResult::PageTableMissing => {
+ continue;
+ }
+ }
+ }
+ }
+
+ mm.tlb().flush(self.pdb_addr)
+ }
+}
+
+macro_rules! pt_map_dispatch {
+ ($self:expr, $method:ident ( $($arg:expr),* $(,)? )) => {
+ match $self {
+ PtMap::V2(inner) => inner.$method($($arg),*),
+ PtMap::V3(inner) => inner.$method($($arg),*),
+ }
+ };
+}
+
+/// Page table mapper dispatch.
+pub(in crate::mm) enum PtMap {
+ /// MMU v2 (Turing/Ampere/Ada).
+ V2(PtMapInner<MmuV2>),
+ /// MMU v3 (Hopper+).
+ V3(PtMapInner<MmuV3>),
+}
+
+impl PtMap {
+ /// Create a new page table mapper for the given MMU version.
+ pub(in crate::mm) fn new(pdb_addr: VramAddress, version: MmuVersion) -> Self {
+ match version {
+ MmuVersion::V2 => Self::V2(PtMapInner::<MmuV2>::new(pdb_addr)),
+ MmuVersion::V3 => Self::V3(PtMapInner::<MmuV3>::new(pdb_addr)),
+ }
+ }
+
+ /// Prepare page table resources for a mapping.
+ pub(in crate::mm) fn prepare_map(
+ &self,
+ mm: &mut GpuMm<'_>,
+ vfn_start: Vfn,
+ num_pages: usize,
+ page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
+ pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
+ ) -> Result {
+ pt_map_dispatch!(
+ self,
+ prepare_map(mm, vfn_start, num_pages, page_table_allocs, pt_pages)
+ )
+ }
+
+ /// Install prepared PDEs and write PTEs, then flush TLB.
+ pub(in crate::mm) fn install_mappings(
+ &self,
+ mm: &mut GpuMm<'_>,
+ pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
+ page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
+ vfn_start: Vfn,
+ pfns: &[Pfn],
+ writable: bool,
+ ) -> Result {
+ pt_map_dispatch!(
+ self,
+ install_mappings(mm, pt_pages, page_table_allocs, vfn_start, pfns, writable)
+ )
+ }
+
+ /// Invalidate PTEs for a range and flush TLB.
+ pub(in crate::mm) fn invalidate_ptes(
+ &self,
+ mm: &mut GpuMm<'_>,
+ vfn_start: Vfn,
+ num_pages: usize,
+ ) -> Result {
+ pt_map_dispatch!(self, invalidate_ptes(mm, vfn_start, num_pages))
+ }
+}
diff --git a/drivers/gpu/nova-core/mm/vmm.rs b/drivers/gpu/nova-core/mm/vmm.rs
index 0bcae29db4f2..411710d03f7a 100644
--- a/drivers/gpu/nova-core/mm/vmm.rs
+++ b/drivers/gpu/nova-core/mm/vmm.rs
@@ -3,21 +3,30 @@
//! Virtual Memory Manager for NVIDIA GPU page table management.
//!
//! The [`Vmm`] provides high-level page mapping and unmapping operations for GPU
-//! virtual address spaces (Channels, BAR1, BAR2). It wraps the page table walker
-//! and handles TLB flushing after modifications.
+//! virtual address spaces (Channels, BAR1, BAR2).
use kernel::{
gpu::buddy::AllocatedBlocks,
maple_tree::MapleTreeAlloc,
- prelude::*, //
+ prelude::*,
+ rbtree::RBTree, //
};
-use core::ops::Range;
+use core::{
+ cell::Cell,
+ ops::Range, //
+};
use crate::{
mm::{
pagetable::{
- walk::{PtWalk, WalkResult},
+ map::{
+ PtMap, //
+ },
+ walk::{
+ PtWalk,
+ WalkResult, //
+ },
MmuVersion, //
},
GpuMm,
@@ -31,22 +40,108 @@
},
};
+/// Multi-page prepared mapping -- VA range allocated, ready for execute.
+///
+/// Produced by [`Vmm::prepare_map()`], consumed by [`Vmm::execute_map()`].
+/// The VA space allocation is tracked in the [`Vmm`]'s maple tree and freed
+/// on error or via [`Vmm::unmap_pages()`].
+///
+/// Dropping without calling [`Vmm::execute_map()`] logs a warning and leaks
+/// the VA range in the maple tree.
+pub(crate) struct PreparedMapping {
+ vfn_start: Vfn,
+ num_pages: usize,
+ /// Logs a warning if dropped without executing.
+ _drop_guard: MustExecuteGuard,
+}
+
+/// Result of a mapping operation -- tracks the active mapped range.
+///
+/// Returned by [`Vmm::execute_map()`] and [`Vmm::map_pages()`].
+/// Callers must call [`Vmm::unmap_pages()`] before dropping to invalidate
+/// PTEs and free the VA range. Dropping without unmapping logs a warning
+/// and leaks the VA range in the maple tree.
+pub(crate) struct MappedRange {
+ pub(super) vfn_start: Vfn,
+ pub(super) num_pages: usize,
+ /// Logs a warning if dropped without unmapping.
+ _drop_guard: MustUnmapGuard,
+}
+
+/// Guard that logs a warning if a [`PreparedMapping`] is dropped without
+/// being consumed by [`Vmm::execute_map()`].
+struct MustExecuteGuard {
+ armed: Cell<bool>,
+}
+
+impl MustExecuteGuard {
+ const fn new() -> Self {
+ Self {
+ armed: Cell::new(true),
+ }
+ }
+
+ fn disarm(&self) {
+ self.armed.set(false);
+ }
+}
+
+impl Drop for MustExecuteGuard {
+ fn drop(&mut self) {
+ if self.armed.get() {
+ kernel::pr_warn!("PreparedMapping dropped without calling execute_map()\n");
+ }
+ }
+}
+
+/// Guard that logs a warning if a [`MappedRange`] is dropped without
+/// calling [`Vmm::unmap_pages()`].
+struct MustUnmapGuard {
+ armed: Cell<bool>,
+}
+
+impl MustUnmapGuard {
+ const fn new() -> Self {
+ Self {
+ armed: Cell::new(true),
+ }
+ }
+
+ fn disarm(&self) {
+ self.armed.set(false);
+ }
+}
+
+impl Drop for MustUnmapGuard {
+ fn drop(&mut self) {
+ if self.armed.get() {
+ kernel::pr_warn!("MappedRange dropped without calling unmap_pages()\n");
+ }
+ }
+}
+
/// Virtual Memory Manager for a GPU address space.
///
/// Each [`Vmm`] instance manages a single address space identified by its Page
-/// Directory Base (`PDB`) address. The [`Vmm`] is used for Channel, BAR1 and
-/// BAR2 mappings.
+/// Directory Base (`PDB`) address. Used for Channel, BAR1 and BAR2 mappings.
pub(crate) struct Vmm {
/// Page Directory Base address for this address space.
pdb_addr: VramAddress,
- /// MMU version used for page table layout.
- mmu_version: MmuVersion,
+ /// Page table walker for reading existing mappings.
+ pt_walk: PtWalk,
+ /// Page table mapper for prepare/execute operations.
+ pt_map: PtMap,
/// Page table allocations required for mappings.
page_table_allocs: KVec<Pin<KBox<AllocatedBlocks>>>,
/// Maple tree allocator for virtual address range tracking.
virt_alloc: Pin<KBox<MapleTreeAlloc<()>>>,
/// Total number of pages in the virtual address space.
va_pages: usize,
+ /// Prepared PT pages pending PDE installation, keyed by `install_addr`.
+ ///
+ /// Populated during prepare phase and drained in execute phase. Shared by all
+ /// pending maps, preventing races on the same PDE slot.
+ pt_pages: RBTree<VramAddress, super::pagetable::map::PreparedPtPage>,
}
impl Vmm {
@@ -64,20 +159,16 @@ pub(crate) fn new(
Ok(Self {
pdb_addr,
- mmu_version,
+ pt_walk: PtWalk::new(pdb_addr, mmu_version),
+ pt_map: PtMap::new(pdb_addr, mmu_version),
page_table_allocs: KVec::new(),
virt_alloc,
va_pages,
+ pt_pages: RBTree::new(),
})
}
/// Allocate a contiguous virtual frame number range.
- ///
- /// # Arguments
- ///
- /// - `num_pages`: Number of pages to allocate.
- /// - `va_range`: `None` = allocate anywhere, `Some(range)` = constrain allocation to the given
- /// range.
fn alloc_vfn_range(&self, num_pages: usize, va_range: Option<Range<u64>>) -> Result<Vfn> {
let page_size: u64 = PAGE_SIZE.into_safe_cast();
@@ -113,11 +204,142 @@ 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>> {
- let walker = PtWalk::new(self.pdb_addr, self.mmu_version);
-
- match walker.walk_to_pte(mm, vfn)? {
+ match self.pt_walk.walk_to_pte(mm, vfn)? {
WalkResult::Mapped { pfn, .. } => Ok(Some(pfn)),
WalkResult::Unmapped { .. } | WalkResult::PageTableMissing => Ok(None),
}
}
+
+ /// Prepare resources for mapping `num_pages` pages.
+ ///
+ /// Allocates a contiguous VA range, then walks the hierarchy per-VFN to prepare pages
+ /// for all missing PDEs. Returns a [`PreparedMapping`] with the VA allocation.
+ ///
+ /// If `va_range` is not `None`, the VA range is constrained to the given range. Safe
+ /// to call outside the fence signalling critical path.
+ pub(crate) fn prepare_map(
+ &mut self,
+ mm: &mut GpuMm<'_>,
+ num_pages: usize,
+ va_range: Option<Range<u64>>,
+ ) -> Result<PreparedMapping> {
+ if num_pages == 0 {
+ return Err(EINVAL);
+ }
+
+ // Allocate contiguous VA range.
+ let vfn_start = self.alloc_vfn_range(num_pages, va_range)?;
+
+ if let Err(e) = self.pt_map.prepare_map(
+ mm,
+ vfn_start,
+ num_pages,
+ &mut self.page_table_allocs,
+ &mut self.pt_pages,
+ ) {
+ self.free_vfn(vfn_start);
+ return Err(e);
+ }
+
+ Ok(PreparedMapping {
+ vfn_start,
+ num_pages,
+ _drop_guard: MustExecuteGuard::new(),
+ })
+ }
+
+ /// Execute a prepared multi-page mapping.
+ ///
+ /// Installs all prepared PDEs and writes PTEs into the page table, then flushes TLB.
+ pub(crate) fn execute_map(
+ &mut self,
+ mm: &mut GpuMm<'_>,
+ prepared: PreparedMapping,
+ pfns: &[Pfn],
+ writable: bool,
+ ) -> Result<MappedRange> {
+ if pfns.len() != prepared.num_pages {
+ self.free_vfn(prepared.vfn_start);
+ return Err(EINVAL);
+ }
+
+ let PreparedMapping {
+ vfn_start,
+ num_pages,
+ _drop_guard,
+ } = prepared;
+ _drop_guard.disarm();
+
+ if let Err(e) = self.pt_map.install_mappings(
+ mm,
+ &mut self.pt_pages,
+ &mut self.page_table_allocs,
+ vfn_start,
+ pfns,
+ writable,
+ ) {
+ self.free_vfn(vfn_start);
+ return Err(e);
+ }
+
+ Ok(MappedRange {
+ vfn_start,
+ num_pages,
+ _drop_guard: MustUnmapGuard::new(),
+ })
+ }
+
+ /// Map pages doing prepare and execute in the same call.
+ ///
+ /// This is a convenience wrapper for callers outside the fence signalling critical
+ /// path (e.g., BAR mappings). For DRM usecases, [`Vmm::prepare_map()`] and
+ /// [`Vmm::execute_map()`] will be called separately.
+ pub(crate) fn map_pages(
+ &mut self,
+ mm: &mut GpuMm<'_>,
+ pfns: &[Pfn],
+ va_range: Option<Range<u64>>,
+ writable: bool,
+ ) -> Result<MappedRange> {
+ if pfns.is_empty() {
+ return Err(EINVAL);
+ }
+
+ // Check if provided VA range is sufficient (if provided).
+ if let Some(ref range) = va_range {
+ let required: u64 = pfns
+ .len()
+ .checked_mul(PAGE_SIZE)
+ .ok_or(EOVERFLOW)?
+ .into_safe_cast();
+ let available = range.end.checked_sub(range.start).ok_or(EINVAL)?;
+ if available < required {
+ return Err(EINVAL);
+ }
+ }
+
+ let prepared = self.prepare_map(mm, pfns.len(), va_range)?;
+ self.execute_map(mm, prepared, pfns, writable)
+ }
+
+ /// Unmap all pages in a [`MappedRange`] with a single TLB flush.
+ pub(crate) fn unmap_pages(&mut self, mm: &mut GpuMm<'_>, range: MappedRange) -> Result {
+ let result = self
+ .pt_map
+ .invalidate_ptes(mm, range.vfn_start, range.num_pages);
+
+ // TODO: Internal page table pages (PDE, PTE pages) are still kept around.
+ // This is by design as repeated maps/unmaps will be fast. As a future TODO,
+ // we can add a reclaimer here to reclaim if VRAM is short. For now, the PT
+ // pages are dropped once the `Vmm` is dropped.
+
+ // Free the VA range regardless of PTE invalidation success, so that the VA
+ // range is recovered even on failure (PTEs may be stale, but that is better
+ // than leaking both PTEs and VA range).
+ self.free_vfn(range.vfn_start);
+
+ // Unmap complete, safe to drop `MappedRange`.
+ range._drop_guard.disarm();
+ result
+ }
}
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 14/16] gpu: nova-core: Add BAR1 aperture type and size constant
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (12 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API " Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:14 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface Eliot Courtney
` (2 subsequent siblings)
16 siblings, 1 reply; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes, Zhi Wang
From: Joel Fernandes <joelagnelf@nvidia.com>
Add BAR1_SIZE constant and Bar1 type alias for the 256MB BAR1 aperture.
These are prerequisites for BAR1 memory access functionality.
Co-developed-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: add the Bar1 lifetime for current PCI BAR ownership]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/driver.rs | 2 ++
drivers/gpu/nova-core/gsp/commands.rs | 4 ++++
drivers/gpu/nova-core/gsp/fw/commands.rs | 8 ++++++++
3 files changed, 14 insertions(+)
diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver.rs
index 8cef4c284277..5723ff8f71ea 100644
--- a/drivers/gpu/nova-core/driver.rs
+++ b/drivers/gpu/nova-core/driver.rs
@@ -38,6 +38,8 @@ pub(crate) struct NovaCore<'bound> {
pub(crate) type Bar0<'a> = &'a pci::Bar<'a, BAR0_SIZE>;
pub(crate) type NovaRegisters = kernel::io::Region<BAR0_SIZE>;
+#[expect(dead_code)]
+pub(crate) type Bar1<'a> = pci::Bar<'a>;
kernel::pci_device_table!(
PCI_TABLE,
diff --git a/drivers/gpu/nova-core/gsp/commands.rs b/drivers/gpu/nova-core/gsp/commands.rs
index eea1c9ed4684..1c467718c679 100644
--- a/drivers/gpu/nova-core/gsp/commands.rs
+++ b/drivers/gpu/nova-core/gsp/commands.rs
@@ -214,6 +214,9 @@ fn init(&self) -> impl Init<Self::Command, Self::InitError> {
/// The reply from the GSP to the [`GetGspStaticInfo`] command.
pub(crate) struct GetGspStaticInfoReply {
gpu_name: [u8; 64],
+ /// BAR1 Page Directory Entry base address.
+ #[expect(dead_code)]
+ pub(crate) bar1_pde_base: u64,
/// Usable FB (VRAM) regions for driver memory allocation.
pub(crate) usable_fb_regions: KVec<Range<u64>>,
/// Exclusive end of the FB physical address space.
@@ -237,6 +240,7 @@ fn read(
Ok(GetGspStaticInfoReply {
gpu_name: msg.gpu_name_str(),
+ bar1_pde_base: msg.bar1_pde_base(),
usable_fb_regions,
total_fb_end,
})
diff --git a/drivers/gpu/nova-core/gsp/fw/commands.rs b/drivers/gpu/nova-core/gsp/fw/commands.rs
index 6e85442a4b13..32856ff74183 100644
--- a/drivers/gpu/nova-core/gsp/fw/commands.rs
+++ b/drivers/gpu/nova-core/gsp/fw/commands.rs
@@ -131,6 +131,14 @@ impl GspStaticConfigInfo {
self.0.gpuNameString
}
+ /// Returns the BAR1 Page Directory Entry base address.
+ ///
+ /// This is the root page table address for BAR1 virtual memory,
+ /// set up by GSP-RM firmware.
+ pub(crate) fn bar1_pde_base(&self) -> u64 {
+ self.0.bar1PdeBase
+ }
+
/// Returns an iterator over valid FB regions from GSP firmware data.
fn fb_regions(
&self,
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (13 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 14/16] gpu: nova-core: Add BAR1 aperture type and size constant Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:16 ` sashiko-bot
2026-09-09 20:13 ` Danilo Krummrich
2026-09-09 3:59 ` [PATCH 16/16] gpu: nova-core: mm: Add BAR1 memory management self-tests Eliot Courtney
2026-09-09 21:11 ` [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Danilo Krummrich
16 siblings, 2 replies; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Add the BAR1 user interface for CPU access to GPU virtual memory through
the BAR1 aperture.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: map BAR1 in NovaCore, borrow it in Gpu and BarUser, no Devres]
[ecourtney: update for the VramAddress raw API and gsp_resources chipset]
[ecourtney: drop the owned GpuMm, pass it mutably through map and release]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/driver.rs | 45 +++++++--
drivers/gpu/nova-core/gpu.rs | 32 ++++++-
drivers/gpu/nova-core/gsp/commands.rs | 1 -
drivers/gpu/nova-core/mm.rs | 1 +
drivers/gpu/nova-core/mm/bar_user.rs | 171 ++++++++++++++++++++++++++++++++++
5 files changed, 240 insertions(+), 10 deletions(-)
diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver.rs
index 5723ff8f71ea..0672a0707a71 100644
--- a/drivers/gpu/nova-core/driver.rs
+++ b/drivers/gpu/nova-core/driver.rs
@@ -2,7 +2,11 @@
use kernel::{
auxiliary,
- device::Core,
+ device::{
+ Bound,
+ Core, //
+ },
+ io::resource,
pci,
pci::{
Class,
@@ -28,6 +32,7 @@ pub(crate) struct NovaCore<'bound> {
#[pin]
pub(crate) gpu: Gpu<'bound>,
bar: pci::Bar<'bound, BAR0_SIZE>,
+ bar1: Bar1<'bound>,
#[allow(clippy::type_complexity)]
_reg: auxiliary::Registration<'bound, CovariantForLt!(())>,
}
@@ -38,9 +43,27 @@ pub(crate) struct NovaCore<'bound> {
pub(crate) type Bar0<'a> = &'a pci::Bar<'a, BAR0_SIZE>;
pub(crate) type NovaRegisters = kernel::io::Region<BAR0_SIZE>;
-#[expect(dead_code)]
pub(crate) type Bar1<'a> = pci::Bar<'a>;
+/// Returns the Linux PCI resource index that holds BAR1 for an NVIDIA GPU.
+///
+/// On Maxwell through Ada, BAR0 is a 32-bit memory BAR occupying a single
+/// Linux PCI resource slot, so BAR1 lives at index 1. Starting with Blackwell
+/// (and on some Ampere GA100 / Hopper SKUs) BAR0 is a 64-bit memory BAR that
+/// consumes two consecutive resource slots: index 0 holds the low 32 bits and
+/// index 1 holds the high 32 bits (with no `flags` / or size of its own),
+/// shifting BAR1 to index 2.
+pub(crate) fn bar1_resource_index(pdev: &pci::Device<Bound>) -> Result<u32> {
+ // Probe the `IORESOURCE_MEM_64` flag of BAR0 as a robust way of exposing
+ // if BAR0 and hence BAR1 is 64-bit.
+ let flags0 = pdev.resource_flags(0)?;
+ if flags0.contains(resource::Flags::IORESOURCE_MEM_64) {
+ Ok(2)
+ } else {
+ Ok(1)
+ }
+}
+
kernel::pci_device_table!(
PCI_TABLE,
<NovaCoreDriver as pci::Driver>::IdInfo,
@@ -82,12 +105,18 @@ fn probe<'bound>(
Ok(try_pin_init!(NovaCore {
bar: pdev.iomap_region_sized::<BAR0_SIZE>(0, c"nova-core/bar0")?,
- // TODO: Use `&bar` self-referential pin-init syntax once available.
- //
- // SAFETY: `bar` is initialized before this expression is evaluated
- // (`try_pin_init!()` initializes fields in declaration order), lives at a pinned
- // stable address, and is dropped after `gpu` (struct field drop order).
- gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) }),
+ bar1: {
+ let bar1_idx = bar1_resource_index(pdev)?;
+ pdev.iomap_region(bar1_idx, c"nova-core/bar1")?
+ },
+ // TODO: Use self-referential pin-init syntax once available.
+ gpu <- Gpu::new(
+ pdev,
+ // SAFETY: `bar` is initialized above, pinned, and outlives `gpu`.
+ unsafe { &*core::ptr::from_ref(bar) },
+ // SAFETY: `bar1` is initialized above, pinned, and outlives `gpu`.
+ unsafe { &*core::ptr::from_ref(bar1) },
+ ),
// Run optional GPU selftests.
#[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
_: { gpu.run_selftests(pdev) },
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index b797472279d3..f72a92e045e5 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -16,11 +16,15 @@
SizeConstants,
SZ_4K, //
},
+ sync::Arc,
};
use crate::{
bounded_enum,
- driver::Bar0,
+ driver::{
+ Bar0,
+ Bar1, //
+ },
falcon::{
gsp::Gsp as GspFalcon,
sec2::Sec2 as Sec2Falcon,
@@ -35,6 +39,8 @@
GspBootContext, //
},
mm::{
+ bar_user::BarUser,
+ pagetable::MmuVersion,
GpuMm,
VramAddress, //
},
@@ -148,6 +154,11 @@ pub(crate) const fn arch(self) -> Architecture {
pub(crate) fn pci_config_mirror_range(self) -> Range<u32> {
hal::gpu_hal(self).pci_config_mirror_range()
}
+
+ /// Returns the MMU version for this chipset.
+ pub(crate) fn mmu_version(self) -> MmuVersion {
+ MmuVersion::from(self.arch())
+ }
}
// TODO
@@ -297,6 +308,8 @@ pub(crate) struct Gpu<'gpu> {
/// Must be kept declared *before* `gsp_resources`, so that its components are dropped while
/// the GSP is still operational.
mm: GpuMm<'gpu>,
+ /// BAR1 user interface for CPU access to GPU virtual memory.
+ bar_user: Arc<BarUser<'gpu>>,
/// GSP and its resources.
#[pin]
gsp_resources: GspResources<'gpu>,
@@ -340,6 +353,7 @@ impl<'gpu> Gpu<'gpu> {
pub(crate) fn new<'a>(
pdev: &'gpu pci::Device<device::Core<'a>>,
bar: Bar0<'gpu>,
+ bar1: &'gpu Bar1<'gpu>,
) -> impl PinInit<Self, Error> + use<'gpu, 'a> {
let dev = pdev.as_ref();
@@ -442,6 +456,22 @@ pub(crate) fn new<'a>(
VramAddress::from_raw(gsp_static_info.total_fb_end),
)?
},
+
+ // Create BAR1 user interface for CPU access to GPU virtual memory.
+ bar_user: {
+ let pdb_addr = VramAddress::from_raw(gsp_static_info.bar1_pde_base);
+ let bar1_idx = crate::driver::bar1_resource_index(pdev)?;
+ let bar1_size = pdev.resource_len(bar1_idx)?;
+ Arc::pin_init(
+ BarUser::new(
+ pdb_addr,
+ gsp_resources.spec.chipset,
+ bar1_size,
+ bar1,
+ )?,
+ GFP_KERNEL,
+ )?
+ },
})
}
diff --git a/drivers/gpu/nova-core/gsp/commands.rs b/drivers/gpu/nova-core/gsp/commands.rs
index 1c467718c679..663e1d124781 100644
--- a/drivers/gpu/nova-core/gsp/commands.rs
+++ b/drivers/gpu/nova-core/gsp/commands.rs
@@ -215,7 +215,6 @@ fn init(&self) -> impl Init<Self::Command, Self::InitError> {
pub(crate) struct GetGspStaticInfoReply {
gpu_name: [u8; 64],
/// BAR1 Page Directory Entry base address.
- #[expect(dead_code)]
pub(crate) bar1_pde_base: u64,
/// Usable FB (VRAM) regions for driver memory allocation.
pub(crate) usable_fb_regions: KVec<Range<u64>>,
diff --git a/drivers/gpu/nova-core/mm.rs b/drivers/gpu/nova-core/mm.rs
index 2cf37254fbb9..e04497256519 100644
--- a/drivers/gpu/nova-core/mm.rs
+++ b/drivers/gpu/nova-core/mm.rs
@@ -60,6 +60,7 @@ macro_rules! impl_pfn_bounded {
pub(crate) use tlb::Tlb;
+pub(crate) mod bar_user;
mod hal;
pub(super) mod pagetable;
mod pramin;
diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
new file mode 100644
index 000000000000..ef1d8e6f8c9c
--- /dev/null
+++ b/drivers/gpu/nova-core/mm/bar_user.rs
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! BAR1 user interface for CPU access to GPU virtual memory. Used for USERD
+//! for GPU work submission, and applications to access GPU buffers via mmap().
+
+use kernel::{
+ io::Io,
+ new_mutex,
+ prelude::*,
+ sync::{
+ Arc,
+ Mutex, //
+ },
+};
+
+use crate::{
+ driver::Bar1,
+ gpu::Chipset,
+ mm::{
+ vmm::{
+ MappedRange,
+ Vmm, //
+ },
+ GpuMm,
+ Pfn,
+ Vfn,
+ VirtualAddress,
+ VramAddress,
+ PAGE_SIZE, //
+ },
+ num::IntoSafeCast,
+};
+
+/// BAR1 user interface for virtual memory mappings.
+///
+/// Owns the [`Vmm`] for the BAR1 address space.
+#[pin_data]
+pub(crate) struct BarUser<'gpu> {
+ #[pin]
+ vmm: Mutex<Vmm>,
+ bar1: &'gpu Bar1<'gpu>,
+}
+
+impl<'gpu> BarUser<'gpu> {
+ /// Create a pin-initializer for [`BarUser`].
+ pub(crate) fn new(
+ pdb_addr: VramAddress,
+ chipset: Chipset,
+ va_size: u64,
+ bar1: &'gpu Bar1<'gpu>,
+ ) -> Result<impl PinInit<Self> + 'gpu> {
+ let vmm = Vmm::new(pdb_addr, chipset.mmu_version(), va_size)?;
+ Ok(pin_init!(Self {
+ vmm <- new_mutex!(vmm, "bar_user_vmm"),
+ bar1,
+ }))
+ }
+
+ /// Map physical pages to a contiguous BAR1 virtual range.
+ pub(crate) fn map(
+ self: &Arc<Self>,
+ mm: &mut GpuMm<'_>,
+ pfns: &[Pfn],
+ writable: bool,
+ ) -> Result<BarUserAccess<'gpu>> {
+ if pfns.is_empty() {
+ return Err(EINVAL);
+ }
+ let mut vmm = self.vmm.lock();
+ let mapped = vmm.map_pages(mm, pfns, None, writable)?;
+
+ Ok(BarUserAccess {
+ bar_user: self.clone(),
+ mapped: Some(mapped),
+ })
+ }
+}
+
+/// Access object for a mapped BAR1 region.
+pub(crate) struct BarUserAccess<'gpu> {
+ bar_user: Arc<BarUser<'gpu>>,
+ /// [`BarUserAccess::release`] [`Option::take`]s this; `Some` at
+ /// drop time means `release()` was never called.
+ mapped: Option<MappedRange>,
+}
+
+impl BarUserAccess<'_> {
+ /// Tear down the BAR1 mapping.
+ pub(crate) fn release(mut self, mm: &mut GpuMm<'_>) -> Result {
+ let mapped = self.mapped.take().ok_or(EINVAL)?;
+ let mut vmm = self.bar_user.vmm.lock();
+ vmm.unmap_pages(mm, mapped)?;
+ Ok(())
+ }
+
+ /// Returns the active mapping.
+ fn mapped(&self) -> &MappedRange {
+ // `mapped` is only `None` after `take()` in `release`; hence unwrap()
+ // cannot panic here.
+ self.mapped.as_ref().unwrap()
+ }
+
+ /// Get the base virtual address of this mapping.
+ pub(crate) fn base(&self) -> VirtualAddress {
+ VirtualAddress::from(self.mapped().vfn_start)
+ }
+
+ /// Get the total size of the mapped region in bytes.
+ pub(crate) fn size(&self) -> usize {
+ self.mapped().num_pages * PAGE_SIZE
+ }
+
+ /// Get the starting virtual frame number.
+ pub(crate) fn vfn_start(&self) -> Vfn {
+ self.mapped().vfn_start
+ }
+
+ /// Get the number of pages in this mapping.
+ pub(crate) fn num_pages(&self) -> usize {
+ self.mapped().num_pages
+ }
+
+ /// Translate an offset within this mapping to a BAR1 aperture offset.
+ fn bar_offset(&self, offset: usize) -> Result<usize> {
+ if offset >= self.size() {
+ return Err(EINVAL);
+ }
+
+ let base_vfn: usize = self.mapped().vfn_start.raw().into_safe_cast();
+ let base = base_vfn.checked_mul(PAGE_SIZE).ok_or(EOVERFLOW)?;
+ base.checked_add(offset).ok_or(EOVERFLOW)
+ }
+
+ // Fallible accessors with runtime bounds checking.
+
+ /// Read a 32-bit value at the given offset.
+ pub(crate) fn try_read32(&self, offset: usize) -> Result<u32> {
+ let off = self.bar_offset(offset)?;
+ self.bar_user.bar1.try_read32(off)
+ }
+
+ /// Write a 32-bit value at the given offset.
+ pub(crate) fn try_write32(&self, value: u32, offset: usize) -> Result {
+ let off = self.bar_offset(offset)?;
+ self.bar_user.bar1.try_write32(value, off)
+ }
+
+ /// Read a 64-bit value at the given offset.
+ pub(crate) fn try_read64(&self, offset: usize) -> Result<u64> {
+ let off = self.bar_offset(offset)?;
+ self.bar_user.bar1.try_read64(off)
+ }
+
+ /// Write a 64-bit value at the given offset.
+ pub(crate) fn try_write64(&self, value: u64, offset: usize) -> Result {
+ let off = self.bar_offset(offset)?;
+ self.bar_user.bar1.try_write64(value, off)
+ }
+}
+
+impl Drop for BarUserAccess<'_> {
+ fn drop(&mut self) {
+ if self.mapped.is_some() {
+ kernel::pr_warn!(
+ "BarUserAccess dropped without calling release(). BarUser address space will leak.\n"
+ );
+ }
+ // The inner `MappedRange`'s own `MustUnmapGuard` will also fire,
+ // identifying the leaked VA range.
+ }
+}
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* [PATCH 16/16] gpu: nova-core: mm: Add BAR1 memory management self-tests
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (14 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface Eliot Courtney
@ 2026-09-09 3:59 ` Eliot Courtney
2026-09-09 4:18 ` sashiko-bot
2026-09-09 21:11 ` [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Danilo Krummrich
16 siblings, 1 reply; 34+ messages in thread
From: Eliot Courtney @ 2026-09-09 3:59 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: Alice Ryhl, John Hubbard, Alistair Popple, Timur Tabi, nova-gpu,
dri-devel, linux-kernel, Eliot Courtney, Joel Fernandes
From: Joel Fernandes <joelagnelf@nvidia.com>
Add self-tests for BAR1 access during driver probe when
CONFIG_NOVA_CORE_SELFTESTS is enabled (default disabled). This results in
testing the Vmm, GPU buddy allocator and BAR1 region all of which should
function correctly for the tests to pass.
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[ecourtney: use existing self-test runner and CONFIG_NOVA_CORE_SELFTESTS]
[ecourtney: update for mutable GpuMm, PRAMIN views and VramAddress raw API]
[ecourtney: restore the conditional dead_code expect]
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
---
drivers/gpu/nova-core/gpu.rs | 9 +-
drivers/gpu/nova-core/mm.rs | 12 +-
drivers/gpu/nova-core/mm/bar_user.rs | 251 ++++++++++++++++++++++++++++++++++
drivers/gpu/nova-core/mm/pagetable.rs | 24 ++++
drivers/gpu/nova-core/mm/vmm.rs | 1 +
5 files changed, 293 insertions(+), 4 deletions(-)
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index f72a92e045e5..f5bdfdea803a 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -482,7 +482,14 @@ pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device<device::Bou
let dev = pdev.as_ref();
let regions = &this.gsp_static_info.usable_fb_regions;
- if let Err(err) = crate::mm::selftest::run(dev, this.mm, regions) {
+ if let Err(err) = crate::mm::selftest::run(
+ dev,
+ this.mm,
+ regions,
+ this.bar_user,
+ this.gsp_static_info.bar1_pde_base,
+ this.spec.chipset,
+ ) {
dev_err!(dev, "self-tests failed: {:?}\n", err);
}
}
diff --git a/drivers/gpu/nova-core/mm.rs b/drivers/gpu/nova-core/mm.rs
index e04497256519..a5bc4042577b 100644
--- a/drivers/gpu/nova-core/mm.rs
+++ b/drivers/gpu/nova-core/mm.rs
@@ -3,7 +3,7 @@
//! Memory management subsystems.
-#![expect(dead_code)]
+#![cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))]
/// Implements `From` conversions between a frame-number type and `Bounded<u64, N>`.
///
@@ -202,6 +202,7 @@ pub(crate) struct VirtualAddress(u64) {
impl VirtualAddress {
/// Create a new virtual address from a raw value.
+ #[expect(dead_code)]
pub(crate) const fn new(addr: u64) -> Self {
Self::from_raw(addr)
}
@@ -297,7 +298,8 @@ pub(crate) mod selftest {
use kernel::{
device,
- sizes::SizeConstants, //
+ sizes::SizeConstants,
+ sync::Arc, //
};
use super::*;
@@ -307,6 +309,9 @@ pub(crate) fn run(
dev: &device::Device<device::Bound>,
mm: &mut GpuMm<'_>,
usable_fb_regions: &[Range<u64>],
+ bar_user: &Arc<bar_user::BarUser<'_>>,
+ bar1_pdb: u64,
+ chipset: Chipset,
) -> Result {
// VRAM span the self-tests are free to overwrite, from the chosen test base.
const SELFTEST_SPAN: u64 = u64::SZ_64M;
@@ -325,6 +330,7 @@ pub(crate) fn run(
return Ok(());
};
- pramin::selftest::run(dev, mm.pramin_mut(), VramAddress::from_raw(base))
+ pramin::selftest::run(dev, mm.pramin_mut(), VramAddress::from_raw(base))?;
+ bar_user::run_self_test(dev, mm, bar_user, bar1_pdb, chipset)
}
}
diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
index ef1d8e6f8c9c..1bef01d147ad 100644
--- a/drivers/gpu/nova-core/mm/bar_user.rs
+++ b/drivers/gpu/nova-core/mm/bar_user.rs
@@ -31,6 +31,9 @@
num::IntoSafeCast,
};
+#[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
+use kernel::device;
+
/// BAR1 user interface for virtual memory mappings.
///
/// Owns the [`Vmm`] for the BAR1 address space.
@@ -84,6 +87,7 @@ pub(crate) struct BarUserAccess<'gpu> {
mapped: Option<MappedRange>,
}
+#[expect(dead_code)]
impl BarUserAccess<'_> {
/// Tear down the BAR1 mapping.
pub(crate) fn release(mut self, mm: &mut GpuMm<'_>) -> Result {
@@ -169,3 +173,250 @@ fn drop(&mut self) {
// identifying the leaked VA range.
}
}
+
+/// Run MM subsystem self-tests during probe.
+///
+/// Tests page table infrastructure and `BAR1` MMIO access using the `BAR1`
+/// address space. Uses the `GpuMm`'s buddy allocator to allocate page tables
+/// and test pages as needed.
+#[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
+pub(crate) fn run_self_test(
+ dev: &device::Device<device::Bound>,
+ mm: &mut GpuMm<'_>,
+ bar_user: &Arc<BarUser<'_>>,
+ bar1_pdb: u64,
+ chipset: Chipset,
+) -> Result {
+ use kernel::gpu::buddy::{
+ GpuBuddyAllocFlags,
+ GpuBuddyAllocMode, //
+ };
+ use kernel::ptr::Alignment;
+ use kernel::sizes::{
+ SZ_16K,
+ SZ_32K,
+ SZ_4K,
+ SZ_64K, //
+ };
+
+ // Test patterns.
+ const PATTERN_PRAMIN: u32 = 0xDEAD_BEEF;
+ const PATTERN_BAR1: u32 = 0xCAFE_BABE;
+
+ let bar1 = bar_user.bar1;
+ dev_info!(dev, "MM: Starting self-test...\n");
+
+ 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() {
+ dev_info!(dev, "MM: Self-test SKIPPED - no valid VRAM page tables\n");
+ return Ok(());
+ }
+
+ // Set up a test page from the buddy allocator.
+ let test_page_blocks = KBox::pin_init(
+ mm.buddy().alloc_blocks(
+ GpuBuddyAllocMode::Simple,
+ SZ_4K.into_safe_cast(),
+ Alignment::new::<SZ_4K>(),
+ GpuBuddyAllocFlags::default(),
+ ),
+ GFP_KERNEL,
+ )?;
+ let test_vram_offset = test_page_blocks.iter().next().ok_or(ENOMEM)?.offset();
+ let test_vram = VramAddress::from_raw(test_vram_offset);
+ let test_pfn = Pfn::from(test_vram);
+
+ // Create a VMM of size 64K to track virtual memory mappings.
+ let mut vmm = Vmm::new(pdb_addr, chipset.mmu_version(), SZ_64K.into_safe_cast())?;
+
+ // Create a test mapping.
+ let mapped = vmm.map_pages(mm, &[test_pfn], None, true)?;
+ let test_vfn = mapped.vfn_start;
+
+ // Pre-compute test addresses for the PRAMIN to BAR1 read test.
+ let vfn_offset: usize = test_vfn.raw().into_safe_cast();
+ let bar1_base_offset = vfn_offset.checked_mul(PAGE_SIZE).ok_or(EOVERFLOW)?;
+ let bar1_read_offset: usize = bar1_base_offset + 0x100;
+ 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);
+
+ // Read back via BAR1 aperture.
+ let bar1_value = bar1.try_read32(bar1_read_offset)?;
+
+ let test1_passed = if bar1_value == PATTERN_PRAMIN {
+ true
+ } else {
+ dev_err!(
+ dev,
+ "MM: Test 1 FAILED - Expected {:#010x}, got {:#010x}\n",
+ PATTERN_PRAMIN,
+ bar1_value
+ );
+ false
+ };
+
+ // Cleanup - invalidate PTE.
+ vmm.unmap_pages(mm, mapped)?;
+
+ // Test 2: Two-phase prepare/execute API.
+ let prepared = vmm.prepare_map(mm, 1, None)?;
+ let mapped2 = vmm.execute_map(mm, prepared, &[test_pfn], true)?;
+ let readback = vmm.read_mapping(mm, mapped2.vfn_start)?;
+ let test2_passed = if readback == Some(test_pfn) {
+ true
+ } else {
+ dev_err!(dev, "MM: Test 2 FAILED - Two-phase map readback mismatch\n");
+ false
+ };
+ vmm.unmap_pages(mm, mapped2)?;
+
+ // Test 3: Range-constrained allocation with a hole — exercises block.size()-driven
+ // BAR1 mapping. A 4K hole is punched at base+16K, then a single 32K allocation
+ // is requested within [base, base+36K). The buddy allocator must split around the
+ // hole, returning multiple blocks (expected: {16K, 4K, 8K, 4K} = 32K total).
+ // Each block is mapped into BAR1 and verified via PRAMIN read-back.
+ //
+ // Address layout (base = 0x10000):
+ // [ 16K ] [HOLE 4K] [4K] [ 8K ] [4K]
+ // 0x10000 0x14000 0x15000 0x16000 0x18000 0x19000
+ let range_base: u64 = SZ_64K.into_safe_cast();
+ let sz_4k: u64 = SZ_4K.into_safe_cast();
+ let sz_16k: u64 = SZ_16K.into_safe_cast();
+ let sz_32k_4k: u64 = (SZ_32K + SZ_4K).into_safe_cast();
+
+ // Punch a 4K hole at base+16K so the subsequent 32K allocation must split.
+ let _hole = KBox::pin_init(
+ mm.buddy().alloc_blocks(
+ GpuBuddyAllocMode::Range(range_base + sz_16k..range_base + sz_16k + sz_4k),
+ SZ_4K.into_safe_cast(),
+ Alignment::new::<SZ_4K>(),
+ GpuBuddyAllocFlags::default(),
+ ),
+ GFP_KERNEL,
+ )?;
+
+ // Allocate 32K within [base, base+36K). The hole forces the allocator to return
+ // split blocks whose sizes are determined by buddy alignment.
+ let blocks = KBox::pin_init(
+ mm.buddy().alloc_blocks(
+ GpuBuddyAllocMode::Range(range_base..range_base + sz_32k_4k),
+ SZ_32K.into_safe_cast(),
+ Alignment::new::<SZ_4K>(),
+ GpuBuddyAllocFlags::default(),
+ ),
+ GFP_KERNEL,
+ )?;
+
+ let mut test3_passed = true;
+ let mut total_size = 0usize;
+
+ for block in blocks.iter() {
+ total_size += IntoSafeCast::<usize>::into_safe_cast(block.size());
+
+ // Map all pages of this block.
+ let page_size: u64 = PAGE_SIZE.into_safe_cast();
+ let num_pages: usize = (block.size() / page_size).into_safe_cast();
+
+ let mut pfns = KVec::new();
+ for j in 0..num_pages {
+ let j_u64: u64 = j.into_safe_cast();
+ pfns.push(
+ Pfn::from(VramAddress::from_raw(
+ block.offset() + j_u64.checked_mul(page_size).ok_or(EOVERFLOW)?,
+ )),
+ GFP_KERNEL,
+ )?;
+ }
+
+ let mapped = vmm.map_pages(mm, &pfns, None, true)?;
+ let bar1_base_vfn: usize = mapped.vfn_start.raw().into_safe_cast();
+ let bar1_base = bar1_base_vfn.checked_mul(PAGE_SIZE).ok_or(EOVERFLOW)?;
+
+ for j in 0..num_pages {
+ let page_bar1_off = bar1_base + j * PAGE_SIZE;
+ let j_u64: u64 = j.into_safe_cast();
+ let page_phys = block.offset()
+ + j_u64
+ .checked_mul(PAGE_SIZE.into_safe_cast())
+ .ok_or(EOVERFLOW)?;
+
+ 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();
+
+ if pramin_val != PATTERN_BAR1 {
+ dev_err!(
+ dev,
+ "MM: Test 3 FAILED block offset {:#x} page {} (val={:#x})\n",
+ block.offset(),
+ j,
+ pramin_val
+ );
+ test3_passed = false;
+ }
+ }
+
+ vmm.unmap_pages(mm, mapped)?;
+ }
+
+ // Verify aggregate: all returned block sizes must sum to allocation size.
+ if total_size != SZ_32K {
+ dev_err!(
+ dev,
+ "MM: Test 3 FAILED - total size {} != expected {}\n",
+ total_size,
+ SZ_32K
+ );
+ test3_passed = false;
+ }
+
+ // Release Tests 1-3's Vmm before Test 4 constructs a fresh BarUser on
+ // the same PDB.
+ drop(vmm);
+
+ // Test 4: Exercise `BarUser::map()` end-to-end.
+ let bar_user = Arc::pin_init(
+ BarUser::new(pdb_addr, chipset, SZ_64K.into_safe_cast(), bar1)?,
+ GFP_KERNEL,
+ )?;
+ 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);
+
+ let readback = access.try_read32(0)?;
+ let test4_passed = if readback == PATTERN_BAR1 {
+ true
+ } else {
+ dev_err!(
+ dev,
+ "MM: Test 4 FAILED - Expected {:#010x}, got {:#010x}\n",
+ PATTERN_BAR1,
+ readback
+ );
+ false
+ };
+ access.release(mm)?;
+
+ if test1_passed && test2_passed && test3_passed && test4_passed {
+ dev_info!(dev, "MM: All self-tests PASSED\n");
+ Ok(())
+ } else {
+ dev_err!(dev, "MM: Self-tests FAILED\n");
+ Err(EIO)
+ }
+}
diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
index ffc69fbdb067..de2f8ea5aeef 100644
--- a/drivers/gpu/nova-core/mm/pagetable.rs
+++ b/drivers/gpu/nova-core/mm/pagetable.rs
@@ -396,3 +396,27 @@ fn from(val: AperturePde) -> Self {
Bounded::from_expr(val as u64 & 0x3)
}
}
+
+/// Check if the PDB has valid, VRAM-backed page tables.
+#[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
+fn check_pdb_inner<M: MmuConfig>(pramin: &mut pramin::Pramin<'_>, pdb_addr: VramAddress) -> Result {
+ let raw = pramin.window_at::<u64>(pdb_addr)?.view().read_val();
+
+ if !M::Pde::from_raw(raw).is_valid_vram() {
+ return Err(ENOENT);
+ }
+ Ok(())
+}
+
+/// Check if the PDB has valid, VRAM-backed page tables, dispatching by MMU version.
+#[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
+pub(super) fn check_pdb_valid(
+ pramin: &mut pramin::Pramin<'_>,
+ pdb_addr: VramAddress,
+ chipset: crate::gpu::Chipset,
+) -> Result {
+ match MmuVersion::from(chipset.arch()) {
+ MmuVersion::V2 => check_pdb_inner::<MmuV2>(pramin, pdb_addr),
+ MmuVersion::V3 => check_pdb_inner::<MmuV3>(pramin, pdb_addr),
+ }
+}
diff --git a/drivers/gpu/nova-core/mm/vmm.rs b/drivers/gpu/nova-core/mm/vmm.rs
index 411710d03f7a..51b500a27233 100644
--- a/drivers/gpu/nova-core/mm/vmm.rs
+++ b/drivers/gpu/nova-core/mm/vmm.rs
@@ -126,6 +126,7 @@ fn drop(&mut self) {
/// Directory Base (`PDB`) address. Used for Channel, BAR1 and BAR2 mappings.
pub(crate) struct Vmm {
/// Page Directory Base address for this address space.
+ #[expect(dead_code)]
pdb_addr: VramAddress,
/// Page table walker for reading existing mappings.
pt_walk: PtWalk,
--
2.55.0
^ permalink raw reply related [flat|nested] 34+ messages in thread
* Re: [PATCH 10/16] gpu: nova-core: mm: Add page table walker for MMU v2/v3
2026-09-09 3:59 ` [PATCH 10/16] gpu: nova-core: mm: Add page table walker for MMU v2/v3 Eliot Courtney
@ 2026-09-09 4:07 ` sashiko-bot
0 siblings, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:07 UTC (permalink / raw)
To: Eliot Courtney; +Cc: Danilo Krummrich, Alexandre Courbot, dri-devel
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] The page table walker treats valid system-memory PDEs as missing, which can lead to silent lookup failures or page table corruption if overwritten.
- [High] The page table walker silently truncates system-memory Dual PDEs, bypassing the VRAM location check and causing it to read from an invalid physical address.
- [Medium] The page table walker unconditionally traverses only the small page table in Dual PDEs, ignoring big page mappings and incorrectly reporting them as missing or unmapped.
--
commit 8ab80bbde0121304a601722ca26dc100aca36061
Author: Joel Fernandes <joelagnelf@nvidia.com>
gpu: nova-core: mm: Add page table walker for MMU v2/v3
This commit adds the page table walker implementation that traverses the
page table hierarchy for both MMU v2 (5-level) and MMU v3 (6-level) to
resolve virtual addresses to physical addresses or find PTE locations.
> diff --git a/drivers/gpu/nova-core/mm/pagetable/walk.rs b/drivers/gpu/nova-core/mm/pagetable/walk.rs
> new file mode 100644
> index 0000000000000..76c1729971f53
> --- /dev/null
> +++ b/drivers/gpu/nova-core/mm/pagetable/walk.rs
[ ... ]
> + pub(super) fn walk_pde_levels(
> + &self,
> + pramin: &mut pramin::Pramin<'_>,
> + vfn: Vfn,
> + resolve_prepared: impl Fn(VramAddress) -> Option<VramAddress>,
> + ) -> Result<WalkPdeResult> {
> + let va = VirtualAddress::from(vfn);
> + let mut cur_table = self.pdb_addr;
> +
> + for &level in M::PDE_LEVELS {
> + let idx = M::level_index(va, level.as_index());
> + let install_addr = Self::entry_addr(cur_table, level, idx);
> +
> + if level == M::DUAL_PDE_LEVEL {
> + // 128-bit dual PDE with big+small page table pointers.
> + let dpde = M::DualPde::read(pramin, install_addr)?;
> + if dpde.has_small() {
[Severity: Medium]
Are big page mappings intentionally ignored here? The walker unconditionally
traverses only the small page table in Dual PDEs.
If a virtual address is mapped via a big page, this would either fall
through to WalkPdeResult::Missing (if has_small() is false) or incorrectly
search the small page table and fail, resulting in lookup failures instead
of returning an explicit error or resolving the mapping.
> + cur_table = dpde.small_vram_address();
[Severity: High]
Does this silently truncate system-memory Dual PDEs?
Unlike the regular PDE path which explicitly checks pde.is_valid_vram() to
prevent truncating the wider system-memory frame number, this Dual PDE path
unconditionally calls dpde.small_vram_address(). If a Dual PDE points to a
small page table in system memory, this could read from an invalid physical
VRAM address, leading to data corruption or a GPU fault.
> + continue;
> + }
> + } else {
> + // Regular 64-bit PDE. Use `is_valid_vram()` because
> + // `table_vram_address()` only reads the VRAM frame-number
> + // bitfield; system-memory PDEs store the address in a
> + // different (wider) field and would be silently truncated.
> + let pde = M::Pde::read(pramin, install_addr)?;
> + if pde.is_valid_vram() {
> + cur_table = pde.table_vram_address();
> + continue;
> + }
> + }
> +
> + // PDE missing in HW. Ask caller for resolution.
> + if let Some(prepared_addr) = resolve_prepared(install_addr) {
[Severity: High]
Could this lead to overwriting valid system-memory PDEs?
When walk_pde_levels() encounters a regular PDE that points to system
memory, pde.is_valid_vram() will return false. The logic then falls through
to this "PDE missing" block.
If the walker is used to allocate or install a missing PDE, it could
instruct the caller to overwrite the valid system-memory PDE with a new VRAM
PDE, causing a memory leak of the old page table and loss of its mappings.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=10
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 04/16] gpu: nova-core: mm: pagetable: Add PteOps trait
2026-09-09 3:59 ` [PATCH 04/16] gpu: nova-core: mm: pagetable: Add PteOps trait Eliot Courtney
@ 2026-09-09 4:07 ` sashiko-bot
0 siblings, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:07 UTC (permalink / raw)
To: Eliot Courtney; +Cc: dri-devel, Alexandre Courbot, Danilo Krummrich
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Vertical imports in the `crate::mm` block are not alphabetically sorted.
--
commit ee1cdc1cc3fda4aebff8e2ad80ace37f03baef14
Author: Joel Fernandes <joelagnelf@nvidia.com>
gpu: nova-core: mm: pagetable: Add PteOps trait
This introduces a trait for GPU Page Table Entries. New read and write
helpers are provided that go through a Pramin, allowing the later
page-table walker and mapper to call PTE operations.
> diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
> --- a/drivers/gpu/nova-core/mm/pagetable.rs
> +++ b/drivers/gpu/nova-core/mm/pagetable.rs
> @@ -8,9 +8,18 @@
>
> #![expect(dead_code)]
>
> -use kernel::num::Bounded;
> +use kernel::{
> + io::Io,
> + num::Bounded,
> + prelude::*, //
> +};
>
> use crate::gpu::Architecture;
> +use crate::mm::{
> + pramin,
> + Pfn,
> + VramAddress, //
> +};
[Severity: Low]
This isn't a bug, but it looks like the vertical imports in the crate::mm
block are not alphabetically sorted. Should Pfn precede pramin to comply
with the Rust kernel coding guidelines for import formatting?
[ ... ]
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=4
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 05/16] gpu: nova-core: mm: pagetable: Add PdeOps trait
2026-09-09 3:59 ` [PATCH 05/16] gpu: nova-core: mm: pagetable: Add PdeOps trait Eliot Courtney
@ 2026-09-09 4:08 ` sashiko-bot
0 siblings, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:08 UTC (permalink / raw)
To: Eliot Courtney; +Cc: Danilo Krummrich, dri-devel, Alexandre Courbot
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] The `PdeOps` trait only provides a `table_vram_address()` getter instead of a generic `table_pfn()`, causing a semantic mismatch and data corruption for system memory PDEs.
--
commit 43d16f339a2596bedc1626661f8f6564c220f1cb
Author: Joel Fernandes <joelagnelf@nvidia.com>
gpu: nova-core: mm: pagetable: Add PdeOps trait
Introduce a trait for GPU Page Directory Entries (PDEs). Default
`read()`/`write()` helpers via a `Pramin` are provided. The forthcoming MMU
v2, v3 PDE structs will each implement `PdeOps`, allowing the later page-table
walker and mapper to call PDE operations.
> diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
> index a23370b4b62d1..14436fa6adf04 100644
> --- a/drivers/gpu/nova-core/mm/pagetable.rs
> +++ b/drivers/gpu/nova-core/mm/pagetable.rs
> @@ -128,6 +128,47 @@ fn write(&self, pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result {
> }
> }
>
> +/// Operations on Page Directory Entries (`PDE`s).
> +pub(super) trait PdeOps: Copy + core::fmt::Debug + Into<u64> {
[ ... ]
> + /// Get the memory aperture of this `PDE`.
> + fn aperture(&self) -> AperturePde;
> +
> + /// Get the VRAM address of the page table.
> + fn table_vram_address(&self) -> VramAddress;
[Severity: High]
Does this trait need a generic table_pfn() method instead of forcing VRAM
addresses?
When a PDE points to system memory (AperturePde::SystemCoherent), forcing the
implementation to return a VRAM address causes issues. For instance, in
PtWalkInner::walk_pde_levels(), the page table walker calls
dpde.small_vram_address() (which delegates to PdeOps::table_vram_address)
after only checking if the PDE has a small page table:
drivers/gpu/nova-core/mm/pagetable/walk.rs:PtWalkInner::walk_pde_levels() {
...
if dpde.has_small() {
cur_table = dpde.small_vram_address();
continue;
}
...
}
Because system memory PFNs are often stored in different bitfields than VRAM
PFNs, returning a VRAM address for a system memory PDE can result in
returning a corrupted frame number or panicking in debug builds, which
would cause the walker to perform an out-of-bounds VRAM read via pramin.
> +
> + /// Read a `PDE` from VRAM.
> + fn read(pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result<Self> {
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=5
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 02/16] gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm
2026-09-09 3:59 ` [PATCH 02/16] gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm Eliot Courtney
@ 2026-09-09 4:09 ` sashiko-bot
0 siblings, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:09 UTC (permalink / raw)
To: Eliot Courtney; +Cc: Danilo Krummrich, Alexandre Courbot, dri-devel
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Tlb::flush unconditionally uses TlbAckMode::None, which fails to wait for global TLB invalidation and creates a use-after-free risk during unmaps.
--
commit d4de9556e03b0600a4f0e5f45fee95f566102c9d
Author: Joel Fernandes <joelagnelf@nvidia.com>
gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm
Extend GpuMm with the buddy allocator for VRAM allocation and the TLB
manager for translation buffer operations. This completes the centralized
ownership model for memory management components.
> diff --git a/drivers/gpu/nova-core/mm/tlb.rs b/drivers/gpu/nova-core/mm/tlb.rs
> new file mode 100644
> index 0000000000000..cc862e8159a19
> --- /dev/null
> +++ b/drivers/gpu/nova-core/mm/tlb.rs
[ ... ]
> + /// Flush the GPU TLB for a specific page directory base.
> + ///
> + /// This invalidates all TLB entries associated with the given PDB address.
> + /// Must be called after modifying page table entries to ensure the GPU sees
> + /// the updated mappings.
> + pub(super) fn flush(&self, pdb_addr: VramAddress) -> Result {
> + let _guard = self.lock.lock();
> +
> + // Write PDB address.
> + self.bar.write_reg(regs::NV_TLB_FLUSH_PDB_LO::from_pdb_addr(
> + pdb_addr.into_raw(),
> + ));
> + self.bar.write_reg(regs::NV_TLB_FLUSH_PDB_HI::from_pdb_addr(
> + pdb_addr.into_raw(),
> + ));
> +
> + // Trigger flush.
> + self.bar.write_reg(
> + regs::NV_TLB_FLUSH_CTRL::zeroed()
> + .with_all_va(true)
> + .with_ack(TlbAckMode::None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
[Severity: High]
Does hardcoding the fire-and-forget acknowledgment mode here create a
use-after-free risk?
Since TLB flushes are used during unmap operations, a fire-and-forget mode
fails to wait for global TLB invalidation. The GPU might retain and use stale
TLB entries to access freed physical memory before the invalidation fully
propagates.
The documentation for TlbAckMode::Globally notes that it is strictly
required during unmap or permission tightening to prevent this exact issue.
Should Tlb::flush accept the acknowledgment mode as a parameter, or use
TlbAckMode::Globally by default?
> + .with_trigger(true),
> + );
> +
> + // Poll for completion.
> + read_poll_timeout(
> + || Ok(self.bar.read(regs::NV_TLB_FLUSH_CTRL)),
> + |ctrl: ®s::NV_TLB_FLUSH_CTRL| !ctrl.trigger(),
> + Delta::ZERO,
> + Delta::from_secs(2),
> + )?;
> +
> + Ok(())
> + }
> +}
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=2
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 09/16] gpu: nova-core: mm: pagetable: Add MmuConfig trait
2026-09-09 3:59 ` [PATCH 09/16] gpu: nova-core: mm: pagetable: Add MmuConfig trait Eliot Courtney
@ 2026-09-09 4:12 ` sashiko-bot
0 siblings, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:12 UTC (permalink / raw)
To: Eliot Courtney; +Cc: Danilo Krummrich, Alexandre Courbot, dri-devel
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Critical] pt_pages_upper_bound incorrectly computes the best-case page table capacity, leading to GPU Use-After-Free via under-allocation.
--
commit 48288e6179a4c23329aba38095ea6a337c240c2a
Author: Joel Fernandes <joelagnelf@nvidia.com>
gpu: nova-core: mm: pagetable: Add MmuConfig trait
This commit introduces the MmuConfig trait to tie entry-operation
traits together with version-specific constants and helpers. It provides
zero-sized marker structs for MMU v2 and v3 to fully resolve dispatch
at compile time without runtime overhead.
> diff --git a/drivers/gpu/nova-core/mm/pagetable.rs b/drivers/gpu/nova-core/mm/pagetable.rs
> index 128bfc0d277a8..d88499ed3d563 100644
> --- a/drivers/gpu/nova-core/mm/pagetable.rs
> +++ b/drivers/gpu/nova-core/mm/pagetable.rs
[ ... ]
> @@ -213,6 +214,114 @@ fn write(&self, pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result {
[ ... ]
> + /// Compute upper bound on page table pages needed for `num_virt_pages`.
> + ///
> + /// Walks from PTE level up through PDE levels, accumulating the tree.
> + fn pt_pages_upper_bound(num_virt_pages: usize) -> usize {
> + let mut total = 0;
> +
> + // PTE pages at the leaf level.
> + let pte_epp = Self::entries_per_page(Self::PTE_LEVEL);
> + let mut pages_at_level = num_virt_pages.div_ceil(pte_epp);
> + total += pages_at_level;
> +
> + // Walk PDE levels bottom-up (reverse of PDE_LEVELS).
> + for &level in Self::PDE_LEVELS.iter().rev() {
> + let epp = Self::entries_per_page(level);
> +
> + // How many pages at this level do we need to point to
> + // the previous pages_at_level?
> + pages_at_level = pages_at_level.div_ceil(epp);
[Severity: Critical]
Does this calculation account for unaligned virtual memory mappings?
If a userspace application requests an unaligned virtual memory mapping
(e.g., via a BAR1 mapping or DRM VM bind that crosses a 512-page PTE
boundary), computing capacity using div_ceil on num_virt_pages and
pages_at_level assumes perfect alignment. This propagates the flawed
alignment assumption to all higher directory levels, systematically
underestimating the maximum pages required.
If the capacity is underestimated, when install_mappings allocates PDEs
and pushes the newly allocated pages into page_table_allocs,
push_within_capacity can fail with ENOMEM. Since this happens after
the hardware PDE has already been written, the function bails out and
AllocatedBlocks is dropped. This frees the VRAM while the GPU MMU still
points to it, which could lead to a use-after-free of GPU VRAM.
> + total += pages_at_level;
> + }
> +
> + total
> + }
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=9
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 07/16] gpu: nova-core: mm: Add MMU v2 page table types
2026-09-09 3:59 ` [PATCH 07/16] gpu: nova-core: mm: Add MMU v2 page table types Eliot Courtney
@ 2026-09-09 4:12 ` sashiko-bot
2026-09-09 18:43 ` Danilo Krummrich
1 sibling, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:12 UTC (permalink / raw)
To: Eliot Courtney; +Cc: Alexandre Courbot, dri-devel, Danilo Krummrich
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] PdeOps::invalid in MMU v2 creates a valid large page PTE instead of an invalid PDE.
- [Medium] Commit message claims MMU v2 is for Hopper, contradicting the code implementation.
--
commit 123f278dccc75525e59331c1fb9bc862c6096243
Author: Joel Fernandes <joelagnelf@nvidia.com>
gpu: nova-core: mm: Add MMU v2 page table types
Add page table entry and directory structures for MMU version 2. The Pte,
Pde, and DualPde types each implement traits for the version-agnostic API
used by the forthcoming page-table walker and mapper.
> Add page table entry and directory structures for MMU version 2 used by
> Hopper and later GPUs.
[Severity: Medium]
Does the commit message have a typo regarding the supported architectures?
The commit message states MMU version 2 is used by Hopper and later GPUs,
but the module documentation in drivers/gpu/nova-core/mm/pagetable/ver2.rs
specifies it is for Turing, Ampere, and Ada GPUs. Hopper uses MMU v3.
> diff --git a/drivers/gpu/nova-core/mm/pagetable/ver2.rs b/drivers/gpu/nova-core/mm/pagetable/ver2.rs
> new file mode 100644
> index 0000000000000..089e5cc2bfc30
> --- /dev/null
> +++ b/drivers/gpu/nova-core/mm/pagetable/ver2.rs
[ ... ]
> +impl PdeOps for Pde {
> + fn from_raw(val: u64) -> Self {
> + Self::from_raw(val)
> + }
[ ... ]
> + fn invalid() -> Self {
> + Self::zeroed()
> + .with_valid_inverted(true)
> + .with_aperture(AperturePde::Invalid)
> + }
[Severity: High]
Does PdeOps::invalid() in MMU v2 create a valid large page PTE in hardware
instead of an invalid PDE?
By setting valid_inverted to true (bit 0 = 1), this constructs a raw value
where bit 0 is set. In NVIDIA MMU hardware, bit 0 at the PDE level acts as
the IS_PTE bit (0 = PDE, 1 = large page PTE).
The hardware will interpret this as a valid large page mapped to VRAM
physical address 0. If this is accessed, could it cause severe memory
corruption?
While currently unreachable by untrusted input because install_mappings()
only uses AperturePde::VideoMemory, this breaks the page table abstraction
for any future code that uses invalid() to clear a PDE slot.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=7
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 14/16] gpu: nova-core: Add BAR1 aperture type and size constant
2026-09-09 3:59 ` [PATCH 14/16] gpu: nova-core: Add BAR1 aperture type and size constant Eliot Courtney
@ 2026-09-09 4:14 ` sashiko-bot
0 siblings, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:14 UTC (permalink / raw)
To: Eliot Courtney; +Cc: Danilo Krummrich, Alexandre Courbot, dri-devel
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Mismatch between commit message and code: missing BAR1_SIZE constant.
--
commit db55f37382f142c32f879637ebd2448ef45bd83e
Author: Joel Fernandes <joelagnelf@nvidia.com>
gpu: nova-core: Add BAR1 aperture type and size constant
This commit adds the Bar1 type alias and related GSP structures for BAR1
memory access functionality. It also adds parsing for the BAR1 PDE base
address.
> gpu: nova-core: Add BAR1 aperture type and size constant
>
> Add BAR1_SIZE constant and Bar1 type alias for the 256MB BAR1 aperture.
[Severity: Medium]
Is the BAR1_SIZE constant missing from this patch?
The commit message explicitly states that a BAR1_SIZE constant is added,
but it appears to be entirely missing from the changes.
Note that this omission does not cause runtime bounds checks to fail, as
pci::Bar gracefully falls back to dynamic runtime bounds checks against the
actual PCI resource length. However, there is a mismatch between the intended
change described in the commit message and the actual code.
> diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver.rs
> index 8cef4c284277f..5723ff8f71ea4 100644
> --- a/drivers/gpu/nova-core/driver.rs
> +++ b/drivers/gpu/nova-core/driver.rs
> @@ -38,6 +38,8 @@ pub(crate) struct NovaCore<'bound> {
>
> pub(crate) type Bar0<'a> = &'a pci::Bar<'a, BAR0_SIZE>;
> pub(crate) type NovaRegisters = kernel::io::Region<BAR0_SIZE>;
> +#[expect(dead_code)]
> +pub(crate) type Bar1<'a> = pci::Bar<'a>;
[Severity: Medium]
This is where the Bar1 type alias is defined. Should this include the
promised BAR1_SIZE constant as a generic parameter, similar to Bar0?
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=14
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface
2026-09-09 3:59 ` [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface Eliot Courtney
@ 2026-09-09 4:16 ` sashiko-bot
2026-09-09 20:13 ` Danilo Krummrich
1 sibling, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:16 UTC (permalink / raw)
To: Eliot Courtney; +Cc: Danilo Krummrich, dri-devel, Alexandre Courbot
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] Insufficient bounds check in `bar_offset()` allows out-of-bounds multi-byte accesses across mapping boundaries.
- [Medium] Decoupled `GpuMm` lifetime in `BarUser::map` and `release` allows cross-device page table corruption.
- [Medium] `BarUserAccess` breaks RAII, silently leaking address space on standard Rust error paths.
- [Medium] BAR1 is mapped as uncacheable MMIO instead of write-combining (WC), causing massive performance degradation.
--
commit f4c54c8b0e0e82f490fc3199121f6bdbfd3815b4
Author: Joel Fernandes <joelagnelf@nvidia.com>
Subject: gpu: nova-core: mm: Add BAR1 user interface
Adds the BAR1 user interface for CPU access to GPU virtual memory through
the BAR1 aperture.
> diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver.rs
> index 5723ff8f71ea4..0672a0707a713 100644
> --- a/drivers/gpu/nova-core/driver.rs
> +++ b/drivers/gpu/nova-core/driver.rs
[ ... ]
> @@ -82,12 +105,18 @@ fn probe<'bound>(
>
> Ok(try_pin_init!(NovaCore {
> bar: pdev.iomap_region_sized::<BAR0_SIZE>(0, c"nova-core/bar0")?,
> - // TODO: Use `&bar` self-referential pin-init syntax once available.
> - //
> - // SAFETY: `bar` is initialized before this expression is evaluated
> - // (`try_pin_init!()` initializes fields in declaration order), lives at a pinned
> - // stable address, and is dropped after `gpu` (struct field drop order).
> - gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) }),
> + bar1: {
> + let bar1_idx = bar1_resource_index(pdev)?;
> + pdev.iomap_region(bar1_idx, c"nova-core/bar1")?
[Severity: Medium]
Will this uncacheable MMIO mapping cause severe performance bottlenecks for
CPU-to-GPU transfers?
BAR1 is the framebuffer aperture and is designed for bulk data transfers like
USERD or command buffers. By using iomap_region (uncacheable), every write
will generate a separate, synchronous PCIe transaction. Could this be mapped
with write-combining instead, even if it requires adding new WC bindings to
the Rust pci module?
> + },
> + // TODO: Use self-referential pin-init syntax once available.
[ ... ]
> diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
> new file mode 100644
> index 0000000000000..ef1d8e6f8c9c3
> --- /dev/null
> +++ b/drivers/gpu/nova-core/mm/bar_user.rs
[ ... ]
> + /// Map physical pages to a contiguous BAR1 virtual range.
> + pub(crate) fn map(
> + self: &Arc<Self>,
> + mm: &mut GpuMm<'_>,
> + pfns: &[Pfn],
> + writable: bool,
> + ) -> Result<BarUserAccess<'gpu>> {
[Severity: Medium]
Does this decoupled GpuMm lifetime allow cross-device page table corruption?
Because the mm parameter uses an unbound anonymous lifetime instead of the
'gpu lifetime associated with BarUser, the Rust compiler cannot statically
prevent cross-device mixing.
In a multi-GPU system, could a caller inadvertently pass a GpuMm belonging to
a different device into the map or release methods, causing the method to
allocate from the first GPU's VMM but write page table entries to the second
GPU's PRAMIN?
> + if pfns.is_empty() {
> + return Err(EINVAL);
> + }
> + let mut vmm = self.vmm.lock();
> + let mapped = vmm.map_pages(mm, pfns, None, writable)?;
[ ... ]
> + /// Translate an offset within this mapping to a BAR1 aperture offset.
> + fn bar_offset(&self, offset: usize) -> Result<usize> {
> + if offset >= self.size() {
> + return Err(EINVAL);
> + }
[Severity: High]
Does this bounds check properly account for the multi-byte access width?
When callers use BarUserAccess::try_read32/64 or try_write32/64, the access
extends 4 or 8 bytes past the provided offset. If offset = self.size() - 2,
this check passes, but the access will overflow the mapping boundary. Could
this lead to unmapped MMIO reads/writes or accesses into adjacent
allocations?
> +
> + let base_vfn: usize = self.mapped().vfn_start.raw().into_safe_cast();
> + let base = base_vfn.checked_mul(PAGE_SIZE).ok_or(EOVERFLOW)?;
> + base.checked_add(offset).ok_or(EOVERFLOW)
> + }
[ ... ]
> +impl Drop for BarUserAccess<'_> {
> + fn drop(&mut self) {
> + if self.mapped.is_some() {
> + kernel::pr_warn!(
> + "BarUserAccess dropped without calling release(). BarUser address space will leak.\n"
> + );
> + }
[Severity: Medium]
Could this design break Rust's RAII guarantees and permanently leak address
space on standard error paths?
If a caller maps BAR1, performs some fallible operations using the ? operator,
and returns an error before manually calling access.release(mm), the BAR1
virtual address space will leak.
Since BarUserAccess does not hold a reference to GpuMm, its Drop
implementation cannot unmap the pages. Is there a way to refactor this to
ensure automatic cleanup during drop?
> + // The inner `MappedRange`'s own `MustUnmapGuard` will also fire,
> + // identifying the leaked VA range.
> + }
> +}
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=15
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API to VMM
2026-09-09 3:59 ` [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API " Eliot Courtney
@ 2026-09-09 4:17 ` sashiko-bot
2026-09-09 19:58 ` Danilo Krummrich
2026-09-10 0:47 ` Alistair Popple
2 siblings, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:17 UTC (permalink / raw)
To: Eliot Courtney; +Cc: dri-devel, Danilo Krummrich, Alexandre Courbot
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [Critical] Capacity exhaustion during page table installation causes hardware Use-After-Free.
- [Critical] Freeing the VFN range on partial mapping/unmapping failure leaves dangling hardware PTEs.
- [High] Early error return in `invalidate_ptes` skips mandatory TLB flush.
- [Medium] `PreparedMapping` and `MappedRange` permanently leak VFN space on drop.
- [Low] Spurious false-positive kernel warning on `execute_map` validation failure.
--
commit dc299c1a2ad37eca6a9c91c4b5425f4e7871fa45
Author: Joel Fernandes <joelagnelf@nvidia.com>
gpu: nova-core: mm: Add multi-page mapping API to VMM
Add the page table mapping and unmapping API to the Virtual Memory
Manager, implementing a two-phase prepare/execute model suitable for
use both inside and outside the DMA fence signalling critical path.
> diff --git a/drivers/gpu/nova-core/mm/pagetable/map.rs b/drivers/gpu/nova-core/mm/pagetable/map.rs
> --- a/drivers/gpu/nova-core/mm/pagetable/map.rs
> +++ b/drivers/gpu/nova-core/mm/pagetable/map.rs
[ ... ]
> + pub(super) fn prepare_map(
> + &self,
> + mm: &mut GpuMm<'_>,
> + vfn_start: Vfn,
> + num_pages: usize,
> + page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
> + pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
> + ) -> Result {
> + // Pre-reserve so install_mappings() can use push_within_capacity (no alloc
> + // in fence signalling critical path).
> + let pt_upper_bound = M::pt_pages_upper_bound(num_pages);
> + page_table_allocs.reserve(pt_upper_bound, GFP_KERNEL)?;
[Severity: Critical]
Does this reservation fail to account for multiple pending allocations?
If prepare_map() is called multiple times before execute_map() or fails
partway through, orphaned pages accumulate in the shared pt_pages tree.
This regression occurs because page_table_allocs.reserve() does not
accumulate capacity across multiple calls, causing install_mappings()
to later run out of reserved capacity.
[ ... ]
> + pub(super) fn install_mappings(
> + &self,
> + mm: &mut GpuMm<'_>,
> + pt_pages: &mut RBTree<VramAddress, PreparedPtPage>,
> + page_table_allocs: &mut KVec<Pin<KBox<AllocatedBlocks>>>,
> + vfn_start: Vfn,
> + pfns: &[Pfn],
> + writable: bool,
> + ) -> Result {
> + {
> + let pramin = mm.pramin_mut();
> +
> + // Drain prepared PT pages, install all pending PDEs.
> + let mut cursor = pt_pages.cursor_front_mut();
> + while let Some(c) = cursor {
> + let (next, node) = c.remove_current();
> + let (install_addr, page) = node.to_key_value();
> + let page_vram =
> + VramAddress::from_raw(page.alloc.iter().next().ok_or(ENOMEM)?.offset());
> +
> + if page.level == M::DUAL_PDE_LEVEL {
> + let new_dpde = M::DualPde::new_small(Pfn::from(page_vram));
> + new_dpde.write(pramin, install_addr)?;
> + } else {
> + let new_pde = M::Pde::new(AperturePde::VideoMemory, Pfn::from(page_vram));
> + new_pde.write(pramin, install_addr)?;
> + }
> +
> + page_table_allocs
> + .push_within_capacity(page.alloc)
> + .map_err(|_| ENOMEM)?;
[Severity: Critical]
Can this capacity check failure lead to a use-after-free in the hardware?
The physical memory is committed to the hardware PDE right before the
capacity check fails. If push_within_capacity() returns an error, this
regression causes the allocation to be dropped and the memory to be freed
back to the buddy allocator, but the hardware PDE is left pointing to that
freed memory.
[ ... ]
> + pub(super) fn invalidate_ptes(
> + &self,
> + mm: &mut GpuMm<'_>,
> + vfn_start: Vfn,
> + num_pages: usize,
> + ) -> Result {
> + let invalid_pte = M::Pte::invalid();
> +
> + {
> + let pramin = mm.pramin_mut();
> + for i in 0..num_pages {
> + let i_u64: u64 = i.into_safe_cast();
> + let vfn = Vfn::new(vfn_start.raw() + i_u64);
> + let result = self.walker.walk_to_pte_lookup_with_window(pramin, vfn)?;
> +
> + match result {
> + WalkResult::Mapped { pte_addr, .. } | WalkResult::Unmapped { pte_addr } => {
> + invalid_pte.write(pramin, pte_addr)?;
> + }
[Severity: High]
Does the ? operator here skip the mandatory TLB flush? If a hardware I/O
error occurs during the page table window write, the function returns
early.
> + WalkResult::PageTableMissing => {
> + continue;
> + }
> + }
> + }
> + }
> +
> + mm.tlb().flush(self.pdb_addr)
> + }
[Severity: High]
This required TLB flush is bypassed on the early error return mentioned
above. Any PTEs successfully invalidated before the error will remain
active in the GPU's TLB, creating a regression where continued access to
memory is allowed after it has been unmapped and freed.
> diff --git a/drivers/gpu/nova-core/mm/vmm.rs b/drivers/gpu/nova-core/mm/vmm.rs
> --- a/drivers/gpu/nova-core/mm/vmm.rs
> +++ b/drivers/gpu/nova-core/mm/vmm.rs
[ ... ]
> +impl Drop for MustExecuteGuard {
> + fn drop(&mut self) {
> + if self.armed.get() {
> + kernel::pr_warn!("PreparedMapping dropped without calling execute_map()\n");
> + }
> + }
> +}
[Severity: Medium]
Does this drop guard permanently leak the allocated VFN space? While the
guard logs a warning, it lacks a reference to the Vmm and cannot free the
underlying virtual address allocation from the maple tree, causing a
regression that permanently leaks virtual address space.
[ ... ]
> +impl Drop for MustUnmapGuard {
> + fn drop(&mut self) {
> + if self.armed.get() {
> + kernel::pr_warn!("MappedRange dropped without calling unmap_pages()\n");
> + }
> + }
> +}
[Severity: Medium]
Similarly, does dropping a MappedRange without calling unmap_pages() leak
the virtual address space? If a caller propagates an error and drops the
range, the warning is printed but the VFN space is permanently lost.
[ ... ]
> + pub(crate) fn execute_map(
> + &mut self,
> + mm: &mut GpuMm<'_>,
> + prepared: PreparedMapping,
> + pfns: &[Pfn],
> + writable: bool,
> + ) -> Result<MappedRange> {
> + if pfns.len() != prepared.num_pages {
> + self.free_vfn(prepared.vfn_start);
> + return Err(EINVAL);
> + }
[Severity: Low]
Could this validation failure trigger a false-positive kernel warning?
The prepared mapping is passed by value and is dropped on this early
return. Because its drop guard is still armed, MustExecuteGuard::drop()
will log a warning that the mapping was dropped without calling
execute_map(), even though the caller did correctly invoke execute_map().
[ ... ]
> + if let Err(e) = self.pt_map.install_mappings(
> + mm,
> + &mut self.pt_pages,
> + &mut self.page_table_allocs,
> + vfn_start,
> + pfns,
> + writable,
> + ) {
> + self.free_vfn(vfn_start);
> + return Err(e);
> + }
[Severity: Critical]
Does freeing the VFN range on partial mapping failure leave dangling
hardware PTEs? If install_mappings() returns early due to an I/O error
after writing some PTEs, self.free_vfn() frees the virtual address space,
and the caller will likely free the underlying physical pages. However, the
successfully written hardware PTEs are not rolled back. This regression
allows the GPU to access the freed physical memory.
[ ... ]
> + pub(crate) fn unmap_pages(&mut self, mm: &mut GpuMm<'_>, range: MappedRange) -> Result {
> + let result = self
> + .pt_map
> + .invalidate_ptes(mm, range.vfn_start, range.num_pages);
> +
> + // TODO: Internal page table pages (PDE, PTE pages) are still kept around.
> + // This is by design as repeated maps/unmaps will be fast. As a future TODO,
> + // we can add a reclaimer here to reclaim if VRAM is short. For now, the PT
> + // pages are dropped once the `Vmm` is dropped.
> +
> + // Free the VA range regardless of PTE invalidation success, so that the VA
> + // range is recovered even on failure (PTEs may be stale, but that is better
> + // than leaking both PTEs and VA range).
> + self.free_vfn(range.vfn_start);
[Severity: Critical]
Is it safe to free the VFN range if PTE invalidation fails? If
invalidate_ptes() fails partially, explicit freeing of the VFN range
leaves active, stale PTEs in the hardware. This regression allows the GPU
to retain access to physical pages that the caller will assume are safe to
free and reuse.
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=13
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM
2026-09-09 3:59 ` [PATCH 12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM Eliot Courtney
@ 2026-09-09 4:18 ` sashiko-bot
2026-09-09 19:32 ` Danilo Krummrich
1 sibling, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:18 UTC (permalink / raw)
To: Eliot Courtney; +Cc: Alexandre Courbot, Danilo Krummrich, dri-devel
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] `free_vfn` inadvertently frees entire multi-page or unrelated adjacent allocations because the maple tree automatically coalesces identical values and `erase` removes the full node.
- [High] `alloc_vfn_range` silently truncates unaligned requested virtual addresses instead of returning an error, mapping a different virtual address range than requested.
- [High] `alloc_vfn_range` fails to validate that an explicitly requested `va_range` falls within the VMM's maximum address space limits.
--
commit 72ebdc957b03c40c8135fdeabd96b70130feb75f
Author: Joel Fernandes <joelagnelf@nvidia.com>
gpu: nova-core: mm: Add virtual address range tracking to VMM
This commit adds a maple tree allocator for tracking contiguous virtual
address ranges. It enables allocating and freeing virtual frame numbers
for mappings.
> diff --git a/drivers/gpu/nova-core/mm/vmm.rs b/drivers/gpu/nova-core/mm/vmm.rs
> index a7911efb65a03..0bcae29db4f2c 100644
> --- a/drivers/gpu/nova-core/mm/vmm.rs
> +++ b/drivers/gpu/nova-core/mm/vmm.rs
[ ... ]
> @@ -34,18 +43,74 @@ pub(crate) struct Vmm {
> mmu_version: MmuVersion,
> /// Page table allocations required for mappings.
> page_table_allocs: KVec<Pin<KBox<AllocatedBlocks>>>,
> + /// Maple tree allocator for virtual address range tracking.
> + virt_alloc: Pin<KBox<MapleTreeAlloc<()>>>,
> + /// Total number of pages in the virtual address space.
> + va_pages: usize,
> }
>
> impl Vmm {
> /// Create a new [`Vmm`] for the given Page Directory Base address.
> - pub(crate) fn new(pdb_addr: VramAddress, mmu_version: MmuVersion) -> Result<Self> {
> + ///
> + /// The [`Vmm`] will manage a virtual address space of `va_size` bytes.
> + pub(crate) fn new(
> + pdb_addr: VramAddress,
> + mmu_version: MmuVersion,
> + va_size: u64,
> + ) -> Result<Self> {
> + let page_size: u64 = PAGE_SIZE.into_safe_cast();
> + let va_pages: usize = (va_size / page_size).into_safe_cast();
> + let virt_alloc = KBox::pin_init(MapleTreeAlloc::<()>::new(), GFP_KERNEL)?;
[Severity: High]
Since the maple tree allocator is instantiated with () as the value, won't it
automatically coalesce contiguous allocations into a single node because the
stored pointers are identical?
> +
> Ok(Self {
> pdb_addr,
> mmu_version,
> page_table_allocs: KVec::new(),
> + virt_alloc,
> + va_pages,
> })
> }
>
> + /// Allocate a contiguous virtual frame number range.
> + ///
> + /// # Arguments
> + ///
> + /// - `num_pages`: Number of pages to allocate.
> + /// - `va_range`: `None` = allocate anywhere, `Some(range)` = constrain allocation to the given
> + /// range.
> + fn alloc_vfn_range(&self, num_pages: usize, va_range: Option<Range<u64>>) -> Result<Vfn> {
> + let page_size: u64 = PAGE_SIZE.into_safe_cast();
> +
> + let start_vfn = match va_range {
> + Some(r) => {
> + let num_pages_u64: u64 = num_pages.into_safe_cast();
> + let size = num_pages_u64.checked_mul(page_size).ok_or(EOVERFLOW)?;
> + let range_size = r.end.checked_sub(r.start).ok_or(EOVERFLOW)?;
> + if range_size != size {
> + return Err(EINVAL);
> + }
> + let start_vfn: usize = (r.start / page_size).into_safe_cast();
> + let end_vfn: usize = (r.end / page_size).into_safe_cast();
[Severity: High]
Could the integer division truncate misaligned addresses here?
If r.start or r.end are not page-aligned, this division silently maps a
different page-aligned address instead of returning -EINVAL for the misaligned
request.
> + self.virt_alloc
> + .insert_range(start_vfn..end_vfn, (), GFP_KERNEL)?;
[Severity: High]
Does this insertion need to be validated against the VMM's maximum address space
limit?
If an explicitly requested end_vfn exceeds self.va_pages, this succeeds but
could later cause wrap-around truncation and page table corruption during
hardware programming.
> + start_vfn
> + }
> + None => self
> + .virt_alloc
> + .alloc_range(num_pages, (), ..self.va_pages, GFP_KERNEL)?,
> + };
> +
> + Ok(Vfn::new(start_vfn.into_safe_cast()))
> + }
> +
> + /// Free a virtual frame number range back to the maple tree.
> + fn free_vfn(&self, vfn: Vfn) {
> + let vfn_index: usize = vfn.raw().into_safe_cast();
> + if self.virt_alloc.erase(vfn_index).is_none() {
[Severity: High]
If the maple tree automatically coalesced contiguous allocations because they all
share the () value, won't erase() remove the entire coalesced node rather
than just the originally requested range?
This could inadvertently free unrelated adjacent mappings or the remainder of a
multi-page allocation.
> + kernel::pr_warn!("free_vfn: VFN {} not found in maple tree\n", vfn_index);
> + }
> + }
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=12
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 16/16] gpu: nova-core: mm: Add BAR1 memory management self-tests
2026-09-09 3:59 ` [PATCH 16/16] gpu: nova-core: mm: Add BAR1 memory management self-tests Eliot Courtney
@ 2026-09-09 4:18 ` sashiko-bot
0 siblings, 0 replies; 34+ messages in thread
From: sashiko-bot @ 2026-09-09 4:18 UTC (permalink / raw)
To: Eliot Courtney; +Cc: Danilo Krummrich, Alexandre Courbot, dri-devel
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Hardware Use-After-Free due to dangling Page Directory Entries (PDEs) when temporary Vmm instances are dropped.
- [High] Hardware Use-After-Free: Early error returns bypass explicit unmapping, leaking hardware PTEs pointing to freed VRAM.
- [Medium] Logic Error: Overlapping Virtual Frame Number (VFN) allocations corrupt global state.
- [Medium] Hardware Synchronization: Missing dummy reads to flush posted MMIO writes across different PCI BARs.
- [Low] Unconditional `#[expect(dead_code)]` causes a build error when selftests are enabled.
--
commit 8fda415a03ac7ee1e1b918cb7cfe5d0bb8315e6c
Author: Joel Fernandes <joelagnelf@nvidia.com>
gpu: nova-core: mm: Add BAR1 memory management self-tests
Add self-tests for BAR1 access during driver probe when
CONFIG_NOVA_CORE_SELFTESTS is enabled (default disabled). This results in
testing the Vmm, GPU buddy allocator and BAR1 region all of which should
function correctly for the tests to pass.
> diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
> index ef1d8e6f8c9c3..1bef01d147ada 100644
> --- a/drivers/gpu/nova-core/mm/bar_user.rs
> +++ b/drivers/gpu/nova-core/mm/bar_user.rs
[ ... ]
> @@ -84,6 +87,7 @@ pub(crate) struct BarUserAccess<'gpu> {
> mapped: Option<MappedRange>,
> }
>
> +#[expect(dead_code)]
> impl BarUserAccess<'_> {
> /// Tear down the BAR1 mapping.
> pub(crate) fn release(mut self, mm: &mut GpuMm<'_>) -> Result {
[Severity: Low]
When CONFIG_NOVA_CORE_SELFTESTS is enabled, try_read32 and release are
used by the self-test, so they are no longer dead code. Since kernel
Rust builds treat warnings as errors, does this unconditional lint
expectation cause a build failure?
Should this use cfg_attr to be conditionally applied?
[ ... ]
> + // Create a VMM of size 64K to track virtual memory mappings.
> + let mut vmm = Vmm::new(pdb_addr, chipset.mmu_version(), SZ_64K.into_safe_cast())?;
[Severity: High]
Does dropping this temporary Vmm later in the function leave dangling PDEs
in the live hardware pointing to freed VRAM?
The Vmm allocates PT pages from the buddy allocator and writes PDEs into the
live hardware page directory, but its Drop implementation does not clear them,
and the PT VRAM is freed when the temporary Vmm is dropped. If this VRAM is
reallocated for user buffers, could the GPU MMU misinterpret user data as
page tables?
[Severity: Medium]
Will this temporary Vmm (and the BarUser created later) allocate VFN 0
for their first mappings and blindly overwrite mappings placed in the
global page directory by the live driver's bar_user?
> +
> + // Create a test mapping.
> + let mapped = vmm.map_pages(mm, &[test_pfn], None, true)?;
> + let test_vfn = mapped.vfn_start;
> +
> + // Pre-compute test addresses for the PRAMIN to BAR1 read test.
> + let vfn_offset: usize = test_vfn.raw().into_safe_cast();
> + let bar1_base_offset = vfn_offset.checked_mul(PAGE_SIZE).ok_or(EOVERFLOW)?;
> + let bar1_read_offset: usize = bar1_base_offset + 0x100;
> + 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);
> +
> + // Read back via BAR1 aperture.
> + let bar1_value = bar1.try_read32(bar1_read_offset)?;
[Severity: Medium]
Since PCI memory space writes are posted operations, could the read from
the BAR1 aperture arrive at VRAM before the write via PRAMIN completes?
Is a dummy read from PRAMIN required to explicitly flush the write before
reading via BAR1 to avoid spurious test failures?
[Severity: High]
If try_read32() returns an error, the function will return early via the
`?` operator. Since the early return bypasses explicit cleanup calls like
vmm.unmap_pages(), does this leak live PTEs in hardware pointing to freed
VRAM?
If the selftest fails early, the driver probe continues normally since the
error is caught in run_selftests() in gpu.rs, which would cement this UAF
condition in the running system.
[ ... ]
> + for j in 0..num_pages {
> + let page_bar1_off = bar1_base + j * PAGE_SIZE;
> + let j_u64: u64 = j.into_safe_cast();
> + let page_phys = block.offset()
> + + j_u64
> + .checked_mul(PAGE_SIZE.into_safe_cast())
> + .ok_or(EOVERFLOW)?;
> +
> + 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();
[Severity: Medium]
Similarly, does writing to BAR1 and immediately reading from PRAMIN
require a dummy read from BAR1 to flush the posted write?
--
Sashiko AI review · https://sashiko.dev/#/patchset/20260909-mmrebase-v1-0-8dd5d4225d2e@nvidia.com?part=16
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 07/16] gpu: nova-core: mm: Add MMU v2 page table types
2026-09-09 3:59 ` [PATCH 07/16] gpu: nova-core: mm: Add MMU v2 page table types Eliot Courtney
2026-09-09 4:12 ` sashiko-bot
@ 2026-09-09 18:43 ` Danilo Krummrich
1 sibling, 0 replies; 34+ messages in thread
From: Danilo Krummrich @ 2026-09-09 18:43 UTC (permalink / raw)
To: Eliot Courtney
Cc: Alexandre Courbot, Alice Ryhl, John Hubbard, Alistair Popple,
Timur Tabi, nova-gpu, dri-devel, linux-kernel, Joel Fernandes
On Wed Sep 9, 2026 at 5:59 AM CEST, Eliot Courtney wrote:
> +impl PteOps for Pte {
> + fn from_raw(val: u64) -> Self {
> + Self::from_raw(val)
> + }
> +
> + fn invalid() -> Self {
> + Self::zeroed()
> + }
> +
> + fn new(aperture: AperturePte, pfn: Pfn, writable: bool) -> Self {
> + let base = Self::zeroed()
> + .with_valid(true)
> + .with_aperture(aperture)
> + .with_read_only(!writable);
> + match aperture {
> + AperturePte::VideoMemory => base.with_frame_number_vid(pfn),
> + // Sysmem PTEs use VOL=1 to bypass L2 for cache coherency.
> + AperturePte::SystemCoherent => base.with_frame_number_sys(pfn).with_volatile(true),
> + AperturePte::PeerMemory | AperturePte::SystemNonCoherent => {
> + kernel::pr_warn!("MMU v2 PTE aperture {:?} not supported\n", aperture);
> + Self::invalid()
> + }
This looks pretty odd. The aperture argument should either be of a type that can
only contain valid Aperture variants (which might be tricky as v2 and v3 are
different) or the constructor should just be fallible. The same goes for the v3
code and the Pde code.
Besides that, please don't use pr_*() print primitives, please use dev_*()
instead. But with this being fallible there's no more reason to warn here.
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM
2026-09-09 3:59 ` [PATCH 12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM Eliot Courtney
2026-09-09 4:18 ` sashiko-bot
@ 2026-09-09 19:32 ` Danilo Krummrich
1 sibling, 0 replies; 34+ messages in thread
From: Danilo Krummrich @ 2026-09-09 19:32 UTC (permalink / raw)
To: Eliot Courtney
Cc: Alexandre Courbot, Alice Ryhl, John Hubbard, Alistair Popple,
Timur Tabi, nova-gpu, dri-devel, linux-kernel, Joel Fernandes
On Wed Sep 9, 2026 at 5:59 AM CEST, Eliot Courtney wrote:
> + /// Allocate a contiguous virtual frame number range.
> + ///
> + /// # Arguments
> + ///
> + /// - `num_pages`: Number of pages to allocate.
> + /// - `va_range`: `None` = allocate anywhere, `Some(range)` = constrain allocation to the given
> + /// range.
> + fn alloc_vfn_range(&self, num_pages: usize, va_range: Option<Range<u64>>) -> Result<Vfn> {
> + let page_size: u64 = PAGE_SIZE.into_safe_cast();
> +
> + let start_vfn = match va_range {
> + Some(r) => {
> + let num_pages_u64: u64 = num_pages.into_safe_cast();
> + let size = num_pages_u64.checked_mul(page_size).ok_or(EOVERFLOW)?;
> + let range_size = r.end.checked_sub(r.start).ok_or(EOVERFLOW)?;
> + if range_size != size {
> + return Err(EINVAL);
> + }
> + let start_vfn: usize = (r.start / page_size).into_safe_cast();
> + let end_vfn: usize = (r.end / page_size).into_safe_cast();
> + self.virt_alloc
> + .insert_range(start_vfn..end_vfn, (), GFP_KERNEL)?;
> + start_vfn
> + }
> + None => self
> + .virt_alloc
> + .alloc_range(num_pages, (), ..self.va_pages, GFP_KERNEL)?,
> + };
> +
> + Ok(Vfn::new(start_vfn.into_safe_cast()))
> + }
> +
> + /// Free a virtual frame number range back to the maple tree.
> + fn free_vfn(&self, vfn: Vfn) {
> + let vfn_index: usize = vfn.raw().into_safe_cast();
> + if self.virt_alloc.erase(vfn_index).is_none() {
> + kernel::pr_warn!("free_vfn: VFN {} not found in maple tree\n", vfn_index);
> + }
> + }
Ick! I think this should be done with a guard type, e.g.
struct AllocatedVfnRange<'a> {
vfn_start: Vfn,
virt_alloc: &'a MapleTreeAlloc<()>,
}
Now, I get that this isn't done because the whole Vmm is within a Mutex and
hence it would tie its lifetime to the MutexGuard.
But, Vmm shouldn't be embedded in a Mutex in the first place, as it defeats the
whole purpose of having the prepare_map() and execute_map() split.
Requiring the same lock for execute_map() as for prepare_map() will pull a
memory reclaim path into the DMA fence signaling critical path.
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API to VMM
2026-09-09 3:59 ` [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API " Eliot Courtney
2026-09-09 4:17 ` sashiko-bot
@ 2026-09-09 19:58 ` Danilo Krummrich
2026-09-10 0:47 ` Alistair Popple
2 siblings, 0 replies; 34+ messages in thread
From: Danilo Krummrich @ 2026-09-09 19:58 UTC (permalink / raw)
To: Eliot Courtney
Cc: Alexandre Courbot, Alice Ryhl, John Hubbard, Alistair Popple,
Timur Tabi, nova-gpu, dri-devel, linux-kernel, Joel Fernandes
On Wed Sep 9, 2026 at 5:59 AM CEST, Eliot Courtney wrote:
> +/// Guard that logs a warning if a [`PreparedMapping`] is dropped without
> +/// being consumed by [`Vmm::execute_map()`].
> +struct MustExecuteGuard {
> + armed: Cell<bool>,
> +}
> +
> +impl MustExecuteGuard {
> + const fn new() -> Self {
> + Self {
> + armed: Cell::new(true),
> + }
> + }
> +
> + fn disarm(&self) {
> + self.armed.set(false);
> + }
> +}
> +
> +impl Drop for MustExecuteGuard {
> + fn drop(&mut self) {
> + if self.armed.get() {
> + kernel::pr_warn!("PreparedMapping dropped without calling execute_map()\n");
> + }
> + }
> +}
> +
> +/// Guard that logs a warning if a [`MappedRange`] is dropped without
> +/// calling [`Vmm::unmap_pages()`].
> +struct MustUnmapGuard {
> + armed: Cell<bool>,
> +}
> +
> +impl MustUnmapGuard {
> + const fn new() -> Self {
> + Self {
> + armed: Cell::new(true),
> + }
> + }
> +
> + fn disarm(&self) {
> + self.armed.set(false);
> + }
> +}
> +
> +impl Drop for MustUnmapGuard {
> + fn drop(&mut self) {
> + if self.armed.get() {
> + kernel::pr_warn!("MappedRange dropped without calling unmap_pages()\n");
> + }
> + }
> +}
As mentioned in the previous reply, none of this seems necessary if we get rid
of the big vmm lock and use proper RAII guards instead.
> + // TODO: Internal page table pages (PDE, PTE pages) are still kept around.
> + // This is by design as repeated maps/unmaps will be fast. As a future TODO,
So, if I got the math right it means that once we scattered mappings across 1TiB
of address space, this is 2GiB of VRAM gone given that we currently only have
4KiB pages?
Performance wise it depends on the reclaim strategy. Also, given that we have no
software mirror, isn't this N * 4 PRAMIN reads for a mapping of N pages?
So, I'm not sure I'd call this by design.
> + // we can add a reclaimer here to reclaim if VRAM is short. For now, the PT
> + // pages are dropped once the `Vmm` is dropped.
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface
2026-09-09 3:59 ` [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface Eliot Courtney
2026-09-09 4:16 ` sashiko-bot
@ 2026-09-09 20:13 ` Danilo Krummrich
1 sibling, 0 replies; 34+ messages in thread
From: Danilo Krummrich @ 2026-09-09 20:13 UTC (permalink / raw)
To: Eliot Courtney
Cc: Alexandre Courbot, Alice Ryhl, John Hubbard, Alistair Popple,
Timur Tabi, nova-gpu, dri-devel, linux-kernel, Joel Fernandes
On Wed Sep 9, 2026 at 5:59 AM CEST, Eliot Courtney wrote:
> +/// Access object for a mapped BAR1 region.
> +pub(crate) struct BarUserAccess<'gpu> {
> + bar_user: Arc<BarUser<'gpu>>,
This shouldn't be an Arc, we can just borrow from BarUser.
> + /// [`BarUserAccess::release`] [`Option::take`]s this; `Some` at
> + /// drop time means `release()` was never called.
> + mapped: Option<MappedRange>,
This Option, the panic in mapped() and the odd warning in drop() should go away
with using proper RAII types as suggested in a previous reply. I.e.
unmap_pages() doesn't need to call free_vfn() anymore, but MappedRange's drop()
does it.
> +}
> +
> +impl BarUserAccess<'_> {
> + /// Tear down the BAR1 mapping.
> + pub(crate) fn release(mut self, mm: &mut GpuMm<'_>) -> Result {
> + let mapped = self.mapped.take().ok_or(EINVAL)?;
> + let mut vmm = self.bar_user.vmm.lock();
> + vmm.unmap_pages(mm, mapped)?;
> + Ok(())
> + }
> +
> + /// Returns the active mapping.
> + fn mapped(&self) -> &MappedRange {
> + // `mapped` is only `None` after `take()` in `release`; hence unwrap()
> + // cannot panic here.
> + self.mapped.as_ref().unwrap()
> + }
[...]
> +impl Drop for BarUserAccess<'_> {
> + fn drop(&mut self) {
> + if self.mapped.is_some() {
> + kernel::pr_warn!(
> + "BarUserAccess dropped without calling release(). BarUser address space will leak.\n"
> + );
> + }
> + // The inner `MappedRange`'s own `MustUnmapGuard` will also fire,
> + // identifying the leaked VA range.
> + }
> +}
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
` (15 preceding siblings ...)
2026-09-09 3:59 ` [PATCH 16/16] gpu: nova-core: mm: Add BAR1 memory management self-tests Eliot Courtney
@ 2026-09-09 21:11 ` Danilo Krummrich
16 siblings, 0 replies; 34+ messages in thread
From: Danilo Krummrich @ 2026-09-09 21:11 UTC (permalink / raw)
To: Eliot Courtney
Cc: Alexandre Courbot, Alice Ryhl, John Hubbard, Alistair Popple,
Timur Tabi, nova-gpu, dri-devel, linux-kernel, Joel Fernandes,
Zhi Wang
On Wed Sep 9, 2026 at 5:59 AM CEST, Eliot Courtney wrote:
> I am reposting Joel Fernandes's original series [1]. The rebase adapts
> the patches to recent changes in the rust infra, like HRT lifetimes. It
> also adapts to the changes I posted in [2]. It keeps Joel's design and
> patch split.
I left a few comments that we really need to address. However, I'm fine if we do
that with subsequent patches. Thus, a bit hesitantly:
Acked-by: Danilo Krummrich <dakr@kernel.org>
Also note that eventually we want per-PT-page reference counts, so VM_BIND
ioctls can reserve for the whole range requested by userspace. We only know at
job execution time which parts of the requested range are mapped already (either
already with or without the correct contents) and which page size is used. I.e.
we need quite some flexibility in the API to take the optimal decision at job
execution time. So, this together with a reclaim approach will probably be a
huge rework anyway.
Eliot, when you apply this, can you please fix up the nits, e.g. make the
imports use the correct kernel vertical style, etc.?
Thanks,
Danilo
^ permalink raw reply [flat|nested] 34+ messages in thread
* Re: [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API to VMM
2026-09-09 3:59 ` [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API " Eliot Courtney
2026-09-09 4:17 ` sashiko-bot
2026-09-09 19:58 ` Danilo Krummrich
@ 2026-09-10 0:47 ` Alistair Popple
2 siblings, 0 replies; 34+ messages in thread
From: Alistair Popple @ 2026-09-10 0:47 UTC (permalink / raw)
To: Eliot Courtney
Cc: Danilo Krummrich, Alexandre Courbot, Alice Ryhl, John Hubbard,
Timur Tabi, nova-gpu, dri-devel, linux-kernel, Joel Fernandes
On 2026-09-09 at 13:59 +1000, Eliot Courtney <ecourtney@nvidia.com> wrote...
> From: Joel Fernandes <joelagnelf@nvidia.com>
[...]
> + // TODO: Internal page table pages (PDE, PTE pages) are still kept around.
> + // This is by design as repeated maps/unmaps will be fast. As a future TODO,
> + // we can add a reclaimer here to reclaim if VRAM is short. For now, the PT
> + // pages are dropped once the `Vmm` is dropped.
> +
> + // Free the VA range regardless of PTE invalidation success, so that the VA
> + // range is recovered even on failure (PTEs may be stale, but that is better
> + // than leaking both PTEs and VA range).
I don't think this is the correct approach. I'm not sure what exactly can cause
PTE invalidation to fail, but I don't think we can just recover the VA range
if something might still be using it via stale PTEs. That would cause problems
if the VA was ever reused for example. TLB invalidation is also part of PTE
invalidation as written, so we could also end up with stale TLB entries.
So leaking the range might be bad, but it's the least bad option IMHO.
- Alistair
> + self.free_vfn(range.vfn_start);
> +
> + // Unmap complete, safe to drop `MappedRange`.
> + range._drop_guard.disarm();
> + result
> + }
> }
>
> --
> 2.55.0
>
^ permalink raw reply [flat|nested] 34+ messages in thread
end of thread, other threads:[~2026-09-10 0:47 UTC | newest]
Thread overview: 34+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-09-09 3:59 [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Eliot Courtney
2026-09-09 3:59 ` [PATCH 01/16] gpu: nova-core: mm: Add common types for virtual memory management Eliot Courtney
2026-09-09 3:59 ` [PATCH 02/16] gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm Eliot Courtney
2026-09-09 4:09 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 03/16] gpu: nova-core: mm: Add common types for all page table formats Eliot Courtney
2026-09-09 3:59 ` [PATCH 04/16] gpu: nova-core: mm: pagetable: Add PteOps trait Eliot Courtney
2026-09-09 4:07 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 05/16] gpu: nova-core: mm: pagetable: Add PdeOps trait Eliot Courtney
2026-09-09 4:08 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 06/16] gpu: nova-core: mm: pagetable: Add DualPdeOps trait Eliot Courtney
2026-09-09 3:59 ` [PATCH 07/16] gpu: nova-core: mm: Add MMU v2 page table types Eliot Courtney
2026-09-09 4:12 ` sashiko-bot
2026-09-09 18:43 ` Danilo Krummrich
2026-09-09 3:59 ` [PATCH 08/16] gpu: nova-core: mm: Add MMU v3 " Eliot Courtney
2026-09-09 3:59 ` [PATCH 09/16] gpu: nova-core: mm: pagetable: Add MmuConfig trait Eliot Courtney
2026-09-09 4:12 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 10/16] gpu: nova-core: mm: Add page table walker for MMU v2/v3 Eliot Courtney
2026-09-09 4:07 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 11/16] gpu: nova-core: mm: Add Virtual Memory Manager Eliot Courtney
2026-09-09 3:59 ` [PATCH 12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM Eliot Courtney
2026-09-09 4:18 ` sashiko-bot
2026-09-09 19:32 ` Danilo Krummrich
2026-09-09 3:59 ` [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API " Eliot Courtney
2026-09-09 4:17 ` sashiko-bot
2026-09-09 19:58 ` Danilo Krummrich
2026-09-10 0:47 ` Alistair Popple
2026-09-09 3:59 ` [PATCH 14/16] gpu: nova-core: Add BAR1 aperture type and size constant Eliot Courtney
2026-09-09 4:14 ` sashiko-bot
2026-09-09 3:59 ` [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface Eliot Courtney
2026-09-09 4:16 ` sashiko-bot
2026-09-09 20:13 ` Danilo Krummrich
2026-09-09 3:59 ` [PATCH 16/16] gpu: nova-core: mm: Add BAR1 memory management self-tests Eliot Courtney
2026-09-09 4:18 ` sashiko-bot
2026-09-09 21:11 ` [PATCH 00/16] gpu: nova-core: GPU page table, vmm, and bar1 mapping Danilo Krummrich
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.