mirror of https://lore.kernel.org/lkml/
 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 v6 26/34] gpu: nova-core: vgpu: add instance shutdown
Date: Wed, 2 Dec 2026 13:58:50 +0530	[thread overview]
Message-ID: <1ee16d4314bd675abf5d9fdcb494260bc7c8afe8.1796191008.git.alkumar@nvidia.com> (raw)
In-Reply-To: <cover.1796191007.git.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        | 92 +++++++++++++++++--
 5 files changed, 160 insertions(+), 9 deletions(-)

diff --git a/drivers/gpu/nova-core/gsp/cmdq/gmc.rs b/drivers/gpu/nova-core/gsp/cmdq/gmc.rs
index c9465b20df78..5c0d078204c0 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 af257d0f8bc5..1e4c510ea4dd 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 ec435c026b64..126ba9ad99cf 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 7a3f29251c4e..892347f073ff 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<'pool, 'gpu> {
     // Unmap the communication region before returning its slot and channel IDs.
     vram_slot: VgpuVramSlot<'pool>,
     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.
@@ -293,12 +329,19 @@ fn create_instance(&mut self, vgpu: &VgpuManagerInner<'gpu>, info: InstanceInfo)
             .with_project(|this| this.registry.create_instance(vgpu, info))
     }
 
-    fn destroy_instance(&mut self, gfid: Gfid) -> Result {
+    fn destroy_instance(&mut self, vgpu: &VgpuManagerInner<'gpu>, gfid: Gfid) -> Result {
         self.pool
             .as_mut()
             .ok_or(ENOENT)?
             .as_mut()
-            .with_project(|this| this.registry.destroy_instance(gfid))
+            .with_project(|this| this.registry.destroy_instance(vgpu, gfid))
+    }
+
+    pub(super) fn release_all(&mut self, vgpu: &VgpuManagerInner<'gpu>) {
+        if let Some(pool) = self.pool.as_mut() {
+            pool.as_mut()
+                .with_project(|this| this.registry.release_all(vgpu));
+        }
     }
 }
 
@@ -369,21 +412,45 @@ 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();
+    }
+
     /// Allocate, register, and activate a vGPU instance.
     ///
     /// Keep the registry locked through creation or rollback so duplicate checks and
@@ -396,6 +463,19 @@ fn create_instance(&mut self, vgpu: &VgpuManagerInner<'gpu>, info: InstanceInfo)
         let mut instance = self.allocate_instance(vgpu, info)?;
         let result = instance.activate(vgpu);
 
+        if result.is_err() {
+            match instance.teardown(vgpu) {
+                // Firmware owns nothing anymore; drop the instance to release its resources.
+                Ok(()) => return result,
+                Err(error) => dev_err!(
+                    vgpu.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.
         self.instances
             .push_within_capacity(instance)

  parent reply	other threads:[~2026-12-02  8:38 UTC|newest]

Thread overview: 35+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-02  8:28 [PATCH v6 00/34] Introduce NVIDIA vGPU manager Alok Kumar
2026-12-02  8:28 ` [PATCH v6 01/34] gpu: nova-core: populate VF information in GSP_INIT Alok Kumar
2026-12-02  8:28 ` [PATCH v6 02/34] gpu: nova-core: gsp: pass boot context through setup helpers Alok Kumar
2026-12-02  8:28 ` [PATCH v6 03/34] gpu: nova-core: vgpu: decouple boot state from the manager Alok Kumar
2026-12-02  8:28 ` [PATCH v6 04/34] gpu: nova-core: gpu: add a channel ID pool for vGPU Alok Kumar
2026-12-02  8:28 ` [PATCH v6 05/34] gpu: nova-core: gsp: decode the FIFO engine table Alok Kumar
2026-12-02  8:28 ` [PATCH v6 06/34] gpu: nova-core: vgpu: initialize runtime parameters after GSP boot Alok Kumar
2026-12-02  8:28 ` [PATCH v6 07/34] gpu: nova-core: vgpu: reserve the 48-VM WPR2 heap Alok Kumar
2026-12-02  8:28 ` [PATCH v6 08/34] gpu: nova-core: mm: replace BarUserAccess accessors with typed MMIO view Alok Kumar
2026-12-02  8:28 ` [PATCH v6 09/34] gpu: nova-core: mm: retain BAR1 reservations after unmap failure Alok Kumar
2026-12-02  8:28 ` [PATCH v6 10/34] gpu: nova-core: mm: borrow BarUser for temporary BAR1 access Alok Kumar
2026-12-02  8:28 ` [PATCH v6 11/34] gpu: nova-core: mm: add VramBlock Alok Kumar
2026-12-02  8:28 ` [PATCH v6 12/34] gpu: nova-core: mm: add VramRegion Alok Kumar
2026-12-02  8:28 ` [PATCH v6 13/34] gpu: nova-core: mm: add BarMapping Alok Kumar
2026-12-02  8:28 ` [PATCH v6 14/34] gpu: nova-core: mm: add SharedGpuMm Alok Kumar
2026-12-02  8:28 ` [PATCH v6 15/34] gpu: nova-core: gsp: cmdq: gmc: add types for variable-length payloads Alok Kumar
2026-12-02  8:28 ` [PATCH v6 16/34] gpu: nova-core: gsp: add the vGPU commands to GmcCommandId Alok Kumar
2026-12-02  8:28 ` [PATCH v6 17/34] gpu: nova-core: gsp: cmdq: add send_gmc_command_await_event Alok Kumar
2026-12-02  8:28 ` [PATCH v6 18/34] gpu: nova-core: vgpu: add r000 plugin bindings Alok Kumar
2026-12-02  8:28 ` [PATCH v6 19/34] gpu: nova-core: gsp: factor out NVKV payload conversion Alok Kumar
2026-12-02  8:28 ` [PATCH v6 20/34] gpu: nova-core: vgpu: add VRAM slot pool Alok Kumar
2026-12-02  8:28 ` [PATCH v6 21/34] gpu: nova-core: vgpu: query VF assignments and properties Alok Kumar
2026-12-02  8:28 ` [PATCH v6 22/34] gpu: nova-core: vgpu: add instance create/destroy Alok Kumar
2026-12-02  8:28 ` [PATCH v6 23/34] gpu: nova-core: vgpu: encode vGPU boot requests Alok Kumar
2026-12-02  8:28 ` [PATCH v6 24/34] gpu: nova-core: vgpu: add GSP plugin communication buffer Alok Kumar
2026-12-02  8:28 ` [PATCH v6 25/34] gpu: nova-core: vgpu: add instance boot Alok Kumar
2026-12-02  8:28 ` Alok Kumar [this message]
2026-12-02  8:28 ` [PATCH v6 27/34] gpu: nova-core: vgpu: add GSP plugin RPC transactions Alok Kumar
2026-12-02  8:28 ` [PATCH v6 28/34] gpu: nova-core: vgpu: negotiate the GSP plugin RPC version Alok Kumar
2026-12-02  8:28 ` [PATCH v6 29/34] gpu: nova-core: vgpu: send GSP plugin configuration parameters Alok Kumar
2026-12-02  8:28 ` [PATCH v6 30/34] gpu: nova-core: vgpu: update the GSP plugin BME state Alok Kumar
2026-12-02  8:28 ` [PATCH v6 31/34] gpu: nova-core: vgpu: add CeUtils commands Alok Kumar
2026-12-02  8:28 ` [PATCH v6 32/34] gpu: nova-core: vgpu: scrub guest VRAM with CeUtils Alok Kumar
2026-12-02  8:28 ` [PATCH v6 33/34] gpu: nova-core: vgpu: introduce SR-IOV PF APIs Alok Kumar
2026-12-02  8:28 ` [PATCH v6 34/34] 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=1ee16d4314bd675abf5d9fdcb494260bc7c8afe8.1796191008.git.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

all inboxes | Powered by JetHome®