From: Zhi Wang A vGPU instance needs channel IDs and framebuffer and management-heap regions determined by its assigned type. Let instances own their channel reservations and borrow their VRAM regions from a manager-owned pool. Keep the pinned pool and its instance registry together. The registry borrows the pool through a pin-init self-reference and drops its instances before the pool's backing VramBlock is released. Keep those borrows inside the owning object through scoped projections. Reject duplicate GFID or DBDF entries and enforce the profile's instance limit. Reserve registry capacity before acquiring instance resources. Removing an instance releases its channel reservation and makes its VRAM slot available for reuse. Keep the pool cached when the last instance is removed. Replace it for a different layout only when no instances remain, releasing the old backing allocation before reserving the new one. Signed-off-by: Zhi Wang Co-developed-by: Alexandre Courbot Signed-off-by: Alexandre Courbot Signed-off-by: Alok Kumar --- drivers/gpu/nova-core/gpu.rs | 50 +++-- drivers/gpu/nova-core/mm.rs | 1 - drivers/gpu/nova-core/vgpu.rs | 56 +++-- drivers/gpu/nova-core/vgpu/instance.rs | 291 +++++++++++++++++++++++++ drivers/gpu/nova-core/vgpu/vram.rs | 1 - 5 files changed, 363 insertions(+), 36 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 549a0a90d244..40cc326b5cf2 100644 --- a/drivers/gpu/nova-core/gpu.rs +++ b/drivers/gpu/nova-core/gpu.rs @@ -51,6 +51,7 @@ bar_user::BarUser, pagetable::MmuVersion, GpuMm, + SharedGpuMm, VramAddress, // }, timer::{ @@ -63,7 +64,6 @@ }, }; -#[cfg_attr(not(CONFIG_KUNIT = "y"), expect(dead_code))] pub(crate) mod channel; mod hal; mod regs; @@ -390,7 +390,9 @@ unsafe fn new( #[pin_data] pub(crate) struct Gpu<'gpu> { pub(crate) spec: Spec, - vgpu: Option>, + /// Drops before the MM and BAR1 mappings needed for instance teardown. + #[uses('bar_user, 'chid_pool)] + vgpu: Option>>>, /// GSP event interrupt registration, and the enable of its subtree. /// /// Must be kept declared *before* `gsp_resources`, so that the handler is unregistered, and @@ -403,7 +405,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>, @@ -568,7 +571,7 @@ pub(crate) fn new<'a>( }, // Create GPU memory manager owning memory management resources. - mm: { + mm <- { let info = &gsp_resources.boot_result.static_info; let usable_vram = info.usable_fb_regions.first().ok_or(ENODEV)?; let buddy_params = GpuBuddyParams { @@ -577,12 +580,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. @@ -604,15 +607,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, + )?), } }, - }) } @@ -645,14 +651,16 @@ pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device impl<'gpu> SharedGpuMm<'gpu> { /// Creates a pin-initializer sharing `mm`. - #[expect(dead_code)] pub(crate) fn new(mm: GpuMm<'gpu>) -> impl PinInit + '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 5688d6bf1e08..e7b4f1f3a614 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>, + 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 + 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..40f32da359d5 --- /dev/null +++ b/drivers/gpu/nova-core/vgpu/instance.rs @@ -0,0 +1,291 @@ +// 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::channel::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); + +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) -> Result { + 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<'pool, 'gpu> { + gfid: Gfid, + dbdf: Dbdf, + vgpu_type: VgpuType, + vm_pid: u32, + chids: ChannelIdReservation<'gpu>, + vram_slot: VgpuVramSlot<'pool>, +} + +/// 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, + } + } +} + +/// Instance registry and cached VRAM pool for one physical GPU. +pub(super) struct VgpuInstances<'gpu> { + pool: Option>>>, +} + +/// Instances borrow the pool, and are destroyed before its backing allocation. +#[pin_data] +struct VgpuInstancePool<'gpu> { + // Preserve the pool lifetime when inserting new borrowed regions into the registry. + #[uses('pool: invariant)] + registry: InstanceRegistry<'pool, 'gpu>, + #[pin] + pool: VgpuVramSlotPool, +} + +impl<'gpu> VgpuInstancePool<'gpu> { + fn new(mm: &GpuMm<'_>, layout: VgpuVramLayout) -> Result> { + let pool = VgpuVramSlotPool::new(mm, layout)?; + Ok(try_pin_init!(Self { + pool <- pool, + registry: InstanceRegistry { + instances: KVec::new(), + pool: pool.get_ref(), + }, + })) + } +} + +#[expect(dead_code)] +impl<'gpu> VgpuInstances<'gpu> { + pub(super) const fn new() -> Self { + Self { pool: None } + } + + fn create_instance(&mut self, vgpu: &VgpuManagerInner<'gpu>, info: InstanceInfo) -> Result { + let layout = VgpuVramLayout::new( + info.vgpu_type.vgpu_type_id, + info.vgpu_type.max_instance, + info.vgpu_type.fb_length, + info.vgpu_type.gsp_heap_size, + vgpu.vmmu_segment_size, + )?; + let replace = match self.pool.as_ref() { + Some(pool) => pool.as_ref().with_project_ref(|this| { + if this.pool.matches_layout(layout) { + Ok(false) + } else if this.registry.instances.is_empty() { + Ok(true) + } else { + Err(EBUSY) + } + })?, + None => true, + }; + if replace { + // Release the old reservation only after all its borrowers are gone. + self.pool = None; + self.pool = Some(vgpu.mm.with_locked(|mm| { + KBox::pin_init(VgpuInstancePool::new(mm, layout)?, GFP_KERNEL) + })?); + } + self.pool + .as_mut() + .ok_or(EIO)? + .as_mut() + .with_project(|this| this.registry.create_instance(vgpu, info)) + } + + fn destroy_instance(&mut self, gfid: Gfid) -> Result { + self.pool + .as_mut() + .ok_or(ENOENT)? + .as_mut() + .with_project(|this| this.registry.destroy_instance(gfid)) + } +} + +/// Registry of instances borrowing one layout's pool. +struct InstanceRegistry<'pool, 'gpu> { + instances: KVec>, + pool: &'pool VgpuVramSlotPool, +} + +impl<'pool, 'gpu> InstanceRegistry<'pool, 'gpu> { + fn alloc_vram_slot(&self) -> Result> { + let index = (0..self.pool.max_slots()) + .find(|i| !self.instances.iter().any(|inst| inst.vram_slot.index == *i)) + .ok_or(ENOSPC)?; + self.pool.slot(index) + } + + /// Creates and returns a [`VgpuInstance`]. + fn allocate_instance( + &mut self, + vgpu: &VgpuManagerInner<'gpu>, + info: InstanceInfo, + ) -> Result> { + 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_slot = self.alloc_vram_slot()?; + + 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(()) + } + + /// 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. + fn create_instance(&mut self, vgpu: &VgpuManagerInner<'gpu>, info: InstanceInfo) -> Result { + // Reserve capacity before acquiring resources so registration cannot allocate. + self.instances.reserve(1, GFP_KERNEL)?; + + let instance = self.allocate_instance(vgpu, info)?; + + // Register live instances, and failed ones whose resources firmware may still own. + self.instances + .push_within_capacity(instance) + .map_err(|_| EIO)?; + + Ok(()) + } +} + +impl VgpuManagerInner<'_> { + #[expect(dead_code)] + fn create_instance(&self, info: InstanceInfo) -> Result { + self.instances.lock().create_instance(self, info) + } +} diff --git a/drivers/gpu/nova-core/vgpu/vram.rs b/drivers/gpu/nova-core/vgpu/vram.rs index b6356a9765e2..a6d3f02341da 100644 --- a/drivers/gpu/nova-core/vgpu/vram.rs +++ b/drivers/gpu/nova-core/vgpu/vram.rs @@ -94,7 +94,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.