* [PATCH v5 01/35] gpu: nova-core: populate VF information in GSP_INIT
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
@ 2026-11-24 13:58 ` Alok Kumar
2026-11-24 13:58 ` [PATCH v5 02/35] gpu: nova-core: gsp: pass boot context through setup helpers Alok Kumar
` (33 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:58 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Link: https://lore.kernel.org/nova-gpu/20260730181404.776028-2-zhiw@nvidia.com/
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/gsp/fw/commands.rs | 34 +++++++++++++++++++++++-
1 file changed, 33 insertions(+), 1 deletion(-)
diff --git a/drivers/gpu/nova-core/gsp/fw/commands.rs b/drivers/gpu/nova-core/gsp/fw/commands.rs
index 3c9fa459af88..4cc4b086c1d7 100644
--- a/drivers/gpu/nova-core/gsp/fw/commands.rs
+++ b/drivers/gpu/nova-core/gsp/fw/commands.rs
@@ -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)?,
})
}
}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 02/35] gpu: nova-core: gsp: pass boot context through setup helpers
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
2026-11-24 13:58 ` [PATCH v5 01/35] gpu: nova-core: populate VF information in GSP_INIT Alok Kumar
@ 2026-11-24 13:58 ` Alok Kumar
2026-11-24 13:58 ` [PATCH v5 03/35] gpu: nova-core: gsp: decouple boot context from VgpuManager Alok Kumar
` (32 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:58 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Cc: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/fb.rs b/drivers/gpu/nova-core/fb.rs
index 5ceb7760c78e..26e94d908b77 100644
--- a/drivers/gpu/nova-core/fb.rs
+++ b/drivers/gpu/nova-core/fb.rs
@@ -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(),
diff --git a/drivers/gpu/nova-core/gsp/boot.rs b/drivers/gpu/nova-core/gsp/boot.rs
index 1924f759171b..43a2bbb9de98 100644
--- a/drivers/gpu/nova-core/gsp/boot.rs
+++ b/drivers/gpu/nova-core/gsp/boot.rs
@@ -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(),
diff --git a/drivers/gpu/nova-core/gsp/commands/gmc.rs b/drivers/gpu/nova-core/gsp/commands/gmc.rs
index a6cc5759c2a2..27bd67fbe93e 100644
--- a/drivers/gpu/nova-core/gsp/commands/gmc.rs
+++ b/drivers/gpu/nova-core/gsp/commands/gmc.rs
@@ -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(),
diff --git a/drivers/gpu/nova-core/gsp/fw/commands.rs b/drivers/gpu/nova-core/gsp/fw/commands.rs
index 4cc4b086c1d7..9ecab9418be4 100644
--- a/drivers/gpu/nova-core/gsp/fw/commands.rs
+++ b/drivers/gpu/nova-core/gsp/fw/commands.rs
@@ -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)?,
})
}
}
diff --git a/drivers/gpu/nova-core/gsp/hal/gh100.rs b/drivers/gpu/nova-core/gsp/hal/gh100.rs
index 91201b51030e..f91cdd061706 100644
--- a/drivers/gpu/nova-core/gsp/hal/gh100.rs
+++ b/drivers/gpu/nova-core/gsp/hal/gh100.rs
@@ -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 =
diff --git a/drivers/gpu/nova-core/gsp/hal/tu102.rs b/drivers/gpu/nova-core/gsp/hal/tu102.rs
index 244c7f3ae89e..d866bd6037a2 100644
--- a/drivers/gpu/nova-core/gsp/hal/tu102.rs
+++ b/drivers/gpu/nova-core/gsp/hal/tu102.rs
@@ -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
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 03/35] gpu: nova-core: gsp: decouple boot context from VgpuManager
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
2026-11-24 13:58 ` [PATCH v5 01/35] gpu: nova-core: populate VF information in GSP_INIT Alok Kumar
2026-11-24 13:58 ` [PATCH v5 02/35] gpu: nova-core: gsp: pass boot context through setup helpers Alok Kumar
@ 2026-11-24 13:58 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 04/35] gpu: nova-core: vgpu: detect boot state independently Alok Kumar
` (31 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:58 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Cc: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/fb.rs b/drivers/gpu/nova-core/fb.rs
index 26e94d908b77..882827bcfd3a 100644
--- a/drivers/gpu/nova-core/fb.rs
+++ b/drivers/gpu/nova-core/fb.rs
@@ -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)?,
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 3d693656a5d6..ad200242f0f5 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -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(),
})?,
}),
diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs
index a69362138cce..efb94aad417a 100644
--- a/drivers/gpu/nova-core/gsp.rs
+++ b/drivers/gpu/nova-core/gsp.rs
@@ -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> {
diff --git a/drivers/gpu/nova-core/gsp/fw/commands.rs b/drivers/gpu/nova-core/gsp/fw/commands.rs
index 9ecab9418be4..1b2cd342c404 100644
--- a/drivers/gpu/nova-core/gsp/fw/commands.rs
+++ b/drivers/gpu/nova-core/gsp/fw/commands.rs
@@ -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)?;
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index 6b7e045acea8..e074a8294d36 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -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
}
}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 04/35] gpu: nova-core: vgpu: detect boot state independently
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (2 preceding siblings ...)
2026-11-24 13:58 ` [PATCH v5 03/35] gpu: nova-core: gsp: decouple boot context from VgpuManager Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 05/35] gpu: nova-core: gpu: add a channel ID pool for vGPU Alok Kumar
` (30 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Cc: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/gpu.rs | 11 +++++------
drivers/gpu/nova-core/vgpu.rs | 25 ++++++++-----------------
2 files changed, 13 insertions(+), 23 deletions(-)
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index ad200242f0f5..5c304a129df2 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -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,
})?,
}),
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index e074a8294d36..c59e7d2f933c 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -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
- }
}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 05/35] gpu: nova-core: gpu: add a channel ID pool for vGPU
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (3 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 04/35] gpu: nova-core: vgpu: detect boot state independently Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 06/35] gpu: nova-core: gsp: decode the FIFO engine table Alok Kumar
` (29 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Cc: Alexandre Courbot <acourbot@nvidia.com>
Suggested-by: Eliot Courtney <ecourtney@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/gpu.rs | 9 +++++++++
drivers/gpu/nova-core/gpu/channel.rs | 4 ++++
2 files changed, 13 insertions(+)
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 5c304a129df2..b3775365a74e 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -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,
diff --git a/drivers/gpu/nova-core/gpu/channel.rs b/drivers/gpu/nova-core/gpu/channel.rs
index 7263bb4227d8..790d9be7c26c 100644
--- a/drivers/gpu/nova-core/gpu/channel.rs
+++ b/drivers/gpu/nova-core/gpu/channel.rs
@@ -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 {
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 06/35] gpu: nova-core: gsp: decode the FIFO engine table
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (4 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 05/35] gpu: nova-core: gpu: add a channel ID pool for vGPU Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 07/35] gpu: nova-core: vgpu: initialize runtime parameters after GSP boot Alok Kumar
` (28 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
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.
Cc: Alexandre Courbot <acourbot@nvidia.com>
Co-developed-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/gsp/commands.rs b/drivers/gpu/nova-core/gsp/commands.rs
index 8b047744c36d..f5ec27995627 100644
--- a/drivers/gpu/nova-core/gsp/commands.rs
+++ b/drivers/gpu/nova-core/gsp/commands.rs
@@ -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 {
diff --git a/drivers/gpu/nova-core/gsp/commands/gmc.rs b/drivers/gpu/nova-core/gsp/commands/gmc.rs
index 27bd67fbe93e..4f813a780d1b 100644
--- a/drivers/gpu/nova-core/gsp/commands/gmc.rs
+++ b/drivers/gpu/nova-core/gsp/commands/gmc.rs
@@ -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(),
})
}
}
diff --git a/drivers/gpu/nova-core/gsp/fw/commands.rs b/drivers/gpu/nova-core/gsp/fw/commands.rs
index 1b2cd342c404..af3948ed79f5 100644
--- a/drivers/gpu/nova-core/gsp/fw/commands.rs
+++ b/drivers/gpu/nova-core/gsp/fw/commands.rs
@@ -22,8 +22,10 @@
nvkv_decode,
nvkv_encode,
Accumulated,
+ DecoderValue,
Encodable,
Encoder,
+ Indexed,
Key,
Required,
TruncatingArray, //
@@ -316,6 +318,52 @@ pub(crate) fn new(ctx: &GspBootContext<'_, '_>) -> Result<Self> {
// Decode:
+const MAX_FIFO_ENGINES: usize = 64;
+
+/// Bit mask for `NVGMC_SC_ENGINE_FLAGS_IS_HOST_DRIVEN`.
+const ENGINE_FLAGS_IS_HOST_DRIVEN: u32 = 1 << 0;
+
+/// Host-driven GMC engine IDs in hardware FIFO order, including any repeated IDs.
+///
+/// # Invariants
+///
+/// `count` is at most [`MAX_FIFO_ENGINES`]. The first `count` slots are the retained engine IDs.
+#[derive(Copy, Clone)]
+pub(crate) struct FifoEngineList {
+ gmc_ids: [u32; MAX_FIFO_ENGINES],
+ count: usize,
+}
+
+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]
+ }
+}
+
+/// A FIFO engine count that fits the supported tables.
+///
+/// # Invariants
+///
+/// The count is at most [`MAX_FIFO_ENGINES`].
+#[derive(Default)]
+struct FifoEngineCount(usize);
+
+impl TryFrom<DecoderValue<'_>> for FifoEngineCount {
+ type Error = Error;
+
+ fn try_from(value: DecoderValue<'_>) -> Result<Self> {
+ let count = crate::num::u32_as_usize(u32::try_from(value)?);
+ if count > MAX_FIFO_ENGINES {
+ Err(EINVAL)
+ } else {
+ // INVARIANT: The count was checked against the table capacity above.
+ Ok(Self(count))
+ }
+ }
+}
+
// Should decode with UnknownKeyPolicy::Ignore.
nvkv_decode! {
/// Schema for the `GSP_INIT` response.
@@ -326,6 +374,9 @@ pub(crate) struct GspInitResponseSchema => GspInitResponse {
fb_regions: Accumulated<FbRegionSchema>,
bar1_pde_base: Required<Key<u64, 0x1020>>,
vmmu_segment_size: Key<u64, 0x1050>,
+ fifo_engine_count: Key<FifoEngineCount, 0x0500>,
+ fifo_engine_gmc_ids: Indexed<u32, MAX_FIFO_ENGINES, 0x0501>,
+ fifo_engine_flags: Indexed<u32, MAX_FIFO_ENGINES, 0x0502>,
}
}
@@ -337,6 +388,9 @@ pub(crate) struct GspInitResponse {
fb_regions: KVVec<FbRegion>,
bar1_pde_base: u64,
vmmu_segment_size: u64,
+ fifo_engine_count: FifoEngineCount,
+ fifo_engine_gmc_ids: [u32; MAX_FIFO_ENGINES],
+ fifo_engine_flags: [u32; MAX_FIFO_ENGINES],
}
impl GspInitResponse {
@@ -390,6 +444,29 @@ pub(crate) fn total_fb_end(&self) -> Option<u64> {
.checked_add(1)
}
+ /// Returns the host-driven engines in their firmware FIFO order.
+ pub(crate) fn fifo_engine_list(&self) -> FifoEngineList {
+ // INVARIANT: The list starts empty and appends at most one ID per supported input slot.
+ let mut fifo_engine_list = FifoEngineList {
+ gmc_ids: [0; MAX_FIFO_ENGINES],
+ count: 0,
+ };
+ for (&gmc_id, &flags) in self
+ .fifo_engine_gmc_ids
+ .iter()
+ .zip(&self.fifo_engine_flags)
+ .take(self.fifo_engine_count.0)
+ {
+ if flags & ENGINE_FLAGS_IS_HOST_DRIVEN != 0 {
+ // PANIC: At most one slot is filled per input, and the input has at most
+ // MAX_FIFO_ENGINES entries, so the next retained ID always fits.
+ fifo_engine_list.gmc_ids[fifo_engine_list.count] = gmc_id;
+ fifo_engine_list.count += 1;
+ }
+ }
+ fifo_engine_list
+ }
+
/// Returns the BAR1 page directory entry base address.
pub(crate) fn bar1_pde_base(&self) -> u64 {
self.bar1_pde_base
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 07/35] gpu: nova-core: vgpu: initialize runtime parameters after GSP boot
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (5 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 06/35] gpu: nova-core: gsp: decode the FIFO engine table Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 08/35] gpu: nova-core: vgpu: reserve the 48-VM WPR2 heap Alok Kumar
` (27 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Cc: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index b3775365a74e..cf7173b72a13 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -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,
+ )),
+ }
+ },
+
})
}
diff --git a/drivers/gpu/nova-core/gsp/commands.rs b/drivers/gpu/nova-core/gsp/commands.rs
index f5ec27995627..799f26e0ae74 100644
--- a/drivers/gpu/nova-core/gsp/commands.rs
+++ b/drivers/gpu/nova-core/gsp/commands.rs
@@ -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
}
diff --git a/drivers/gpu/nova-core/gsp/commands/gmc.rs b/drivers/gpu/nova-core/gsp/commands/gmc.rs
index 4f813a780d1b..14e04db90594 100644
--- a/drivers/gpu/nova-core/gsp/commands/gmc.rs
+++ b/drivers/gpu/nova-core/gsp/commands/gmc.rs
@@ -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,
})
}
}
diff --git a/drivers/gpu/nova-core/gsp/fw/commands.rs b/drivers/gpu/nova-core/gsp/fw/commands.rs
index af3948ed79f5..d9dd4841566f 100644
--- a/drivers/gpu/nova-core/gsp/fw/commands.rs
+++ b/drivers/gpu/nova-core/gsp/fw/commands.rs
@@ -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],
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index c59e7d2f933c..8a6d87233aaf 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -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,
+ }
+ }
+}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 08/35] gpu: nova-core: vgpu: reserve the 48-VM WPR2 heap
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (6 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 07/35] gpu: nova-core: vgpu: initialize runtime parameters after GSP boot Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 09/35] gpu: nova-core: mm: replace BarUserAccess accessors with typed MMIO view Alok Kumar
` (26 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/fb.rs b/drivers/gpu/nova-core/fb.rs
index 882827bcfd3a..ba68a812b095 100644
--- a/drivers/gpu/nova-core/fb.rs
+++ b/drivers/gpu/nova-core/fb.rs
@@ -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()),
),
})
}
diff --git a/drivers/gpu/nova-core/gsp/fw.rs b/drivers/gpu/nova-core/gsp/fw.rs
index 6e44fe14b2f4..46d3605b24b1 100644
--- a/drivers/gpu/nova-core/gsp/fw.rs
+++ b/drivers/gpu/nova-core/gsp/fw.rs
@@ -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
diff --git a/drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs b/drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs
index 454d0ea9360f..fa17d3e2edf6 100644
--- a/drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs
+++ b/drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs
@@ -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;
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 09/35] gpu: nova-core: mm: replace BarUserAccess accessors with typed MMIO view
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (7 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 08/35] gpu: nova-core: vgpu: reserve the 48-VM WPR2 heap Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 10/35] gpu: nova-core: mm: retain BAR1 reservations after unmap failure Alok Kumar
` (25 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs, Alexandre Courbot
From: Alexandre Courbot <gnurou@gmail.com>
`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.
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/mm/bar_user.rs | 58 ++++++++++++----------------
1 file changed, 25 insertions(+), 33 deletions(-)
diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
index 2e8bd2a8ed91..f82372ccab6e 100644
--- a/drivers/gpu/nova-core/mm/bar_user.rs
+++ b/drivers/gpu/nova-core/mm/bar_user.rs
@@ -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 {
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 10/35] gpu: nova-core: mm: retain BAR1 reservations after unmap failure
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (8 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 09/35] gpu: nova-core: mm: replace BarUserAccess accessors with typed MMIO view Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 11/35] gpu: nova-core: mm: borrow BarUser for temporary BAR1 access Alok Kumar
` (24 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/mm/bar_user.rs | 35 +++++++++++++++++++---------
drivers/gpu/nova-core/mm/vmm.rs | 18 +++++++-------
2 files changed, 34 insertions(+), 19 deletions(-)
diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
index f82372ccab6e..5a8770782d14 100644
--- a/drivers/gpu/nova-core/mm/bar_user.rs
+++ b/drivers/gpu/nova-core/mm/bar_user.rs
@@ -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.
diff --git a/drivers/gpu/nova-core/mm/vmm.rs b/drivers/gpu/nova-core/mm/vmm.rs
index 51b500a27233..49b1e5db1498 100644
--- a/drivers/gpu/nova-core/mm/vmm.rs
+++ b/drivers/gpu/nova-core/mm/vmm.rs
@@ -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(())
}
}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 11/35] gpu: nova-core: mm: borrow BarUser for temporary BAR1 access
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (9 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 10/35] gpu: nova-core: mm: retain BAR1 reservations after unmap failure Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 12/35] gpu: nova-core: mm: add VramBlock Alok Kumar
` (23 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Cc: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/gpu.rs | 2 +-
drivers/gpu/nova-core/mm/bar_user.rs | 16 ++++++++--------
2 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index cf7173b72a13..03d0411008c9 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -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,
) {
diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
index 5a8770782d14..ff1d0e443281 100644
--- a/drivers/gpu/nova-core/mm/bar_user.rs
+++ b/drivers/gpu/nova-core/mm/bar_user.rs
@@ -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<'_>,
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 12/35] gpu: nova-core: mm: add VramBlock
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (10 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 11/35] gpu: nova-core: mm: borrow BarUser for temporary BAR1 access Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 13/35] gpu: nova-core: mm: add VramRegion Alok Kumar
` (22 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Cc: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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
diff --git a/drivers/gpu/nova-core/mm.rs b/drivers/gpu/nova-core/mm.rs
index f53886f9ed91..a0aeb96bfa36 100644
--- a/drivers/gpu/nova-core/mm.rs
+++ b/drivers/gpu/nova-core/mm.rs
@@ -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.
///
diff --git a/drivers/gpu/nova-core/mm/vram.rs b/drivers/gpu/nova-core/mm/vram.rs
new file mode 100644
index 000000000000..6839960eeb2c
--- /dev/null
+++ b/drivers/gpu/nova-core/mm/vram.rs
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! VRAM allocation.
+
+use core::ops::Range;
+
+use kernel::{
+ gpu::buddy::{
+ AllocatedBlocks,
+ GpuBuddyAllocFlags,
+ GpuBuddyAllocMode, //
+ },
+ num::casts::FromSafeCast,
+ prelude::*,
+ ptr::Alignment,
+ sync::Arc, //
+};
+
+use super::{
+ GpuMm,
+ PAGE_SIZE, //
+};
+
+/// A physically contiguous VRAM allocation.
+///
+/// # Invariants
+///
+/// `range.start <= range.end`.
+pub(crate) struct VramBlock {
+ _blocks: Pin<KBox<AllocatedBlocks>>,
+ range: Range<u64>,
+}
+
+impl VramBlock {
+ /// Returns the range covered by this VRAM block.
+ pub(crate) const fn range(&self) -> &Range<u64> {
+ &self.range
+ }
+}
+
+impl GpuMm<'_> {
+ /// Allocates an exact byte range relative to the buddy allocator's base.
+ pub(crate) fn alloc_vram_range(
+ &self,
+ range: Range<u64>,
+ align: Alignment,
+ ) -> Result<Arc<VramBlock>> {
+ const PAGE_SIZE_ALIGN: Alignment = Alignment::new::<PAGE_SIZE>();
+
+ let align = if align > PAGE_SIZE_ALIGN {
+ align
+ } else {
+ PAGE_SIZE_ALIGN
+ };
+ let size = range.end.checked_sub(range.start).ok_or(EINVAL)?;
+ let buddy = self.buddy();
+ let base = buddy.base_offset();
+ let start = base.checked_add(range.start).ok_or(EOVERFLOW)?;
+ let end = base.checked_add(range.end).ok_or(EOVERFLOW)?;
+ if !start.is_multiple_of(u64::from_safe_cast(align.as_usize())) {
+ return Err(EINVAL);
+ }
+
+ let blocks = KBox::pin_init(
+ buddy.alloc_blocks(
+ GpuBuddyAllocMode::Range(range),
+ size,
+ align,
+ GpuBuddyAllocFlags::default(),
+ ),
+ GFP_KERNEL,
+ )?;
+
+ Ok(Arc::new(
+ VramBlock {
+ _blocks: blocks,
+ // INVARIANT: `range.start <= range.end` was checked above, hence
+ // `address <= end`.
+ range: start..end,
+ },
+ GFP_KERNEL,
+ )?)
+ }
+}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 13/35] gpu: nova-core: mm: add VramRegion
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (11 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 12/35] gpu: nova-core: mm: add VramBlock Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 14/35] gpu: nova-core: mm: add BarMapping Alok Kumar
` (21 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Cc: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/mm/vram.rs | 56 ++++++++++++++++++++++++++++++++
1 file changed, 56 insertions(+)
diff --git a/drivers/gpu/nova-core/mm/vram.rs b/drivers/gpu/nova-core/mm/vram.rs
index 6839960eeb2c..6054eed9aeb0 100644
--- a/drivers/gpu/nova-core/mm/vram.rs
+++ b/drivers/gpu/nova-core/mm/vram.rs
@@ -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<'_> {
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 14/35] gpu: nova-core: mm: add BarMapping
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (12 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 13/35] gpu: nova-core: mm: add VramRegion Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 15/35] gpu: nova-core: mm: add SharedGpuMm Alok Kumar
` (20 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Cc: Alistair Popple <apopple@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/mm/bar_user.rs | 100 +++++++++++++++++++++++++++
1 file changed, 100 insertions(+)
diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
index ff1d0e443281..243f8739dfe6 100644
--- a/drivers/gpu/nova-core/mm/bar_user.rs
+++ b/drivers/gpu/nova-core/mm/bar_user.rs
@@ -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`
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 15/35] gpu: nova-core: mm: add SharedGpuMm
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (13 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 14/35] gpu: nova-core: mm: add BarMapping Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 16/35] gpu: nova-core: gsp: cmdq: gmc: add types for variable-length payloads Alok Kumar
` (19 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Alexandre Courbot <acourbot@nvidia.com>
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.
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/mm.rs | 31 +++++++++++++++++++++++++++-
drivers/gpu/nova-core/mm/bar_user.rs | 9 ++++----
2 files changed, 35 insertions(+), 5 deletions(-)
diff --git a/drivers/gpu/nova-core/mm.rs b/drivers/gpu/nova-core/mm.rs
index a0aeb96bfa36..d4cba022ccad 100644
--- a/drivers/gpu/nova-core/mm.rs
+++ b/drivers/gpu/nova-core/mm.rs
@@ -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;
diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
index 243f8739dfe6..75970cb0b5cb 100644
--- a/drivers/gpu/nova-core/mm/bar_user.rs
+++ b/drivers/gpu/nova-core/mm/bar_user.rs
@@ -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);
}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 16/35] gpu: nova-core: gsp: cmdq: gmc: add types for variable-length payloads
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (14 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 15/35] gpu: nova-core: mm: add SharedGpuMm Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 17/35] gpu: nova-core: gsp: add the vGPU commands to GmcCommandId Alok Kumar
` (18 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Alexandre Courbot <acourbot@nvidia.com>
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.
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/gsp/cmdq/gmc.rs b/drivers/gpu/nova-core/gsp/cmdq/gmc.rs
index 7215cbfa5ca0..bf54f73afbc8 100644
--- a/drivers/gpu/nova-core/gsp/cmdq/gmc.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq/gmc.rs
@@ -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(())
}
}
diff --git a/drivers/gpu/nova-core/gsp/commands/gmc.rs b/drivers/gpu/nova-core/gsp/commands/gmc.rs
index 14e04db90594..e1d47e86c82e 100644
--- a/drivers/gpu/nova-core/gsp/commands/gmc.rs
+++ b/drivers/gpu/nova-core/gsp/commands/gmc.rs
@@ -11,34 +11,33 @@
transmute::AsBytes, //
};
-use crate::{
- gsp::{
- cmdq::{
- gmc::{
- CommandToGsp,
- MessageFromGsp, //
- },
- NoReply, //
+use crate::gsp::{
+ cmdq::{
+ gmc::{
+ CommandPayload,
+ CommandToGsp,
+ MessageFromGsp,
+ MessagePayload, //
},
- commands::GspStaticInfo,
- fw::{
- self,
- commands::{
- GspInitRequest,
- GspInitResponseSchema, //
- },
- GmcCommandId, //
- },
- nvkv::{
- Decoder,
- Encodable,
- Encoder,
- Schema,
- UnknownKeyPolicy, //
+ NoReply,
+ },
+ commands::GspStaticInfo,
+ fw::{
+ self,
+ commands::{
+ GspInitRequest,
+ GspInitResponseSchema, //
},
- GspBootContext, //
+ GmcCommandId,
+ },
+ nvkv::{
+ Decoder,
+ Encodable,
+ Encoder,
+ Schema,
+ UnknownKeyPolicy, //
},
- sbuffer::SBufferIter, //
+ GspBootContext,
};
/// The `GSP_INIT` command, which carries the system information and registry keys to GSP-RM.
@@ -88,10 +87,7 @@ fn variable_payload_len(&self) -> usize {
self.payload_bytes().len()
}
- fn init_variable_payload(
- &self,
- dst: &mut SBufferIter<core::array::IntoIter<&mut [u8], 2>>,
- ) -> Result {
+ fn init_variable_payload(&self, dst: &mut CommandPayload<'_>) -> Result {
dst.write_all(self.payload_bytes())
}
}
@@ -147,7 +143,7 @@ impl MessageFromGsp for GspStaticInfo {
/// 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> {
+ fn read(payload: &mut MessagePayload<'_>) -> Result<Self> {
let bytes = payload.flush_into_kvec(GFP_KERNEL)?;
let chunks = bytes.chunks_exact(size_of::<u64>());
diff --git a/drivers/gpu/nova-core/gsp/load_exec.rs b/drivers/gpu/nova-core/gsp/load_exec.rs
index 6ea853e31b77..cef6f314151a 100644
--- a/drivers/gpu/nova-core/gsp/load_exec.rs
+++ b/drivers/gpu/nova-core/gsp/load_exec.rs
@@ -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)?;
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 17/35] gpu: nova-core: gsp: add the vGPU commands to GmcCommandId
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (15 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 16/35] gpu: nova-core: gsp: cmdq: gmc: add types for variable-length payloads Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 18/35] gpu: nova-core: gsp: cmdq: add send_gmc_command_await_event Alok Kumar
` (17 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Alexandre Courbot <acourbot@nvidia.com>
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.
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/gsp/cmdq.rs | 2 +-
drivers/gpu/nova-core/gsp/fw.rs | 14 ++++++++++++++
2 files changed, 15 insertions(+), 1 deletion(-)
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index 990edfcd2bc2..0977cba4d122 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -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.
diff --git a/drivers/gpu/nova-core/gsp/fw.rs b/drivers/gpu/nova-core/gsp/fw.rs
index 46d3605b24b1..6daabb6aea78 100644
--- a/drivers/gpu/nova-core/gsp/fw.rs
+++ b/drivers/gpu/nova-core/gsp/fw.rs
@@ -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,
}
}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 18/35] gpu: nova-core: gsp: cmdq: add send_gmc_command_await_event
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (16 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 17/35] gpu: nova-core: gsp: add the vGPU commands to GmcCommandId Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 19/35] gpu: nova-core: vgpu: add r000 plugin bindings Alok Kumar
` (16 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Alexandre Courbot <acourbot@nvidia.com>
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`.
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/gsp/cmdq/gmc.rs | 44 +++++++++++++++++++++++++++
1 file changed, 44 insertions(+)
diff --git a/drivers/gpu/nova-core/gsp/cmdq/gmc.rs b/drivers/gpu/nova-core/gsp/cmdq/gmc.rs
index bf54f73afbc8..d4017c2e04ce 100644
--- a/drivers/gpu/nova-core/gsp/cmdq/gmc.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq/gmc.rs
@@ -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
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 19/35] gpu: nova-core: vgpu: add r000 plugin bindings
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (17 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 18/35] gpu: nova-core: gsp: cmdq: add send_gmc_command_await_event Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 20/35] gpu: nova-core: gsp: factor out NVKV payload conversion Alok Kumar
` (15 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
.../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
diff --git a/drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs b/drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs
index fa17d3e2edf6..f836d7ee84a0 100644
--- a/drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs
+++ b/drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs
@@ -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)]
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index 8a6d87233aaf..ea4bb5915879 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -21,6 +21,7 @@
gsp::commands::FifoEngineList, //
};
+mod fw;
mod hal;
/// vGPU state detected during GPU construction.
diff --git a/drivers/gpu/nova-core/vgpu/fw.rs b/drivers/gpu/nova-core/vgpu/fw.rs
new file mode 100644
index 000000000000..e4571cfe11a3
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/fw.rs
@@ -0,0 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+mod r000_00;
diff --git a/drivers/gpu/nova-core/vgpu/fw/r000_00.rs b/drivers/gpu/nova-core/vgpu/fw/r000_00.rs
new file mode 100644
index 000000000000..77d6b06961f7
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/fw/r000_00.rs
@@ -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");
diff --git a/drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs b/drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs
new file mode 100644
index 000000000000..85f965335b64
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: GPL-2.0
+
+pub type __u8 = ffi::c_uchar;
+pub type __u16 = ffi::c_ushort;
+pub type __u32 = ffi::c_uint;
+pub type __u64 = ffi::c_ulonglong;
+pub type u8_ = __u8;
+pub type u16_ = __u16;
+pub type u32_ = __u32;
+pub type u64_ = __u64;
+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;
+pub const VGPU_CPU_GSP_RESPONSE_BUFF_REGION_SIZE: u32 = 4096;
+pub const VGPU_CPU_GSP_MESSAGE_BUFF_REGION_SIZE: u32 = 4096;
+pub const VGPU_CPU_GSP_MIGRATION_BUFF_REGION_SIZE: u32 = 2097152;
+pub const VGPU_CPU_GSP_ERROR_BUFF_REGION_SIZE: u32 = 4096;
+pub const VGPU_CPU_GSP_INIT_TASK_LOG_BUFF_REGION_SIZE: u32 = 131072;
+pub const VGPU_CPU_GSP_VGPU_TASK_LOG_BUFF_REGION_SIZE: u32 = 262144;
+pub const VGPU_CPU_GSP_KERNEL_TASK_LOG_BUFF_REGION_SIZE: u32 = 65536;
+pub const VGPU_CPU_GSP_GUEST_RPC_TRACE_BUFF_REGION_SIZE: u32 = 65536;
+pub const VGPU_CPU_GSP_COMMUNICATION_BUFF_TOTAL_SIZE: u32 = 2637824;
+pub type VGPU_CPU_GSP_BOOL = u32_;
+#[repr(C)]
+#[derive(Debug, Default, Copy, Clone, MaybeZeroable)]
+pub struct VGPU_CPU_GSP_VGX_VERSION {
+ pub major_number: u32_,
+ pub minor_number: u32_,
+}
+#[repr(C)]
+#[derive(Debug, Copy, Clone, MaybeZeroable)]
+pub struct VGPU_CPU_GSP_GUEST_INFO {
+ pub vgx_version: VGPU_CPU_GSP_VGX_VERSION,
+ pub guest_driver_version_buffer_length: u32_,
+ pub guest_version_buffer_length: u32_,
+ pub guest_title_buffer_length: u32_,
+ pub guest_changelist_number: u32_,
+ pub guest_driver_version_buffer: [ffi::c_char; 256usize],
+ pub guest_version_buffer: [ffi::c_char; 256usize],
+ pub guest_title_buffer: [ffi::c_char; 256usize],
+ pub guest_branch_buffer: [ffi::c_char; 256usize],
+}
+impl Default for VGPU_CPU_GSP_GUEST_INFO {
+ fn default() -> Self {
+ let mut s = ::core::mem::MaybeUninit::<Self>::uninit();
+ unsafe {
+ ::core::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
+ s.assume_init()
+ }
+ }
+}
+#[repr(C)]
+#[derive(Copy, Clone, MaybeZeroable)]
+pub union VGPU_CPU_GSP_CTRL_BUFF_REGION {
+ pub buf: [u8_; 4096usize],
+ pub __bindgen_anon_1: VGPU_CPU_GSP_CTRL_BUFF_REGION__bindgen_ty_1,
+}
+#[repr(C)]
+#[derive(Debug, Default, Copy, Clone, MaybeZeroable)]
+pub struct VGPU_CPU_GSP_CTRL_BUFF_REGION__bindgen_ty_1 {
+ pub version: u32_,
+ pub message_type: u32_,
+ pub message_seq_num: u32_,
+ pub __bindgen_padding_0: [u8; 4usize],
+ pub response_buff_offset: u64_,
+ pub message_buff_offset: u64_,
+ pub migration_buff_offset: u64_,
+ pub error_buff_offset: u64_,
+ pub guest_rpc_trace_buff_offset: u64_,
+ pub migration_buf_cpu_access_offset: u32_,
+ pub is_migration_in_progress: u8_,
+ pub __bindgen_padding_1: [u8; 3usize],
+ pub error_buff_cpu_get_idx: u32_,
+ pub guest_rpc_trace_buff_cpu_get_idx: u32_,
+ pub attached_vgpu_count: u32_,
+ pub is_gr_init_done: u8_,
+ pub __bindgen_padding_2: [u8; 3usize],
+ pub host_info: [VGPU_CPU_GSP_CTRL_BUFF_REGION__bindgen_ty_1__bindgen_ty_1; 16usize],
+}
+#[repr(C)]
+#[derive(Debug, Default, Copy, Clone, MaybeZeroable)]
+pub struct VGPU_CPU_GSP_CTRL_BUFF_REGION__bindgen_ty_1__bindgen_ty_1 {
+ pub vgpu_type_id: u32_,
+ pub host_gpu_pci_id: u32_,
+ pub pci_dev_id: u32_,
+ pub vgpu_uuid: [u8_; 16usize],
+}
+impl Default for VGPU_CPU_GSP_CTRL_BUFF_REGION {
+ fn default() -> Self {
+ let mut s = ::core::mem::MaybeUninit::<Self>::uninit();
+ unsafe {
+ ::core::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
+ s.assume_init()
+ }
+ }
+}
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_VERSION_NEGOTIATION: MESSAGE = 1;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_SETUP_CONFIG_PARAMS_AND_INIT: MESSAGE = 2;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_RESET: MESSAGE = 3;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_MIGRATION_STOP_WORK: MESSAGE = 4;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_MIGRATION_CANCEL_STOP: MESSAGE = 5;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_MIGRATION_SAVE_STATE: MESSAGE = 6;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_MIGRATION_CANCEL_SAVE: MESSAGE = 7;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_MIGRATION_RESTORE_STATE: MESSAGE = 8;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_MIGRATION_RESTORE_DEFERRED_STATE: MESSAGE = 9;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_MIGRATION_RESUME_WORK: MESSAGE = 10;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_CONSOLE_VNC_STATE: MESSAGE = 11;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_VF_BAR0_REG_ACCESS: MESSAGE = 12;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_UPDATE_BME_STATE: MESSAGE = 13;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_RESET_MIGRATION_BUFFER_PTR: MESSAGE = 14;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_RELEASE_CLIENT_DATABASE: MESSAGE = 15;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_CHECK_IS_ALIVE: MESSAGE = 16;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_SEND_STATIC_INFO: MESSAGE = 17;
+pub const MESSAGE_NV_VGPU_CPU_RPC_MSG_MAX: MESSAGE = 18;
+pub type MESSAGE = ffi::c_uint;
+#[repr(C)]
+#[derive(Debug, Default, Copy, Clone, MaybeZeroable)]
+pub struct VGPU_CPU_GSP_DISPLAYLESS_SURFACE {
+ pub sequence_update_start: u64_,
+ pub sequence_update_end: u64_,
+ pub effective_fb_page_size: u32_,
+ pub rect_width: u32_,
+ pub rect_height: u32_,
+ pub surface_width: u32_,
+ pub surface_height: u32_,
+ pub surface_size: u32_,
+ pub surface_offset: u32_,
+ pub surface_format: u32_,
+ pub surface_kind: u32_,
+ pub surface_pitch: u32_,
+ pub surface_type: u32_,
+ pub surface_block_height: u8_,
+ pub __bindgen_padding_0: [u8; 3usize],
+ pub is_blanking_enabled: VGPU_CPU_GSP_BOOL,
+ pub is_flip_pending: VGPU_CPU_GSP_BOOL,
+ pub is_free_pending: VGPU_CPU_GSP_BOOL,
+ pub is_memory_blocklinear: VGPU_CPU_GSP_BOOL,
+}
+#[repr(C)]
+#[derive(Copy, Clone, MaybeZeroable)]
+pub union VGPU_CPU_GSP_RESPONSE_BUFF_REGION {
+ pub buf: [u8_; 4096usize],
+ pub __bindgen_anon_1: VGPU_CPU_GSP_RESPONSE_BUFF_REGION__bindgen_ty_1,
+}
+#[repr(C)]
+#[derive(Debug, Copy, Clone, MaybeZeroable)]
+pub struct VGPU_CPU_GSP_RESPONSE_BUFF_REGION__bindgen_ty_1 {
+ pub message_seq_num_received: u32_,
+ pub message_seq_num_processed: u32_,
+ pub result_code: u32_,
+ pub guest_rpc_version: u32_,
+ pub migration_buf_gsp_access_offset: u32_,
+ pub migration_state_save_complete: u32_,
+ pub is_migration_allowed: VGPU_CPU_GSP_BOOL,
+ pub __bindgen_padding_0: [u8; 4usize],
+ pub surface: [VGPU_CPU_GSP_DISPLAYLESS_SURFACE; 4usize],
+ pub error_buff_gsp_put_idx: u32_,
+ pub grid_license_state: u32_,
+ pub guest_os_type: u32_,
+ pub frl_config: u32_,
+ pub guest_info: VGPU_CPU_GSP_GUEST_INFO,
+ pub is_guest_info_populated: VGPU_CPU_GSP_BOOL,
+ pub guest_rpc_trace_buff_gsp_put_idx: u32_,
+}
+impl Default for VGPU_CPU_GSP_RESPONSE_BUFF_REGION__bindgen_ty_1 {
+ fn default() -> Self {
+ let mut s = ::core::mem::MaybeUninit::<Self>::uninit();
+ unsafe {
+ ::core::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
+ s.assume_init()
+ }
+ }
+}
+impl Default for VGPU_CPU_GSP_RESPONSE_BUFF_REGION {
+ fn default() -> Self {
+ let mut s = ::core::mem::MaybeUninit::<Self>::uninit();
+ unsafe {
+ ::core::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
+ s.assume_init()
+ }
+ }
+}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 20/35] gpu: nova-core: gsp: factor out NVKV payload conversion
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (18 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 19/35] gpu: nova-core: vgpu: add r000 plugin bindings Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 21/35] gpu: nova-core: vgpu: add VRAM slot pool Alok Kumar
` (14 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs
index efb94aad417a..4bce365c96e5 100644
--- a/drivers/gpu/nova-core/gsp.rs
+++ b/drivers/gpu/nova-core/gsp.rs
@@ -22,7 +22,7 @@
mod fw;
mod load_exec;
mod logbuffer;
-mod nvkv;
+pub(crate) mod nvkv;
mod regs;
use logbuffer::LogBuffers;
diff --git a/drivers/gpu/nova-core/gsp/commands/gmc.rs b/drivers/gpu/nova-core/gsp/commands/gmc.rs
index e1d47e86c82e..81abeb3264ce 100644
--- a/drivers/gpu/nova-core/gsp/commands/gmc.rs
+++ b/drivers/gpu/nova-core/gsp/commands/gmc.rs
@@ -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)?;
diff --git a/drivers/gpu/nova-core/gsp/nvkv.rs b/drivers/gpu/nova-core/gsp/nvkv.rs
index f81a9e60d89c..5887a61af02a 100644
--- a/drivers/gpu/nova-core/gsp/nvkv.rs
+++ b/drivers/gpu/nova-core/gsp/nvkv.rs
@@ -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::*;
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 21/35] gpu: nova-core: vgpu: add VRAM slot pool
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (19 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 20/35] gpu: nova-core: gsp: factor out NVKV payload conversion Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 22/35] gpu: nova-core: vgpu: query VF assignments and properties Alok Kumar
` (13 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
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.
Co-developed-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index ea4bb5915879..5fd9641db579 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -23,6 +23,7 @@
mod fw;
mod hal;
+mod vram;
/// vGPU state detected during GPU construction.
#[derive(Debug, Clone, Copy)]
diff --git a/drivers/gpu/nova-core/vgpu/vram.rs b/drivers/gpu/nova-core/vgpu/vram.rs
new file mode 100644
index 000000000000..0c840c03f988
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/vram.rs
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! VRAM slot allocation for vGPU instances.
+
+use kernel::{
+ prelude::*,
+ sizes::SizeConstants,
+ sync::Arc, //
+};
+
+use crate::mm::{
+ vram::{
+ VramBlock,
+ VramRegion, //
+ },
+ GpuMm, //
+};
+
+const VRAM_SLOT_MIN_ALIGN: u64 = u64::SZ_4K;
+// `VRAM_SLOT_MIN_ALIGN` is used for alignment.
+static_assert!(VRAM_SLOT_MIN_ALIGN.is_power_of_two());
+
+/// Describes the VRAM layout used by vGPU instances.
+#[derive(Clone, Copy, PartialEq)]
+pub(super) struct VgpuVramLayout {
+ // Firmware ID of the vGPU type this layout was built for.
+ type_id: u32,
+ // Maximum number of slots with this layout.
+ max_slots: u32,
+ // Size of the framebuffer for a vGPU instance.
+ fb_size: u64,
+ // Size of heap for a vGPU instance.
+ heap_size: u64,
+ // Alignment of the framebuffer for vGPU instances.
+ fb_align: u64,
+}
+
+#[expect(dead_code)]
+impl VgpuVramLayout {
+ pub(super) fn new(
+ type_id: u32,
+ max_slots: u32,
+ fb_size: u64,
+ heap_size: u64,
+ fb_align: u64,
+ ) -> Result<Self> {
+ if max_slots == 0 || fb_size == 0 || heap_size == 0 {
+ return Err(EINVAL);
+ }
+
+ let fb_align = core::cmp::max(fb_align, VRAM_SLOT_MIN_ALIGN);
+
+ if !fb_align.is_power_of_two()
+ || !fb_size.is_multiple_of(fb_align)
+ || !heap_size.is_multiple_of(VRAM_SLOT_MIN_ALIGN)
+ {
+ return Err(EINVAL);
+ }
+
+ Ok(Self {
+ type_id,
+ max_slots,
+ fb_size,
+ heap_size,
+ fb_align,
+ })
+ }
+
+ pub(super) fn max_slots(&self) -> u32 {
+ self.max_slots
+ }
+}
+
+/// A description of a VRAM slot.
+///
+/// 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,
+ /// Management heap VRAM region.
+ pub(super) mgmt_heap: VramRegion,
+ /// Index of this slot.
+ pub(super) index: u32,
+}
+
+/// A pool of VRAM slots, split according to a [`VgpuVramLayout`].
+pub(super) struct VgpuVramSlotPool {
+ backing: Arc<VramBlock>,
+ layout: VgpuVramLayout,
+ 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.
+ pub(super) fn new(mm: &GpuMm<'_>, layout: VgpuVramLayout) -> Result<Self> {
+ let max_slots = u64::from(layout.max_slots);
+ // Keep guest VRAM slots contiguous so each starts at `fb_align`;
+ // interleaving page-aligned heaps could misalign later slots.
+ let fb_region_size = layout.fb_size.checked_mul(max_slots).ok_or(EINVAL)?;
+ let heap_region_size = layout.heap_size.checked_mul(max_slots).ok_or(EINVAL)?;
+ let pool_size = fb_region_size.checked_add(heap_region_size).ok_or(EINVAL)?;
+
+ let backing = mm.alloc_vram_range(0..pool_size, cv!(VRAM_SLOT_MIN_ALIGN))?;
+ if !backing.range().start.is_multiple_of(layout.fb_align) {
+ return Err(EINVAL);
+ }
+
+ Ok(Self {
+ backing,
+ layout,
+ fb_region_size,
+ })
+ }
+
+ /// Returns `true` if `layout` is identical to the layout used by this pool.
+ pub(super) fn matches_layout(&self, layout: VgpuVramLayout) -> bool {
+ self.layout == layout
+ }
+
+ /// Returns the VRAM slot corresponding to `index`, or `EINVAL` if `index` is not a valid slot
+ /// index for the pool's layout.
+ pub(super) fn slot(&self, index: u32) -> Result<VgpuVramSlot> {
+ if index >= self.layout.max_slots {
+ return Err(EINVAL);
+ }
+
+ let fb_size = self.layout.fb_size;
+ let fb_offset = fb_size.checked_mul(index.into()).ok_or(EINVAL)?;
+ let fb_end = fb_offset.checked_add(fb_size).ok_or(EINVAL)?;
+
+ let heap_size = self.layout.heap_size;
+ let heap_slot_offset = heap_size.checked_mul(index.into()).ok_or(EINVAL)?;
+ let heap_offset = self
+ .fb_region_size
+ .checked_add(heap_slot_offset)
+ .ok_or(EINVAL)?;
+ let heap_end = heap_offset.checked_add(heap_size).ok_or(EINVAL)?;
+
+ let fbmem = self.backing.region(fb_offset..fb_end)?;
+ let mgmt_heap = self.backing.region(heap_offset..heap_end)?;
+
+ Ok(VgpuVramSlot {
+ fbmem,
+ mgmt_heap,
+ index,
+ })
+ }
+}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 22/35] gpu: nova-core: vgpu: query VF assignments and properties
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (20 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 21/35] gpu: nova-core: vgpu: add VRAM slot pool Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 23/35] gpu: nova-core: vgpu: add instance create/destroy Alok Kumar
` (12 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Co-developed-by: Eliot Courtney <ecourtney@nvidia.com>
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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
diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs
index 4bce365c96e5..125dfd06aab1 100644
--- a/drivers/gpu/nova-core/gsp.rs
+++ b/drivers/gpu/nova-core/gsp.rs
@@ -29,6 +29,7 @@
pub(crate) use logbuffer::RetainedLogs;
pub(crate) use fw::{
+ GmcCommandId,
GspFmcBootParams,
GspFwWprMeta,
LibosMemoryRegionInitArgument,
diff --git a/drivers/gpu/nova-core/gsp/fw.rs b/drivers/gpu/nova-core/gsp/fw.rs
index 6daabb6aea78..5158f0e7c12c 100644
--- a/drivers/gpu/nova-core/gsp/fw.rs
+++ b/drivers/gpu/nova-core/gsp/fw.rs
@@ -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;
diff --git a/drivers/gpu/nova-core/sbuffer.rs b/drivers/gpu/nova-core/sbuffer.rs
index b8c01104c255..fd410aef2a1f 100644
--- a/drivers/gpu/nova-core/sbuffer.rs
+++ b/drivers/gpu/nova-core/sbuffer.rs
@@ -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.
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index 5fd9641db579..0934932e051d 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -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 {
diff --git a/drivers/gpu/nova-core/vgpu/commands.rs b/drivers/gpu/nova-core/vgpu/commands.rs
new file mode 100644
index 000000000000..66669948230a
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/commands.rs
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! vGPU firmware command operations.
+//!
+//! Sends requests, checks responses and coordinates the firmware command
+//! sequences used by instance lifecycle operations.
+
+use core::convert::Infallible;
+
+use kernel::{
+ device,
+ prelude::*, //
+};
+
+use crate::{
+ gsp::{
+ cmdq::{
+ gmc::{
+ CommandToGsp,
+ MessageFromGsp,
+ MessagePayload, //
+ },
+ Cmdq,
+ },
+ nvkv::{
+ nvkv_words,
+ Decoder,
+ Schema,
+ UnknownKeyPolicy, //
+ },
+ GmcCommandId,
+ GSP_PAGE_SIZE, //
+ },
+ vgpu::{
+ fw::commands::{
+ AssignedVfVgpuType,
+ VgpuProperties,
+ VgpuPropertiesSchema, //
+ },
+ Dbdf,
+ },
+};
+
+struct QueryAssignedVfVgpuType(Dbdf);
+
+impl CommandToGsp for QueryAssignedVfVgpuType {
+ const COMMAND: GmcCommandId = GmcCommandId::QueryAssignedVfVgpuType;
+ type Command = u64;
+ type Reply = AssignedVfVgpuType;
+ const MAX_REPLY_SIZE: u32 = cv!(size_of::<AssignedVfVgpuType>());
+ type InitError = Infallible;
+
+ fn init(&self) -> impl Init<Self::Command, Self::InitError> {
+ u64::from(self.0.into_raw()).to_le()
+ }
+}
+
+impl MessageFromGsp for AssignedVfVgpuType {
+ type InitError = Error;
+
+ fn read(payload: &mut MessagePayload<'_>) -> Result<Self, Self::InitError> {
+ payload.read()
+ }
+}
+
+/// 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<'_>,
+ dbdf: Dbdf,
+) -> Result<u32> {
+ let reply = cmdq
+ .send_gmc_command(QueryAssignedVfVgpuType(dbdf), |_| Ok(()))?
+ .map_err(|_| EIO)?;
+
+ Ok(reply.vgpu_type_id)
+}
+
+struct QueryVgpuProperties(u32);
+
+impl CommandToGsp for QueryVgpuProperties {
+ const COMMAND: GmcCommandId = GmcCommandId::QueryVgpuProperties;
+ type Command = u32;
+ type Reply = KBox<VgpuProperties>;
+ /// The reply is NVKV-encoded and varies in length.
+ const MAX_REPLY_SIZE: u32 = cv!(GSP_PAGE_SIZE);
+ type InitError = Infallible;
+
+ fn init(&self) -> impl Init<Self::Command, Self::InitError> {
+ self.0.to_le()
+ }
+}
+
+impl MessageFromGsp for KBox<VgpuProperties> {
+ type InitError = Error;
+
+ fn read(payload: &mut MessagePayload<'_>) -> Result<Self, Self::InitError> {
+ let bytes = payload.flush_into_kvec(GFP_KERNEL)?;
+ let words = nvkv_words(&bytes, &[])?;
+ let decoder = Decoder::new(&words, UnknownKeyPolicy::Ignore);
+ let mut schema = KBox::init(VgpuPropertiesSchema::init(), GFP_KERNEL)?;
+ let properties = KBox::try_init(decoder.decode(&mut *schema)?, GFP_KERNEL)?;
+
+ Ok(properties)
+ }
+}
+
+/// Query and decode the firmware properties of one vGPU type.
+#[expect(dead_code)]
+pub(super) fn query_vgpu_properties(
+ _dev: &device::Device,
+ cmdq: &Cmdq<'_>,
+ type_id: u32,
+) -> Result<KBox<VgpuProperties>> {
+ let properties = cmdq
+ .send_gmc_command(QueryVgpuProperties(type_id), |_| Ok(()))?
+ .map_err(|_| EIO)?;
+
+ if properties.type_id != type_id || properties.max_instance == 0 {
+ Err(EINVAL)
+ } else {
+ Ok(properties)
+ }
+}
diff --git a/drivers/gpu/nova-core/vgpu/fw.rs b/drivers/gpu/nova-core/vgpu/fw.rs
index e4571cfe11a3..2d32e196a771 100644
--- a/drivers/gpu/nova-core/vgpu/fw.rs
+++ b/drivers/gpu/nova-core/vgpu/fw.rs
@@ -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;
diff --git a/drivers/gpu/nova-core/vgpu/fw/commands.rs b/drivers/gpu/nova-core/vgpu/fw/commands.rs
new file mode 100644
index 000000000000..d1864d7ab530
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/fw/commands.rs
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! Wire types and codecs for vGPU commands.
+//!
+//! Defines request encoders and response schemas independently of command
+//! submission and instance lifecycle operations.
+
+use kernel::{
+ alloc::ArrayVec,
+ prelude::*, //
+};
+
+use crate::{
+ gsp::nvkv::{
+ nvkv_decode,
+ Array,
+ Key,
+ Required, //
+ }, //
+};
+
+nvkv_decode! {
+ pub(crate) struct VgpuPropertiesSchema => VgpuProperties {
+ // TODO: `name`/`class` required?
+ name: Array<u8, { VgpuProperties::STRING_LEN }, 0x3100>,
+ class: Array<u8, { VgpuProperties::STRING_LEN }, 0x3101>,
+ type_id: Required<Key<u32, 0x3102>>,
+ bar1_length: Required<Key<u64, 0x3103>>,
+ max_instance: Required<Key<u32, 0x3104>>,
+ ecc: Key<u32, 0x3105>,
+ profile_size: Required<Key<u64, 0x3106>>,
+ max_fps: Key<u32, 0x3107>,
+ num_heads: Key<u32, 0x3108>,
+ max_res_x: Key<u32, 0x3109>,
+ max_res_y: Key<u32, 0x310A>,
+ dev_id: Required<Key<u32, 0x310B>>,
+ subsystem_id: Required<Key<u32, 0x310C>>,
+ fb_length: Required<Key<u64, 0x310D>>,
+ gsp_heap_size: Required<Key<u64, 0x310E>>,
+ fb_reservation: Required<Key<u64, 0x310F>>,
+ }
+}
+
+pub(crate) struct VgpuProperties {
+ name: ArrayVec<u8, { Self::STRING_LEN }>,
+ class: ArrayVec<u8, { Self::STRING_LEN }>,
+ pub(crate) type_id: u32,
+ pub(crate) bar1_length: u64,
+ pub(crate) max_instance: u32,
+ ecc: u32,
+ profile_size: u64,
+ max_fps: u32,
+ num_heads: u32,
+ max_res_x: u32,
+ max_res_y: u32,
+ pub(crate) dev_id: u32,
+ pub(crate) subsystem_id: u32,
+ pub(crate) fb_length: u64,
+ pub(crate) gsp_heap_size: u64,
+ fb_reservation: u64,
+}
+
+impl VgpuProperties {
+ const STRING_LEN: usize = 64;
+}
+
+// TODO: extract from bindings
+#[repr(C)]
+#[derive(FromBytes, IntoBytes)]
+pub(crate) struct AssignedVfVgpuType {
+ pub(crate) vgpu_type_id: u32,
+ _swizz_id: u32,
+ _placement_id: u32,
+}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 23/35] gpu: nova-core: vgpu: add instance create/destroy
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (21 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 22/35] gpu: nova-core: vgpu: query VF assignments and properties Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 24/35] gpu: nova-core: vgpu: encode vGPU boot requests Alok Kumar
` (11 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 03d0411008c9..962a6a3f4d29 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -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);
}
}
diff --git a/drivers/gpu/nova-core/mm.rs b/drivers/gpu/nova-core/mm.rs
index d4cba022ccad..f1f86931928c 100644
--- a/drivers/gpu/nova-core/mm.rs
+++ b/drivers/gpu/nova-core/mm.rs
@@ -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"),
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index 0934932e051d..65362ca31ba3 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -6,8 +6,10 @@
use kernel::{
bitfield,
device,
+ new_mutex,
pci,
- prelude::*, //
+ prelude::*,
+ sync::Mutex, //
};
use crate::{
@@ -20,11 +22,15 @@
Chipset, //
},
gsp::commands::FifoEngineList, //
+ mm::{
+ SharedGpuMm, //
+ }, //
};
mod commands;
mod fw;
mod hal;
+mod instance;
mod vram;
bitfield! {
@@ -99,32 +105,56 @@ fn query_state(
}
}
+use self::instance::VgpuInstances;
+
/// Runtime resources for an enabled vGPU boot.
-pub(crate) struct VgpuManager<'gpu> {
- #[expect(dead_code)]
+#[pin_data]
+pub(crate) struct VgpuManager<'gpu>
+where
+ // Hide the invariant resource lifetime of the instance registry so `VgpuManager` remains
+ // covariant.
+ exists<'res>: 'gpu,
+{
+ #[pin]
+ #[uses('res: invariant)]
+ inner: VgpuManagerInner<'res>,
+}
+
+/// Inner state of [`VgpuManager`].
+///
+/// The instances kept in the registry borrow the GPU resources below, which makes this type
+/// invariant over `'gpu`.
+#[pin_data]
+struct VgpuManagerInner<'gpu> {
+ #[pin]
+ instances: Mutex<VgpuInstances<'gpu>>,
+ mm: &'gpu SharedGpuMm<'gpu>,
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(
+ mm: &'gpu SharedGpuMm<'gpu>,
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,
- }
+ ) -> impl PinInit<Self> + use<'gpu> {
+ let fifo_engine_list = *fifo_engine_list;
+ pin_init!(Self {
+ inner <- pin_init!(VgpuManagerInner {
+ instances <- new_mutex!(VgpuInstances::new(), "nova-core::vgpu-instances"),
+ mm,
+ chid_pool,
+ vmmu_segment_size,
+ total_channels,
+ fifo_engine_list,
+ }),
+ })
}
}
diff --git a/drivers/gpu/nova-core/vgpu/instance.rs b/drivers/gpu/nova-core/vgpu/instance.rs
new file mode 100644
index 000000000000..68c93418cc26
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/instance.rs
@@ -0,0 +1,245 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use core::num::{
+ NonZero,
+ NonZeroUsize, //
+};
+
+use kernel::{
+ prelude::*,
+ ptr::Alignment,
+ sizes::SizeConstants, //
+};
+
+use crate::{
+ gpu::ChannelIdReservation,
+ mm::GpuMm, //
+ num::FromSafeCast,
+};
+
+use super::{
+ fw::commands::VgpuProperties,
+ vram::{
+ VgpuVramLayout,
+ VgpuVramSlot,
+ VgpuVramSlotPool, //
+ },
+ Dbdf,
+ VgpuManagerInner, //
+};
+
+/// Guest Function ID validated against one device's total number of VFs.
+///
+/// GFID 0 is reserved for the PF; VFs start at 1. Keeping the nonzero `u16`
+/// preserves the PCI SR-IOV range when forming a plugin doorbell handle.
+#[repr(transparent)]
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(super) struct Gfid(NonZero<u16>);
+
+impl Gfid {
+ /// Validates an external GFID for a device supporting `total_vfs` VFs.
+ #[expect(dead_code)]
+ pub(super) fn new(gfid: u32, total_vfs: NonZero<u16>) -> Result<Self> {
+ let gfid = u16::try_from(gfid).map_err(|_| EINVAL)?;
+ let gfid = NonZero::new(gfid).ok_or(EINVAL)?;
+
+ if gfid > total_vfs {
+ Err(EINVAL)
+ } else {
+ Ok(Self(gfid))
+ }
+ }
+
+ #[expect(dead_code)]
+ pub(super) const fn get(self) -> u16 {
+ self.0.get()
+ }
+}
+
+/// Resource requirements for one vGPU type.
+struct VgpuType {
+ vgpu_type_id: u32,
+ max_instance: u32,
+ fb_length: u64,
+ gsp_heap_size: u64,
+}
+
+impl From<&VgpuProperties> for VgpuType {
+ fn from(properties: &VgpuProperties) -> Self {
+ Self {
+ vgpu_type_id: properties.type_id,
+ max_instance: properties.max_instance,
+ fb_length: properties.fb_length,
+ gsp_heap_size: properties.gsp_heap_size,
+ }
+ }
+}
+
+/// A vGPU instance and the resources reserved for it.
+#[expect(dead_code)]
+struct VgpuInstance<'gpu> {
+ gfid: Gfid,
+ dbdf: Dbdf,
+ vgpu_type: VgpuType,
+ vm_pid: u32,
+ chids: ChannelIdReservation<'gpu>,
+ vram_slot: VgpuVramSlot,
+}
+
+/// Identity and firmware profile used to allocate an instance.
+pub(super) struct InstanceInfo {
+ gfid: Gfid,
+ dbdf: Dbdf,
+ vgpu_type: VgpuType,
+ vm_pid: u32,
+}
+
+#[expect(dead_code)]
+impl InstanceInfo {
+ pub(super) fn new(gfid: Gfid, dbdf: Dbdf, properties: &VgpuProperties, vm_pid: u32) -> Self {
+ Self {
+ gfid,
+ dbdf,
+ vgpu_type: VgpuType::from(properties),
+ vm_pid,
+ }
+ }
+}
+
+/// Registry of live vGPU instances.
+pub(super) struct VgpuInstances<'gpu> {
+ instances: KVec<VgpuInstance<'gpu>>,
+ vram_slots: Option<VgpuVramSlotPool>,
+}
+
+#[expect(dead_code)]
+impl<'gpu> VgpuInstances<'gpu> {
+ pub(super) const fn new() -> Self {
+ Self {
+ instances: KVec::new(),
+ vram_slots: None,
+ }
+ }
+
+ fn alloc_vram_slot(&mut self, mm: &GpuMm<'_>, layout: VgpuVramLayout) -> Result<VgpuVramSlot> {
+ let allocator = match self.vram_slots.as_mut() {
+ // Don't replace the allocator if the current one already matches the requested layout.
+ Some(allocator) if allocator.matches_layout(layout) => allocator,
+ // The allocator cannot be replaced if there already are instances.
+ Some(_) if !self.instances.is_empty() => return Err(EBUSY),
+ _ => {
+ // Release the previous pool's VRAM so the new one can reuse it.
+ self.vram_slots = None;
+ self.vram_slots.insert(VgpuVramSlotPool::new(mm, layout)?)
+ }
+ };
+
+ // Find the lowest slot index not used by any instance.
+ let index = (0..layout.max_slots())
+ .find(|i| !self.instances.iter().any(|inst| inst.vram_slot.index == *i))
+ .ok_or(ENOSPC)?;
+
+ allocator.slot(index)
+ }
+
+ /// Creates and returns a [`VgpuInstance`].
+ fn allocate_instance(
+ &mut self,
+ vgpu: &VgpuManagerInner<'gpu>,
+ info: InstanceInfo,
+ ) -> Result<VgpuInstance<'gpu>> {
+ let InstanceInfo {
+ gfid,
+ dbdf,
+ vgpu_type,
+ vm_pid,
+ } = info;
+
+ let instance_exists = self
+ .instances
+ .iter()
+ .any(|instance| instance.gfid == gfid || instance.dbdf == dbdf);
+ if instance_exists {
+ return Err(EEXIST);
+ }
+
+ let type_id = vgpu_type.vgpu_type_id;
+ let num_type_instances = self
+ .instances
+ .iter()
+ .filter(|instance| instance.vgpu_type.vgpu_type_id == type_id)
+ .count();
+ if num_type_instances >= usize::from_safe_cast(vgpu_type.max_instance) {
+ return Err(ENOSPC);
+ }
+
+ let channels_per_instance = vgpu
+ .total_channels
+ .checked_div(vgpu_type.max_instance)
+ .map(usize::from_safe_cast)
+ .and_then(NonZeroUsize::new)
+ .ok_or(EINVAL)?;
+ let chids = vgpu
+ .chid_pool
+ .reserve_ids(channels_per_instance, Alignment::SZ_1)?;
+
+ let vram_layout = VgpuVramLayout::new(
+ type_id,
+ vgpu_type.max_instance,
+ vgpu_type.fb_length,
+ vgpu_type.gsp_heap_size,
+ vgpu.vmmu_segment_size,
+ )?;
+
+ let vram_slot = vgpu
+ .mm
+ .with_locked(|mm| self.alloc_vram_slot(mm, vram_layout))?;
+
+ Ok(VgpuInstance {
+ gfid,
+ dbdf,
+ vgpu_type,
+ vm_pid,
+ chids,
+ vram_slot,
+ })
+ }
+
+ /// Remove an instance and release its channel and VRAM reservations.
+ fn destroy_instance(&mut self, gfid: Gfid) -> Result {
+ let instance_index = self
+ .instances
+ .iter()
+ .position(|instance| instance.gfid == gfid)
+ .ok_or(ENOENT)?;
+ let instance = self.instances.remove(instance_index).map_err(|_| EIO)?;
+ drop(instance);
+ Ok(())
+ }
+}
+
+impl VgpuManagerInner<'_> {
+ /// Allocate, register, and activate a vGPU instance.
+ ///
+ /// Keep the registry locked through creation or rollback so duplicate checks and
+ /// type limits remain stable. MM and BAR-user locks are acquired only within
+ /// individual memory operations, in that order.
+ #[expect(dead_code)]
+ fn create_instance(&self, info: InstanceInfo) -> Result {
+ let mut instances = self.instances.lock();
+
+ // Reserve capacity before acquiring resources so registration cannot allocate.
+ instances.instances.reserve(1, GFP_KERNEL)?;
+
+ let instance = instances.allocate_instance(self, info)?;
+
+ // Register live instances, and failed ones whose resources firmware may still own.
+ instances
+ .instances
+ .push_within_capacity(instance)
+ .map_err(|_| EIO)?;
+
+ Ok(())
+ }
+}
diff --git a/drivers/gpu/nova-core/vgpu/vram.rs b/drivers/gpu/nova-core/vgpu/vram.rs
index 0c840c03f988..77446b2bdceb 100644
--- a/drivers/gpu/nova-core/vgpu/vram.rs
+++ b/drivers/gpu/nova-core/vgpu/vram.rs
@@ -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.
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 24/35] gpu: nova-core: vgpu: encode vGPU boot requests
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (22 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 23/35] gpu: nova-core: vgpu: add instance create/destroy Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 25/35] gpu: nova-core: vgpu: add GSP plugin communication buffer Alok Kumar
` (10 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Co-developed-by: Eliot Courtney <ecourtney@nvidia.com>
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/gsp/nvkv.rs b/drivers/gpu/nova-core/gsp/nvkv.rs
index 5887a61af02a..0e8e14f98059 100644
--- a/drivers/gpu/nova-core/gsp/nvkv.rs
+++ b/drivers/gpu/nova-core/gsp/nvkv.rs
@@ -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) {
diff --git a/drivers/gpu/nova-core/gsp/nvkv/encode.rs b/drivers/gpu/nova-core/gsp/nvkv/encode.rs
index c6891c0441ff..c4578e3ecef9 100644
--- a/drivers/gpu/nova-core/gsp/nvkv/encode.rs
+++ b/drivers/gpu/nova-core/gsp/nvkv/encode.rs
@@ -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 {
diff --git a/drivers/gpu/nova-core/vgpu/fw/commands.rs b/drivers/gpu/nova-core/vgpu/fw/commands.rs
index d1864d7ab530..666c549e55b1 100644
--- a/drivers/gpu/nova-core/vgpu/fw/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/fw/commands.rs
@@ -8,18 +8,157 @@
use kernel::{
alloc::ArrayVec,
+ bitfield,
prelude::*, //
};
use crate::{
gsp::nvkv::{
nvkv_decode,
+ nvkv_encode,
Array,
+ Encodable,
+ Encoder,
+ Index, //
Key,
- Required, //
- }, //
+ KeyId,
+ Required,
+ },
+ mm::vram::VramRegion,
+ vgpu::Dbdf, //
};
+#[derive(Clone, Copy)]
+struct SwizzId(u32);
+
+impl SwizzId {
+ const WHOLE_GPU: Self = Self(0xFFFF_FFFF);
+}
+
+impl From<SwizzId> for u32 {
+ fn from(value: SwizzId) -> Self {
+ value.0
+ }
+}
+
+bitfield! {
+ pub(crate) struct ChannelMapEntry(u64) {
+ 15:0 engine_type;
+ 31:16 index;
+ 63:32 chid_offset;
+ }
+}
+
+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)
+ .with_index(index)
+ .with_chid_offset(chid_offset)
+ }
+}
+
+impl Encodable for KVVec<ChannelMapEntry> {
+ fn encode(&self, encoder: &mut Encoder) -> Result {
+ // SAFETY: `ChannelMapEntry` is a `bitfield!` over `u64`, i.e.
+ // `#[repr(transparent)]` around a `u64`, so the entries are
+ // layout-compatible with `u64` and can be viewed as a `u64` slice.
+ let slice = unsafe { core::slice::from_raw_parts(self.as_ptr().cast::<u64>(), self.len()) };
+ encoder.encode_array64(ChannelMapEntry::KEY, Index::new::<0>(), slice)
+ }
+}
+
+bitfield! {
+ struct VgpuBootloadOptions(u64) {
+ }
+}
+
+nvkv_encode! {
+ struct VgpuBootloadRequest {
+ dbdf: Key<Dbdf, 0x0001, u32>,
+ gfid: Key<u32, 0x0002>,
+ vgpu_type: Key<u32, 0x0003>,
+ vm_pid: Key<u32, 0x0004>,
+ swizz_id: Key<SwizzId, 0x0005, u32>,
+ num_channels: Key<u32, 0x0006>,
+ num_plugin_channels: Key<u32, 0x0007>,
+ guest_fb_segment_count: Key<u32, 0x0008>,
+ options: Key<VgpuBootloadOptions, 0x1000, u64>,
+ channel_mapping: KVVec<ChannelMapEntry>,
+ guest_fb_segment_phys_addr: Array<u64, 8, 0x1002>,
+ guest_fb_segment_length: Array<u64, 8, 0x1003>,
+ plugin_heap_phys_addr: Key<u64, 0x1004>,
+ plugin_heap_length: Key<u64, 0x1005>,
+ ctrl_buff_offset: Key<u64, 0x1006>,
+ init_task_log_offset: Key<u64, 0x1007>,
+ init_task_log_size: Key<u64, 0x1008>,
+ vgpu_task_log_offset: Key<u64, 0x1009>,
+ vgpu_task_log_size: Key<u64, 0x100A>,
+ kernel_log_offset: Key<u64, 0x100B>,
+ kernel_log_size: Key<u64, 0x100C>,
+ mig_rm_heap_phys_addr: Key<u64, 0x100D>,
+ mig_rm_heap_length: Key<u64, 0x100E>,
+ }
+}
+
+/// Identity, channel mapping and VRAM regions passed to a GSP plugin at boot.
+///
+/// Region addresses are physical VRAM addresses, including the log fields whose wire
+/// names contain `offset`. The control-buffer offset is relative to the plugin heap.
+pub(crate) struct BootloadInfo<'a> {
+ pub(crate) dbdf: Dbdf,
+ pub(crate) gfid: u32,
+ pub(crate) vgpu_type: u32,
+ pub(crate) vm_pid: u32,
+ pub(crate) num_channels: u32,
+ pub(crate) num_plugin_channels: u32,
+ pub(crate) channel_mapping: KVVec<ChannelMapEntry>,
+ pub(crate) guest_fb: &'a VramRegion,
+ pub(crate) plugin_heap: &'a VramRegion,
+ pub(crate) ctrl_buffer_offset: u64,
+ pub(crate) init_log: &'a VramRegion,
+ pub(crate) vgpu_log: &'a VramRegion,
+ pub(crate) kernel_log: &'a VramRegion,
+}
+
+/// 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(),
+ gfid: info.gfid.into(),
+ vgpu_type: info.vgpu_type.into(),
+ vm_pid: info.vm_pid.into(),
+ swizz_id: SwizzId::WHOLE_GPU.into(),
+ num_channels: info.num_channels.into(),
+ num_plugin_channels: info.num_plugin_channels.into(),
+ guest_fb_segment_count: 1.into(),
+ options: VgpuBootloadOptions::zeroed().into(),
+ channel_mapping: info.channel_mapping,
+ guest_fb_segment_phys_addr: Array::new(&[info.guest_fb.range().start])?,
+ guest_fb_segment_length: Array::new(&[info.guest_fb.len()])?,
+ plugin_heap_phys_addr: info.plugin_heap.range().start.into(),
+ plugin_heap_length: info.plugin_heap.len().into(),
+ ctrl_buff_offset: info.ctrl_buffer_offset.into(),
+ init_task_log_offset: info.init_log.range().start.into(),
+ init_task_log_size: info.init_log.len().into(),
+ vgpu_task_log_offset: info.vgpu_log.range().start.into(),
+ vgpu_task_log_size: info.vgpu_log.len().into(),
+ kernel_log_offset: info.kernel_log.range().start.into(),
+ kernel_log_size: info.kernel_log.len().into(),
+ // The current non-SMIG firmware path does not map a separate MIG-RM heap.
+ mig_rm_heap_phys_addr: 0.into(),
+ mig_rm_heap_length: 0.into(),
+ };
+
+ let mut encoder = Encoder::new();
+ request.encode(&mut encoder)?;
+ Ok(encoder.finish())
+}
+
nvkv_decode! {
pub(crate) struct VgpuPropertiesSchema => VgpuProperties {
// TODO: `name`/`class` required?
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 25/35] gpu: nova-core: vgpu: add GSP plugin communication buffer
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (23 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 24/35] gpu: nova-core: vgpu: encode vGPU boot requests Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 26/35] gpu: nova-core: vgpu: add instance boot Alok Kumar
` (9 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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
diff --git a/drivers/gpu/nova-core/mm.rs b/drivers/gpu/nova-core/mm.rs
index f1f86931928c..9489502d3362 100644
--- a/drivers/gpu/nova-core/mm.rs
+++ b/drivers/gpu/nova-core/mm.rs
@@ -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.
diff --git a/drivers/gpu/nova-core/mm/vram.rs b/drivers/gpu/nova-core/mm/vram.rs
index 6054eed9aeb0..7774b15e4c89 100644
--- a/drivers/gpu/nova-core/mm/vram.rs
+++ b/drivers/gpu/nova-core/mm/vram.rs
@@ -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> {
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index 65362ca31ba3..eaff5b8b318d 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -29,6 +29,7 @@
mod commands;
mod fw;
+mod gsp_plugin_comm;
mod hal;
mod instance;
mod vram;
diff --git a/drivers/gpu/nova-core/vgpu/fw.rs b/drivers/gpu/nova-core/vgpu/fw.rs
index 2d32e196a771..84a89c32a77b 100644
--- a/drivers/gpu/nova-core/vgpu/fw.rs
+++ b/drivers/gpu/nova-core/vgpu/fw.rs
@@ -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, //
+};
diff --git a/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs b/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
new file mode 100644
index 000000000000..983d5002ff5b
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
@@ -0,0 +1,201 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! GSP plugin communication buffer mappings and access.
+
+use core::mem::offset_of;
+
+use kernel::{
+ io::{
+ io_project,
+ io_read,
+ io_write,
+ Mmio, //
+ },
+ num::casts::FromSafeCast,
+ prelude::*, //
+};
+
+use crate::mm::{
+ bar_user::{
+ BarMapping,
+ BarUser, //
+ },
+ vram::VramRegion,
+ SharedGpuMm, //
+};
+
+use super::fw::{
+ self,
+ RawControlRegion,
+ RawResponseRegion, //
+};
+
+/// Layout of the plugin communication region, located at the start of the management heap.
+///
+/// This type is never instantiated; it only describes the layout of the region for I/O
+/// projections.
+///
+/// r000 layout, with byte offsets from the management heap (not to scale):
+///
+/// ```text
+/// 0x000000 +----------------------------------------+
+/// | Control (boot-ready marker) 4 KiB |
+/// 0x001000 +----------------------------------------+
+/// | Response 4 KiB |
+/// 0x002000 +----------------------------------------+
+/// | Message 4 KiB |
+/// 0x003000 +----------------------------------------+
+/// | Migration 2 MiB |
+/// 0x203000 +----------------------------------------+
+/// | Error 4 KiB |
+/// 0x204000 +----------------------------------------+
+/// | Init task log 128 KiB |
+/// 0x224000 +----------------------------------------+
+/// | vGPU task log 256 KiB |
+/// 0x264000 +----------------------------------------+
+/// | Kernel task log 64 KiB |
+/// 0x274000 +----------------------------------------+
+/// | Guest RPC trace 64 KiB |
+/// 0x284000 +----------------------------------------+
+/// ```
+#[repr(C)]
+struct CommBuffer {
+ control: RawControlRegion,
+ response: RawResponseRegion,
+ message: [u8; cv!(fw::VGPU_CPU_GSP_MESSAGE_BUFF_REGION_SIZE)],
+ migration: [u8; cv!(fw::VGPU_CPU_GSP_MIGRATION_BUFF_REGION_SIZE)],
+ error: [u8; cv!(fw::VGPU_CPU_GSP_ERROR_BUFF_REGION_SIZE)],
+ init_log: [u8; cv!(fw::VGPU_CPU_GSP_INIT_TASK_LOG_BUFF_REGION_SIZE)],
+ vgpu_log: [u8; cv!(fw::VGPU_CPU_GSP_VGPU_TASK_LOG_BUFF_REGION_SIZE)],
+ kernel_log: [u8; cv!(fw::VGPU_CPU_GSP_KERNEL_TASK_LOG_BUFF_REGION_SIZE)],
+ guest_trace: [u8; cv!(fw::VGPU_CPU_GSP_GUEST_RPC_TRACE_BUFF_REGION_SIZE)],
+}
+
+static_assert!(size_of::<CommBuffer>() == cv!(fw::VGPU_CPU_GSP_COMMUNICATION_BUFF_TOTAL_SIZE));
+static_assert!(size_of::<RawControlRegion>() == cv!(fw::VGPU_CPU_GSP_CTRL_BUFF_REGION_SIZE));
+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,
+ pub(super) kernel: VramRegion,
+}
+
+/// BAR1 mapping of the plugin communication region in its management heap.
+///
+/// See [`CommBuffer`] for the layout of the region.
+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(
+ bar_user: &'map BarUser<'gpu>,
+ mm: &'map SharedGpuMm<'gpu>,
+ management_heap: &VramRegion,
+ ) -> Result<Self> {
+ let region = management_heap.subregion(0..u64::from_safe_cast(size_of::<CommBuffer>()))?;
+
+ Ok(Self {
+ map: BarMapping::new(bar_user, mm, region, true)?,
+ })
+ }
+
+ /// Returns the MMIO view of the communication region.
+ ///
+ /// Fails if the region has been unmapped.
+ fn view(&self) -> Result<Mmio<'_, CommBuffer>> {
+ self.map.view()
+ }
+
+ /// Return the physical regions occupied by the three plugin logs.
+ pub(super) fn plugin_logs(&self) -> Result<PluginLogRegions> {
+ let log_region = |offset, size| {
+ let start = u64::from_safe_cast(offset);
+
+ self.map.region().subregion(start..start + u64::from(size))
+ };
+
+ Ok(PluginLogRegions {
+ init: log_region(
+ offset_of!(CommBuffer, init_log),
+ fw::VGPU_CPU_GSP_INIT_TASK_LOG_BUFF_REGION_SIZE,
+ )?,
+ vgpu: log_region(
+ offset_of!(CommBuffer, vgpu_log),
+ fw::VGPU_CPU_GSP_VGPU_TASK_LOG_BUFF_REGION_SIZE,
+ )?,
+ kernel: log_region(
+ offset_of!(CommBuffer, kernel_log),
+ fw::VGPU_CPU_GSP_KERNEL_TASK_LOG_BUFF_REGION_SIZE,
+ )?,
+ })
+ }
+
+ /// 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);
+
+ Ok(value == fw::GSP_PLUGIN_BOOTLOADED)
+ }
+
+ /// 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);
+ let response = io_project!(comm, .response.__bindgen_anon_1);
+
+ io_write!(
+ control,
+ .response_buff_offset,
+ u64::from_safe_cast(offset_of!(CommBuffer, response))
+ );
+ io_write!(
+ control,
+ .message_buff_offset,
+ u64::from_safe_cast(offset_of!(CommBuffer, message))
+ );
+ io_write!(
+ control,
+ .migration_buff_offset,
+ u64::from_safe_cast(offset_of!(CommBuffer, migration))
+ );
+ io_write!(
+ control,
+ .error_buff_offset,
+ u64::from_safe_cast(offset_of!(CommBuffer, error))
+ );
+ io_write!(
+ control,
+ .guest_rpc_trace_buff_offset,
+ u64::from_safe_cast(offset_of!(CommBuffer, guest_trace))
+ );
+ io_write!(control, .migration_buf_cpu_access_offset, 0);
+ io_write!(control, .is_migration_in_progress, 0);
+ io_write!(control, .error_buff_cpu_get_idx, 0);
+ io_write!(control, .guest_rpc_trace_buff_cpu_get_idx, 0);
+ io_write!(control, .attached_vgpu_count, 1);
+ io_write!(control, .is_gr_init_done, 0);
+
+ io_write!(control, .message_type, 0);
+ // Replace the boot-ready marker with the initial RPC sequence.
+ io_write!(control, .message_seq_num, 0);
+ io_write!(response, .message_seq_num_processed, 0);
+ io_write!(response, .result_code, 0);
+ io_write!(control, .version, fw::VGPU_CPU_GSP_CTRL_BUFF_VERSION);
+
+ Ok(())
+ }
+
+ /// Invalidate the PTEs and release the communication mapping.
+ #[expect(dead_code)]
+ pub(super) fn unmap(&mut self) -> Result {
+ self.map.unmap()
+ }
+}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 26/35] gpu: nova-core: vgpu: add instance boot
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (24 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 25/35] gpu: nova-core: vgpu: add GSP plugin communication buffer Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 27/35] gpu: nova-core: vgpu: add instance shutdown Alok Kumar
` (8 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Co-developed-by: Alok Kumar <alkumar@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 962a6a3f4d29..031878cdb626 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -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,
diff --git a/drivers/gpu/nova-core/gsp/fw/commands.rs b/drivers/gpu/nova-core/gsp/fw/commands.rs
index d9dd4841566f..362db885bc0c 100644
--- a/drivers/gpu/nova-core/gsp/fw/commands.rs
+++ b/drivers/gpu/nova-core/gsp/fw/commands.rs
@@ -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]
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index eaff5b8b318d..e1dbd46338a6 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -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,
diff --git a/drivers/gpu/nova-core/vgpu/commands.rs b/drivers/gpu/nova-core/vgpu/commands.rs
index 66669948230a..b384c190a66a 100644
--- a/drivers/gpu/nova-core/vgpu/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/commands.rs
@@ -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)
+}
diff --git a/drivers/gpu/nova-core/vgpu/fw/commands.rs b/drivers/gpu/nova-core/vgpu/fw/commands.rs
index 666c549e55b1..a8b80bd6d33b 100644
--- a/drivers/gpu/nova-core/vgpu/fw/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/fw/commands.rs
@@ -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(),
diff --git a/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs b/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
index 983d5002ff5b..310230702562 100644
--- a/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
+++ b/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
@@ -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);
diff --git a/drivers/gpu/nova-core/vgpu/instance.rs b/drivers/gpu/nova-core/vgpu/instance.rs
index 68c93418cc26..6df3d9ec8dde 100644
--- a/drivers/gpu/nova-core/vgpu/instance.rs
+++ b/drivers/gpu/nova-core/vgpu/instance.rs
@@ -7,19 +7,37 @@
};
use kernel::{
+ device,
prelude::*,
ptr::Alignment,
- sizes::SizeConstants, //
+ sizes::SizeConstants,
+ time::{
+ delay::fsleep,
+ Delta,
+ Instant,
+ Monotonic, //
+ }, //
};
use crate::{
gpu::ChannelIdReservation,
+ gsp::{
+ cmdq::Cmdq,
+ commands::FifoEngineList, //
+ },
mm::GpuMm, //
num::FromSafeCast,
};
use super::{
- fw::commands::VgpuProperties,
+ commands::send_bootload,
+ fw::commands::{
+ encode_vgpu_bootload,
+ BootloadInfo,
+ ChannelMapEntry,
+ VgpuProperties, //
+ },
+ gsp_plugin_comm::CommBufferRegion,
vram::{
VgpuVramLayout,
VgpuVramSlot,
@@ -29,6 +47,49 @@
VgpuManagerInner, //
};
+/// Ready limit used by `vmiopd_negotiate_cpu_gsp_version()` for the same marker.
+const PLUGIN_READY_TIMEOUT: Delta = Delta::from_secs(10);
+
+/// Per-engine channel budget reserved by the full SR-IOV plugin.
+///
+/// The supported GB20x path keeps firmware's non-heavy default, which uses
+/// `PLUGIN_ALLOCATED_CHANNELS_PER_ENGINE` rather than the heavy-mode budget.
+const PLUGIN_CHANNELS_PER_ENGINE: u32 = 3;
+
+/// Build the typed channel mapping from the GSP FIFO engine list.
+fn channel_mapping(
+ fifo_engine_list: &FifoEngineList,
+ chid_offset: u32,
+) -> Result<KVVec<ChannelMapEntry>> {
+ let mut mapping = KVVec::new();
+ for &gmc_id in fifo_engine_list.gmc_ids() {
+ // CAST: The mask leaves only the low 16 bits of the GMC engine ID.
+ let engine_type = (gmc_id & u32::from(u16::MAX)) as u16;
+ // CAST: Shifting a `u32` by 16 leaves at most 16 bits.
+ let index = (gmc_id >> u16::BITS) as u16;
+ mapping.push(
+ ChannelMapEntry::new(engine_type, index, chid_offset),
+ GFP_KERNEL,
+ )?;
+ }
+ Ok(mapping)
+}
+
+fn wait_plugin_ready(dev: &device::Device, comm: &CommBufferRegion<'_, '_>) -> Result {
+ let start = Instant::<Monotonic>::now();
+
+ loop {
+ if comm.is_plugin_ready()? {
+ dev_dbg!(dev, "vGPU plugin ready after {:?}\n", start.elapsed());
+ return Ok(());
+ }
+ if start.elapsed() >= PLUGIN_READY_TIMEOUT {
+ return Err(ETIMEDOUT);
+ }
+ fsleep(Delta::from_millis(1));
+ }
+}
+
/// Guest Function ID validated against one device's total number of VFs.
///
/// GFID 0 is reserved for the PF; VFs start at 1. Keeping the nonzero `u16`
@@ -51,7 +112,6 @@ pub(super) fn new(gfid: u32, total_vfs: NonZero<u16>) -> Result<Self> {
}
}
- #[expect(dead_code)]
pub(super) const fn get(self) -> u16 {
self.0.get()
}
@@ -77,14 +137,72 @@ fn from(properties: &VgpuProperties) -> Self {
}
/// A vGPU instance and the resources reserved for it.
-#[expect(dead_code)]
struct VgpuInstance<'gpu> {
gfid: Gfid,
dbdf: Dbdf,
vgpu_type: VgpuType,
vm_pid: u32,
- chids: ChannelIdReservation<'gpu>,
+ num_plugin_channels: u32,
+ comm: CommBufferRegion<'gpu, 'gpu>,
+ // Unmap the communication region before returning its slot and channel IDs.
vram_slot: VgpuVramSlot,
+ chids: ChannelIdReservation<'gpu>,
+}
+
+impl<'gpu> VgpuInstance<'gpu> {
+ #[expect(dead_code)]
+ fn activate(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
+ let dev = vgpu.dev;
+ self.bootload(dev, vgpu.cmdq, &vgpu.fifo_engine_list)?;
+
+ Ok(())
+ }
+
+ /// Bootload the GSP vGPU plugin and wait for its BAR1 ready indication.
+ fn bootload(
+ &mut self,
+ dev: &device::Device,
+ cmdq: &Cmdq<'_>,
+ fifo_engine_list: &FifoEngineList,
+ ) -> Result {
+ let fb = &self.vram_slot.fbmem;
+ let mgmt = &self.vram_slot.mgmt_heap;
+ let logs = self.comm.plugin_logs()?;
+
+ let payload = encode_vgpu_bootload(BootloadInfo {
+ dbdf: self.dbdf,
+ gfid: u32::from(self.gfid.get()),
+ vgpu_type: self.vgpu_type.vgpu_type_id,
+ vm_pid: self.vm_pid,
+ num_channels: u32::try_from(self.chids.len()).map_err(|_| EOVERFLOW)?,
+ num_plugin_channels: self.num_plugin_channels,
+ channel_mapping: channel_mapping(
+ fifo_engine_list,
+ u32::try_from(self.chids.start).map_err(|_| EOVERFLOW)?,
+ )?,
+ guest_fb: fb,
+ plugin_heap: mgmt,
+ ctrl_buffer_offset: 0,
+ init_log: &logs.init,
+ vgpu_log: &logs.vgpu,
+ kernel_log: &logs.kernel,
+ })?;
+
+ dev_dbg!(
+ dev,
+ "bootload: gfid={} sending {} typed NVKV bytes\n",
+ self.gfid.get(),
+ payload.len() * size_of::<u64>(),
+ );
+
+ self.comm.clear_plugin_ready()?;
+ send_bootload(dev, cmdq, &payload)?;
+
+ wait_plugin_ready(dev, &self.comm)?;
+
+ dev_dbg!(dev, "bootload: gfid={} plugin ready\n", self.gfid.get());
+ Ok(())
+ }
}
/// Identity and firmware profile used to allocate an instance.
@@ -195,14 +313,17 @@ fn allocate_instance(
let vram_slot = vgpu
.mm
.with_locked(|mm| self.alloc_vram_slot(mm, vram_layout))?;
+ let comm = CommBufferRegion::new(vgpu.bar_user, vgpu.mm, &vram_slot.mgmt_heap)?;
Ok(VgpuInstance {
gfid,
dbdf,
vgpu_type,
vm_pid,
- chids,
+ num_plugin_channels: PLUGIN_CHANNELS_PER_ENGINE,
+ comm,
vram_slot,
+ chids,
})
}
@@ -232,7 +353,8 @@ fn create_instance(&self, info: InstanceInfo) -> Result {
// Reserve capacity before acquiring resources so registration cannot allocate.
instances.instances.reserve(1, GFP_KERNEL)?;
- let instance = instances.allocate_instance(self, info)?;
+ let mut instance = instances.allocate_instance(self, info)?;
+ let result = instance.activate(self);
// Register live instances, and failed ones whose resources firmware may still own.
instances
@@ -240,6 +362,6 @@ fn create_instance(&self, info: InstanceInfo) -> Result {
.push_within_capacity(instance)
.map_err(|_| EIO)?;
- Ok(())
+ result
}
}
diff --git a/drivers/gpu/nova-core/vgpu/vram.rs b/drivers/gpu/nova-core/vgpu/vram.rs
index 77446b2bdceb..fb7c460b9d97 100644
--- a/drivers/gpu/nova-core/vgpu/vram.rs
+++ b/drivers/gpu/nova-core/vgpu/vram.rs
@@ -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,
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 27/35] gpu: nova-core: vgpu: add instance shutdown
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (25 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 26/35] gpu: nova-core: vgpu: add instance boot Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 28/35] gpu: nova-core: vgpu: add GSP plugin RPC transactions Alok Kumar
` (7 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
Stop the GSP plugin, wait for SHUTDOWN completion, and release its
firmware resources with CLEANUP before unmapping the communication
buffers.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Co-developed-by: Alok Kumar <alkumar@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/gsp/cmdq/gmc.rs b/drivers/gpu/nova-core/gsp/cmdq/gmc.rs
index d4017c2e04ce..b4e956a2ed50 100644
--- a/drivers/gpu/nova-core/gsp/cmdq/gmc.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq/gmc.rs
@@ -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,
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index e1dbd46338a6..fbaaf8e1d6fa 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -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);
+ }
+}
diff --git a/drivers/gpu/nova-core/vgpu/commands.rs b/drivers/gpu/nova-core/vgpu/commands.rs
index b384c190a66a..d0fd7ab2593b 100644
--- a/drivers/gpu/nova-core/vgpu/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/commands.rs
@@ -25,6 +25,7 @@
MessagePayload, //
},
Cmdq,
+ NoReply, //
},
nvkv::{
nvkv_words,
@@ -35,12 +36,14 @@
GmcCommandId,
GSP_PAGE_SIZE, //
},
+ sbuffer::SBufferIter,
vgpu::{
fw::commands::{
AssignedVfVgpuType,
VgpuProperties,
VgpuPropertiesSchema, //
},
+ instance::Gfid,
Dbdf,
},
};
@@ -157,3 +160,66 @@ pub(super) fn send_bootload(_dev: &device::Device, cmdq: &Cmdq<'_>, payload: &[u
cmdq.send_gmc_command(BootloadPluginTask(payload), |_| Ok(()))?
.map_err(|_| EIO)
}
+
+/// The `SHUTDOWN_GSP_VGPU_PLUGIN_TASK` command.
+///
+/// The GSP does not answer it, and sends a `SHUTDOWN_GSP_VGPU_PLUGIN_TASK_COMPLETE` event carrying
+/// the same GFID once the task has stopped.
+struct ShutdownPluginTask(Gfid);
+
+impl CommandToGsp for ShutdownPluginTask {
+ const COMMAND: GmcCommandId = GmcCommandId::ShutdownGspVgpuPluginTask;
+ type Command = u32;
+ type Reply = NoReply;
+ 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> {
+ u32::from(self.0.get()).to_le()
+ }
+}
+
+/// The `CLEANUP_GSP_VGPU_PLUGIN_RESOURCES` command.
+struct CleanupPluginResources(Gfid);
+
+impl CommandToGsp for CleanupPluginResources {
+ const COMMAND: GmcCommandId = GmcCommandId::CleanupGspVgpuPluginResources;
+ 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()
+ }
+}
+
+/// Shut down a vGPU plugin task and wait for its completion event.
+pub(super) fn send_shutdown(dev: &device::Device, cmdq: &Cmdq<'_>, gfid: Gfid) -> Result {
+ cmdq.send_gmc_command_await_event(ShutdownPluginTask(gfid), |event| {
+ let command = event.header().command();
+ if !matches!(
+ command.id(),
+ Ok(GmcCommandId::ShutdownGspVgpuPluginTaskComplete)
+ ) {
+ dev_dbg!(dev, "shutdown: ignoring GMC event {:?}\n", command);
+ return Ok(None);
+ }
+
+ let (payload_0, payload_1) = event.payload();
+ let mut event_gfid = [0u8; size_of::<u32>()];
+ SBufferIter::new_reader([payload_0, payload_1]).read_exact(&mut event_gfid)?;
+
+ Ok((u32::from_le_bytes(event_gfid) == u32::from(gfid.get())).then_some(()))
+ })
+}
+
+/// Release firmware resources after a plugin task has stopped.
+pub(super) fn send_cleanup(dev: &device::Device, cmdq: &Cmdq<'_>, gfid: Gfid) -> Result {
+ cmdq.send_gmc_command(CleanupPluginResources(gfid), |_| Ok(()))?
+ .map_err(|_| EIO)?;
+
+ dev_dbg!(dev, "cleanup: gfid={} done\n", gfid.get());
+ Ok(())
+}
diff --git a/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs b/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
index 310230702562..e4ce82c6b2d7 100644
--- a/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
+++ b/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
@@ -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()
}
diff --git a/drivers/gpu/nova-core/vgpu/instance.rs b/drivers/gpu/nova-core/vgpu/instance.rs
index 6df3d9ec8dde..2d045ebcd9cd 100644
--- a/drivers/gpu/nova-core/vgpu/instance.rs
+++ b/drivers/gpu/nova-core/vgpu/instance.rs
@@ -30,7 +30,11 @@
};
use super::{
- commands::send_bootload,
+ commands::{
+ send_bootload,
+ send_cleanup,
+ send_shutdown, //
+ },
fw::commands::{
encode_vgpu_bootload,
BootloadInfo,
@@ -147,10 +151,12 @@ struct VgpuInstance<'gpu> {
// Unmap the communication region before returning its slot and channel IDs.
vram_slot: VgpuVramSlot,
chids: ChannelIdReservation<'gpu>,
+ needs_teardown: bool,
+ /// An uncertain or failed operation retains resources until device removal.
+ failure: Option<Error>,
}
impl<'gpu> VgpuInstance<'gpu> {
- #[expect(dead_code)]
fn activate(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
let dev = vgpu.dev;
self.bootload(dev, vgpu.cmdq, &vgpu.fifo_engine_list)?;
@@ -158,6 +164,26 @@ fn activate(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
Ok(())
}
+ /// Tear down once, retaining all remaining resources if an operation fails.
+ fn teardown(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
+ if let Some(error) = self.failure {
+ return Err(error);
+ }
+ let result = (|| {
+ self.shutdown(vgpu.dev, vgpu.cmdq)?;
+
+ if self.needs_teardown {
+ send_cleanup(vgpu.dev, vgpu.cmdq, self.gfid)?;
+ self.needs_teardown = false;
+ }
+ self.comm.unmap()
+ })();
+ if let Err(error) = result {
+ self.failure = Some(error);
+ }
+ result
+ }
+
/// Bootload the GSP vGPU plugin and wait for its BAR1 ready indication.
fn bootload(
&mut self,
@@ -196,6 +222,7 @@ fn bootload(
);
self.comm.clear_plugin_ready()?;
+ self.needs_teardown = true;
send_bootload(dev, cmdq, &payload)?;
wait_plugin_ready(dev, &self.comm)?;
@@ -203,6 +230,15 @@ fn bootload(
dev_dbg!(dev, "bootload: gfid={} plugin ready\n", self.gfid.get());
Ok(())
}
+
+ /// Stop the plugin when firmware may own instance resources.
+ fn shutdown(&mut self, dev: &device::Device, cmdq: &Cmdq<'_>) -> Result {
+ if self.needs_teardown {
+ send_shutdown(dev, cmdq, self.gfid)?;
+ dev_dbg!(dev, "shutdown: gfid={} stopped\n", self.gfid.get());
+ }
+ Ok(())
+ }
}
/// Identity and firmware profile used to allocate an instance.
@@ -324,20 +360,44 @@ fn allocate_instance(
comm,
vram_slot,
chids,
+ needs_teardown: false,
+ failure: None,
})
}
- /// Remove an instance and release its channel and VRAM reservations.
- fn destroy_instance(&mut self, gfid: Gfid) -> Result {
+ /// Remove an instance only after firmware and mapping teardown have succeeded.
+ fn destroy_instance(&mut self, vgpu: &VgpuManagerInner<'gpu>, gfid: Gfid) -> Result {
let instance_index = self
.instances
.iter()
.position(|instance| instance.gfid == gfid)
.ok_or(ENOENT)?;
+ let instance = self.instances.get_mut(instance_index).ok_or(EIO)?;
+ instance.teardown(vgpu)?;
+
let instance = self.instances.remove(instance_index).map_err(|_| EIO)?;
drop(instance);
Ok(())
}
+
+ /// Release the registry while the manager's MM and firmware dependencies remain available.
+ pub(super) fn release_all(&mut self, vgpu: &VgpuManagerInner<'gpu>) {
+ for instance in &mut self.instances {
+ // Failed operations retain their resources until this final device removal.
+ // Do not resubmit commands whose firmware outcome was uncertain.
+ if instance.failure.is_none() {
+ if let Err(error) = instance.teardown(vgpu) {
+ dev_err!(
+ vgpu.dev,
+ "vGPU teardown failed for gfid={}: {:?}\n",
+ instance.gfid.get(),
+ error,
+ );
+ }
+ }
+ }
+ self.instances.clear();
+ }
}
impl VgpuManagerInner<'_> {
@@ -356,6 +416,19 @@ fn create_instance(&self, info: InstanceInfo) -> Result {
let mut instance = instances.allocate_instance(self, info)?;
let result = instance.activate(self);
+ if result.is_err() {
+ match instance.teardown(self) {
+ // Firmware owns nothing anymore; drop the instance to release its resources.
+ Ok(()) => return result,
+ Err(error) => dev_err!(
+ self.dev,
+ "vGPU creation could not release gfid={}: {:?}; resources retained\n",
+ instance.gfid.get(),
+ error,
+ ),
+ }
+ }
+
// Register live instances, and failed ones whose resources firmware may still own.
instances
.instances
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 28/35] gpu: nova-core: vgpu: add GSP plugin RPC transactions
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (26 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 27/35] gpu: nova-core: vgpu: add instance shutdown Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 29/35] gpu: nova-core: vgpu: negotiate the GSP plugin RPC version Alok Kumar
` (6 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 031878cdb626..0de451fc3d7b 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -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(),
diff --git a/drivers/gpu/nova-core/regs.rs b/drivers/gpu/nova-core/regs.rs
index 050054a2b23d..867fc591b43d 100644
--- a/drivers/gpu/nova-core/regs.rs
+++ b/drivers/gpu/nova-core/regs.rs
@@ -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
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index fbaaf8e1d6fa..bdb4821751e7 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -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,
diff --git a/drivers/gpu/nova-core/vgpu/fw.rs b/drivers/gpu/nova-core/vgpu/fw.rs
index 84a89c32a77b..76bd2b7e4e52 100644
--- a/drivers/gpu/nova-core/vgpu/fw.rs
+++ b/drivers/gpu/nova-core/vgpu/fw.rs
@@ -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,
+ },
+}
diff --git a/drivers/gpu/nova-core/vgpu/fw/commands.rs b/drivers/gpu/nova-core/vgpu/fw/commands.rs
index a8b80bd6d33b..a8f6f0316d25 100644
--- a/drivers/gpu/nova-core/vgpu/fw/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/fw/commands.rs
@@ -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);
diff --git a/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs b/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
index e4ce82c6b2d7..49d85df70018 100644
--- a/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
+++ b/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
@@ -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()
diff --git a/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs b/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs
new file mode 100644
index 000000000000..d96f6072a941
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs
@@ -0,0 +1,155 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! GSP plugin RPC.
+//!
+//! ```text
+//! Host (PluginRpc) Shared RPC buffer (VRAM) GSP plugin
+//! | | |
+//! |-- BAR1: payload --------->| Message |
+//! |-- BAR1: type, sequence -->| Control |
+//! | | |
+//! |-- BAR0: VF doorbell ----------------------------->|
+//! | |<-- read request ------|
+//! | | | process RPC
+//! | |<-- completion --------|
+//! |-- poll processed seq ---->| Response |
+//! |<-- matching seq, status --| |
+//! ```
+
+use kernel::{
+ device,
+ prelude::*,
+ time::{
+ delay::fsleep,
+ Delta,
+ Instant,
+ Monotonic, //
+ },
+};
+
+use crate::{
+ driver::Bar0,
+ regs::NV_VIRTUAL_FUNCTION_PRIV_DOORBELL, //
+};
+
+use super::{
+ fw::{
+ RpcMessage,
+ RpcResponse, //
+ },
+ gsp_plugin_comm::CommBufferRegion,
+ instance::Gfid, //
+};
+
+/// BAR1-backed channel used to communicate with one GSP plugin.
+pub(super) struct PluginRpc<'map, 'gpu> {
+ comm: CommBufferRegion<'map, 'gpu>,
+ bar0: Bar0<'gpu>,
+ gfid: Gfid,
+ message_sequence: u32,
+}
+
+impl<'map, 'gpu> PluginRpc<'map, 'gpu> {
+ pub(super) fn new(comm: CommBufferRegion<'map, 'gpu>, bar0: Bar0<'gpu>, gfid: Gfid) -> Self {
+ Self {
+ comm,
+ bar0,
+ gfid,
+ message_sequence: 0,
+ }
+ }
+
+ pub(super) fn comm(&self) -> &CommBufferRegion<'map, 'gpu> {
+ &self.comm
+ }
+
+ /// 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;
+ Ok(())
+ }
+
+ fn next_sequence(&self) -> u32 {
+ let sequence = self.message_sequence.wrapping_add(1);
+ if sequence == 0 {
+ 1
+ } else {
+ sequence
+ }
+ }
+
+ /// 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,
+ message_type: RpcMessage,
+ data: &[u8],
+ ) -> Result {
+ let sequence = self.next_sequence();
+ self.comm.submit(message_type, sequence, data)?;
+ self.message_sequence = sequence;
+
+ dev_dbg!(
+ dev,
+ "vGPU RPC: gfid={} type={} bytes={} sequence={}\n",
+ self.gfid.get(),
+ // CAST: `RpcMessage` has a `u32` representation.
+ message_type as u32,
+ data.len(),
+ sequence,
+ );
+
+ NV_VIRTUAL_FUNCTION_PRIV_DOORBELL::ring_gsp_plugin(self.bar0, self.gfid.get())?;
+ self.wait_response(dev, sequence)
+ }
+
+ fn wait_response(&self, dev: &device::Device, expected_sequence: u32) -> Result {
+ let start = Instant::<Monotonic>::now();
+ let timeout = Delta::from_secs(120);
+
+ loop {
+ match self.comm.response(expected_sequence)? {
+ RpcResponse::Complete { status } => {
+ if status != 0 {
+ dev_dbg!(
+ dev,
+ "vGPU RPC: sequence {} failed with status {}\n",
+ expected_sequence,
+ status,
+ );
+ return Err(EIO);
+ }
+
+ dev_dbg!(
+ dev,
+ "vGPU RPC: sequence {} completed after {:?}\n",
+ expected_sequence,
+ start.elapsed(),
+ );
+ return Ok(());
+ }
+ RpcResponse::Pending { sequence } => {
+ if start.elapsed() >= timeout {
+ dev_dbg!(
+ dev,
+ "vGPU RPC: sequence {} timed out; last response was {}\n",
+ expected_sequence,
+ sequence,
+ );
+ return Err(ETIMEDOUT);
+ }
+ }
+ }
+ fsleep(Delta::from_millis(1));
+ }
+ }
+
+ /// Release the BAR1 mapping.
+ pub(super) fn unmap(&mut self) -> Result {
+ self.comm.unmap()
+ }
+}
diff --git a/drivers/gpu/nova-core/vgpu/instance.rs b/drivers/gpu/nova-core/vgpu/instance.rs
index 2d045ebcd9cd..94735df79e1a 100644
--- a/drivers/gpu/nova-core/vgpu/instance.rs
+++ b/drivers/gpu/nova-core/vgpu/instance.rs
@@ -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,
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 29/35] gpu: nova-core: vgpu: negotiate the GSP plugin RPC version
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (27 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 28/35] gpu: nova-core: vgpu: add GSP plugin RPC transactions Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 30/35] gpu: nova-core: vgpu: send GSP plugin configuration parameters Alok Kumar
` (5 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Co-developed-by: Eliot Courtney <ecourtney@nvidia.com>
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/vgpu/commands.rs b/drivers/gpu/nova-core/vgpu/commands.rs
index d0fd7ab2593b..c1783ace8b3f 100644
--- a/drivers/gpu/nova-core/vgpu/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/commands.rs
@@ -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, &[])
+}
diff --git a/drivers/gpu/nova-core/vgpu/fw/commands.rs b/drivers/gpu/nova-core/vgpu/fw/commands.rs
index a8f6f0316d25..168a2447b67c 100644
--- a/drivers/gpu/nova-core/vgpu/fw/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/fw/commands.rs
@@ -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 {
diff --git a/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs b/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs
index d96f6072a941..c68681d8d08b 100644
--- a/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs
+++ b/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs
@@ -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,
diff --git a/drivers/gpu/nova-core/vgpu/instance.rs b/drivers/gpu/nova-core/vgpu/instance.rs
index 94735df79e1a..2c8542a45643 100644
--- a/drivers/gpu/nova-core/vgpu/instance.rs
+++ b/drivers/gpu/nova-core/vgpu/instance.rs
@@ -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(())
}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 30/35] gpu: nova-core: vgpu: send GSP plugin configuration parameters
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (28 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 29/35] gpu: nova-core: vgpu: negotiate the GSP plugin RPC version Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 31/35] gpu: nova-core: vgpu: update the GSP plugin BME state Alok Kumar
` (4 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Co-developed-by: Eliot Courtney <ecourtney@nvidia.com>
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(+)
diff --git a/drivers/gpu/nova-core/vgpu/commands.rs b/drivers/gpu/nova-core/vgpu/commands.rs
index c1783ace8b3f..70fd35566822 100644
--- a/drivers/gpu/nova-core/vgpu/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/commands.rs
@@ -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)
+}
diff --git a/drivers/gpu/nova-core/vgpu/fw/commands.rs b/drivers/gpu/nova-core/vgpu/fw/commands.rs
index 168a2447b67c..c7ff27fcf6d7 100644
--- a/drivers/gpu/nova-core/vgpu/fw/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/fw/commands.rs
@@ -9,6 +9,7 @@
use kernel::{
alloc::ArrayVec,
bitfield,
+ num::casts::usize_as_u64,
prelude::*, //
};
@@ -35,6 +36,7 @@
#[repr(u32)]
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,
}
#[derive(Clone, Copy)]
@@ -211,6 +213,122 @@ impl VgpuProperties {
const STRING_LEN: usize = 64;
}
+#[derive(Clone, Copy)]
+#[repr(u32)]
+enum HypervisorType {
+ Unknown = 4,
+}
+
+impl From<HypervisorType> for u32 {
+ fn from(value: HypervisorType) -> Self {
+ // CAST: `HypervisorType` uses the wire field's `u32` representation.
+ value as u32
+ }
+}
+
+#[derive(Clone, Copy)]
+#[repr(u32)]
+enum CpuArch {
+ Aarch64 = 1,
+ X86_64 = 2,
+}
+
+impl CpuArch {
+ fn host() -> Result<Self> {
+ if cfg!(target_arch = "x86_64") {
+ Ok(Self::X86_64)
+ } else if cfg!(target_arch = "aarch64") {
+ Ok(Self::Aarch64)
+ } else {
+ Err(EOPNOTSUPP)
+ }
+ }
+}
+
+impl From<CpuArch> for u32 {
+ fn from(value: CpuArch) -> Self {
+ // CAST: `CpuArch` uses the wire field's `u32` representation.
+ value as u32
+ }
+}
+
+#[derive(Clone, Copy)]
+struct MigrationFeature(u32);
+
+impl MigrationFeature {
+ const PRESERVE_CTX_BUF: Self = Self(0x4000);
+}
+
+impl From<MigrationFeature> for u32 {
+ fn from(value: MigrationFeature) -> Self {
+ value.0
+ }
+}
+
+bitfield! {
+ struct FeatureFlags(u64) {
+ 3:3 enable_uvm => bool;
+ 5:5 vmm_migration => bool;
+ }
+}
+
+nvkv_encode! {
+ struct PluginConfigParamsRequest {
+ uuid: Key<[u8; 16], 0x0001>,
+ dbdf: Key<Dbdf, 0x0002, u32>,
+ device_instance_id: Key<u32, 0x0004>,
+ vgpu_type: Key<u32, 0x0005>,
+ vm_pid: Key<u32, 0x0006>,
+ swizz_id: Key<SwizzId, 0x0010, u32>,
+ num_channels: Key<u32, 0x0011>,
+ num_plugin_channels: Key<u32, 0x0012>,
+ vmm_cap: Key<u32, 0x0020>,
+ migration_feature: Key<MigrationFeature, 0x0021, u32>,
+ hypervisor_type: Key<HypervisorType, 0x0022, u32>,
+ cpu_arch: Key<CpuArch, 0x0023, u32>,
+ page_size: Key<u64, 0x0024>,
+ feature_flags: Key<FeatureFlags, 0x0030, u64>,
+ }
+}
+
+/// Encodes plugin configuration parameters using the typed NVKV schema.
+pub(crate) fn encode_plugin_config_params(
+ uuid: [u8; 16],
+ dbdf: Dbdf,
+ vgpu_type: u32,
+ vm_pid: u32,
+ num_channels: u32,
+ num_plugin_channels: u32,
+) -> Result<KVVec<u64>> {
+ let request = PluginConfigParamsRequest {
+ uuid: uuid.into(),
+ dbdf: dbdf.into(),
+ // The full host PCI address distinguishes VFs within a VM, including VFs
+ // from different PFs. This opaque identity lasts for the host device lifetime.
+ device_instance_id: dbdf.into_raw().into(),
+ vgpu_type: vgpu_type.into(),
+ vm_pid: vm_pid.into(),
+ swizz_id: SwizzId::WHOLE_GPU.into(),
+ num_channels: num_channels.into(),
+ num_plugin_channels: num_plugin_channels.into(),
+ // Advertise no optional VMM capabilities (vmioplugin.h VMM_CAP_*),
+ // independently of the plugin feature_flags and migration_feature below.
+ vmm_cap: 0.into(),
+ migration_feature: MigrationFeature::PRESERVE_CTX_BUF.into(),
+ hypervisor_type: HypervisorType::Unknown.into(),
+ cpu_arch: CpuArch::host()?.into(),
+ page_size: usize_as_u64(kernel::page::PAGE_SIZE).into(),
+ feature_flags: FeatureFlags::zeroed()
+ .with_enable_uvm(false)
+ .with_vmm_migration(true)
+ .into(),
+ };
+
+ let mut encoder = Encoder::new();
+ request.encode(&mut encoder)?;
+ Ok(encoder.finish())
+}
+
// TODO: extract from bindings
#[repr(C)]
#[derive(FromBytes, IntoBytes)]
diff --git a/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs b/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs
index c68681d8d08b..1197c427312a 100644
--- a/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs
+++ b/drivers/gpu/nova-core/vgpu/gsp_plugin_rpc.rs
@@ -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);
diff --git a/drivers/gpu/nova-core/vgpu/instance.rs b/drivers/gpu/nova-core/vgpu/instance.rs
index 2c8542a45643..af1b43533a77 100644
--- a/drivers/gpu/nova-core/vgpu/instance.rs
+++ b/drivers/gpu/nova-core/vgpu/instance.rs
@@ -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 {
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 31/35] gpu: nova-core: vgpu: update the GSP plugin BME state
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (29 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 30/35] gpu: nova-core: vgpu: send GSP plugin configuration parameters Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 32/35] gpu: nova-core: vgpu: add CeUtils commands Alok Kumar
` (3 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Co-developed-by: Eliot Courtney <ecourtney@nvidia.com>
Signed-off-by: Eliot Courtney <ecourtney@nvidia.com>
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/vgpu/commands.rs b/drivers/gpu/nova-core/vgpu/commands.rs
index 70fd35566822..d11f9af27ee0 100644
--- a/drivers/gpu/nova-core/vgpu/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/commands.rs
@@ -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)
+}
diff --git a/drivers/gpu/nova-core/vgpu/fw/commands.rs b/drivers/gpu/nova-core/vgpu/fw/commands.rs
index c7ff27fcf6d7..10f1427bf355 100644
--- a/drivers/gpu/nova-core/vgpu/fw/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/fw/commands.rs
@@ -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)]
diff --git a/drivers/gpu/nova-core/vgpu/instance.rs b/drivers/gpu/nova-core/vgpu/instance.rs
index af1b43533a77..59d7014d7f69 100644
--- a/drivers/gpu/nova-core/vgpu/instance.rs
+++ b/drivers/gpu/nova-core/vgpu/instance.rs
@@ -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(())
}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 32/35] gpu: nova-core: vgpu: add CeUtils commands
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (30 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 31/35] gpu: nova-core: vgpu: update the GSP plugin BME state Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 33/35] gpu: nova-core: vgpu: scrub guest VRAM with CeUtils Alok Kumar
` (2 subsequent siblings)
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Co-developed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/vgpu/commands.rs b/drivers/gpu/nova-core/vgpu/commands.rs
index d11f9af27ee0..a71379165eaf 100644
--- a/drivers/gpu/nova-core/vgpu/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/commands.rs
@@ -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)
+}
diff --git a/drivers/gpu/nova-core/vgpu/fw.rs b/drivers/gpu/nova-core/vgpu/fw.rs
index 76bd2b7e4e52..02f51bb8cf7f 100644
--- a/drivers/gpu/nova-core/vgpu/fw.rs
+++ b/drivers/gpu/nova-core/vgpu/fw.rs
@@ -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 {
diff --git a/drivers/gpu/nova-core/vgpu/fw/commands.rs b/drivers/gpu/nova-core/vgpu/fw/commands.rs
index 10f1427bf355..c2e2ffad2b2d 100644
--- a/drivers/gpu/nova-core/vgpu/fw/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/fw/commands.rs
@@ -20,10 +20,10 @@
Array,
Encodable,
Encoder,
- Index, //
+ Index,
Key,
KeyId,
- Required,
+ Required, //
},
mm::vram::VramRegion,
vgpu::Dbdf, //
@@ -330,6 +330,50 @@ pub(crate) fn encode_plugin_config_params(
Ok(encoder.finish())
}
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub(crate) struct AllocCeutilsRequest {
+ pub(crate) gfid: u32,
+ pub(crate) fixed_chid: u32,
+ pub(crate) force_ceid: u32,
+ pub(crate) swizz_id: u32,
+}
+
+// SAFETY: All fields are integers, and the struct has no padding.
+unsafe impl kernel::transmute::AsBytes for AllocCeutilsRequest {}
+
+// SAFETY: All fields are integers, for which all bit patterns are valid.
+unsafe impl kernel::transmute::FromBytes for AllocCeutilsRequest {}
+
+#[repr(C)]
+#[derive(FromBytes, IntoBytes)]
+pub(crate) struct AllocCeutilsResponse {
+ pub(crate) semaphore_address: u64,
+ pub(crate) semaphore_aperture: u32,
+ _reserved: u32,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub(crate) struct ScrubGuestFbRequest {
+ pub(crate) gfid: u32,
+ pub(crate) reserved: u32,
+ pub(crate) fb_offset: u64,
+ pub(crate) fb_size: u64,
+}
+
+// SAFETY: All fields are integers, and the struct has no padding.
+unsafe impl kernel::transmute::AsBytes for ScrubGuestFbRequest {}
+
+// SAFETY: All fields are integers, for which all bit patterns are valid.
+unsafe impl kernel::transmute::FromBytes for ScrubGuestFbRequest {}
+
+#[repr(C)]
+#[derive(FromBytes, IntoBytes)]
+pub(crate) struct ScrubGuestFbResponse {
+ pub(crate) work_id: u64,
+}
+
nvkv_encode! {
struct PluginSetBmeRequest {
bme_enable: Key<bool, 0x0100, u32>,
diff --git a/drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs b/drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs
index 85f965335b64..e46f7339544a 100644
--- a/drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs
+++ b/drivers/gpu/nova-core/vgpu/fw/r000_00/bindings.rs
@@ -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;
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 33/35] gpu: nova-core: vgpu: scrub guest VRAM with CeUtils
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (31 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 32/35] gpu: nova-core: vgpu: add CeUtils commands Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 34/35] gpu: nova-core: vgpu: introduce SR-IOV PF APIs Alok Kumar
2026-11-24 13:59 ` [PATCH v5 35/35] gpu: nova-core: mm: keep BAR1 self-test page tables alive Alok Kumar
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index bdb4821751e7..e1e2d6bcfd31 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -41,6 +41,7 @@
mod gsp_plugin_rpc;
mod hal;
mod instance;
+mod scrubber;
mod vram;
bitfield! {
diff --git a/drivers/gpu/nova-core/vgpu/commands.rs b/drivers/gpu/nova-core/vgpu/commands.rs
index a71379165eaf..07a8e071d34d 100644
--- a/drivers/gpu/nova-core/vgpu/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/commands.rs
@@ -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<'_>,
diff --git a/drivers/gpu/nova-core/vgpu/instance.rs b/drivers/gpu/nova-core/vgpu/instance.rs
index 59d7014d7f69..2f6c2a8f3a02 100644
--- a/drivers/gpu/nova-core/vgpu/instance.rs
+++ b/drivers/gpu/nova-core/vgpu/instance.rs
@@ -31,12 +31,14 @@
use super::{
commands::{
+ free_ceutils,
negotiate_plugin_version,
send_bootload,
send_cleanup,
send_plugin_config,
send_shutdown,
- set_plugin_bme, //
+ set_plugin_bme,
+ CeUtilsAllocError, //
},
fw::commands::{
encode_plugin_config_params,
@@ -47,6 +49,7 @@
},
gsp_plugin_comm::CommBufferRegion,
gsp_plugin_rpc::PluginRpc,
+ scrubber::CeUtils,
vram::{
VgpuVramLayout,
VgpuVramSlot,
@@ -156,12 +159,41 @@ struct VgpuInstance<'gpu> {
// Unmap the communication region before returning its slot and channel IDs.
vram_slot: VgpuVramSlot,
chids: ChannelIdReservation<'gpu>,
+ ceutils: Option<CeUtils>,
needs_teardown: bool,
/// An uncertain or failed operation retains resources until device removal.
failure: Option<Error>,
}
impl<'gpu> VgpuInstance<'gpu> {
+ fn initialize(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
+ let ceutils_chid =
+ u32::try_from(self.chids.end.checked_sub(1).ok_or(EINVAL)?).map_err(|_| EOVERFLOW)?;
+ let ceutils = match CeUtils::allocate(vgpu.dev, vgpu.cmdq, self.gfid, ceutils_chid) {
+ Ok(ceutils) => ceutils,
+ Err(CeUtilsAllocError::NotOwned(error)) => return Err(error),
+ Err(CeUtilsAllocError::MayOwn(error)) => {
+ self.failure = Some(error);
+ dev_err!(vgpu.dev, "CeUtils allocation failed: {:?}\n", error);
+ return Err(error);
+ }
+ };
+
+ let result = ceutils.scrub_guest_fb(
+ vgpu.dev,
+ vgpu.cmdq,
+ vgpu.bar_user,
+ vgpu.mm,
+ &self.vram_slot.fbmem,
+ );
+ self.ceutils = Some(ceutils);
+ if let Err(error) = result {
+ // A failed wait does not establish that the submitted scrub has stopped.
+ self.failure = Some(error);
+ }
+ result
+ }
+
fn activate(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
let dev = vgpu.dev;
self.bootload(dev, vgpu.cmdq, &vgpu.fifo_engine_list)?;
@@ -180,7 +212,17 @@ fn teardown(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
}
let result = (|| {
self.shutdown(vgpu.dev, vgpu.cmdq)?;
-
+ if let Some(ceutils) = self.ceutils.as_ref() {
+ ceutils.scrub_guest_fb(
+ vgpu.dev,
+ vgpu.cmdq,
+ vgpu.bar_user,
+ vgpu.mm,
+ &self.vram_slot.fbmem,
+ )?;
+ free_ceutils(vgpu.dev, vgpu.cmdq, self.gfid)?;
+ self.ceutils = None;
+ }
if self.needs_teardown {
send_cleanup(vgpu.dev, vgpu.cmdq, self.gfid)?;
self.needs_teardown = false;
@@ -246,7 +288,7 @@ fn configure_plugin(&mut self, dev: &device::Device) -> Result {
self.dbdf,
self.vgpu_type.vgpu_type_id,
self.vm_pid,
- u32::try_from(self.chids.len()).map_err(|_| EOVERFLOW)?,
+ u32::try_from(self.chids.len().checked_sub(1).ok_or(EINVAL)?).map_err(|_| EOVERFLOW)?,
self.num_plugin_channels,
)?;
@@ -356,6 +398,9 @@ fn allocate_instance(
.map(usize::from_safe_cast)
.and_then(NonZeroUsize::new)
.ok_or(EINVAL)?;
+ if channels_per_instance <= cv!(1) {
+ return Err(EINVAL);
+ }
let chids = vgpu
.chid_pool
.reserve_ids(channels_per_instance, Alignment::SZ_1)?;
@@ -382,6 +427,7 @@ fn allocate_instance(
plugin_rpc: PluginRpc::new(comm, vgpu.bar, gfid),
vram_slot,
chids,
+ ceutils: None,
needs_teardown: false,
failure: None,
})
@@ -436,7 +482,9 @@ fn create_instance(&self, info: InstanceInfo) -> Result {
instances.instances.reserve(1, GFP_KERNEL)?;
let mut instance = instances.allocate_instance(self, info)?;
- let result = instance.activate(self);
+ let result = instance
+ .initialize(self)
+ .and_then(|()| instance.activate(self));
if result.is_err() {
match instance.teardown(self) {
diff --git a/drivers/gpu/nova-core/vgpu/scrubber.rs b/drivers/gpu/nova-core/vgpu/scrubber.rs
new file mode 100644
index 000000000000..00daa11b8653
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/scrubber.rs
@@ -0,0 +1,172 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! Per-VM CeUtils guest VRAM scrubbing.
+
+use kernel::{
+ device,
+ io::io_read,
+ prelude::*,
+ time::{
+ delay::fsleep,
+ Delta,
+ Instant,
+ Monotonic, //
+ },
+ types::ScopeGuard, //
+};
+
+use crate::{
+ gsp::cmdq::Cmdq,
+ mm::{
+ bar_user::BarUser,
+ vram::VramRegion,
+ Pfn,
+ SharedGpuMm,
+ VramAddress, //
+ },
+ vgpu::instance::Gfid, //
+};
+
+use super::commands::{
+ self,
+ CeUtilsAllocError, //
+};
+
+// Semaphore layout from OpenRM `channel_utils.h`.
+const NV_CEUTILS_SEMA_PAGE_MAGIC: u32 = 0xce5e_5ea0;
+
+#[repr(C)]
+struct CeUtilsSemaphoreHeader {
+ magic: u32,
+ payload: u32,
+}
+
+static_assert!(size_of::<CeUtilsSemaphoreHeader>() == 8);
+
+const SCRUB_REQUEST_SIZE: u64 = 4 * 1024 * 1024 * 1024;
+
+// Host timeout policy; not a firmware ABI value.
+const SCRUB_TIMEOUT: Delta = Delta::from_secs(5);
+
+/// A firmware-owned per-VM CeUtils allocation.
+///
+/// Submitted scrubs must complete before releasing this allocation or its VRAM.
+pub(super) struct CeUtils {
+ gfid: Gfid,
+ semaphore_address: u64,
+}
+
+impl CeUtils {
+ pub(super) fn allocate(
+ dev: &device::Device<device::Bound>,
+ cmdq: &Cmdq<'_>,
+ gfid: Gfid,
+ chid: u32,
+ ) -> core::result::Result<Self, CeUtilsAllocError> {
+ let semaphore_address = commands::alloc_ceutils(dev, cmdq, gfid, chid)?;
+ Ok(Self {
+ gfid,
+ semaphore_address,
+ })
+ }
+
+ /// Scrub the complete guest VRAM and wait for semaphore completion.
+ pub(super) fn scrub_guest_fb(
+ &self,
+ dev: &device::Device<device::Bound>,
+ cmdq: &Cmdq<'_>,
+ bar_user: &BarUser<'_>,
+ mm: &SharedGpuMm<'_>,
+ fb: &VramRegion,
+ ) -> Result {
+ let mut offset = fb.range().start;
+ let end = fb.range().end;
+ while offset < end {
+ let size = core::cmp::min(SCRUB_REQUEST_SIZE, end - offset);
+ let work_id = commands::submit_ceutils_scrub(dev, cmdq, self.gfid, offset, size)?;
+ wait_scrub_complete(bar_user, mm, dev, self.semaphore_address, work_id)?;
+ offset = offset.checked_add(size).ok_or(EOVERFLOW)?;
+ }
+
+ Ok(())
+ }
+}
+
+/// Poll the GSP-owned CeUtils semaphore page through a temporary BAR1 map.
+fn wait_scrub_complete(
+ bar_user: &BarUser<'_>,
+ mm: &SharedGpuMm<'_>,
+ dev: &device::Device<device::Bound>,
+ semaphore_address: u64,
+ work_id: u32,
+) -> Result {
+ let pfn = Pfn::from(VramAddress::from_raw(semaphore_address));
+ let semaphore_map = mm.with_locked(|mm| bar_user.map(mm, &[pfn], false))?;
+ let semaphore_map = ScopeGuard::new_with_data(semaphore_map, |mapping| {
+ if let Err(error) = mm.with_locked(|mm| mapping.release(mm)) {
+ dev_err!(
+ dev,
+ "failed to release semaphore BAR1 mapping: {:?}\n",
+ error
+ );
+ }
+ });
+
+ let result = (|| {
+ let semaphore = semaphore_map.view::<CeUtilsSemaphoreHeader>(0)?;
+
+ let magic = io_read!(semaphore, .magic);
+ if magic != NV_CEUTILS_SEMA_PAGE_MAGIC {
+ dev_warn!(
+ dev,
+ "bad CeUtils semaphore magic {:#x}, expected {:#x}\n",
+ magic,
+ NV_CEUTILS_SEMA_PAGE_MAGIC,
+ );
+ return Err(EIO);
+ }
+
+ let start = Instant::<Monotonic>::now();
+ loop {
+ let value = io_read!(semaphore, .payload);
+ if value.wrapping_sub(work_id) < 0x8000_0000 {
+ dev_dbg!(
+ dev,
+ "scrub completed after {:?}: semaphore={:#x}, target={:#x}\n",
+ start.elapsed(),
+ value,
+ work_id,
+ );
+ return Ok(());
+ }
+
+ if start.elapsed() >= SCRUB_TIMEOUT {
+ dev_warn!(
+ dev,
+ "scrub timed out: semaphore={:#x}, target={:#x}\n",
+ value,
+ work_id,
+ );
+ return Err(ETIMEDOUT);
+ }
+ fsleep(Delta::from_millis(1));
+ }
+ })();
+
+ let cleanup = mm.with_locked(|mm| semaphore_map.dismiss().release(mm));
+ match result {
+ Ok(()) => cleanup,
+ Err(error) => {
+ if let Err(cleanup_error) = cleanup {
+ dev_err!(
+ dev,
+ "failed to release semaphore BAR1 mapping after error {:?}: {:?}\n",
+ error,
+ cleanup_error,
+ );
+ }
+ Err(error)
+ }
+ }
+}
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 34/35] gpu: nova-core: vgpu: introduce SR-IOV PF APIs
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (32 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 33/35] gpu: nova-core: vgpu: scrub guest VRAM with CeUtils Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
2026-11-24 13:59 ` [PATCH v5 35/35] gpu: nova-core: mm: keep BAR1 self-test page tables alive Alok Kumar
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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.
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
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
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 0de451fc3d7b..a2f78dfb1121 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -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>,
diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
index 75970cb0b5cb..e0fc62630fbe 100644
--- a/drivers/gpu/nova-core/mm/bar_user.rs
+++ b/drivers/gpu/nova-core/mm/bar_user.rs
@@ -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(
diff --git a/drivers/gpu/nova-core/mm/vram.rs b/drivers/gpu/nova-core/mm/vram.rs
index 7774b15e4c89..6054eed9aeb0 100644
--- a/drivers/gpu/nova-core/mm/vram.rs
+++ b/drivers/gpu/nova-core/mm/vram.rs
@@ -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> {
diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
index 84f777844592..418571724543 100644
--- a/drivers/gpu/nova-core/nova_core.rs
+++ b/drivers/gpu/nova-core/nova_core.rs
@@ -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.
diff --git a/drivers/gpu/nova-core/vgpu.rs b/drivers/gpu/nova-core/vgpu.rs
index e1e2d6bcfd31..1aee21dbe740 100644
--- a/drivers/gpu/nova-core/vgpu.rs
+++ b/drivers/gpu/nova-core/vgpu.rs
@@ -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! {
diff --git a/drivers/gpu/nova-core/vgpu/commands.rs b/drivers/gpu/nova-core/vgpu/commands.rs
index 07a8e071d34d..ae2ae3b69a1c 100644
--- a/drivers/gpu/nova-core/vgpu/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/commands.rs
@@ -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;
diff --git a/drivers/gpu/nova-core/vgpu/fw/commands.rs b/drivers/gpu/nova-core/vgpu/fw/commands.rs
index c2e2ffad2b2d..7cb2db63c3a0 100644
--- a/drivers/gpu/nova-core/vgpu/fw/commands.rs
+++ b/drivers/gpu/nova-core/vgpu/fw/commands.rs
@@ -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,
}
diff --git a/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs b/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
index 49d85df70018..f9fd8c2a5da0 100644
--- a/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
+++ b/drivers/gpu/nova-core/vgpu/gsp_plugin_comm.rs
@@ -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(
diff --git a/drivers/gpu/nova-core/vgpu/instance.rs b/drivers/gpu/nova-core/vgpu/instance.rs
index 2f6c2a8f3a02..5c6353f8c09a 100644
--- a/drivers/gpu/nova-core/vgpu/instance.rs
+++ b/drivers/gpu/nova-core/vgpu/instance.rs
@@ -33,6 +33,7 @@
commands::{
free_ceutils,
negotiate_plugin_version,
+ reset_plugin,
send_bootload,
send_cleanup,
send_plugin_config,
@@ -56,6 +57,7 @@
VgpuVramSlotPool, //
},
Dbdf,
+ VgpuManager,
VgpuManagerInner, //
};
@@ -112,7 +114,6 @@ fn wait_plugin_ready(dev: &device::Device, comm: &CommBufferRegion<'_, '_>) -> R
impl Gfid {
/// Validates an external GFID for a device supporting `total_vfs` VFs.
- #[expect(dead_code)]
pub(super) fn new(gfid: u32, total_vfs: NonZero<u16>) -> Result<Self> {
let gfid = u16::try_from(gfid).map_err(|_| EINVAL)?;
let gfid = NonZero::new(gfid).ok_or(EINVAL)?;
@@ -160,6 +161,7 @@ struct VgpuInstance<'gpu> {
vram_slot: VgpuVramSlot,
chids: ChannelIdReservation<'gpu>,
ceutils: Option<CeUtils>,
+ active: bool,
needs_teardown: bool,
/// An uncertain or failed operation retains resources until device removal.
failure: Option<Error>,
@@ -202,6 +204,7 @@ fn activate(&mut self, vgpu: &VgpuManagerInner<'gpu>) -> Result {
self.configure_plugin(dev)?;
set_plugin_bme(dev, &mut self.plugin_rpc, true)?;
+ self.active = true;
Ok(())
}
@@ -301,6 +304,7 @@ fn shutdown(&mut self, dev: &device::Device, cmdq: &Cmdq<'_>) -> Result {
send_shutdown(dev, cmdq, self.gfid)?;
dev_dbg!(dev, "shutdown: gfid={} stopped\n", self.gfid.get());
}
+ self.active = false;
Ok(())
}
}
@@ -313,7 +317,6 @@ pub(super) struct InstanceInfo {
vm_pid: u32,
}
-#[expect(dead_code)]
impl InstanceInfo {
pub(super) fn new(gfid: Gfid, dbdf: Dbdf, properties: &VgpuProperties, vm_pid: u32) -> Self {
Self {
@@ -331,7 +334,6 @@ pub(super) struct VgpuInstances<'gpu> {
vram_slots: Option<VgpuVramSlotPool>,
}
-#[expect(dead_code)]
impl<'gpu> VgpuInstances<'gpu> {
pub(super) const fn new() -> Self {
Self {
@@ -428,6 +430,7 @@ fn allocate_instance(
vram_slot,
chids,
ceutils: None,
+ active: false,
needs_teardown: false,
failure: None,
})
@@ -468,13 +471,27 @@ pub(super) fn release_all(&mut self, vgpu: &VgpuManagerInner<'gpu>) {
}
}
+impl VgpuManager<'_> {
+ /// Allocate, register, and activate a vGPU instance.
+ pub(super) fn create_instance(&self, info: InstanceInfo) -> Result {
+ self.with_inner(|inner| inner.create_instance(info))
+ }
+
+ pub(super) fn close_instance(&self, gfid: Gfid) -> Result {
+ self.with_inner(|inner| inner.close_instance(gfid))
+ }
+
+ pub(super) fn reset_instance(&self, gfid: Gfid) -> Result {
+ self.with_inner(|inner| inner.reset_instance(gfid))
+ }
+}
+
impl VgpuManagerInner<'_> {
/// Allocate, register, and activate a vGPU instance.
///
/// Keep the registry locked through creation or rollback so duplicate checks and
/// type limits remain stable. MM and BAR-user locks are acquired only within
/// individual memory operations, in that order.
- #[expect(dead_code)]
fn create_instance(&self, info: InstanceInfo) -> Result {
let mut instances = self.instances.lock();
@@ -507,4 +524,36 @@ fn create_instance(&self, info: InstanceInfo) -> Result {
result
}
+
+ fn close_instance(&self, gfid: Gfid) -> Result {
+ self.instances.lock().destroy_instance(self, gfid)
+ }
+
+ fn reset_instance(&self, gfid: Gfid) -> Result {
+ let mut instances = self.instances.lock();
+ let instance = instances
+ .instances
+ .iter_mut()
+ .find(|instance| instance.gfid == gfid)
+ .ok_or(ENOENT)?;
+ if instance.failure.is_some() || !instance.active {
+ return Err(EBUSY);
+ }
+
+ let result = (|| {
+ reset_plugin(self.dev, &mut instance.plugin_rpc)?;
+ instance.ceutils.as_ref().ok_or(EINVAL)?.scrub_guest_fb(
+ self.dev,
+ self.cmdq,
+ self.bar_user,
+ self.mm,
+ &instance.vram_slot.fbmem,
+ )
+ })();
+ if let Err(error) = result {
+ instance.failure = Some(error);
+ instance.active = false;
+ }
+ result
+ }
}
diff --git a/drivers/gpu/nova-core/vgpu/vgpu_api.rs b/drivers/gpu/nova-core/vgpu/vgpu_api.rs
new file mode 100644
index 000000000000..b263e96098a8
--- /dev/null
+++ b/drivers/gpu/nova-core/vgpu/vgpu_api.rs
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! PF-owned lifecycle operations for Nova VF drivers.
+
+use core::num::NonZero;
+
+use kernel::{
+ device,
+ pci,
+ prelude::*, //
+};
+
+use crate::{
+ gpu::Gpu,
+ gsp::cmdq::Cmdq,
+ vgpu::{
+ commands::query_vgpu_properties,
+ fw::commands::VgpuProperties,
+ instance::{
+ Gfid,
+ InstanceInfo, //
+ },
+ },
+};
+
+use super::{
+ commands::query_assigned_vf_type,
+ Dbdf,
+ VgpuManager, //
+};
+
+/// Guest PCI properties of an activated vGPU instance.
+pub struct VgpuTypeInfo {
+ /// PCI device ID to present to the guest.
+ pub pci_dev_id: u32,
+ /// PCI subsystem ID to present to the guest.
+ pub pci_subsys_id: u32,
+ /// BAR1 aperture size in MiB.
+ pub bar1_length: u64,
+}
+
+impl From<&VgpuProperties> for VgpuTypeInfo {
+ fn from(vgpu_properties: &VgpuProperties) -> Self {
+ Self {
+ pci_dev_id: vgpu_properties.dev_id,
+ pci_subsys_id: vgpu_properties.subsystem_id,
+ bar1_length: vgpu_properties.bar1_length,
+ }
+ }
+}
+
+/// PF-owned operations available while a VF driver is bound.
+pub struct NovaCoreVfApi<'gpu> {
+ pdev: &'gpu pci::Device<device::Bound>,
+ cmdq: &'gpu Cmdq<'gpu>,
+ vgpu: Option<&'gpu VgpuManager<'gpu>>,
+ total_vfs: Option<NonZero<u16>>,
+}
+
+impl<'gpu> NovaCoreVfApi<'gpu> {
+ #[expect(dead_code)]
+ pub(crate) fn new(gpu: &'gpu Gpu<'gpu>, pdev: &'gpu pci::Device<device::Bound>) -> Self {
+ Self {
+ pdev,
+ cmdq: gpu.cmdq(),
+ vgpu: gpu.vgpu_manager(),
+ total_vfs: gpu.vgpu_total_vfs(),
+ }
+ }
+
+ /// Returns whether the PF booted with vGPU support enabled.
+ pub fn is_available(&self) -> bool {
+ self.vgpu.is_some()
+ }
+
+ fn gfid(&self, gfid: u32) -> Result<Gfid> {
+ let total_vfs = self.total_vfs.ok_or(ENODEV)?;
+ Gfid::new(gfid, total_vfs)
+ }
+}
+
+impl NovaCoreVfApi<'_> {
+ /// Creates and boots an instance for a one-based VF ID.
+ ///
+ /// `sbdf` encodes the VF address as `(segment << 16) | (bus << 8) | devfn`.
+ /// `vm_pid` identifies the VM process's thread group. This call may sleep.
+ pub fn open_instance(&self, gfid: u32, sbdf: u32, vm_pid: u32) -> Result<VgpuTypeInfo> {
+ let dev = self.pdev.as_ref();
+ let gfid = self.gfid(gfid)?;
+ let dbdf = Dbdf::from_raw(sbdf);
+
+ dev_dbg!(
+ dev,
+ "vgpu_open: gfid={} sbdf={:#x}\n",
+ gfid.get(),
+ dbdf.into_raw()
+ );
+
+ let cmdq = self.cmdq;
+ let vgpu = self.vgpu.ok_or(ENODEV)?;
+
+ let type_id = query_assigned_vf_type(dev, cmdq, dbdf)?;
+ dev_dbg!(
+ dev,
+ "vgpu_open: gfid={} assigned type_id={}\n",
+ gfid.get(),
+ type_id
+ );
+
+ let vgpu_properties = query_vgpu_properties(dev, cmdq, type_id)?;
+ dev_dbg!(
+ dev,
+ "vgpu_open: gfid={} vgpu_type={} fb_length={:#x}\n",
+ gfid.get(),
+ vgpu_properties.type_id,
+ vgpu_properties.fb_length
+ );
+
+ vgpu.create_instance(InstanceInfo::new(gfid, dbdf, &vgpu_properties, vm_pid))?;
+
+ Ok(VgpuTypeInfo::from(&*vgpu_properties))
+ }
+
+ /// Tears down an instance, retaining resources if firmware cleanup fails.
+ ///
+ /// This call may sleep.
+ pub fn close_instance(&self, gfid: u32) -> Result {
+ let dev = self.pdev.as_ref();
+ let gfid = self.gfid(gfid)?;
+
+ dev_dbg!(dev, "vgpu_close: gfid={}\n", gfid.get());
+
+ let result = self.vgpu.ok_or(ENODEV)?.close_instance(gfid);
+ if let Err(error) = result {
+ dev_err!(dev, "vgpu_close: gfid={} failed: {:?}\n", gfid.get(), error);
+ }
+ result
+ }
+
+ /// Resets an instance and scrubs its guest VRAM. This call may sleep.
+ pub fn reset_instance(&self, gfid: u32) -> Result {
+ let dev = self.pdev.as_ref();
+ let gfid = self.gfid(gfid)?;
+
+ dev_dbg!(dev, "vgpu_reset: gfid={}\n", gfid.get());
+
+ self.vgpu.ok_or(ENODEV)?.reset_instance(gfid)?;
+
+ dev_dbg!(dev, "vgpu_reset: gfid={} done\n", gfid.get());
+ Ok(())
+ }
+}
diff --git a/drivers/gpu/nova-core/vgpu/vram.rs b/drivers/gpu/nova-core/vgpu/vram.rs
index fb7c460b9d97..e3edf25549af 100644
--- a/drivers/gpu/nova-core/vgpu/vram.rs
+++ b/drivers/gpu/nova-core/vgpu/vram.rs
@@ -36,7 +36,6 @@ pub(super) struct VgpuVramLayout {
fb_align: u64,
}
-#[expect(dead_code)]
impl VgpuVramLayout {
pub(super) fn new(
type_id: u32,
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread* [PATCH v5 35/35] gpu: nova-core: mm: keep BAR1 self-test page tables alive
2026-11-24 13:58 [PATCH v5 00/35] Introduce NVIDIA vGPU manager Alok Kumar
` (33 preceding siblings ...)
2026-11-24 13:59 ` [PATCH v5 34/35] gpu: nova-core: vgpu: introduce SR-IOV PF APIs Alok Kumar
@ 2026-11-24 13:59 ` Alok Kumar
34 siblings, 0 replies; 36+ messages in thread
From: Alok Kumar @ 2026-11-24 13:59 UTC (permalink / raw)
To: dakr, acourbot, kvm, rust-for-linux, nova-gpu, linux-pci
Cc: alex, jgg, yishaih, skolothumtho, kevin.tian, airlied, simona,
ojeda, alex.gaynor, boqun.feng, gary, bjorn3_gh, lossin,
a.hindborg, aliceryhl, tmgross, markus.probst, jhubbard, apopple,
joelagnelf, ecourtney, cjia, smitra, kjaju, alkumar, ankita,
aniketa, kwankhede, targupta, linux-kernel, zhiwang, zhiw, boqun,
daniel.almeida, tamird, work, jgg, bhelgaas, kwilczynski,
dri-devel, peter, xinmengs
From: Zhi Wang <zhiw@nvidia.com>
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")
Signed-off-by: Zhi Wang <zhiw@nvidia.com>
Signed-off-by: Alok Kumar <alkumar@nvidia.com>
---
drivers/gpu/nova-core/mm/bar_user.rs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/drivers/gpu/nova-core/mm/bar_user.rs b/drivers/gpu/nova-core/mm/bar_user.rs
index e0fc62630fbe..4a49962f7f68 100644
--- a/drivers/gpu/nova-core/mm/bar_user.rs
+++ b/drivers/gpu/nova-core/mm/bar_user.rs
@@ -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.
--
2.53.0
^ permalink raw reply [flat|nested] 36+ messages in thread