gpu: nova-core: GPU page table, vmm, and bar1 mapping
Subsystems (4)
cover gpu: nova-core: GPU page table, vmm, and bar1 mapping
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/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/
---
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,
Signature · 1 line
Eliot Courtney <[email protected]>
PATCH 1/16 gpu: nova-core: mm: Add common types for virtual memory management
From: Joel Fernandes <[email protected]>
Add common virtual memory memory management types: PAGE_SIZE constant, VirtualAddress bitfield type, Vfn (Virtual Frame Number) type, Pfn (Physical Frame Number) type.
--- drivers/gpu/nova-core/mm.rs | 142 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 141 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/mm.rs +141 -1
@@ -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 ;
Signature · 1 line
2.55.0
PATCH 2/16 gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- 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(-)
drivers/gpu/nova-core/Kconfig +1 -0
@@ -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
drivers/gpu/nova-core/gpu.rs +21 -6
@@ -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), + )? + }, }) }
drivers/gpu/nova-core/mm.rs +24 -0
@@ -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).
drivers/gpu/nova-core/mm/tlb.rs new file +120 -0
120 lines not on this page · raw message
drivers/gpu/nova-core/regs.rs +68 -0
83 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 3/16 gpu: nova-core: mm: Add common types for all page table formats
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
Add common page table types shared between MMU v2 and v3. These types are hardware-agnostic and used by both MMU versions.
--- drivers/gpu/nova-core/mm.rs | 1 + drivers/gpu/nova-core/mm/pagetable.rs | 158 ++++++++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+)
drivers/gpu/nova-core/mm.rs +1 -0
@@ -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;
drivers/gpu/nova-core/mm/pagetable.rs new file +158 -0
158 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 4/16 gpu: nova-core: mm: pagetable: Add PteOps trait
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- drivers/gpu/nova-core/mm/pagetable.rs | 46 ++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/mm/pagetable.rs +45 -1
@@ -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.
Signature · 1 line
2.55.0
PATCH 5/16 gpu: nova-core: mm: pagetable: Add PdeOps trait
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- drivers/gpu/nova-core/mm/pagetable.rs | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+)
drivers/gpu/nova-core/mm/pagetable.rs +41 -0
@@ -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.
Signature · 1 line
2.55.0
PATCH 6/16 gpu: nova-core: mm: pagetable: Add DualPdeOps trait
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- drivers/gpu/nova-core/mm/pagetable.rs | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+)
drivers/gpu/nova-core/mm/pagetable.rs +41 -0
@@ -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.
Signature · 1 line
2.55.0
PATCH 7/16 gpu: nova-core: mm: Add MMU v2 page table types
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- drivers/gpu/nova-core/mm/pagetable.rs | 2 + drivers/gpu/nova-core/mm/pagetable/ver2.rs | 271 +++++++++++++++++++++++++++++ 2 files changed, 273 insertions(+)
drivers/gpu/nova-core/mm/pagetable.rs +2 -0
@@ -8,6 +8,8 @@#![expect(dead_code)] +pub (super )mod ver2; +use kernel::{ io::Io , num::Bounded ,
drivers/gpu/nova-core/mm/pagetable/ver2.rs new file +271 -0
271 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 8/16 gpu: nova-core: mm: Add MMU v3 page table types
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- drivers/gpu/nova-core/mm/pagetable.rs | 1 + drivers/gpu/nova-core/mm/pagetable/ver3.rs | 417 +++++++++++++++++++++++++++++ 2 files changed, 418 insertions(+)
drivers/gpu/nova-core/mm/pagetable.rs +1 -0
@@ -9,6 +9,7 @@#![expect(dead_code)] pub (super )mod ver2; +pub (super )mod ver3;use kernel::{ io::Io ,
drivers/gpu/nova-core/mm/pagetable/ver3.rs new file +417 -0
417 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 9/16 gpu: nova-core: mm: pagetable: Add MmuConfig trait
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- drivers/gpu/nova-core/mm/pagetable.rs | 109 ++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+)
drivers/gpu/nova-core/mm/pagetable.rs +109 -0
@@ -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 &levelin 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.
Signature · 1 line
2.55.0
PATCH 10/16 gpu: nova-core: mm: Add page table walker for MMU v2/v3
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- drivers/gpu/nova-core/mm/pagetable.rs | 1 + drivers/gpu/nova-core/mm/pagetable/walk.rs | 244 +++++++++++++++++++++++++++++ 2 files changed, 245 insertions(+)
drivers/gpu/nova-core/mm/pagetable.rs +1 -0
@@ -10,6 +10,7 @@pub (super )mod ver2;pub (super )mod ver3; +pub (super )mod walk;use kernel::{ io::Io ,
drivers/gpu/nova-core/mm/pagetable/walk.rs new file +244 -0
244 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 11/16 gpu: nova-core: mm: Add Virtual Memory Manager
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- drivers/gpu/nova-core/mm.rs | 1 + drivers/gpu/nova-core/mm/vmm.rs | 58 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+)
drivers/gpu/nova-core/mm.rs +1 -0
@@ -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. ///
drivers/gpu/nova-core/mm/vmm.rs new file +58 -0
58 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 12/16 gpu: nova-core: mm: Add virtual address range tracking to VMM
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
Add virtual address range tracking to the VMM using a maple tree allocator. This enables contiguous virtual address range allocation for mappings.
--- drivers/gpu/nova-core/mm/vmm.rs | 83 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 74 insertions(+), 9 deletions(-)
drivers/gpu/nova-core/mm/vmm.rs +74 -9
@@ -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);
Signature · 1 line
2.55.0
PATCH 13/16 gpu: nova-core: mm: Add multi-page mapping API to VMM
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- 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(-)
drivers/gpu/nova-core/mm/pagetable.rs +1 -0
@@ -8,6 +8,7 @@#![expect(dead_code)] +pub (super )mod map;pub (super )mod ver2;pub (super )mod ver3;pub (super )mod walk;
drivers/gpu/nova-core/mm/pagetable/map.rs new file +342 -0
342 lines not on this page · raw message
drivers/gpu/nova-core/mm/vmm.rs +241 -19
315 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 14/16 gpu: nova-core: Add BAR1 aperture type and size constant
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
Add BAR1_SIZE constant and Bar1 type alias for the 256MB BAR1 aperture. These are prerequisites for BAR1 memory access functionality.
--- 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(+)
drivers/gpu/nova-core/driver.rs +2 -0
@@ -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 ,
drivers/gpu/nova-core/gsp/commands.rs +4 -0
@@ -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, })
drivers/gpu/nova-core/gsp/fw/commands.rs +8 -0
@@ -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,
Signature · 1 line
2.55.0
PATCH 15/16 gpu: nova-core: mm: Add BAR1 user interface
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
Add the BAR1 user interface for CPU access to GPU virtual memory through the BAR1 aperture.
--- 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(-)
drivers/gpu/nova-core/driver.rs +37 -8
@@ -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) },
drivers/gpu/nova-core/gpu.rs +31 -1
@@ -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: &'gpuBar1 <'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 , + )? + }, }) }
drivers/gpu/nova-core/gsp/commands.rs +0 -1
@@ -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 >>,
drivers/gpu/nova-core/mm.rs +1 -0
@@ -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;
drivers/gpu/nova-core/mm/bar_user.rs new file +171 -0
171 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH 16/16 gpu: nova-core: mm: Add BAR1 memory management self-tests
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
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.
--- 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(-)
drivers/gpu/nova-core/gpu.rs +8 -1
@@ -482,7 +482,14 @@ pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device<device::Boulet 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); } }
drivers/gpu/nova-core/mm.rs +9 -3
@@ -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) } }
drivers/gpu/nova-core/mm/bar_user.rs +251 -0
266 lines not on this page · raw message
drivers/gpu/nova-core/mm/pagetable.rs +24 -0
@@ -396,3 +396,27 @@ fn from(val: AperturePde) -> Self {Bounded ::from_expr (valas 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), + } +}
drivers/gpu/nova-core/mm/vmm.rs +1 -0
@@ -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 ,
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH 10/16] gpu: nova-core: mm: Add page table walker for MMU v2/v3
In reply to Eliot CourtneyThank 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…
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 <[email protected]>
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.
Quoted 5 lines
drivers/gpu/nova-core/mm/pagetable/walk.rs new file +0
-0
[ ... ]
Quoted 7 lines
drivers/gpu/nova-core/mm/pagetable/walk.rs new file +7
-0+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);
drivers/gpu/nova-core/mm/pagetable/walk.rs line 138
Quoted 10 lines
drivers/gpu/nova-core/mm/pagetable/walk.rs new file +10
-0+let mut cur_table = self.pdb_addr; + +for &levelin 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.
Quoted 1 line
+
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.
Quoted 6 lines
drivers/gpu/nova-core/mm/pagetable/walk.rs new file +6
-0+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
drivers/gpu/nova-core/mm/pagetable/walk.rs line 155
Quoted 10 lines
drivers/gpu/nova-core/mm/pagetable/walk.rs new file +10
-0+// 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.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
[email protected]
AI reviewRe: [PATCH 04/16] gpu: nova-core: mm: pagetable: Add PteOps trait
In reply to Eliot CourtneyThank 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. --
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 <[email protected]>
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.
Quoted 10 lines
drivers/gpu/nova-core/mm/pagetable.rs +2
-1@@ -8,9 +8,18 @@#![expect(dead_code)] -use kernel::num::Bounded ; +use kernel::{ + io::Io ,
drivers/gpu/nova-core/mm/pagetable.rs line 22
Quoted 10 lines
drivers/gpu/nova-core/mm/pagetable.rs +8
-0+ 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?
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
[email protected]
AI reviewRe: [PATCH 05/16] gpu: nova-core: mm: pagetable: Add PdeOps trait
In reply to Eliot CourtneyThank 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…
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 <[email protected]>
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.
Quoted 10 lines
drivers/gpu/nova-core/mm/pagetable.rs +2
-0@@ -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 > {
[ ... ]
drivers/gpu/nova-core/mm/pagetable.rs fn write(&self, pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result { · line 149
Quoted 5 lines
drivers/gpu/nova-core/mm/pagetable.rs +5
-0+/// 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.
Quoted 3 lines
drivers/gpu/nova-core/mm/pagetable.rs +3
-0+ +/// Read a `PDE` from VRAM. +fn read (pramin: &mut pramin::Pramin <'_>, addr:VramAddress ) ->Result <Self > {
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
[email protected]
AI reviewRe: [PATCH 02/16] gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm
In reply to Eliot CourtneyThank 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…
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 <[email protected]>
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.
Quoted 5 lines
drivers/gpu/nova-core/mm/tlb.rs new file +0
-0
[ ... ]
Quoted 11 lines
drivers/gpu/nova-core/mm/tlb.rs new file +11
-0+/// 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(),
drivers/gpu/nova-core/mm/tlb.rs line 106
Quoted 10 lines
drivers/gpu/nova-core/mm/tlb.rs new file +10
-0+ )); + 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?
Quoted 14 lines
drivers/gpu/nova-core/mm/tlb.rs new file +14
-0+ .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 (()) + } +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewRe: [PATCH 09/16] gpu: nova-core: mm: pagetable: Add MmuConfig trait
In reply to Eliot CourtneyThank 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…
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 <[email protected]>
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.
Quoted 4 lines
drivers/gpu/nova-core/mm/pagetable.rs +0
-0
[ ... ]
Quoted 1 line
drivers/gpu/nova-core/mm/pagetable.rs +0
-0@@ -213,6 +214,114 @@ fn write(&self, pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result {
[ ... ]
Quoted 8 lines
drivers/gpu/nova-core/mm/pagetable.rs +8
-0+/// 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 );
drivers/gpu/nova-core/mm/pagetable.rs fn write(&self, pramin: &mut pramin::Pramin<'_>, addr: VramAddress) -> Result { · line 265
Quoted 10 lines
drivers/gpu/nova-core/mm/pagetable.rs +10
-0+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 &levelin 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.
Quoted 5 lines
drivers/gpu/nova-core/mm/pagetable.rs +5
-0+ total += pages_at_level; + } + + total + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
[email protected]
AI reviewRe: [PATCH 07/16] gpu: nova-core: mm: Add MMU v2 page table types
In reply to Eliot CourtneyThank 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]…
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 <[email protected]>
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.
Quoted 2 lines
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.
Quoted 5 lines
drivers/gpu/nova-core/mm/pagetable/ver2.rs new file +0
-0
[ ... ]
Quoted 4 lines
drivers/gpu/nova-core/mm/pagetable/ver2.rs new file +4
-0+impl PdeOps for Pde { +fn from_raw (val:u64 ) ->Self { +Self ::from_raw (val) + }
[ ... ]
drivers/gpu/nova-core/mm/pagetable/ver2.rs line 202
Quoted 5 lines
drivers/gpu/nova-core/mm/pagetable/ver2.rs new file +5
-0+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.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
[email protected]
AI reviewRe: [PATCH 14/16] gpu: nova-core: Add BAR1 aperture type and size constant
In reply to Eliot CourtneyThank 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. --
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 <[email protected]>
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.
Quoted 3 lines
gpu: nova-core: Add BAR1 aperture type and size constant
Add
BAR1_SIZEconstant 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.
drivers/gpu/nova-core/driver.rs pub(crate) struct NovaCore<'bound> { · line 42
Quoted 10 lines
drivers/gpu/nova-core/driver.rs +2
-0@@ -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?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
[email protected]
AI reviewRe: [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface
In reply to Eliot CourtneyThank 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…
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 <[email protected]>
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.
Quoted 4 lines
drivers/gpu/nova-core/driver.rs +0
-0
[ ... ]
drivers/gpu/nova-core/driver.rs fn probe<'bound>( · line 110
Quoted 13 lines
drivers/gpu/nova-core/driver.rs +3
-6@@ -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?
Quoted 2 lines
drivers/gpu/nova-core/driver.rs +2
-0+ }, +// TODO: Use self-referential pin-init syntax once available.
[ ... ]
Quoted 5 lines
drivers/gpu/nova-core/mm/bar_user.rs new file +0
-0
[ ... ]
drivers/gpu/nova-core/mm/bar_user.rs line 65
Quoted 7 lines
drivers/gpu/nova-core/mm/bar_user.rs new file +7
-0+/// 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?
Quoted 5 lines
drivers/gpu/nova-core/mm/bar_user.rs new file +5
-0+if pfns.is_empty () { +return Err (EINVAL ); + } +let mut vmm = self.vmm.lock (); +let mapped = vmm.map_pages (mm, pfns,None , writable)?;
[ ... ]
drivers/gpu/nova-core/mm/bar_user.rs line 127
Quoted 5 lines
drivers/gpu/nova-core/mm/bar_user.rs new file +5
-0+/// 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?
Quoted 5 lines
drivers/gpu/nova-core/mm/bar_user.rs new file +5
-0+ +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 ) + }
[ ... ]
drivers/gpu/nova-core/mm/bar_user.rs line 167
Quoted 7 lines
drivers/gpu/nova-core/mm/bar_user.rs new file +7
-0+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?
Quoted 4 lines
drivers/gpu/nova-core/mm/bar_user.rs new file +4
-0+// The inner `MappedRange`'s own `MustUnmapGuard` will also fire, +// identifying the leaked VA range. + } +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
[email protected]
AI reviewRe: [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API to VMM
In reply to Eliot CourtneyThank 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.…
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 <[email protected]>
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.
Quoted 3 lines
drivers/gpu/nova-core/mm/pagetable/map.rs +0
-0
[ ... ]
drivers/gpu/nova-core/mm/pagetable/map.rs line 173
Quoted 12 lines
drivers/gpu/nova-core/mm/pagetable/map.rs +12
-0+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.
[ ... ]
Quoted 21 lines
drivers/gpu/nova-core/mm/pagetable/map.rs +21
-0+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 {
drivers/gpu/nova-core/mm/pagetable/map.rs line 217
Quoted 10 lines
drivers/gpu/nova-core/mm/pagetable/map.rs +10
-0+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.
[ ... ]
Quoted 9 lines
drivers/gpu/nova-core/mm/pagetable/map.rs +9
-0+pub (super )fn invalidate_ptes ( + &self, + mm: &mut GpuMm <'_>, + vfn_start:Vfn , + num_pages:usize , + ) ->Result { +let invalid_pte =M ::Pte ::invalid (); + + {
drivers/gpu/nova-core/mm/pagetable/map.rs line 264
Quoted 10 lines
drivers/gpu/nova-core/mm/pagetable/map.rs +10
-0+let pramin = mm.pramin_mut (); +for iin 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.
drivers/gpu/nova-core/mm/pagetable/map.rs line 273
Quoted 9 lines
drivers/gpu/nova-core/mm/pagetable/map.rs +9
-0+ 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.
Quoted 3 lines
drivers/gpu/nova-core/mm/vmm.rs +0
-0
[ ... ]
drivers/gpu/nova-core/mm/vmm.rs line 95
Quoted 7 lines
drivers/gpu/nova-core/mm/vmm.rs +7
-0+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.
[ ... ]
drivers/gpu/nova-core/mm/vmm.rs line 121
Quoted 7 lines
drivers/gpu/nova-core/mm/vmm.rs +7
-0+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.
[ ... ]
drivers/gpu/nova-core/mm/vmm.rs fn free_vfn(&self, vfn: Vfn) { · line 264
Quoted 11 lines
drivers/gpu/nova-core/mm/vmm.rs +11
-0+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().
[ ... ]
drivers/gpu/nova-core/mm/vmm.rs fn free_vfn(&self, vfn: Vfn) { · line 283
Quoted 11 lines
drivers/gpu/nova-core/mm/vmm.rs +11
-0+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.
[ ... ]
Quoted 4 lines
drivers/gpu/nova-core/mm/vmm.rs +4
-0+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);
drivers/gpu/nova-core/mm/vmm.rs fn free_vfn(&self, vfn: Vfn) { · line 339
Quoted 10 lines
drivers/gpu/nova-core/mm/vmm.rs +10
-0+ +// 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.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
[email protected]
AI reviewRe: [PATCH 12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM
In reply to Eliot CourtneyThank 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…
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 <[email protected]>
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.
Quoted 4 lines
drivers/gpu/nova-core/mm/vmm.rs +0
-0
[ ... ]
Quoted 13 lines
drivers/gpu/nova-core/mm/vmm.rs +4
-1@@ -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 > {
drivers/gpu/nova-core/mm/vmm.rs pub(crate) struct Vmm { · line 63
Quoted 10 lines
drivers/gpu/nova-core/mm/vmm.rs +10
-0+/// +/// 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?
Quoted 20 lines
drivers/gpu/nova-core/mm/vmm.rs +13
-0+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 (); +
drivers/gpu/nova-core/mm/vmm.rs pub(crate) struct Vmm { · line 93
Quoted 10 lines
drivers/gpu/nova-core/mm/vmm.rs +10
-0+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.
drivers/gpu/nova-core/mm/vmm.rs pub(crate) struct Vmm { · line 95
Quoted 2 lines
drivers/gpu/nova-core/mm/vmm.rs +2
-0+ 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.
Quoted 4 lines
drivers/gpu/nova-core/mm/vmm.rs +4
-0+ start_vfn + } + None => self + .virt_alloc
drivers/gpu/nova-core/mm/vmm.rs pub(crate) struct Vmm { · line 109
Quoted 10 lines
drivers/gpu/nova-core/mm/vmm.rs +10
-0+ .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.
Quoted 3 lines
drivers/gpu/nova-core/mm/vmm.rs +3
-0+ kernel::pr_warn!("free_vfn: VFN {} not found in maple tree\n" , vfn_index); + } + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
[email protected]
AI reviewRe: [PATCH 16/16] gpu: nova-core: mm: Add BAR1 memory management self-tests
In reply to Eliot CourtneyThank 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…
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 <[email protected]>
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.
Quoted 4 lines
drivers/gpu/nova-core/mm/bar_user.rs +0
-0
[ ... ]
drivers/gpu/nova-core/mm/bar_user.rs pub(crate) struct BarUserAccess<'gpu> { · line 93
Quoted 8 lines
drivers/gpu/nova-core/mm/bar_user.rs +1
-0@@ -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?
[ ... ]
drivers/gpu/nova-core/mm/bar_user.rs fn drop(&mut self) { · line 232
Quoted 2 lines
drivers/gpu/nova-core/mm/bar_user.rs +2
-0+// 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?
Quoted 9 lines
drivers/gpu/nova-core/mm/bar_user.rs +9
-0+ +// 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 ;
drivers/gpu/nova-core/mm/bar_user.rs fn drop(&mut self) { · line 251
Quoted 10 lines
drivers/gpu/nova-core/mm/bar_user.rs +10
-0+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.
[ ... ]
Quoted 5 lines
drivers/gpu/nova-core/mm/bar_user.rs +5
-0+for jin 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
drivers/gpu/nova-core/mm/bar_user.rs fn drop(&mut self) { · line 356
Quoted 10 lines
drivers/gpu/nova-core/mm/bar_user.rs +10
-0+ .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?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
Danilo Krummrich
maintainerRe: [PATCH 07/16] gpu: nova-core: mm: Add MMU v2 page table types
In reply to Eliot CourtneyQuoted 12 lines · Eliot Courtney
drivers/gpu/nova-core/mm/pagetable/ver2.rs new file +12
-0+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 )
drivers/gpu/nova-core/mm/pagetable/ver2.rs line 141
Quoted 10 lines
drivers/gpu/nova-core/mm/pagetable/ver2.rs new file +10
-0+ .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.
Danilo Krummrich
maintainerRe: [PATCH 12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM
In reply to Eliot CourtneyQuoted 29 lines · Eliot Courtney
drivers/gpu/nova-core/mm/vmm.rs +29
-0+/// 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 )?, + }; +
drivers/gpu/nova-core/mm/vmm.rs pub(crate) struct Vmm { · line 112
Quoted 10 lines
drivers/gpu/nova-core/mm/vmm.rs +10
-0+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.
Danilo Krummrich
maintainerRe: [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API to VMM
In reply to Eliot CourtneyQuoted 41 lines · Eliot Courtney
drivers/gpu/nova-core/mm/vmm.rs +41
-0+/// 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 );
drivers/gpu/nova-core/mm/vmm.rs line 121
Quoted 10 lines
drivers/gpu/nova-core/mm/vmm.rs +10
-0+ } +} + +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.
drivers/gpu/nova-core/mm/vmm.rs fn free_vfn(&self, vfn: Vfn) { · line 332
Quoted 2 lines
drivers/gpu/nova-core/mm/vmm.rs +2
-0+// 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.
Quoted 2 lines
drivers/gpu/nova-core/mm/vmm.rs +2
-0+// we can add a reclaimer here to reclaim if VRAM is short. For now, the PT +// pages are dropped once the `Vmm` is dropped.
Danilo Krummrich
maintainerRe: [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface
In reply to Eliot Courtneydrivers/gpu/nova-core/mm/bar_user.rs line 81
Quoted 3 lines · Eliot Courtney
drivers/gpu/nova-core/mm/bar_user.rs new file +3
-0+/// 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.
drivers/gpu/nova-core/mm/bar_user.rs line 84
Quoted 3 lines
drivers/gpu/nova-core/mm/bar_user.rs new file +3
-0+/// [`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.
Quoted 17 lines
drivers/gpu/nova-core/mm/bar_user.rs new file +17
-0+} + +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 () + }
[...]
Quoted 11 lines
drivers/gpu/nova-core/mm/bar_user.rs new file +11
-0+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. + } +}
Quoted 4 lines · Eliot Courtney
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:
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
Re: [PATCH 13/16] gpu: nova-core: mm: Add multi-page mapping API to VMM
In reply to Eliot CourtneyOn 2026-09-09 at 13:59 +1000, Eliot Courtney <[email protected]> wrote...
Quoted 1 line
From: Joel Fernandes <[email protected]>
[...]
drivers/gpu/nova-core/mm/vmm.rs fn free_vfn(&self, vfn: Vfn) { · line 338
Quoted 8 lines
drivers/gpu/nova-core/mm/vmm.rs +8
-0+// 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
Quoted 11 lines
drivers/gpu/nova-core/mm/vmm.rs +6
-0+ self.free_vfn (range.vfn_start); + +// Unmap complete, safe to drop `MappedRange`. + range._drop_guard.disarm (); + result + } }Signature · 2 lines
-- 2.55.0
Quoted 8 lines · Eliot Courtney
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:
[...]
Applied to drm-rust-next, thanks!
... a bit hesitantly like Danilo, but we are in a state where the issues are easier to address through follow-ups than by reworking this base. This is also not used yet outside of self-tests, so we have some runway to fix it before it goes live.
Thanks Eliot for driving this series all the way to merge.
[01/16] gpu: nova-core: mm: Add common types for virtual memory management [acourbot: drop repeated "memory" in commit message.]
commit: b8ca2d0b7fcf5b8ff0ec174b092f732a9d3d27a3
[02/16] gpu: nova-core: mm: Add buddy allocator and TLB to GpuMm
commit: 33be8f687bd8204965c137a5600822a1959033b8
[03/16] gpu: nova-core: mm: Add common types for all page table formats
commit: a5dfe5955c6beff8403ce966efde6822700a6634
[04/16] gpu: nova-core: mm: pagetable: Add PteOps trait
[acourbot: use vertical import style.]
commit: 239bb057a81dca1623857102cfd963e1305aadc1
[05/16] gpu: nova-core: mm: pagetable: Add PdeOps trait
commit: 85a7542510cdff8bbeef9fb016e98a2f8bcd1171
[06/16] gpu: nova-core: mm: pagetable: Add DualPdeOps trait
commit: 71e99998a6559d71e5d6eff85afcc0f7f99ece25
[07/16] gpu: nova-core: mm: Add MMU v2 page table types
[acourbot: use vertical import style.]
commit: 98b7273f5de149b2c6ff0d98bc2b3fa55b749b74
[08/16] gpu: nova-core: mm: Add MMU v3 page table types
[acourbot: use vertical import style.]
commit: 103fb3a4b2b85ebf30f11a433df17df708f85689
[09/16] gpu: nova-core: mm: pagetable: Add MmuConfig trait
commit: a9eabe320b60e5af72ff10551be1b2d67ca614af
[10/16] gpu: nova-core: mm: Add page table walker for MMU v2/v3
commit: 1123774f3610c45a7acf055b8c9841883ed4bf75
[11/16] gpu: nova-core: mm: Add Virtual Memory Manager
[acourbot: use vertical import style.]
commit: 3c7561e194d573a3926702d1e051a8c8fbc187ea
[12/16] gpu: nova-core: mm: Add virtual address range tracking to VMM
[acourbot: use vertical import style.]
commit: 16f573374fd6ff8ff4ab54abceb5d093869de9d2
[13/16] gpu: nova-core: mm: Add multi-page mapping API to VMM
[acourbot: use vertical import style.]
commit: 4e4182282d4e8d81bfe62ed8ff634526fdd5e238
[14/16] gpu: nova-core: Add BAR1 aperture type and size constant
commit: 75ad43886a20e17aa5fad9ae71ebb413cadd8d64
[15/16] gpu: nova-core: mm: Add BAR1 user interface
commit: 159427b213524a90853ef24d0a0c2ed1aec1dbf9
[16/16] gpu: nova-core: mm: Add BAR1 memory management self-tests
[acourbot: use vertical import style.]
commit: d669686f8170c234edf12212fac9180ea18b1448Dave Airlie
maintainerRe: [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface
In reply to Eliot CourtneyQuoted 6 lines · Eliot Courtney
From: Joel Fernandes <[email protected]>
Add the BAR1 user interface for CPU access to GPU virtual memory through the BAR1 aperture.
Quoted 6 lines
Signed-off-by Joel Fernandes <[email protected]>[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 <[email protected]>---
BAR 1 and 2 need to be optionally detected and used. At least on SPARK there is only BAR0.
I've been playing with John's branch on spark and had to rework this code to make BAR 1 optional.
Dave.
Alexandre Courbot
maintainerRe: [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface
Quoted 14 lines · Dave Airlie
Quoted 6 lines · Eliot Courtney
From: Joel Fernandes <[email protected]>
Add the BAR1 user interface for CPU access to GPU virtual memory through the BAR1 aperture.
Quoted 6 lines
Signed-off-by Joel Fernandes <[email protected]>[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 <[email protected]>---
Quoted 5 lines
BAR 1 and 2 need to be optionally detected and used. At least on SPARK there is only BAR0.
I've been playing with John's branch on spark and had to rework this code to make BAR 1 optional.
Thanks Dave - indeed we also hit an issue on a device where the FB console was enabled (?), which preventing BAR1 from being used.
I know Eliot has a bunch of follow-ups in the pipe, Eliot can we make sure to dynamically detect and enable BAR1?
Re: [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface
Quoted 15 lines · Alexandre Courbot
Quoted 14 lines · Dave Airlie
Quoted 12 lines · Eliot Courtney
From: Joel Fernandes <[email protected]>
Add the BAR1 user interface for CPU access to GPU virtual memory through the BAR1 aperture.
Signed-off-by Joel Fernandes <[email protected]>[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 <[email protected]>---
Quoted 9 lines
Quoted 5 lines
BAR 1 and 2 need to be optionally detected and used. At least on SPARK there is only BAR0.
I've been playing with John's branch on spark and had to rework this code to make BAR 1 optional.
Thanks Dave - indeed we also hit an issue on a device where the FB console was enabled (?), which preventing BAR1 from being used.
That's different: another device driver was using the GPU. People should Kconfig their system to avoid having two device drivers trying to claim the same hardware.
Once Nova get a bit further along, it will be a non-issue too, because Nova can drive either an fbdev, or whatever the modern alternative to that is.
Quoted 2 lines
I know Eliot has a bunch of follow-ups in the pipe, Eliot can we make sure to dynamically detect and enable BAR1?
thanks,
Signature · 1 line
John Hubbard
Dave Airlie
maintainerRe: [PATCH 15/16] gpu: nova-core: mm: Add BAR1 user interface
Quoted 23 lines · John Hubbard
Quoted 21 lines · Alexandre Courbot
Quoted 19 lines · Dave Airlie
Quoted 6 lines · Eliot Courtney
From: Joel Fernandes <[email protected]>
Add the BAR1 user interface for CPU access to GPU virtual memory through the BAR1 aperture.
Quoted 6 lines
Signed-off-by Joel Fernandes <[email protected]>[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 <[email protected]>---
BAR 1 and 2 need to be optionally detected and used. At least on SPARK there is only BAR0.
I've been playing with John's branch on spark and had to rework this code to make BAR 1 optional.
Quoted 7 lines
Quoted 3 lines
Thanks Dave - indeed we also hit an issue on a device where the FB console was enabled (?), which preventing BAR1 from being used.
That's different: another device driver was using the GPU. People should
Kconfigtheir system to avoid having two device drivers trying to claim the same hardware.
At some point nova-core needs to call the remove_conflicting interface to make sure we kick off the overlapping drivers properly.
Quoted 8 lines
Once Nova get a bit further along, it will be a non-issue too, because Nova can drive either an fbdev, or whatever the modern alternative to that is.
Quoted 2 lines
I know Eliot has a bunch of follow-ups in the pipe, Eliot can we make sure to dynamically detect and enable BAR1?
Also I'm asking for this now as it it might be easier to make that sort of design decision earlier, rather than trying to revisit it later.
Dave.