Skip to contentSkip to conversation

Introduce NVIDIA vGPU manager

PATCH New Alok Kumar 1 participant 36 messages Nov 24

Subsystems (7)
DRM drivers KVM PCI Rust +3 more subsystems
lore
Share & tools
lore

Alok Kumar

author
#0 lore raw

v5 cover Introduce NVIDIA vGPU manager

Add the nova-core support needed to create and manage NVIDIA vGPU instances on the whole-GPU SR-IOV path.

The overall control path is shown below. This series contains the nova-core manager and PF-side lifecycle APIs. Typed PF-service publication and the VFIO variant driver are separate series.

 +-----------------------+         +-----------------------+
 | Linux guest           |         | Windows guest         |
 | NVIDIA guest driver   |         | NVIDIA guest driver   |
 +-----------+-----------+         +-----------+-----------+
             |                                 |
 +-----------v-----------+         +-----------v-----------+
 | QEMU (VFIO user)      |         | QEMU (VFIO user)      |
 +-----------+-----------+         +-----------+-----------+
             +----------------+----------------+
                              |
                      +-------v-------+
                      |   VFIO core   |
                      +-------+-------+
                              |
        +---------------------v---------------------+
        | NVIDIA vGPU VFIO variant driver           |
        +---------------------+---------------------+
                              |
              +---------------+----------------------+
              | binds PCI VF                         | PF lifecycle API
              |                                      | open / close / reset
              v                                      v
     +--------+--------+               +-------------+-------------+
     |    PCI VF(s)    |               | nova-core (PF driver)     |
     |  (virtual GPU)  |               |       vGPU Manager        |
     +--------+--------+               |     VRAM / channels ...   |
              |                        +-------------+-------------+
              |                                      |
+-------------v--------------------------------------v----------------+
|                      NVIDIA physical GPU                            |
|            VF resources                 PF / GSP / VRAM             |
+---------------------------------------------------------------------+

The manager queries the type assigned to a VF by GSP-RM, reserves its channel and VRAM resources, boots and configures the GSP plugin, and handles reset and shutdown. Guest VRAM is scrubbed before reuse.

Host resources remain owned until firmware teardown and BAR unmapping complete. Failed creation rolls back through the instance owner. If firmware ownership is uncertain or teardown fails, the manager retains the affected resources until device removal.

This continues the rework of the earlier vGPU RFC [2]: firmware-facing management belongs to nova-core, while the VFIO driver binds to the VF and uses the PF's services. The companion VFIO driver does not need its own copies of the RM firmware headers.

The patches are organized as follows:

  1-8   VF boot information, boot state, runtime parameters and WPR2 heap.
  9-15  Typed BAR1 access, mapping ownership and VRAM allocation.
 16-18  Typed GMC payloads, command IDs and completion-event waits.
 19-23  Plugin bindings, NVKV conversion, properties and allocation.
 24-31  Plugin boot requests, communication buffers, shutdown and RPC.
 32-33  CeUtils commands and guest VRAM scrubbing.
 34     SR-IOV PF lifecycle APIs.
 35     Preserve BAR1 self-test page-table ownership until GPU teardown.

Changes since v4 [1]:

- Rebase onto the newer r000 firmware and vGPU integration stack.
- Include VF information in GSP_INIT in this series.
- Add typed BAR1 MMIO access and SharedGpuMm support, and rework the memory helpers and VRAM slot pool for the newer interfaces.
- Use the existing typed GMC transaction API. Add variable-length payload aliases, vGPU command IDs and a typed completion-event wait.
- Place plugin ABI definitions under vgpu/fw/r000_00, keeping them separate from the base GSP firmware bindings.
- Query VgpuProperties through typed requests and retain BAR0 in the manager for instance plugin RPC setup.
- Fold plugin RPC buffer initialization into the communication-buffer and RPC transaction patches.
- Leave per-instance plugin log export through debugfs for a follow-up.
- Include the BAR1 self-test lifetime fix as patch 35. The test borrows the persistent BarUser VMM and releases its lock before BarUser::map() acquires it again.

Dependencies:

The drm-rust-next base is:

https://gitlab.freedesktop.org/drm/rust/kernel/-/commit/0dbf41fd03abee01a37a83336ed84cd5812af633

The complete integration tree, including the prerequisites and the companion VFIO driver, is available at:

https://github.com/alokk-nvidia/nova-core/tree/nova-vgpu-wip-20261124

Previous versions:

v4 posting: [1]
v3 posting: [3]
v2 posting: [4]
v1 posting: [5]

[1]
https://lore.kernel.org/nova-gpu/[email protected]/
[2]
https://lore.kernel.org/kvm/[email protected]/
[3]
https://lore.kernel.org/nova-gpu/[email protected]/
[4]
https://lore.kernel.org/nova-gpu/[email protected]/
[5]
https://lore.kernel.org/nova-gpu/[email protected]/

Alexandre Courbot (5):
gpu: nova-core: mm: replace BarUserAccess accessors with typed MMIO
view
gpu: nova-core: mm: add SharedGpuMm
gpu: nova-core: gsp: cmdq: gmc: add types for variable-length payloads
gpu: nova-core: gsp: add the vGPU commands to GmcCommandId
gpu: nova-core: gsp: cmdq: add send_gmc_command_await_event

Alok Kumar (2):
gpu: nova-core: gsp: decode the FIFO engine table
gpu: nova-core: vgpu: add VRAM slot pool

Zhi Wang (28):
gpu: nova-core: populate VF information in GSP_INIT
gpu: nova-core: gsp: pass boot context through setup helpers
gpu: nova-core: gsp: decouple boot context from VgpuManager
gpu: nova-core: vgpu: detect boot state independently
gpu: nova-core: gpu: add a channel ID pool for vGPU
gpu: nova-core: vgpu: initialize runtime parameters after GSP boot
gpu: nova-core: vgpu: reserve the 48-VM WPR2 heap
gpu: nova-core: mm: retain BAR1 reservations after unmap failure
gpu: nova-core: mm: borrow BarUser for temporary BAR1 access
gpu: nova-core: mm: add VramBlock
gpu: nova-core: mm: add VramRegion
gpu: nova-core: mm: add BarMapping
gpu: nova-core: vgpu: add r000 plugin bindings
gpu: nova-core: gsp: factor out NVKV payload conversion
gpu: nova-core: vgpu: query VF assignments and properties
gpu: nova-core: vgpu: add instance create/destroy
gpu: nova-core: vgpu: encode vGPU boot requests
gpu: nova-core: vgpu: add GSP plugin communication buffer
gpu: nova-core: vgpu: add instance boot
gpu: nova-core: vgpu: add instance shutdown
gpu: nova-core: vgpu: add GSP plugin RPC transactions
gpu: nova-core: vgpu: negotiate the GSP plugin RPC version
gpu: nova-core: vgpu: send GSP plugin configuration parameters
gpu: nova-core: vgpu: update the GSP plugin BME state
gpu: nova-core: vgpu: add CeUtils commands
gpu: nova-core: vgpu: scrub guest VRAM with CeUtils
gpu: nova-core: vgpu: introduce SR-IOV PF APIs
gpu: nova-core: mm: keep BAR1 self-test page tables alive

 drivers/gpu/nova-core/fb.rs                   |  28 +-
 drivers/gpu/nova-core/gpu.rs                  |  97 ++-
 drivers/gpu/nova-core/gpu/channel.rs          |   4 +
 drivers/gpu/nova-core/gsp.rs                  |   7 +-
 drivers/gpu/nova-core/gsp/boot.rs             |   2 +-
 drivers/gpu/nova-core/gsp/cmdq.rs             |   2 +-
 drivers/gpu/nova-core/gsp/cmdq/gmc.rs         |  68 ++-
 drivers/gpu/nova-core/gsp/commands.rs         |  11 +
 drivers/gpu/nova-core/gsp/commands/gmc.rs     |  86 ++-
 drivers/gpu/nova-core/gsp/fw.rs               |  23 +-
 drivers/gpu/nova-core/gsp/fw/commands.rs      | 127 +++-
 .../gpu/nova-core/gsp/fw/r000_00/bindings.rs  |   2 +
 drivers/gpu/nova-core/gsp/hal/gh100.rs        |   2 +-
 drivers/gpu/nova-core/gsp/hal/tu102.rs        |   2 +-
 drivers/gpu/nova-core/gsp/load_exec.rs        |   9 +-
 drivers/gpu/nova-core/gsp/nvkv.rs             |  42 +-
 drivers/gpu/nova-core/gsp/nvkv/encode.rs      |  12 +
 drivers/gpu/nova-core/mm.rs                   |  31 +-
 drivers/gpu/nova-core/mm/bar_user.rs          | 209 +++++--
 drivers/gpu/nova-core/mm/vmm.rs               |  18 +-
 drivers/gpu/nova-core/mm/vram.rs              | 141 +++++
 drivers/gpu/nova-core/nova_core.rs            |   6 +
 drivers/gpu/nova-core/regs.rs                 |  31 +-
 drivers/gpu/nova-core/sbuffer.rs              |   7 +
 drivers/gpu/nova-core/vgpu.rs                 | 136 ++++-
 drivers/gpu/nova-core/vgpu/commands.rs        | 412 +++++++++++++
 drivers/gpu/nova-core/vgpu/fw.rs              |  45 ++
 drivers/gpu/nova-core/vgpu/fw/commands.rs     | 402 +++++++++++++
 drivers/gpu/nova-core/vgpu/fw/r000_00.rs      |  25 +
 .../gpu/nova-core/vgpu/fw/r000_00/bindings.rs | 183 ++++++
 drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs | 243 ++++++++
 drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs  | 170 ++++++
 drivers/gpu/nova-core/vgpu/instance.rs        | 559 ++++++++++++++++++
 drivers/gpu/nova-core/vgpu/scrubber.rs        | 172 ++++++
 drivers/gpu/nova-core/vgpu/vgpu_api.rs        | 153 +++++
 drivers/gpu/nova-core/vgpu/vram.rs            | 150 +++++
 36 files changed, 3414 insertions(+), 203 deletions(-)
 create mode 100644 drivers/gpu/nova-core/mm/vram.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/commands.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/fw.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/fw/commands.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/fw/r000_00.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/instance.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/scrubber.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/vgpu_api.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/vram.rs

base-commit: a8b840ca342e40b0d8af03b85958b63cdf29ff41

Signature · 1 line
2.53.0
author
#1 lore raw

PATCH v5 1/35 gpu: nova-core: populate VF information in GSP_INIT

From: Zhi Wang <[email protected]>

GSP firmware requires the VF BAR layout to route interrupts and doorbell events to individual virtual functions.

When vGPU mode is enabled, read the VF topology from the typed PCI SR-IOV extended capability and populate the existing NVKV VF information schema in GSP_INIT.

---
 drivers/gpu/nova-core/gsp/fw/commands.rs | 34 +++++++++++++++++++++++-
 1 file changed, 33 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/gsp/fw/commands.rs +33 -1
index 3c9fa459af88..4cc4b086c1d7 100644
@@ -245,6 +245,38 @@ fn new(dev: &pci::Device<device::Bound>) -> Self {
 ];
 
 impl GspInitRequest {
+    fn build_vf_info(
+        dev: &pci::Device<device::Bound>,
+        vgpu_state: VgpuState,
+    ) -> Result<Option<VfInfo>> {
+        let total_vfs = match vgpu_state {
+            VgpuState::Disabled => return Ok(None),
+            VgpuState::Enabled { total_vfs } => total_vfs,
+        };
+
+        let sriov = dev
+            .config_space_extended()?
+            .find_ext_capability::<pci::ExtSriovRegs>()?
+            .ok_or(ENODEV)?;
+
+        let mut vf_bars = sriov.vf_bars()?;
+        let bar0 = vf_bars.next().ok_or(EINVAL)?;
+        let bar1 = vf_bars.next().ok_or(EINVAL)?;
+        let bar2 = vf_bars.next().ok_or(EINVAL)?;
+        let flags = u64::from(bar0.is_64bit)
+            | (u64::from(bar1.is_64bit) << 1)
+            | (u64::from(bar2.is_64bit) << 2);
+
+        Ok(Some(VfInfo {
+            total_vfs: u32::from(total_vfs.get()).into(),
+            first_vf_offset: u32::from(sriov.first_vf_offset()).into(),
+            flags: flags.into(),
+            first_bar0_address: bar0.address.into(),
+            first_bar1_address: bar1.address.into(),
+            first_bar2_address: bar2.address.into(),
+        }))
+    }
+
     /// Creates the request for `dev`.
     ///
     /// The registry keys are [`REGISTRY_ENTRIES`], plus `RMSetSriovMode` when `vgpu_state` reports
@@ -280,7 +312,7 @@ pub(crate) fn new(
             host_arch: HostArch::host().into(),
             bus_device_func: u64::from(DomainBusDevice::new(dev)).into(),
             regkeys,
-            vf_info: None,
+            vf_info: Self::build_vf_info(dev, vgpu_state)?,
         })
     }
 }
Signature · 1 line
2.53.0
author
#2 lore raw

PATCH v5 2/35 gpu: nova-core: gsp: pass boot context through setup helpers

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

The GSP boot paths pass the device, chipset, BAR and vGPU state to the VRAM layout and GSP_INIT helpers as separate arguments. These values are already available in GspBootContext, and some are forwarded again to the WPR2 heap and VF topology helpers.

Pass the boot context through these helpers so each can read the fields it needs. This simplifies the helper signatures and their call sites.

No functional change is intended.

---
 drivers/gpu/nova-core/fb.rs               | 26 +++++++++-----------
 drivers/gpu/nova-core/gsp/boot.rs         |  2 +-
 drivers/gpu/nova-core/gsp/commands/gmc.rs | 17 ++++---------
 drivers/gpu/nova-core/gsp/fw/commands.rs  | 29 ++++++++++-------------
 drivers/gpu/nova-core/gsp/hal/gh100.rs    |  2 +-
 drivers/gpu/nova-core/gsp/hal/tu102.rs    |  2 +-
 6 files changed, 32 insertions(+), 46 deletions(-)
drivers/gpu/nova-core/fb.rs +11 -15
index 5ceb7760c78e..26e94d908b77 100644
@@ -174,13 +174,9 @@ pub(crate) struct FbRanges {
 
 impl FbRanges {
     /// Computes concrete framebuffer ranges required on non-FSP booting architectures.
-    pub(crate) fn new(
-        chipset: Chipset,
-        bar: Bar0<'_>,
-        gsp_fw: &GspFirmware<'_>,
-        vgpu_state: VgpuState,
-    ) -> Result<Self> {
-        let hal = hal::fb_hal(chipset);
+    pub(crate) fn new(ctx: &gsp::GspBootContext<'_, '_>, gsp_fw: &GspFirmware<'_>) -> Result<Self> {
+        let bar = ctx.bar;
+        let hal = hal::fb_hal(ctx.chipset);
 
         let fb = {
             let fb_size = hal.vidmem_size(bar);
@@ -242,7 +238,7 @@ pub(crate) fn new(
             FbRange(fw_image_addr..fw_image_addr + fw_image_size)
         };
 
-        let (vf_partition_count, wpr2_heap_size) = wpr2_heap_params(chipset, vgpu_state, fb.end)?;
+        let (vf_partition_count, wpr2_heap_size) = wpr2_heap_params(ctx, fb.end)?;
 
         let wpr2_heap = {
             const WPR2_HEAP_DOWN_ALIGN: Alignment = Alignment::SZ_1M;
@@ -298,11 +294,11 @@ pub(crate) fn wpr2_range(bar: Bar0<'_>) -> Option<Range<u64>> {
 }
 
 /// Computes the number of VF partitions and the WPR2 heap size from the vGPU state.
-fn wpr2_heap_params(chipset: Chipset, vgpu_state: VgpuState, fb_size: u64) -> Result<(u8, u64)> {
-    Ok(match vgpu_state {
+fn wpr2_heap_params(ctx: &gsp::GspBootContext<'_, '_>, fb_size: u64) -> Result<(u8, u64)> {
+    Ok(match ctx.vgpu.state() {
         VgpuState::Disabled => (
             0,
-            gsp::LibosParams::from_chipset(chipset).wpr_heap_size(chipset, fb_size)?,
+            gsp::LibosParams::from_chipset(ctx.chipset).wpr_heap_size(ctx.chipset, fb_size)?,
         ),
         VgpuState::Enabled { total_vfs } => (
             u8::try_from(total_vfs.get()).map_err(|_| EINVAL)?,
@@ -328,10 +324,10 @@ pub(crate) struct FbSizes {
 
 impl FbSizes {
     /// Computes the framebuffer region sizes for GSP-FMC boot.
-    pub(crate) fn new(chipset: Chipset, bar: Bar0<'_>, vgpu_state: VgpuState) -> Result<Self> {
-        let hal = hal::fb_hal(chipset);
-        let fb_size = hal.vidmem_size(bar);
-        let (vf_partition_count, wpr2_heap_size) = wpr2_heap_params(chipset, vgpu_state, fb_size)?;
+    pub(crate) fn new(ctx: &gsp::GspBootContext<'_, '_>) -> Result<Self> {
+        let hal = hal::fb_hal(ctx.chipset);
+        let fb_size = hal.vidmem_size(ctx.bar);
+        let (vf_partition_count, wpr2_heap_size) = wpr2_heap_params(ctx, fb_size)?;
 
         Ok(Self {
             frts_size: hal.frts_size(),
drivers/gpu/nova-core/gsp/boot.rs +1 -1
index 1924f759171b..43a2bbb9de98 100644
@@ -97,7 +97,7 @@ pub(crate) fn boot(
         let bootloader_app_version = gsp_fw.bootloader.app_version;
         let static_info = self
             .cmdq
-            .send_gmc_command(GspInit::new(pdev, chipset, ctx.vgpu.state())?, |event| {
+            .send_gmc_command(GspInit::new(ctx)?, |event| {
                 load_exec::handle_event(
                     ctx,
                     generic_bootloader.as_ref(),
drivers/gpu/nova-core/gsp/commands/gmc.rs +5 -12
index a6cc5759c2a2..27bd67fbe93e 100644
@@ -6,15 +6,12 @@
 use core::convert::Infallible;
 
 use kernel::{
-    device,
-    pci,
     prelude::*,
     time::Delta,
     transmute::AsBytes, //
 };
 
 use crate::{
-    gpu::Chipset,
     gsp::{
         cmdq::{
             gmc::{
@@ -39,9 +36,9 @@
             Schema,
             UnknownKeyPolicy, //
         },
+        GspBootContext, //
     },
-    sbuffer::SBufferIter,
-    vgpu::VgpuState, //
+    sbuffer::SBufferIter, //
 };
 
 /// The `GSP_INIT` command, which carries the system information and registry keys to GSP-RM.
@@ -53,18 +50,14 @@ pub(crate) struct GspInit {
 }
 
 impl GspInit {
-    /// Builds the request for `pdev`.
+    /// Builds the request using the device, chipset and vGPU state from `ctx`.
     ///
     /// # Errors
     ///
     /// - `ENOMEM` if the request or the encoder buffer cannot be allocated.
-    pub(crate) fn new(
-        pdev: &pci::Device<device::Bound>,
-        chipset: Chipset,
-        vgpu_state: VgpuState,
-    ) -> Result<Self> {
+    pub(crate) fn new(ctx: &GspBootContext<'_, '_>) -> Result<Self> {
         let mut encoder = Encoder::new();
-        GspInitRequest::new(pdev, chipset, vgpu_state)?.encode(&mut encoder)?;
+        GspInitRequest::new(ctx)?.encode(&mut encoder)?;
 
         Ok(Self {
             payload: encoder.finish(),
drivers/gpu/nova-core/gsp/fw/commands.rs +13 -16
index 4cc4b086c1d7..9ecab9418be4 100644
@@ -16,7 +16,6 @@
 };
 
 use crate::{
-    gpu::Chipset,
     gsp::{
         commands::GspStaticInfo,
         nvkv::{
@@ -29,6 +28,7 @@
             Required,
             TruncatingArray, //
         },
+        GspBootContext, //
     },
     vgpu::VgpuState, //
 };
@@ -245,16 +245,14 @@ fn new(dev: &pci::Device<device::Bound>) -> Self {
 ];
 
 impl GspInitRequest {
-    fn build_vf_info(
-        dev: &pci::Device<device::Bound>,
-        vgpu_state: VgpuState,
-    ) -> Result<Option<VfInfo>> {
-        let total_vfs = match vgpu_state {
+    fn build_vf_info(ctx: &GspBootContext<'_, '_>) -> Result<Option<VfInfo>> {
+        let total_vfs = match ctx.vgpu.state() {
             VgpuState::Disabled => return Ok(None),
             VgpuState::Enabled { total_vfs } => total_vfs,
         };
 
-        let sriov = dev
+        let sriov = ctx
+            .pdev
             .config_space_extended()?
             .find_ext_capability::<pci::ExtSriovRegs>()?
             .ok_or(ENODEV)?;
@@ -277,19 +275,18 @@ fn build_vf_info(
         }))
     }
 
-    /// Creates the request for `dev`.
+    /// Creates the request using the device, chipset and vGPU state from `ctx`.
     ///
-    /// The registry keys are [`REGISTRY_ENTRIES`], plus `RMSetSriovMode` when `vgpu_state` reports
-    /// that vGPU is enabled.
+    /// The registry keys are [`REGISTRY_ENTRIES`], plus `RMSetSriovMode` when the boot context
+    /// reports that vGPU is enabled.
     ///
     /// # Errors
     ///
     /// - `ENOMEM` if the registry list cannot be allocated.
-    pub(crate) fn new(
-        dev: &pci::Device<device::Bound>,
-        chipset: Chipset,
-        vgpu_state: VgpuState,
-    ) -> Result<Self> {
+    pub(crate) fn new(ctx: &GspBootContext<'_, '_>) -> Result<Self> {
+        let dev = ctx.pdev;
+        let chipset = ctx.chipset;
+        let vgpu_state = ctx.vgpu.state();
         let mut regkeys = KVVec::new();
         for &(name, value) in REGISTRY_ENTRIES {
             regkeys.push(RegKey::new(name, value), GFP_KERNEL)?;
@@ -312,7 +309,7 @@ pub(crate) fn new(
             host_arch: HostArch::host().into(),
             bus_device_func: u64::from(DomainBusDevice::new(dev)).into(),
             regkeys,
-            vf_info: Self::build_vf_info(dev, vgpu_state)?,
+            vf_info: Self::build_vf_info(ctx)?,
         })
     }
 }
drivers/gpu/nova-core/gsp/hal/gh100.rs +1 -1
index 91201b51030e..f91cdd061706 100644
@@ -151,7 +151,7 @@ fn boot<'gpu>(
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
 
-        let fb_sizes = FbSizes::new(chipset, ctx.bar, ctx.vgpu.state())?;
+        let fb_sizes = FbSizes::new(ctx)?;
         dev_dbg!(dev, "{:#x?}\n", fb_sizes);
 
         let wpr_meta =
drivers/gpu/nova-core/gsp/hal/tu102.rs +1 -1
index 244c7f3ae89e..d866bd6037a2 100644
@@ -258,7 +258,7 @@ fn boot<'gpu>(
         let gsp_falcon = ctx.gsp_falcon;
         let sec2_falcon = ctx.sec2_falcon;
 
-        let fb_ranges = FbRanges::new(chipset, bar, gsp_fw, ctx.vgpu.state())?;
+        let fb_ranges = FbRanges::new(ctx, gsp_fw)?;
         dev_dbg!(dev, "{:#x?}\n", fb_ranges);
 
         // Declared before the unload guard so that if Booter fails while running, SEC2 is reset
Signature · 1 line
2.53.0
author
#3 lore raw

PATCH v5 3/35 gpu: nova-core: gsp: decouple boot context from VgpuManager

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

GSP boot uses the detected vGPU mode to size firmware resources and populate GSP_INIT. Carrying the whole manager in the boot and unload context couples these operations to its runtime interface.

The boot code only needs read access to the mode, and unloading does not use the manager. A short state borrow is sufficient for both context construction sites.

Make GspBootContext borrow VgpuState directly and read it in the VRAM and GSP_INIT helpers. Return a state reference from the manager without changing mode detection or the values passed to firmware.

No functional change is intended.

---
 drivers/gpu/nova-core/fb.rs              | 2 +-
 drivers/gpu/nova-core/gpu.rs             | 4 ++--
 drivers/gpu/nova-core/gsp.rs             | 4 ++--
 drivers/gpu/nova-core/gsp/fw/commands.rs | 4 ++--
 drivers/gpu/nova-core/vgpu.rs            | 5 +++--
 5 files changed, 10 insertions(+), 9 deletions(-)
drivers/gpu/nova-core/fb.rs +1 -1
index 26e94d908b77..882827bcfd3a 100644
@@ -295,7 +295,7 @@ pub(crate) fn wpr2_range(bar: Bar0<'_>) -> Option<Range<u64>> {
 
 /// Computes the number of VF partitions and the WPR2 heap size from the vGPU state.
 fn wpr2_heap_params(ctx: &gsp::GspBootContext<'_, '_>, fb_size: u64) -> Result<(u8, u64)> {
-    Ok(match ctx.vgpu.state() {
+    Ok(match *ctx.vgpu_state {
         VgpuState::Disabled => (
             0,
             gsp::LibosParams::from_chipset(ctx.chipset).wpr_heap_size(ctx.chipset, fb_size)?,
drivers/gpu/nova-core/gpu.rs +2 -2
index 3d693656a5d6..ad200242f0f5 100644
@@ -443,7 +443,7 @@ fn drop(self: Pin<&mut Self>) {
                     gsp_falcon: &*this.gsp_falcon,
                     sec2_falcon: &*this.sec2_falcon,
                     fsp: this.fsp.as_mut(),
-                    vgpu: &*this.vgpu,
+                    vgpu_state: this.vgpu.state(),
                 },
                 bundle,
             )
@@ -516,7 +516,7 @@ pub(crate) fn new<'a>(
                     gsp_falcon,
                     sec2_falcon,
                     fsp: fsp.as_mut(),
-                    vgpu,
+                    vgpu_state: vgpu.state(),
                 })?,
             }),
 
drivers/gpu/nova-core/gsp.rs +2 -2
index a69362138cce..efb94aad417a 100644
@@ -50,7 +50,7 @@
         fw::GspArgumentsPadded, //
     },
     num,
-    vgpu::VgpuManager, //
+    vgpu::VgpuState, //
 };
 
 pub(crate) const GSP_PAGE_SHIFT: usize = 12;
@@ -69,7 +69,7 @@ pub(crate) struct GspBootContext<'ctx, 'gpu> {
     pub(crate) gsp_falcon: &'ctx Falcon<'gpu, GspFalcon>,
     pub(crate) sec2_falcon: &'ctx Falcon<'gpu, Sec2Falcon>,
     pub(crate) fsp: Option<&'ctx mut Fsp<'gpu>>,
-    pub(crate) vgpu: &'ctx VgpuManager,
+    pub(crate) vgpu_state: &'ctx VgpuState,
 }
 
 impl<'ctx, 'gpu> GspBootContext<'ctx, 'gpu> {
drivers/gpu/nova-core/gsp/fw/commands.rs +2 -2
index 9ecab9418be4..1b2cd342c404 100644
@@ -246,7 +246,7 @@ fn new(dev: &pci::Device<device::Bound>) -> Self {
 
 impl GspInitRequest {
     fn build_vf_info(ctx: &GspBootContext<'_, '_>) -> Result<Option<VfInfo>> {
-        let total_vfs = match ctx.vgpu.state() {
+        let total_vfs = match *ctx.vgpu_state {
             VgpuState::Disabled => return Ok(None),
             VgpuState::Enabled { total_vfs } => total_vfs,
         };
@@ -286,7 +286,7 @@ fn build_vf_info(ctx: &GspBootContext<'_, '_>) -> Result<Option<VfInfo>> {
     pub(crate) fn new(ctx: &GspBootContext<'_, '_>) -> Result<Self> {
         let dev = ctx.pdev;
         let chipset = ctx.chipset;
-        let vgpu_state = ctx.vgpu.state();
+        let vgpu_state = *ctx.vgpu_state;
         let mut regkeys = KVVec::new();
         for &(name, value) in REGISTRY_ENTRIES {
             regkeys.push(RegKey::new(name, value), GFP_KERNEL)?;
drivers/gpu/nova-core/vgpu.rs +3 -2
index 6b7e045acea8..e074a8294d36 100644
@@ -1,4 +1,5 @@
 // SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
 use core::num::NonZero;
 
@@ -85,7 +86,7 @@ fn detect_state(
     }
 
     /// Returns the detected vGPU state for this boot.
-    pub(crate) fn state(&self) -> VgpuState {
-        self.state
+    pub(crate) fn state(&self) -> &VgpuState {
+        &self.state
     }
 }
Signature · 1 line
2.53.0
author
#5 lore raw

PATCH v5 5/35 gpu: nova-core: gpu: add a channel ID pool for vGPU

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Channel ID reservations need a GPU-owned pool shared by vGPU instances.

The pool must remain at a stable address while its reservations exist. Its storage also needs to remain available throughout GPU cleanup.

Create a private pinned ChannelIdPool with a single 2048-channel capacity constant.

---
 drivers/gpu/nova-core/gpu.rs         | 9 +++++++++
 drivers/gpu/nova-core/gpu/channel.rs | 4 ++++
 2 files changed, 13 insertions(+)
drivers/gpu/nova-core/gpu.rs +9 -0
index 5c304a129df2..b3775365a74e 100644
@@ -49,6 +49,7 @@
         GpuMm,
         VramAddress, //
     },
+    num,
     timer::{
         Timer,
         TimerState, //
@@ -61,6 +62,10 @@
 mod hal;
 mod regs;
 
+use self::channel::TOTAL_CHANNELS;
+
+pub(crate) use self::channel::ChannelIdPool;
+
 macro_rules! define_chipset {
     ({ $($variant:ident),* $(,)* }) =>
     {
@@ -409,6 +414,8 @@ pub(crate) struct Gpu<'gpu> {
     /// GSP and its resources.
     #[pin]
     gsp_resources: GspResources<'gpu>,
+    #[pin]
+    chid_pool: ChannelIdPool,
     /// System memory page required for flushing all pending GPU-side memory writes done through
     /// PCIE into system memory, via sysmembar (A GPU-initiated HW memory-barrier operation).
     ///
@@ -486,6 +493,8 @@ pub(crate) fn new<'a>(
             // Initialize this early because `gsp_resources` depends on it.
             sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?,
 
+            chid_pool <- ChannelIdPool::new(cv!(num::u32_as_usize(TOTAL_CHANNELS))),
+
             gsp_resources <- try_pin_init!(GspResources {
                 device: pdev,
 
drivers/gpu/nova-core/gpu/channel.rs +4 -0
index 7263bb4227d8..790d9be7c26c 100644
@@ -21,6 +21,10 @@
     }, //
 };
 
+// TODO: Query the channel capacity through GMCAPI once an equivalent of
+// NV2080_CTRL_CMD_INTERNAL_FIFO_GET_NUM_CHANNELS is available.
+pub(super) const TOTAL_CHANNELS: u32 = 2048;
+
 /// Pool for tracking reservations of channel IDs.
 #[pin_data]
 pub(crate) struct ChannelIdPool {
Signature · 1 line
2.53.0
author
#6 lore raw

PATCH v5 6/35 gpu: nova-core: gsp: decode the FIFO engine table

In reply to Alok Kumar

GSP_INIT reports the FIFO engine topology used to build the channel map for vGPU instances.

Decode the count, GMC IDs and flags into GspStaticInfo and expose host-driven engines in firmware FIFO order, retaining repeated IDs. Reject counts and indexed entries beyond the driver's 64-entry table capacity rather than silently accepting a prefix. An omitted count remains zero.

---
 drivers/gpu/nova-core/gsp/commands.rs     | 10 +++
 drivers/gpu/nova-core/gsp/commands/gmc.rs |  4 +-
 drivers/gpu/nova-core/gsp/fw/commands.rs  | 77 +++++++++++++++++++++++
 3 files changed, 90 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/gsp/commands.rs +10 -0
index 8b047744c36d..f5ec27995627 100644
@@ -11,6 +11,8 @@
 
 use kernel::prelude::*;
 
+use super::fw::commands::FifoEngineList;
+
 /// The static GPU configuration, which GSP-RM reports in reply to [`GspInit`](gmc::GspInit).
 pub struct GspStaticInfo {
     gpu_name: [u8; Self::MAX_GPU_NAME_LEN],
@@ -23,6 +25,8 @@ pub struct GspStaticInfo {
     pub(crate) usable_fb_regions: KVec<Range<u64>>,
     /// Exclusive end of the FB physical address space.
     pub(crate) total_fb_end: u64,
+    /// Host-driven engines in firmware FIFO order.
+    fifo_engine_list: FifoEngineList,
 }
 
 /// Error type for [`GspStaticInfo::gpu_name`].
@@ -63,6 +67,12 @@ pub fn gpu_short_name(&self) -> core::result::Result<&str, GpuNameError> {
             .map_err(GpuNameError::InvalidUtf8)
     }
 
+    /// Returns the host-driven engines in their firmware FIFO order.
+    #[expect(dead_code)]
+    pub(crate) fn fifo_engine_list(&self) -> FifoEngineList {
+        self.fifo_engine_list
+    }
+
     /// Returns the total usable VRAM size in bytes, i.e. the summed lengths of all usable FB
     /// regions.
     pub fn vram_size(&self) -> u64 {
drivers/gpu/nova-core/gsp/commands/gmc.rs +3 -1
index 27bd67fbe93e..4f813a780d1b 100644
@@ -144,7 +144,8 @@ impl MessageFromGsp for GspStaticInfo {
     /// # Errors
     ///
     /// - `EINVAL` if the payload is not a whole number of NVKV words, if the stream is malformed
-    ///   or omits a required key, or if GSP-RM reported no framebuffer region.
+    ///   or omits a required key, if GSP-RM reported no framebuffer region, or if the FIFO engine
+    ///   count or indexed entries exceed the supported table capacity.
     /// - `ENOMEM` if the words or the decoded regions cannot be allocated.
     fn read(payload: &mut SBufferIter<core::array::IntoIter<&[u8], 2>>) -> Result<Self> {
         let bytes = payload.flush_into_kvec(GFP_KERNEL)?;
@@ -183,6 +184,7 @@ fn read(payload: &mut SBufferIter<core::array::IntoIter<&[u8], 2>>) -> Result<Se
             bar1_pde_base: reply.bar1_pde_base(),
             usable_fb_regions,
             total_fb_end: reply.total_fb_end().ok_or(EINVAL)?,
+            fifo_engine_list: reply.fifo_engine_list(),
         })
     }
 }
drivers/gpu/nova-core/gsp/fw/commands.rs +77 -0

109 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#4 lore raw

PATCH v5 4/35 gpu: nova-core: vgpu: detect boot state independently

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

The vGPU manager currently contains only the detected boot mode. Its construction couples mode detection to an object with no runtime management responsibilities.

Firmware setup needs the mode before allocating GSP resources, even when vGPU is disabled. Keeping that value with GspResources also makes it available throughout the firmware lifecycle without a manager.

Move detection to VgpuState and store its result in GspResources. Borrow it directly when constructing the boot and unload contexts, and remove the state-only manager wrapper. Preserve the FSP query order, existing diagnostics and disabled fallback.

No functional change is intended.

---
 drivers/gpu/nova-core/gpu.rs  | 11 +++++------
 drivers/gpu/nova-core/vgpu.rs | 25 ++++++++-----------------
 2 files changed, 13 insertions(+), 23 deletions(-)
drivers/gpu/nova-core/gpu.rs +5 -6
index ad200242f0f5..5c304a129df2 100644
@@ -53,7 +53,7 @@
         Timer,
         TimerState, //
     },
-    vgpu::VgpuManager, //
+    vgpu::VgpuState,
 };
 
 #[cfg_attr(not(CONFIG_KUNIT = "y"), expect(dead_code))]
@@ -335,8 +335,7 @@ struct GspResources<'gpu> {
     fsp: Option<Fsp<'gpu>>,
     /// Timer state - contains system timer offset
     timer: TimerState,
-    /// vGPU state detected before GSP boot.
-    vgpu: VgpuManager,
+    vgpu_state: VgpuState,
     /// GSP runtime data.
     #[pin]
     gsp: Gsp<'gpu>,
@@ -443,7 +442,7 @@ fn drop(self: Pin<&mut Self>) {
                     gsp_falcon: &*this.gsp_falcon,
                     sec2_falcon: &*this.sec2_falcon,
                     fsp: this.fsp.as_mut(),
-                    vgpu_state: this.vgpu.state(),
+                    vgpu_state: this.vgpu_state,
                 },
                 bundle,
             )
@@ -502,7 +501,7 @@ pub(crate) fn new<'a>(
 
                 timer: Timer::setup(dev, bar, spec.chipset, fsp.as_ref())?,
 
-                vgpu: VgpuManager::new(pdev, spec.chipset, fsp.as_mut()),
+                vgpu_state: VgpuState::detect(pdev, spec.chipset, fsp.as_mut()),
 
                 gsp <- Gsp::new(pdev, bar),
 
@@ -516,7 +515,7 @@ pub(crate) fn new<'a>(
                     gsp_falcon,
                     sec2_falcon,
                     fsp: fsp.as_mut(),
-                    vgpu_state: vgpu.state(),
+                    vgpu_state,
                 })?,
             }),
 
drivers/gpu/nova-core/vgpu.rs +8 -17
index e074a8294d36..c59e7d2f933c 100644
@@ -31,19 +31,16 @@ pub(crate) enum VgpuState {
     },
 }
 
-/// vGPU state manager.
-pub(crate) struct VgpuManager {
-    state: VgpuState,
-}
-
-impl VgpuManager {
-    /// Creates a vGPU manager by querying SR-IOV and the FSP PRC vGPU knob.
-    pub(crate) fn new(
+impl VgpuState {
+    /// Detects the boot mode, falling back to disabled if querying the device fails.
+    ///
+    /// Call after creating the FSP and before allocating GSP firmware resources.
+    pub(crate) fn detect(
         pdev: &pci::Device<device::Core<'_>>,
         chipset: Chipset,
         fsp: Option<&mut Fsp<'_>>,
     ) -> Self {
-        let state = Self::detect_state(pdev, chipset, fsp).unwrap_or_else(|e| {
+        let state = Self::query_state(pdev, chipset, fsp).unwrap_or_else(|e| {
             dev_warn!(
                 pdev,
                 "vGPU state detection failed: {:?}; disabling vGPU\n",
@@ -52,12 +49,11 @@ pub(crate) fn new(
             VgpuState::Disabled
         });
         dev_dbg!(pdev, "vGPU state: {:?}\n", state);
-
-        Self { state }
+        state
     }
 
     /// Detects the vGPU state from the chipset, SR-IOV capability and FSP PRC knob.
-    fn detect_state(
+    fn query_state(
         pdev: &pci::Device<device::Core<'_>>,
         chipset: Chipset,
         fsp: Option<&mut Fsp<'_>>,
@@ -84,9 +80,4 @@ fn detect_state(
             VgpuMode::Disabled => Ok(VgpuState::Disabled),
         }
     }
-
-    /// Returns the detected vGPU state for this boot.
-    pub(crate) fn state(&self) -> &VgpuState {
-        &self.state
-    }
 }
Signature · 1 line
2.53.0
author
#7 lore raw

PATCH v5 7/35 gpu: nova-core: vgpu: initialize runtime parameters after GSP boot

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

The vGPU manager needs the VMMU segment size and FIFO engine topology returned by a successful GSP boot to divide instance resources.

Construct VgpuManager only for a vGPU-enabled boot. Retain the GPU-owned channel pool, the ordered host-driven engine
list and the VMMU segment size. Expose the existing decoded VMMU value from GspStaticInfo at its first consumer, preserving zero when firmware omits the key.

Keep the runtime values in the manager for its instance module, and drop the manager before the pool and memory resources it borrows.

---
 drivers/gpu/nova-core/gpu.rs              | 20 ++++++++++++-
 drivers/gpu/nova-core/gsp/commands.rs     |  5 ++--
 drivers/gpu/nova-core/gsp/commands/gmc.rs |  1 +
 drivers/gpu/nova-core/gsp/fw/commands.rs  |  2 +-
 drivers/gpu/nova-core/vgpu.rs             | 36 ++++++++++++++++++++++-
 5 files changed, 59 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/gpu.rs +19 -1
index b3775365a74e..cf7173b72a13 100644
@@ -54,7 +54,10 @@
         Timer,
         TimerState, //
     },
-    vgpu::VgpuState,
+    vgpu::{
+        VgpuManager,
+        VgpuState, //
+    },
 };
 
 #[cfg_attr(not(CONFIG_KUNIT = "y"), expect(dead_code))]
@@ -395,6 +398,7 @@ unsafe fn new(
 #[pin_data]
 pub(crate) struct Gpu<'gpu> {
     pub(crate) spec: Spec,
+    vgpu: Option<VgpuManager<'chid_pool>>,
     /// GSP event interrupt registration, and the enable of its subtree.
     ///
     /// Must be kept declared *before* `gsp_resources`, so that the handler is unregistered, and
@@ -602,6 +606,20 @@ pub(crate) fn new<'a>(
                     bar1,
                 )
             },
+
+            vgpu: {
+                let info = &gsp_resources.boot_result.static_info;
+                match gsp_resources.vgpu_state {
+                    VgpuState::Disabled => None,
+                    VgpuState::Enabled { .. } => Some(VgpuManager::new(
+                        chid_pool.get_ref(),
+                        &info.fifo_engine_list(),
+                        info.vmmu_segment_size,
+                        TOTAL_CHANNELS,
+                    )),
+                }
+            },
+
         })
     }
 
drivers/gpu/nova-core/gsp/commands.rs +3 -2
index f5ec27995627..799f26e0ae74 100644
@@ -11,7 +11,7 @@
 
 use kernel::prelude::*;
 
-use super::fw::commands::FifoEngineList;
+pub(crate) use super::fw::commands::FifoEngineList;
 
 /// The static GPU configuration, which GSP-RM reports in reply to [`GspInit`](gmc::GspInit).
 pub struct GspStaticInfo {
@@ -25,6 +25,8 @@ pub struct GspStaticInfo {
     pub(crate) usable_fb_regions: KVec<Range<u64>>,
     /// Exclusive end of the FB physical address space.
     pub(crate) total_fb_end: u64,
+    /// VMMU segment size in bytes, or zero if GSP-RM omitted it.
+    pub(crate) vmmu_segment_size: u64,
     /// Host-driven engines in firmware FIFO order.
     fifo_engine_list: FifoEngineList,
 }
@@ -68,7 +70,6 @@ pub fn gpu_short_name(&self) -> core::result::Result<&str, GpuNameError> {
     }
 
     /// Returns the host-driven engines in their firmware FIFO order.
-    #[expect(dead_code)]
     pub(crate) fn fifo_engine_list(&self) -> FifoEngineList {
         self.fifo_engine_list
     }
drivers/gpu/nova-core/gsp/commands/gmc.rs +1 -0
index 4f813a780d1b..14e04db90594 100644
@@ -185,6 +185,7 @@ fn read(payload: &mut SBufferIter<core::array::IntoIter<&[u8], 2>>) -> Result<Se
             usable_fb_regions,
             total_fb_end: reply.total_fb_end().ok_or(EINVAL)?,
             fifo_engine_list: reply.fifo_engine_list(),
+            vmmu_segment_size: reply.vmmu_segment_size,
         })
     }
 }
drivers/gpu/nova-core/gsp/fw/commands.rs +1 -1
index af3948ed79f5..d9dd4841566f 100644
@@ -387,7 +387,7 @@ pub(crate) struct GspInitResponse {
     gpu_gid: ArrayVec<u8, { GspStaticInfo::GID_LEN }>,
     fb_regions: KVVec<FbRegion>,
     bar1_pde_base: u64,
-    vmmu_segment_size: u64,
+    pub(crate) vmmu_segment_size: u64,
     fifo_engine_count: FifoEngineCount,
     fifo_engine_gmc_ids: [u32; MAX_FIFO_ENGINES],
     fifo_engine_flags: [u32; MAX_FIFO_ENGINES],
drivers/gpu/nova-core/vgpu.rs +35 -1
index c59e7d2f933c..8a6d87233aaf 100644
@@ -14,7 +14,11 @@
         Fsp,
         VgpuMode, //
     },
-    gpu::Chipset, //
+    gpu::{
+        ChannelIdPool,
+        Chipset, //
+    },
+    gsp::commands::FifoEngineList, //
 };
 
 mod hal;
@@ -81,3 +85,33 @@ fn query_state(
         }
     }
 }
+
+/// Runtime resources for an enabled vGPU boot.
+pub(crate) struct VgpuManager<'gpu> {
+    #[expect(dead_code)]
+    chid_pool: &'gpu ChannelIdPool,
+    /// VMMU segment size in bytes, or zero if GSP-RM omitted it.
+    #[expect(dead_code)]
+    vmmu_segment_size: u64,
+    #[expect(dead_code)]
+    total_channels: u32,
+    #[expect(dead_code)]
+    fifo_engine_list: FifoEngineList,
+}
+
+impl<'gpu> VgpuManager<'gpu> {
+    /// Retains runtime parameters from a completed vGPU-enabled GSP boot.
+    pub(crate) fn new(
+        chid_pool: &'gpu ChannelIdPool,
+        fifo_engine_list: &FifoEngineList,
+        vmmu_segment_size: u64,
+        total_channels: u32,
+    ) -> Self {
+        Self {
+            chid_pool,
+            vmmu_segment_size,
+            total_channels,
+            fifo_engine_list: *fifo_engine_list,
+        }
+    }
+}
Signature · 1 line
2.53.0
author
#8 lore raw

PATCH v5 8/35 gpu: nova-core: vgpu: reserve the 48-VM WPR2 heap

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

GSP-RM needs the larger r000 vGPU WPR2 heap on devices that advertise more than 32 VFs. The default heap is too small for the 48-VF GB202 configuration and GSP-RM fails to start.

Select the firmware-defined 48-VM size from the detected VF count while retaining the default size for configurations with 2 through 32 VFs.

---
 drivers/gpu/nova-core/fb.rs                      | 2 +-
 drivers/gpu/nova-core/gsp/fw.rs                  | 7 +++++--
 drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs | 1 +
 3 files changed, 7 insertions(+), 3 deletions(-)
drivers/gpu/nova-core/fb.rs +1 -1
index 882827bcfd3a..ba68a812b095 100644
@@ -302,7 +302,7 @@ fn wpr2_heap_params(ctx: &gsp::GspBootContext<'_, '_>, fb_size: u64) -> Result<(
         ),
         VgpuState::Enabled { total_vfs } => (
             u8::try_from(total_vfs.get()).map_err(|_| EINVAL)?,
-            gsp::LibosParams::vgpu_wpr_heap_size(),
+            gsp::LibosParams::vgpu_wpr_heap_size(total_vfs.get()),
         ),
     })
 }
drivers/gpu/nova-core/gsp/fw.rs +5 -2
index 6e44fe14b2f4..46d3605b24b1 100644
@@ -137,8 +137,11 @@ pub(crate) fn from_chipset(chipset: Chipset) -> &'static LibosParams {
     }
 
     /// Returns the WPR heap size to reserve when vGPU is enabled.
-    pub(crate) fn vgpu_wpr_heap_size() -> u64 {
-        u64::from(bindings::GSP_FW_HEAP_SIZE_VGPU_DEFAULT)
+    pub(crate) fn vgpu_wpr_heap_size(total_vfs: u16) -> u64 {
+        u64::from(match total_vfs {
+            2..=32 => bindings::GSP_FW_HEAP_SIZE_VGPU_DEFAULT,
+            _ => r000_00::GSP_FW_HEAP_SIZE_VGPU_48VMS,
+        })
     }
 
     /// Returns the amount of memory (in bytes) to allocate for the WPR heap for a framebuffer size
drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs +1 -0
index 454d0ea9360f..fa17d3e2edf6 100644
@@ -84,6 +84,7 @@ impl<T> ::core::cmp::Eq for __BindgenUnionField<T> {}
 pub const GSP_FW_HEAP_PARAM_SIZE_PER_GB: u32 = 98304;
 pub const GSP_FW_HEAP_PARAM_CLIENT_ALLOC_SIZE: u32 = 100663296;
 pub const GSP_FW_HEAP_SIZE_VGPU_DEFAULT: u32 = 609222656;
+pub const GSP_FW_HEAP_SIZE_VGPU_48VMS: u32 = 1436549120;
 pub const GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS2_MIN_MB: u32 = 64;
 pub const GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS2_MAX_MB: u32 = 256;
 pub const GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS3_BAREMETAL_MIN_MB: u32 = 88;
Signature · 1 line
2.53.0
author
#9 lore raw

PATCH v5 9/35 gpu: nova-core: mm: replace BarUserAccess accessors with typed MMIO view

In reply to Alok Kumar

From: Alexandre Courbot <[email protected]>

BarUserAccess exposes one fallible accessor per access width, each translating its offset into BAR1 before doing the access.

Replace them with a single view() method returning a Mmio<T> of the requested type at a given offset of the mapping.

This lets callers describe the layout of a mapping with a type instead of offsets, and to use the regular I/O API.

---
 drivers/gpu/nova-core/mm/bar_user.rs | 58 ++++++++++++----------------
 1 file changed, 25 insertions(+), 33 deletions(-)
drivers/gpu/nova-core/mm/bar_user.rs +25 -33
index 2e8bd2a8ed91..f82372ccab6e 100644
@@ -4,7 +4,11 @@
 //! for GPU work submission, and applications to access GPU buffers via mmap().
 
 use kernel::{
-    io::Io,
+    io::{
+        io_project,
+        register::OffsetLoc,
+        Mmio, //
+    },
     new_mutex,
     prelude::*,
     sync::Mutex, //
@@ -125,41 +129,28 @@ pub(crate) fn num_pages(&self) -> usize {
         self.mapped().num_pages
     }
 
-    /// Translate an offset within this mapping to a BAR1 aperture offset.
-    fn bar_offset(&self, offset: usize) -> Result<usize> {
-        if offset >= self.size() {
+    /// Returns a typed MMIO view of a `T` located at `offset` within this mapping.
+    ///
+    /// Returns an error if the mapping has been torn down, if a `T` at `offset` does not fit
+    /// within the mapping, or if `offset` is not properly aligned for `T`.
+    pub(crate) fn view<T>(&self, offset: usize) -> Result<Mmio<'_, T>> {
+        let mapped = self.mapped.as_ref().ok_or(ENODEV)?;
+
+        // The I/O layer only knows about the bounds of BAR1, not the ones of this mapping.
+        let end = offset.checked_add(size_of::<T>()).ok_or(EOVERFLOW)?;
+        if end > mapped.num_pages * PAGE_SIZE {
             return Err(EINVAL);
         }
 
-        let base_vfn: usize = self.mapped().vfn_start.raw().into_safe_cast();
-        let base = base_vfn.checked_mul(PAGE_SIZE).ok_or(EOVERFLOW)?;
-        base.checked_add(offset).ok_or(EOVERFLOW)
-    }
-
-    // Fallible accessors with runtime bounds checking.
-
-    /// Read a 32-bit value at the given offset.
-    pub(crate) fn try_read32(&self, offset: usize) -> Result<u32> {
-        let off = self.bar_offset(offset)?;
-        self.bar_user.bar1.try_read32(off)
-    }
-
-    /// Write a 32-bit value at the given offset.
-    pub(crate) fn try_write32(&self, value: u32, offset: usize) -> Result {
-        let off = self.bar_offset(offset)?;
-        self.bar_user.bar1.try_write32(value, off)
-    }
-
-    /// Read a 64-bit value at the given offset.
-    pub(crate) fn try_read64(&self, offset: usize) -> Result<u64> {
-        let off = self.bar_offset(offset)?;
-        self.bar_user.bar1.try_read64(off)
-    }
+        // Offset of the `T` within BAR1.
+        let base_vfn: usize = mapped.vfn_start.raw().into_safe_cast();
+        let bar_offset = base_vfn
+            .checked_mul(PAGE_SIZE)
+            .and_then(|base| base.checked_add(offset))
+            .ok_or(EOVERFLOW)?;
 
-    /// Write a 64-bit value at the given offset.
-    pub(crate) fn try_write64(&self, value: u64, offset: usize) -> Result {
-        let off = self.bar_offset(offset)?;
-        self.bar_user.bar1.try_write64(value, off)
+        // This also checks that the `T` is within BAR1 and properly aligned.
+        Ok(io_project!(self.bar_user.bar1, try: OffsetLoc::new(bar_offset)))
     }
 }
 
@@ -193,6 +184,7 @@ pub(crate) fn run_self_test(
             GpuBuddyAllocFlags,
             GpuBuddyAllocMode, //
         },
+        io::Io,
         ptr::Alignment,
         sizes::{
             SizeConstants,
@@ -397,7 +389,7 @@ pub(crate) fn run_self_test(
         .view()
         .write_val(PATTERN_BAR1);
 
-    let readback = access.try_read32(0)?;
+    let readback = access.view::<u32>(0)?.read_val();
     let test4_passed = if readback == PATTERN_BAR1 {
         true
     } else {
Signature · 1 line
2.53.0
author
#10 lore raw

PATCH v5 10/35 gpu: nova-core: mm: retain BAR1 reservations after unmap failure

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Vmm::unmap_pages currently returns a virtual address range to its pool even when PTE invalidation or its TLB flush fails. Hardware can still use that mapping, so reusing the range can alias a live mapping.

Borrow MappedRange during unmap and release its VA reservation only after invalidation succeeds. Disarm its drop guard at that point and reject a second unmap of a range whose guard is already disarmed.

Keep BarUserAccess's mapped state until unmap succeeds, and update its callers to pass a borrowed range. A failed unmap leaves the VA reserved; callers must retain the backing storage while hardware may still access it.

Extend the MM self-test to unmap an old range after its virtual address has been reused. Require the stale token to fail without invalidating the new mapping.

---
 drivers/gpu/nova-core/mm/bar_user.rs | 35 +++++++++++++++++++---------
 drivers/gpu/nova-core/mm/vmm.rs      | 18 +++++++-------
 2 files changed, 34 insertions(+), 19 deletions(-)
drivers/gpu/nova-core/mm/bar_user.rs +24 -11
index f82372ccab6e..5a8770782d14 100644
@@ -87,8 +87,7 @@ pub(crate) fn map(
 /// Borrows the [`BarUser`] managing the mapping for the lifetime of the access object.
 pub(crate) struct BarUserAccess<'a> {
     bar_user: &'a BarUser<'a>,
-    /// [`BarUserAccess::release`] [`Option::take`]s this; `Some` at
-    /// drop time means `release()` was never called.
+    /// Cleared only after PTE invalidation and its TLB flush succeed.
     mapped: Option<MappedRange>,
 }
 
@@ -96,16 +95,22 @@ pub(crate) struct BarUserAccess<'a> {
 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)?;
+        self.unmap(mm)
+    }
+
+    fn unmap(&mut self, mm: &mut GpuMm<'_>) -> Result {
+        let Some(mapped) = self.mapped.as_ref() else {
+            return Ok(());
+        };
         let mut vmm = self.bar_user.vmm.lock();
         vmm.unmap_pages(mm, mapped)?;
+        self.mapped = None;
         Ok(())
     }
 
     /// Returns the active mapping.
     fn mapped(&self) -> &MappedRange {
-        // `mapped` is only `None` after `take()` in `release`; hence unwrap()
-        // cannot panic here.
+        // `release` consumes the access, so no accessor can run after successful release.
         self.mapped.as_ref().unwrap()
     }
 
@@ -158,7 +163,7 @@ 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"
+                "BarUserAccess dropped with a live mapping; BAR1 VA remains reserved.\n"
             );
         }
         // The inner `MappedRange`'s own `MustUnmapGuard` will also fire,
@@ -259,19 +264,27 @@ pub(crate) fn run_self_test(
     };
 
     // Cleanup - invalidate PTE.
-    vmm.unmap_pages(mm, mapped)?;
+    vmm.unmap_pages(mm, &mapped)?;
 
     // Test 2: Two-phase prepare/execute API.
     let prepared = vmm.prepare_map(mm, 1, None)?;
     let mapped2 = vmm.execute_map(mm, prepared, &[test_pfn], true)?;
+    // An old token must not invalidate a new mapping that reused its address.
+    let repeated_unmap = vmm.unmap_pages(mm, &mapped);
     let readback = vmm.read_mapping(mm, mapped2.vfn_start)?;
-    let test2_passed = if readback == Some(test_pfn) {
+    let test2_passed = if mapped2.vfn_start == test_vfn
+        && repeated_unmap == Err(EINVAL)
+        && readback == Some(test_pfn)
+    {
         true
     } else {
-        dev_err!(dev, "MM: Test 2 FAILED - Two-phase map readback mismatch\n");
+        dev_err!(
+            dev,
+            "MM: Test 2 FAILED - Remapped page or stale-token rejection mismatch\n"
+        );
         false
     };
-    vmm.unmap_pages(mm, mapped2)?;
+    vmm.unmap_pages(mm, &mapped2)?;
 
     // Test 3: Range-constrained allocation with a hole — exercises block.size()-driven
     // BAR1 mapping. A 4K hole is punched at base+16K, then a single 32K allocation
@@ -363,7 +376,7 @@ pub(crate) fn run_self_test(
             }
         }
 
-        vmm.unmap_pages(mm, mapped)?;
+        vmm.unmap_pages(mm, &mapped)?;
     }
 
     // Verify aggregate: all returned block sizes must sum to allocation size.
drivers/gpu/nova-core/mm/vmm.rs +10 -8
index 51b500a27233..49b1e5db1498 100644
@@ -324,23 +324,25 @@ pub(crate) fn map_pages(
     }
 
     /// Unmap all pages in a [`MappedRange`] with a single TLB flush.
-    pub(crate) fn unmap_pages(&mut self, mm: &mut GpuMm<'_>, range: MappedRange) -> Result {
-        let result = self
-            .pt_map
-            .invalidate_ptes(mm, range.vfn_start, range.num_pages);
+    ///
+    /// A failed invalidation retains the VA reservation. The caller must keep
+    /// the mapped storage alive while hardware may still access it.
+    pub(crate) fn unmap_pages(&mut self, mm: &mut GpuMm<'_>, range: &MappedRange) -> Result {
+        if !range._drop_guard.armed.get() {
+            return Err(EINVAL);
+        }
+        self.pt_map
+            .invalidate_ptes(mm, range.vfn_start, range.num_pages)?;
 
         // TODO: Internal page table pages (PDE, PTE pages) are still kept around.
         // This is by design as repeated maps/unmaps will be fast. As a future TODO,
         // we can add a reclaimer here to reclaim if VRAM is short. For now, the PT
         // pages are dropped once the `Vmm` is dropped.
 
-        // Free the VA range regardless of PTE invalidation success, so that the VA
-        // range is recovered even on failure (PTEs may be stale, but that is better
-        // than leaking both PTEs and VA range).
         self.free_vfn(range.vfn_start);
 
         // Unmap complete, safe to drop `MappedRange`.
         range._drop_guard.disarm();
-        result
+        Ok(())
     }
 }
Signature · 1 line
2.53.0
author
#12 lore raw

PATCH v5 12/35 gpu: nova-core: mm: add VramBlock

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

vGPU memory slots need allocations at fixed offsets within usable VRAM. Add GpuMm::alloc_vram_range and VramBlock to own these exact allocations and return their storage to the buddy allocator on drop.

Use the buddy allocator's range validation and retain the checks for absolute physical address overflow and alignment.

---
 drivers/gpu/nova-core/mm.rs      |  2 +
 drivers/gpu/nova-core/mm/vram.rs | 85 ++++++++++++++++++++++++++++++++
 2 files changed, 87 insertions(+)
 create mode 100644 drivers/gpu/nova-core/mm/vram.rs
drivers/gpu/nova-core/mm.rs +2 -0
index f53886f9ed91..a0aeb96bfa36 100644
@@ -67,6 +67,8 @@ macro_rules! impl_pfn_bounded {
 mod regs;
 pub(super) mod tlb;
 pub(super) mod vmm;
+#[expect(dead_code)]
+pub(crate) mod vram;
 
 /// GPU Memory Manager - owns all core MM components.
 ///
drivers/gpu/nova-core/mm/vram.rs new file +85 -0

85 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#11 lore raw

PATCH v5 11/35 gpu: nova-core: mm: borrow BarUser for temporary BAR1 access

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Temporary BAR1 access needs a borrow of the GPU-owned BarUser. Store BarUser inline in Gpu and borrow it in BarUserAccess, avoiding a separate allocation and reference counting for these accesses. Update the existing self-test entry points to accept the borrowed interface.

No functional change is intended.

---
 drivers/gpu/nova-core/gpu.rs         |  2 +-
 drivers/gpu/nova-core/mm/bar_user.rs | 16 ++++++++--------
 2 files changed, 9 insertions(+), 9 deletions(-)
drivers/gpu/nova-core/gpu.rs +1 -1
index cf7173b72a13..03d0411008c9 100644
@@ -656,7 +656,7 @@ pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device<device::Bou
             dev,
             this.mm,
             &info.usable_fb_regions,
-            &this.bar_user,
+            this.bar_user.as_ref().get_ref(),
             info.bar1_pde_base,
             this.spec.chipset,
         ) {
drivers/gpu/nova-core/mm/bar_user.rs +8 -8
index 5a8770782d14..ff1d0e443281 100644
@@ -63,12 +63,12 @@ pub(crate) fn new(
     }
 
     /// Map physical pages to a contiguous BAR1 virtual range.
-    pub(crate) fn map(
-        &self,
+    pub(crate) fn map<'access>(
+        &'access self,
         mm: &mut GpuMm<'_>,
         pfns: &[Pfn],
         writable: bool,
-    ) -> Result<BarUserAccess<'_>> {
+    ) -> Result<BarUserAccess<'access, 'a>> {
         if pfns.is_empty() {
             return Err(EINVAL);
         }
@@ -85,14 +85,14 @@ pub(crate) fn map(
 /// Access object for a mapped BAR1 region.
 ///
 /// Borrows the [`BarUser`] managing the mapping for the lifetime of the access object.
-pub(crate) struct BarUserAccess<'a> {
-    bar_user: &'a BarUser<'a>,
+pub(crate) struct BarUserAccess<'access, 'gpu> {
+    bar_user: &'access BarUser<'gpu>,
     /// Cleared only after PTE invalidation and its TLB flush succeed.
     mapped: Option<MappedRange>,
 }
 
 #[expect(dead_code)]
-impl BarUserAccess<'_> {
+impl BarUserAccess<'_, '_> {
     /// Tear down the BAR1 mapping.
     pub(crate) fn release(mut self, mm: &mut GpuMm<'_>) -> Result {
         self.unmap(mm)
@@ -159,7 +159,7 @@ pub(crate) fn view<T>(&self, offset: usize) -> Result<Mmio<'_, T>> {
     }
 }
 
-impl Drop for BarUserAccess<'_> {
+impl Drop for BarUserAccess<'_, '_> {
     fn drop(&mut self) {
         if self.mapped.is_some() {
             kernel::pr_warn!(
@@ -177,7 +177,7 @@ fn drop(&mut self) {
 /// address space. Uses the `GpuMm`'s buddy allocator to allocate page tables
 /// and test pages as needed.
 #[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
-pub(crate) fn run_self_test(
+pub(super) fn run_self_test(
     dev: &device::Device<device::Bound>,
     mm: &mut GpuMm<'_>,
     bar_user: &BarUser<'_>,
Signature · 1 line
2.53.0
author
#13 lore raw

PATCH v5 13/35 gpu: nova-core: mm: add VramRegion

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

BAR mappings do not necessarily cover an entire VRAM block. A region layer lets a mapping select a byte range while keeping the underlying allocation alive.

For vGPU, communication buffers occupy only part of the management heap and need a BAR mapping of that range.

Add VramRegion to describe ranges within a shared VramBlock and support bounds-checked subregions.

---
 drivers/gpu/nova-core/mm/vram.rs | 56 ++++++++++++++++++++++++++++++++
 1 file changed, 56 insertions(+)
drivers/gpu/nova-core/mm/vram.rs +56 -0
index 6839960eeb2c..6054eed9aeb0 100644
@@ -22,6 +22,21 @@
     PAGE_SIZE, //
 };
 
+/// Rebases the nonempty range `rel`, relative to the start of `base`, onto `base`.
+///
+/// Returns `EINVAL` if `rel` is empty or does not fit within `base`.
+fn rebase(base: &Range<u64>, rel: Range<u64>) -> Result<Range<u64>> {
+    let start = base.start.checked_add(rel.start).ok_or(EINVAL)?;
+    let end = base.start.checked_add(rel.end).ok_or(EINVAL)?;
+
+    // Check that the rebased range on not empty and fits within `base`.
+    if start >= end || end > base.end {
+        return Err(EINVAL);
+    }
+
+    Ok(start..end)
+}
+
 /// A physically contiguous VRAM allocation.
 ///
 /// # Invariants
@@ -37,6 +52,47 @@ impl VramBlock {
     pub(crate) const fn range(&self) -> &Range<u64> {
         &self.range
     }
+
+    /// Creates a byte range relative to this allocation, retaining its backing storage.
+    pub(crate) fn region(self: &Arc<Self>, range: Range<u64>) -> Result<VramRegion> {
+        Ok(VramRegion {
+            backing: self.clone(),
+            // INVARIANT: `rebase` returns a nonempty range.
+            range: rebase(&self.range, range)?,
+        })
+    }
+}
+
+/// A byte range that keeps its VRAM allocation alive.
+///
+/// # Invariants
+///
+/// `range.start < range.end`, and `range` lies within the range of `backing`.
+#[derive(Clone)]
+pub(crate) struct VramRegion {
+    backing: Arc<VramBlock>,
+    range: Range<u64>,
+}
+
+impl VramRegion {
+    /// Returns the range covered by this region.
+    pub(crate) const fn range(&self) -> &Range<u64> {
+        &self.range
+    }
+
+    /// Returns the length of this region in bytes.
+    pub(crate) const fn len(&self) -> u64 {
+        self.range.end.saturating_sub(self.range.start)
+    }
+
+    /// Creates a nonempty subregion relative to this view's start.
+    pub(crate) fn subregion(&self, range: Range<u64>) -> Result<Self> {
+        Ok(Self {
+            backing: self.backing.clone(),
+            // INVARIANT: `rebase` returns a nonempty range.
+            range: rebase(&self.range, range)?,
+        })
+    }
 }
 
 impl GpuMm<'_> {
Signature · 1 line
2.53.0
author
#14 lore raw

PATCH v5 14/35 gpu: nova-core: mm: add BarMapping

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

vGPU communication buffers need CPU access to regions within their VramBlocks. Add BarMapping to map these regions through BAR1.

Retain the backing region and borrow BarUser and the MM mutex for the mapping's lifetime, and unmap on drop using the retained MM dependency.

Provide an explicit unmap operation so owners can observe errors before releasing resources. Keep the mapping and backing region on failure, remember the first error and reject subsequent accesses. Owners must retain failed mappings until device teardown; drop does not retry an unmap that already failed.

---
 drivers/gpu/nova-core/mm/bar_user.rs | 100 +++++++++++++++++++++++++++
 1 file changed, 100 insertions(+)
drivers/gpu/nova-core/mm/bar_user.rs +100 -0
index ff1d0e443281..243f8739dfe6 100644
@@ -10,6 +10,7 @@
         Mmio, //
     },
     new_mutex,
+    num::casts::FromSafeCast,
     prelude::*,
     sync::Mutex, //
 };
@@ -22,6 +23,7 @@
             MappedRange,
             Vmm, //
         },
+        vram::VramRegion,
         GpuMm,
         Pfn,
         Vfn,
@@ -171,6 +173,104 @@ fn drop(&mut self) {
     }
 }
 
+/// A BAR mapping that retains its backing VRAM region.
+#[must_use]
+pub(crate) struct BarMapping<'map, 'gpu> {
+    /// Mapping of `region`.
+    access: BarUserAccess<'map, 'gpu>,
+    mm: &'map Mutex<GpuMm<'gpu>>,
+    /// The VRAM region that is mapped.
+    region: VramRegion,
+    unmap_error: Option<Error>,
+}
+
+#[expect(dead_code)]
+impl<'map, 'gpu> BarMapping<'map, 'gpu> {
+    /// Maps `region`, which must start and end on a page boundary.
+    pub(crate) fn new(
+        bar_user: &'map BarUser<'gpu>,
+        mm: &'map Mutex<GpuMm<'gpu>>,
+        region: VramRegion,
+        writable: bool,
+    ) -> Result<Self> {
+        const U64_PAGE_SIZE: u64 = cv!(PAGE_SIZE);
+
+        let range = region.range();
+        if !range.start.is_multiple_of(U64_PAGE_SIZE) || !range.end.is_multiple_of(U64_PAGE_SIZE) {
+            return Err(EINVAL);
+        }
+
+        let num_pages = usize::try_from(region.len() / U64_PAGE_SIZE).map_err(|_| EOVERFLOW)?;
+        let mut pfns = KVec::with_capacity(num_pages, GFP_KERNEL)?;
+        for page in 0..num_pages {
+            let address = u64::from_safe_cast(page)
+                .checked_mul(U64_PAGE_SIZE)
+                .and_then(|byte_offset| byte_offset.checked_add(range.start))
+                .ok_or(EOVERFLOW)?;
+            pfns.push(Pfn::from(VramAddress::from_raw(address)), GFP_KERNEL)?;
+        }
+
+        let access = bar_user.map(&mut mm.lock(), &pfns, writable)?;
+
+        Ok(Self {
+            access,
+            mm,
+            region,
+            unmap_error: None,
+        })
+    }
+
+    pub(crate) fn region(&self) -> &VramRegion {
+        &self.region
+    }
+
+    fn access(&self) -> Result<&BarUserAccess<'map, 'gpu>> {
+        if self.access.mapped.is_none() {
+            return Err(ENODEV);
+        }
+        if let Some(error) = self.unmap_error {
+            return Err(error);
+        }
+        Ok(&self.access)
+    }
+
+    /// Returns a typed MMIO view of a `T` located at the start of the mapped region.
+    ///
+    /// Returns an error if the mapping is not live anymore, if a `T` does not fit within the
+    /// region, or if the region is not properly aligned for `T`.
+    pub(crate) fn view<T>(&self) -> Result<Mmio<'_, T>> {
+        // The mapping covers exactly the region, so this also checks that the `T` fits within it.
+        self.access()?.view(0)
+    }
+
+    /// Unmap while retaining the mapping and its backing storage on failure.
+    ///
+    /// The first error is retained; later calls do not retry the operation.
+    pub(crate) fn unmap(&mut self) -> Result {
+        if let Some(error) = self.unmap_error {
+            return Err(error);
+        }
+        let result = self.access.unmap(&mut self.mm.lock());
+        if let Err(error) = result {
+            self.unmap_error = Some(error);
+        }
+        result
+    }
+}
+
+impl Drop for BarMapping<'_, '_> {
+    /// Drop unmaps the region and may sleep. Call [`Self::unmap`] to observe errors;
+    /// on failure the owner must retain this object until device teardown.
+    fn drop(&mut self) {
+        if self.unmap_error.is_some() {
+            return;
+        }
+        if let Err(error) = self.unmap() {
+            kernel::pr_err!("failed to unmap BAR1 region: {:?}\n", error);
+        }
+    }
+}
+
 /// Run MM subsystem self-tests during probe.
 ///
 /// Tests page table infrastructure and `BAR1` MMIO access using the `BAR1`
Signature · 1 line
2.53.0
author
#15 lore raw

PATCH v5 15/35 gpu: nova-core: mm: add SharedGpuMm

In reply to Alok Kumar

From: Alexandre Courbot <[email protected]>

Share the memory manager through SharedGpuMm, which hides the mutex's invariant resource lifetime behind an existential lifetime so that it and its users remain covariant, like Cmdq does.

---
 drivers/gpu/nova-core/mm.rs          | 31 +++++++++++++++++++++++++++-
 drivers/gpu/nova-core/mm/bar_user.rs |  9 ++++----
 2 files changed, 35 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/mm.rs +30 -1
index a0aeb96bfa36..d4cba022ccad 100644
@@ -44,13 +44,15 @@ macro_rules! impl_pfn_bounded {
         GpuBuddy,
         GpuBuddyParams, //
     },
+    new_mutex,
     num::Bounded,
     prelude::*,
     ptr::{
         Alignable,
         Alignment, //
     },
-    sizes::SZ_4K, //
+    sizes::SZ_4K,
+    sync::Mutex, //
 };
 
 use crate::{
@@ -117,6 +119,33 @@ pub(crate) fn tlb(&self) -> &Tlb<'gpu> {
     }
 }
 
+/// A [`GpuMm`] shared between several users, serialized by a mutex.
+#[pin_data]
+pub(crate) struct SharedGpuMm<'gpu>
+where
+    // Hide the mutex's invariant resource lifetime so `SharedGpuMm` remains covariant.
+    exists<'res>: 'gpu,
+{
+    #[pin]
+    #[uses('res: invariant)]
+    inner: Mutex<GpuMm<'res>>,
+}
+
+impl<'gpu> SharedGpuMm<'gpu> {
+    /// Creates a pin-initializer sharing `mm`.
+    #[expect(dead_code)]
+    pub(crate) fn new(mm: GpuMm<'gpu>) -> impl PinInit<Self> + 'gpu {
+        pin_init!(Self {
+            inner <- new_mutex!(mm, "nova-core::gpu-mm"),
+        })
+    }
+
+    /// Runs `f` with the memory manager locked.
+    pub(crate) fn with_locked<R>(&self, f: impl FnOnce(&mut GpuMm<'_>) -> R) -> R {
+        self.with_inner(|inner| f(&mut inner.lock()))
+    }
+}
+
 /// Page size in bytes (4 KiB).
 pub(crate) const PAGE_SIZE: usize = SZ_4K;
 
drivers/gpu/nova-core/mm/bar_user.rs +5 -4
index 243f8739dfe6..75970cb0b5cb 100644
@@ -26,6 +26,7 @@
         vram::VramRegion,
         GpuMm,
         Pfn,
+        SharedGpuMm,
         Vfn,
         VirtualAddress,
         VramAddress,
@@ -178,7 +179,7 @@ fn drop(&mut self) {
 pub(crate) struct BarMapping<'map, 'gpu> {
     /// Mapping of `region`.
     access: BarUserAccess<'map, 'gpu>,
-    mm: &'map Mutex<GpuMm<'gpu>>,
+    mm: &'map SharedGpuMm<'gpu>,
     /// The VRAM region that is mapped.
     region: VramRegion,
     unmap_error: Option<Error>,
@@ -189,7 +190,7 @@ impl<'map, 'gpu> BarMapping<'map, 'gpu> {
     /// Maps `region`, which must start and end on a page boundary.
     pub(crate) fn new(
         bar_user: &'map BarUser<'gpu>,
-        mm: &'map Mutex<GpuMm<'gpu>>,
+        mm: &'map SharedGpuMm<'gpu>,
         region: VramRegion,
         writable: bool,
     ) -> Result<Self> {
@@ -210,7 +211,7 @@ pub(crate) fn new(
             pfns.push(Pfn::from(VramAddress::from_raw(address)), GFP_KERNEL)?;
         }
 
-        let access = bar_user.map(&mut mm.lock(), &pfns, writable)?;
+        let access = mm.with_locked(|mm| bar_user.map(mm, &pfns, writable))?;
 
         Ok(Self {
             access,
@@ -250,7 +251,7 @@ pub(crate) fn unmap(&mut self) -> Result {
         if let Some(error) = self.unmap_error {
             return Err(error);
         }
-        let result = self.access.unmap(&mut self.mm.lock());
+        let result = self.mm.with_locked(|mm| self.access.unmap(mm));
         if let Err(error) = result {
             self.unmap_error = Some(error);
         }
Signature · 1 line
2.53.0
author
#16 lore raw

PATCH v5 16/35 gpu: nova-core: gsp: cmdq: gmc: add types for variable-length payloads

In reply to Alok Kumar

From: Alexandre Courbot <[email protected]>

Both the CommandToGsp and MessageFromGsp traits support a variable-length payload, described using a SBufferIter of two slices to represent the fact that the payload might wrap around the message queue.

The type of this slice is rather convoluted, and does not convey its purpose, eventually getting in the way of writing clean implementations of the traits.

Define two type aliases, CommandPayload and MessagePayload that are shorter to type and obvious as to their purpose, and use them where relevant.

---
 drivers/gpu/nova-core/gsp/cmdq/gmc.rs     | 25 ++++++----
 drivers/gpu/nova-core/gsp/commands/gmc.rs | 56 +++++++++++------------
 drivers/gpu/nova-core/gsp/load_exec.rs    |  9 ++--
 3 files changed, 45 insertions(+), 45 deletions(-)
drivers/gpu/nova-core/gsp/cmdq/gmc.rs +15 -10
index 7215cbfa5ca0..bf54f73afbc8 100644
@@ -37,6 +37,18 @@
     sbuffer::SBufferIter, //
 };
 
+/// Payload of a GMC command.
+///
+/// Since the command queue is circular, the payload may loop onto the start of the queue. Hence it
+/// is presented as a [`SBufferIter`] of potentially two elements.
+pub(crate) type CommandPayload<'a> = SBufferIter<core::array::IntoIter<&'a mut [u8], 2>>;
+
+/// Payload of a GMC message.
+///
+/// Since the message queue is circular, the payload may loop onto the start of the queue. Hence it
+/// is presented as a [`SBufferIter`] of potentially two elements.
+pub(crate) type MessagePayload<'a> = SBufferIter<core::array::IntoIter<&'a [u8], 2>>;
+
 /// Trait implemented by types representing a GMC command to send to the GSP.
 ///
 /// The main purpose of this trait is to provide [`Cmdq`] with the information it needs to send
@@ -94,10 +106,7 @@ fn variable_payload_len(&self) -> usize {
     /// unwritten space will lead to an error.
     ///
     /// Most commands don't have a variable-length payload, so this does nothing by default.
-    fn init_variable_payload(
-        &self,
-        _dst: &mut SBufferIter<core::array::IntoIter<&mut [u8], 2>>,
-    ) -> Result {
+    fn init_variable_payload(&self, _dst: &mut CommandPayload<'_>) -> Result {
         Ok(())
     }
 
@@ -178,18 +187,14 @@ pub(crate) trait MessageFromGsp: Sized {
     type InitError;
 
     /// Method reading the reply from the payload of the message and returning it.
-    fn read(
-        payload: &mut SBufferIter<core::array::IntoIter<&[u8], 2>>,
-    ) -> Result<Self, Self::InitError>;
+    fn read(payload: &mut MessagePayload<'_>) -> Result<Self, Self::InitError>;
 }
 
 /// Reply type for commands that the GSP answers with a status and no payload.
 impl MessageFromGsp for () {
     type InitError = Infallible;
 
-    fn read(
-        _payload: &mut SBufferIter<core::array::IntoIter<&[u8], 2>>,
-    ) -> Result<Self, Self::InitError> {
+    fn read(_payload: &mut MessagePayload<'_>) -> Result<Self, Self::InitError> {
         Ok(())
     }
 }
drivers/gpu/nova-core/gsp/commands/gmc.rs +26 -30

77 lines not on this page · raw message

drivers/gpu/nova-core/gsp/load_exec.rs +4 -5
index 6ea853e31b77..cef6f314151a 100644
@@ -12,8 +12,6 @@
 //!   memory (DMEM) of a falcon, and the DMA engine that loads a binary into them. The DMA engine
 //!   accesses the framebuffer or system memory through the FBIF (Framebuffer Interface).
 
-use core::array;
-
 use kernel::{
     device,
     dma::DmaAddress,
@@ -40,7 +38,8 @@
     gsp::{
         cmdq::gmc::{
             GmcMessage,
-            MessageFromGsp, //
+            MessageFromGsp,
+            MessagePayload, //
         },
         fw::GmcCommandId,
         GspBootContext, //
@@ -426,7 +425,7 @@ unsafe impl FromBytes for HsBinaryParams {}
 impl MessageFromGsp for HsBinaryParams {
     type InitError = Error;
 
-    fn read(payload: &mut SBufferIter<array::IntoIter<&[u8], 2>>) -> Result<Self> {
+    fn read(payload: &mut MessagePayload<'_>) -> Result<Self> {
         let mut bytes = [0u8; size_of::<Self>()];
 
         payload.read_exact(&mut bytes)?;
@@ -482,7 +481,7 @@ unsafe impl FromBytes for GenericBootloaderParams {}
 impl MessageFromGsp for GenericBootloaderParams {
     type InitError = Error;
 
-    fn read(payload: &mut SBufferIter<array::IntoIter<&[u8], 2>>) -> Result<Self> {
+    fn read(payload: &mut MessagePayload<'_>) -> Result<Self> {
         let mut bytes = [0u8; size_of::<Self>()];
 
         payload.read_exact(&mut bytes)?;
Signature · 1 line
2.53.0
author
#17 lore raw

PATCH v5 17/35 gpu: nova-core: gsp: add the vGPU commands to GmcCommandId

In reply to Alok Kumar

From: Alexandre Courbot <[email protected]>

The vGPU manager sends GMC commands and receives GMC events that GmcCommandId does not list, so they cannot be recognized.

Add them, and make the gmc module visible to the rest of the crate so the vGPU code can implement its commands.

---
 drivers/gpu/nova-core/gsp/cmdq.rs |  2 +-
 drivers/gpu/nova-core/gsp/fw.rs   | 14 ++++++++++++++
 2 files changed, 15 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/gsp/cmdq.rs +1 -1
index 990edfcd2bc2..0977cba4d122 100644
@@ -1,7 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0
 // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
-pub(super) mod gmc;
+pub(crate) mod gmc;
 // No caller sends an RPC command: GSP_INIT and GSP_SUSPEND replaced the RPC commands that the
 // driver used during boot and shutdown. The r000 GSP-RM still accepts RPC commands once it is up,
 // so the RPC send and reply paths stay, and are built as dead code.
drivers/gpu/nova-core/gsp/fw.rs +14 -0
index 46d3605b24b1..6daabb6aea78 100644
@@ -720,6 +720,20 @@ pub(crate) enum GmcCommandId with TryFrom<Bounded<u32, 24>> {
         ExecGenericBootloader = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER,
         ExecHsBinary = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_EXEC_HS_BINARY,
         GspSuspend = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_GSP_SUSPEND,
+        QueryVgpuProperties = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_QUERY_VGPU_PROPERTIES,
+        QueryAssignedVfVgpuType = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_QUERY_ASSIGNED_VF_VGPU_TYPE,
+        BootloadGspVgpuPluginTask =
+            bindings::GMCAPI_COMMANDS_GMCAPI_CMD_BOOTLOAD_GSP_VGPU_PLUGIN_TASK,
+        ShutdownGspVgpuPluginTask =
+            bindings::GMCAPI_COMMANDS_GMCAPI_CMD_SHUTDOWN_GSP_VGPU_PLUGIN_TASK,
+        ShutdownGspVgpuPluginTaskComplete =
+            bindings::GMCAPI_COMMANDS_GMCAPI_CMD_SHUTDOWN_GSP_VGPU_PLUGIN_TASK_COMPLETE,
+        CleanupGspVgpuPluginResources =
+            bindings::GMCAPI_COMMANDS_GMCAPI_CMD_CLEANUP_GSP_VGPU_PLUGIN_RESOURCES,
+        VgpuPluginTriggeredEvent = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_VGPU_PLUGIN_TRIGGERED_EVENT,
+        VgpuMgrScrubGuestFb = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_VGPU_MGR_SCRUB_GUEST_FB,
+        VgpuMgrAllocGspCeutils = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_VGPU_MGR_ALLOC_GSP_CEUTILS,
+        VgpuMgrFreeGspCeutils = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_VGPU_MGR_FREE_GSP_CEUTILS,
         MmuFaultQueued = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_MMU_FAULT_QUEUED,
     }
 }
Signature · 1 line
2.53.0
author
#18 lore raw

PATCH v5 18/35 gpu: nova-core: gsp: cmdq: add send_gmc_command_await_event

In reply to Alok Kumar

From: Alexandre Courbot <[email protected]>

Some GMC commands are not answered, and report their completion with a separate event instead. Receiving that event after releasing the queue would let another receiver, such as the interrupt thread, consume it.

Add a method that sends such a command and offers the GMC events that follow to a closure until it accepts one, all under a single lock of the queue. The wait is bounded by the command's COMPLETION_TIMEOUT.

---
 drivers/gpu/nova-core/gsp/cmdq/gmc.rs | 44 +++++++++++++++++++++++++++
 1 file changed, 44 insertions(+)
drivers/gpu/nova-core/gsp/cmdq/gmc.rs +44 -0
index bf54f73afbc8..d4017c2e04ce 100644
@@ -349,6 +349,50 @@ pub(crate) fn send_gmc_command<C>(
         })
     }
 
+    /// Sends `command`, which the GSP does not answer, and waits for the event that completes it.
+    ///
+    /// GMC events are passed to `on_event` until it returns `Ok(Some(_))`, which ends the wait.
+    /// Other messages are logged and consumed.
+    ///
+    /// The queue is locked for the entire send+receive cycle, including the calls to `on_event`,
+    /// so that no other receiver can consume the event. `on_event` must thus not use the queue.
+    ///
+    /// # Errors
+    ///
+    /// - `EMSGSIZE` if the command does not fit in a single command queue element.
+    /// - `ETIMEDOUT` if space does not become available to send the command, or if `on_event`
+    ///   accepts no event within [`CommandToGsp::COMPLETION_TIMEOUT`] of the send.
+    /// - `EIO` if the variable payload requested by the command has not been entirely
+    ///   written to by its [`CommandToGsp::init_variable_payload`] method, or if a message fails
+    ///   framing validation.
+    ///
+    /// Error codes returned by the command initializer and by `on_event` are propagated as-is.
+    #[expect(dead_code)]
+    pub(crate) fn send_gmc_command_await_event<C, R>(
+        &self,
+        command: C,
+        on_event: impl Fn(&GmcMessage<'_>) -> Result<Option<R>>,
+    ) -> Result<R>
+    where
+        C: CommandToGsp<Reply = NoReply>,
+        Error: From<C::InitError>,
+    {
+        self.with_inner_locked(|inner| {
+            inner.send_gmc_command(command)?;
+            let dev = inner.dev;
+
+            inner.await_msg_with(C::COMPLETION_TIMEOUT, |message| match message {
+                GspParsedMessage::Gmc(event) if !event.header.command().is_response() => {
+                    on_event(&event)
+                }
+                _ => {
+                    message.log(dev);
+                    Ok(None)
+                }
+            })
+        })
+    }
+
     /// Sends `command` to the GSP without waiting for a reply.
     ///
     /// # Errors
Signature · 1 line
2.53.0
author
#19 lore raw

PATCH v5 19/35 gpu: nova-core: vgpu: add r000 plugin bindings

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

The GSP plugin communication area and RPC protocol are defined by the r000 firmware interface. Keeping local copies of that ABI risks letting the vGPU manager drift from the firmware layout.

Extend the existing r000 binding set with the nova-core subset of dev_vgpu_gsp_shared.h. The bindings expose the control and response region types, message IDs, and firmware-defined region sizes. Keep the raw declarations private and expose only the symbols needed by the GSP plugin communication layer.

---
 .../gpu/nova-core/gsp/fw/r000_00/bindings.rs  |   1 +
 drivers/gpu/nova-core/vgpu.rs                 |   1 +
 drivers/gpu/nova-core/vgpu/fw.rs              |   4 +
 drivers/gpu/nova-core/vgpu/fw/r000_00.rs      |  25 +++
 .../gpu/nova-core/vgpu/fw/r000_00/bindings.rs | 182 ++++++++++++++++++
 5 files changed, 213 insertions(+)
 create mode 100644 drivers/gpu/nova-core/vgpu/fw.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/fw/r000_00.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs
drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs +1 -0
index fa17d3e2edf6..f836d7ee84a0 100644
@@ -1,4 +1,5 @@
 // SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
 #[repr(C)]
 #[derive(Default)]
drivers/gpu/nova-core/vgpu.rs +1 -0
index 8a6d87233aaf..ea4bb5915879 100644
@@ -21,6 +21,7 @@
     gsp::commands::FifoEngineList, //
 };
 
+mod fw;
 mod hal;
 
 /// vGPU state detected during GPU construction.
drivers/gpu/nova-core/vgpu/fw.rs new file +4 -0
new file mode 100644
index 000000000000..e4571cfe11a3
@@ -0,0 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+mod r000_00;
drivers/gpu/nova-core/vgpu/fw/r000_00.rs new file +25 -0
new file mode 100644
index 000000000000..77d6b06961f7
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Bindings generated by `bindgen` from the r000 GSP firmware headers.
+//!
+//! Use them only through the parent module, which abstracts or re-exports the symbols that the
+//! driver needs.
+
+#![allow(
+    dead_code,
+    clippy::all,
+    clippy::undocumented_unsafe_blocks,
+    clippy::ptr_as_ptr,
+    clippy::ref_as_ptr,
+    missing_docs,
+    non_camel_case_types,
+    non_upper_case_globals,
+    non_snake_case,
+    improper_ctypes,
+    unreachable_pub,
+    unsafe_op_in_unsafe_fn
+)]
+use kernel::ffi;
+use pin_init::MaybeZeroable;
+
+include!("r000_00/bindings.rs");
drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs new file +182 -0

182 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#20 lore raw

PATCH v5 20/35 gpu: nova-core: gsp: factor out NVKV payload conversion

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Both GSP initialization and vGPU property queries decode their replies as NVKV streams.

Move the byte-to-word conversion helper into the NVKV module and make that module accessible to the vGPU firmware interface.

No functional change is intended.

---
 drivers/gpu/nova-core/gsp.rs              |  2 +-
 drivers/gpu/nova-core/gsp/commands/gmc.rs | 12 ++-------
 drivers/gpu/nova-core/gsp/nvkv.rs         | 31 ++++++++++++++++++++++-
 3 files changed, 33 insertions(+), 12 deletions(-)
drivers/gpu/nova-core/gsp.rs +1 -1
index efb94aad417a..4bce365c96e5 100644
@@ -22,7 +22,7 @@
 mod fw;
 mod load_exec;
 mod logbuffer;
-mod nvkv;
+pub(crate) mod nvkv;
 mod regs;
 
 use logbuffer::LogBuffers;
drivers/gpu/nova-core/gsp/commands/gmc.rs +2 -10
index e1d47e86c82e..81abeb3264ce 100644
@@ -31,6 +31,7 @@
         GmcCommandId,
     },
     nvkv::{
+        nvkv_words,
         Decoder,
         Encodable,
         Encoder,
@@ -146,16 +147,7 @@ impl MessageFromGsp for GspStaticInfo {
     fn read(payload: &mut MessagePayload<'_>) -> Result<Self> {
         let bytes = payload.flush_into_kvec(GFP_KERNEL)?;
 
-        let chunks = bytes.chunks_exact(size_of::<u64>());
-        if !chunks.remainder().is_empty() {
-            return Err(EINVAL);
-        }
-        let mut words = KVVec::with_capacity(chunks.len(), GFP_KERNEL)?;
-        for chunk in chunks {
-            // `chunks_exact` yields slices of exactly `size_of::<u64>()` bytes.
-            let word = chunk.try_into().map_err(|_| EINVAL)?;
-            words.push(u64::from_le_bytes(word), GFP_KERNEL)?;
-        }
+        let words = nvkv_words(&bytes, &[])?;
 
         let decoder = Decoder::new(&words, UnknownKeyPolicy::Ignore);
         let mut schema = KBox::init(GspInitResponseSchema::init(), GFP_KERNEL)?;
drivers/gpu/nova-core/gsp/nvkv.rs +30 -1
index f81a9e60d89c..5887a61af02a 100644
@@ -20,11 +20,40 @@
 use kernel::{
     alloc::ArrayVec,
     bitfield,
-    num::Bounded, //
+    num::Bounded,
+    prelude::*, //
 };
 
 use crate::bounded_enum;
 
+use crate::sbuffer::SBufferIter;
+
+/// Joins the two halves of a wrapped payload into the `u64` words an NVKV stream is made of.
+///
+/// # Errors
+///
+/// - `EINVAL` if the combined length is not a whole number of words.
+/// - `ENOMEM` if the buffer cannot be allocated.
+pub(crate) fn nvkv_words(payload_0: &[u8], payload_1: &[u8]) -> Result<KVVec<u64>> {
+    const WORD_SIZE: usize = size_of::<u64>();
+
+    // Each byte slice is at most `isize::MAX` bytes, so their sum fits in `usize`.
+    let len = payload_0.len() + payload_1.len();
+    if len % WORD_SIZE != 0 {
+        return Err(EINVAL);
+    }
+
+    let mut words = KVVec::with_capacity(len / WORD_SIZE, GFP_KERNEL)?;
+    let mut bytes = SBufferIter::new_reader([payload_0, payload_1]);
+    for _ in 0..len / WORD_SIZE {
+        let mut word = [0u8; WORD_SIZE];
+        bytes.read_exact(&mut word)?;
+        words.push(u64::from_le_bytes(word), GFP_KERNEL)?;
+    }
+
+    Ok(words)
+}
+
 mod encode;
 pub(crate) use encode::*;
 
Signature · 1 line
2.53.0
author
#22 lore raw

PATCH v5 22/35 gpu: nova-core: vgpu: query VF assignments and properties

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Creating an instance requires its VF assignment and the corresponding vGPU properties before reserving resources.

Decode the VF assignment and NVKV property replies at their query entry points. Validate the returned type ID and nonzero instance limit, and initialize the decoded properties on the heap.

---
 drivers/gpu/nova-core/gsp.rs              |   1 +
 drivers/gpu/nova-core/gsp/fw.rs           |   2 +-
 drivers/gpu/nova-core/sbuffer.rs          |   7 ++
 drivers/gpu/nova-core/vgpu.rs             |  11 ++
 drivers/gpu/nova-core/vgpu/commands.rs    | 126 ++++++++++++++++++++++
 drivers/gpu/nova-core/vgpu/fw.rs          |   6 ++
 drivers/gpu/nova-core/vgpu/fw/commands.rs |  75 +++++++++++++
 7 files changed, 227 insertions(+), 1 deletion(-)
 create mode 100644 drivers/gpu/nova-core/vgpu/commands.rs
 create mode 100644 drivers/gpu/nova-core/vgpu/fw/commands.rs
drivers/gpu/nova-core/gsp.rs +1 -0
index 4bce365c96e5..125dfd06aab1 100644
@@ -29,6 +29,7 @@
 pub(crate) use logbuffer::RetainedLogs;
 
 pub(crate) use fw::{
+    GmcCommandId,
     GspFmcBootParams,
     GspFwWprMeta,
     LibosMemoryRegionInitArgument,
drivers/gpu/nova-core/gsp/fw.rs +1 -1
index 6daabb6aea78..5158f0e7c12c 100644
@@ -2,7 +2,7 @@
 // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
 pub(crate) mod commands;
-mod r000_00;
+pub(crate) mod r000_00;
 
 // Alias to avoid repeating the version number with every use.
 use r000_00 as bindings;
drivers/gpu/nova-core/sbuffer.rs +7 -0
index b8c01104c255..fd410aef2a1f 100644
@@ -161,6 +161,13 @@ pub(crate) fn read_exact(&mut self, mut dst: &mut [u8]) -> Result {
         Ok(())
     }
 
+    pub(crate) fn read<T: FromBytes + IntoBytes>(&mut self) -> Result<T> {
+        let mut ret = T::new_zeroed();
+        self.read_exact(ret.as_mut_bytes())?;
+
+        Ok(ret)
+    }
+
     /// Read all the remaining data into a [`KVec`].
     ///
     /// `self` will be empty after this operation.
drivers/gpu/nova-core/vgpu.rs +11 -0
index 5fd9641db579..0934932e051d 100644
@@ -4,6 +4,7 @@
 use core::num::NonZero;
 
 use kernel::{
+    bitfield,
     device,
     pci,
     prelude::*, //
@@ -21,10 +22,20 @@
     gsp::commands::FifoEngineList, //
 };
 
+mod commands;
 mod fw;
 mod hal;
 mod vram;
 
+bitfield! {
+    struct Dbdf(u32) {
+        2:0 function;
+        7:3 device;
+        15:8 bus;
+        31:16 domain;
+    }
+}
+
 /// vGPU state detected during GPU construction.
 #[derive(Debug, Clone, Copy)]
 pub(crate) enum VgpuState {
drivers/gpu/nova-core/vgpu/commands.rs new file +126 -0

126 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/fw.rs +6 -0
index e4571cfe11a3..2d32e196a771 100644
@@ -1,4 +1,10 @@
 // SPDX-License-Identifier: GPL-2.0
 // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
+//! vGPU firmware interface.
+//!
+//! Exposes command constants and communication buffer layout types from
+//! raw firmware bindings.
+
+pub(super) mod commands;
 mod r000_00;
drivers/gpu/nova-core/vgpu/fw/commands.rs new file +75 -0

75 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#23 lore raw

PATCH v5 23/35 gpu: nova-core: vgpu: add instance create/destroy

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

A vGPU instance owns the host resources reserved for a VF. Its assigned type determines the channel range and VRAM and management-heap reservation.

Add a manager-owned instance registry, reject duplicate GFID or DBDF entries and enforce the profile's instance limit. Reserve registry capacity before acquiring resources, then move the channel and VRAM reservations into the instance. Removing an instance or dropping the registry releases these host reservations through their owners.

---
 drivers/gpu/nova-core/gpu.rs           |  55 +++---
 drivers/gpu/nova-core/mm.rs            |   1 -
 drivers/gpu/nova-core/vgpu.rs          |  56 ++++--
 drivers/gpu/nova-core/vgpu/instance.rs | 245 +++++++++++++++++++++++++
 drivers/gpu/nova-core/vgpu/vram.rs     |   1 -
 5 files changed, 321 insertions(+), 37 deletions(-)
 create mode 100644 drivers/gpu/nova-core/vgpu/instance.rs
drivers/gpu/nova-core/gpu.rs +33 -22
index 03d0411008c9..962a6a3f4d29 100644
@@ -47,6 +47,7 @@
         bar_user::BarUser,
         pagetable::MmuVersion,
         GpuMm,
+        SharedGpuMm,
         VramAddress, //
     },
     num,
@@ -60,14 +61,16 @@
     },
 };
 
-#[cfg_attr(not(CONFIG_KUNIT = "y"), expect(dead_code))]
 mod channel;
 mod hal;
 mod regs;
 
 use self::channel::TOTAL_CHANNELS;
 
-pub(crate) use self::channel::ChannelIdPool;
+pub(crate) use self::channel::{
+    ChannelIdPool,
+    ChannelIdReservation, //
+};
 
 macro_rules! define_chipset {
     ({ $($variant:ident),* $(,)* }) =>
@@ -398,7 +401,9 @@ unsafe fn new(
 #[pin_data]
 pub(crate) struct Gpu<'gpu> {
     pub(crate) spec: Spec,
-    vgpu: Option<VgpuManager<'chid_pool>>,
+    /// Drops before the MM and BAR1 mappings needed for instance teardown.
+    #[uses('bar_user, 'chid_pool)]
+    vgpu: Option<Pin<KBox<VgpuManager<'mm>>>>,
     /// GSP event interrupt registration, and the enable of its subtree.
     ///
     /// Must be kept declared *before* `gsp_resources`, so that the handler is unregistered, and
@@ -411,7 +416,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>,
+    #[pin]
+    mm: SharedGpuMm<'gpu>,
     /// BAR1 user interface for CPU access to GPU virtual memory.
     #[pin]
     bar_user: BarUser<'gpu>,
@@ -576,7 +582,7 @@ pub(crate) fn new<'a>(
             },
 
             // Create GPU memory manager owning memory management resources.
-            mm: {
+            mm <- {
                 let info = gsp_resources.static_info();
                 let usable_vram = info.usable_fb_regions.first().ok_or(ENODEV)?;
                 let buddy_params = GpuBuddyParams {
@@ -585,12 +591,12 @@ pub(crate) fn new<'a>(
                     chunk_size: Alignment::SZ_4K,
                 };
 
-                GpuMm::new(
+                SharedGpuMm::new(GpuMm::new(
                     bar,
                     gsp_resources.spec.chipset,
                     buddy_params,
                     VramAddress::from_raw(info.total_fb_end),
-                )?
+                )?)
             },
 
             // Create BAR1 user interface for CPU access to GPU virtual memory.
@@ -611,15 +617,18 @@ pub(crate) fn new<'a>(
                 let info = &gsp_resources.boot_result.static_info;
                 match gsp_resources.vgpu_state {
                     VgpuState::Disabled => None,
-                    VgpuState::Enabled { .. } => Some(VgpuManager::new(
-                        chid_pool.get_ref(),
-                        &info.fifo_engine_list(),
-                        info.vmmu_segment_size,
-                        TOTAL_CHANNELS,
-                    )),
+                    VgpuState::Enabled { .. } => Some(KBox::pin_init(
+                        VgpuManager::new(
+                            mm.get_ref(),
+                            chid_pool.get_ref(),
+                            &info.fifo_engine_list(),
+                            info.vmmu_segment_size,
+                            TOTAL_CHANNELS,
+                        ),
+                        GFP_KERNEL,
+                    )?),
                 }
             },
-
         })
     }
 
@@ -652,14 +661,16 @@ pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device<device::Bou
         let dev = pdev.as_ref();
         let info = this.gsp_resources.static_info();
 
-        if let Err(err) = crate::mm::selftest::run(
-            dev,
-            this.mm,
-            &info.usable_fb_regions,
-            this.bar_user.as_ref().get_ref(),
-            info.bar1_pde_base,
-            this.spec.chipset,
-        ) {
+        if let Err(err) = this.mm.with_locked(|mm| {
+            crate::mm::selftest::run(
+                dev,
+                mm,
+                &info.usable_fb_regions,
+                this.bar_user.get_ref(),
+                info.bar1_pde_base,
+                this.spec.chipset,
+            )
+        }) {
             dev_err!(dev, "self-tests failed: {:?}\n", err);
         }
     }
drivers/gpu/nova-core/mm.rs +0 -1
index d4cba022ccad..f1f86931928c 100644
@@ -133,7 +133,6 @@ pub(crate) struct SharedGpuMm<'gpu>
 
 impl<'gpu> SharedGpuMm<'gpu> {
     /// Creates a pin-initializer sharing `mm`.
-    #[expect(dead_code)]
     pub(crate) fn new(mm: GpuMm<'gpu>) -> impl PinInit<Self> + 'gpu {
         pin_init!(Self {
             inner <- new_mutex!(mm, "nova-core::gpu-mm"),
drivers/gpu/nova-core/vgpu.rs +43 -13

94 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/instance.rs new file +245 -0

245 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/vram.rs +0 -1
index 0c840c03f988..77446b2bdceb 100644
@@ -93,7 +93,6 @@ pub(super) struct VgpuVramSlotPool {
     fb_region_size: u64,
 }
 
-#[expect(dead_code)]
 impl VgpuVramSlotPool {
     /// Reserve the VRAM for all possible slots of `layout`, and returns a [`VgpuVramSlotPool`] that
     /// can provide these slots.
Signature · 1 line
2.53.0
author
#24 lore raw

PATCH v5 24/35 gpu: nova-core: vgpu: encode vGPU boot requests

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

The boot request describes a vGPU's identity, channel map, VRAM, plugin heap and log buffers to GSP-RM.

Add the NVKV schema and encode it from a named boot description. Pass VRAM region views so each physical address stays paired with its length until encoding, and retain the control offset relative to the plugin heap. Represent channel-map engine and index fields in their 16-bit wire domains.

Describe one guest VRAM segment and the current whole-GPU, non-SMIG resource layout. Keep separate MIG-RM heap fields zero for that supported firmware path.

---
 drivers/gpu/nova-core/gsp/nvkv.rs         |  11 ++
 drivers/gpu/nova-core/gsp/nvkv/encode.rs  |  12 ++
 drivers/gpu/nova-core/vgpu/fw/commands.rs | 143 +++++++++++++++++++++-
 3 files changed, 164 insertions(+), 2 deletions(-)
drivers/gpu/nova-core/gsp/nvkv.rs +11 -0
index 5887a61af02a..0e8e14f98059 100644
@@ -131,6 +131,17 @@ pub(crate) struct Array<T, const N: usize, const KEY_ID: KeyId> {
     vec: ArrayVec<T, N>,
 }
 
+impl<T: Default + Copy, const N: usize, const KEY_ID: KeyId> Array<T, N, KEY_ID> {
+    /// Creates an array filled from `values`.
+    ///
+    /// Fails with `EINVAL` if `values` is longer than `N`.
+    pub(crate) fn new(values: &[T]) -> Result<Self> {
+        let mut vec = ArrayVec::default();
+        vec.extend_from_slice(values)?;
+        Ok(Self { vec })
+    }
+}
+
 bitfield! {
     /// The op word that starts each NVKV operation.
     struct Op(u64) {
drivers/gpu/nova-core/gsp/nvkv/encode.rs +12 -0
index c6891c0441ff..c4578e3ecef9 100644
@@ -7,6 +7,7 @@
 use zerocopy::Immutable;
 
 use super::{
+    Array,
     Index,
     IndexedKey,
     Key,
@@ -130,6 +131,17 @@ fn encode(&self, encoder: &mut Encoder) -> Result {
     }
 }
 
+impl<T, const N: usize, const KEY_ID: KeyId> Encodable for Array<T, N, KEY_ID>
+where
+    T: Default + Copy,
+    for<'a> IndexedKey<&'a [T], KEY_ID>: Encodable,
+{
+    #[inline(always)]
+    fn encode(&self, encoder: &mut Encoder) -> Result {
+        IndexedKey::<&[T], KEY_ID>::new(Index::new::<0>(), self.vec.as_slice()).encode(encoder)
+    }
+}
+
 impl<T: Encodable> Encodable for Option<T> {
     fn encode(&self, encoder: &mut Encoder) -> Result {
         if let Some(value) = self {
drivers/gpu/nova-core/vgpu/fw/commands.rs +141 -2

159 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#25 lore raw

PATCH v5 25/35 gpu: nova-core: vgpu: add GSP plugin communication buffer

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Each vGPU instance shares a communication buffer with its GSP plugin, located at the start of the instance's management heap. It contains the control and response regions used for plugin RPCs, the message and migration buffers, and the plugin logs.

Describe its layout with a CommBuffer type, and add CommBufferRegion which maps the buffer through BAR1 and provides the operations needed before the first RPC: checking the plugin's boot-ready marker, obtaining the VRAM regions of the logs, and initializing the control and response regions.

The ready marker is stored in the control region's sequence number field, so the regions must only be initialized after the plugin has reported itself ready.

---
 drivers/gpu/nova-core/mm.rs                   |   1 -
 drivers/gpu/nova-core/mm/vram.rs              |   1 +
 drivers/gpu/nova-core/vgpu.rs                 |   1 +
 drivers/gpu/nova-core/vgpu/fw.rs              |  20 ++
 drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs | 201 ++++++++++++++++++
 5 files changed, 223 insertions(+), 1 deletion(-)
 create mode 100644 drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
drivers/gpu/nova-core/mm.rs +0 -1
index f1f86931928c..9489502d3362 100644
@@ -69,7 +69,6 @@ macro_rules! impl_pfn_bounded {
 mod regs;
 pub(super) mod tlb;
 pub(super) mod vmm;
-#[expect(dead_code)]
 pub(crate) mod vram;
 
 /// GPU Memory Manager - owns all core MM components.
drivers/gpu/nova-core/mm/vram.rs +1 -0
index 6054eed9aeb0..7774b15e4c89 100644
@@ -74,6 +74,7 @@ pub(crate) struct VramRegion {
     range: Range<u64>,
 }
 
+#[expect(dead_code)]
 impl VramRegion {
     /// Returns the range covered by this region.
     pub(crate) const fn range(&self) -> &Range<u64> {
drivers/gpu/nova-core/vgpu.rs +1 -0
index 65362ca31ba3..eaff5b8b318d 100644
@@ -29,6 +29,7 @@
 
 mod commands;
 mod fw;
+mod gsp_plugin_comm;
 mod hal;
 mod instance;
 mod vram;
drivers/gpu/nova-core/vgpu/fw.rs +20 -0
index 2d32e196a771..84a89c32a77b 100644
@@ -8,3 +8,23 @@
 
 pub(super) mod commands;
 mod r000_00;
+
+// Alias to avoid repeating the version number with every use.
+use r000_00 as bindings;
+
+pub(super) use bindings::{
+    GSP_PLUGIN_BOOTLOADED,
+    VGPU_CPU_GSP_COMMUNICATION_BUFF_TOTAL_SIZE,
+    VGPU_CPU_GSP_CTRL_BUFF_REGION as RawControlRegion,
+    VGPU_CPU_GSP_CTRL_BUFF_REGION_SIZE,
+    VGPU_CPU_GSP_CTRL_BUFF_VERSION,
+    VGPU_CPU_GSP_ERROR_BUFF_REGION_SIZE,
+    VGPU_CPU_GSP_GUEST_RPC_TRACE_BUFF_REGION_SIZE,
+    VGPU_CPU_GSP_INIT_TASK_LOG_BUFF_REGION_SIZE,
+    VGPU_CPU_GSP_KERNEL_TASK_LOG_BUFF_REGION_SIZE,
+    VGPU_CPU_GSP_MESSAGE_BUFF_REGION_SIZE,
+    VGPU_CPU_GSP_MIGRATION_BUFF_REGION_SIZE,
+    VGPU_CPU_GSP_RESPONSE_BUFF_REGION as RawResponseRegion,
+    VGPU_CPU_GSP_RESPONSE_BUFF_REGION_SIZE,
+    VGPU_CPU_GSP_VGPU_TASK_LOG_BUFF_REGION_SIZE, //
+};
drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs new file +201 -0

201 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#21 lore raw

PATCH v5 21/35 gpu: nova-core: vgpu: add VRAM slot pool

In reply to Alok Kumar

A vGPU type specifies the guest VRAM and GSP plugin management-heap sizes for each instance. Allocating these regions independently fragments VRAM and does not preserve a stable layout for the vGPU type.

Add a standalone slot pool that reserves one exact VRAM range and provides the memory ranges corresponding to a given slot.

---
 drivers/gpu/nova-core/vgpu.rs      |   1 +
 drivers/gpu/nova-core/vgpu/vram.rs | 153 +++++++++++++++++++++++++++++
 2 files changed, 154 insertions(+)
 create mode 100644 drivers/gpu/nova-core/vgpu/vram.rs
drivers/gpu/nova-core/vgpu.rs +1 -0
index ea4bb5915879..5fd9641db579 100644
@@ -23,6 +23,7 @@
 
 mod fw;
 mod hal;
+mod vram;
 
 /// vGPU state detected during GPU construction.
 #[derive(Debug, Clone, Copy)]
drivers/gpu/nova-core/vgpu/vram.rs new file +153 -0

153 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#26 lore raw

PATCH v5 26/35 gpu: nova-core: vgpu: add instance boot

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Start an allocated instance's GSP plugin with its channel map, VRAM, plugin heap and log regions. Clear the old ready marker before BOOTLOAD and wait for firmware to publish a new one.

Retain the command queue and memory dependencies needed by the instance, and map its communication buffers before boot.

---
 drivers/gpu/nova-core/gpu.rs                  |  11 +-
 drivers/gpu/nova-core/gsp/fw/commands.rs      |   1 -
 drivers/gpu/nova-core/vgpu.rs                 |  24 ++-
 drivers/gpu/nova-core/vgpu/commands.rs        |  35 ++++-
 drivers/gpu/nova-core/vgpu/fw/commands.rs     |   2 -
 drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs |  12 ++
 drivers/gpu/nova-core/vgpu/instance.rs        | 138 +++++++++++++++++-
 drivers/gpu/nova-core/vgpu/vram.rs            |   1 -
 8 files changed, 202 insertions(+), 22 deletions(-)
drivers/gpu/nova-core/gpu.rs +6 -5
index 962a6a3f4d29..031878cdb626 100644
@@ -401,8 +401,8 @@ unsafe fn new(
 #[pin_data]
 pub(crate) struct Gpu<'gpu> {
     pub(crate) spec: Spec,
-    /// Drops before the MM and BAR1 mappings needed for instance teardown.
-    #[uses('bar_user, 'chid_pool)]
+    /// Drops before the MM, BAR1 mappings and GSP needed for instance teardown.
+    #[uses('bar_user, 'gsp_resources, 'chid_pool)]
     vgpu: Option<Pin<KBox<VgpuManager<'mm>>>>,
     /// GSP event interrupt registration, and the enable of its subtree.
     ///
@@ -614,15 +614,16 @@ pub(crate) fn new<'a>(
             },
 
             vgpu: {
-                let info = &gsp_resources.boot_result.static_info;
                 match gsp_resources.vgpu_state {
                     VgpuState::Disabled => None,
                     VgpuState::Enabled { .. } => Some(KBox::pin_init(
                         VgpuManager::new(
+                            dev,
+                            &gsp_resources.get_ref().gsp.cmdq,
+                            bar_user.get_ref(),
                             mm.get_ref(),
                             chid_pool.get_ref(),
-                            &info.fifo_engine_list(),
-                            info.vmmu_segment_size,
+                            gsp_resources.static_info(),
                             TOTAL_CHANNELS,
                         ),
                         GFP_KERNEL,
drivers/gpu/nova-core/gsp/fw/commands.rs +0 -1
index d9dd4841566f..362db885bc0c 100644
@@ -335,7 +335,6 @@ pub(crate) struct FifoEngineList {
 }
 
 impl FifoEngineList {
-    #[expect(dead_code)]
     pub(crate) fn gmc_ids(&self) -> &[u32] {
         // PANIC: The type invariant bounds `count` by the array capacity.
         &self.gmc_ids[..self.count]
drivers/gpu/nova-core/vgpu.rs +20 -4
index eaff5b8b318d..e1dbd46338a6 100644
@@ -21,8 +21,15 @@
         ChannelIdPool,
         Chipset, //
     },
-    gsp::commands::FifoEngineList, //
+    gsp::{
+        cmdq::Cmdq,
+        commands::{
+            FifoEngineList,
+            GspStaticInfo, //
+        },
+    },
     mm::{
+        bar_user::BarUser,
         SharedGpuMm, //
     }, //
 };
@@ -129,6 +136,9 @@ pub(crate) struct VgpuManager<'gpu>
 struct VgpuManagerInner<'gpu> {
     #[pin]
     instances: Mutex<VgpuInstances<'gpu>>,
+    dev: &'gpu device::Device<device::Bound>,
+    cmdq: &'gpu Cmdq<'gpu>,
+    bar_user: &'gpu BarUser<'gpu>,
     mm: &'gpu SharedGpuMm<'gpu>,
     chid_pool: &'gpu ChannelIdPool,
     /// VMMU segment size in bytes, or zero if GSP-RM omitted it.
@@ -140,16 +150,22 @@ struct VgpuManagerInner<'gpu> {
 impl<'gpu> VgpuManager<'gpu> {
     /// Retains runtime parameters from a completed vGPU-enabled GSP boot.
     pub(crate) fn new(
+        dev: &'gpu device::Device<device::Bound>,
+        cmdq: &'gpu Cmdq<'gpu>,
+        bar_user: &'gpu BarUser<'gpu>,
         mm: &'gpu SharedGpuMm<'gpu>,
         chid_pool: &'gpu ChannelIdPool,
-        fifo_engine_list: &FifoEngineList,
-        vmmu_segment_size: u64,
+        info: &GspStaticInfo,
         total_channels: u32,
     ) -> impl PinInit<Self> + use<'gpu> {
-        let fifo_engine_list = *fifo_engine_list;
+        let fifo_engine_list = info.fifo_engine_list();
+        let vmmu_segment_size = info.vmmu_segment_size;
         pin_init!(Self {
             inner <- pin_init!(VgpuManagerInner {
                 instances <- new_mutex!(VgpuInstances::new(), "nova-core::vgpu-instances"),
+                dev,
+                cmdq,
+                bar_user,
                 mm,
                 chid_pool,
                 vmmu_segment_size,
drivers/gpu/nova-core/vgpu/commands.rs +34 -1
index 66669948230a..b384c190a66a 100644
@@ -10,13 +10,16 @@
 
 use kernel::{
     device,
-    prelude::*, //
+    prelude::*,
+    time::Delta,
+    transmute::AsBytes, //
 };
 
 use crate::{
     gsp::{
         cmdq::{
             gmc::{
+                CommandPayload,
                 CommandToGsp,
                 MessageFromGsp,
                 MessagePayload, //
@@ -124,3 +127,33 @@ pub(super) fn query_vgpu_properties(
         Ok(properties)
     }
 }
+
+/// The `BOOTLOAD_GSP_VGPU_PLUGIN_TASK` command, which carries NVKV-encoded parameters.
+struct BootloadPluginTask<'a>(&'a [u64]);
+
+impl CommandToGsp for BootloadPluginTask<'_> {
+    const COMMAND: GmcCommandId = GmcCommandId::BootloadGspVgpuPluginTask;
+    type Command = ();
+    type Reply = ();
+    const MAX_REPLY_SIZE: u32 = 0;
+    const COMPLETION_TIMEOUT: Delta = Delta::from_secs(10);
+    type InitError = Infallible;
+
+    fn init(&self) -> impl Init<Self::Command, Self::InitError> {
+        pin_init::init_zeroed()
+    }
+
+    fn variable_payload_len(&self) -> usize {
+        size_of_val(self.0)
+    }
+
+    fn init_variable_payload(&self, dst: &mut CommandPayload<'_>) -> Result {
+        dst.write_all(AsBytes::as_bytes(self.0))
+    }
+}
+
+/// Send BOOTLOAD and check its firmware status.
+pub(super) fn send_bootload(_dev: &device::Device, cmdq: &Cmdq<'_>, payload: &[u64]) -> Result {
+    cmdq.send_gmc_command(BootloadPluginTask(payload), |_| Ok(()))?
+        .map_err(|_| EIO)
+}
drivers/gpu/nova-core/vgpu/fw/commands.rs +0 -2
index 666c549e55b1..a8b80bd6d33b 100644
@@ -52,7 +52,6 @@ pub(crate) struct ChannelMapEntry(u64) {
 impl ChannelMapEntry {
     const KEY: KeyId = 0x1001;
 
-    #[expect(dead_code)]
     pub(crate) fn new(engine_type: u16, index: u16, chid_offset: u32) -> Self {
         Self::zeroed()
             .with_engine_type(engine_type)
@@ -125,7 +124,6 @@ pub(crate) struct BootloadInfo<'a> {
 }
 
 /// Encodes a `VGPU_BOOTLOAD` request using the typed NVKV schema.
-#[expect(dead_code)]
 pub(crate) fn encode_vgpu_bootload(info: BootloadInfo<'_>) -> Result<KVVec<u64>> {
     let request = VgpuBootloadRequest {
         dbdf: info.dbdf.into(),
drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs +12 -0
index 983d5002ff5b..310230702562 100644
@@ -10,6 +10,7 @@
         io_project,
         io_read,
         io_write,
+        Io,
         Mmio, //
     },
     num::casts::FromSafeCast,
@@ -137,6 +138,17 @@ pub(super) fn plugin_logs(&self) -> Result<PluginLogRegions> {
         })
     }
 
+    /// Clear a previous boot marker before starting the plugin.
+    pub(super) fn clear_plugin_ready(&self) -> Result {
+        let seq_num = io_project!(self.view()?, .control.__bindgen_anon_1.message_seq_num);
+
+        seq_num.write_val(0);
+        // Complete the posted clear before firmware can publish its new marker.
+        seq_num.read_val();
+
+        Ok(())
+    }
+
     /// Return whether firmware has published the plugin boot marker.
     pub(super) fn is_plugin_ready(&self) -> Result<bool> {
         let value = io_read!(self.view()?, .control.__bindgen_anon_1.message_seq_num);
drivers/gpu/nova-core/vgpu/instance.rs +130 -8

203 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/vram.rs +0 -1
index 77446b2bdceb..fb7c460b9d97 100644
@@ -76,7 +76,6 @@ pub(super) fn max_slots(&self) -> u32 {
 ///
 /// All device accesses and mappings of its regions must end before dropping the slot.
 #[must_use]
-#[expect(dead_code)]
 pub(super) struct VgpuVramSlot {
     /// Framebuffer VRAM region.
     pub(super) fbmem: VramRegion,
Signature · 1 line
2.53.0
author
#27 lore raw

PATCH v5 27/35 gpu: nova-core: vgpu: add instance shutdown

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Stop the GSP plugin, wait for SHUTDOWN completion, and release its firmware resources with CLEANUP before unmapping the communication buffers.

---
 drivers/gpu/nova-core/gsp/cmdq/gmc.rs         |  1 -
 drivers/gpu/nova-core/vgpu.rs                 |  9 ++-
 drivers/gpu/nova-core/vgpu/commands.rs        | 66 +++++++++++++++
 drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs |  1 -
 drivers/gpu/nova-core/vgpu/instance.rs        | 81 ++++++++++++++++++-
 5 files changed, 151 insertions(+), 7 deletions(-)
drivers/gpu/nova-core/gsp/cmdq/gmc.rs +0 -1
index d4017c2e04ce..b4e956a2ed50 100644
@@ -367,7 +367,6 @@ pub(crate) fn send_gmc_command<C>(
     ///   framing validation.
     ///
     /// Error codes returned by the command initializer and by `on_event` are propagated as-is.
-    #[expect(dead_code)]
     pub(crate) fn send_gmc_command_await_event<C, R>(
         &self,
         command: C,
drivers/gpu/nova-core/vgpu.rs +8 -1
index e1dbd46338a6..fbaaf8e1d6fa 100644
@@ -132,7 +132,7 @@ pub(crate) struct VgpuManager<'gpu>
 ///
 /// The instances kept in the registry borrow the GPU resources below, which makes this type
 /// invariant over `'gpu`.
-#[pin_data]
+#[pin_data(PinnedDrop)]
 struct VgpuManagerInner<'gpu> {
     #[pin]
     instances: Mutex<VgpuInstances<'gpu>>,
@@ -175,3 +175,10 @@ pub(crate) fn new(
         })
     }
 }
+
+#[pinned_drop]
+impl PinnedDrop for VgpuManagerInner<'_> {
+    fn drop(self: Pin<&mut Self>) {
+        self.instances.lock().release_all(&self);
+    }
+}
drivers/gpu/nova-core/vgpu/commands.rs +66 -0

87 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs +0 -1
index 310230702562..e4ce82c6b2d7 100644
@@ -206,7 +206,6 @@ pub(super) fn initialize(&self) -> Result {
     }
 
     /// Invalidate the PTEs and release the communication mapping.
-    #[expect(dead_code)]
     pub(super) fn unmap(&mut self) -> Result {
         self.map.unmap()
     }
drivers/gpu/nova-core/vgpu/instance.rs +77 -4

138 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#28 lore raw

PATCH v5 28/35 gpu: nova-core: vgpu: add GSP plugin RPC transactions

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

A GSP plugin consumes a shared-buffer request after its VF doorbell is rung and publishes completion in the response region.

Add PluginRpc to own the communication mapping together with the instance's stable BAR0 and validated GFID. Accept typed RPC message IDs, copy the payload before publishing its sequence, advance the local sequence, ring and read back the doorbell, then wait for a matching completion and check its firmware status.

Keep one sequence identity for each published request, including a request whose doorbell or wait later fails, and bound completion polling with the RPC timeout. Delegate explicit unmap to the owned communication region so teardown errors retain its owner; ordinary drop releases the mapping through BarMapping.

---
 drivers/gpu/nova-core/gpu.rs                  |   1 +
 drivers/gpu/nova-core/regs.rs                 |  31 +++-
 drivers/gpu/nova-core/vgpu.rs                 |   6 +
 drivers/gpu/nova-core/vgpu/fw.rs              |  13 ++
 drivers/gpu/nova-core/vgpu/fw/commands.rs     |  10 ++
 drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs |  37 ++++-
 drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs  | 155 ++++++++++++++++++
 drivers/gpu/nova-core/vgpu/instance.rs        |  13 +-
 8 files changed, 257 insertions(+), 9 deletions(-)
 create mode 100644 drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs
drivers/gpu/nova-core/gpu.rs +1 -0
index 031878cdb626..0de451fc3d7b 100644
@@ -619,6 +619,7 @@ pub(crate) fn new<'a>(
                     VgpuState::Enabled { .. } => Some(KBox::pin_init(
                         VgpuManager::new(
                             dev,
+                            bar,
                             &gsp_resources.get_ref().gsp.cmdq,
                             bar_user.get_ref(),
                             mm.get_ref(),
drivers/gpu/nova-core/regs.rs +30 -1
index 050054a2b23d..867fc591b43d 100644
@@ -7,13 +7,17 @@
         Io,
         Mmio, //
     },
+    prelude::*,
     sizes::SizeConstants,
     time, //
 };
 use pin_init::Zeroable;
 
 use crate::{
-    driver::NovaRegisters,
+    driver::{
+        Bar0,
+        NovaRegisters, //
+    },
     falcon::{
         DmaTrfCmdSize,
         FalconCoreRev,
@@ -39,6 +43,31 @@
     pub(crate) NV_PBUS_SW_SCRATCH(u32)[64] @ 0x00001400 {}
 }
 
+// VIRTUAL_FUNCTION
+
+register! {
+    base: NovaRegisters;
+
+    // PF BAR0 exposes the virtual-function register window at 0x00b8_0000.
+    pub(crate) NV_VIRTUAL_FUNCTION_PRIV_DOORBELL(u32) @ 0x00b8_2200 {
+        31:0 handle;
+    }
+}
+
+impl NV_VIRTUAL_FUNCTION_PRIV_DOORBELL {
+    const DOORBELL_STRIDE: u32 = 32;
+    const DOORBELL_VECTOR: u32 = 17;
+
+    /// Notify the GSP plugin for the given guest function and read back the doorbell.
+    pub(crate) fn ring_gsp_plugin(bar0: Bar0<'_>, gfid: u16) -> Result {
+        // A `u16` GFID produces a handle of at most 0x1f_fff1, which fits in `u32`.
+        let value = u32::from(gfid) * Self::DOORBELL_STRIDE + Self::DOORBELL_VECTOR;
+        bar0.try_write_reg(Self::zeroed().with_handle(value))?;
+        bar0.try_read(NV_VIRTUAL_FUNCTION_PRIV_DOORBELL)?;
+        Ok(())
+    }
+}
+
 // PGC6 register space.
 //
 // `GC6` is a GPU low-power state where VRAM is in self-refresh and the GPU is powered down (except
drivers/gpu/nova-core/vgpu.rs +6 -0
index fbaaf8e1d6fa..bdb4821751e7 100644
@@ -13,6 +13,7 @@
 };
 
 use crate::{
+    driver::Bar0,
     fsp::{
         Fsp,
         VgpuMode, //
@@ -37,6 +38,7 @@
 mod commands;
 mod fw;
 mod gsp_plugin_comm;
+mod gsp_plugin_rpc;
 mod hal;
 mod instance;
 mod vram;
@@ -137,6 +139,7 @@ struct VgpuManagerInner<'gpu> {
     #[pin]
     instances: Mutex<VgpuInstances<'gpu>>,
     dev: &'gpu device::Device<device::Bound>,
+    bar: Bar0<'gpu>,
     cmdq: &'gpu Cmdq<'gpu>,
     bar_user: &'gpu BarUser<'gpu>,
     mm: &'gpu SharedGpuMm<'gpu>,
@@ -149,8 +152,10 @@ struct VgpuManagerInner<'gpu> {
 
 impl<'gpu> VgpuManager<'gpu> {
     /// Retains runtime parameters from a completed vGPU-enabled GSP boot.
+    #[expect(clippy::too_many_arguments)]
     pub(crate) fn new(
         dev: &'gpu device::Device<device::Bound>,
+        bar: Bar0<'gpu>,
         cmdq: &'gpu Cmdq<'gpu>,
         bar_user: &'gpu BarUser<'gpu>,
         mm: &'gpu SharedGpuMm<'gpu>,
@@ -164,6 +169,7 @@ pub(crate) fn new(
             inner <- pin_init!(VgpuManagerInner {
                 instances <- new_mutex!(VgpuInstances::new(), "nova-core::vgpu-instances"),
                 dev,
+                bar,
                 cmdq,
                 bar_user,
                 mm,
drivers/gpu/nova-core/vgpu/fw.rs +13 -0
index 84a89c32a77b..76bd2b7e4e52 100644
@@ -12,6 +12,8 @@
 // Alias to avoid repeating the version number with every use.
 use r000_00 as bindings;
 
+pub(super) use commands::RpcMessage;
+
 pub(super) use bindings::{
     GSP_PLUGIN_BOOTLOADED,
     VGPU_CPU_GSP_COMMUNICATION_BUFF_TOTAL_SIZE,
@@ -28,3 +30,14 @@
     VGPU_CPU_GSP_RESPONSE_BUFF_REGION_SIZE,
     VGPU_CPU_GSP_VGPU_TASK_LOG_BUFF_REGION_SIZE, //
 };
+
+/// State observed in the response buffer for an expected RPC sequence.
+pub(super) enum RpcResponse {
+    Pending {
+        /// Last sequence completed by firmware.
+        sequence: u32,
+    },
+    Complete {
+        status: u32,
+    },
+}
drivers/gpu/nova-core/vgpu/fw/commands.rs +10 -0
index a8b80bd6d33b..a8f6f0316d25 100644
@@ -28,6 +28,16 @@
     vgpu::Dbdf, //
 };
 
+use super::bindings;
+
+/// Message types supported by the nova-core plugin RPC channel.
+#[expect(dead_code)]
+#[derive(Clone, Copy)]
+#[repr(u32)]
+pub(crate) enum RpcMessage {
+    VersionNegotiation = bindings::MESSAGE_NV_VGPU_CPU_RPC_MSG_VERSION_NEGOTIATION,
+}
+
 #[derive(Clone, Copy)]
 struct SwizzId(u32);
 
drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs +35 -2
index e4ce82c6b2d7..49d85df70018 100644
@@ -29,7 +29,9 @@
 use super::fw::{
     self,
     RawControlRegion,
-    RawResponseRegion, //
+    RawResponseRegion,
+    RpcMessage,
+    RpcResponse, //
 };
 
 /// Layout of the plugin communication region, located at the start of the management heap.
@@ -157,7 +159,6 @@ pub(super) fn is_plugin_ready(&self) -> Result<bool> {
     }
 
     /// Initialize the shared control and response buffers for plugin RPC.
-    #[expect(dead_code)]
     pub(super) fn initialize(&self) -> Result {
         let comm = self.view()?;
         let control = io_project!(comm, .control.__bindgen_anon_1);
@@ -205,6 +206,38 @@ pub(super) fn initialize(&self) -> Result {
         Ok(())
     }
 
+    /// Copy and publish one RPC request to firmware.
+    pub(super) fn submit(&self, message: RpcMessage, sequence: u32, data: &[u8]) -> Result {
+        let comm = self.view()?;
+        let control = io_project!(comm, .control.__bindgen_anon_1);
+        let buffer = io_project!(comm, .message);
+
+        if data.len() > buffer.size() {
+            return Err(E2BIG);
+        }
+        io_project!(buffer, [try: ..data.len()]).copy_from_slice(data);
+
+        // CAST: `RpcMessage` has a `u32` representation.
+        io_write!(control, .message_type, message as u32);
+        io_write!(control, .message_seq_num, sequence);
+
+        Ok(())
+    }
+
+    /// Read firmware's response for an expected RPC sequence.
+    pub(super) fn response(&self, expected_sequence: u32) -> Result<RpcResponse> {
+        let response = io_project!(self.view()?, .response.__bindgen_anon_1);
+
+        let sequence = io_read!(response, .message_seq_num_processed);
+        if sequence != expected_sequence {
+            return Ok(RpcResponse::Pending { sequence });
+        }
+
+        Ok(RpcResponse::Complete {
+            status: io_read!(response, .result_code),
+        })
+    }
+
     /// Invalidate the PTEs and release the communication mapping.
     pub(super) fn unmap(&mut self) -> Result {
         self.map.unmap()
drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs new file +155 -0

155 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/instance.rs +7 -6
index 2d045ebcd9cd..94735df79e1a 100644
@@ -42,6 +42,7 @@
         VgpuProperties, //
     },
     gsp_plugin_comm::CommBufferRegion,
+    gsp_plugin_rpc::PluginRpc,
     vram::{
         VgpuVramLayout,
         VgpuVramSlot,
@@ -147,7 +148,7 @@ struct VgpuInstance<'gpu> {
     vgpu_type: VgpuType,
     vm_pid: u32,
     num_plugin_channels: u32,
-    comm: CommBufferRegion<'gpu, 'gpu>,
+    plugin_rpc: PluginRpc<'gpu, 'gpu>,
     // Unmap the communication region before returning its slot and channel IDs.
     vram_slot: VgpuVramSlot,
     chids: ChannelIdReservation<'gpu>,
@@ -176,7 +177,7 @@ fn teardown(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
                 send_cleanup(vgpu.dev, vgpu.cmdq, self.gfid)?;
                 self.needs_teardown = false;
             }
-            self.comm.unmap()
+            self.plugin_rpc.unmap()
         })();
         if let Err(error) = result {
             self.failure = Some(error);
@@ -193,7 +194,7 @@ fn bootload(
     ) -> Result {
         let fb = &self.vram_slot.fbmem;
         let mgmt = &self.vram_slot.mgmt_heap;
-        let logs = self.comm.plugin_logs()?;
+        let logs = self.plugin_rpc.comm().plugin_logs()?;
 
         let payload = encode_vgpu_bootload(BootloadInfo {
             dbdf: self.dbdf,
@@ -221,11 +222,11 @@ fn bootload(
             payload.len() * size_of::<u64>(),
         );
 
-        self.comm.clear_plugin_ready()?;
+        self.plugin_rpc.comm().clear_plugin_ready()?;
         self.needs_teardown = true;
         send_bootload(dev, cmdq, &payload)?;
 
-        wait_plugin_ready(dev, &self.comm)?;
+        wait_plugin_ready(dev, self.plugin_rpc.comm())?;
 
         dev_dbg!(dev, "bootload: gfid={} plugin ready\n", self.gfid.get());
         Ok(())
@@ -357,7 +358,7 @@ fn allocate_instance(
             vgpu_type,
             vm_pid,
             num_plugin_channels: PLUGIN_CHANNELS_PER_ENGINE,
-            comm,
+            plugin_rpc: PluginRpc::new(comm, vgpu.bar, gfid),
             vram_slot,
             chids,
             needs_teardown: false,
Signature · 1 line
2.53.0
author
#29 lore raw

PATCH v5 29/35 gpu: nova-core: vgpu: negotiate the GSP plugin RPC version

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

The host must negotiate the RPC protocol with the booted GSP plugin before sending instance configuration.

After observing the plugin's ready marker, initialize the shared RPC buffers and submit the existing typed version-negotiation request through the instance's PluginRpc channel.

---
 drivers/gpu/nova-core/vgpu/commands.rs       | 20 ++++++++++++++++----
 drivers/gpu/nova-core/vgpu/fw/commands.rs    |  1 -
 drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs |  2 --
 drivers/gpu/nova-core/vgpu/instance.rs       |  3 +++
 4 files changed, 19 insertions(+), 7 deletions(-)
drivers/gpu/nova-core/vgpu/commands.rs +16 -4
index d0fd7ab2593b..c1783ace8b3f 100644
@@ -38,11 +38,15 @@
     },
     sbuffer::SBufferIter,
     vgpu::{
-        fw::commands::{
-            AssignedVfVgpuType,
-            VgpuProperties,
-            VgpuPropertiesSchema, //
+        fw::{
+            commands::{
+                AssignedVfVgpuType,
+                VgpuProperties,
+                VgpuPropertiesSchema, //
+            },
+            RpcMessage,
         },
+        gsp_plugin_rpc::PluginRpc,
         instance::Gfid,
         Dbdf,
     },
@@ -223,3 +227,11 @@ pub(super) fn send_cleanup(dev: &device::Device, cmdq: &Cmdq<'_>, gfid: Gfid) ->
     dev_dbg!(dev, "cleanup: gfid={} done\n", gfid.get());
     Ok(())
 }
+
+/// Negotiate the host protocol with a bootloaded GSP plugin.
+pub(super) fn negotiate_plugin_version(
+    dev: &device::Device,
+    rpc: &mut PluginRpc<'_, '_>,
+) -> Result {
+    rpc.rpc_call(dev, RpcMessage::VersionNegotiation, &[])
+}
drivers/gpu/nova-core/vgpu/fw/commands.rs +0 -1
index a8f6f0316d25..168a2447b67c 100644
@@ -31,7 +31,6 @@
 use super::bindings;
 
 /// Message types supported by the nova-core plugin RPC channel.
-#[expect(dead_code)]
 #[derive(Clone, Copy)]
 #[repr(u32)]
 pub(crate) enum RpcMessage {
drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs +0 -2
index d96f6072a941..c68681d8d08b 100644
@@ -65,7 +65,6 @@ pub(super) fn comm(&self) -> &CommBufferRegion<'map, 'gpu> {
     }
 
     /// Initialize the control and response buffers for the first RPC.
-    #[expect(dead_code)]
     pub(super) fn init_rpc(&mut self) -> Result {
         self.comm.initialize()?;
         self.message_sequence = 0;
@@ -82,7 +81,6 @@ fn next_sequence(&self) -> u32 {
     }
 
     /// Write one RPC message, ring the VF doorbell, and wait for its response.
-    #[expect(dead_code)]
     pub(super) fn rpc_call(
         &mut self,
         dev: &device::Device,
drivers/gpu/nova-core/vgpu/instance.rs +3 -0
index 94735df79e1a..2c8542a45643 100644
@@ -31,6 +31,7 @@
 
 use super::{
     commands::{
+        negotiate_plugin_version,
         send_bootload,
         send_cleanup,
         send_shutdown, //
@@ -161,6 +162,8 @@ impl<'gpu> VgpuInstance<'gpu> {
     fn activate(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
         let dev = vgpu.dev;
         self.bootload(dev, vgpu.cmdq, &vgpu.fifo_engine_list)?;
+        self.plugin_rpc.init_rpc()?;
+        negotiate_plugin_version(dev, &mut self.plugin_rpc)?;
 
         Ok(())
     }
Signature · 1 line
2.53.0
author
#30 lore raw

PATCH v5 30/35 gpu: nova-core: vgpu: send GSP plugin configuration parameters

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

The GSP plugin needs instance identity, channel allocation and host parameters before it can serve guest requests.

Encode the configuration as an NVKV stream, prefix it with its word count and send SETUP_CONFIG_PARAMS_AND_INIT after protocol negotiation through the instance's PluginRpc channel.

Derive the host's opaque device identity from the VF DBDF within the supported 16-bit PCI segment namespace. This identifies the local device without imposing a migration-persistent identity.

Describe the supported whole-GPU configuration and distinguish the optional VMM capability bitmap from the separately reported migration features. Encode the host page size with the kernel's infallible conversion.

---
 drivers/gpu/nova-core/vgpu/commands.rs       |   9 ++
 drivers/gpu/nova-core/vgpu/fw/commands.rs    | 118 +++++++++++++++++++
 drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs |  17 +++
 drivers/gpu/nova-core/vgpu/instance.rs       |  16 +++
 4 files changed, 160 insertions(+)
drivers/gpu/nova-core/vgpu/commands.rs +9 -0
index c1783ace8b3f..70fd35566822 100644
@@ -235,3 +235,12 @@ pub(super) fn negotiate_plugin_version(
 ) -> Result {
     rpc.rpc_call(dev, RpcMessage::VersionNegotiation, &[])
 }
+
+/// Send an instance's encoded configuration to the GSP plugin.
+pub(super) fn send_plugin_config(
+    dev: &device::Device,
+    rpc: &mut PluginRpc<'_, '_>,
+    config: &[u64],
+) -> Result {
+    rpc.rpc_call_nvkv(dev, RpcMessage::SetupConfigParamsAndInit, config)
+}
drivers/gpu/nova-core/vgpu/fw/commands.rs +118 -0

136 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs +17 -0
index c68681d8d08b..1197c427312a 100644
@@ -19,6 +19,7 @@
 
 use kernel::{
     device,
+    num::casts::usize_as_u64,
     prelude::*,
     time::{
         delay::fsleep,
@@ -26,6 +27,7 @@
         Instant,
         Monotonic, //
     },
+    transmute::AsBytes, //
 };
 
 use crate::{
@@ -105,6 +107,21 @@ pub(super) fn rpc_call(
         self.wait_response(dev, sequence)
     }
 
+    /// Send an NVKV stream prefixed by its word count.
+    pub(super) fn rpc_call_nvkv(
+        &mut self,
+        dev: &device::Device,
+        message_type: RpcMessage,
+        encoded: &[u64],
+    ) -> Result {
+        let word_count = usize_as_u64(encoded.len());
+        let mut payload = KVec::new();
+        payload.extend_from_slice(&word_count.to_le_bytes(), GFP_KERNEL)?;
+        payload.extend_from_slice(AsBytes::as_bytes(encoded), GFP_KERNEL)?;
+
+        self.rpc_call(dev, message_type, &payload)
+    }
+
     fn wait_response(&self, dev: &device::Device, expected_sequence: u32) -> Result {
         let start = Instant::<Monotonic>::now();
         let timeout = Delta::from_secs(120);
drivers/gpu/nova-core/vgpu/instance.rs +16 -0
index 2c8542a45643..af1b43533a77 100644
@@ -34,9 +34,11 @@
         negotiate_plugin_version,
         send_bootload,
         send_cleanup,
+        send_plugin_config,
         send_shutdown, //
     },
     fw::commands::{
+        encode_plugin_config_params,
         encode_vgpu_bootload,
         BootloadInfo,
         ChannelMapEntry,
@@ -164,6 +166,7 @@ fn activate(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
         self.bootload(dev, vgpu.cmdq, &vgpu.fifo_engine_list)?;
         self.plugin_rpc.init_rpc()?;
         negotiate_plugin_version(dev, &mut self.plugin_rpc)?;
+        self.configure_plugin(dev)?;
 
         Ok(())
     }
@@ -235,6 +238,19 @@ fn bootload(
         Ok(())
     }
 
+    fn configure_plugin(&mut self, dev: &device::Device) -> Result {
+        let config = encode_plugin_config_params(
+            [0; 16],
+            self.dbdf,
+            self.vgpu_type.vgpu_type_id,
+            self.vm_pid,
+            u32::try_from(self.chids.len()).map_err(|_| EOVERFLOW)?,
+            self.num_plugin_channels,
+        )?;
+
+        send_plugin_config(dev, &mut self.plugin_rpc, &config)
+    }
+
     /// Stop the plugin when firmware may own instance resources.
     fn shutdown(&mut self, dev: &device::Device, cmdq: &Cmdq<'_>) -> Result {
         if self.needs_teardown {
Signature · 1 line
2.53.0
author
#31 lore raw

PATCH v5 31/35 gpu: nova-core: vgpu: update the GSP plugin BME state

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

The vGPU manager reports the enabled bus-mastering state to the GSP plugin after its initial configuration. The guest can then use the vGPU from now on.

Add the BME state request and NVKV encoder, and send the enabled state after configuration succeeds.

---
 drivers/gpu/nova-core/vgpu/commands.rs    | 11 +++++++++++
 drivers/gpu/nova-core/vgpu/fw/commands.rs | 18 ++++++++++++++++++
 drivers/gpu/nova-core/vgpu/instance.rs    |  4 +++-
 3 files changed, 32 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/vgpu/commands.rs +11 -0
index 70fd35566822..d11f9af27ee0 100644
@@ -40,6 +40,7 @@
     vgpu::{
         fw::{
             commands::{
+                encode_plugin_set_bme,
                 AssignedVfVgpuType,
                 VgpuProperties,
                 VgpuPropertiesSchema, //
@@ -244,3 +245,13 @@ pub(super) fn send_plugin_config(
 ) -> Result {
     rpc.rpc_call_nvkv(dev, RpcMessage::SetupConfigParamsAndInit, config)
 }
+
+/// Update the bus-mastering state reported to the GSP plugin.
+pub(super) fn set_plugin_bme(
+    dev: &device::Device,
+    rpc: &mut PluginRpc<'_, '_>,
+    enable: bool,
+) -> Result {
+    let bme = encode_plugin_set_bme(enable)?;
+    rpc.rpc_call_nvkv(dev, RpcMessage::UpdateBmeState, &bme)
+}
drivers/gpu/nova-core/vgpu/fw/commands.rs +18 -0
index c7ff27fcf6d7..10f1427bf355 100644
@@ -37,6 +37,7 @@
 pub(crate) enum RpcMessage {
     VersionNegotiation = bindings::MESSAGE_NV_VGPU_CPU_RPC_MSG_VERSION_NEGOTIATION,
     SetupConfigParamsAndInit = bindings::MESSAGE_NV_VGPU_CPU_RPC_MSG_SETUP_CONFIG_PARAMS_AND_INIT,
+    UpdateBmeState = bindings::MESSAGE_NV_VGPU_CPU_RPC_MSG_UPDATE_BME_STATE,
 }
 
 #[derive(Clone, Copy)]
@@ -329,6 +330,23 @@ pub(crate) fn encode_plugin_config_params(
     Ok(encoder.finish())
 }
 
+nvkv_encode! {
+    struct PluginSetBmeRequest {
+        bme_enable: Key<bool, 0x0100, u32>,
+    }
+}
+
+/// Encodes a plugin BME state update using the typed NVKV schema.
+pub(crate) fn encode_plugin_set_bme(enable: bool) -> Result<KVVec<u64>> {
+    let request = PluginSetBmeRequest {
+        bme_enable: enable.into(),
+    };
+
+    let mut encoder = Encoder::new();
+    request.encode(&mut encoder)?;
+    Ok(encoder.finish())
+}
+
 // TODO: extract from bindings
 #[repr(C)]
 #[derive(FromBytes, IntoBytes)]
drivers/gpu/nova-core/vgpu/instance.rs +3 -1
index af1b43533a77..59d7014d7f69 100644
@@ -35,7 +35,8 @@
         send_bootload,
         send_cleanup,
         send_plugin_config,
-        send_shutdown, //
+        send_shutdown,
+        set_plugin_bme, //
     },
     fw::commands::{
         encode_plugin_config_params,
@@ -167,6 +168,7 @@ fn activate(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
         self.plugin_rpc.init_rpc()?;
         negotiate_plugin_version(dev, &mut self.plugin_rpc)?;
         self.configure_plugin(dev)?;
+        set_plugin_bme(dev, &mut self.plugin_rpc, true)?;
 
         Ok(())
     }
Signature · 1 line
2.53.0
author
#32 lore raw

PATCH v5 32/35 gpu: nova-core: vgpu: add CeUtils commands

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Add Cmdq operations to allocate and free a CeUtils channel and submit guest VRAM scrub requests. Decode the allocation and scrub replies, and validate the returned semaphore address and aperture.

Distinguish an explicit allocation rejection from failures that may leave firmware owning the channel, so callers can decide whether to retain its host resources.

---
 drivers/gpu/nova-core/vgpu/commands.rs        | 153 ++++++++++++++++++
 drivers/gpu/nova-core/vgpu/fw.rs              |   2 +
 drivers/gpu/nova-core/vgpu/fw/commands.rs     |  48 +++++-
 .../gpu/nova-core/vgpu/fw/r000_00/bindings.rs |   1 +
 4 files changed, 202 insertions(+), 2 deletions(-)
drivers/gpu/nova-core/vgpu/commands.rs +153 -0
index d11f9af27ee0..a71379165eaf 100644
@@ -10,6 +10,7 @@
 
 use kernel::{
     device,
+    num::casts::usize_as_u64,
     prelude::*,
     time::Delta,
     transmute::AsBytes, //
@@ -36,16 +37,22 @@
         GmcCommandId,
         GSP_PAGE_SIZE, //
     },
+    mm::PAGE_SIZE,
     sbuffer::SBufferIter,
     vgpu::{
         fw::{
             commands::{
                 encode_plugin_set_bme,
+                AllocCeutilsRequest,
+                AllocCeutilsResponse,
                 AssignedVfVgpuType,
+                ScrubGuestFbRequest,
+                ScrubGuestFbResponse,
                 VgpuProperties,
                 VgpuPropertiesSchema, //
             },
             RpcMessage,
+            NV_ADDR_FBMEM, //
         },
         gsp_plugin_rpc::PluginRpc,
         instance::Gfid,
@@ -255,3 +262,149 @@ pub(super) fn set_plugin_bme(
     let bme = encode_plugin_set_bme(enable)?;
     rpc.rpc_call_nvkv(dev, RpcMessage::UpdateBmeState, &bme)
 }
+
+impl CommandToGsp for AllocCeutilsRequest {
+    const COMMAND: GmcCommandId = GmcCommandId::VgpuMgrAllocGspCeutils;
+    type Command = Self;
+    type Reply = AllocCeutilsResponse;
+    const MAX_REPLY_SIZE: u32 = cv!(size_of::<AllocCeutilsResponse>());
+    type InitError = Infallible;
+
+    fn init(&self) -> impl Init<Self::Command, Self::InitError> {
+        *self
+    }
+}
+
+impl MessageFromGsp for AllocCeutilsResponse {
+    type InitError = Error;
+
+    fn read(payload: &mut MessagePayload<'_>) -> Result<Self, Self::InitError> {
+        payload.read()
+    }
+}
+
+/// The `VGPU_MGR_FREE_GSP_CEUTILS` command.
+struct FreeCeutils(Gfid);
+
+impl CommandToGsp for FreeCeutils {
+    const COMMAND: GmcCommandId = GmcCommandId::VgpuMgrFreeGspCeutils;
+    type Command = u32;
+    type Reply = ();
+    const MAX_REPLY_SIZE: u32 = 0;
+    type InitError = Infallible;
+
+    fn init(&self) -> impl Init<Self::Command, Self::InitError> {
+        u32::from(self.0.get()).to_le()
+    }
+}
+
+impl CommandToGsp for ScrubGuestFbRequest {
+    const COMMAND: GmcCommandId = GmcCommandId::VgpuMgrScrubGuestFb;
+    type Command = Self;
+    type Reply = ScrubGuestFbResponse;
+    const MAX_REPLY_SIZE: u32 = cv!(size_of::<ScrubGuestFbResponse>());
+    type InitError = Infallible;
+
+    fn init(&self) -> impl Init<Self::Command, Self::InitError> {
+        *self
+    }
+}
+
+impl MessageFromGsp for ScrubGuestFbResponse {
+    type InitError = Error;
+
+    fn read(payload: &mut MessagePayload<'_>) -> Result<Self, Self::InitError> {
+        payload.read()
+    }
+}
+
+/// Whether a failed allocation may still have transferred CHID ownership to firmware.
+#[expect(dead_code)]
+pub(super) enum CeUtilsAllocError {
+    /// A matching firmware response explicitly rejected the allocation.
+    NotOwned(Error),
+    /// The request may have completed despite a transport or response-validation error.
+    MayOwn(Error),
+}
+
+/// Allocate a CeUtils channel and validate its semaphore description.
+#[expect(dead_code)]
+pub(super) fn alloc_ceutils(
+    dev: &device::Device,
+    cmdq: &Cmdq<'_>,
+    gfid: Gfid,
+    chid: u32,
+) -> core::result::Result<u64, CeUtilsAllocError> {
+    let request = AllocCeutilsRequest {
+        gfid: u32::from(gfid.get()).to_le(),
+        fixed_chid: chid.to_le(),
+        force_ceid: u32::MAX.to_le(),
+        swizz_id: 0,
+    };
+
+    dev_dbg!(dev, "alloc CeUtils: gfid={} chid={}\n", gfid.get(), chid,);
+
+    let response = cmdq
+        .send_gmc_command(request, |_| Ok(()))
+        .map_err(CeUtilsAllocError::MayOwn)?
+        .map_err(|_| CeUtilsAllocError::NotOwned(EIO))?;
+
+    let semaphore_address = u64::from_le(response.semaphore_address);
+    let semaphore_aperture = u32::from_le(response.semaphore_aperture);
+    let page_size = usize_as_u64(PAGE_SIZE);
+
+    if semaphore_address == 0
+        || !semaphore_address.is_multiple_of(page_size)
+        || semaphore_aperture != NV_ADDR_FBMEM
+    {
+        return Err(CeUtilsAllocError::MayOwn(EINVAL));
+    }
+
+    dev_dbg!(
+        dev,
+        "alloc CeUtils: gfid={} semaphore={:#x}\n",
+        gfid.get(),
+        semaphore_address,
+    );
+    Ok(semaphore_address)
+}
+
+/// Release a CeUtils allocation, including one whose allocation reply was lost.
+#[expect(dead_code)]
+pub(super) fn free_ceutils(dev: &device::Device, cmdq: &Cmdq<'_>, gfid: Gfid) -> Result {
+    dev_dbg!(dev, "free CeUtils: gfid={}\n", gfid.get());
+
+    cmdq.send_gmc_command(FreeCeutils(gfid), |_| Ok(()))?
+        .map_err(|_| EIO)
+}
+
+/// Submit an asynchronous guest FB scrub and return its work identifier.
+#[expect(dead_code)]
+pub(super) fn submit_ceutils_scrub(
+    dev: &device::Device,
+    cmdq: &Cmdq<'_>,
+    gfid: Gfid,
+    fb_offset: u64,
+    fb_size: u64,
+) -> Result<u32> {
+    let request = ScrubGuestFbRequest {
+        gfid: u32::from(gfid.get()).to_le(),
+        reserved: 0,
+        fb_offset: fb_offset.to_le(),
+        fb_size: fb_size.to_le(),
+    };
+
+    dev_dbg!(
+        dev,
+        "submit scrub: gfid={} offset={:#x} size={:#x}\n",
+        gfid.get(),
+        fb_offset,
+        fb_size,
+    );
+
+    let response = cmdq
+        .send_gmc_command(request, |_| Ok(()))?
+        .map_err(|_| EIO)?;
+
+    u32::try_from(u64::from_le(response.work_id)).map_err(|_| EOVERFLOW)
+}
drivers/gpu/nova-core/vgpu/fw.rs +2 -0
index 76bd2b7e4e52..02f51bb8cf7f 100644
@@ -31,6 +31,8 @@
     VGPU_CPU_GSP_VGPU_TASK_LOG_BUFF_REGION_SIZE, //
 };
 
+pub(super) use bindings::NV_ADDR_FBMEM;
+
 /// State observed in the response buffer for an expected RPC sequence.
 pub(super) enum RpcResponse {
     Pending {
drivers/gpu/nova-core/vgpu/fw/commands.rs +46 -2

62 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs +1 -0
index 85f965335b64..e46f7339544a 100644
@@ -8,6 +8,7 @@
 pub type u16_ = __u16;
 pub type u32_ = __u32;
 pub type u64_ = __u64;
+pub const NV_ADDR_FBMEM: u32 = 2;
 pub const GSP_PLUGIN_BOOTLOADED: u32 = 1315261039;
 pub const VGPU_CPU_GSP_CTRL_BUFF_VERSION: u32 = 2;
 pub const VGPU_CPU_GSP_CTRL_BUFF_REGION_SIZE: u32 = 4096;
Signature · 1 line
2.53.0
author
#33 lore raw

PATCH v5 33/35 gpu: nova-core: vgpu: scrub guest VRAM with CeUtils

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Scrub guest VRAM before plugin boot and after plugin shutdown, before its slot can be reused. Reserve the last channel ID in each instance range for CeUtils and give the remaining channels to the plugin.

Submit scrubs in chunks and wait for completion through a temporary BAR1 mapping of the CeUtils semaphore. Release the mapping on both success and failure, preserving a polling error if unmapping also fails.

Keep allocation, scrubbing and release within the instance lifecycle. Retain host resources until device removal when firmware ownership is uncertain or a scrub fails, and do not retry a recorded teardown failure.

---
 drivers/gpu/nova-core/vgpu.rs          |   1 +
 drivers/gpu/nova-core/vgpu/commands.rs |   4 -
 drivers/gpu/nova-core/vgpu/instance.rs |  56 +++++++-
 drivers/gpu/nova-core/vgpu/scrubber.rs | 172 +++++++++++++++++++++++++
 4 files changed, 225 insertions(+), 8 deletions(-)
 create mode 100644 drivers/gpu/nova-core/vgpu/scrubber.rs
drivers/gpu/nova-core/vgpu.rs +1 -0
index bdb4821751e7..e1e2d6bcfd31 100644
@@ -41,6 +41,7 @@
 mod gsp_plugin_rpc;
 mod hal;
 mod instance;
+mod scrubber;
 mod vram;
 
 bitfield! {
drivers/gpu/nova-core/vgpu/commands.rs +0 -4
index a71379165eaf..07a8e071d34d 100644
@@ -319,7 +319,6 @@ fn read(payload: &mut MessagePayload<'_>) -> Result<Self, Self::InitError> {
 }
 
 /// Whether a failed allocation may still have transferred CHID ownership to firmware.
-#[expect(dead_code)]
 pub(super) enum CeUtilsAllocError {
     /// A matching firmware response explicitly rejected the allocation.
     NotOwned(Error),
@@ -328,7 +327,6 @@ pub(super) enum CeUtilsAllocError {
 }
 
 /// Allocate a CeUtils channel and validate its semaphore description.
-#[expect(dead_code)]
 pub(super) fn alloc_ceutils(
     dev: &device::Device,
     cmdq: &Cmdq<'_>,
@@ -370,7 +368,6 @@ pub(super) fn alloc_ceutils(
 }
 
 /// Release a CeUtils allocation, including one whose allocation reply was lost.
-#[expect(dead_code)]
 pub(super) fn free_ceutils(dev: &device::Device, cmdq: &Cmdq<'_>, gfid: Gfid) -> Result {
     dev_dbg!(dev, "free CeUtils: gfid={}\n", gfid.get());
 
@@ -379,7 +376,6 @@ pub(super) fn free_ceutils(dev: &device::Device, cmdq: &Cmdq<'_>, gfid: Gfid) ->
 }
 
 /// Submit an asynchronous guest FB scrub and return its work identifier.
-#[expect(dead_code)]
 pub(super) fn submit_ceutils_scrub(
     dev: &device::Device,
     cmdq: &Cmdq<'_>,
drivers/gpu/nova-core/vgpu/instance.rs +52 -4

115 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/scrubber.rs new file +172 -0

172 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#34 lore raw

PATCH v5 34/35 gpu: nova-core: vgpu: introduce SR-IOV PF APIs

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

Provide PF operations for querying vGPU availability and creating, closing and resetting VF instances.

Validate VF identifiers against the PF's VF count and route lifecycle operations through the manager. Retain the GPU context needed to create plugin RPC channels and return guest PCI properties after activation.

---
 drivers/gpu/nova-core/gpu.rs                  |  20 ++-
 drivers/gpu/nova-core/mm/bar_user.rs          |   1 -
 drivers/gpu/nova-core/mm/vram.rs              |   1 -
 drivers/gpu/nova-core/nova_core.rs            |   6 +
 drivers/gpu/nova-core/vgpu.rs                 |   2 +
 drivers/gpu/nova-core/vgpu/commands.rs        |  10 +-
 drivers/gpu/nova-core/vgpu/fw/commands.rs     |   1 +
 drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs |   2 -
 drivers/gpu/nova-core/vgpu/instance.rs        |  57 ++++++-
 drivers/gpu/nova-core/vgpu/vgpu_api.rs        | 153 ++++++++++++++++++
 drivers/gpu/nova-core/vgpu/vram.rs            |   1 -
 11 files changed, 242 insertions(+), 12 deletions(-)
 create mode 100644 drivers/gpu/nova-core/vgpu/vgpu_api.rs
drivers/gpu/nova-core/gpu.rs +19 -1
index 0de451fc3d7b..a2f78dfb1121 100644
@@ -1,6 +1,9 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use core::ops::Range;
+use core::{
+    num::NonZero,
+    ops::Range, //
+};
 
 use kernel::{
     device,
@@ -468,6 +471,21 @@ fn drop(self: Pin<&mut Self>) {
 }
 
 impl<'gpu> Gpu<'gpu> {
+    pub(crate) fn cmdq(&self) -> &Cmdq<'gpu> {
+        &self.gsp_resources.gsp.cmdq
+    }
+
+    pub(crate) fn vgpu_manager(&self) -> Option<&VgpuManager<'_>> {
+        self.vgpu().as_ref().map(|vgpu| vgpu.as_ref().get_ref())
+    }
+
+    pub(crate) fn vgpu_total_vfs(&self) -> Option<NonZero<u16>> {
+        match self.gsp_resources.vgpu_state {
+            VgpuState::Disabled => None,
+            VgpuState::Enabled { total_vfs } => Some(total_vfs),
+        }
+    }
+
     pub(crate) fn new<'a>(
         pdev: &'gpu pci::Device<device::Core<'a>>,
         bar: Bar0<'gpu>,
drivers/gpu/nova-core/mm/bar_user.rs +0 -1
index 75970cb0b5cb..e0fc62630fbe 100644
@@ -185,7 +185,6 @@ pub(crate) struct BarMapping<'map, 'gpu> {
     unmap_error: Option<Error>,
 }
 
-#[expect(dead_code)]
 impl<'map, 'gpu> BarMapping<'map, 'gpu> {
     /// Maps `region`, which must start and end on a page boundary.
     pub(crate) fn new(
drivers/gpu/nova-core/mm/vram.rs +0 -1
index 7774b15e4c89..6054eed9aeb0 100644
@@ -74,7 +74,6 @@ pub(crate) struct VramRegion {
     range: Range<u64>,
 }
 
-#[expect(dead_code)]
 impl VramRegion {
     /// Returns the range covered by this region.
     pub(crate) const fn range(&self) -> &Range<u64> {
drivers/gpu/nova-core/nova_core.rs +6 -0
index 84f777844592..418571724543 100644
@@ -34,6 +34,12 @@
 
 use debugfs::DebugfsData;
 
+#[cfg(CONFIG_PCI_IOV)]
+pub use vgpu::vgpu_api::{
+    NovaCoreVfApi,
+    VgpuTypeInfo, //
+};
+
 pub(crate) const MODULE_NAME: &core::ffi::CStr = <LocalModule as kernel::ModuleMetadata>::NAME;
 
 /// Pointer to the [`DebugfsData`] of the module.
drivers/gpu/nova-core/vgpu.rs +2 -0
index e1e2d6bcfd31..1aee21dbe740 100644
@@ -42,6 +42,8 @@
 mod hal;
 mod instance;
 mod scrubber;
+#[cfg_attr(not(CONFIG_PCI_IOV), expect(dead_code, unreachable_pub))]
+pub(crate) mod vgpu_api;
 mod vram;
 
 bitfield! {
drivers/gpu/nova-core/vgpu/commands.rs +8 -2
index 07a8e071d34d..ae2ae3b69a1c 100644
@@ -83,7 +83,6 @@ fn read(payload: &mut MessagePayload<'_>) -> Result<Self, Self::InitError> {
 }
 
 /// Query the vGPU type assigned to a VF by its DBDF.
-#[expect(dead_code)]
 pub(super) fn query_assigned_vf_type(
     _dev: &device::Device,
     cmdq: &Cmdq<'_>,
@@ -126,7 +125,6 @@ fn read(payload: &mut MessagePayload<'_>) -> Result<Self, Self::InitError> {
 }
 
 /// Query and decode the firmware properties of one vGPU type.
-#[expect(dead_code)]
 pub(super) fn query_vgpu_properties(
     _dev: &device::Device,
     cmdq: &Cmdq<'_>,
@@ -263,6 +261,14 @@ pub(super) fn set_plugin_bme(
     rpc.rpc_call_nvkv(dev, RpcMessage::UpdateBmeState, &bme)
 }
 
+/// Reset an active GSP plugin.
+pub(super) fn reset_plugin(
+    dev: &device::Device<device::Bound>,
+    rpc: &mut PluginRpc<'_, '_>,
+) -> Result {
+    rpc.rpc_call(dev, RpcMessage::Reset, &[])
+}
+
 impl CommandToGsp for AllocCeutilsRequest {
     const COMMAND: GmcCommandId = GmcCommandId::VgpuMgrAllocGspCeutils;
     type Command = Self;
drivers/gpu/nova-core/vgpu/fw/commands.rs +1 -0
index c2e2ffad2b2d..7cb2db63c3a0 100644
@@ -37,6 +37,7 @@
 pub(crate) enum RpcMessage {
     VersionNegotiation = bindings::MESSAGE_NV_VGPU_CPU_RPC_MSG_VERSION_NEGOTIATION,
     SetupConfigParamsAndInit = bindings::MESSAGE_NV_VGPU_CPU_RPC_MSG_SETUP_CONFIG_PARAMS_AND_INIT,
+    Reset = bindings::MESSAGE_NV_VGPU_CPU_RPC_MSG_RESET,
     UpdateBmeState = bindings::MESSAGE_NV_VGPU_CPU_RPC_MSG_UPDATE_BME_STATE,
 }
 
drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs +0 -2
index 49d85df70018..f9fd8c2a5da0 100644
@@ -80,7 +80,6 @@ struct CommBuffer {
 static_assert!(size_of::<RawResponseRegion>() == cv!(fw::VGPU_CPU_GSP_RESPONSE_BUFF_REGION_SIZE));
 
 /// Physical VRAM regions containing the vGPU plugin logs.
-#[expect(dead_code)]
 pub(super) struct PluginLogRegions {
     pub(super) init: VramRegion,
     pub(super) vgpu: VramRegion,
@@ -94,7 +93,6 @@ pub(super) struct CommBufferRegion<'map, 'gpu> {
     map: BarMapping<'map, 'gpu>,
 }
 
-#[expect(dead_code)]
 impl<'map, 'gpu> CommBufferRegion<'map, 'gpu> {
     /// Map the communication portion of a plugin management heap.
     pub(super) fn new(
drivers/gpu/nova-core/vgpu/instance.rs +53 -4

127 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/vgpu_api.rs new file +153 -0

153 lines not on this page · raw message

drivers/gpu/nova-core/vgpu/vram.rs +0 -1
index fb7c460b9d97..e3edf25549af 100644
@@ -36,7 +36,6 @@ pub(super) struct VgpuVramLayout {
     fb_align: u64,
 }
 
-#[expect(dead_code)]
 impl VgpuVramLayout {
     pub(super) fn new(
         type_id: u32,
Signature · 1 line
2.53.0
author
#35 lore raw

PATCH v5 35/35 gpu: nova-core: mm: keep BAR1 self-test page tables alive

In reply to Alok Kumar

From: Zhi Wang <[email protected]>

The BAR1 self-test creates temporary Vmm and BarUser instances on the live BAR1 page directory. Dropping them releases their page-table pages while parent PDEs still point to those pages. Reusing a freed page for another leaf table can make disjoint BAR mappings alias: unmapping one vGPU then invalidates its sibling's mapping.

Use the supplied persistent BarUser for all tests so the installed page tables remain owned until GPU teardown. Borrow its Vmm for the direct mapping tests and release the mutex guard before testing BarUser::map().

Fixes d669686f8170 ("gpu: nova-core: mm: Add BAR1 memory management self-tests")
---
 drivers/gpu/nova-core/mm/bar_user.rs | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/gpu/nova-core/mm/bar_user.rs +3 -3
index e0fc62630fbe..4a49962f7f68 100644
@@ -329,8 +329,8 @@ pub(super) fn run_self_test(
     let test_vram = VramAddress::from_raw(test_vram_offset);
     let test_pfn = Pfn::from(test_vram);
 
-    // Create a VMM of size 64K to track virtual memory mappings.
-    let mut vmm = Vmm::new(pdb_addr, chipset.mmu_version(), SZ_64K.into_safe_cast())?;
+    // Page tables installed in the live BAR1 PDB must keep their owner until GPU teardown.
+    let mut vmm = bar_user.vmm.lock();
 
     // Create a test mapping.
     let mapped = vmm.map_pages(mm, &[test_pfn], None, true)?;
@@ -490,7 +490,7 @@ pub(super) fn run_self_test(
         test3_passed = false;
     }
 
-    // Release Tests 1-3's Vmm before Test 4 uses the GPU's BarUser on the same PDB.
+    // Release the lock before `BarUser::map()` acquires it again.
     drop(vmm);
 
     // Test 4: Exercise `BarUser::map()` end-to-end.
Signature · 1 line
2.53.0