gpu: nova-core: add PRAMIN window support
Subsystems (8)
v2 cover gpu: nova-core: add PRAMIN window support
This series adds support for the PRAMIN window, plus some documentation. Some of these patches were originally written by Joel Fernandes [1]. I have updated them with changelog notes in each patch. For example, I updated them for the newer IO machinery from Gary Guo.
This series adds a Pramin structure which deals with updating the PRAMIN window and handing out typed MMIO views. The PRAMIN window is a method that lets arbitrary VRAM be written over BAR0 by configuring a 1 MiB window through GPU registers. That 1 MiB window can point anywhere in VRAM. This is useful for bootstrapping e.g. GPU side page tables.
The Pramin structure hands out typed MMIO views to do writes through rather than letting callers write directly through it. A follow up series will add support for GPU side page table entry writing through this mechanism. This abstraction is important for later since we will eventually want to write the PTEs via BAR2 not PRAMIN - using a view that we grab from the Pramin structure can abstract this out.
[1]: https://lore.kernel.org/all/[email protected]/
This is based on drm-rust-next.
---
Changes in v2:
- Rebase onto Gary's IO register projection series
- Drop Region::try_subregion patch in favour of Gary's reg projection
- Convert Pramin code to use Gary's reg projection
- Fix const {assert!} -> const_assert! (Gary)
- Add #[inline] to shr_exact (Sashiko, Alex)
- Link to v1: https://patch.msgid.link/[email protected]
---
Eliot Courtney (6):
rust: num: use const_assert! in Bounded
rust: num: reject Bounded::shr overshifts at build time
rust: num: add Bounded::shr_exact
gpu: nova-core: mm: Implement Alignable and Debug for VramAddress
gpu: nova-core: mm: Add the memory management HAL
gpu: nova-core: Add self-test assertion macros and config option
Joel Fernandes (6):
gpu: nova-core: mm: Add VramAddress type
gpu: nova-core: mm: Add PRAMIN window registers
gpu: nova-core: mm: Add support to use PRAMIN windows to write to VRAM
docs: gpu: nova-core: Document the PRAMIN aperture mechanism
gpu: nova-core: mm: Add GpuMm centralized memory manager
gpu: nova-core: mm: Add PRAMIN aperture self-tests
Documentation/gpu/nova/core/pramin.rst | 128 +++++++++++++ Documentation/gpu/nova/index.rst | 1 + drivers/gpu/nova-core/Kconfig | 9 + drivers/gpu/nova-core/driver.rs | 3 + drivers/gpu/nova-core/gpu.rs | 30 ++- drivers/gpu/nova-core/gsp/commands.rs | 4 + drivers/gpu/nova-core/gsp/fw/commands.rs | 5 + drivers/gpu/nova-core/mm.rs | 163 ++++++++++++++++ drivers/gpu/nova-core/mm/hal.rs | 56 ++++++ drivers/gpu/nova-core/mm/hal/gb100.rs | 35 ++++ drivers/gpu/nova-core/mm/hal/gh100.rs | 35 ++++ drivers/gpu/nova-core/mm/hal/tu102.rs | 37 ++++ drivers/gpu/nova-core/mm/pramin.rs | 312 +++++++++++++++++++++++++++++++ drivers/gpu/nova-core/mm/regs.rs | 70 +++++++ drivers/gpu/nova-core/nova_core.rs | 3 + drivers/gpu/nova-core/selftest.rs | 64 +++++++ rust/kernel/num/bounded.rs | 36 +++- 17 files changed, 988 insertions(+), 3 deletions(-)
---
base-commit: 4c9ba407018e8deb06dbc643112bac8f40404f95
change-id: 20260804-pramin-split-950e210b6e3f
prerequisite-change-id: 20260721-typed_register-176eab3abee7:v2
prerequisite-patch-id: d58e4b8a0fabdeb9363b30f1aa28ca0d42d5190e
prerequisite-patch-id: 5f0c85c6bea0600a4b0bd28b389351e71010a846
prerequisite-patch-id: 8094bc0f51da3764837321c84d71d9c49ac2ac3f
prerequisite-patch-id: cc38839e9c3d9866bd889d89b7e2fdfe609ffc5b
prerequisite-patch-id: 2e919d4f6db02e9d9ed51081a1a803b12f67535f
prerequisite-patch-id: af8a6b3f4bed0953fa8d8f7c1b9e52d746aeb6b2
prerequisite-patch-id: 131291b0a4dc1ee7e43dd038f6f99fc5dc0eb99b
prerequisite-patch-id: 12288c2ebdd58989c5fdabab6237137dd12da566
prerequisite-patch-id: 8224018b7cfec0b00cce46b238abd9f68240e187
prerequisite-patch-id: c7676cbc77ff50b2b7bf13b28c8b7c971285cc9d
prerequisite-patch-id: 1aaed2df7816f907a9403d693be068ddc9a2e43c
prerequisite-patch-id: 04d879d32289f6d715c97ba0cc94b5e94371cc92
prerequisite-patch-id: 127be60ba6331574f6784cc8a5013d4f91b47df4
prerequisite-patch-id: 97fde91d1a5eb35efbbd43e99f595d8bba844cb5
prerequisite-patch-id: 77292e35e0b794e12c0ba7eea16f89c76d899757
prerequisite-patch-id: 95bfd46c2861a2da0179630b02565398d79d55a3
Best regards,
Signature · 1 line
Eliot Courtney <[email protected]>
PATCH v2 1/12 rust: num: use const_assert! in Bounded
Convert the const-block asserts in bounded.rs to const_assert!, matching the rest of the file.
--- rust/kernel/num/bounded.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
rust/kernel/num/bounded.rs +2 -2
@@ -485,7 +485,7 @@ pub fn cast<U>(self) -> Bounded<U, N>/// assert_eq!(v_shifted.get(), 0xff); /// ``` pub fn shr <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES > { -const {assert! (RES +SHIFT >=N ) } +const_assert! (RES +SHIFT >=N );// SAFETY: We shift the value right by `SHIFT`, reducing the number of bits needed to // represent the shifted value by as much, and just asserted that `RES >= N - SHIFT`.
@@ -506,7 +506,7 @@ pub fn shr<const SHIFT: u32, const RES: u32>(self) -> Bounded<T, RES> {/// assert_eq!(v_shifted.get(), 0xff00); /// ``` pub fn shl <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES > { -const {assert! (RES >=N +SHIFT ) } +const_assert! (RES >=N +SHIFT );// SAFETY: We shift the value left by `SHIFT`, augmenting the number of bits needed to // represent the shifted value by as much, and just asserted that `RES >= N + SHIFT`.
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 01/12] rust: num: use const_assert! in Bounded
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
Pre-existing issues:
- [Critical] This problem wasn't introduced by this patch, but Bounded::shr lacks a bound check for SHIFT < T::BITS, allowing wrapping shifts that break safety invariants and lead to Undefined Behavior. --
--- Patch [1]: [PATCH v2 01/12] rust: num: use const_assert! in Bounded --- commit afcfa782abd748c8cc818867c320e813e00f8278
Author: Eliot Courtney <[email protected]>
rust: num: use const_assert! in Bounded
This patch converts the const-block asserts in bounded.rs to use the const_assert! macro, matching the styling in the rest of the file.
rust/kernel/num/bounded.rs pub fn cast<U>(self) -> Bounded<U, N> · line 488
Quoted 10 lines
rust/kernel/num/bounded.rs +1
-1@@ -485,7 +485,7 @@ pub fn cast<U>(self) -> Bounded<U, N>/// assert_eq!(v_shifted.get(), 0xff); /// ``` pub fn shr <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES > { -const {assert! (RES +SHIFT >=N ) } +const_assert! (RES +SHIFT >=N );
[Severity: Critical]
This isn't a bug introduced by this patch, but does Bounded::shr lack a bounds check for SHIFT being less than the number of bits in the type?
If a caller invokes Bounded::shr with a SHIFT value greater than or equal to the bit width of the type, the shift amount can be masked in release builds without overflow checks. This would leave the original value unchanged.
Because the condition RES + SHIFT >= N would still be satisfied, this unchanged value is unsafely wrapped in the returned Bounded type. If the value exceeds RES bits, it breaks the safety invariant of the struct. Subsequent safe calls like Bounded::cast could then trigger undefined behavior when encountering unwrap_unchecked on a failed try_from conversion.
Could we add an additional bounds check here to prevent wrapping shifts?
Quoted 3 lines
rust/kernel/num/bounded.rs +0
-0// SAFETY: We shift the value right by `SHIFT`, reducing the number of bits needed to // represent the shifted value by as much, and just asserted that `RES >= N - SHIFT`.
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Re: [PATCH v2 01/12] rust: num: use const_assert! in Bounded
In reply to Eliot CourtneyQuoted 4 lines · Eliot Courtney
Convert the const-block asserts in
bounded.rstoconst_assert!, matching the rest of the file.Signed-off-by Eliot Courtney <[email protected]>
Quoted 3 lines
--- rust/kernel/num/bounded.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
Re: [PATCH v2 01/12] rust: num: use const_assert! in Bounded
In reply to Eliot CourtneyQuoted 4 lines · Eliot Courtney
Convert the const-block asserts in
bounded.rstoconst_assert!, matching the rest of the file.Signed-off-by Eliot Courtney <[email protected]>
Re: [PATCH v2 01/12] rust: num: use const_assert! in Bounded
In reply to Eliot CourtneyQuoted 4 lines · Eliot Courtney
Convert the const-block asserts in
bounded.rstoconst_assert!, matching the rest of the file.Signed-off-by Eliot Courtney <[email protected]>
Alexandre Courbot
maintainerRe: [PATCH v2 01/12] rust: num: use const_assert! in Bounded
Quoted 7 lines · Alexandre Courbot
Quoted 4 lines · Eliot Courtney
Convert the const-block asserts in
bounded.rstoconst_assert!, matching the rest of the file.Signed-off-by Eliot Courtney <[email protected]>
Errr this is already in rust-next, never mind! :)
PATCH v2 2/12 rust: num: reject Bounded::shr overshifts at build time
In reply to Eliot CourtneyMake shr reject shifts of at least the type's bit width at build time, instead of panicking or masking the shift amount at runtime.
--- rust/kernel/num/bounded.rs | 1 + 1 file changed, 1 insertion(+)
rust/kernel/num/bounded.rs +1 -0
@@ -485,6 +485,7 @@ pub fn cast<U>(self) -> Bounded<U, N>/// assert_eq!(v_shifted.get(), 0xff); /// ``` pub fn shr <const SHIFT :u32 ,const RES :u32 >(self) ->Bounded <T ,RES > { +const_assert! (SHIFT <T ::BITS );const_assert! (RES +SHIFT >=N );// SAFETY: We shift the value right by `SHIFT`, reducing the number of bits needed to
Signature · 1 line
2.55.0
Re: [PATCH v2 02/12] rust: num: reject Bounded::shr overshifts at build time
Quoted 5 lines · Eliot Courtney
Make
shrreject shifts of at least the type's bit width at build time, instead of panicking or masking the shift amount at runtime.Signed-off-by Eliot Courtney <[email protected]>
Quoted 3 lines
--- rust/kernel/num/bounded.rs | 1 + 1 file changed, 1 insertion(+)
Re: [PATCH v2 02/12] rust: num: reject Bounded::shr overshifts at build time
In reply to Eliot CourtneyQuoted 5 lines · Eliot Courtney
Make
shrreject shifts of at least the type's bit width at build time, instead of panicking or masking the shift amount at runtime.Signed-off-by Eliot Courtney <[email protected]>
PATCH v2 3/12 rust: num: add Bounded::shr_exact
In reply to Eliot CourtneyAdd shr_exact in the vein of try_shrink which shifts a bounded right only if it loses no set bits. This is useful for getting a shifted down integer while simultaneously checking that it's aligned.
--- rust/kernel/num/bounded.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+)
rust/kernel/num/bounded.rs +31 -0
@@ -493,6 +493,37 @@ pub fn shr<const SHIFT: u32, const RES: u32>(self) -> Bounded<T, RES> {unsafe {Bounded ::__new (self.0 >>SHIFT ) } } +/// Right-shifts `self` by `SHIFT` if that loses no set bits, and returns the result as a +/// `Bounded<_, RES>`, where `RES >= N - SHIFT`. +/// +/// Returns [`None`] if any of the `SHIFT` least significant bits of `self` is set. +/// +/// # Examples +/// +/// ``` +/// use kernel::num::Bounded; +/// +/// let v = Bounded::<u32, 16>::new::<0xff00>(); +/// let v_shifted: Option<Bounded<u32, 8>> = v.shr_exact::<8, _>(); +/// +/// assert_eq!(v_shifted.map(|v| v.get()), Some(0xff)); +/// +/// // A set bit would be shifted out. +/// let v = Bounded::<u32, 16>::new::<0xff01>(); +/// let v_shifted: Option<Bounded<u32, 8>> = v.shr_exact::<8, _>(); +/// +/// assert!(v_shifted.is_none()); +/// ``` +#[inline] +pub fn shr_exact <const SHIFT :u32 ,const RES :u32 >(self) ->Option <Bounded <T ,RES >> { +let shifted = self.shr ::<SHIFT ,RES >(); +if shifted.get () <<SHIFT == self.0 { +Some (shifted) + }else { +None + } + } +/// Left-shifts `self` by `SHIFT` and returns the result as a `Bounded<_, RES>`, where `RES >= /// N + SHIFT`. ///
Signature · 1 line
2.55.0
Re: [PATCH v2 03/12] rust: num: add Bounded::shr_exact
Quoted 6 lines · Eliot Courtney
Add
shr_exactin the vein oftry_shrinkwhich shifts a bounded right only if it loses no set bits. This is useful for getting a shifted down integer while simultaneously checking that it's aligned.Signed-off-by Eliot Courtney <[email protected]>
PATCH v2 4/12 gpu: nova-core: mm: Add VramAddress type
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
Add the VramAddress type representing a physical address in VRAM. Also add an arithmetic helper, comparison, and operator overloads which are required in later patches for address arithmetic.
--- drivers/gpu/nova-core/mm.rs | 60 ++++++++++++++++++++++++++++++++++++++ drivers/gpu/nova-core/nova_core.rs | 1 + 2 files changed, 61 insertions(+)
drivers/gpu/nova-core/mm.rs new file +60 -0
@@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Memory management subsystems. + +#![expect(dead_code)] + +use core::{ + fmt::LowerHex , + ops,// +}; + +use kernel::fmt; + +/// Physical VRAM address in GPU video memory. +#[derive( Clone , Copy , PartialEq , Eq , PartialOrd , Ord )] +#[repr(transparent)] +pub (crate )struct VramAddress (u64 ); + +impl VramAddress { +/// Creates an address from a raw value. +pub (crate )const fn from_raw (addr:u64 ) ->Self { +Self (addr) + } + +/// Returns the address as a raw value. +pub (crate )const fn into_raw (self) ->u64 { + self.0 + } + +/// Adds `rhs` to this address, returning [`None`] on overflow. +pub (crate )const fn checked_add (self, rhs:u64 ) ->Option <Self > { +match self.into_raw ().checked_add (rhs) { +Some (addr) =>Some (Self ::from_raw (addr)), +None =>None , + } + } +} + +impl LowerHex for VramAddress { +fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { +LowerHex ::fmt (&self.into_raw (), f) + } +} + +impl ops::Add <u64 >for VramAddress { +type Output =Self ; + +fn add (self, rhs:u64 ) ->Self ::Output { +Self ::from_raw (self.into_raw () + rhs) + } +} + +impl ops::Sub for VramAddress { +type Output =u64 ; + +fn sub (self, rhs:Self ) ->Self ::Output { + self.into_raw () - rhs.into_raw () + } +}
drivers/gpu/nova-core/nova_core.rs +1 -0
@@ -18,6 +18,7 @@mod gpu;mod gsp;mod mctp; +mod mm;#[macro_use] mod num;mod regs;
Signature · 1 line
2.55.0
Danilo Krummrich
maintainerRe: [PATCH v2 04/12] gpu: nova-core: mm: Add VramAddress type
drivers/gpu/nova-core/mm.rs line 18
Quoted 4 lines · Eliot Courtney
drivers/gpu/nova-core/mm.rs new file +4
-0+/// Physical VRAM address in GPU video memory. +#[derive( Clone , Copy , PartialEq , Eq , PartialOrd , Ord )] +#[repr(transparent)] +pub (crate )struct VramAddress (u64 );
Let's move this into generic code, maybe rust/kernel/gpu/types.rs? I wouldn't mind doing this as a follow-up though. Will go over the rest of the series soon.
Thanks,
Danilo
Re: [PATCH v2 04/12] gpu: nova-core: mm: Add VramAddress type
In reply to Eliot CourtneyOn 2026-08-10 at 23:55 +1000, Eliot Courtney <[email protected]> wrote...
Quoted 33 lines
From: Joel Fernandes <[email protected]>
Add the
VramAddresstype representing a physical address in VRAM. Also add an arithmetic helper, comparison, and operator overloads which are required in later patches for address arithmetic.Signed-off-by Joel Fernandes <[email protected]>[ecourtney: create mm.rs here, squashing in the arithmetic patch][ecourtney: splice the two commit bodies][ecourtney: drop the Pfn fields, open-coding what bitfield! generated][ecourtney: drop align_down and the IntoVramOffset/IntoVramRange traits][ecourtney: make checked_add() const over a plain u64, derive the ordering][ecourtney: doc wording, header, import, and signature cleanups]Signed-off-by Eliot Courtney <[email protected]>--- drivers/gpu/nova-core/mm.rs | 60 ++++++++++++++++++++++++++++++++++++++ drivers/gpu/nova-core/nova_core.rs | 1 + 2 files changed, 61 insertions(+)drivers/gpu/nova-core/mm.rs new file +8
-0@@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Memory management subsystems. + +#![expect(dead_code)] + +use core::{
drivers/gpu/nova-core/mm.rs line 18
Quoted 10 lines
drivers/gpu/nova-core/mm.rs new file +10
-0+ fmt::LowerHex, + ops, // +}; + +use kernel::fmt; + +/// Physical VRAM address in GPU video memory. +#[derive( Clone , Copy , PartialEq , Eq , PartialOrd , Ord )] +#[repr(transparent)] +pub (crate )struct VramAddress (u64 );
Is this the best type here, or should this be bounded via runtime checking to ensure it refers to a valid address?
I was going to ask if it should be bounded to reflect the physical addressing capabilities of the GPU in question, but that would actually need to be a different type as GPU physical addresses might not even refer to local vidmem.
Although I think that's a concern for future series - AFAIK PRAMIN can only access local VRAM.
Quoted 58 lines
drivers/gpu/nova-core/mm.rs new file +42
-0+ +impl VramAddress { +/// Creates an address from a raw value. +pub (crate )const fn from_raw (addr:u64 ) ->Self { +Self (addr) + } + +/// Returns the address as a raw value. +pub (crate )const fn into_raw (self) ->u64 { + self.0 + } + +/// Adds `rhs` to this address, returning [`None`] on overflow. +pub (crate )const fn checked_add (self, rhs:u64 ) ->Option <Self > { +match self.into_raw ().checked_add (rhs) { +Some (addr) =>Some (Self ::from_raw (addr)), +None =>None , + } + } +} + +impl LowerHex for VramAddress { +fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { +LowerHex ::fmt (&self.into_raw (), f) + } +} + +impl ops::Add <u64 >for VramAddress { +type Output =Self ; + +fn add (self, rhs:u64 ) ->Self ::Output { +Self ::from_raw (self.into_raw () + rhs) + } +} + +impl ops::Sub for VramAddress { +type Output =u64 ; + +fn sub (self, rhs:Self ) ->Self ::Output { + self.into_raw () - rhs.into_raw () + } +}drivers/gpu/nova-core/nova_core.rs +1
-0@@ -18,6 +18,7 @@mod gpu;mod gsp;mod mctp; +mod mm;#[macro_use] mod num;mod regs;Signature · 2 lines
-- 2.55.0
Re: [PATCH v2 04/12] gpu: nova-core: mm: Add VramAddress type
Quoted 48 lines · Alistair Popple
On 2026-08-10 at 23:55 +1000, Eliot Courtney <[email protected]> wrote...
Quoted 33 lines
From: Joel Fernandes <[email protected]>
Add the
VramAddresstype representing a physical address in VRAM. Also add an arithmetic helper, comparison, and operator overloads which are required in later patches for address arithmetic.Signed-off-by Joel Fernandes <[email protected]>[ecourtney: create mm.rs here, squashing in the arithmetic patch][ecourtney: splice the two commit bodies][ecourtney: drop the Pfn fields, open-coding what bitfield! generated][ecourtney: drop align_down and the IntoVramOffset/IntoVramRange traits][ecourtney: make checked_add() const over a plain u64, derive the ordering][ecourtney: doc wording, header, import, and signature cleanups]Signed-off-by Eliot Courtney <[email protected]>--- drivers/gpu/nova-core/mm.rs | 60 ++++++++++++++++++++++++++++++++++++++ drivers/gpu/nova-core/nova_core.rs | 1 + 2 files changed, 61 insertions(+)drivers/gpu/nova-core/mm.rs new file +8
-0@@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Memory management subsystems. + +#![expect(dead_code)] + +use core::{drivers/gpu/nova-core/mm.rs line 18
Quoted 10 lines
drivers/gpu/nova-core/mm.rs new file +10
-0+ fmt::LowerHex, + ops, // +}; + +use kernel::fmt; + +/// Physical VRAM address in GPU video memory. +#[derive( Clone , Copy , PartialEq , Eq , PartialOrd , Ord )] +#[repr(transparent)] +pub (crate )struct VramAddress (u64 );Is this the best type here, or should this be bounded via runtime checking to ensure it refers to a valid address?
Quoted 6 lines
I was going to ask if it should be bounded to reflect the physical addressing capabilities of the GPU in question, but that would actually need to be a different type as GPU physical addresses might not even refer to local vidmem.
Although I think that's a concern for future series - AFAIK PRAMIN can only access local VRAM.
Yeah good question. I am looking at memory management stuff after this, and e.g. how many bits the hardware actually accept for physical addresses (e.g. page table structures) is different depending on the hardware. So it's not trivial to determine if the address is valid without a bunch of extra info.
So the approach here IMO is just to tag it as a general VRAM address at the type level and gradually apply runtime checks to narrow the type into code that is more specific. Since our HALs use dynamic dispatch based on the chipid we can't avoid some kind of runtime checks here anyway.
I think it makes sense to say VramAddress is a local vidmem address, and later we could e.g. add an enum to distinguish local vidmem, sysmem, peer memory etc. This appears to be essentially what UVM does (uvm_gpu_phys_address_t), AFAICT. What do you think?
And yeah I believe PRAMIN can only access local VRAM and sysmem (on pre hopper).
Quoted 59 lines
Quoted 59 lines
drivers/gpu/nova-core/mm.rs new file +42
-0+ +impl VramAddress { +/// Creates an address from a raw value. +pub (crate )const fn from_raw (addr:u64 ) ->Self { +Self (addr) + } + +/// Returns the address as a raw value. +pub (crate )const fn into_raw (self) ->u64 { + self.0 + } + +/// Adds `rhs` to this address, returning [`None`] on overflow. +pub (crate )const fn checked_add (self, rhs:u64 ) ->Option <Self > { +match self.into_raw ().checked_add (rhs) { +Some (addr) =>Some (Self ::from_raw (addr)), +None =>None , + } + } +} + +impl LowerHex for VramAddress { +fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { +LowerHex ::fmt (&self.into_raw (), f) + } +} + +impl ops::Add <u64 >for VramAddress { +type Output =Self ; + +fn add (self, rhs:u64 ) ->Self ::Output { +Self ::from_raw (self.into_raw () + rhs) + } +} + +impl ops::Sub for VramAddress { +type Output =u64 ; + +fn sub (self, rhs:Self ) ->Self ::Output { + self.into_raw () - rhs.into_raw () + } +}drivers/gpu/nova-core/nova_core.rs +1
-0@@ -18,6 +18,7 @@mod gpu;mod gsp;mod mctp; +mod mm;#[macro_use] mod num;mod regs;Signature · 2 lines
-- 2.55.0
Re: [PATCH v2 04/12] gpu: nova-core: mm: Add VramAddress type
On 2026-08-17 at 18:20 +1000, Eliot Courtney <[email protected]> wrote...
Quoted 68 lines · Alistair Popple
Quoted 48 lines
On 2026-08-10 at 23:55 +1000, Eliot Courtney <[email protected]> wrote...
Quoted 33 lines
From: Joel Fernandes <[email protected]>
Add the
VramAddresstype representing a physical address in VRAM. Also add an arithmetic helper, comparison, and operator overloads which are required in later patches for address arithmetic.Signed-off-by Joel Fernandes <[email protected]>[ecourtney: create mm.rs here, squashing in the arithmetic patch][ecourtney: splice the two commit bodies][ecourtney: drop the Pfn fields, open-coding what bitfield! generated][ecourtney: drop align_down and the IntoVramOffset/IntoVramRange traits][ecourtney: make checked_add() const over a plain u64, derive the ordering][ecourtney: doc wording, header, import, and signature cleanups]Signed-off-by Eliot Courtney <[email protected]>--- drivers/gpu/nova-core/mm.rs | 60 ++++++++++++++++++++++++++++++++++++++ drivers/gpu/nova-core/nova_core.rs | 1 + 2 files changed, 61 insertions(+)drivers/gpu/nova-core/mm.rs new file +8
-0@@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Memory management subsystems. + +#![expect(dead_code)] + +use core::{drivers/gpu/nova-core/mm.rs line 18
Quoted 10 lines
drivers/gpu/nova-core/mm.rs new file +10
-0+ fmt::LowerHex, + ops, // +}; + +use kernel::fmt; + +/// Physical VRAM address in GPU video memory. +#[derive( Clone , Copy , PartialEq , Eq , PartialOrd , Ord )] +#[repr(transparent)] +pub (crate )struct VramAddress (u64 );Is this the best type here, or should this be bounded via runtime checking to ensure it refers to a valid address?
Quoted 6 lines
I was going to ask if it should be bounded to reflect the physical addressing capabilities of the GPU in question, but that would actually need to be a different type as GPU physical addresses might not even refer to local vidmem.
Although I think that's a concern for future series - AFAIK PRAMIN can only access local VRAM.
Yeah good question. I am looking at memory management stuff after this, and e.g. how many bits the hardware actually accept for physical addresses (e.g. page table structures) is different depending on the hardware. So it's not trivial to determine if the address is valid without a bunch of extra info.
So the approach here IMO is just to tag it as a general VRAM address at the type level and gradually apply runtime checks to narrow the type into code that is more specific. Since our HALs use dynamic dispatch based on the chipid we can't avoid some kind of runtime checks here anyway.
Quoted 4 lines
I think it makes sense to say VramAddress is a local vidmem address, and later we could e.g. add an enum to distinguish local vidmem, sysmem, peer memory etc. This appears to be essentially what UVM does (
uvm_gpu_phys_address_t), AFAICT. What do you think?
Yeah, after reading the rest of the series I think this is where I landed as well - VramAddress as a local vidmem address that we use as one component when building up the more complicated physical address. As much as anything though just wanted to check we weren't accidentally conflating this with physical addressing which is more complicated than just VramAddress.
Also seeing as you've obviously been looking at UVM source it's worth noting that UVM's physical address type is not exhaustive either as it currently only deals with some aspects of physical memory addressing and leaves the rest to RM.
Quoted 63 lines
And yeah I believe PRAMIN can only access local VRAM and sysmem (on pre hopper).
Quoted 59 lines
Quoted 59 lines
drivers/gpu/nova-core/mm.rs new file +42
-0+ +impl VramAddress { +/// Creates an address from a raw value. +pub (crate )const fn from_raw (addr:u64 ) ->Self { +Self (addr) + } + +/// Returns the address as a raw value. +pub (crate )const fn into_raw (self) ->u64 { + self.0 + } + +/// Adds `rhs` to this address, returning [`None`] on overflow. +pub (crate )const fn checked_add (self, rhs:u64 ) ->Option <Self > { +match self.into_raw ().checked_add (rhs) { +Some (addr) =>Some (Self ::from_raw (addr)), +None =>None , + } + } +} + +impl LowerHex for VramAddress { +fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { +LowerHex ::fmt (&self.into_raw (), f) + } +} + +impl ops::Add <u64 >for VramAddress { +type Output =Self ; + +fn add (self, rhs:u64 ) ->Self ::Output { +Self ::from_raw (self.into_raw () + rhs) + } +} + +impl ops::Sub for VramAddress { +type Output =u64 ; + +fn sub (self, rhs:Self ) ->Self ::Output { + self.into_raw () - rhs.into_raw () + } +}drivers/gpu/nova-core/nova_core.rs +1
-0@@ -18,6 +18,7 @@mod gpu;mod gsp;mod mctp; +mod mm;#[macro_use] mod num;mod regs;Signature · 2 lines
-- 2.55.0
PATCH v2 5/12 gpu: nova-core: mm: Implement Alignable and Debug for VramAddress
In reply to Eliot CourtneyLater patches align VRAM addresses down to the PRAMIN window. Implement Alignable trait for VramAddress and plus add a ZERO constant.
Also print the address in hex under {:?}, so it reads well in debug output.
--- drivers/gpu/nova-core/mm.rs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/mm.rs +27 -1
@@ -10,7 +10,14 @@ ops, // }; -use kernel::fmt; +use kernel::{ + fmt, + prelude::*, + ptr::{ +Alignable , +Alignment ,// + }, +};/// Physical VRAM address in GPU video memory. #[derive( Clone , Copy , PartialEq , Eq , PartialOrd , Ord )]
@@ -18,6 +25,9 @@pub (crate )struct VramAddress (u64 );impl VramAddress { +/// The zero address. +pub (crate )const ZERO :Self =Self ::from_raw (0 ); +/// Creates an address from a raw value. pub (crate )const fn from_raw (addr:u64 ) ->Self {Self (addr)
@@ -37,12 +47,28 @@ pub(crate) const fn checked_add(self, rhs: u64) -> Option<Self> { } } +impl Alignable for VramAddress { +fn align_down (self, alignment:Alignment ) ->Self { +Self ::from_raw (self.into_raw ().align_down (alignment)) + } + +fn align_up (self, alignment:Alignment ) ->Option <Self > { + self.into_raw ().align_up (alignment).map (Self ::from_raw) + } +} +impl LowerHex for VramAddress {fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result {LowerHex ::fmt (&self.into_raw (), f) } } +impl fmt::Debug for VramAddress { +fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { + f.write_fmt (fmt! ("{:#x}" , self)) + } +} +impl ops::Add <u64 >for VramAddress {type Output =Self ;
Signature · 1 line
2.55.0
PATCH v2 6/12 gpu: nova-core: mm: Add PRAMIN window registers
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
PRAMIN apertures are a crucial mechanism for direct CPU read/write to VRAM. Add the BAR0 window registers that position the PRAMIN aperture on all supported GPU architectures: Turing, Ampere, Ada (via NV_PBUS_BAR0_WINDOW), Hopper (via gh100::NV_XAL_EP_BAR0_WINDOW), and Blackwell (via gb100::NV_XAL_EP_BAR0_WINDOW).
Hopper/Blackwell window-base registers are based on Eliot Courtney's offlist reference patch.
--- drivers/gpu/nova-core/mm.rs | 2 ++ drivers/gpu/nova-core/mm/regs.rs | 70 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+)
drivers/gpu/nova-core/mm.rs +2 -0
@@ -19,6 +19,8 @@ }, }; +mod regs; +/// Physical VRAM address in GPU video memory. #[derive( Clone , Copy , PartialEq , Eq , PartialOrd , Ord )] #[repr(transparent)]
drivers/gpu/nova-core/mm/regs.rs new file +70 -0
70 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 7/12 gpu: nova-core: mm: Add the memory management HAL
In reply to Eliot CourtneyPositioning the PRAMIN window requires writing an architecture-specific
register: NV_PBUS_BAR0_WINDOW on Turing, Ampere and Ada, and NV_XAL_EP_BAR0_WINDOW with a different field width on Hopper and on Blackwell.
A MmHal trait with one implementation per hardware family hides the register choice from the rest of the mm code, matching the layout of the driver's other HALs.
--- drivers/gpu/nova-core/mm.rs | 1 + drivers/gpu/nova-core/mm/hal.rs | 56 +++++++++++++++++++++++++++++++++++ drivers/gpu/nova-core/mm/hal/gb100.rs | 35 ++++++++++++++++++++++ drivers/gpu/nova-core/mm/hal/gh100.rs | 35 ++++++++++++++++++++++ drivers/gpu/nova-core/mm/hal/tu102.rs | 37 +++++++++++++++++++++++ 5 files changed, 164 insertions(+)
drivers/gpu/nova-core/mm.rs +1 -0
@@ -19,6 +19,7 @@ }, }; +mod hal;mod regs;/// Physical VRAM address in GPU video memory.
drivers/gpu/nova-core/mm/hal.rs new file +56 -0
56 lines not on this page · raw message
drivers/gpu/nova-core/mm/hal/gb100.rs new file +35 -0
@@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Blackwell GB10x/GB20x memory management HAL. + +use kernel::{ + io::Io , + prelude::*,// +}; + +use crate ::{ + driver::Bar0 , + mm::{ + hal::{ + window_base, +MmHal ,// + }, + regs, +VramAddress ,// + }, +}; + +struct Gb100 ; + +impl MmHal for Gb100 { +fn write_pramin_window_base (&self, bar:Bar0 <'_>, base:VramAddress ) ->Result { + bar.write_reg ( + regs::gb100::NV_XAL_EP_BAR0_WINDOW ::zeroed ().with_base (window_base (base)?.cast ()), + ); +Ok (()) + } +} + +const GB100 :Gb100 =Gb100 ; +pub (super )const GB100_HAL : &dyn MmHal = &GB100 ;
drivers/gpu/nova-core/mm/hal/gh100.rs new file +35 -0
@@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Hopper memory management HAL. + +use kernel::{ + io::Io , + prelude::*,// +}; + +use crate ::{ + driver::Bar0 , + mm::{ + hal::{ + window_base, +MmHal ,// + }, + regs, +VramAddress ,// + }, +}; + +struct Gh100 ; + +impl MmHal for Gh100 { +fn write_pramin_window_base (&self, bar:Bar0 <'_>, base:VramAddress ) ->Result { + bar.write_reg ( + regs::gh100::NV_XAL_EP_BAR0_WINDOW ::zeroed ().with_base (window_base (base)?.cast ()), + ); +Ok (()) + } +} + +const GH100 :Gh100 =Gh100 ; +pub (super )const GH100_HAL : &dyn MmHal = &GH100 ;
drivers/gpu/nova-core/mm/hal/tu102.rs new file +37 -0
@@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Turing, Ampere and Ada memory management HAL. + +use kernel::{ + io::Io , + prelude::*,// +}; + +use crate ::{ + driver::Bar0 , + mm::{ + hal::{ + window_base, +MmHal ,// + }, + regs, +VramAddress ,// + }, +}; + +struct Tu102 ; + +impl MmHal for Tu102 { +fn write_pramin_window_base (&self, bar:Bar0 <'_>, base:VramAddress ) ->Result { + bar.write_reg ( + regs::NV_PBUS_BAR0_WINDOW ::zeroed () + .with_target (regs::Bar0WindowTarget ::VidMem ) + .with_base (window_base (base)?.cast ()), + ); +Ok (()) + } +} + +const TU102 :Tu102 =Tu102 ; +pub (super )const TU102_HAL : &dyn MmHal = &TU102 ;
Signature · 1 line
2.55.0
PATCH v2 8/12 gpu: nova-core: mm: Add support to use PRAMIN windows to write to VRAM
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
PRAMIN apertures are a crucial mechanism for direct CPU read/write to VRAM. Add a Pramin manager whose window_at() returns a typed MMIO view of VRAM through the 1 MiB PRAMIN aperture in BAR0, validating the view against the VRAM region and repositioning the window as needed for the accessed address.
A view borrows Pramin mutably, so the window cannot move while the view is in use, and it inserts an ordering point on Drop.
--- drivers/gpu/nova-core/mm.rs | 1 + drivers/gpu/nova-core/mm/pramin.rs | 178 +++++++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+)
drivers/gpu/nova-core/mm.rs +1 -0
@@ -20,6 +20,7 @@ };mod hal; +mod pramin;mod regs;/// Physical VRAM address in GPU video memory.
drivers/gpu/nova-core/mm/pramin.rs new file +178 -0
178 lines not on this page · raw message
Signature · 1 line
2.55.0
Re: [PATCH v2 08/12] gpu: nova-core: mm: Add support to use PRAMIN windows to write to VRAM
On 2026-08-10 at 23:55 +1000, Eliot Courtney <[email protected]> wrote...
Quoted 87 lines
From: Joel Fernandes <[email protected]>
PRAMIN apertures are a crucial mechanism for direct CPU read/write to VRAM. Add a
Praminmanager whosewindow_at()returns a typed MMIO view of VRAM through the 1 MiB PRAMIN aperture in BAR0, validating the view against the VRAM region and repositioning the window as needed for the accessed address.A view borrows
Praminmutably, so the window cannot move while the view is in use, and it inserts an ordering point on Drop.Signed-off-by Joel Fernandes <[email protected]>[ecourtney: split the registers and HAL into the two preceding patches][ecourtney: rebase w.r.t. Bar0 lifetime changes and register projections][ecourtney: drop the window guard and mutex, use &mut self][ecourtney: position at init to avoid reads, reposition in window_offset][ecourtney: return typed MMIO views instead of read/write accessors][ecourtney: insert an ordering read when a view drops][ecourtney: declare the window location, drop the doc examples][ecourtney: add the copyright header, doc and naming cleanups][ecourtney: the pramin module is mm-internal]Co-developed-by Eliot Courtney <[email protected]>Signed-off-by Eliot Courtney <[email protected]>--- drivers/gpu/nova-core/mm.rs | 1 + drivers/gpu/nova-core/mm/pramin.rs | 178 +++++++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+)drivers/gpu/nova-core/mm.rs +1
-0@@ -20,6 +20,7 @@ };mod hal; +mod pramin;mod regs;/// Physical VRAM address in GPU video memory. drivers/gpu/nova-core/mm/pramin.rs new file +41
-0@@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Utilities for accessing VRAM through the PRAMIN window. + +use core::ops::Range ; + +use kernel::{ + io::{ + io_project, + register, + register::OffsetLoc , +Io , +Mmio ,// + }, + prelude::*, + ptr::{ +Alignable , +Alignment ,// + }, + sizes::{ +SZ_1M , +SZ_64K ,// + }, +}; + +use crate ::{ + driver::{ +Bar0 , +NovaRegisters ,// + }, + gpu::Chipset , + mm::{ + hal::{ + self, +MmHal ,// + }, +VramAddress ,// + }, + num::IntoSafeCast ,// +};
drivers/gpu/nova-core/mm/pramin.rs line 51
Quoted 10 lines
drivers/gpu/nova-core/mm/pramin.rs new file +10
-0+ +/// Size of the PRAMIN window (1 MiB). +const WINDOW_SIZE :usize =SZ_1M ; + +/// The PRAMIN window, which is a 1 MiB window into VRAM at a fixed BAR0 offset. +#[derive( FromBytes , IntoBytes )] +struct PraminWindow ([u8 ;WINDOW_SIZE ]); + +register! { + base:NovaRegisters ;
I tried building this on drm-rust-next against the base commit (4c9ba407018e8deb06dbc643112bac8f40404f95) but am getting some build errors:
error: no rules expected :
--> /data/source/linux/drivers/gpu/nova-core/mm/pramin.rs:51:9
|
51 | base: NovaRegisters;
| ^ no rules expected this token in macro call
|
note: while trying to match `(`
--> /data/source/linux/rust/kernel/io/register.rs:809:52
|
809 | $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty)
| ^I'm guessing maybe because this depends on some other series that isn't in drm-rust-next or something in drm-rust-next has changed things here.
There are a couple of others with this series applied as well:
error: no rules expected build
--> /data/source/linux/drivers/gpu/nova-core/mm/pramin.rs:115:39
|
115 | let window = io_project!(bar, build: PRAMIN);
| ^^^^^ no rules expected this token in macro call
|
note: while trying to match `,`
--> /data/source/linux/rust/kernel/ptr/projection.rs:319:21
|
319 | (@gen $ptr:ident, ) => {};
| ^error: no rules expected reserved keyword try
--> /data/source/linux/drivers/gpu/nova-core/mm/pramin.rs:174:45
|
174 | let view = io_project!(self.window, try: OffsetLoc::new(offset));
| ^^^ no rules expected this token in macro call
|
note: while trying to match `,`
--> /data/source/linux/rust/kernel/ptr/projection.rs:319:21
|
319 | (@gen $ptr:ident, ) => {};
| ^error: no rules expected :
--> /data/source/linux/drivers/gpu/nova-core/mm/regs.rs:29:9
|
29 | base: NovaRegisters;
| ^ no rules expected this token in macro call
|
note: while trying to match `(`
--> /data/source/linux/rust/kernel/io/register.rs:809:52
|
809 | $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty)
| ^error: no rules expected :
--> /data/source/linux/drivers/gpu/nova-core/mm/regs.rs:46:13
|
46 | base: NovaRegisters;
| ^ no rules expected this token in macro call
|
note: while trying to match `(`
--> /data/source/linux/rust/kernel/io/register.rs:809:52
|
809 | $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty)
| ^error: no rules expected :
--> /data/source/linux/drivers/gpu/nova-core/mm/regs.rs:62:13
|
62 | base: NovaRegisters;
| ^ no rules expected this token in macro call
|
note: while trying to match `(`
--> /data/source/linux/rust/kernel/io/register.rs:809:52
|
809 | $(#[$attr:meta])* $vis:vis $name:ident ($storage:ty)
| ^error: aborting due to 6 previous errors
- Alistair
Quoted 131 lines
drivers/gpu/nova-core/mm/pramin.rs new file +127
-0+ +/// Location of the window inside BAR0. + PRAMIN: PraminWindow @ 0x700000; +} + +/// Owner of the PRAMIN window state. +/// +/// [`Pramin::window_at()`] repositions the window as needed and returns a typed MMIO view into +/// it, holding the manager borrowed for the lifetime of the view. +pub (super )struct Pramin <'gpu> { + bar:Bar0 <'gpu>, + hal: &'staticdyn MmHal , +/// MMIO view of the PRAMIN window in BAR0. + window:Mmio <'gpu,PraminWindow >, +/// VRAM range to keep the PRAMIN window inside. + vram_range:Range <VramAddress >, +/// Cached window position. + window_range:Range <VramAddress >, +} + +/// Typed view of VRAM through the PRAMIN window. +/// +/// Inserts an ordering point after previous writes through the window on drop. Views returned +/// by [`PraminAccess::view()`] cannot outlive this access, so the ordering point covers every +/// write made through them. +pub (super )struct PraminAccess <'a,T > +where +T :FromBytes +IntoBytes , +{ + view:Mmio <'a,T >, +} + +impl <T >PraminAccess <'_,T > +where +T :FromBytes +IntoBytes , +{ +/// Returns the MMIO view of the accessed location. +pub (super )fn view (&self) ->Mmio <'_,T > { + self.view + } +} + +impl <T >Drop for PraminAccess <'_,T > +where +T :FromBytes +IntoBytes , +{ +fn drop (&mut self) { +// Insert an ordering point after previous writes through this window. + self.view.cast ::<u8 >().read_val (); + } +} + +impl <'gpu>Pramin <'gpu> { +/// Alignment required by the PRAMIN window. +const BASE_ALIGN :Alignment =Alignment ::new ::<SZ_64K >(); + +/// Creates the window manager for the given VRAM region. +pub (super )fn new ( + bar:Bar0 <'gpu>, + chipset:Chipset , + vram_range:Range <VramAddress >, + ) ->Result <Self > { +let hal = hal::mm_hal (chipset); +let window =io_project! (bar, build:PRAMIN ); +let base = vram_range.start.align_down (Self ::BASE_ALIGN ); +let window_range =Self ::window_range (base)?; + hal.write_pramin_window_base (bar, base)?; + +Ok (Self { + bar, + hal, + window, + vram_range, + window_range, + }) + } + +/// Returns the VRAM range a window based at `base` exposes. +fn window_range (base:VramAddress ) ->Result <Range <VramAddress >> { +let end = base + .checked_add (WINDOW_SIZE .into_safe_cast ()) + .ok_or (EINVAL )?; +Ok (base..end) + } + +/// Check the window covers `len` bytes at `addr`, moving it if needed. +/// +/// Returns the window offset at which to perform the access. +fn window_offset (&mut self, addr:VramAddress , len:usize ) ->Result <usize > { +let end = addr.checked_add (len.into_safe_cast ()).ok_or (EINVAL )?; + +let inside = |r: &Range <VramAddress >| r.contains (&addr) && end <= r.end; +if !inside (&self.vram_range) { +return Err (EINVAL ); + } + +// Reposition the window if the access falls outside it. +if !inside (&self.window_range) { +let base = addr.align_down (Self ::BASE_ALIGN ); +let window_range =Self ::window_range (base)?; +if !inside (&window_range) { +return Err (EINVAL ); + } + self.hal.write_pramin_window_base (self.bar, base)?; + self.window_range = window_range; + } + +Ok ((addr - self.window_range.start).into_safe_cast ()) + } + +/// Return a typed MMIO view of a `T` at `vram_addr`. +/// +/// Returns an error if `vram_addr` is not aligned to `T`'s alignment, or if +/// a `T` at `vram_addr` does not fit within the VRAM region. +pub (super )fn window_at <'a,T >( + &'amut self, + vram_addr:VramAddress , + ) ->Result <PraminAccess <'a,T >> +where +T :FromBytes +IntoBytes , + { +let offset = self.window_offset (vram_addr,size_of ::<T >())?; +let view =io_project! (self.window, try:OffsetLoc ::new (offset)); + +Ok (PraminAccess { view }) + } +}Signature · 2 lines
-- 2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 08/12] gpu: nova-core: mm: Add support to use PRAMIN windows to write to VRAM
Quoted 93 lines · Alistair Popple
On 2026-08-10 at 23:55 +1000, Eliot Courtney <[email protected]> wrote...
Quoted 92 lines
From: Joel Fernandes <[email protected]>
PRAMIN apertures are a crucial mechanism for direct CPU read/write to VRAM. Add a
Praminmanager whosewindow_at()returns a typed MMIO view of VRAM through the 1 MiB PRAMIN aperture in BAR0, validating the view against the VRAM region and repositioning the window as needed for the accessed address.A view borrows
Praminmutably, so the window cannot move while the view is in use, and it inserts an ordering point on Drop.Signed-off-by Joel Fernandes <[email protected]>[ecourtney: split the registers and HAL into the two preceding patches][ecourtney: rebase w.r.t. Bar0 lifetime changes and register projections][ecourtney: drop the window guard and mutex, use &mut self][ecourtney: position at init to avoid reads, reposition in window_offset][ecourtney: return typed MMIO views instead of read/write accessors][ecourtney: insert an ordering read when a view drops][ecourtney: declare the window location, drop the doc examples][ecourtney: add the copyright header, doc and naming cleanups][ecourtney: the pramin module is mm-internal]Co-developed-by Eliot Courtney <[email protected]>Signed-off-by Eliot Courtney <[email protected]>--- drivers/gpu/nova-core/mm.rs | 1 + drivers/gpu/nova-core/mm/pramin.rs | 178 +++++++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+)drivers/gpu/nova-core/mm.rs +1
-0@@ -20,6 +20,7 @@ };mod hal; +mod pramin;mod regs;/// Physical VRAM address in GPU video memory. drivers/gpu/nova-core/mm/pramin.rs new file +46
-0@@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! Utilities for accessing VRAM through the PRAMIN window. + +use core::ops::Range ; + +use kernel::{ + io::{ + io_project, + register, + register::OffsetLoc , +Io , +Mmio ,// + }, + prelude::*, + ptr::{ +Alignable , +Alignment ,// + }, + sizes::{ +SZ_1M , +SZ_64K ,// + }, +}; + +use crate ::{ + driver::{ +Bar0 , +NovaRegisters ,// + }, + gpu::Chipset , + mm::{ + hal::{ + self, +MmHal ,// + }, +VramAddress ,// + }, + num::IntoSafeCast ,// +}; + +/// Size of the PRAMIN window (1 MiB). +const WINDOW_SIZE :usize =SZ_1M ; + +/// The PRAMIN window, which is a 1 MiB window into VRAM at a fixed BAR0 offset.
Quoted 8 lines
drivers/gpu/nova-core/mm/pramin.rs line 51
Quoted 5 lines
drivers/gpu/nova-core/mm/pramin.rs new file +5
-0+#[derive( FromBytes , IntoBytes )] +struct PraminWindow ([u8 ;WINDOW_SIZE ]); + +register! { + base:NovaRegisters ;I tried building this on drm-rust-next against the base commit (
4c9ba407018e8deb06dbc643112bac8f40404f95) but am getting some build errors:
I think you also need [1] (the v3 might also work, but not tested yet).
PATCH v2 9/12 docs: gpu: nova-core: Document the PRAMIN aperture mechanism
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
Add documentation for the PRAMIN aperture mechanism used by nova-core for direct VRAM access.
Nova only uses TARGET=VRAM for VRAM access. The SYS_MEM target values are documented for completeness but not used by the driver.
--- Documentation/gpu/nova/core/pramin.rst | 128 +++++++++++++++++++++++++++++++++ Documentation/gpu/nova/index.rst | 1 + 2 files changed, 129 insertions(+)
Documentation/gpu/nova/core/pramin.rst new file +128 -0
@@ -0,0 +1,128 @@ +.. SPDX-License-Identifier: GPL-2.0 + +========================= +PRAMIN aperture mechanism +========================= + +.. note:: + The following description is approximate and current as of the Ampere + family. It may change for future generations and is intended to assist in + understanding the driver code. + +Introduction +============ + +PRAMIN is a hardware aperture mechanism that provides CPU access to GPU Video +RAM (VRAM) before the GPU's Memory Management Unit (MMU) and page tables are +initialized. This 1 MiB sliding window, located at a fixed offset within BAR0, +is essential for setting up page tables and other critical GPU data structures +without relying on the GPU's MMU. + +Architecture Overview +===================== + +The PRAMIN aperture mechanism is logically implemented by the GPU's PBUS (PCIe +Bus Controller Unit) and provides a CPU-accessible window into VRAM through the +PCIe interface:: + + +-----------------+ PCIe +------------------------------+ + | CPU |<----------->| GPU | + +-----------------+ | | + | +----------------------+ | + | | PBUS | | + | | (Bus Controller) | | + | | | | + | | +--------------+ <------------ [1] + | | | PRAMIN | | | + | | | Window | | | + | | | (1 MiB) | | | + | | +--------------+ | | + | | | | | + | +---------|------------+ | + | | | + | v | + | +----------------------+ <------- [2] + | | VRAM | | + | | (Several GiB) | | + | | | | + | | FB[0x0000000000] | | + | | ... | | + | | FB[0xFFFFFFFFFF] | | + | +----------------------+ | + +------------------------------+ + + [1] Window starts at BAR0 + 0x700000. + [2] Program PRAMIN to any 64 KiB-aligned VRAM boundary. + +PBUS is responsible for, among other things, handling MMIO +accesses to the BAR registers. + +PRAMIN Window Operation +======================= + +The PRAMIN window provides a 1 MiB sliding aperture that can be repositioned +over the entire VRAM address space using the ``NV_PBUS_BAR0_WINDOW`` register. + +Window Control Mechanism +------------------------- + +:: + + NV_PBUS_BAR0_WINDOW Register (0x1700): + +-------+--------+--------------------------------------+ + | 31:26 | 25:24 | 23:0 | + | RSVD | TARGET | BASE_ADDR | + | | | (bits 39:16 of VRAM address) | + +-------+--------+--------------------------------------+ + + The 24-bit BASE_ADDR field encodes bits [39:16] of the target VRAM address, + providing 40-bit (1 TiB) address space coverage with 64 KiB alignment. + + TARGET field (bits 25:24): + - 0x0: VRAM (Video Memory) + - 0x1: Reserved (unused) + - 0x2: SYS_MEM_COH (Coherent System Memory) + - 0x3: SYS_MEM_NONCOH (Non-coherent System Memory) + +.. note:: + Nova only uses TARGET=VRAM (0x0) for video memory access. The SYS_MEM + target values are documented here for hardware completeness but are + not used by the driver. + +64 KiB Alignment Requirement +---------------------------- + +The PRAMIN window must be aligned to 64 KiB boundaries in VRAM. This is enforced +by the ``BASE_ADDR`` field representing bits [39:16] of the target address:: + + VRAM Address Calculation: + actual_vram_addr = (BASE_ADDR << 16) + pramin_offset + Where: + - BASE_ADDR: 24-bit value from NV_PBUS_BAR0_WINDOW[23:0] + - pramin_offset: 20-bit offset within the PRAMIN window [0x00000-0xFFFFF] + + Example Window Positioning: + +---------------------------------------------------------+ + | VRAM Space | + | | + | 0x0000000000 +-----------------+ <-- 64 KiB aligned | + | | PRAMIN Window | | + | | (1 MiB) | | + | 0x00000FFFFF +-----------------+ | + | | + | | ^ | + | | | Window can slide | + | v | to any 64 KiB-aligned boundary | + | | + | 0x0123400000 +-----------------+ <-- 64 KiB aligned | + | | PRAMIN Window | | + | | (1 MiB) | | + | 0x01234FFFFF +-----------------+ | + | | + | ... | + | | + | 0xFFFFF00000 +-----------------+ <-- 64 KiB aligned | + | | PRAMIN Window | | + | | (1 MiB) | | + | 0xFFFFFFFFFF +-----------------+ | + +---------------------------------------------------------+
Documentation/gpu/nova/index.rst +1 -0
@@ -34,3 +34,4 @@ vGPU manager VFIO driver and the nova-drm driver. core/fwsec core/falcon core/tlv + core/pramin
Signature · 1 line
2.55.0
PATCH v2 10/12 gpu: nova-core: mm: Add GpuMm centralized memory manager
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
Introduce GpuMm as the centralized GPU memory manager. At this point in the series, GpuMm only owns the PRAMIN window for direct VRAM access; the buddy allocator and TLB manager are added later when those backing types become available.
This provides a clean ownership model where GpuMm provides accessor methods for its components that can be used for memory management operations, and lets follow-on patches (such as the PRAMIN aperture self-tests) reference pramin_mut() cleanly.
--- drivers/gpu/nova-core/gpu.rs | 18 +++++++++++++++- drivers/gpu/nova-core/gsp/commands.rs | 4 ++++ drivers/gpu/nova-core/gsp/fw/commands.rs | 5 +++++ drivers/gpu/nova-core/mm.rs | 35 ++++++++++++++++++++++++++++++++ 4 files changed, 61 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/gpu.rs +17 -1
@@ -29,6 +29,10 @@ Gsp, GspBootContext, // }, + mm::{ + GpuMm, + VramAddress, // + }, regs, vgpu::VgpuManager, // };
@@ -283,6 +287,11 @@ pub(crate) struct Gpu<'gpu> { spec: Spec,/// Static GPU information as provided by the GSP. gsp_static_info: GetGspStaticInfoReply, +/// GPU memory manager owning memory management resources. +/// +/// Must be kept declared *before* `gsp_resources`, so that its components are dropped while +/// the GSP is still operational. + mm: GpuMm<'gpu>,/// GSP and its resources. #[pin] gsp_resources: GspResources<'gpu>,
@@ -410,7 +419,14 @@ pub(crate) fn new( } info - } + }, + +// 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), + )?, }) } }
drivers/gpu/nova-core/gsp/commands.rs +4 -0
@@ -216,6 +216,8 @@ pub(crate) struct GetGspStaticInfoReply { gpu_name: [u8; 64],/// Usable FB (VRAM) regions for driver memory allocation. pub(crate) usable_fb_regions: KVec<Range<u64>>, +/// Exclusive end of the FB physical address space. + pub(crate) total_fb_end: u64, }impl MessageFromGsp for GetGspStaticInfoReply {
@@ -231,10 +233,12 @@ fn read(for regionin msg.usable_fb_regions () { usable_fb_regions.push (region,GFP_KERNEL )?; } +let total_fb_end = msg.total_fb_end ().ok_or (EINVAL )?;Ok (GetGspStaticInfoReply { gpu_name: msg.gpu_name_str (), usable_fb_regions, + total_fb_end, }) } }
drivers/gpu/nova-core/gsp/fw/commands.rs +5 -0
@@ -165,6 +165,11 @@ pub(crate) fn usable_fb_regions(&self) -> impl Iterator<Item = Range<u64>> + '_ } }) } + +/// Computes the exclusive end of the FB physical address space. +pub (crate )fn total_fb_end (&self) ->Option <u64 > { + self.fb_regions ().map (|reg| reg.limit).max ()?.checked_add (1 ) + } }// SAFETY: Padding is explicit and will not contain uninitialized data.
drivers/gpu/nova-core/mm.rs +35 -0
@@ -19,10 +19,45 @@ }, }; +use crate ::{ + driver::Bar0 , + gpu::Chipset ,// +}; +mod hal;mod pramin;mod regs; +/// GPU Memory Manager - owns all core MM components. +/// +/// Provides centralized ownership of memory management resources: +/// - [`pramin::Pramin`] for direct VRAM access. +pub (crate )struct GpuMm <'gpu> { + pramin: pramin::Pramin <'gpu>, +} + +impl <'gpu>GpuMm <'gpu> { +/// Creates the GPU memory manager. +pub (crate )fn new ( + bar:Bar0 <'gpu>, + chipset:Chipset , + total_fb_end:VramAddress , + ) ->Result <Self > { +// PRAMIN covers all physical VRAM (including GSP-reserved areas +// above the usable region, e.g. the BAR1 page directory). +let vram_region =VramAddress ::ZERO ..total_fb_end; + +Ok (Self { + pramin: pramin::Pramin ::new (bar, chipset, vram_region)?, + }) + } + +/// Access the [`pramin::Pramin`]. +fn pramin_mut (&mut self) -> &mut pramin::Pramin <'gpu> { + &mut self.pramin + } +} +/// Physical VRAM address in GPU video memory. #[derive( Clone , Copy , PartialEq , Eq , PartialOrd , Ord )] #[repr(transparent)]
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 10/12] gpu: nova-core: mm: Add GpuMm centralized memory manager
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The `pramin_mut` method in `GpuMm` is missing the `pub(crate)` visibility modifier, despite the…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The pramin_mut method in GpuMm is missing the pub(crate) visibility modifier, despite the commit message claiming it is exposed for follow-on patches. --
--- Patch [10]: [PATCH v2 10/12] gpu: nova-core: mm: Add GpuMm centralized memory manager --- commit 454fed327c5dab971b01225656d96fa09a0fc921
Author: Joel Fernandes <[email protected]>
gpu: nova-core: mm: Add GpuMm centralized memory manager
Introduce GpuMm as the centralized GPU memory manager. At this point in the series, GpuMm only owns the PRAMIN window for direct VRAM access. This provides a clean ownership model where GpuMm provides accessor methods for its components.
Quoted 4 lines
drivers/gpu/nova-core/mm.rs +0
-0
[ ... ]
drivers/gpu/nova-core/mm.rs line 59
Quoted 6 lines
drivers/gpu/nova-core/mm.rs +6
-0+ +/// Access the [`pramin::Pramin`]. +fn pramin_mut (&mut self) -> &mut pramin::Pramin <'gpu> { + &mut self.pramin + } +}
[Severity: Medium]
The commit message mentions this provides accessor methods so that follow-on patches can reference pramin_mut() cleanly. However, GpuMm::pramin_mut() is defined without the pub(crate) visibility modifier, making it strictly private to the mm module.
Will this prevent cross-subsystem access from gpu.rs or external tests as intended by the commit message?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
PATCH v2 11/12 gpu: nova-core: Add self-test assertion macros and config option
In reply to Eliot CourtneyThe existing assert! and assert_eq! macros cause a panic. For self tests in nova-core, it's inconvenient to cause a panic since these need to be run on actual hardware. Instead, define similar macros that log an error then return an Err.
Also add the NOVA_CORE_SELFTESTS Kconfig option that gates the driver self-tests.
--- drivers/gpu/nova-core/Kconfig | 9 ++++++ drivers/gpu/nova-core/nova_core.rs | 2 ++ drivers/gpu/nova-core/selftest.rs | 64 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+)
drivers/gpu/nova-core/Kconfig +9 -0
@@ -15,3 +15,12 @@ config NOVA_CORE This driver is work in progress and may not be functional. If M is selected, the module will be called nova-core. + +config NOVA_CORE_SELFTESTS + bool "Nova Core driver self-tests" + depends on NOVA_CORE + default n + help + Build the driver self-tests and run them when the GPU is probed. + + If unsure, say N.
drivers/gpu/nova-core/nova_core.rs +2 -0
@@ -23,6 +23,8 @@mod num;mod regs;mod sbuffer; +#[cfg( CONFIG_NOVA_CORE_SELFTESTS )] +mod selftest;mod vbios;mod vgpu;
drivers/gpu/nova-core/selftest.rs new file +64 -0
64 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 11/12] gpu: nova-core: Add self-test assertion macros and config option
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The `$dev` expression in `selftest_assert!` is conditionally evaluated only when the assertion…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The $dev expression in selftest_assert! is conditionally evaluated only when the assertion fails, which can lead to inconsistent side effects. --
--- Patch [11]: [PATCH v2 11/12] gpu: nova-core: Add self-test assertion macros and config option --- commit 205e1404103e41ca5c6fd34482ac0f24c1d05216
Author: Eliot Courtney <[email protected]>
gpu: nova-core: Add self-test assertion macros and config option
The existing assert! and assert_eq! macros cause a panic. For self tests in nova-core, it's inconvenient to cause a panic since these need to be run on actual hardware. Instead, define similar macros that log an error then return an Err.
Quoted 5 lines
drivers/gpu/nova-core/selftest.rs new file +0
-0
[ ... ]
Quoted 3 lines
drivers/gpu/nova-core/selftest.rs new file +2
-0@@ -0,0 +1,64 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
[ ... ]
drivers/gpu/nova-core/selftest.rs line 22
Quoted 9 lines
drivers/gpu/nova-core/selftest.rs new file +9
-0+#[macro_export] +macro_rules! selftest_assert { + ($dev:expr, $cond:expr $(,)?) => { + $crate::selftest_assert!($dev, $cond,"assertion failed: {}" , ::core::stringify!($cond)) + }; + ($dev:expr, $cond:expr, $($arg:tt)+) => {{ +if !$cond { + ::kernel::dev_err!( + $dev,
[Severity: Low]
Could this lead to inconsistent side effects if the $dev expression contains them?
Since $dev is only evaluated inside the if !$cond block, any side effects in the expression passed as $dev will only occur on the error path when the assertion fails. They will be skipped on the happy path.
Would it be safer to evaluate $dev outside the condition, for instance by binding it to a local variable like let dev = $dev; before the check?
Quoted 9 lines
drivers/gpu/nova-core/selftest.rs new file +9
-0+ "Selftest: {}:{}: {}\n", + ::core::file!(), + ::core::line!(), + ::kernel::prelude::fmt!($($arg)+) + ); +return Err (::kernel::error::code::EIO ); + } + }}; +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
PATCH v2 12/12 gpu: nova-core: mm: Add PRAMIN aperture self-tests
In reply to Eliot CourtneyFrom: Joel Fernandes <[email protected]>
Add self-tests for the PRAMIN aperture mechanism to verify correct operation during GPU probe. The tests validate various alignment requirements and corner cases.
The tests are default disabled and behind CONFIG_NOVA_CORE_SELFTESTS. When enabled, tests run after GSP boot during probe.
--- drivers/gpu/nova-core/driver.rs | 3 + drivers/gpu/nova-core/gpu.rs | 12 ++++ drivers/gpu/nova-core/mm.rs | 40 ++++++++++- drivers/gpu/nova-core/mm/pramin.rs | 134 +++++++++++++++++++++++++++++++++++++ 4 files changed, 188 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/driver.rs +3 -0
@@ -87,6 +87,9 @@ fn probe<'bound>(// (`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) }), +// Run optional GPU selftests. +#[cfg( CONFIG_NOVA_CORE_SELFTESTS )] + _: { gpu.run_selftests(pdev) }, _reg: auxiliary::Registration::new( pdev.as_ref (), c"nova-drm",
drivers/gpu/nova-core/gpu.rs +12 -0
@@ -429,4 +429,16 @@ pub(crate) fn new( )?, }) } + +/// Runs self-tests on the constructed [`Gpu`], logging failures without failing probe. +#[cfg( CONFIG_NOVA_CORE_SELFTESTS )] +pub (crate )fn run_selftests (self:Pin <&mut Self >, pdev: &pci::Device <device::Bound >) { +let this = self.project (); +let dev = pdev.as_ref (); +let regions = &this.gsp_static_info.usable_fb_regions; + +if let Err (err) =crate ::mm::selftest::run (dev, this.mm, regions) { +dev_err! (dev,"self-tests failed: {:?}\n" , err); + } + } }
drivers/gpu/nova-core/mm.rs +39 -1
@@ -3,7 +3,7 @@//! Memory management subsystems. -#![expect(dead_code)] +#![cfg_attr(not( CONFIG_NOVA_CORE_SELFTESTS ), expect(dead_code))] use core::{ fmt::LowerHex ,
@@ -123,3 +123,41 @@ fn sub(self, rhs: Self) -> Self::Output { self.into_raw () - rhs.into_raw () } } + +#[cfg( CONFIG_NOVA_CORE_SELFTESTS )] +pub (crate )mod selftest { +use core::ops::Range ; + +use kernel::{ + device, + sizes::SizeConstants ,// + }; + +use super ::*; + +/// Run MM subsystem self-tests during probe. +pub (crate )fn run ( + dev: &device::Device <device::Bound >, + mm: &mut GpuMm <'_>, + usable_fb_regions: &[Range <u64 >], + ) ->Result { +// VRAM span the self-tests are free to overwrite, from the chosen test base. +const SELFTEST_SPAN :u64 = u64::SZ_64M ; + +let base = usable_fb_regions.iter ().find_map (|region| { +// Tests rely on this being 8 byte aligned for checking misalignment handling. +let base = region.start.align_up (Alignment ::new ::<8 >())?; + (base.checked_add (SELFTEST_SPAN )? <= region.end).then_some (base) + }); +let Some (base) = baseelse { +dev_warn! ( + dev, +"PRAMIN: skipping self-tests, no usable VRAM region of {:#x} bytes\n" , +SELFTEST_SPAN + ); +return Ok (()); + }; + + pramin::selftest::run (dev, mm.pramin_mut (),VramAddress ::from_raw (base)) + } +}
drivers/gpu/nova-core/mm/pramin.rs +134 -0
137 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 12/12] gpu: nova-core: mm: Add PRAMIN aperture self-tests
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The `io_read!` macro invocation uses a runtime loop variable `i` with the `[build: i]` syntax…
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The io_read! macro invocation uses a runtime loop variable i with the [build: i] syntax, which relies on the optimizer to eliminate the bounds check and may cause a build failure. --
--- Patch [12]: [PATCH v2 12/12] gpu: nova-core: mm: Add PRAMIN aperture self-tests --- commit e3c26c738212001e40a3ab7fef15d2c8cf5421b5
Author: Joel Fernandes <[email protected]>
gpu: nova-core: mm: Add PRAMIN aperture self-tests
This commit adds self-tests for the PRAMIN aperture mechanism to verify correct operation, alignment requirements, and corner cases during GPU probe. The tests are default disabled and gated behind CONFIG_NOVA_CORE_SELFTESTS.
Quoted 3 lines
drivers/gpu/nova-core/mm/pramin.rs +0
-0
[ ... ]
drivers/gpu/nova-core/mm/pramin.rs pub(super) fn window_at<'a, T>( · line 228
Quoted 12 lines
drivers/gpu/nova-core/mm/pramin.rs +12
-0+fn test_u32_as_bytes ( + dev: &device::Device <device::Bound >, + pramin: &mut Pramin <'_>, + base:VramAddress , + ) ->Result { +let addr = base +0x10 ; +let val:u32 =0xDEADBEEF ; + pramin.window_at ::<u32 >(addr)?.view ().write_val (val); + +let window = pramin.window_at ::<[u8 ;4 ]>(addr)?; +for (i, &expected)in val.to_le_bytes ().iter ().enumerate () { +selftest_assert_eq! (dev,io_read! (window.view (), [build: i]), expected);
[Severity: Low]
Will this cause a link-time build failure if the optimizer does not unroll the loop?
The io_read! macro invocation in test_u32_as_bytes uses the runtime loop variable i with the [build: i] syntax. This relies on LLVM optimization heuristics to unroll the loop and resolve the value statically at build time.
If the compiler fails to unroll this loop, the code will retain a call to rust_build_error, which results in an undefined symbol linker error unless CONFIG_RUST_BUILD_ASSERT_ALLOW is explicitly enabled.
Should this be rewritten to manually unroll the four reads, or use a runtime index rather than [build: i]?
Quoted 3 lines
drivers/gpu/nova-core/mm/pramin.rs +3
-0+ } +Ok (()) + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
Danilo Krummrich
maintainerQuoted 3 lines · Eliot Courtney
rust: num: use
const_assert! in Bounded
rust: num: rejectBounded::shrovershifts at build time
rust: num: addBounded::shr_exact
I think it would make sense to route them through the Rust tree this cycle.
Quoted 2 lines · Danilo Krummrich
I think it would make sense to route them through the Rust tree this cycle.
Yeah, I asked Alex in v1.
Cheers,
Miguel
Miguel Ojeda
AppliedQuoted 4 lines · Eliot Courtney
rust: num: use
const_assert! in Bounded
rust: num: rejectBounded::shrovershifts at build time
rust: num: addBounded::shr_exact
Applied to rust-next -- thanks everyone!
Alex: I didn't add an implicit Acked-by to the first one but I assume you are OK with it:
The second one is actually fairly important so I did:
[ This implies we can break the type invariant, which in turn means
we can trigger UB via Deref, e.g.:
rust_kernel: panicked at rust/kernel/num/bounded.rs:528:22:
unsafe precondition(s) violated: hint::unreachable_unchecked
must never be reached
- Miguel ]
Cheers,
Miguel
Alexandre Courbot
maintainerQuoted 10 lines · Miguel Ojeda
Quoted 4 lines · Eliot Courtney
rust: num: use
const_assert! in Bounded
rust: num: rejectBounded::shrovershifts at build time
rust: num: addBounded::shr_exactApplied to
rust-next-- thanks everyone!Alex: I didn't add an implicit Acked-by to the first one but I assume you are OK with it:
Yup no problem, I did ack the previous version that included this bit. I was just a bit slow to react to this one. :)
Quoted 9 lines
Suggested-by Gary Guo <[email protected]>The second one is actually fairly important so I did:
[ This implies we can break the type invariant, which in turn means
we can trigger UB viaDeref, e.g.:
Quoted 8 lines
rust_kernel: panicked atrust/kernel/num/bounded.rs:528:22:
unsafe precondition(s) violated:hint::unreachable_unchecked
must never be reached- Miguel ]
Fixes c59a2d14cd24 ("rust: num: add `shr` and `shl` methods to `Bounded`")
Thanks!