Rust for Linux List
 help / color / mirror / Atom feed
From: Alok Kumar <alkumar@nvidia.com>
To: <dakr@kernel.org>, <acourbot@nvidia.com>, <kvm@vger.kernel.org>,
	<rust-for-linux@vger.kernel.org>, <nova-gpu@lists.linux.dev>,
	<linux-pci@vger.kernel.org>
Cc: <alex@shazbot.org>, <jgg@nvidia.com>, <yishaih@nvidia.com>,
	<skolothumtho@nvidia.com>, <kevin.tian@intel.com>,
	<airlied@gmail.com>, <simona@ffwll.ch>, <ojeda@kernel.org>,
	<alex.gaynor@gmail.com>, <boqun.feng@gmail.com>,
	<gary@garyguo.net>, <bjorn3_gh@protonmail.com>,
	<lossin@kernel.org>, <a.hindborg@kernel.org>,
	<aliceryhl@google.com>, <tmgross@umich.edu>,
	<markus.probst@posteo.de>, <jhubbard@nvidia.com>,
	<apopple@nvidia.com>, <joelagnelf@nvidia.com>,
	<ecourtney@nvidia.com>, <cjia@nvidia.com>, <smitra@nvidia.com>,
	<kjaju@nvidia.com>, <alkumar@nvidia.com>, <ankita@nvidia.com>,
	<aniketa@nvidia.com>, <kwankhede@nvidia.com>,
	<targupta@nvidia.com>, <linux-kernel@vger.kernel.org>,
	<zhiwang@kernel.org>, <zhiw@nvidia.com>, <boqun@kernel.org>,
	<daniel.almeida@collabora.com>, <tamird@kernel.org>,
	<work@onurozkan.dev>, <jgg@ziepe.ca>, <bhelgaas@google.com>,
	<kwilczynski@kernel.org>, <dri-devel@lists.freedesktop.org>,
	<peter@colberg.org>, <xinmengs@nvidia.com>
Subject: [PATCH v5 27/35] gpu: nova-core: vgpu: add instance shutdown
Date: Tue, 24 Nov 2026 19:29:23 +0530	[thread overview]
Message-ID: <20261124135937.18583-28-alkumar@nvidia.com> (raw)
In-Reply-To: <20261124135937.18583-1-alkumar@nvidia.com>

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


  parent reply	other threads:[~2026-11-24 14:08 UTC|newest]

Thread overview: 36+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
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 ` [PATCH v5 03/35] gpu: nova-core: gsp: decouple boot context from VgpuManager Alok Kumar
2026-11-24 13:59 ` [PATCH v5 04/35] gpu: nova-core: vgpu: detect boot state independently Alok Kumar
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 ` [PATCH v5 06/35] gpu: nova-core: gsp: decode the FIFO engine table Alok Kumar
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 ` [PATCH v5 08/35] gpu: nova-core: vgpu: reserve the 48-VM WPR2 heap Alok Kumar
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 ` [PATCH v5 10/35] gpu: nova-core: mm: retain BAR1 reservations after unmap failure Alok Kumar
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 ` [PATCH v5 12/35] gpu: nova-core: mm: add VramBlock Alok Kumar
2026-11-24 13:59 ` [PATCH v5 13/35] gpu: nova-core: mm: add VramRegion Alok Kumar
2026-11-24 13:59 ` [PATCH v5 14/35] gpu: nova-core: mm: add BarMapping Alok Kumar
2026-11-24 13:59 ` [PATCH v5 15/35] gpu: nova-core: mm: add SharedGpuMm 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
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 ` [PATCH v5 18/35] gpu: nova-core: gsp: cmdq: add send_gmc_command_await_event Alok Kumar
2026-11-24 13:59 ` [PATCH v5 19/35] gpu: nova-core: vgpu: add r000 plugin bindings Alok Kumar
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 ` [PATCH v5 21/35] gpu: nova-core: vgpu: add VRAM slot pool Alok Kumar
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 ` [PATCH v5 23/35] gpu: nova-core: vgpu: add instance create/destroy Alok Kumar
2026-11-24 13:59 ` [PATCH v5 24/35] gpu: nova-core: vgpu: encode vGPU boot requests Alok Kumar
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 ` [PATCH v5 26/35] gpu: nova-core: vgpu: add instance boot Alok Kumar
2026-11-24 13:59 ` Alok Kumar [this message]
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 ` [PATCH v5 29/35] gpu: nova-core: vgpu: negotiate the GSP plugin RPC version Alok Kumar
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 ` [PATCH v5 31/35] gpu: nova-core: vgpu: update the GSP plugin BME state Alok Kumar
2026-11-24 13:59 ` [PATCH v5 32/35] gpu: nova-core: vgpu: add CeUtils commands Alok Kumar
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 ` [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

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261124135937.18583-28-alkumar@nvidia.com \
    --to=alkumar@nvidia.com \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=airlied@gmail.com \
    --cc=alex.gaynor@gmail.com \
    --cc=alex@shazbot.org \
    --cc=aliceryhl@google.com \
    --cc=aniketa@nvidia.com \
    --cc=ankita@nvidia.com \
    --cc=apopple@nvidia.com \
    --cc=bhelgaas@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=boqun@kernel.org \
    --cc=cjia@nvidia.com \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=dri-devel@lists.freedesktop.org \
    --cc=ecourtney@nvidia.com \
    --cc=gary@garyguo.net \
    --cc=jgg@nvidia.com \
    --cc=jgg@ziepe.ca \
    --cc=jhubbard@nvidia.com \
    --cc=joelagnelf@nvidia.com \
    --cc=kevin.tian@intel.com \
    --cc=kjaju@nvidia.com \
    --cc=kvm@vger.kernel.org \
    --cc=kwankhede@nvidia.com \
    --cc=kwilczynski@kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-pci@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=markus.probst@posteo.de \
    --cc=nova-gpu@lists.linux.dev \
    --cc=ojeda@kernel.org \
    --cc=peter@colberg.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=simona@ffwll.ch \
    --cc=skolothumtho@nvidia.com \
    --cc=smitra@nvidia.com \
    --cc=tamird@kernel.org \
    --cc=targupta@nvidia.com \
    --cc=tmgross@umich.edu \
    --cc=work@onurozkan.dev \
    --cc=xinmengs@nvidia.com \
    --cc=yishaih@nvidia.com \
    --cc=zhiw@nvidia.com \
    --cc=zhiwang@kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox