From: Zhi Wang <[email protected]>

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

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

Signed-off-by: Zhi Wang <[email protected]>
Co-developed-by: Alok Kumar <[email protected]>
Signed-off-by: Alok Kumar <[email protected]>
Co-developed-by: Alexandre Courbot <[email protected]>
Signed-off-by: Alexandre Courbot <[email protected]>
---
 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

Reply via email to