Skip to contentSkip to conversation

gpu: nova-core: consolidate and streamline GSP boot process

PATCH Superseded Alexandre Courbot 3 participants 34 messages Jun 29 – Jul 7

Subsystems (5)

v4 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

v4 cover gpu: nova-core: consolidate and streamline GSP boot process

The recently introduced GspBootContext is useful in at least two other places:

- As a replacement for the sequencer's GspSequencerParams,
- As the main parameter of Gsp::unload, for symmetry with Gsp::boot.

This symmetry can be further exploited to make Gsp::boot and Gsp::unload generic over the exact boot context required for the current chip. Doing so requires some more preliminary work that goes beyond this series, but this groundwork is needed regardless.

Another cleanup that can be performed as a consequence is the removal of the BootUnloadGuard. This type is cumbersome as it holds extra references to the boot context, making it difficult to make some of these references mutable (as we want to do with the Falcons that should require exclusive access to load and run firmware). Furthermore, it is only needed a single time in Gsp::boot, and inadequate to handle errors occurring in HALs.

Building on this, the series also introduces a proper type for identifying the GSP boot method, and moves the Fsp instance to Gpu to make it available outside of the GSP boot process. This will be notably useful for vGPU support [1].

This series applies on the latest drm-rust-next.

Since v3, drm-rust-next gained a change that makes Falcon retain references tied to the lifetime of the bound GPU [2]. GspBootContext thus needs separate lifetimes: one for these references valid as long as the GPU is bound, and another for its own shorter borrows of the GPU's subdevices.

The distinction becomes necessary because the final patch adds a mutable reference to Fsp. Mutable references are invariant over their pointee type, and so the compiler raises an error unless the two lifetimes are separated.

A new patch is introduced to take care of this.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

---
Changes in v4:
- Rebase on top of latest drm-rust-next.
- Add preparatory patch to separate the different lifetimes at play in GspBootContext.
- Link to v3: https://patch.msgid.link/[email protected]

Changes in v3:
- Drop the preparatory closure-only patch.
- Use ScopeGuard for GSP boot-error cleanup.
- Keep TU102 boot-error cleanup local to the HAL.
- Avoid spurious unload-bundle warnings on early failures.
- Keep GH100 FMC boot arguments alive through lockdown release.
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- Replace nonexistent ENODATA with the more appropriate EAGAIN.
- Add patches introducing GspBootMethod.
- Add patches moving Fsp to Gpu.
- Link to v1: https://patch.msgid.link/[email protected]

---
Alexandre Courbot (13):
gpu: nova-core: gsp: sequencer: use GspBootContext
gpu: nova-core: gsp: sequencer: do not store sequence into GspSequencer
gpu: nova-core: gsp: replace BootUnloadGuard with local handlers
gpu: nova-core: gsp: pass GspBootContext to unload methods
gpu: nova-core: gsp: centralize missing unload bundle warnings
gpu: nova-core: gsp: fold TU102 unload bundle construction into HAL method
gpu: nova-core: gsp: turn FWSEC execution into HAL method
gpu: nova-core: gsp: make use of FWSEC bootloader a property of the TU102 HAL
gpu: nova-core: introduce GspBootMethod
gpu: nova-core: avoid repeated calls to pci::Device::as_ref
gpu: nova-core: gsp: pass GspBootContext mutably
gpu: nova-core: gsp: separate context and GPU lifetimes in GspBootContext
gpu: nova-core: store Fsp instance in Gpu

 drivers/gpu/nova-core/firmware.rs       |  25 ++-
 drivers/gpu/nova-core/firmware/fwsec.rs |   5 +-
 drivers/gpu/nova-core/gpu.rs            |  68 ++++---
 drivers/gpu/nova-core/gsp.rs            |  63 +++++-
 drivers/gpu/nova-core/gsp/boot.rs       |  99 +++-------
 drivers/gpu/nova-core/gsp/hal.rs        |  56 +++---
 drivers/gpu/nova-core/gsp/hal/ga102.rs  |  14 ++
 drivers/gpu/nova-core/gsp/hal/gh100.rs  |  42 ++--
 drivers/gpu/nova-core/gsp/hal/tu102.rs  | 332 ++++++++++++++++----------------
 drivers/gpu/nova-core/gsp/sequencer.rs  |  71 +++----
 10 files changed, 383 insertions(+), 392 deletions(-)

---
base-commit: 23d66dbab84e8518943563df2ced14aaab28b77a
change-id: 20260619-nova-bootcontext-401d6107e8fb

Best regards,

Signature · 1 line
Alexandre Courbot <[email protected]>
author maintainer
#1 lore raw

PATCH v4 1/13 gpu: nova-core: gsp: sequencer: use GspBootContext

GspBootContext contains all the resources currently carried by GspSequencerParams, so replace the latter with the former for better integration with the boot process and less code.

---
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 21 +++++++-------------
 drivers/gpu/nova-core/gsp/sequencer.rs | 36 ++++++++++++----------------------
 2 files changed, 20 insertions(+), 37 deletions(-)
drivers/gpu/nova-core/gsp/hal/tu102.rs +7 -14
index ff71b45b5432..87ceb8878f01 100644
@@ -37,10 +37,7 @@
             GspHal,
             UnloadBundle, //
         },
-        sequencer::{
-            GspSequencer,
-            GspSequencerParams, //
-        },
+        sequencer::GspSequencer,
         Gsp,
         GspBootContext,
         GspFwWprMeta, //
@@ -326,16 +323,12 @@ fn boot<'a>(
     }
 
     fn post_boot(&self, gsp: &Gsp, ctx: &GspBootContext<'_>, gsp_fw: &GspFirmware) -> Result {
-        // Create and run the GSP sequencer.
-        let seq_params = GspSequencerParams {
-            bootloader_app_version: gsp_fw.bootloader.app_version,
-            libos_dma_handle: gsp.libos.dma_handle(),
-            gsp_falcon: ctx.gsp_falcon,
-            sec2_falcon: ctx.sec2_falcon,
-            dev: ctx.dev(),
-            bar: ctx.bar,
-        };
-        GspSequencer::run(&gsp.cmdq, seq_params)?;
+        GspSequencer::run(
+            &gsp.cmdq,
+            ctx,
+            gsp.libos.dma_handle(),
+            gsp_fw.bootloader.app_version,
+        )?;
 
         Ok(())
     }
drivers/gpu/nova-core/gsp/sequencer.rs +13 -23
index 13983d42b12b..f55205bd61f3 100644
@@ -31,6 +31,7 @@
             MessageFromGsp, //
         },
         fw,
+        GspBootContext, //
     },
     num::FromSafeCast,
     sbuffer::SBufferIter,
@@ -335,24 +336,13 @@ fn iter(&self) -> GspSeqIter<'_> {
     }
 }
 
-/// Parameters for running the GSP sequencer.
-pub(crate) struct GspSequencerParams<'a> {
-    /// Bootloader application version.
-    pub(crate) bootloader_app_version: u32,
-    /// LibOS DMA handle address.
-    pub(crate) libos_dma_handle: u64,
-    /// GSP falcon for core operations.
-    pub(crate) gsp_falcon: &'a Falcon<'a, Gsp>,
-    /// SEC2 falcon for core operations.
-    pub(crate) sec2_falcon: &'a Falcon<'a, Sec2>,
-    /// Device for logging.
-    pub(crate) dev: &'a device::Device,
-    /// BAR0 for register access.
-    pub(crate) bar: Bar0<'a>,
-}
-
 impl<'a> GspSequencer<'a> {
-    pub(crate) fn run(cmdq: &Cmdq, params: GspSequencerParams<'a>) -> Result {
+    pub(crate) fn run(
+        cmdq: &Cmdq,
+        ctx: &'a GspBootContext<'_>,
+        libos_dma_handle: u64,
+        bootloader_app_version: u32,
+    ) -> Result {
         let seq_info = loop {
             match cmdq.receive_msg::<GspSequence>(Cmdq::RECEIVE_TIMEOUT) {
                 Ok(seq_info) => break seq_info,
@@ -363,12 +353,12 @@ pub(crate) fn run(cmdq: &Cmdq, params: GspSequencerParams<'a>) -> Result {
 
         let sequencer = GspSequencer {
             seq_info,
-            bar: params.bar,
-            sec2_falcon: params.sec2_falcon,
-            gsp_falcon: params.gsp_falcon,
-            libos_dma_handle: params.libos_dma_handle,
-            bootloader_app_version: params.bootloader_app_version,
-            dev: params.dev,
+            bar: ctx.bar,
+            sec2_falcon: ctx.sec2_falcon,
+            gsp_falcon: ctx.gsp_falcon,
+            libos_dma_handle,
+            bootloader_app_version,
+            dev: ctx.dev(),
         };
 
         dev_dbg!(sequencer.dev, "Running CPU Sequencer commands\n");
Signature · 1 line
2.54.0
#2 lore raw

Re: [PATCH v4 01/13] gpu: nova-core: gsp: sequencer: use GspBootContext

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Pre-existing issues:
- [High] Incorrect loop bounds check causes RPC message padding bytes to be executed as hardware sequencer commands (e.g., unintended RegWrite to address 0).
- [High] Fixed-size zero-padded buffer bypasses length checks for truncated commands, leading to execution of zeroed out-of-bounds payloads.
- [High] Unaligned stack array passed to FromBytes::from_bytes may cause spurious parsing failures and abort the GSP boot process depending on compiler stack layout. --

commit c264aea160f8cb747324a1d5a568d1e3a869623a
Author: Alexandre Courbot <[email protected]>

gpu: nova-core: gsp: sequencer: use GspBootContext

GspBootContext contains all the resources currently carried by GspSequencerParams, so replace the latter with the former for better integration with the boot process and less code.

Quoted 4 lines
drivers/gpu/nova-core/gsp/sequencer.rs +0 -0
index 13983d42b12bc..f55205bd61f35 100644

[ ... ]

drivers/gpu/nova-core/gsp/sequencer.rs fn iter(&self) -> GspSeqIter<'_> { · line 337

Quoted 3 lines
drivers/gpu/nova-core/gsp/sequencer.rs +0 -0
@@ -335,24 +336,13 @@ fn iter(&self) -> GspSeqIter<'_> {
     }
 }

[Severity: High]
This is a pre-existing issue, but does this bounds check in GspSeqIter::next() fail to prevent processing alignment padding bytes?

In drivers/gpu/nova-core/gsp/sequencer.rs:GspSeqIter::new(), total_cmds is initialized using the length in DWORDs rather than the command count:

    GspSeqIter {
        ...
        total_cmds: self.seq_info.cmd_index,
        ...
    }

Then in GspSeqIter::next(), the loop bounds check compares commands processed against this DWORD count:

    if self.cmds_processed >= self.total_cmds ||
       self.current_offset >= self.cmd_data.len() {
        return None;
    }

If the message buffer contains RPC alignment padding (e.g., trailing zeros), could cmds_processed fail to reach total_cmds, causing these zeros to be incorrectly parsed as hardware sequencer commands (where opcode 0 is RegWrite to address 0)?

[Severity: High]
This is a pre-existing issue, but does passing a zero-padded buffer bypass the length check for truncated commands?

In drivers/gpu/nova-core/gsp/sequencer.rs:GspSeqIter::next(), a truncated command is copied into a fixed 24-byte zero-initialized array, and a slice covering the entire array is passed to GspSeqCmd::new():

    let mut buffer = [0u8; CMD_SIZE];
    ...
    buffer[..copy_len].copy_from_slice(
        &self.cmd_data[offset..offset + copy_len]
    );
    let cmd_result = GspSeqCmd::new(&buffer, self.dev);

Inside GspSeqCmd::new(), the length check evaluates data.len(), which will always be 24 regardless of copy_len:

    if data.len() < size {
        dev_err!(dev, "Data is not enough for command\n");
        return Err(EINVAL);
    }

Could this allow execution of malformed, zero-padded hardware commands?

[Severity: High]
This is a pre-existing issue, but can the unaligned stack array passed to FromBytes::from_bytes() cause spurious parsing failures?

In drivers/gpu/nova-core/gsp/sequencer.rs:GspSeqIter::next(), buffer is backed by a u8 array which only guarantees 1-byte alignment:

    let mut buffer = [0u8; CMD_SIZE];

When this buffer is passed to GspSeqCmd::new() and then to SequencerBufferCmd::from_bytes():

    let fw_cmd = fw::SequencerBufferCmd::from_bytes(data).ok_or(EINVAL)?;

If the compiler places the array at a misaligned address on the stack, could from_bytes() (which expects 4-byte alignment for u32 fields) fail silently and abort the GSP boot process?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#3 lore raw

PATCH v4 2/13 gpu: nova-core: gsp: sequencer: do not store sequence into GspSequencer

In reply to Alexandre Courbot

The sequence is currently stored in the GspSequencer even though its lifetime is limited to GspSequencer::run. This object-oriented design does not play well with the borrow-checker, as GspSequencer::iter borrows a reference to the GspSequencer, which makes it difficult to introduce mutable references in GspBootContext, as we want to do in order to make the Falcon references mutable.

Thus, store the sequence locally in GspSequencer::run, and move iterator creation to GspSeqIter::new so it no longer needs to borrow the whole GspSequencer.

---
 drivers/gpu/nova-core/gsp/sequencer.rs | 35 +++++++++++++++-------------------
 1 file changed, 15 insertions(+), 20 deletions(-)
drivers/gpu/nova-core/gsp/sequencer.rs +15 -20
index f55205bd61f3..ddce32cc4e30 100644
@@ -129,8 +129,6 @@ pub(crate) fn new(data: &[u8], dev: &device::Device) -> Result<(Self, usize)> {
 
 /// GSP Sequencer for executing firmware commands during boot.
 pub(crate) struct GspSequencer<'a> {
-    /// Sequencer information with command data.
-    seq_info: GspSequence,
     /// `Bar0` for register access.
     bar: Bar0<'a>,
     /// SEC2 falcon for core operations.
@@ -268,7 +266,7 @@ fn run(&self, seq: &GspSequencer<'_>) -> Result {
 }
 
 /// Iterator over GSP sequencer commands.
-pub(crate) struct GspSeqIter<'a> {
+struct GspSeqIter<'a> {
     /// Command data buffer.
     cmd_data: &'a [u8],
     /// Current position in the buffer.
@@ -281,6 +279,18 @@ pub(crate) struct GspSeqIter<'a> {
     dev: &'a device::Device,
 }
 
+impl<'a> GspSeqIter<'a> {
+    fn new(seq: &'a GspSequence, dev: &'a device::Device) -> Self {
+        Self {
+            cmd_data: &seq.cmd_data,
+            current_offset: 0,
+            total_cmds: seq.cmd_index,
+            cmds_processed: 0,
+            dev,
+        }
+    }
+}
+
 impl<'a> Iterator for GspSeqIter<'a> {
     type Item = Result<GspSeqCmd>;
 
@@ -322,20 +332,6 @@ fn next(&mut self) -> Option<Self::Item> {
     }
 }
 
-impl<'a> GspSequencer<'a> {
-    fn iter(&self) -> GspSeqIter<'_> {
-        let cmd_data = &self.seq_info.cmd_data[..];
-
-        GspSeqIter {
-            cmd_data,
-            current_offset: 0,
-            total_cmds: self.seq_info.cmd_index,
-            cmds_processed: 0,
-            dev: self.dev,
-        }
-    }
-}
-
 impl<'a> GspSequencer<'a> {
     pub(crate) fn run(
         cmdq: &Cmdq,
@@ -352,7 +348,6 @@ pub(crate) fn run(
         };
 
         let sequencer = GspSequencer {
-            seq_info,
             bar: ctx.bar,
             sec2_falcon: ctx.sec2_falcon,
             gsp_falcon: ctx.gsp_falcon,
@@ -363,14 +358,14 @@ pub(crate) fn run(
 
         dev_dbg!(sequencer.dev, "Running CPU Sequencer commands\n");
 
-        for cmd_result in sequencer.iter() {
+        for cmd_result in GspSeqIter::new(&seq_info, sequencer.dev) {
             match cmd_result {
                 Ok(cmd) => cmd.run(&sequencer)?,
                 Err(e) => {
                     dev_err!(
                         sequencer.dev,
                         "Error running command at index {}\n",
-                        sequencer.seq_info.cmd_index
+                        seq_info.cmd_index
                     );
                     return Err(e);
                 }
Signature · 1 line
2.54.0
#4 lore raw

Re: [PATCH v4 02/13] gpu: nova-core: gsp: sequencer: do not store sequence into GspSequencer

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Pre-existing issues:
- [High] The sequencer iterator silently terminates upon encountering a command parsing error, causing the boot sequence to falsely report success.
- [High] Truncated commands at the end of the sequence buffer are silently executed with zero-padded payloads instead of failing. --

commit ffd1618690514804f608d22ee8574e39be09904e
Author: Alexandre Courbot <[email protected]>

gpu: nova-core: gsp: sequencer: do not store sequence into GspSequencer

The sequence is currently stored in the GspSequencer even though its lifetime is limited to GspSequencer::run. This object-oriented design does not play well with the borrow-checker, as GspSequencer::iter borrows a reference to the GspSequencer, which makes it difficult to introduce mutable references in GspBootContext, as we want to do in order to make the Falcon references mutable.

Thus, store the sequence locally in GspSequencer::run, and move iterator creation to GspSeqIter::new so it no longer needs to borrow the whole GspSequencer.

Quoted 4 lines
drivers/gpu/nova-core/gsp/sequencer.rs +0 -0
index f55205bd61f35..ddce32cc4e308 100644

[ ... ]

Quoted 27 lines
drivers/gpu/nova-core/gsp/sequencer.rs +12 -4
@@ -281,6 +279,18 @@ pub(crate) struct GspSeqIter<'a> {
     dev: &'a device::Device,
 }
 
+impl<'a> GspSeqIter<'a> {
+    fn new(seq: &'a GspSequence, dev: &'a device::Device) -> Self {
+        Self {
+            cmd_data: &seq.cmd_data,
+            current_offset: 0,
+            total_cmds: seq.cmd_index,
+            cmds_processed: 0,
+            dev,
+        }
+    }
+}
+
 impl<'a> Iterator for GspSeqIter<'a> {
     type Item = Result<GspSeqCmd>;
 
@@ -322,20 +332,6 @@ fn next(&mut self) -> Option<Self::Item> {
     }
 }
 
-impl<'a> GspSequencer<'a> {
-    fn iter(&self) -> GspSeqIter<'_> {
-        let cmd_data = &self.seq_info.cmd_data[..];
-

drivers/gpu/nova-core/gsp/sequencer.rs fn next(&mut self) -> Option<Self::Item> { · line 338

Quoted 10 lines
drivers/gpu/nova-core/gsp/sequencer.rs +0 -10
-        GspSeqIter {
-            cmd_data,
-            current_offset: 0,
-            total_cmds: self.seq_info.cmd_index,
-            cmds_processed: 0,
-            dev: self.dev,
-        }
-    }
-}
-

[Severity: High]
This isn't a bug introduced by this patch, but while looking at GspSeqIter::next() I noticed that it silently terminates on parsing errors:

drivers/gpu/nova-core/gsp/sequencer.rs:GspSeqIter::next() {
    ...
    let cmd_result = GspSeqCmd::new(&buffer, self.dev);

    cmd_result.map_or_else(
        |_err| {
            dev_err!(self.dev, "Error parsing command at offset {}\n", offset);
            None
        },
    ...
}

If firmware sends invalid data and GspSeqCmd::new() returns an error, the iterator returns None instead of propagating the error. This silently stops the iterator loop, causing the remaining hardware initialization commands to be skipped while GspSequencer::run() falsely reports success.

Can this leave the GPU in an uninitialized state and cause system hangs or memory corruption?

[Severity: High]
This is a pre-existing issue, but I also noticed a potential bounds checking bypass when GspSeqIter::next() processes truncated commands at the end of the sequence buffer:

drivers/gpu/nova-core/gsp/sequencer.rs:GspSeqIter::next() {
    ...
    let mut buffer = [0u8; CMD_SIZE];
    let copy_len = if offset + CMD_SIZE <= self.cmd_data.len() {
        CMD_SIZE
    } else {
        self.cmd_data.len() - offset
    };
    buffer[..copy_len].copy_from_slice(&self.cmd_data[offset..offset + copy_len]);
    let cmd_result = GspSeqCmd::new(&buffer, self.dev);
    ...
}

When copy_len is less than CMD_SIZE, the data is copied into the zero-padded buffer and passed to GspSeqCmd::new() as a full CMD_SIZE slice.

Inside GspSeqCmd::new():

drivers/gpu/nova-core/gsp/sequencer.rs:GspSeqCmd::new() {
    ...
    if data.len() < size {
        dev_err!(dev, "Data is not enough for command\n");
        return Err(EINVAL);
    }
    ...
}

Since data.len() is always evaluated as the full buffer length (CMD_SIZE), this check always passes, neutralizing the intended length validation.

Does this execute truncated firmware commands with zeroed payloads instead of failing, potentially causing unintended hardware actions or state corruption?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author maintainer
#5 lore raw

PATCH v4 3/13 gpu: nova-core: gsp: replace BootUnloadGuard with local handlers

In reply to Alexandre Courbot

When adding the GSP unload capability, we introduced BootUnloadGuard to automatically call Gsp::unload whenever an error occurred during the boot process, in order to try to reset the GSP to a valid state.

This approach is not well-suited to the errors that may occur in HALs:
by definition, an error occurring in the HAL means that the GSP is not booted; yet the first thing that Gsp::unload does is queue a shutdown message to the GSP, which will inevitably result in a timeout when done from a HAL.

Furthermore, BootUnloadGuard is problematic because it holds additional references to the boot context, notably the Falcons. These extra references stand in the way of making some of the Falcon's methods mutable, since those methods would require exclusive access. As this behavior is only needed in one place, introducing dedicated types for it is distracting and unnecessary.

Thus, remove BootUnloadGuard and adopt a two-level error handling strategy:

- HALs are free to handle their errors as they see fit (most likely, by running their unload bundle if it is ready by the time of the error),
- Gsp::boot uses a ScopeGuard that runs Gsp::unload, since the GSP should be up and running by the time GspHal::boot has returned.

---
 drivers/gpu/nova-core/gsp/boot.rs      | 67 +++-------------------------------
 drivers/gpu/nova-core/gsp/hal.rs       | 13 +++----
 drivers/gpu/nova-core/gsp/hal/gh100.rs | 20 ++++------
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 23 +++++++-----
 4 files changed, 33 insertions(+), 90 deletions(-)
drivers/gpu/nova-core/gsp/boot.rs +6 -61
index ab0491b57944..536f2e341c01 100644
@@ -30,66 +30,6 @@
     },
 };
 
-/// Arguments required to call [`Gsp::unload`](super::Gsp::unload).
-///
-/// Stored as their own type to avoid repeating a long and tedious list in [`BootUnloadGuard`].
-pub(super) struct BootUnloadArgs<'a> {
-    gsp: &'a super::Gsp,
-    dev: &'a device::Device<device::Bound>,
-    bar: Bar0<'a>,
-    gsp_falcon: &'a Falcon<'a, Gsp>,
-    sec2_falcon: &'a Falcon<'a, Sec2>,
-    unload_bundle: Option<super::UnloadBundle>,
-}
-
-/// Guard that calls [`Gsp::unload`](super::Gsp::unload) with a
-/// [`UnloadBundle`](super::UnloadBundle) when dropped.
-///
-/// Used to ensure the `UnloadBundle` is run during failure paths.
-pub(super) struct BootUnloadGuard<'a> {
-    guard: ScopeGuard<BootUnloadArgs<'a>, fn(BootUnloadArgs<'a>)>,
-}
-
-impl<'a> BootUnloadGuard<'a> {
-    /// Wraps `unload_bundle` into a guard that executes it when dropped.
-    pub(super) fn new(
-        gsp: &'a super::Gsp,
-        dev: &'a device::Device<device::Bound>,
-        bar: Bar0<'a>,
-        gsp_falcon: &'a Falcon<'a, Gsp>,
-        sec2_falcon: &'a Falcon<'a, Sec2>,
-        unload_bundle: Option<super::UnloadBundle>,
-    ) -> Self {
-        Self {
-            guard: ScopeGuard::new_with_data(
-                BootUnloadArgs {
-                    gsp,
-                    dev,
-                    bar,
-                    gsp_falcon,
-                    sec2_falcon,
-                    unload_bundle,
-                },
-                |args| {
-                    let _ = super::Gsp::unload(
-                        args.gsp,
-                        args.dev,
-                        args.bar,
-                        args.gsp_falcon,
-                        args.sec2_falcon,
-                        args.unload_bundle,
-                    );
-                },
-            ),
-        }
-    }
-
-    /// Disarms the guard and returns the [`UnloadBundle`](super::UnloadBundle) it contains.
-    pub(super) fn dismiss(self) -> Option<super::UnloadBundle> {
-        self.guard.dismiss().unload_bundle
-    }
-}
-
 impl super::Gsp {
     /// Attempt to boot the GSP.
     ///
@@ -107,6 +47,7 @@ pub(crate) fn boot(
         let bar = ctx.bar;
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
+        let sec2_falcon = ctx.sec2_falcon;
         let dev = pdev.as_ref();
         let hal = super::hal::gsp_hal(chipset);
 
@@ -118,7 +59,11 @@ pub(crate) fn boot(
         let wpr_meta = Coherent::init(dev, GFP_KERNEL, GspFwWprMeta::new(&gsp_fw, &fb_layout))?;
 
         // Perform the chipset-specific boot sequence, and retrieve the unload bundle.
-        let unload_guard = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?;
+        let unload_bundle = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?;
+
+        let unload_guard = ScopeGuard::new_with_data(unload_bundle, |unload_bundle| {
+            let _ = self.unload(dev, bar, gsp_falcon, sec2_falcon, unload_bundle);
+        });
 
         gsp_falcon.write_os_version(gsp_fw.bootloader.app_version);
 
drivers/gpu/nova-core/gsp/hal.rs +6 -7
index d3e47ef206de..851d1f24c137 100644
@@ -24,7 +24,6 @@
         Chipset, //
     },
     gsp::{
-        boot::BootUnloadGuard,
         Gsp,
         GspBootContext,
         GspFwWprMeta, //
@@ -51,15 +50,15 @@ fn run(
 pub(super) trait GspHal: Send {
     /// Performs the GSP boot process, loading and running the required firmwares as needed.
     ///
-    /// Upon success, returns a guard that runs the GSP unload sequence if GSP boot does not
-    /// complete.
-    fn boot<'a>(
+    /// Upon success, returns the [`crate::gsp::UnloadBundle`] to use with [`Gsp::unload`], if one
+    /// could be created.
+    fn boot(
         &self,
-        gsp: &'a Gsp,
-        ctx: &GspBootContext<'a>,
+        gsp: &Gsp,
+        ctx: &GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
-    ) -> Result<BootUnloadGuard<'a>>;
+    ) -> Result<Option<crate::gsp::UnloadBundle>>;
 
     /// Performs HAL-specific post-GSP boot tasks.
     ///
drivers/gpu/nova-core/gsp/hal/gh100.rs +8 -12
index 1d06405a32f6..5fe445d73599 100644
@@ -23,7 +23,6 @@
         Fsp, //
     },
     gsp::{
-        boot::BootUnloadGuard,
         hal::{
             GspHal,
             UnloadBundle, //
@@ -143,27 +142,22 @@ impl GspHal for Gh100 {
     ///
     /// This path uses FSP to establish a chain of trust and boot GSP-FMC. FSP handles
     /// the GSP boot internally - no manual GSP reset/boot is needed.
-    fn boot<'a>(
+    fn boot(
         &self,
-        gsp: &'a Gsp,
-        ctx: &GspBootContext<'a>,
+        gsp: &Gsp,
+        ctx: &GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
-    ) -> Result<BootUnloadGuard<'a>> {
+    ) -> Result<Option<crate::gsp::UnloadBundle>> {
         let dev = ctx.dev();
         let bar = ctx.bar;
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
-        let sec2_falcon = ctx.sec2_falcon;
 
         let unload_bundle = crate::gsp::UnloadBundle(
             KBox::new(FspUnloadBundle, GFP_KERNEL)? as KBox<dyn UnloadBundle>
         );
 
-        // Wrap the unload bundle into a drop guard so it is automatically run upon failure.
-        let unload_guard =
-            BootUnloadGuard::new(gsp, dev, bar, gsp_falcon, sec2_falcon, Some(unload_bundle));
-
         let mut fsp = Fsp::wait_secure_boot(dev, bar, chipset)?;
 
         let args = FmcBootArgs::new(
@@ -174,11 +168,13 @@ fn boot<'a>(
             false,
         )?;
 
-        fsp.boot_fmc(dev, fb_layout, &args)?;
+        // Keep the result as we want to wait for lockdown release even in case of error, to make
+        // sure `args` is not accessed by the GSP anymore.
+        let res = fsp.boot_fmc(dev, fb_layout, &args);
 
         wait_for_gsp_lockdown_release(dev, gsp_falcon, args.boot_params_dma_handle())?;
 
-        Ok(unload_guard)
+        res.map(|()| Some(unload_bundle))
     }
 }
 
drivers/gpu/nova-core/gsp/hal/tu102.rs +13 -10
index 87ceb8878f01..f78e2489f5a6 100644
@@ -6,7 +6,8 @@
 use kernel::{
     device,
     dma::Coherent,
-    io::Io, //
+    io::Io,
+    types::ScopeGuard, //
 };
 
 use crate::{
@@ -32,7 +33,6 @@
     },
     gpu::Chipset,
     gsp::{
-        boot::BootUnloadGuard,
         hal::{
             GspHal,
             UnloadBundle, //
@@ -259,13 +259,13 @@ fn run_fwsec_frts(
 struct Tu102;
 
 impl GspHal for Tu102 {
-    fn boot<'a>(
+    fn boot(
         &self,
-        gsp: &'a Gsp,
-        ctx: &GspBootContext<'a>,
+        gsp: &Gsp,
+        ctx: &GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
-    ) -> Result<BootUnloadGuard<'a>> {
+    ) -> Result<Option<crate::gsp::UnloadBundle>> {
         let dev = ctx.dev();
         let bar = ctx.bar;
         let chipset = ctx.chipset;
@@ -290,9 +290,12 @@ fn boot<'a>(
             .ok()
             .map(crate::gsp::UnloadBundle);
 
-        // Wrap the unload bundle into a drop guard so it is automatically run upon failure.
-        let unload_guard =
-            BootUnloadGuard::new(gsp, dev, bar, gsp_falcon, sec2_falcon, unload_bundle);
+        // Run the unload bundle to try and recover the GSP if an error occurs.
+        let unload_guard = ScopeGuard::new_with_data(unload_bundle, |unload_bundle| {
+            if let Some(unload_bundle) = unload_bundle {
+                let _ = unload_bundle.0.run(dev, bar, gsp_falcon, sec2_falcon);
+            }
+        });
 
         // FWSEC-FRTS is not executed on chips where the FRTS region size is 0 (e.g. GA100).
         if !fb_layout.frts.is_empty() {
@@ -319,7 +322,7 @@ fn boot<'a>(
         )?
         .run(dev, sec2_falcon, wpr_meta)?;
 
-        Ok(unload_guard)
+        Ok(unload_guard.dismiss())
     }
 
     fn post_boot(&self, gsp: &Gsp, ctx: &GspBootContext<'_>, gsp_fw: &GspFirmware) -> Result {
Signature · 1 line
2.54.0
#6 lore raw

Re: [PATCH v4 03/13] gpu: nova-core: gsp: replace BootUnloadGuard with local handlers

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The root cause error from `fsp.boot_fmc` is masked by a subsequent timeout error from…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The root cause error from fsp.boot_fmc is masked by a subsequent timeout error from wait_for_gsp_lockdown_release. --

commit 24f94e0b36617b6956b3b5c28c4a63019c91588f
Author: Alexandre Courbot <[email protected]>

gpu: nova-core: gsp: replace BootUnloadGuard with local handlers

This commit removes the BootUnloadGuard abstraction, replacing it with a two-level error handling strategy. HALs handle their own errors and Gsp::boot uses a ScopeGuard to run Gsp::unload.

Quoted 3 lines
drivers/gpu/nova-core/gsp/hal/gh100.rs +0 -0

[ ... ]

drivers/gpu/nova-core/gsp/hal/gh100.rs fn boot<'a>( · line 175

Quoted 10 lines
drivers/gpu/nova-core/gsp/hal/gh100.rs +3 -1
@@ -174,11 +168,13 @@ fn boot<'a>(
             false,
         )?;
 
-        fsp.boot_fmc(dev, fb_layout, &args)?;
+        // Keep the result as we want to wait for lockdown release even in case of error, to make
+        // sure args is not accessed by the GSP anymore.
+        let res = fsp.boot_fmc(dev, fb_layout, &args);
 
         wait_for_gsp_lockdown_release(dev, gsp_falcon, args.boot_params_dma_handle())?;

[Severity: Medium]
Will this mask the original error if fsp.boot_fmc() fails?

If fsp.boot_fmc() fails, its error is stored in res. The function then calls wait_for_gsp_lockdown_release() to ensure the boot arguments are no longer accessed. Because the FSP boot failed, the lockdown release polling will inevitably time out. The ? operator on wait_for_gsp_lockdown_release() will propagate this timeout error immediately, causing the function to return early and silently discard the original root cause error held in res.

Quoted 5 lines
drivers/gpu/nova-core/gsp/hal/gh100.rs +1 -1
-        Ok(unload_guard)
+        res.map(|()| Some(unload_bundle))
     }
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#7 lore raw

Re: [PATCH v4 03/13] gpu: nova-core: gsp: replace BootUnloadGuard with local handlers

In reply to Alexandre Courbot
Quoted 204 lines · Alexandre Courbot

When adding the GSP unload capability, we introduced BootUnloadGuard to automatically call Gsp::unload whenever an error occurred during the boot process, in order to try to reset the GSP to a valid state.

This approach is not well-suited to the errors that may occur in HALs:
by definition, an error occurring in the HAL means that the GSP is not booted; yet the first thing that Gsp::unload does is queue a shutdown message to the GSP, which will inevitably result in a timeout when done from a HAL.

Furthermore, BootUnloadGuard is problematic because it holds additional references to the boot context, notably the Falcons. These extra references stand in the way of making some of the Falcon's methods mutable, since those methods would require exclusive access. As this behavior is only needed in one place, introducing dedicated types for it is distracting and unnecessary.

Thus, remove BootUnloadGuard and adopt a two-level error handling strategy:

- HALs are free to handle their errors as they see fit (most likely, by running their unload bundle if it is ready by the time of the error),
- Gsp::boot uses a ScopeGuard that runs Gsp::unload, since the GSP should be up and running by the time GspHal::boot has returned.

---
 drivers/gpu/nova-core/gsp/boot.rs      | 67 +++-------------------------------
 drivers/gpu/nova-core/gsp/hal.rs       | 13 +++----
 drivers/gpu/nova-core/gsp/hal/gh100.rs | 20 ++++------
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 23 +++++++-----
 4 files changed, 33 insertions(+), 90 deletions(-)
drivers/gpu/nova-core/gsp/boot.rs +6 -61
index ab0491b57944..536f2e341c01 100644
@@ -30,66 +30,6 @@
     },
 };
 
-/// Arguments required to call [`Gsp::unload`](super::Gsp::unload).
-///
-/// Stored as their own type to avoid repeating a long and tedious list in [`BootUnloadGuard`].
-pub(super) struct BootUnloadArgs<'a> {
-    gsp: &'a super::Gsp,
-    dev: &'a device::Device<device::Bound>,
-    bar: Bar0<'a>,
-    gsp_falcon: &'a Falcon<'a, Gsp>,
-    sec2_falcon: &'a Falcon<'a, Sec2>,
-    unload_bundle: Option<super::UnloadBundle>,
-}
-
-/// Guard that calls [`Gsp::unload`](super::Gsp::unload) with a
-/// [`UnloadBundle`](super::UnloadBundle) when dropped.
-///
-/// Used to ensure the `UnloadBundle` is run during failure paths.
-pub(super) struct BootUnloadGuard<'a> {
-    guard: ScopeGuard<BootUnloadArgs<'a>, fn(BootUnloadArgs<'a>)>,
-}
-
-impl<'a> BootUnloadGuard<'a> {
-    /// Wraps `unload_bundle` into a guard that executes it when dropped.
-    pub(super) fn new(
-        gsp: &'a super::Gsp,
-        dev: &'a device::Device<device::Bound>,
-        bar: Bar0<'a>,
-        gsp_falcon: &'a Falcon<'a, Gsp>,
-        sec2_falcon: &'a Falcon<'a, Sec2>,
-        unload_bundle: Option<super::UnloadBundle>,
-    ) -> Self {
-        Self {
-            guard: ScopeGuard::new_with_data(
-                BootUnloadArgs {
-                    gsp,
-                    dev,
-                    bar,
-                    gsp_falcon,
-                    sec2_falcon,
-                    unload_bundle,
-                },
-                |args| {
-                    let _ = super::Gsp::unload(
-                        args.gsp,
-                        args.dev,
-                        args.bar,
-                        args.gsp_falcon,
-                        args.sec2_falcon,
-                        args.unload_bundle,
-                    );
-                },
-            ),
-        }
-    }
-
-    /// Disarms the guard and returns the [`UnloadBundle`](super::UnloadBundle) it contains.
-    pub(super) fn dismiss(self) -> Option<super::UnloadBundle> {
-        self.guard.dismiss().unload_bundle
-    }
-}
-
 impl super::Gsp {
     /// Attempt to boot the GSP.
     ///
@@ -107,6 +47,7 @@ pub(crate) fn boot(
         let bar = ctx.bar;
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
+        let sec2_falcon = ctx.sec2_falcon;
         let dev = pdev.as_ref();
         let hal = super::hal::gsp_hal(chipset);
 
@@ -118,7 +59,11 @@ pub(crate) fn boot(
         let wpr_meta = Coherent::init(dev, GFP_KERNEL, GspFwWprMeta::new(&gsp_fw, &fb_layout))?;
 
         // Perform the chipset-specific boot sequence, and retrieve the unload bundle.
-        let unload_guard = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?;
+        let unload_bundle = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?;
+
+        let unload_guard = ScopeGuard::new_with_data(unload_bundle, |unload_bundle| {
+            let _ = self.unload(dev, bar, gsp_falcon, sec2_falcon, unload_bundle);
+        });
 
         gsp_falcon.write_os_version(gsp_fw.bootloader.app_version);
 
drivers/gpu/nova-core/gsp/hal.rs +6 -7
index d3e47ef206de..851d1f24c137 100644
@@ -24,7 +24,6 @@
         Chipset, //
     },
     gsp::{
-        boot::BootUnloadGuard,
         Gsp,
         GspBootContext,
         GspFwWprMeta, //
@@ -51,15 +50,15 @@ fn run(
 pub(super) trait GspHal: Send {
     /// Performs the GSP boot process, loading and running the required firmwares as needed.
     ///
-    /// Upon success, returns a guard that runs the GSP unload sequence if GSP boot does not
-    /// complete.
-    fn boot<'a>(
+    /// Upon success, returns the [`crate::gsp::UnloadBundle`] to use with [`Gsp::unload`], if one
+    /// could be created.
+    fn boot(
         &self,
-        gsp: &'a Gsp,
-        ctx: &GspBootContext<'a>,
+        gsp: &Gsp,
+        ctx: &GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
-    ) -> Result<BootUnloadGuard<'a>>;
+    ) -> Result<Option<crate::gsp::UnloadBundle>>;
 
     /// Performs HAL-specific post-GSP boot tasks.
     ///
drivers/gpu/nova-core/gsp/hal/gh100.rs +4 -10
index 1d06405a32f6..5fe445d73599 100644
@@ -23,7 +23,6 @@
         Fsp, //
     },
     gsp::{
-        boot::BootUnloadGuard,
         hal::{
             GspHal,
             UnloadBundle, //
@@ -143,27 +142,22 @@ impl GspHal for Gh100 {
     ///
     /// This path uses FSP to establish a chain of trust and boot GSP-FMC. FSP handles
     /// the GSP boot internally - no manual GSP reset/boot is needed.
-    fn boot<'a>(
+    fn boot(
         &self,
-        gsp: &'a Gsp,
-        ctx: &GspBootContext<'a>,
+        gsp: &Gsp,
+        ctx: &GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
-    ) -> Result<BootUnloadGuard<'a>> {
+    ) -> Result<Option<crate::gsp::UnloadBundle>> {
         let dev = ctx.dev();
         let bar = ctx.bar;
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
-        let sec2_falcon = ctx.sec2_falcon;
 
         let unload_bundle = crate::gsp::UnloadBundle(
             KBox::new(FspUnloadBundle, GFP_KERNEL)? as KBox<dyn UnloadBundle>
         );
 
-        // Wrap the unload bundle into a drop guard so it is automatically run upon failure.
-        let unload_guard =
-            BootUnloadGuard::new(gsp, dev, bar, gsp_falcon, sec2_falcon, Some(unload_bundle));
-
         let mut fsp = Fsp::wait_secure_boot(dev, bar, chipset)?;
 
         let args = FmcBootArgs::new(

drivers/gpu/nova-core/gsp/hal/gh100.rs fn boot<'a>( · line 173

Quoted 7 lines
drivers/gpu/nova-core/gsp/hal/gh100.rs +3 -1
@@ -174,11 +168,13 @@ fn boot<'a>(
             false,
         )?;
 
-        fsp.boot_fmc(dev, fb_layout, &args)?;
+        // Keep the result as we want to wait for lockdown release even in case of error, to make
+        // sure `args` is not accessed by the GSP anymore.
+        let res = fsp.boot_fmc(dev, fb_layout, &args);

In the error case this no longer runs the unload bundle (which waits for GSP halt). But, we need to wait for GSP halt to ensure stuff is properly torn down (e.g. in [1], not needing to wait on FSP queue is predicated on GSP riscv actually halting, to avoid an issue on reprobe, IIUC).

Separately, are you sure that GSP lockdown will release in an error case? I'm worried that we'll just timeout here, which while it probably works in that it waits long enough, is semantically a bit weird.

What about using a ScopeGuard that runs the unload_bundle? That way we will have waited for GSP halt. Later, we could add additional HAL specific common code for trying to reset GSP in case it doesn't halt. WDYT?

[1]: https://lore.kernel.org/all/[email protected]/

Quoted 58 lines
drivers/gpu/nova-core/gsp/hal/gh100.rs +0 -1
         wait_for_gsp_lockdown_release(dev, gsp_falcon,
         args.boot_params_dma_handle())?;
 
-        Ok(unload_guard) +        res.map(|()| Some(unload_bundle)) }
 }
 
(quoted diff) +0 -0

b/drivers/gpu/nova-core/gsp/hal/tu102.rs index 87ceb8878f01..f78e2489f5a6 100644 --- a/drivers/gpu/nova-core/gsp/hal/tu102.rs +++ b/drivers/gpu/nova-core/gsp/hal/tu102.rs @@ -6,7 +6,8 @@ use kernel::{
device, dma::Coherent, - io::Io, // + io::Io, +
types::ScopeGuard, // };

use crate::{ @@ -32,7 +33,6 @@ }, gpu::Chipset, gsp::{ - boot::BootUnloadGuard, hal::{ GspHal, UnloadBundle, // @@ -259,13 +259,13 @@ fn run_fwsec_frts( struct Tu102;

impl GspHal for Tu102 { - fn boot<'a>(

drivers/gpu/nova-core/gsp/hal/gh100.rs +11 -7
+    fn boot(
         &self,
-        gsp: &'a Gsp,
-        ctx: &GspBootContext<'a>,
+        gsp: &Gsp,
+        ctx: &GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
-    ) -> Result<BootUnloadGuard<'a>> {
+    ) -> Result<Option<crate::gsp::UnloadBundle>> {
         let dev = ctx.dev();
         let bar = ctx.bar;
         let chipset = ctx.chipset;
@@ -290,9 +290,12 @@ fn boot<'a>(
             .ok()
             .map(crate::gsp::UnloadBundle);
 
-        // Wrap the unload bundle into a drop guard so it is automatically run upon failure.
-        let unload_guard =
-            BootUnloadGuard::new(gsp, dev, bar, gsp_falcon, sec2_falcon, unload_bundle);
+        // Run the unload bundle to try and recover the GSP if an error occurs.
+        let unload_guard = ScopeGuard::new_with_data(unload_bundle, |unload_bundle| {
+            if let Some(unload_bundle) = unload_bundle {
+                let _ = unload_bundle.0.run(dev, bar, gsp_falcon, sec2_falcon);
+            }
+        });
 
         // FWSEC-FRTS is not executed on chips where the FRTS region size is 0 (e.g. GA100).
         if !fb_layout.frts.is_empty() {
@@ -319,7 +322,7 @@ fn boot<'a>(
         )?
         .run(dev, sec2_falcon, wpr_meta)?;
 
-        Ok(unload_guard)
+        Ok(unload_guard.dismiss())
     }
 
     fn post_boot(&self, gsp: &Gsp, ctx: &GspBootContext<'_>, gsp_fw: &GspFirmware) -> Result {
author maintainer
#8 lore raw

Re: [PATCH v4 03/13] gpu: nova-core: gsp: replace BootUnloadGuard with local handlers

Quoted 222 lines · Eliot Courtney
Quoted 204 lines · Alexandre Courbot

When adding the GSP unload capability, we introduced BootUnloadGuard to automatically call Gsp::unload whenever an error occurred during the boot process, in order to try to reset the GSP to a valid state.

This approach is not well-suited to the errors that may occur in HALs:
by definition, an error occurring in the HAL means that the GSP is not booted; yet the first thing that Gsp::unload does is queue a shutdown message to the GSP, which will inevitably result in a timeout when done from a HAL.

Furthermore, BootUnloadGuard is problematic because it holds additional references to the boot context, notably the Falcons. These extra references stand in the way of making some of the Falcon's methods mutable, since those methods would require exclusive access. As this behavior is only needed in one place, introducing dedicated types for it is distracting and unnecessary.

Thus, remove BootUnloadGuard and adopt a two-level error handling strategy:

- HALs are free to handle their errors as they see fit (most likely, by running their unload bundle if it is ready by the time of the error),
- Gsp::boot uses a ScopeGuard that runs Gsp::unload, since the GSP should be up and running by the time GspHal::boot has returned.

---
 drivers/gpu/nova-core/gsp/boot.rs      | 67 +++-------------------------------
 drivers/gpu/nova-core/gsp/hal.rs       | 13 +++----
 drivers/gpu/nova-core/gsp/hal/gh100.rs | 20 ++++------
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 23 +++++++-----
 4 files changed, 33 insertions(+), 90 deletions(-)
drivers/gpu/nova-core/gsp/boot.rs +6 -61
index ab0491b57944..536f2e341c01 100644
@@ -30,66 +30,6 @@
     },
 };
 
-/// Arguments required to call [`Gsp::unload`](super::Gsp::unload).
-///
-/// Stored as their own type to avoid repeating a long and tedious list in [`BootUnloadGuard`].
-pub(super) struct BootUnloadArgs<'a> {
-    gsp: &'a super::Gsp,
-    dev: &'a device::Device<device::Bound>,
-    bar: Bar0<'a>,
-    gsp_falcon: &'a Falcon<'a, Gsp>,
-    sec2_falcon: &'a Falcon<'a, Sec2>,
-    unload_bundle: Option<super::UnloadBundle>,
-}
-
-/// Guard that calls [`Gsp::unload`](super::Gsp::unload) with a
-/// [`UnloadBundle`](super::UnloadBundle) when dropped.
-///
-/// Used to ensure the `UnloadBundle` is run during failure paths.
-pub(super) struct BootUnloadGuard<'a> {
-    guard: ScopeGuard<BootUnloadArgs<'a>, fn(BootUnloadArgs<'a>)>,
-}
-
-impl<'a> BootUnloadGuard<'a> {
-    /// Wraps `unload_bundle` into a guard that executes it when dropped.
-    pub(super) fn new(
-        gsp: &'a super::Gsp,
-        dev: &'a device::Device<device::Bound>,
-        bar: Bar0<'a>,
-        gsp_falcon: &'a Falcon<'a, Gsp>,
-        sec2_falcon: &'a Falcon<'a, Sec2>,
-        unload_bundle: Option<super::UnloadBundle>,
-    ) -> Self {
-        Self {
-            guard: ScopeGuard::new_with_data(
-                BootUnloadArgs {
-                    gsp,
-                    dev,
-                    bar,
-                    gsp_falcon,
-                    sec2_falcon,
-                    unload_bundle,
-                },
-                |args| {
-                    let _ = super::Gsp::unload(
-                        args.gsp,
-                        args.dev,
-                        args.bar,
-                        args.gsp_falcon,
-                        args.sec2_falcon,
-                        args.unload_bundle,
-                    );
-                },
-            ),
-        }
-    }
-
-    /// Disarms the guard and returns the [`UnloadBundle`](super::UnloadBundle) it contains.
-    pub(super) fn dismiss(self) -> Option<super::UnloadBundle> {
-        self.guard.dismiss().unload_bundle
-    }
-}
-
 impl super::Gsp {
     /// Attempt to boot the GSP.
     ///
@@ -107,6 +47,7 @@ pub(crate) fn boot(
         let bar = ctx.bar;
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
+        let sec2_falcon = ctx.sec2_falcon;
         let dev = pdev.as_ref();
         let hal = super::hal::gsp_hal(chipset);
 
@@ -118,7 +59,11 @@ pub(crate) fn boot(
         let wpr_meta = Coherent::init(dev, GFP_KERNEL, GspFwWprMeta::new(&gsp_fw, &fb_layout))?;
 
         // Perform the chipset-specific boot sequence, and retrieve the unload bundle.
-        let unload_guard = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?;
+        let unload_bundle = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?;
+
+        let unload_guard = ScopeGuard::new_with_data(unload_bundle, |unload_bundle| {
+            let _ = self.unload(dev, bar, gsp_falcon, sec2_falcon, unload_bundle);
+        });
 
         gsp_falcon.write_os_version(gsp_fw.bootloader.app_version);
 
drivers/gpu/nova-core/gsp/hal.rs +6 -7
index d3e47ef206de..851d1f24c137 100644
@@ -24,7 +24,6 @@
         Chipset, //
     },
     gsp::{
-        boot::BootUnloadGuard,
         Gsp,
         GspBootContext,
         GspFwWprMeta, //
@@ -51,15 +50,15 @@ fn run(
 pub(super) trait GspHal: Send {
     /// Performs the GSP boot process, loading and running the required firmwares as needed.
     ///
-    /// Upon success, returns a guard that runs the GSP unload sequence if GSP boot does not
-    /// complete.
-    fn boot<'a>(
+    /// Upon success, returns the [`crate::gsp::UnloadBundle`] to use with [`Gsp::unload`], if one
+    /// could be created.
+    fn boot(
         &self,
-        gsp: &'a Gsp,
-        ctx: &GspBootContext<'a>,
+        gsp: &Gsp,
+        ctx: &GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
-    ) -> Result<BootUnloadGuard<'a>>;
+    ) -> Result<Option<crate::gsp::UnloadBundle>>;
 
     /// Performs HAL-specific post-GSP boot tasks.
     ///
drivers/gpu/nova-core/gsp/hal/gh100.rs +4 -10
index 1d06405a32f6..5fe445d73599 100644
@@ -23,7 +23,6 @@
         Fsp, //
     },
     gsp::{
-        boot::BootUnloadGuard,
         hal::{
             GspHal,
             UnloadBundle, //
@@ -143,27 +142,22 @@ impl GspHal for Gh100 {
     ///
     /// This path uses FSP to establish a chain of trust and boot GSP-FMC. FSP handles
     /// the GSP boot internally - no manual GSP reset/boot is needed.
-    fn boot<'a>(
+    fn boot(
         &self,
-        gsp: &'a Gsp,
-        ctx: &GspBootContext<'a>,
+        gsp: &Gsp,
+        ctx: &GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
-    ) -> Result<BootUnloadGuard<'a>> {
+    ) -> Result<Option<crate::gsp::UnloadBundle>> {
         let dev = ctx.dev();
         let bar = ctx.bar;
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
-        let sec2_falcon = ctx.sec2_falcon;
 
         let unload_bundle = crate::gsp::UnloadBundle(
             KBox::new(FspUnloadBundle, GFP_KERNEL)? as KBox<dyn UnloadBundle>
         );
 
-        // Wrap the unload bundle into a drop guard so it is automatically run upon failure.
-        let unload_guard =
-            BootUnloadGuard::new(gsp, dev, bar, gsp_falcon, sec2_falcon, Some(unload_bundle));
-
         let mut fsp = Fsp::wait_secure_boot(dev, bar, chipset)?;
 
         let args = FmcBootArgs::new(

drivers/gpu/nova-core/gsp/hal/gh100.rs fn boot<'a>( · line 173

Quoted 7 lines
drivers/gpu/nova-core/gsp/hal/gh100.rs +3 -1
@@ -174,11 +168,13 @@ fn boot<'a>(
             false,
         )?;
 
-        fsp.boot_fmc(dev, fb_layout, &args)?;
+        // Keep the result as we want to wait for lockdown release even in case of error, to make
+        // sure `args` is not accessed by the GSP anymore.
+        let res = fsp.boot_fmc(dev, fb_layout, &args);

In the error case this no longer runs the unload bundle (which waits for GSP halt). But, we need to wait for GSP halt to ensure stuff is properly torn down (e.g. in [1], not needing to wait on FSP queue is predicated on GSP riscv actually halting, to avoid an issue on reprobe, IIUC).

Separately, are you sure that GSP lockdown will release in an error case? I'm worried that we'll just timeout here, which while it probably works in that it waits long enough, is semantically a bit weird.

Quoted 6 lines

What about using a ScopeGuard that runs the unload_bundle? That way we will have waited for GSP halt. Later, we could add additional HAL specific common code for trying to reset GSP in case it doesn't halt. WDYT?

[1]: https://lore.kernel.org/all/[email protected]/

The problem is that we don't know that either procedure (wait for GSP halt vs. wait for GSP lockdown release) are correct in the error case. I settled for GSP lockdown because GSP halt is typically triggered by the shutdown message being received and acknowledged - but if we fail here, the GSP is by definition unable to process that message.

I've noticed only now that wait_for_gsp_lockdown_release actually returns when either the lockdown is released, OR an error has been signaled by GSP-FMC (see lockdown_released_or_error). So, we can be confident that unless something has crashed catastrophically this should not timeout, and also give us the bound after which the FmcBootArgs is not accessed anymore.

By then, we can also probably expect the GSP to halt cleanly; so we might indeed wait for the RISC-V core to halt - not to avoid a use-after-free of FmcBootArgs (it's clearly unused by then), but as a general indicator that the GPU can be reprobed.

So I guess the answer is, we should try and do both? Something like this maybe:

    let fsp_res = fsp.boot_fmc(dev, fb_layout, &args);

    // Wait for GSP-FMC to release the GSP lockdown, indicating that `args` is not accessed anymore.
    let lockdown_res =
        wait_for_gsp_lockdown_release(dev, gsp_falcon, args.boot_params_dma_handle());

    match fsp_res.and(lockdown_res) {
        Ok(()) => Ok(Some(unload_bundle)),
        Err(e) => {
            // Wait for the GSP RISC-V core to halt in case of error.
            let _ = unload_bundle.0.run(ctx);
            Err(e)
        }
    }
author maintainer
#9 lore raw

PATCH v4 4/13 gpu: nova-core: gsp: pass GspBootContext to unload methods

In reply to Alexandre Courbot

GspBootContext contains the resources required to boot the GSP. As it turns out, this is also the context required for unloading it.

Reflect that fact by replacing the arguments of Gsp::unload and UnloadBundle::run with the GspBootContext. This symmetry between Gsp::boot and Gsp::unload will also be convenient when we want to make these methods generic over the boot context corresponding to the boot method used.

---
 drivers/gpu/nova-core/gpu.rs           | 19 ++++++++++++++++---
 drivers/gpu/nova-core/gsp/boot.rs      | 28 +++++++++++++---------------
 drivers/gpu/nova-core/gsp/hal.rs       | 15 +--------------
 drivers/gpu/nova-core/gsp/hal/gh100.rs | 14 +++-----------
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 23 +++++++++++------------
 5 files changed, 44 insertions(+), 55 deletions(-)
drivers/gpu/nova-core/gpu.rs +16 -3
index 43c3f4f8df71..32bfa0be2357 100644
@@ -269,7 +269,9 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 #[pin_data(PinnedDrop)]
 struct GspResources<'gpu> {
     /// Device owning the GPU.
-    device: &'gpu device::Device<device::Bound>,
+    device: &'gpu pci::Device<device::Bound>,
+    /// Details about the chipset.
+    spec: Spec,
     /// MMIO mapping of PCI BAR 0.
     bar: Bar0<'gpu>,
     /// GSP falcon instance, used for GSP boot up and cleanup.
@@ -312,7 +314,16 @@ fn drop(self: Pin<&mut Self>) {
             .gsp
             .as_ref()
             .get_ref()
-            .unload(device, bar, &*this.gsp_falcon, &*this.sec2_falcon, bundle)
+            .unload(
+                GspBootContext {
+                    pdev: device,
+                    bar,
+                    chipset: this.spec.chipset,
+                    gsp_falcon: &*this.gsp_falcon,
+                    sec2_falcon: &*this.sec2_falcon,
+                },
+                bundle,
+            )
             .inspect_err(|e| dev_err!(device, "failed to unload GSP: {:?}\n", e));
     }
 }
@@ -344,7 +355,9 @@ pub(crate) fn new(
             sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.chipset)?,
 
             gsp_resources <- try_pin_init!(GspResources {
-                device: pdev.as_ref(),
+                device: pdev,
+
+                spec: *spec,
 
                 bar,
 
drivers/gpu/nova-core/gsp/boot.rs +13 -15
index 536f2e341c01..75054424a951 100644
@@ -3,7 +3,6 @@
 
 use kernel::{
     bits,
-    device,
     dma::Coherent,
     io::poll::read_poll_timeout,
     prelude::*,
@@ -15,7 +14,6 @@
     driver::Bar0,
     falcon::{
         gsp::Gsp,
-        sec2::Sec2,
         Falcon, //
     },
     fb::FbLayout,
@@ -47,7 +45,6 @@ pub(crate) fn boot(
         let bar = ctx.bar;
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
-        let sec2_falcon = ctx.sec2_falcon;
         let dev = pdev.as_ref();
         let hal = super::hal::gsp_hal(chipset);
 
@@ -61,9 +58,11 @@ pub(crate) fn boot(
         // Perform the chipset-specific boot sequence, and retrieve the unload bundle.
         let unload_bundle = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?;
 
-        let unload_guard = ScopeGuard::new_with_data(unload_bundle, |unload_bundle| {
-            let _ = self.unload(dev, bar, gsp_falcon, sec2_falcon, unload_bundle);
-        });
+        let unload_guard =
+            ScopeGuard::new_with_data((ctx, unload_bundle), |(ctx, unload_bundle)| {
+                let _ = self.unload(ctx, unload_bundle);
+            });
+        let ctx = &unload_guard.0;
 
         gsp_falcon.write_os_version(gsp_fw.bootloader.app_version);
 
@@ -82,12 +81,12 @@ pub(crate) fn boot(
         self.cmdq
             .send_command_no_wait(bar, commands::SetRegistry::new())?;
 
-        hal.post_boot(&self, &ctx, &gsp_fw)?;
+        hal.post_boot(&self, ctx, &gsp_fw)?;
 
         // Wait until GSP is fully initialized.
         commands::wait_gsp_init_done(&self.cmdq)?;
 
-        Ok(unload_guard.dismiss())
+        Ok(unload_guard.dismiss().1)
     }
 
     /// Shut down the GSP and wait until it is offline.
@@ -116,17 +115,16 @@ fn shutdown_gsp(
     /// This stops all activity on the GSP.
     pub(crate) fn unload(
         &self,
-        dev: &device::Device<device::Bound>,
-        bar: Bar0<'_>,
-        gsp_falcon: &Falcon<'_, Gsp>,
-        sec2_falcon: &Falcon<'_, Sec2>,
+        ctx: super::GspBootContext<'_>,
         unload_bundle: Option<super::UnloadBundle>,
     ) -> Result {
+        let dev = ctx.dev();
+
         // Shut down the GSP. Keep going even in case of error.
         let mut res = Self::shutdown_gsp(
             &self.cmdq,
-            bar,
-            gsp_falcon,
+            ctx.bar,
+            ctx.gsp_falcon,
             commands::PowerStateLevel::Level0,
         )
         .inspect_err(|e| dev_err!(dev, "GSP shutdown failed: {:?}\n", e));
@@ -136,7 +134,7 @@ pub(crate) fn unload(
             res = res.and(
                 unload_bundle
                     .0
-                    .run(dev, bar, gsp_falcon, sec2_falcon)
+                    .run(&ctx)
                     .inspect_err(|e| dev_err!(dev, "Unload bundle failed: {:?}\n", e)),
             );
         } else {
drivers/gpu/nova-core/gsp/hal.rs +1 -14
index 851d1f24c137..849ca224085b 100644
@@ -5,18 +5,11 @@
 mod tu102;
 
 use kernel::{
-    device,
     dma::Coherent,
     prelude::*, //
 };
 
 use crate::{
-    driver::Bar0,
-    falcon::{
-        gsp::Gsp as GspEngine,
-        sec2::Sec2,
-        Falcon, //
-    },
     fb::FbLayout,
     firmware::gsp::GspFirmware,
     gpu::{
@@ -37,13 +30,7 @@
 /// required for unloading is prepared at load time, and stored here until it needs to be run.
 pub(super) trait UnloadBundle: Send {
     /// Performs the steps required to properly reset the GSP after it has been stopped.
-    fn run(
-        &self,
-        dev: &device::Device<device::Bound>,
-        bar: Bar0<'_>,
-        gsp_falcon: &Falcon<'_, GspEngine>,
-        sec2_falcon: &Falcon<'_, Sec2>,
-    ) -> Result;
+    fn run(&self, ctx: &GspBootContext<'_>) -> Result;
 }
 
 /// Trait implemented by GSP HALs.
drivers/gpu/nova-core/gsp/hal/gh100.rs +3 -11
index 5fe445d73599..411b06c22fa0 100644
@@ -11,10 +11,8 @@
 };
 
 use crate::{
-    driver::Bar0,
     falcon::{
         gsp::Gsp as GspEngine,
-        sec2::Sec2,
         Falcon, //
     },
     fb::FbLayout,
@@ -116,22 +114,16 @@ fn wait_for_gsp_lockdown_release(
 struct FspUnloadBundle;
 
 impl UnloadBundle for FspUnloadBundle {
-    fn run(
-        &self,
-        dev: &device::Device<device::Bound>,
-        _bar: Bar0<'_>,
-        gsp_falcon: &Falcon<'_, GspEngine>,
-        _sec2_falcon: &Falcon<'_, Sec2>,
-    ) -> Result {
+    fn run(&self, ctx: &GspBootContext<'_>) -> Result {
         // GSP falcon does most of the work of resetting, so just wait for it to finish.
         read_poll_timeout(
-            || Ok(gsp_falcon.is_riscv_active()),
+            || Ok(ctx.gsp_falcon.is_riscv_active()),
             |&active| !active,
             Delta::from_millis(10),
             Delta::from_secs(5),
         )
         .map(|_| ())
-        .inspect_err(|_| dev_err!(dev, "GSP falcon failed to halt\n"))
+        .inspect_err(|_| dev_err!(ctx.dev(), "GSP falcon failed to halt\n"))
     }
 }
 
drivers/gpu/nova-core/gsp/hal/tu102.rs +11 -12
index f78e2489f5a6..c0956fb1c9cf 100644
@@ -121,18 +121,15 @@ fn build(
 }
 
 impl UnloadBundle for Sec2UnloadBundle {
-    fn run(
-        &self,
-        dev: &device::Device<device::Bound>,
-        bar: Bar0<'_>,
-        gsp_falcon: &Falcon<'_, GspEngine>,
-        sec2_falcon: &Falcon<'_, Sec2>,
-    ) -> Result {
+    fn run(&self, ctx: &GspBootContext<'_>) -> Result {
+        let dev = ctx.dev();
+        let bar = ctx.bar;
+
         // Run FWSEC-SB to reset the GSP falcon to its pre-libos state.
         // Log errors but keep going if it fails.
         let fwsec_sb_res = self
             .fwsec_sb
-            .run(dev, bar, gsp_falcon)
+            .run(dev, bar, ctx.gsp_falcon)
             .inspect_err(|e| dev_err!(dev, "FWSEC-SB failed to run: {:?}\n", e));
 
         // Remove WPR2 region if set.
@@ -142,12 +139,14 @@ fn run(
                 return Ok(());
             }
 
-            sec2_falcon.reset()?;
-            sec2_falcon.load(&self.booter_unloader)?;
+            ctx.sec2_falcon.reset()?;
+            ctx.sec2_falcon.load(&self.booter_unloader)?;
 
             // Sentinel value to confirm that Booter Unloader has run.
             const MAILBOX_SENTINEL: u32 = 0xff;
-            let (mbox0, _) = sec2_falcon.boot(Some(MAILBOX_SENTINEL), Some(MAILBOX_SENTINEL))?;
+            let (mbox0, _) = ctx
+                .sec2_falcon
+                .boot(Some(MAILBOX_SENTINEL), Some(MAILBOX_SENTINEL))?;
             if mbox0 != 0 {
                 dev_err!(dev, "Booter Unloader returned error 0x{:x}\n", mbox0);
                 return Err(EINVAL);
@@ -293,7 +292,7 @@ fn boot(
         // Run the unload bundle to try and recover the GSP if an error occurs.
         let unload_guard = ScopeGuard::new_with_data(unload_bundle, |unload_bundle| {
             if let Some(unload_bundle) = unload_bundle {
-                let _ = unload_bundle.0.run(dev, bar, gsp_falcon, sec2_falcon);
+                let _ = unload_bundle.0.run(ctx);
             }
         });
 
Signature · 1 line
2.54.0
Reviewed-by on v4 4/13
#10 lore raw

Re: [PATCH v4 04/13] gpu: nova-core: gsp: pass GspBootContext to unload methods

Quoted 11 lines · Alexandre Courbot

GspBootContext contains the resources required to boot the GSP. As it turns out, this is also the context required for unloading it.

Reflect that fact by replacing the arguments of Gsp::unload and UnloadBundle::run with the GspBootContext. This symmetry between Gsp::boot and Gsp::unload will also be convenient when we want to make these methods generic over the boot context corresponding to the boot method used.

---

author maintainer
#11 lore raw

PATCH v4 5/13 gpu: nova-core: gsp: centralize missing unload bundle warnings

In reply to Alexandre Courbot

The warning emitted when the unload bundle cannot be constructed is valid regardless of the boot method, but it was local to Tu102. Move it to Gsp::boot so it applies to all boot methods.

---
 drivers/gpu/nova-core/gsp/boot.rs      | 10 +++++++++-
 drivers/gpu/nova-core/gsp/hal/tu102.rs |  9 +--------
 2 files changed, 10 insertions(+), 9 deletions(-)
drivers/gpu/nova-core/gsp/boot.rs +9 -1
index 75054424a951..430ffc57b136 100644
@@ -56,7 +56,15 @@ pub(crate) fn boot(
         let wpr_meta = Coherent::init(dev, GFP_KERNEL, GspFwWprMeta::new(&gsp_fw, &fb_layout))?;
 
         // Perform the chipset-specific boot sequence, and retrieve the unload bundle.
-        let unload_bundle = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?;
+        let unload_bundle = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?.or_else(|| {
+            dev_warn!(dev, "The GSP won't be able to unload properly on unbind.\n");
+            dev_warn!(
+                dev,
+                "The GPU will need to be reset before the driver can bind again.\n"
+            );
+
+            None
+        });
 
         let unload_guard =
             ScopeGuard::new_with_data((ctx, unload_bundle), |(ctx, unload_bundle)| {
drivers/gpu/nova-core/gsp/hal/tu102.rs +1 -8
index c0956fb1c9cf..ef465b99af05 100644
@@ -278,14 +278,7 @@ fn boot(
         // If the unload bundle creation fails, the GPU will need to be reset before the driver can
         // be probed again.
         let unload_bundle = Sec2UnloadBundle::build(dev, chipset, &bios, gsp_falcon, sec2_falcon)
-            .inspect_err(|e| {
-                dev_warn!(dev, "Failed to prepare unload firmware: {:?}\n", e);
-                dev_warn!(dev, "The GSP won't be able to unload properly on unbind.\n");
-                dev_warn!(
-                    dev,
-                    "The GPU will need to be reset before the driver can bind again.\n"
-                );
-            })
+            .inspect_err(|e| dev_warn!(dev, "Failed to prepare unload firmware: {:?}\n", e))
             .ok()
             .map(crate::gsp::UnloadBundle);
 
Signature · 1 line
2.54.0
#12 lore raw

Re: [PATCH v4 05/13] gpu: nova-core: gsp: centralize missing unload bundle warnings

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Moving the unload bundle warning to `Gsp::boot` using `hal.boot(...)?.or_else(...)` drops the…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Moving the unload bundle warning to Gsp::boot using hal.boot(...)?.or_else(...) drops the warning on error paths and is dead code for Gh100. --

commit 6422f17d0c05bd4c3b60d0655dea96518aadd1a5
Author: Alexandre Courbot <[email protected]>

gpu: nova-core: gsp: centralize missing unload bundle warnings

This commit moves the warning emitted when the unload bundle cannot be constructed from the Tu102-specific boot code to the generic Gsp::boot method so it applies to all boot methods.

drivers/gpu/nova-core/gsp/boot.rs pub(crate) fn boot( · line 59

Quoted 10 lines
drivers/gpu/nova-core/gsp/boot.rs +1 -1
index 75054424a9516..430ffc57b1366 100644
@@ -56,7 +56,15 @@ pub(crate) fn boot(
         let wpr_meta = Coherent::init(dev, GFP_KERNEL, GspFwWprMeta::new(&gsp_fw, &fb_layout))?;
 
         // Perform the chipset-specific boot sequence, and retrieve the unload bundle.
-        let unload_bundle = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?;
+        let unload_bundle = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?.or_else(|| {

[Severity: Medium]
Will this .or_else() block be skipped if hal.boot() returns an error due to the ? operator?

For example, if Gh100::boot() returns an Err directly when it fails to build its bundle (e.g., KBox::new failure) rather than returning Ok(None), it seems this block would be completely unreachable, contrary to the commit message's goal of applying it to all boot methods.

Likewise for Tu102, if Sec2UnloadBundle::build() fails and results in None, but a subsequent step in Tu102::boot() fails and returns an Err, the immediate error propagation would swallow these warnings.

Quoted 8 lines
drivers/gpu/nova-core/gsp/boot.rs +8 -0
+            dev_warn!(dev, "The GSP won't be able to unload properly on unbind.\n");
+            dev_warn!(
+                dev,
+                "The GPU will need to be reset before the driver can bind again.\n"
+            );
+
+            None
+        });
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Reviewed-by on v4 5/13
#13 lore raw

Re: [PATCH v4 05/13] gpu: nova-core: gsp: centralize missing unload bundle warnings

In reply to Alexandre Courbot
Quoted 6 lines · Alexandre Courbot

The warning emitted when the unload bundle cannot be constructed is valid regardless of the boot method, but it was local to Tu102. Move it to Gsp::boot so it applies to all boot methods.

---

author maintainer
#14 lore raw

PATCH v4 6/13 gpu: nova-core: gsp: fold TU102 unload bundle construction into HAL method

In reply to Alexandre Courbot

The construction of the unload bundle is currently a bit convoluted and could be done in one function instead of two.

Additionally, turn that function into a method of Tu102. A following patch will turn the "use FWSEC bootloader" property into a flag of the TU102 HAL itself, and making this a method will allow the code to access it instead of querying Chipset.

---
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 87 ++++++++++++++++------------------
 1 file changed, 41 insertions(+), 46 deletions(-)
drivers/gpu/nova-core/gsp/hal/tu102.rs +41 -46
index ef465b99af05..0505a5beee6e 100644
@@ -56,22 +56,6 @@ enum FwsecUnloadFirmware {
 }
 
 impl FwsecUnloadFirmware {
-    /// Loads the FWSEC SB firmware, as well as its bootloader if `chipset` requires it.
-    fn new(
-        dev: &device::Device<device::Bound>,
-        chipset: Chipset,
-        bios: &Vbios,
-        gsp_falcon: &Falcon<'_, GspEngine>,
-    ) -> Result<Self> {
-        let fwsec_sb = FwsecFirmware::new(dev, gsp_falcon, bios, FwsecCommand::Sb)?;
-
-        Ok(if chipset.needs_fwsec_bootloader() {
-            Self::WithBl(FwsecFirmwareWithBl::new(fwsec_sb, dev, chipset)?)
-        } else {
-            Self::WithoutBl(fwsec_sb)
-        })
-    }
-
     /// Runs the FWSEC SB firmware.
     fn run(
         &self,
@@ -93,33 +77,6 @@ struct Sec2UnloadBundle {
     booter_unloader: BooterFirmware,
 }
 
-impl Sec2UnloadBundle {
-    /// Load and prepare the resources required to properly reset the GSP after it has been stopped.
-    fn build(
-        dev: &device::Device<device::Bound>,
-        chipset: Chipset,
-        bios: &Vbios,
-        gsp_falcon: &Falcon<'_, GspEngine>,
-        sec2_falcon: &Falcon<'_, Sec2>,
-    ) -> Result<KBox<dyn UnloadBundle>> {
-        KBox::new(
-            Self {
-                fwsec_sb: FwsecUnloadFirmware::new(dev, chipset, bios, gsp_falcon)?,
-                booter_unloader: BooterFirmware::new(
-                    dev,
-                    BooterKind::Unloader,
-                    chipset,
-                    FIRMWARE_VERSION,
-                    sec2_falcon,
-                )?,
-            },
-            GFP_KERNEL,
-        )
-        .map(|b| b as KBox<dyn UnloadBundle>)
-        .map_err(Into::into)
-    }
-}
-
 impl UnloadBundle for Sec2UnloadBundle {
     fn run(&self, ctx: &GspBootContext<'_>) -> Result {
         let dev = ctx.dev();
@@ -257,6 +214,44 @@ fn run_fwsec_frts(
 
 struct Tu102;
 
+impl Tu102 {
+    /// Load and prepare the resources required to properly reset the GSP after it has been stopped.
+    fn build_unload_bundle(
+        &self,
+        dev: &device::Device<device::Bound>,
+        chipset: Chipset,
+        bios: &Vbios,
+        gsp_falcon: &Falcon<'_, GspEngine>,
+        sec2_falcon: &Falcon<'_, Sec2>,
+    ) -> Result<crate::gsp::UnloadBundle> {
+        // Load the FWSEC SB firmware, as well as its bootloader if required.
+        let fwsec_sb =
+            FwsecFirmware::new(dev, gsp_falcon, bios, FwsecCommand::Sb).and_then(|fwsec_sb| {
+                Ok(if chipset.needs_fwsec_bootloader() {
+                    FwsecUnloadFirmware::WithBl(FwsecFirmwareWithBl::new(fwsec_sb, dev, chipset)?)
+                } else {
+                    FwsecUnloadFirmware::WithoutBl(fwsec_sb)
+                })
+            })?;
+
+        KBox::new(
+            Sec2UnloadBundle {
+                fwsec_sb,
+                booter_unloader: BooterFirmware::new(
+                    dev,
+                    BooterKind::Unloader,
+                    chipset,
+                    FIRMWARE_VERSION,
+                    sec2_falcon,
+                )?,
+            },
+            GFP_KERNEL,
+        )
+        .map(|b| crate::gsp::UnloadBundle(b))
+        .map_err(Into::into)
+    }
+}
+
 impl GspHal for Tu102 {
     fn boot(
         &self,
@@ -277,10 +272,10 @@ fn boot(
         //
         // If the unload bundle creation fails, the GPU will need to be reset before the driver can
         // be probed again.
-        let unload_bundle = Sec2UnloadBundle::build(dev, chipset, &bios, gsp_falcon, sec2_falcon)
+        let unload_bundle = self
+            .build_unload_bundle(dev, chipset, &bios, gsp_falcon, sec2_falcon)
             .inspect_err(|e| dev_warn!(dev, "Failed to prepare unload firmware: {:?}\n", e))
-            .ok()
-            .map(crate::gsp::UnloadBundle);
+            .ok();
 
         // Run the unload bundle to try and recover the GSP if an error occurs.
         let unload_guard = ScopeGuard::new_with_data(unload_bundle, |unload_bundle| {
Signature · 1 line
2.54.0
Reviewed-by on v4 6/13
#15 lore raw

Re: [PATCH v4 06/13] gpu: nova-core: gsp: fold TU102 unload bundle construction into HAL method

Quoted 87 lines · Alexandre Courbot

The construction of the unload bundle is currently a bit convoluted and could be done in one function instead of two.

Additionally, turn that function into a method of Tu102. A following patch will turn the "use FWSEC bootloader" property into a flag of the TU102 HAL itself, and making this a method will allow the code to access it instead of querying Chipset.

---
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 87 ++++++++++++++++------------------
 1 file changed, 41 insertions(+), 46 deletions(-)
drivers/gpu/nova-core/gsp/hal/tu102.rs +9 -43
index ef465b99af05..0505a5beee6e 100644
@@ -56,22 +56,6 @@ enum FwsecUnloadFirmware {
 }
 
 impl FwsecUnloadFirmware {
-    /// Loads the FWSEC SB firmware, as well as its bootloader if `chipset` requires it.
-    fn new(
-        dev: &device::Device<device::Bound>,
-        chipset: Chipset,
-        bios: &Vbios,
-        gsp_falcon: &Falcon<'_, GspEngine>,
-    ) -> Result<Self> {
-        let fwsec_sb = FwsecFirmware::new(dev, gsp_falcon, bios, FwsecCommand::Sb)?;
-
-        Ok(if chipset.needs_fwsec_bootloader() {
-            Self::WithBl(FwsecFirmwareWithBl::new(fwsec_sb, dev, chipset)?)
-        } else {
-            Self::WithoutBl(fwsec_sb)
-        })
-    }
-
     /// Runs the FWSEC SB firmware.
     fn run(
         &self,
@@ -93,33 +77,6 @@ struct Sec2UnloadBundle {
     booter_unloader: BooterFirmware,
 }
 
-impl Sec2UnloadBundle {
-    /// Load and prepare the resources required to properly reset the GSP after it has been stopped.
-    fn build(
-        dev: &device::Device<device::Bound>,
-        chipset: Chipset,
-        bios: &Vbios,
-        gsp_falcon: &Falcon<'_, GspEngine>,
-        sec2_falcon: &Falcon<'_, Sec2>,
-    ) -> Result<KBox<dyn UnloadBundle>> {
-        KBox::new(
-            Self {
-                fwsec_sb: FwsecUnloadFirmware::new(dev, chipset, bios, gsp_falcon)?,
-                booter_unloader: BooterFirmware::new(
-                    dev,
-                    BooterKind::Unloader,
-                    chipset,
-                    FIRMWARE_VERSION,
-                    sec2_falcon,
-                )?,
-            },
-            GFP_KERNEL,
-        )
-        .map(|b| b as KBox<dyn UnloadBundle>)
-        .map_err(Into::into)
-    }
-}
-
 impl UnloadBundle for Sec2UnloadBundle {
     fn run(&self, ctx: &GspBootContext<'_>) -> Result {
         let dev = ctx.dev();
@@ -257,6 +214,44 @@ fn run_fwsec_frts(
 
 struct Tu102;
 
+impl Tu102 {
+    /// Load and prepare the resources required to properly reset the GSP after it has been stopped.
+    fn build_unload_bundle(
+        &self,
+        dev: &device::Device<device::Bound>,
+        chipset: Chipset,
+        bios: &Vbios,
+        gsp_falcon: &Falcon<'_, GspEngine>,
+        sec2_falcon: &Falcon<'_, Sec2>,

drivers/gpu/nova-core/gsp/hal/tu102.rs fn run_fwsec_frts( · line 235

Quoted 10 lines
drivers/gpu/nova-core/gsp/hal/tu102.rs +10 -0
+    ) -> Result<crate::gsp::UnloadBundle> {
+        // Load the FWSEC SB firmware, as well as its bootloader if required.
+        let fwsec_sb =
+            FwsecFirmware::new(dev, gsp_falcon, bios, FwsecCommand::Sb).and_then(|fwsec_sb| {
+                Ok(if chipset.needs_fwsec_bootloader() {
+                    FwsecUnloadFirmware::WithBl(FwsecFirmwareWithBl::new(fwsec_sb, dev, chipset)?)
+                } else {
+                    FwsecUnloadFirmware::WithoutBl(fwsec_sb)
+                })
+            })?;

nit: Maybe nicer to write this like:

```
// Load the FWSEC SB firmware, as well as its bootloader if required.
let fwsec_sb = FwsecFirmware::new(dev, gsp_falcon, bios, FwsecCommand::Sb)?;
let fwsec_sb = if self.needs_fwsec_bootloader {
    FwsecUnloadFirmware::WithBl(FwsecFirmwareWithBl::new(fwsec_sb, dev, chipset)?)
} else {
    FwsecUnloadFirmware::WithoutBl(fwsec_sb)
};
```

With that,

Quoted 36 lines
drivers/gpu/nova-core/gsp/hal/tu102.rs +22 -3
+
+        KBox::new(
+            Sec2UnloadBundle {
+                fwsec_sb,
+                booter_unloader: BooterFirmware::new(
+                    dev,
+                    BooterKind::Unloader,
+                    chipset,
+                    FIRMWARE_VERSION,
+                    sec2_falcon,
+                )?,
+            },
+            GFP_KERNEL,
+        )
+        .map(|b| crate::gsp::UnloadBundle(b))
+        .map_err(Into::into)
+    }
+}
+
 impl GspHal for Tu102 {
     fn boot(
         &self,
@@ -277,10 +272,10 @@ fn boot(
         //
         // If the unload bundle creation fails, the GPU will need to be reset before the driver can
         // be probed again.
-        let unload_bundle = Sec2UnloadBundle::build(dev, chipset, &bios, gsp_falcon, sec2_falcon)
+        let unload_bundle = self
+            .build_unload_bundle(dev, chipset, &bios, gsp_falcon, sec2_falcon)
             .inspect_err(|e| dev_warn!(dev, "Failed to prepare unload firmware: {:?}\n", e))
-            .ok()
-            .map(crate::gsp::UnloadBundle);
+            .ok();
 
         // Run the unload bundle to try and recover the GSP if an error occurs.
         let unload_guard = ScopeGuard::new_with_data(unload_bundle, |unload_bundle| {
author maintainer
#16 lore raw

PATCH v4 7/13 gpu: nova-core: gsp: turn FWSEC execution into HAL method

In reply to Alexandre Courbot

Turn the run_fwsec_frts function into a method of Tu102. A following patch will turn the "use FWSEC bootloader" property into a flag of the TU102 HAL itself, and making this a method will allow the code to access it instead of querying Chipset.

---
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 173 +++++++++++++++++----------------
 1 file changed, 87 insertions(+), 86 deletions(-)
drivers/gpu/nova-core/gsp/hal/tu102.rs +87 -86
index 0505a5beee6e..df3d773bd354 100644
@@ -127,94 +127,95 @@ fn run(&self, ctx: &GspBootContext<'_>) -> Result {
     }
 }
 
-/// Helper function to load and run the FWSEC-FRTS firmware and confirm that it has properly
-/// created the WPR2 region.
-fn run_fwsec_frts(
-    dev: &device::Device<device::Bound>,
-    chipset: Chipset,
-    falcon: &Falcon<'_, GspEngine>,
-    bar: Bar0<'_>,
-    bios: &Vbios,
-    fb_layout: &FbLayout,
-) -> Result {
-    // Check that the WPR2 region does not already exist - if it does, we cannot run
-    // FWSEC-FRTS until the GPU is reset.
-    if bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI).higher_bound() != 0 {
-        dev_err!(
-            dev,
-            "WPR2 region already exists - GPU needs to be reset to proceed\n"
-        );
-        return Err(EBUSY);
-    }
-
-    // FWSEC-FRTS will create the WPR2 region.
-    let fwsec_frts = FwsecFirmware::new(
-        dev,
-        falcon,
-        bios,
-        FwsecCommand::Frts {
-            frts_addr: fb_layout.frts.start,
-            frts_size: fb_layout.frts.len(),
-        },
-    )?;
-
-    if chipset.needs_fwsec_bootloader() {
-        let fwsec_frts_bl = FwsecFirmwareWithBl::new(fwsec_frts, dev, chipset)?;
-        // Load and run the bootloader, which will load FWSEC-FRTS and run it.
-        fwsec_frts_bl.run(dev, falcon, bar)?;
-    } else {
-        // Load and run FWSEC-FRTS directly.
-        fwsec_frts.run(dev, falcon)?;
-    }
-
-    // SCRATCH_E contains the error code for FWSEC-FRTS.
-    let frts_status = bar
-        .read(regs::NV_PBUS_SW_SCRATCH_0E_FRTS_ERR)
-        .frts_err_code();
-    if frts_status != 0 {
-        dev_err!(
-            dev,
-            "FWSEC-FRTS returned with error code {:#x}\n",
-            frts_status
-        );
-
-        return Err(EIO);
-    }
-
-    // Check that the WPR2 region has been created as we requested.
-    let (wpr2_lo, wpr2_hi) = (
-        bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_LO).lower_bound(),
-        bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI).higher_bound(),
-    );
-
-    match (wpr2_lo, wpr2_hi) {
-        (_, 0) => {
-            dev_err!(dev, "WPR2 region not created after running FWSEC-FRTS\n");
-
-            Err(EIO)
-        }
-        (wpr2_lo, _) if wpr2_lo != fb_layout.frts.start => {
-            dev_err!(
-                dev,
-                "WPR2 region created at unexpected address {:#x}; expected {:#x}\n",
-                wpr2_lo,
-                fb_layout.frts.start,
-            );
-
-            Err(EIO)
-        }
-        (wpr2_lo, wpr2_hi) => {
-            dev_dbg!(dev, "WPR2: {:#x}-{:#x}\n", wpr2_lo, wpr2_hi);
-            dev_dbg!(dev, "GPU instance built\n");
-
-            Ok(())
-        }
-    }
-}
-
 struct Tu102;
 
 impl Tu102 {
+    /// Helper method to load and run the FWSEC-FRTS firmware and confirm that it has properly
+    /// created the WPR2 region.
+    fn run_fwsec_frts(
+        &self,
+        dev: &device::Device<device::Bound>,
+        chipset: Chipset,
+        falcon: &Falcon<'_, GspEngine>,
+        bar: Bar0<'_>,
+        bios: &Vbios,
+        fb_layout: &FbLayout,
+    ) -> Result {
+        // Check that the WPR2 region does not already exist - if it does, we cannot run
+        // FWSEC-FRTS until the GPU is reset.
+        if bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI).higher_bound() != 0 {
+            dev_err!(
+                dev,
+                "WPR2 region already exists - GPU needs to be reset to proceed\n"
+            );
+            return Err(EBUSY);
+        }
+
+        // FWSEC-FRTS will create the WPR2 region.
+        let fwsec_frts = FwsecFirmware::new(
+            dev,
+            falcon,
+            bios,
+            FwsecCommand::Frts {
+                frts_addr: fb_layout.frts.start,
+                frts_size: fb_layout.frts.len(),
+            },
+        )?;
+
+        if chipset.needs_fwsec_bootloader() {
+            let fwsec_frts_bl = FwsecFirmwareWithBl::new(fwsec_frts, dev, chipset)?;
+            // Load and run the bootloader, which will load FWSEC-FRTS and run it.
+            fwsec_frts_bl.run(dev, falcon, bar)?;
+        } else {
+            // Load and run FWSEC-FRTS directly.
+            fwsec_frts.run(dev, falcon)?;
+        }
+
+        // SCRATCH_E contains the error code for FWSEC-FRTS.
+        let frts_status = bar
+            .read(regs::NV_PBUS_SW_SCRATCH_0E_FRTS_ERR)
+            .frts_err_code();
+        if frts_status != 0 {
+            dev_err!(
+                dev,
+                "FWSEC-FRTS returned with error code {:#x}\n",
+                frts_status
+            );
+
+            return Err(EIO);
+        }
+
+        // Check that the WPR2 region has been created as we requested.
+        let (wpr2_lo, wpr2_hi) = (
+            bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_LO).lower_bound(),
+            bar.read(regs::NV_PFB_PRI_MMU_WPR2_ADDR_HI).higher_bound(),
+        );
+
+        match (wpr2_lo, wpr2_hi) {
+            (_, 0) => {
+                dev_err!(dev, "WPR2 region not created after running FWSEC-FRTS\n");
+
+                Err(EIO)
+            }
+            (wpr2_lo, _) if wpr2_lo != fb_layout.frts.start => {
+                dev_err!(
+                    dev,
+                    "WPR2 region created at unexpected address {:#x}; expected {:#x}\n",
+                    wpr2_lo,
+                    fb_layout.frts.start,
+                );
+
+                Err(EIO)
+            }
+            (wpr2_lo, wpr2_hi) => {
+                dev_dbg!(dev, "WPR2: {:#x}-{:#x}\n", wpr2_lo, wpr2_hi);
+                dev_dbg!(dev, "GPU instance built\n");
+
+                Ok(())
+            }
+        }
+    }
+
     /// Load and prepare the resources required to properly reset the GSP after it has been stopped.
     fn build_unload_bundle(
         &self,
@@ -286,7 +287,7 @@ fn boot(
 
         // FWSEC-FRTS is not executed on chips where the FRTS region size is 0 (e.g. GA100).
         if !fb_layout.frts.is_empty() {
-            run_fwsec_frts(dev, chipset, gsp_falcon, bar, &bios, fb_layout)?;
+            self.run_fwsec_frts(dev, chipset, gsp_falcon, bar, &bios, fb_layout)?;
         }
 
         gsp_falcon.reset()?;
Signature · 1 line
2.54.0
Reviewed-by on v4 7/13
#17 lore raw

Re: [PATCH v4 07/13] gpu: nova-core: gsp: turn FWSEC execution into HAL method

Quoted 7 lines · Alexandre Courbot

Turn the run_fwsec_frts function into a method of Tu102. A following patch will turn the "use FWSEC bootloader" property into a flag of the TU102 HAL itself, and making this a method will allow the code to access it instead of querying Chipset.

---

author maintainer
#18 lore raw

PATCH v4 8/13 gpu: nova-core: gsp: make use of FWSEC bootloader a property of the TU102 HAL

In reply to Alexandre Courbot

By being in the TU102 HAL, we already know that the GSP boot method is the SEC2 Booter, so the only variable is whether the FWSEC bootloader is used or not. Since Chipset also includes the variants that boot FSP, querying it for that information introduces a potential code path where the chipset actually boots via FSP that the current code doesn't handle.

Turn the use of FWSEC bootloader into a property of the Tu102 HAL, and give GA102+ chipsets their own instance with that property set to false. This removes the invalid code path and the only use of Chipset is now to load the correct firmware files.

This also removes some uses of the Chipset::needs_fwsec_bootloader method and prepares the ground for removing it.

---
 drivers/gpu/nova-core/gsp/hal.rs       |  5 ++++-
 drivers/gpu/nova-core/gsp/hal/ga102.rs | 14 ++++++++++++++
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 15 +++++++++++----
 3 files changed, 29 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/gsp/hal.rs +4 -1
index 849ca224085b..eddb4e8bf510 100644
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0
 // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
+mod ga102;
 mod gh100;
 mod tu102;
 
@@ -59,7 +60,9 @@ fn post_boot(&self, _gsp: &Gsp, _ctx: &GspBootContext<'_>, _gsp_fw: &GspFirmware
 /// Returns the GSP HAL to be used for `chipset`.
 pub(super) fn gsp_hal(chipset: Chipset) -> &'static dyn GspHal {
     match chipset.arch() {
-        Architecture::Turing | Architecture::Ampere | Architecture::Ada => tu102::TU102_HAL,
+        Architecture::Turing => tu102::TU102_HAL,
+        Architecture::Ampere if matches!(chipset, Chipset::GA100) => tu102::TU102_HAL,
+        Architecture::Ampere | Architecture::Ada => ga102::GA102_HAL,
         Architecture::Hopper | Architecture::BlackwellGB10x | Architecture::BlackwellGB20x => {
             gh100::GH100_HAL
         }
drivers/gpu/nova-core/gsp/hal/ga102.rs new file +14 -0
new file mode 100644
index 000000000000..ceb3eb39d138
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use crate::gsp::hal::{
+    tu102::Tu102,
+    GspHal, //
+};
+
+/// The GA102 HAL is like the TU102 one, except it doesn't use the bootloader.
+const GA102: Tu102 = Tu102 {
+    needs_fwsec_bootloader: false,
+};
+
+pub(super) const GA102_HAL: &dyn GspHal = &GA102;
drivers/gpu/nova-core/gsp/hal/tu102.rs +11 -4
index df3d773bd354..68274367c70d 100644
@@ -127,7 +127,10 @@ fn run(&self, ctx: &GspBootContext<'_>) -> Result {
     }
 }
 
-struct Tu102;
+pub(super) struct Tu102 {
+    /// If `true`, then the FWSEC-FRTS bootloader will be used to load the actual firmware.
+    pub(super) needs_fwsec_bootloader: bool,
+}
 
 impl Tu102 {
     /// Helper method to load and run the FWSEC-FRTS firmware and confirm that it has properly
@@ -162,7 +165,7 @@ fn run_fwsec_frts(
             },
         )?;
 
-        if chipset.needs_fwsec_bootloader() {
+        if self.needs_fwsec_bootloader {
             let fwsec_frts_bl = FwsecFirmwareWithBl::new(fwsec_frts, dev, chipset)?;
             // Load and run the bootloader, which will load FWSEC-FRTS and run it.
             fwsec_frts_bl.run(dev, falcon, bar)?;
@@ -228,7 +231,7 @@ fn build_unload_bundle(
         // Load the FWSEC SB firmware, as well as its bootloader if required.
         let fwsec_sb =
             FwsecFirmware::new(dev, gsp_falcon, bios, FwsecCommand::Sb).and_then(|fwsec_sb| {
-                Ok(if chipset.needs_fwsec_bootloader() {
+                Ok(if self.needs_fwsec_bootloader {
                     FwsecUnloadFirmware::WithBl(FwsecFirmwareWithBl::new(fwsec_sb, dev, chipset)?)
                 } else {
                     FwsecUnloadFirmware::WithoutBl(fwsec_sb)
@@ -325,5 +328,9 @@ fn post_boot(&self, gsp: &Gsp, ctx: &GspBootContext<'_>, gsp_fw: &GspFirmware) -
     }
 }
 
-const TU102: Tu102 = Tu102;
+/// The TU102 HAL requires the use of the FWSEC bootloader.
+const TU102: Tu102 = Tu102 {
+    needs_fwsec_bootloader: true,
+};
+
 pub(super) const TU102_HAL: &dyn GspHal = &TU102;
Signature · 1 line
2.54.0
author maintainer
#19 lore raw

PATCH v4 9/13 gpu: nova-core: introduce GspBootMethod

In reply to Alexandre Courbot

The GSP boot method is currently determined by two ad-hoc methods of Chipset: uses_fsp (a boolean telling whether to use the FSP boot path or the Sec2 Booter one) and needs_fwsec_bootloader (another boolean valid only for the Sec2 Booter method that tells whether the FWSEC bootloader must be used).

This is neither extensible nor sound: the combination uses_fsp && needs_fwsec_bootloader is invalid, but can still be expressed.

Thus, unify these two predicates into a single gsp_boot_method method that returns an enum type unambiguously describing the boot method to use. This ensures that no invalid combination can be expressed, which makes matching sounder.

---
 drivers/gpu/nova-core/firmware.rs       | 25 ++++++++++++--------
 drivers/gpu/nova-core/firmware/fwsec.rs |  5 ++--
 drivers/gpu/nova-core/gpu.rs            | 16 -------------
 drivers/gpu/nova-core/gsp.rs            | 42 ++++++++++++++++++++++++++++++++-
 drivers/gpu/nova-core/gsp/hal.rs        | 22 ++++++++---------
 5 files changed, 70 insertions(+), 40 deletions(-)
drivers/gpu/nova-core/firmware.rs +15 -10
index 80e948bf7511..7a5978f93f4e 100644
@@ -21,6 +21,7 @@
         FalconFirmware, //
     },
     gpu,
+    gsp::GspBootMethod,
     num::{
         FromSafeCast,
         IntoSafeCast, //
@@ -429,17 +430,21 @@ const fn make_entry_chipset(self, chipset: gpu::Chipset) -> Self {
 
         // FSP-based chipsets (Hopper, Blackwell and later) boot the GSP via the FMC image loaded by
         // FSP. Older chipsets use the SEC2 booter instead.
-        let this = if chipset.uses_fsp() {
-            this.make_entry_file(name, "fmc")
-        } else {
-            this.make_entry_file(name, "booter_load")
-                .make_entry_file(name, "booter_unload")
-        };
+        match chipset.gsp_boot_method() {
+            GspBootMethod::Sec2 {
+                needs_fwsec_bootloader,
+            } => {
+                let mut this = this
+                    .make_entry_file(name, "booter_load")
+                    .make_entry_file(name, "booter_unload");
 
-        if chipset.needs_fwsec_bootloader() {
-            this.make_entry_file(name, "gen_bootloader")
-        } else {
-            this
+                if needs_fwsec_bootloader {
+                    this = this.make_entry_file(name, "gen_bootloader")
+                }
+
+                this
+            }
+            GspBootMethod::Fsp => this.make_entry_file(name, "fmc"),
         }
     }
 
drivers/gpu/nova-core/firmware/fwsec.rs +3 -2
index 95e0dd77746b..dca862c53a6c 100644
@@ -386,8 +386,9 @@ pub(crate) fn new(
     /// Loads the FWSEC firmware into `falcon` and execute it.
     ///
     /// This must only be called on chipsets that do not need the FWSEC bootloader (i.e., where
-    /// [`Chipset::needs_fwsec_bootloader()`](crate::gpu::Chipset::needs_fwsec_bootloader) returns
-    /// `false`). On chipsets that do, use [`bootloader::FwsecFirmwareWithBl`] instead.
+    /// [`Chipset::gsp_boot_method()`](crate::gpu::Chipset::gsp_boot_method) returns
+    /// `GspBootMethod::Sec2 { needs_fwsec_bootloader: false }`). On chipsets where
+    /// `needs_fwsec_bootloader` is `true`, use [`bootloader::FwsecFirmwareWithBl`] instead.
     pub(crate) fn run(&self, dev: &Device<device::Bound>, falcon: &Falcon<'_, Gsp>) -> Result<()> {
         // Reset falcon, load the firmware, and run it.
         falcon
drivers/gpu/nova-core/gpu.rs +0 -16
index 32bfa0be2357..c04706b60ba8 100644
@@ -133,22 +133,6 @@ pub(crate) const fn arch(self) -> Architecture {
         }
     }
 
-    /// Returns `true` if this chipset requires the PIO-loaded bootloader in order to boot FWSEC.
-    ///
-    /// This includes all chipsets < GA102.
-    pub(crate) const fn needs_fwsec_bootloader(self) -> bool {
-        matches!(self.arch(), Architecture::Turing) || matches!(self, Self::GA100)
-    }
-
-    /// Returns `true` if this chipset boots via FSP (Hopper and later), which requires the FMC
-    /// firmware image.
-    pub(crate) const fn uses_fsp(self) -> bool {
-        matches!(
-            self.arch(),
-            Architecture::Hopper | Architecture::BlackwellGB10x | Architecture::BlackwellGB20x
-        )
-    }
-
     /// Returns the address range of the PCI config mirror space.
     pub(crate) fn pci_config_mirror_range(self) -> Range<u32> {
         hal::gpu_hal(self).pci_config_mirror_range()
drivers/gpu/nova-core/gsp.rs +41 -1

53 lines not on this page · raw message

drivers/gpu/nova-core/gsp/hal.rs +11 -11
index eddb4e8bf510..90f076f640e0 100644
@@ -13,13 +13,11 @@
 use crate::{
     fb::FbLayout,
     firmware::gsp::GspFirmware,
-    gpu::{
-        Architecture,
-        Chipset, //
-    },
+    gpu::Chipset,
     gsp::{
         Gsp,
         GspBootContext,
+        GspBootMethod,
         GspFwWprMeta, //
     },
 };
@@ -59,12 +57,14 @@ fn post_boot(&self, _gsp: &Gsp, _ctx: &GspBootContext<'_>, _gsp_fw: &GspFirmware
 
 /// Returns the GSP HAL to be used for `chipset`.
 pub(super) fn gsp_hal(chipset: Chipset) -> &'static dyn GspHal {
-    match chipset.arch() {
-        Architecture::Turing => tu102::TU102_HAL,
-        Architecture::Ampere if matches!(chipset, Chipset::GA100) => tu102::TU102_HAL,
-        Architecture::Ampere | Architecture::Ada => ga102::GA102_HAL,
-        Architecture::Hopper | Architecture::BlackwellGB10x | Architecture::BlackwellGB20x => {
-            gh100::GH100_HAL
-        }
+    // The GSP HAL is entirely determined by the boot method.
+    match chipset.gsp_boot_method() {
+        GspBootMethod::Sec2 {
+            needs_fwsec_bootloader: true,
+        } => tu102::TU102_HAL,
+        GspBootMethod::Sec2 {
+            needs_fwsec_bootloader: false,
+        } => ga102::GA102_HAL,
+        GspBootMethod::Fsp => gh100::GH100_HAL,
     }
 }
Signature · 1 line
2.54.0
#20 lore raw

Re: [PATCH v4 09/13] gpu: nova-core: introduce GspBootMethod

Quoted 9 lines · Alexandre Courbot

The GSP boot method is currently determined by two ad-hoc methods of Chipset: uses_fsp (a boolean telling whether to use the FSP boot path or the Sec2 Booter one) and needs_fwsec_bootloader (another boolean valid only for the Sec2 Booter method that tells whether the FWSEC bootloader must be used).

This is neither extensible nor sound: the combination uses_fsp && needs_fwsec_bootloader is invalid, but can still be expressed.

Quoted 7 lines

Thus, unify these two predicates into a single gsp_boot_method method that returns an enum type unambiguously describing the boot method to use. This ensures that no invalid combination can be expressed, which makes matching sounder.

---

Ideally we would not need to expose bootloader details (needs fwsec bootloader, mapping of architecture to GspBootMethod) outside of the HAL, and also not have to duplicate the logic for determining needs_fwsec_bootloader in both the HAL and Chipset. One thing preventing keeping all this in the HALs is that we need to know the set of firmware files in a const context, which can't go through the &dyn for HALs. I also find it a bit odd to go Chipset->GspBootMethod->HAL which relies on the GSP HAL being entirely determined by the boot method which doesn't feel generally correct to me.

What if we added a const fn n gsp/hal.rs called like boot_firmware_files ( or whatever) which returns the extra firmware files needed to boot the GSP based on the architecture. Then we don't need to expose details like needs_fwsec_bootloader or GspBootMethod outside of the HALs. We still need another set of matches but it's unavoidable AFAICT without being able to know the HAL type in a const context, at least it's consolidated and in the HAL this way. In the future we might consider type parameterising Gpu with the chipset and types that it uses with the minimal set of strategies that it needs (e.g. sec2 vs fsp boot) then we could even make the HALs not use dyn and push a bunch of stuff into associated types.

That looks like this (on top of patch 8):

WDYT?

drivers/gpu/nova-core/firmware.rs +9 -14
index 80e948bf7511..1c02d80de7bc 100644
@@ -423,24 +423,19 @@ const fn make_entry_file(self, chipset: &str, fw: &str) -> Self {
     const fn make_entry_chipset(self, chipset: gpu::Chipset) -> Self {
         let name = chipset.name();
 
-        let this = self
+        let mut this = self
             .make_entry_file(name, "bootloader")
             .make_entry_file(name, "gsp");
 
-        // FSP-based chipsets (Hopper, Blackwell and later) boot the GSP via the FMC image loaded by
-        // FSP. Older chipsets use the SEC2 booter instead.
-        let this = if chipset.uses_fsp() {
-            this.make_entry_file(name, "fmc")
-        } else {
-            this.make_entry_file(name, "booter_load")
-                .make_entry_file(name, "booter_unload")
-        };
-
-        if chipset.needs_fwsec_bootloader() {
-            this.make_entry_file(name, "gen_bootloader")
-        } else {
-            this
+        // Add the firmware files specific to the GSP boot method of `chipset`.
+        let boot_files = crate::gsp::boot_firmware_files(chipset);
+        let mut i = 0;
+        while i < boot_files.len() {
+            this = this.make_entry_file(name, boot_files[i]);
+            i += 1;
         }
+
+        this
     }
 
     pub(crate) const fn create(
drivers/gpu/nova-core/firmware/fwsec.rs +2 -3
index 95e0dd77746b..7a931f22f629 100644
@@ -385,9 +385,8 @@ pub(crate) fn new(
 
     /// Loads the FWSEC firmware into `falcon` and execute it.
     ///
-    /// This must only be called on chipsets that do not need the FWSEC bootloader (i.e., where
-    /// [`Chipset::needs_fwsec_bootloader()`](crate::gpu::Chipset::needs_fwsec_bootloader) returns
-    /// `false`). On chipsets that do, use [`bootloader::FwsecFirmwareWithBl`] instead.
+    /// This must only be called on chipsets that do not need the FWSEC bootloader. On chipsets
+    /// where the bootloader is required, use [`bootloader::FwsecFirmwareWithBl`] instead.
     pub(crate) fn run(&self, dev: &Device<device::Bound>, falcon: &Falcon<'_, Gsp>) -> Result<()> {
         // Reset falcon, load the firmware, and run it.
         falcon
drivers/gpu/nova-core/gpu.rs +0 -16
index 32bfa0be2357..c04706b60ba8 100644
@@ -133,22 +133,6 @@ pub(crate) const fn arch(self) -> Architecture {
         }
     }
 
-    /// Returns `true` if this chipset requires the PIO-loaded bootloader in order to boot FWSEC.
-    ///
-    /// This includes all chipsets < GA102.
-    pub(crate) const fn needs_fwsec_bootloader(self) -> bool {
-        matches!(self.arch(), Architecture::Turing) || matches!(self, Self::GA100)
-    }
-
-    /// Returns `true` if this chipset boots via FSP (Hopper and later), which requires the FMC
-    /// firmware image.
-    pub(crate) const fn uses_fsp(self) -> bool {
-        matches!(
-            self.arch(),
-            Architecture::Hopper | Architecture::BlackwellGB10x | Architecture::BlackwellGB20x
-        )
-    }
-
     /// Returns the address range of the PCI config mirror space.
     pub(crate) fn pci_config_mirror_range(self) -> Range<u32> {
         hal::gpu_hal(self).pci_config_mirror_range()
drivers/gpu/nova-core/gsp.rs +1 -0
index b4ac4156056e..d5cca3c8350a 100644
@@ -30,6 +30,7 @@
     GspFwWprMeta,
     LibosParams, //
 };
+pub(crate) use hal::boot_firmware_files;
 
 use crate::{
     driver::Bar0,
drivers/gpu/nova-core/gsp/hal.rs +19 -0
index eddb4e8bf510..9da078dd1059 100644
@@ -57,6 +57,25 @@ fn post_boot(&self, _gsp: &Gsp, _ctx: &GspBootContext<'_>, _gsp_fw: &GspFirmware
     }
 }
 
+/// Returns the names of the firmware files required to boot the GSP of `chipset`, in addition to
+/// the "bootloader" and "gsp" images required by all chipsets.
+pub(crate) const fn boot_firmware_files(chipset: Chipset) -> &'static [&'static str] {
+    match chipset.arch() {
+        // Turing chipsets boot the GSP via the SEC2 Booter, and require the FWSEC bootloader.
+        Architecture::Turing => &["booter_load", "booter_unload", "gen_bootloader"],
+        // GA100 also requires the FWSEC bootloader.
+        Architecture::Ampere if matches!(chipset, Chipset::GA100) => {
+            &["booter_load", "booter_unload", "gen_bootloader"]
+        }
+        // Other Ampere chipsets, as well as Ada chipsets, run FWSEC directly.
+        Architecture::Ampere | Architecture::Ada => &["booter_load", "booter_unload"],
+        // Hopper and later chipsets boot the GSP via the FMC image loaded by FSP.
+        Architecture::Hopper | Architecture::BlackwellGB10x | Architecture::BlackwellGB20x => {
+            &["fmc"]
+        }
+    }
+}
+
 /// Returns the GSP HAL to be used for `chipset`.
 pub(super) fn gsp_hal(chipset: Chipset) -> &'static dyn GspHal {
     match chipset.arch() {
author maintainer
#21 lore raw

Re: [PATCH v4 09/13] gpu: nova-core: introduce GspBootMethod

Quoted 18 lines · Eliot Courtney
Quoted 9 lines · Alexandre Courbot

The GSP boot method is currently determined by two ad-hoc methods of Chipset: uses_fsp (a boolean telling whether to use the FSP boot path or the Sec2 Booter one) and needs_fwsec_bootloader (another boolean valid only for the Sec2 Booter method that tells whether the FWSEC bootloader must be used).

This is neither extensible nor sound: the combination uses_fsp && needs_fwsec_bootloader is invalid, but can still be expressed.

Quoted 7 lines

Thus, unify these two predicates into a single gsp_boot_method method that returns an enum type unambiguously describing the boot method to use. This ensures that no invalid combination can be expressed, which makes matching sounder.

---

Quoted 9 lines

Ideally we would not need to expose bootloader details (needs fwsec bootloader, mapping of architecture to GspBootMethod) outside of the HAL, and also not have to duplicate the logic for determining needs_fwsec_bootloader in both the HAL and Chipset. One thing preventing keeping all this in the HALs is that we need to know the set of firmware files in a const context, which can't go through the &dyn for HALs. I also find it a bit odd to go Chipset->GspBootMethod->HAL which relies on the GSP HAL being entirely determined by the boot method which doesn't feel generally correct to me.

So far it is a good mapping though - the only thing abstracted by the GSP HAL is how we boot and stop the GSP, which is entirely determined by the boot method used.

While I agree that not exposing these details outside of the HAL would be nice, at least for the time being we need to - the creation of the Fsp happens at the Gpu level, and is now conditional on the boot method. Thus the introduction of GspBootMethod. I would be happy to remove this in the future if we can, but that doesn't look possible without more refactoring, and this series is already doing quite a bit of it just to move the Fsp instance up. I think going further should be a separate effort.

Quoted 12 lines

What if we added a const fn n gsp/hal.rs called like boot_firmware_files ( or whatever) which returns the extra firmware files needed to boot the GSP based on the architecture. Then we don't need to expose details like needs_fwsec_bootloader or GspBootMethod outside of the HALs. We still need another set of matches but it's unavoidable AFAICT without being able to know the HAL type in a const context, at least it's consolidated and in the HAL this way. In the future we might consider type parameterising Gpu with the chipset and types that it uses with the minimal set of strategies that it needs (e.g. sec2 vs fsp boot) then we could even make the HALs not use dyn and push a bunch of stuff into associated types.

I like this idea of a function that provides the required firmware files, I imagine we could have the relevant modules provide the files they need in a const function and the ModInfoBuilder going through that.

For the moment though, as shown in the patch you provided this requires another match on Architecture, with consideration for whether we are using the FWSEC bootloader or not, and handling the special case for GA100 - so it's not really abstacting more things away.

Conversely, the boot method is again a perfect 1:1 mapping for the files we need, and removes the need to special-case GA100, so I think it is a better fit for the current state of the code.

author maintainer
#22 lore raw

Re: [PATCH v4 09/13] gpu: nova-core: introduce GspBootMethod

Quoted 33 lines · Alexandre Courbot
Quoted 18 lines · Eliot Courtney
Quoted 9 lines · Alexandre Courbot

The GSP boot method is currently determined by two ad-hoc methods of Chipset: uses_fsp (a boolean telling whether to use the FSP boot path or the Sec2 Booter one) and needs_fwsec_bootloader (another boolean valid only for the Sec2 Booter method that tells whether the FWSEC bootloader must be used).

This is neither extensible nor sound: the combination uses_fsp && needs_fwsec_bootloader is invalid, but can still be expressed.

Quoted 7 lines

Thus, unify these two predicates into a single gsp_boot_method method that returns an enum type unambiguously describing the boot method to use. This ensures that no invalid combination can be expressed, which makes matching sounder.

---

Quoted 9 lines

Ideally we would not need to expose bootloader details (needs fwsec bootloader, mapping of architecture to GspBootMethod) outside of the HAL, and also not have to duplicate the logic for determining needs_fwsec_bootloader in both the HAL and Chipset. One thing preventing keeping all this in the HALs is that we need to know the set of firmware files in a const context, which can't go through the &dyn for HALs. I also find it a bit odd to go Chipset->GspBootMethod->HAL which relies on the GSP HAL being entirely determined by the boot method which doesn't feel generally correct to me.

So far it is a good mapping though - the only thing abstracted by the GSP HAL is how we boot and stop the GSP, which is entirely determined by the boot method used.

Quoted 8 lines

While I agree that not exposing these details outside of the HAL would be nice, at least for the time being we need to - the creation of the Fsp happens at the Gpu level, and is now conditional on the boot method. Thus the introduction of GspBootMethod. I would be happy to remove this in the future if we can, but that doesn't look possible without more refactoring, and this series is already doing quite a bit of it just to move the Fsp instance up. I think going further should be a separate effort.

Need to give myself a self-rebuke here. :)

The only thing that still required the boot method leaking out of the HAL was the instantiation of Fsp, and that can also be taken care of by adding a constructor that returns an Option<Fsp>. It integrates nicely with the already-existing Fsp HAL, and combining that with Eliot's idea of providing the firmware files from the GSP HAL we can remove the Chipset ad-hoc boolean method entirely, without needing to introduce GspBootMethod.

This makes things look cleaner overall, so I'll use this approach for v5.

author maintainer
#23 lore raw

PATCH v4 10/13 gpu: nova-core: avoid repeated calls to pci::Device::as_ref

In reply to Alexandre Courbot

Add a local Device reference created from the pci::Device in the Gpu constructor to avoid repeatedly calling as_ref.

---
 drivers/gpu/nova-core/gpu.rs | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)
drivers/gpu/nova-core/gpu.rs +10 -8
index c04706b60ba8..663e61d0c023 100644
@@ -317,9 +317,11 @@ pub(crate) fn new(
         pdev: &'gpu pci::Device<device::Core<'_>>,
         bar: Bar0<'gpu>,
     ) -> impl PinInit<Self, Error> + 'gpu {
+        let dev = pdev.as_ref();
+
         try_pin_init!(Self {
-            spec: Spec::new(pdev.as_ref(), bar).inspect(|spec| {
-                dev_info!(pdev,"NVIDIA ({})\n", spec);
+            spec: Spec::new(dev, bar).inspect(|spec| {
+                dev_info!(dev,"NVIDIA ({})\n", spec);
             })?,
 
             // We must wait for GFW_BOOT completion before doing any significant setup on the GPU.
@@ -332,11 +334,11 @@ pub(crate) fn new(
                 unsafe { pdev.dma_set_mask_and_coherent(dma_mask)? };
 
                 hal.wait_gfw_boot_completion(bar)
-                    .inspect_err(|_| dev_err!(pdev, "GFW boot did not complete\n"))?;
+                    .inspect_err(|_| dev_err!(dev, "GFW boot did not complete\n"))?;
             },
 
             // Initialize this early because `gsp_resources` depends on it.
-            sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.chipset)?,
+            sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?,
 
             gsp_resources <- try_pin_init!(GspResources {
                 device: pdev,
@@ -346,13 +348,13 @@ pub(crate) fn new(
                 bar,
 
                 gsp_falcon: Falcon::new(
-                    pdev.as_ref(),
+                    dev,
                     spec.chipset,
                     bar
                 )
                 .inspect(|falcon| falcon.clear_swgen0_intr())?,
 
-                sec2_falcon: Falcon::new(pdev.as_ref(), spec.chipset, bar)?,
+                sec2_falcon: Falcon::new(dev, spec.chipset, bar)?,
 
                 gsp <- Gsp::new(pdev),
 
@@ -372,8 +374,8 @@ pub(crate) fn new(
                 // Obtain and display basic GPU information.
                 let info = gsp_resources.gsp.get_static_info(bar)?;
                 match info.gpu_name() {
-                    Ok(name) => dev_info!(pdev, "GPU name: {}\n", name),
-                    Err(e) => dev_warn!(pdev, "GPU name unavailable: {:?}\n", e),
+                    Ok(name) => dev_info!(dev, "GPU name: {}\n", name),
+                    Err(e) => dev_warn!(dev, "GPU name unavailable: {:?}\n", e),
                 }
 
                 if !info.usable_fb_regions.is_empty() {
Signature · 1 line
2.54.0
#24 lore raw

Re: [PATCH v4 10/13] gpu: nova-core: avoid repeated calls to pci::Device::as_ref

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The refactoring to use a local `Device` reference misses several `dev_dbg!` macro invocations in…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The refactoring to use a local Device reference misses several dev_dbg! macro invocations in Gpu::new, leaving the task incomplete and the code inconsistent. --

commit 5b411de251c3e77848e5e58356562796a1fb83fe
Author: Alexandre Courbot <[email protected]>

gpu: nova-core: avoid repeated calls to pci::Device::as_ref

Add a local Device reference created from the pci::Device in the Gpu constructor to avoid repeatedly calling as_ref.

Quoted 4 lines
drivers/gpu/nova-core/gpu.rs +0 -0
index c04706b60ba80..663e61d0c023b 100644

[ ... ]

Quoted 16 lines
drivers/gpu/nova-core/gpu.rs +2 -2
@@ -372,8 +374,8 @@ pub(crate) fn new(
                 // Obtain and display basic GPU information.
                 let info = gsp_resources.gsp.get_static_info(bar)?;
                 match info.gpu_name() {
-                    Ok(name) => dev_info!(pdev, "GPU name: {}\n", name),
-                    Err(e) => dev_warn!(pdev, "GPU name unavailable: {:?}\n", e),
+                    Ok(name) => dev_info!(dev, "GPU name: {}\n", name),
+                    Err(e) => dev_warn!(dev, "GPU name unavailable: {:?}\n", e),
                 }
 
                 if !info.usable_fb_regions.is_empty() {
                     dev_dbg!(pdev, "Usable FB regions:\n");
                     for region in &info.usable_fb_regions {
                         dev_dbg!(pdev, "  - {:#x?}\n", region);
                     }
Quoted 7 lines
                     dev_dbg!(
                         pdev,
                         "Total usable VRAM: {} MiB\n",
                         info.usable_fb_regions.iter().fold(0u64, |res, region| res
                             .saturating_add(region.end - region.start))
                             / u64::SZ_1M
                     );

[Severity: Low]
This isn't a bug, but should these remaining dev_dbg!() macros also be updated to use dev instead of pdev? Leaving them as pdev continues to implicitly invoke .as_ref(), which this patch is trying to avoid.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author maintainer
#26 lore raw

PATCH v4 11/13 gpu: nova-core: gsp: pass GspBootContext mutably

In reply to Alexandre Courbot

We want to move the Fsp instance into Gpu, which will require passing it as a mutable reference in GspBootContext, since Fsp::boot_fmc is a mutable method. In order to use the mutable references it contains, GspBootContext must also be mutable.

We will also follow up by making some methods of the Falcons mutable, which also requires passing them as mutable references.

Thus, make the GspBootContext passed to Gsp::boot and Gsp::unload mutable, and pass mutable references to it to the GSP boot HAL methods.

---
 drivers/gpu/nova-core/gsp/boot.rs      | 28 +++++++++++++++-------------
 drivers/gpu/nova-core/gsp/hal.rs       | 11 ++++++++---
 drivers/gpu/nova-core/gsp/hal/gh100.rs |  4 ++--
 drivers/gpu/nova-core/gsp/hal/tu102.rs |  6 +++---
 4 files changed, 28 insertions(+), 21 deletions(-)
drivers/gpu/nova-core/gsp/boot.rs +15 -13
index 430ffc57b136..f093e0215b66 100644
@@ -39,7 +39,7 @@ impl super::Gsp {
     /// [`Self::unload`]) returned.
     pub(crate) fn boot(
         self: Pin<&mut Self>,
-        ctx: super::GspBootContext<'_>,
+        mut ctx: super::GspBootContext<'_>,
     ) -> Result<Option<super::UnloadBundle>> {
         let pdev = ctx.pdev;
         let bar = ctx.bar;
@@ -56,21 +56,23 @@ pub(crate) fn boot(
         let wpr_meta = Coherent::init(dev, GFP_KERNEL, GspFwWprMeta::new(&gsp_fw, &fb_layout))?;
 
         // Perform the chipset-specific boot sequence, and retrieve the unload bundle.
-        let unload_bundle = hal.boot(&self, &ctx, &fb_layout, &wpr_meta)?.or_else(|| {
-            dev_warn!(dev, "The GSP won't be able to unload properly on unbind.\n");
-            dev_warn!(
-                dev,
-                "The GPU will need to be reset before the driver can bind again.\n"
-            );
+        let unload_bundle = hal
+            .boot(&self, &mut ctx, &fb_layout, &wpr_meta)?
+            .or_else(|| {
+                dev_warn!(dev, "The GSP won't be able to unload properly on unbind.\n");
+                dev_warn!(
+                    dev,
+                    "The GPU will need to be reset before the driver can bind again.\n"
+                );
 
-            None
-        });
+                None
+            });
 
-        let unload_guard =
+        let mut unload_guard =
             ScopeGuard::new_with_data((ctx, unload_bundle), |(ctx, unload_bundle)| {
                 let _ = self.unload(ctx, unload_bundle);
             });
-        let ctx = &unload_guard.0;
+        let ctx = &mut unload_guard.0;
 
         gsp_falcon.write_os_version(gsp_fw.bootloader.app_version);
 
@@ -123,7 +125,7 @@ fn shutdown_gsp(
     /// This stops all activity on the GSP.
     pub(crate) fn unload(
         &self,
-        ctx: super::GspBootContext<'_>,
+        mut ctx: super::GspBootContext<'_>,
         unload_bundle: Option<super::UnloadBundle>,
     ) -> Result {
         let dev = ctx.dev();
@@ -142,7 +144,7 @@ pub(crate) fn unload(
             res = res.and(
                 unload_bundle
                     .0
-                    .run(&ctx)
+                    .run(&mut ctx)
                     .inspect_err(|e| dev_err!(dev, "Unload bundle failed: {:?}\n", e)),
             );
         } else {
drivers/gpu/nova-core/gsp/hal.rs +8 -3
index 90f076f640e0..a5d0da05ef5f 100644
@@ -29,7 +29,7 @@
 /// required for unloading is prepared at load time, and stored here until it needs to be run.
 pub(super) trait UnloadBundle: Send {
     /// Performs the steps required to properly reset the GSP after it has been stopped.
-    fn run(&self, ctx: &GspBootContext<'_>) -> Result;
+    fn run(&self, ctx: &mut GspBootContext<'_>) -> Result;
 }
 
 /// Trait implemented by GSP HALs.
@@ -41,7 +41,7 @@ pub(super) trait GspHal: Send {
     fn boot(
         &self,
         gsp: &Gsp,
-        ctx: &GspBootContext<'_>,
+        ctx: &mut GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
     ) -> Result<Option<crate::gsp::UnloadBundle>>;
@@ -50,7 +50,12 @@ fn boot(
     ///
     /// This method is called by the GSP boot code after the GSP is confirmed to be running, and
     /// after the initialization commands have been pushed onto its queue.
-    fn post_boot(&self, _gsp: &Gsp, _ctx: &GspBootContext<'_>, _gsp_fw: &GspFirmware) -> Result {
+    fn post_boot(
+        &self,
+        _gsp: &Gsp,
+        _ctx: &mut GspBootContext<'_>,
+        _gsp_fw: &GspFirmware,
+    ) -> Result {
         Ok(())
     }
 }
drivers/gpu/nova-core/gsp/hal/gh100.rs +2 -2
index 411b06c22fa0..45ba8e6c15a7 100644
@@ -114,7 +114,7 @@ fn wait_for_gsp_lockdown_release(
 struct FspUnloadBundle;
 
 impl UnloadBundle for FspUnloadBundle {
-    fn run(&self, ctx: &GspBootContext<'_>) -> Result {
+    fn run(&self, ctx: &mut GspBootContext<'_>) -> Result {
         // GSP falcon does most of the work of resetting, so just wait for it to finish.
         read_poll_timeout(
             || Ok(ctx.gsp_falcon.is_riscv_active()),
@@ -137,7 +137,7 @@ impl GspHal for Gh100 {
     fn boot(
         &self,
         gsp: &Gsp,
-        ctx: &GspBootContext<'_>,
+        ctx: &mut GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
     ) -> Result<Option<crate::gsp::UnloadBundle>> {
drivers/gpu/nova-core/gsp/hal/tu102.rs +3 -3
index 68274367c70d..4fb82350aad6 100644
@@ -78,7 +78,7 @@ struct Sec2UnloadBundle {
 }
 
 impl UnloadBundle for Sec2UnloadBundle {
-    fn run(&self, ctx: &GspBootContext<'_>) -> Result {
+    fn run(&self, ctx: &mut GspBootContext<'_>) -> Result {
         let dev = ctx.dev();
         let bar = ctx.bar;
 
@@ -260,7 +260,7 @@ impl GspHal for Tu102 {
     fn boot(
         &self,
         gsp: &Gsp,
-        ctx: &GspBootContext<'_>,
+        ctx: &mut GspBootContext<'_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
     ) -> Result<Option<crate::gsp::UnloadBundle>> {
@@ -316,7 +316,7 @@ fn boot(
         Ok(unload_guard.dismiss())
     }
 
-    fn post_boot(&self, gsp: &Gsp, ctx: &GspBootContext<'_>, gsp_fw: &GspFirmware) -> Result {
+    fn post_boot(&self, gsp: &Gsp, ctx: &mut GspBootContext<'_>, gsp_fw: &GspFirmware) -> Result {
         GspSequencer::run(
             &gsp.cmdq,
             ctx,
Signature · 1 line
2.54.0
Reviewed-by on v4 11/13
#27 lore raw

Re: [PATCH v4 11/13] gpu: nova-core: gsp: pass GspBootContext mutably

Quoted 5 lines · Alexandre Courbot

We want to move the Fsp instance into Gpu, which will require passing it as a mutable reference in GspBootContext, since Fsp::boot_fmc is a mutable method. In order to use the mutable references it contains, GspBootContext must also be mutable.

Quoted 8 lines

We will also follow up by making some methods of the Falcons mutable, which also requires passing them as mutable references.

Thus, make the GspBootContext passed to Gsp::boot and Gsp::unload mutable, and pass mutable references to it to the GSP boot HAL methods.

---

author maintainer
#28 lore raw

PATCH v4 12/13 gpu: nova-core: gsp: separate context and GPU lifetimes in GspBootContext

In reply to Alexandre Courbot

Falcon instances retain references tied to the lifetime of the bound GPU. GspBootContext currently uses that same lifetime for its own borrows of the Falcon instances and other references.

But these lifetimes are independent: the references captured by a Falcon remain valid for the GPU lifetime, while the context only borrows the Falcon for the duration of a boot or unload operation. This distinction is hidden for shared references by covariance, but cannot be ignored anymore if the context carries mutable references to GPU subdevices, as will happen for the Fsp and the Falcons.

Thus, give GspBootContext separate lifetimes for its subdevice borrows and the GPU resources captured by those subdevices, and update its users accordingly.

---
 drivers/gpu/nova-core/gsp.rs           | 19 ++++++++++++-------
 drivers/gpu/nova-core/gsp/boot.rs      |  4 ++--
 drivers/gpu/nova-core/gsp/hal.rs       |  6 +++---
 drivers/gpu/nova-core/gsp/hal/gh100.rs |  4 ++--
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 11 ++++++++---
 drivers/gpu/nova-core/gsp/sequencer.rs |  2 +-
 6 files changed, 28 insertions(+), 18 deletions(-)
drivers/gpu/nova-core/gsp.rs +12 -7
index cad851e68685..c2d7a557310a 100644
@@ -56,16 +56,21 @@
 pub(crate) const GSP_PAGE_SIZE: usize = 1 << GSP_PAGE_SHIFT;
 
 /// Common context for the GSP boot process.
-pub(crate) struct GspBootContext<'a> {
-    pub(crate) pdev: &'a pci::Device<device::Bound>,
-    pub(crate) bar: Bar0<'a>,
+///
+/// It carries two distinct lifetimes:
+///
+/// - `'gpu` is the lifetime of the bound GPU device, as captured by the GPU subdevices.
+/// - `'ctx` is a shorter lifetime during which this context borrows those subdevices.
+pub(crate) struct GspBootContext<'ctx, 'gpu> {
+    pub(crate) pdev: &'gpu pci::Device<device::Bound>,
+    pub(crate) bar: Bar0<'gpu>,
     pub(crate) chipset: Chipset,
-    pub(crate) gsp_falcon: &'a Falcon<'a, GspFalcon>,
-    pub(crate) sec2_falcon: &'a Falcon<'a, Sec2Falcon>,
+    pub(crate) gsp_falcon: &'ctx Falcon<'gpu, GspFalcon>,
+    pub(crate) sec2_falcon: &'ctx Falcon<'gpu, Sec2Falcon>,
 }
 
-impl<'a> GspBootContext<'a> {
-    pub(crate) fn dev(&self) -> &'a device::Device<device::Bound> {
+impl<'ctx, 'gpu> GspBootContext<'ctx, 'gpu> {
+    pub(crate) fn dev(&self) -> &'gpu device::Device<device::Bound> {
         self.pdev.as_ref()
     }
 }
drivers/gpu/nova-core/gsp/boot.rs +2 -2
index f093e0215b66..c347558aa8e5 100644
@@ -39,7 +39,7 @@ impl super::Gsp {
     /// [`Self::unload`]) returned.
     pub(crate) fn boot(
         self: Pin<&mut Self>,
-        mut ctx: super::GspBootContext<'_>,
+        mut ctx: super::GspBootContext<'_, '_>,
     ) -> Result<Option<super::UnloadBundle>> {
         let pdev = ctx.pdev;
         let bar = ctx.bar;
@@ -125,7 +125,7 @@ fn shutdown_gsp(
     /// This stops all activity on the GSP.
     pub(crate) fn unload(
         &self,
-        mut ctx: super::GspBootContext<'_>,
+        mut ctx: super::GspBootContext<'_, '_>,
         unload_bundle: Option<super::UnloadBundle>,
     ) -> Result {
         let dev = ctx.dev();
drivers/gpu/nova-core/gsp/hal.rs +3 -3
index a5d0da05ef5f..46428c623087 100644
@@ -29,7 +29,7 @@
 /// required for unloading is prepared at load time, and stored here until it needs to be run.
 pub(super) trait UnloadBundle: Send {
     /// Performs the steps required to properly reset the GSP after it has been stopped.
-    fn run(&self, ctx: &mut GspBootContext<'_>) -> Result;
+    fn run(&self, ctx: &mut GspBootContext<'_, '_>) -> Result;
 }
 
 /// Trait implemented by GSP HALs.
@@ -41,7 +41,7 @@ pub(super) trait GspHal: Send {
     fn boot(
         &self,
         gsp: &Gsp,
-        ctx: &mut GspBootContext<'_>,
+        ctx: &mut GspBootContext<'_, '_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
     ) -> Result<Option<crate::gsp::UnloadBundle>>;
@@ -53,7 +53,7 @@ fn boot(
     fn post_boot(
         &self,
         _gsp: &Gsp,
-        _ctx: &mut GspBootContext<'_>,
+        _ctx: &mut GspBootContext<'_, '_>,
         _gsp_fw: &GspFirmware,
     ) -> Result {
         Ok(())
drivers/gpu/nova-core/gsp/hal/gh100.rs +2 -2
index 45ba8e6c15a7..2805a35abb79 100644
@@ -114,7 +114,7 @@ fn wait_for_gsp_lockdown_release(
 struct FspUnloadBundle;
 
 impl UnloadBundle for FspUnloadBundle {
-    fn run(&self, ctx: &mut GspBootContext<'_>) -> Result {
+    fn run(&self, ctx: &mut GspBootContext<'_, '_>) -> Result {
         // GSP falcon does most of the work of resetting, so just wait for it to finish.
         read_poll_timeout(
             || Ok(ctx.gsp_falcon.is_riscv_active()),
@@ -137,7 +137,7 @@ impl GspHal for Gh100 {
     fn boot(
         &self,
         gsp: &Gsp,
-        ctx: &mut GspBootContext<'_>,
+        ctx: &mut GspBootContext<'_, '_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
     ) -> Result<Option<crate::gsp::UnloadBundle>> {
drivers/gpu/nova-core/gsp/hal/tu102.rs +8 -3
index 4fb82350aad6..2b489df6d0aa 100644
@@ -78,7 +78,7 @@ struct Sec2UnloadBundle {
 }
 
 impl UnloadBundle for Sec2UnloadBundle {
-    fn run(&self, ctx: &mut GspBootContext<'_>) -> Result {
+    fn run(&self, ctx: &mut GspBootContext<'_, '_>) -> Result {
         let dev = ctx.dev();
         let bar = ctx.bar;
 
@@ -260,7 +260,7 @@ impl GspHal for Tu102 {
     fn boot(
         &self,
         gsp: &Gsp,
-        ctx: &mut GspBootContext<'_>,
+        ctx: &mut GspBootContext<'_, '_>,
         fb_layout: &FbLayout,
         wpr_meta: &Coherent<GspFwWprMeta>,
     ) -> Result<Option<crate::gsp::UnloadBundle>> {
@@ -316,7 +316,12 @@ fn boot(
         Ok(unload_guard.dismiss())
     }
 
-    fn post_boot(&self, gsp: &Gsp, ctx: &mut GspBootContext<'_>, gsp_fw: &GspFirmware) -> Result {
+    fn post_boot(
+        &self,
+        gsp: &Gsp,
+        ctx: &mut GspBootContext<'_, '_>,
+        gsp_fw: &GspFirmware,
+    ) -> Result {
         GspSequencer::run(
             &gsp.cmdq,
             ctx,
drivers/gpu/nova-core/gsp/sequencer.rs +1 -1
index ddce32cc4e30..422a74f9ecbd 100644
@@ -335,7 +335,7 @@ fn next(&mut self) -> Option<Self::Item> {
 impl<'a> GspSequencer<'a> {
     pub(crate) fn run(
         cmdq: &Cmdq,
-        ctx: &'a GspBootContext<'_>,
+        ctx: &'a GspBootContext<'_, '_>,
         libos_dma_handle: u64,
         bootloader_app_version: u32,
     ) -> Result {
Signature · 1 line
2.54.0
#29 lore raw

Re: [PATCH v4 12/13] gpu: nova-core: gsp: separate context and GPU lifetimes in GspBootContext

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Incomplete lifetime separation in `GspSequencer` defeats the preparatory purpose of the commit. --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Incomplete lifetime separation in GspSequencer defeats the preparatory purpose of the commit. --

commit e32fe8760a6faf814fee0f0f066cd958f9319386
Author: Alexandre Courbot <[email protected]>

gpu: nova-core: gsp: separate context and GPU lifetimes in GspBootContext

This commit separates the lifetimes of GPU-bound resources and the context borrowing them in GspBootContext. This distinction is necessary because the context will eventually carry mutable references, making the lifetimes invariant.

[ ... ]

drivers/gpu/nova-core/gsp/sequencer.rs fn next(&mut self) -> Option<Self::Item> { · line 338

Quoted 10 lines
drivers/gpu/nova-core/gsp/sequencer.rs +1 -1
index ddce32cc4e308..422a74f9ecbd5 100644
@@ -335,7 +335,7 @@ fn next(&mut self) -> Option<Self::Item> {
 impl<'a> GspSequencer<'a> {
     pub(crate) fn run(
         cmdq: &Cmdq,
-        ctx: &'a GspBootContext<'_>,
+        ctx: &'a GspBootContext<'_, '_>,

[Severity: Low]
Does GspSequencer also need to be updated to use separated lifetimes?

Looking at the struct definition for GspSequencer in this file, it still stores the Falcon references using a single 'a lifetime, such as:
sec2_falcon: &'a Falcon<'a, Sec2>.

While this currently compiles because immutable references are covariant, it recouples the context and GPU lifetimes that were separated in GspBootContext.

When the Falcon references are later made mutable as the commit message indicates, they will become invariant. At that point, this conflated lifetime in GspSequencer will cause a compilation error.

Should GspSequencer be updated to use 'ctx and 'gpu as well?

Quoted 3 lines
drivers/gpu/nova-core/gsp/sequencer.rs +0 -0
         libos_dma_handle: u64,
         bootloader_app_version: u32,
     ) -> Result {
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
Reviewed-by on v4 12/13
#30 lore raw

Re: [PATCH v4 12/13] gpu: nova-core: gsp: separate context and GPU lifetimes in GspBootContext

In reply to Alexandre Courbot
Quoted 11 lines · Alexandre Courbot

Falcon instances retain references tied to the lifetime of the bound GPU. GspBootContext currently uses that same lifetime for its own borrows of the Falcon instances and other references.

But these lifetimes are independent: the references captured by a Falcon remain valid for the GPU lifetime, while the context only borrows the Falcon for the duration of a boot or unload operation. This distinction is hidden for shared references by covariance, but cannot be ignored anymore if the context carries mutable references to GPU subdevices, as will happen for the Fsp and the Falcons.

Quoted 6 lines

Thus, give GspBootContext separate lifetimes for its subdevice borrows and the GPU resources captured by those subdevices, and update its users accordingly.

---

author maintainer
#31 lore raw

PATCH v4 13/13 gpu: nova-core: store Fsp instance in Gpu

In reply to Alexandre Courbot

The Fsp instance was only used in the Hopper+ boot path, and consequently built locally (and immediately dropped) in it.

This worked well as a temporary measure, but the FSP is a GPU sub-device, so its lifetime should match the GPU rather than a single boot invocation.

It will also be needed in other parts of the driver, for instance vGPU.

Thus, create the Fsp instance in the Gpu constructor and store it there, passing it to the GSP boot as a mutable reference using GspBootContext. This makes the Fsp available even after the GSP is booted.

---
 drivers/gpu/nova-core/gpu.rs           | 15 ++++++++++++++-
 drivers/gpu/nova-core/gsp.rs           |  2 ++
 drivers/gpu/nova-core/gsp/hal/gh100.rs |  8 ++------
 3 files changed, 18 insertions(+), 7 deletions(-)
drivers/gpu/nova-core/gpu.rs +14 -1
index 663e61d0c023..c0c0c82e3e39 100644
@@ -22,11 +22,13 @@
         Falcon, //
     },
     fb::SysmemFlush,
+    fsp::Fsp,
     gsp::{
         self,
         commands::GetGspStaticInfoReply,
         Gsp,
-        GspBootContext, //
+        GspBootContext,
+        GspBootMethod, //
     },
     regs,
 };
@@ -262,6 +264,10 @@ struct GspResources<'gpu> {
     gsp_falcon: Falcon<'gpu, GspFalcon>,
     /// SEC2 falcon instance, used for GSP boot up and cleanup.
     sec2_falcon: Falcon<'gpu, Sec2Falcon>,
+    /// FSP instance, if on an arch that supports it.
+    // TODO: use different resource types for each boot method, and make the relevant Gsp methods
+    // generic against them.
+    fsp: Option<Fsp<'gpu>>,
     /// GSP runtime data.
     #[pin]
     gsp: Gsp,
@@ -305,6 +311,7 @@ fn drop(self: Pin<&mut Self>) {
                     chipset: this.spec.chipset,
                     gsp_falcon: &*this.gsp_falcon,
                     sec2_falcon: &*this.sec2_falcon,
+                    fsp: this.fsp.as_mut(),
                 },
                 bundle,
             )
@@ -356,6 +363,11 @@ pub(crate) fn new(
 
                 sec2_falcon: Falcon::new(dev, spec.chipset, bar)?,
 
+                fsp: match spec.chipset.gsp_boot_method() {
+                    GspBootMethod::Sec2 { .. } => None,
+                    GspBootMethod::Fsp => Some(Fsp::wait_secure_boot(dev, bar, spec.chipset)?),
+                },
+
                 gsp <- Gsp::new(pdev),
 
                 // This member must be initialized last, so the `UnloadBundle` can never be dropped
@@ -367,6 +379,7 @@ pub(crate) fn new(
                     chipset: spec.chipset,
                     gsp_falcon,
                     sec2_falcon,
+                    fsp: fsp.as_mut(),
                 })?,
             }),
 
drivers/gpu/nova-core/gsp.rs +2 -0
index c2d7a557310a..e89366b425fb 100644
@@ -38,6 +38,7 @@
         sec2::Sec2 as Sec2Falcon,
         Falcon, //
     },
+    fsp::Fsp,
     gpu::{
         Architecture,
         Chipset, //
@@ -67,6 +68,7 @@ pub(crate) struct GspBootContext<'ctx, 'gpu> {
     pub(crate) chipset: Chipset,
     pub(crate) gsp_falcon: &'ctx Falcon<'gpu, GspFalcon>,
     pub(crate) sec2_falcon: &'ctx Falcon<'gpu, Sec2Falcon>,
+    pub(crate) fsp: Option<&'ctx mut Fsp<'gpu>>,
 }
 
 impl<'ctx, 'gpu> GspBootContext<'ctx, 'gpu> {
drivers/gpu/nova-core/gsp/hal/gh100.rs +2 -6
index 2805a35abb79..de786871c8ec 100644
@@ -16,10 +16,7 @@
         Falcon, //
     },
     fb::FbLayout,
-    fsp::{
-        FmcBootArgs,
-        Fsp, //
-    },
+    fsp::FmcBootArgs,
     gsp::{
         hal::{
             GspHal,
@@ -142,7 +139,6 @@ fn boot(
         wpr_meta: &Coherent<GspFwWprMeta>,
     ) -> Result<Option<crate::gsp::UnloadBundle>> {
         let dev = ctx.dev();
-        let bar = ctx.bar;
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
 
@@ -150,7 +146,7 @@ fn boot(
             KBox::new(FspUnloadBundle, GFP_KERNEL)? as KBox<dyn UnloadBundle>
         );
 
-        let mut fsp = Fsp::wait_secure_boot(dev, bar, chipset)?;
+        let fsp = ctx.fsp.as_mut().ok_or(ENODEV)?;
 
         let args = FmcBootArgs::new(
             dev,
Signature · 1 line
2.54.0
#32 lore raw

Re: [PATCH v4 13/13] gpu: nova-core: store Fsp instance in Gpu

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [Critical] DMA Use-After-Free due to freeing buffers while GSP is still active on timeout --

commit ad8609a0c320b89583cef07a17ca5ce5c85167ea
Author: Alexandre Courbot <[email protected]>

gpu: nova-core: store Fsp instance in Gpu

The Fsp instance was only used in the Hopper+ boot path, and consequently built locally (and immediately dropped) in it.

This worked well as a temporary measure, but the FSP is a GPU sub-device, so its lifetime should match the GPU rather than a single boot invocation.

Quoted 4 lines
drivers/gpu/nova-core/gsp/hal/gh100.rs +0 -0
index 2805a35abb798..de786871c8ec4 100644

[ ... ]

drivers/gpu/nova-core/gsp/hal/gh100.rs fn boot( · line 152

Quoted 9 lines
drivers/gpu/nova-core/gsp/hal/gh100.rs +1 -1
@@ -150,7 +146,7 @@ fn boot(
             KBox::new(FspUnloadBundle, GFP_KERNEL)? as KBox<dyn UnloadBundle>
         );
 
-        let mut fsp = Fsp::wait_secure_boot(dev, bar, chipset)?;
+        let fsp = ctx.fsp.as_mut().ok_or(ENODEV)?;
 
         let args = FmcBootArgs::new(
             dev,

[Severity: Critical]
This is a pre-existing issue, but I wanted to ask about the error handling in this function and how it affects DMA buffers.

If wait_for_gsp_lockdown_release() times out later in Gh100::boot(), the ? operator causes an early return:

        let res = fsp.boot_fmc(dev, fb_layout, &args);

        wait_for_gsp_lockdown_release(dev, gsp_falcon, args.boot_params_dma_handle())?;

When this happens, args is dropped, and the error propagates back to Gsp::boot(), which bypasses the unload_guard creation and immediately drops wpr_meta:

let unload_bundle = hal
.boot(&self, &mut ctx, &fb_layout, &wpr_meta)?

Dropping these structures frees their underlying DMA memory. However, since the timeout occurred, the GSP hardware is not forcefully halted.

A similar issue appears during the unload path in FspUnloadBundle::run(). If a timeout occurs while waiting for RISC-V to halt, the code explicitly detects that the engine is still active but returns an error without forcefully halting it:

        read_poll_timeout(
            || Ok(ctx.gsp_falcon.is_riscv_active()),
            |&active| !active,
            Delta::from_millis(10),
            Delta::from_secs(5),
        )
        .map(|_| ())
        .inspect_err(|_| dev_err!(ctx.dev(), "GSP falcon failed to halt\n"))

Since the error propagates and allows the DMA memory to be freed while the engine continues executing, could the active GSP hardware write to the freed host memory and cause memory corruption?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
Reviewed-by on v4 13/13
#33 lore raw

Re: [PATCH v4 13/13] gpu: nova-core: store Fsp instance in Gpu

In reply to Alexandre Courbot
Quoted 9 lines · Alexandre Courbot

The Fsp instance was only used in the Hopper+ boot path, and consequently built locally (and immediately dropped) in it.

This worked well as a temporary measure, but the FSP is a GPU sub-device, so its lifetime should match the GPU rather than a single boot invocation.

It will also be needed in other parts of the driver, for instance vGPU.

Quoted 7 lines

Thus, create the Fsp instance in the Gpu constructor and store it there, passing it to the GSP boot as a mutable reference using GspBootContext. This makes the Fsp available even after the GSP is booted.

---