Skip to contentSkip to conversation

gpu: nova-core: boot on the r000 GSP firmware

PATCH In review John Hubbard 4 participants 77 messages Sep 18 – Oct 1

Subsystems (8)
lore
Share & tools
lore
#0 lore raw

v3 cover gpu: nova-core: boot on the r000 GSP firmware

This series moves nova-core from the r570 GSP (GPU System Processor) firmware onto the ABI that the r615 and later firmware releases share. The driver calls that ABI "r000", because the firmware files carry no version number in their names.

This should boot up on firmware extracted from NVIDIA's very recent publicly released r615 branch, although my testing has been so far on a slightly modified version of that, which Timur Tabi is working on making publicly available for anyone who is hacking on nova-core. The changes are small things for ABI stability for vGPU and don't affect this series.

The GSP runs only one set (version) of firmware at a time, so patch 27 makes the one-commit change over to use r000 firmware. Every patch before patch 27 still boots r570.

In other words, it is safe to merge this patchset, once reviewers are happy with it, because publicly available firmware now exists for it.

I've tested on Turing, Ampere, and Blackwell on a single x86_64 test machine, so far: nova-core dmesg excerpt:

0000:c1:00.0: NVIDIA T400 4GB
0000:c2:00.0: NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition 0000:01:00.0: NVIDIA RTX A4000

Changes in v3:

* Grouped the series into consecuitive sets of patches, each doing something related, per Alex and Eliot.

* The three radix3 patches have been removed and sent out as a separate prerequisite own series.

* The four debug-logging patches have been dropped (I have them ready to post as a follow-up series, though).

* The big switch-to-r000 patch is smaller and much simpler and therefore much easier to review.

* Every commit message and code comment has been rewritten (more than once, in some cases), with a much stronger focus on making it easily readable.

* A refactoring pass over the whole series, with each defect fixed in the patch that introduced it. Most of the fixes either merge duplicated code into shared helpers or move code to the type that owns it.

* Improved how the switch to msgq v2 is done.

The 33 patches come in groups:

* Patches 1 through 8: prerequisites. They add a PCI domain accessor, the MCTP header version, the r000 bindings and the msgq v2 registers, and they prepare the queue code for msgq v2 and for a second kind of element header.

* Patches 9 through 12: the GMC API types and their send and receive paths.

* Patches 13 through 18: the two load-and-execute boot events and their dispatcher.

* Patches 19 through 26: the static configuration returned from boot, the GSP_INIT request and reply, the LIBOS log and state buffers, the ucodes image, the GSP HAL method that loads the generic bootloader for the load-and-execute handler, and the GSP_SUSPEND request.

* Patches 27 through 29: the switch to r000, the cleanup that makes the decoded GSP_INIT reply the static configuration type, and the deletion of the r570 bindings. The switch patch also adds the larger framebuffer reservations that r000 requires on GB100 and GB20x.

* Patches 30 through 33: the receive path hardening. The receive path matches an RPC reply by sequence number, decodes each element by its NVDM type, and matches a GMC response by flag, id and sequence.

The series applies on top of drm-rust-next plus four dependencies:

* the interrupt tree series for GIN, the GPU Interrupt and Notification unit [1]
* Eliot Courtney's NVKV codec series [2]
* the three-patch radix3 cleanup [3]
* two lint fixes for the generated bindings, both already in mainline

A branch with everything applied:

    https://github.com/johnhubbard/linux/tree/nova-core-run-on-r615-or-later-v3/

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

John Hubbard (32):
rust: pci: add domain_nr() accessor
gpu: nova-core: set MCTP transport header version to 1
gpu: nova-core: gsp: give the command queue its own BAR0 mapping
gpu: nova-core: firmware: add r000 bindings
gpu: nova-core: regs: add msgq v2 BAR0 register declarations
gpu: nova-core: gsp: ring the GSP doorbell from the queue memory
gpu: nova-core: gsp: make command allocation generic over the header
gpu: nova-core: gsp: compute the queue regions from a count and a slot
gpu: nova-core: add GMC API message types
gpu: nova-core: add GMC send path
gpu: nova-core: add GMC transport receive path
gpu: nova-core: gsp: add GMC dispatch on receive
gpu: nova-core: separate the generic falcon bootloader from FWSEC
gpu: nova-core: add the falcon DMA and suspend helpers for r000 boot
gpu: nova-core: add the r000 load-and-execute HS binary handler
gpu: nova-core: move the bootloader DMEM descriptor out of FWSEC
gpu: nova-core: add the r000 load-and-execute bootloader handler
gpu: nova-core: gsp: add the GMC boot event dispatcher
gpu: nova-core: gsp: rename the static configuration type
gpu: nova-core: gsp: return the static GPU configuration from boot
gpu: nova-core: gsp: add the GSP_INIT request builder
gpu: nova-core: gsp: send GSP_INIT and decode its reply
gpu: nova-core: add LIBOS3 log buffers and state monitor buffer
gpu: nova-core: add the ucodes firmware loader
gpu: nova-core: gsp: let the GSP HAL load the generic bootloader
gpu: nova-core: gsp: add the GSP_SUSPEND request
gpu: nova-core: switch to the r000 GSP firmware
gpu: nova-core: gsp: make the GSP_INIT reply the static configuration
gpu: nova-core: firmware: delete the r570 bindings
gpu: nova-core: match GSP RPC replies by sequence, not just function
gpu: nova-core: gsp: split the reply match out of the RPC receive path
gpu: nova-core: gsp: decode queue elements by their NVDM type

Zhi Wang (1):
gpu: nova-core: gsp: match a GMC response by flag, id and sequence

 Documentation/gpu/nova/core/fsp.rst           |    2 +
 Documentation/gpu/nova/core/interrupts.rst    |   41 +-
 drivers/gpu/nova-core/falcon.rs               |  203 +++-
 drivers/gpu/nova-core/falcon/gsp.rs           |   10 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs         |   24 +-
 drivers/gpu/nova-core/fb/hal/gb202.rs         |    6 +-
 drivers/gpu/nova-core/firmware.rs             |    8 +-
 drivers/gpu/nova-core/firmware/bindata.rs     |   58 +
 .../nova-core/firmware/fwsec/bootloader.rs    |  160 +--
 .../gpu/nova-core/firmware/gen_bootloader.rs  |  216 ++++
 drivers/gpu/nova-core/firmware/gsp.rs         |   15 +-
 drivers/gpu/nova-core/firmware/tlv.rs         |   40 +-
 drivers/gpu/nova-core/fsp.rs                  |    3 +-
 drivers/gpu/nova-core/gpu.rs                  |   52 +-
 drivers/gpu/nova-core/gsp.rs                  |  156 ++-
 drivers/gpu/nova-core/gsp/boot.rs             |  483 +++++++-
 drivers/gpu/nova-core/gsp/cmdq.rs             | 1036 +++++++++++------
 drivers/gpu/nova-core/gsp/commands.rs         |  368 ++----
 drivers/gpu/nova-core/gsp/fw.rs               |  832 ++++++-------
 drivers/gpu/nova-core/gsp/fw/commands.rs      |  405 ++++---
 .../gsp/fw/{r570_144.rs => r000_00.rs}        |   10 +-
 .../gsp/fw/{r570_144 => r000_00}/bindings.rs  |  691 ++++-------
 drivers/gpu/nova-core/gsp/hal.rs              |   32 +-
 drivers/gpu/nova-core/gsp/hal/tu102.rs        |   24 +-
 drivers/gpu/nova-core/gsp/regs.rs             |   19 +
 drivers/gpu/nova-core/gsp/sequencer.rs        |  379 ------
 drivers/gpu/nova-core/mctp.rs                 |   33 +-
 drivers/gpu/nova-core/mm.rs                   |    4 +-
 drivers/gpu/nova-core/regs.rs                 |    9 +-
 drivers/gpu/nova-core/sbuffer.rs              |    2 +-
 rust/helpers/pci.c                            |    5 +
 rust/kernel/pci.rs                            |   12 +
 32 files changed, 2973 insertions(+), 2365 deletions(-)
 create mode 100644 drivers/gpu/nova-core/firmware/bindata.rs
 create mode 100644 drivers/gpu/nova-core/firmware/gen_bootloader.rs
 rename drivers/gpu/nova-core/gsp/fw/{r570_144.rs => r000_00.rs} (71%)
 rename drivers/gpu/nova-core/gsp/fw/{r570_144 => r000_00}/bindings.rs (71%)
 delete mode 100644 drivers/gpu/nova-core/gsp/sequencer.rs
Signature · 1 line
2.55.0
#1 lore raw

PATCH v3 1/33 rust: pci: add domain_nr() accessor

The nova-core driver has to send the GPU's PCI location to the GPU's firmware as one word that holds the domain, the bus and the device number.

The PCI abstraction has dev_id(), which packs the bus, the device and the function into one value. It has no accessor that reports the domain.

Add an accessor for the domain number. pci_domain_nr() is a static inline, so it needs a C helper. The bus of a bound device always has a domain assigned, so a negative value would be a kernel bug rather than a condition to report. A debug assertion checks for it before the cast to u32, and the accessor returns no error.

---
 rust/helpers/pci.c |  5 +++++
 rust/kernel/pci.rs | 12 ++++++++++++
 2 files changed, 17 insertions(+)
rust/helpers/pci.c +5 -0
index 3686e405160d..53cdc7f36fef 100644
@@ -7,6 +7,11 @@ __rust_helper u16 rust_helper_pci_dev_id(struct pci_dev *dev)
 	return PCI_DEVID(dev->bus->number, dev->devfn);
 }
 
+__rust_helper int rust_helper_pci_domain_nr(struct pci_dev *dev)
+{
+	return pci_domain_nr(dev->bus);
+}
+
 __rust_helper resource_size_t
 rust_helper_pci_resource_start(struct pci_dev *pdev, int bar)
 {
rust/kernel/pci.rs +12 -0
index 19a219847c17..8d379a2d7c71 100644
@@ -400,6 +400,18 @@ pub fn dev_id(&self) -> u16 {
         unsafe { bindings::pci_dev_id(self.as_raw()) }
     }
 
+    /// Returns the PCI domain number of the bus that this device is on.
+    #[inline]
+    pub fn domain_nr(&self) -> u32 {
+        // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
+        // `struct pci_dev`.
+        let domain_nr = unsafe { bindings::pci_domain_nr(self.as_raw()) };
+        debug_assert!(domain_nr >= 0);
+
+        // CAST: `pci_domain_nr` returns a non-negative domain number in an `int`.
+        domain_nr as u32
+    }
+
     /// Returns the PCI subsystem vendor ID.
     #[inline]
     pub fn subsystem_vendor_id(&self) -> u16 {
Signature · 1 line
2.55.0
#2 lore raw

PATCH v3 2/33 gpu: nova-core: set MCTP transport header version to 1

In reply to John Hubbard

FSP, the GPU's Foundation Security Processor, receives the driver's messages as packets of MCTP, the Management Component Transport Protocol. It requires header version 1 in bits 3:0 of the MCTP transport header.

Nova-core left those bits at zero, so every Chain of Trust request and every Product Reconfiguration Control request that it sent carried an invalid transport header.

Declare the version field and set it. Declare the destination endpoint ID field as well. The driver leaves that field at zero.

---
 Documentation/gpu/nova/core/fsp.rst |  2 ++
 drivers/gpu/nova-core/mctp.rs       | 15 +++++++++++++--
 2 files changed, 15 insertions(+), 2 deletions(-)
Documentation/gpu/nova/core/fsp.rst +2 -0
index 52d618d22bb8..60c647181da0 100644
@@ -106,6 +106,8 @@ All FSP messages share a common header format consisting of two 32-bit words:
 - Bit 30: EOM (End of Message)
 - Bits 29:28: Packet sequence number
 - Bits 23:16: Source Endpoint ID
+- Bits 15:8: Destination Endpoint ID
+- Bits 3:0: MCTP header version (1)
 
 **NVDM header** (NVIDIA Vendor Defined Message):
 
drivers/gpu/nova-core/mctp.rs +13 -2
index 90c642c91a72..a3872a740233 100644
@@ -42,13 +42,24 @@ pub(crate) struct MctpHeader(u32) {
         29:28 seq;
         /// Source endpoint ID.
         23:16 seid;
+        /// Destination endpoint ID.
+        15:8 deid;
+        /// MCTP header version.
+        3:0 version;
     }
 }
 
 impl MctpHeader {
-    /// Builds a single-packet MCTP header (`SOM=1`, `EOM=1`, `SEQ=0`, `SEID=0`).
+    /// The MCTP header version that this driver uses.
+    const VERSION: u32 = 1;
+
+    /// Builds the MCTP header of a message that fits in one packet: `SOM` and `EOM` set, the
+    /// version set, and every other field zero.
     pub(crate) fn single_packet() -> Self {
-        Self::zeroed().with_som(true).with_eom(true)
+        Self::zeroed()
+            .with_const_version::<{ Self::VERSION }>()
+            .with_som(true)
+            .with_eom(true)
     }
 
     /// Returns whether this is a complete single-packet message (`SOM=1` and `EOM=1`).
Signature · 1 line
2.55.0
#3 lore raw

Re: [PATCH v3 02/33] gpu: nova-core: set MCTP transport header version to 1

Quoted 11 lines · John Hubbard

FSP, the GPU's Foundation Security Processor, receives the driver's messages as packets of MCTP, the Management Component Transport Protocol. It requires header version 1 in bits 3:0 of the MCTP transport header.

Nova-core left those bits at zero, so every Chain of Trust request and every Product Reconfiguration Control request that it sent carried an invalid transport header.

Declare the version field and set it. Declare the destination endpoint ID field as well. The driver leaves that field at zero.

If we declare this field we should assign a value to it - the fact that this value is 0, which happens to be the default, does not absolve us from setting it explicitly.

With that line added, this patch has been merged to drm-rust-next, thanks!

#4 lore raw

PATCH v3 3/33 gpu: nova-core: gsp: give the command queue its own BAR0 mapping

In reply to John Hubbard

Sending a command to the GSP ends by writing the GSP doorbell, a BAR0 register, so every send path through the command queue needs the BAR0 mapping. A command too large for one queue element goes out as a first element followed by continuation records, so the send path has four functions.

Nova-core passed the mapping down from the caller as an argument, which was threaded through all four functions, and every caller of a send had to carry it as well.

Store the mapping in the command queue and drop the argument. The queue lives exactly as long as the mapping does, since both belong to the bound device.

---
 drivers/gpu/nova-core/gpu.rs      |  4 ++--
 drivers/gpu/nova-core/gsp.rs      | 11 +++++++----
 drivers/gpu/nova-core/gsp/boot.rs | 10 +++-------
 drivers/gpu/nova-core/gsp/cmdq.rs | 24 ++++++++++++++----------
 4 files changed, 26 insertions(+), 23 deletions(-)
drivers/gpu/nova-core/gpu.rs +2 -2
index d1e0da7b8682..9e0570e97cfe 100644
@@ -414,7 +414,7 @@ pub(crate) fn new<'a>(
 
                 vgpu: VgpuManager::new(pdev, spec.chipset, fsp.as_mut()),
 
-                gsp <- Gsp::new(pdev),
+                gsp <- Gsp::new(pdev, bar),
 
                 // This member must be initialized last, so the `UnloadBundle` can never be dropped
                 // from outside of the constructed `GspResources`, ensuring that the unload sequence
@@ -456,7 +456,7 @@ pub(crate) fn new<'a>(
 
             gsp_static_info: {
                 // Obtain and display basic GPU information.
-                let info = gsp_resources.gsp.get_static_info(bar)?;
+                let info = gsp_resources.gsp.get_static_info()?;
                 match info.gpu_name() {
                     Ok(name) => dev_info!(dev, "GPU name: {}\n", name),
                     Err(e) => dev_warn!(dev, "GPU name unavailable: {:?}\n", e),
drivers/gpu/nova-core/gsp.rs +7 -4
index b85e0b6475f0..c9b7498639b7 100644
@@ -162,7 +162,10 @@ pub(crate) struct Gsp<'gsp> {
 
 impl<'gsp> Gsp<'gsp> {
     // Creates an in-place initializer for a `Gsp` manager for `pdev`.
-    pub(crate) fn new(pdev: &'gsp pci::Device<device::Bound>) -> impl PinInit<Self, Error> + 'gsp {
+    pub(crate) fn new(
+        pdev: &'gsp pci::Device<device::Bound>,
+        bar: Bar0<'gsp>,
+    ) -> impl PinInit<Self, Error> + 'gsp {
         pin_init::pin_init_scope(move || {
             let dev = pdev.as_ref();
 
@@ -174,7 +177,7 @@ pub(crate) fn new(pdev: &'gsp pci::Device<device::Bound>) -> impl PinInit<Self,
             // _kgspInitLibosLoggingStructures (allocates memory for buffers)
             // kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array)
             Ok(try_pin_init!(Self {
-                cmdq <- Cmdq::new(dev),
+                cmdq <- Cmdq::new(dev, bar),
                 rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
                 libos: {
                     let mut libos = CoherentBox::zeroed_slice(
@@ -218,8 +221,8 @@ pub(crate) fn new(pdev: &'gsp pci::Device<device::Bound>) -> impl PinInit<Self,
     }
 
     /// Query the GSP for the static GPU information.
-    pub(crate) fn get_static_info(&self, bar: Bar0<'_>) -> Result<commands::GetGspStaticInfoReply> {
-        self.cmdq.send_command(bar, commands::GetGspStaticInfo)
+    pub(crate) fn get_static_info(&self) -> Result<commands::GetGspStaticInfoReply> {
+        self.cmdq.send_command(commands::GetGspStaticInfo)
     }
 }
 
drivers/gpu/nova-core/gsp/boot.rs +3 -7
index 60bed3dc2f5a..4fb1b69ac9d5 100644
@@ -10,7 +10,6 @@
 };
 
 use crate::{
-    driver::Bar0,
     falcon::{
         gsp::Gsp,
         Falcon, //
@@ -36,7 +35,6 @@ pub(crate) fn boot(
         mut ctx: super::GspBootContext<'_, 'gsp>,
     ) -> Result<Option<super::UnloadBundle<'gsp>>> {
         let pdev = ctx.pdev;
-        let bar = ctx.bar;
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
         let dev = pdev.as_ref();
@@ -45,9 +43,9 @@ pub(crate) fn boot(
         let gsp_fw = KBox::pin_init(GspFirmware::new(dev, chipset), GFP_KERNEL)?;
 
         self.cmdq
-            .send_command_no_wait(bar, commands::SetSystemInfo::new(pdev, chipset))?;
+            .send_command_no_wait(commands::SetSystemInfo::new(pdev, chipset))?;
         self.cmdq
-            .send_command_no_wait(bar, commands::SetRegistry::new(ctx.vgpu.state())?)?;
+            .send_command_no_wait(commands::SetRegistry::new(ctx.vgpu.state())?)?;
 
         // Perform the chipset-specific boot sequence, and retrieve the unload bundle.
         let unload_bundle = hal.boot(&self, &mut ctx, &gsp_fw)?.or_else(|| {
@@ -89,12 +87,11 @@ pub(crate) fn boot(
     /// Shut down the GSP and wait until it is offline.
     fn shutdown_gsp(
         cmdq: &Cmdq<'_>,
-        bar: Bar0<'_>,
         gsp_falcon: &Falcon<'_, Gsp>,
         mode: commands::PowerStateLevel,
     ) -> Result {
         // Command to shut the GSP down.
-        cmdq.send_command(bar, commands::UnloadingGuestDriver::new(mode))?;
+        cmdq.send_command(commands::UnloadingGuestDriver::new(mode))?;
 
         // Wait until GSP signals it is suspended.
         const LIBOS_INTERRUPT_PROCESSOR_SUSPENDED: u32 = bits::bit_u32(31);
@@ -120,7 +117,6 @@ pub(crate) fn unload(
         // Shut down the GSP. Keep going even in case of error.
         let mut res = Self::shutdown_gsp(
             &self.cmdq,
-            ctx.bar,
             ctx.gsp_falcon,
             commands::PowerStateLevel::Level0,
         )
drivers/gpu/nova-core/gsp/cmdq.rs +14 -10
index f1231569aa33..9250d596a3e4 100644
@@ -532,6 +532,7 @@ impl<'cmdq> Cmdq<'cmdq> {
     /// Creates a new command queue for `dev`.
     pub(crate) fn new(
         dev: &'cmdq device::Device<device::Bound>,
+        bar: Bar0<'cmdq>,
     ) -> impl PinInit<Self, Error> + 'cmdq {
         pin_init_scope(move || {
             let gsp_mem = DmaGspMem::new(dev)?;
@@ -540,6 +541,7 @@ pub(crate) fn new(
                 dma_addr: gsp_mem.0.dma_address(),
                 inner <- new_mutex!(CmdqInner {
                     dev,
+                    bar,
                     gsp_mem,
                     seq: 0,
                     poisoned: Cell::new(false),
@@ -582,7 +584,7 @@ fn notify_gsp(bar: Bar0<'_>) {
     ///   written to by its [`CommandToGsp::init_variable_payload`] method.
     ///
     /// Error codes returned by the command and reply initializers are propagated as-is.
-    pub(crate) fn send_command<M>(&self, bar: Bar0<'_>, command: M) -> Result<M::Reply>
+    pub(crate) fn send_command<M>(&self, command: M) -> Result<M::Reply>
     where
         M: CommandToGsp,
         M::Reply: MessageFromGsp,
@@ -590,7 +592,7 @@ pub(crate) fn send_command<M>(&self, bar: Bar0<'_>, command: M) -> Result<M::Rep
         Error: From<<M::Reply as MessageFromGsp>::InitError>,
     {
         let mut inner = self.inner.lock();
-        inner.send_command(bar, command)?;
+        inner.send_command(command)?;
 
         inner.await_msg()
     }
@@ -604,12 +606,12 @@ pub(crate) fn send_command<M>(&self, bar: Bar0<'_>, command: M) -> Result<M::Rep
     ///   written to by its [`CommandToGsp::init_variable_payload`] method.
     ///
     /// Error codes returned by the command initializers are propagated as-is.
-    pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Result
+    pub(crate) fn send_command_no_wait<M>(&self, command: M) -> Result
     where
         M: CommandToGsp<Reply = NoReply>,
         Error: From<M::InitError>,
     {
-        self.inner.lock().send_command(bar, command)
+        self.inner.lock().send_command(command)
     }
 
     /// Waits for an unsolicited GSP event of type `M`. Events that arrive before it are logged and
@@ -652,6 +654,8 @@ pub(crate) fn drain(&self) -> Result {
 struct CmdqInner<'a> {
     /// Device this command queue belongs to.
     dev: &'a device::Device,
+    /// MMIO mapping of PCI BAR0, for writing the GSP doorbell.
+    bar: Bar0<'a>,
     /// Current command sequence number.
     seq: u32,
     /// Set once a message fails framing or checksum validation. Every later receive fails, since
@@ -678,7 +682,7 @@ impl CmdqInner<'_> {
     ///   written to by its [`CommandToGsp::init_variable_payload`] method.
     ///
     /// Error codes returned by the command initializers are propagated as-is.
-    fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
+    fn send_single_command<M>(&mut self, command: M) -> Result
     where
         M: CommandToGsp,
         // This allows all error types, including `Infallible`, to be used for `M::InitError`.
@@ -732,7 +736,7 @@ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
         let elem_count = dst.header.element_count();
         self.seq += 1;
         self.gsp_mem.advance_cpu_write_ptr(elem_count);
-        Cmdq::notify_gsp(bar);
+        Cmdq::notify_gsp(self.bar);
 
         Ok(())
     }
@@ -748,19 +752,19 @@ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
     ///   written to by its [`CommandToGsp::init_variable_payload`] method.
     ///
     /// Error codes returned by the command initializers are propagated as-is.
-    fn send_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
+    fn send_command<M>(&mut self, command: M) -> Result
     where
         M: CommandToGsp,
         Error: From<M::InitError>,
     {
         match SplitState::new(command)? {
-            SplitState::Single(command) => self.send_single_command(bar, command),
+            SplitState::Single(command) => self.send_single_command(command),
             SplitState::Split(command, mut continuations) => {
-                self.send_single_command(bar, command)?;
+                self.send_single_command(command)?;
 
                 while let Some(continuation) = continuations.next() {
                     // Turbofish needed because the compiler cannot infer M here.
-                    self.send_single_command::<ContinuationRecord<'_>>(bar, continuation)?;
+                    self.send_single_command::<ContinuationRecord<'_>>(continuation)?;
                 }
 
                 Ok(())
Signature · 1 line
2.55.0
#5 lore raw

Re: [PATCH v3 03/33] gpu: nova-core: gsp: give the command queue its own BAR0 mapping

Quoted 10 lines · John Hubbard

Sending a command to the GSP ends by writing the GSP doorbell, a BAR0 register, so every send path through the command queue needs the BAR0 mapping. A command too large for one queue element goes out as a first element followed by continuation records, so the send path has four functions.

Nova-core passed the mapping down from the caller as an argument, which was threaded through all four functions, and every caller of a send had to carry it as well.

Quoted 7 lines

Store the mapping in the command queue and drop the argument. The queue lives exactly as long as the mapping does, since both belong to the bound device.

This patch is merged into drm-rust-next, thanks! Less arguments is always nice to have.

#6 lore raw

PATCH v3 4/33 gpu: nova-core: firmware: add r000 bindings

In reply to John Hubbard

Nova-core boots the r570 GSP firmware, release 570.144. The GSP firmware releases from r615 onward share one ABI, and their firmware files carry no version number in their names, because each image records its version internally. The driver calls that ABI "r000", so that its name does not change with each release.

Add the bindings that bindgen generates from the r000 headers of Open RM, the open-source NVIDIA kernel driver. They have no user yet. The following patches build the r000 queue code, commands and boot event handlers on them, and the driver keeps compiling against the r570 bindings until the patch that switches firmware.

---
 drivers/gpu/nova-core/gsp/fw.rs               |   1 +
 drivers/gpu/nova-core/gsp/fw/r000_00.rs       |  29 +
 .../gpu/nova-core/gsp/fw/r000_00/bindings.rs  | 851 ++++++++++++++++++
 3 files changed, 881 insertions(+)
 create mode 100644 drivers/gpu/nova-core/gsp/fw/r000_00.rs
 create mode 100644 drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs
drivers/gpu/nova-core/gsp/fw.rs +1 -0
index 918a7ae809eb..285c23cea771 100644
@@ -2,6 +2,7 @@
 // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
 pub(crate) mod commands;
+mod r000_00;
 mod r570_144;
 
 // Alias to avoid repeating the version number with every use.
drivers/gpu/nova-core/gsp/fw/r000_00.rs new file +29 -0
new file mode 100644
index 000000000000..0c32f4ec1e27
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Bindings generated by `bindgen` from the r000 GSP firmware headers.
+//!
+//! Use them only through the parent module, which abstracts or re-exports the symbols that the
+//! driver needs.
+
+#![allow(
+    dead_code,
+    clippy::all,
+    clippy::undocumented_unsafe_blocks,
+    clippy::ptr_as_ptr,
+    clippy::ref_as_ptr,
+    missing_docs,
+    non_camel_case_types,
+    non_upper_case_globals,
+    non_snake_case,
+    improper_ctypes,
+    unreachable_pub,
+    unsafe_op_in_unsafe_fn
+)]
+use kernel::ffi;
+use pin_init::MaybeZeroable;
+
+include!("r000_00/bindings.rs");
+
+// SAFETY: This type has a size of zero, so its inclusion into another type should not affect their
+// ability to implement `Zeroable`.
+unsafe impl<T> kernel::prelude::Zeroable for __IncompleteArrayField<T> {}
drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs new file +851 -0

851 lines not on this page · raw message

Signature · 1 line
2.55.0
#7 lore raw

Re: [PATCH v3 04/33] gpu: nova-core: firmware: add r000 bindings

Quoted 8 lines · John Hubbard

Nova-core boots the r570 GSP firmware, release 570.144. The GSP firmware releases from r615 onward share one ABI, and their firmware files carry no version number in their names, because each image records its version internally. The driver calls that ABI "r000", so that its name does not change with each release.

Add the bindings that bindgen generates from the r000 headers of Open RM, the open-source NVIDIA kernel driver.

You should specify exactly which OpenRM version was used for this, because I suspect that some of these constants might change in future versions. The upcoming NVOC stuff will mitigate that, but it's still useful to be specific, just in case.

#8 lore raw

Re: [PATCH v3 04/33] gpu: nova-core: firmware: add r000 bindings

Quoted 7 lines · Timur Tabi
Quoted 6 lines · John Hubbard

Nova-core boots the r570 GSP firmware, release 570.144. The GSP firmware releases from r615 onward share one ABI, and their firmware files carry no version number in their names, because each image records its version internally. The driver calls that ABI "r000", so that its name does not change with each release.

Quoted 6 lines
Quoted 2 lines

Add the bindings that bindgen generates from the r000 headers of Open RM, the open-source NVIDIA kernel driver.

You should specify exactly which OpenRM version was used for this, because I suspect that some of these constants might change in future versions. The upcoming NVOC stuff will mitigate that, but it's still useful to be specific, just in case.

Yes, good point. I've verified that the bindgen with the publicly released r615 provides the same thing as here--as long as I delete one unused item from bindgen input. Which I've done for v4.

I'm about to re-test against stock r615 firmware, which I now realize would have been ideal to do earlier. I was feeling less optimistic about it at the time, but after looking at some details I think it will work for this patchset, just not necessarily for the follow-on series that Zhi Wang is posting for full vGPU.

thanks,

Signature · 1 line
John Hubbard
#9 lore raw

Re: [PATCH v3 04/33] gpu: nova-core: firmware: add r000 bindings

Quoted 19 lines · John Hubbard
Quoted 7 lines · Timur Tabi
Quoted 6 lines · John Hubbard

Nova-core boots the r570 GSP firmware, release 570.144. The GSP firmware releases from r615 onward share one ABI, and their firmware files carry no version number in their names, because each image records its version internally. The driver calls that ABI "r000", so that its name does not change with each release.

Quoted 6 lines
Quoted 2 lines

Add the bindings that bindgen generates from the r000 headers of Open RM, the open-source NVIDIA kernel driver.

You should specify exactly which OpenRM version was used for this, because I suspect that some of these constants might change in future versions. The upcoming NVOC stuff will mitigate that, but it's still useful to be specific, just in case.

Yes, good point. I've verified that the bindgen with the publicly released r615 provides the same thing as here--as long as I delete one unused item from bindgen input. Which I've done for v4.

Quoted 6 lines

I'm about to re-test against stock r615 firmware, which I now realize would have been ideal to do earlier. I was feeling less optimistic about it at the time, but after looking at some details I think it will work for this patchset, just not necessarily for the follow-on series that Zhi Wang is posting for full vGPU.

Good news, this series boots up on the stock, publicly released r615 firmware, just fine!

I tested Turing, Ampere and Blackwell GPUs:

PCIe Probe: PASS: Chipset info: all 3 GPUs OK

  ok   0000:c1:00.0: NVIDIA (Chipset: TU117, Architecture: Turing, Revision: a.1)
  ok   0000:c2:00.0: NVIDIA (Chipset: GB202, Architecture: BlackwellGB20x, Revision: a.1)
  ok   0000:01:00.0: NVIDIA (Chipset: GA104, Architecture: Ampere, Revision: a.1)

Interrupt Self-test: PASS: Interrupt self-test: all 3 GPUs OK

  ok   0000:c1:00.0: passed, subtree 2, 2 deliveries
  ok   0000:c2:00.0: passed, subtree 2, 2 deliveries
  ok   0000:01:00.0: passed, subtree 2, 2 deliveries

Get GPU Name: PASS: GPU name: all 3 GPUs OK

  ok   0000:c1:00.0: NVIDIA T400 4GB
  ok   0000:c2:00.0: NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition
  ok   0000:01:00.0: NVIDIA RTX A4000

thanks,

Signature · 1 line
John Hubbard
#10 lore raw

PATCH v3 5/33 gpu: nova-core: regs: add msgq v2 BAR0 register declarations

In reply to John Hubbard

Msgq is the pair of ring buffers in shared memory through which the driver and GSP-RM communicate. The command queue carries commands from the driver to GSP-RM, and the message queue carries messages from GSP-RM to the driver. Each ring buffer has a write pointer and a read pointer.

Msgq v0, which the r570 firmware uses, keeps both pointers of each ring buffer in that ring buffer's header, in shared memory. Msgq v2, which the r000 firmware uses, keeps the four pointers, two per ring buffer, in four BAR0 registers instead:

    NV_PGSP_QUEUE_HEAD    command queue write pointer
    NV_PGSP_QUEUE_TAIL    command queue read pointer
    NV_PGSP_MSGQ_HEAD     message queue write pointer
    NV_PGSP_MSGQ_TAIL     message queue read pointer

The GSP numbers its queues 0 through 7, and each numbered queue is one such pair of ring buffers with its own four pointer registers, so the hardware has 32 pointer registers in all. Nova-core uses queue 0 only.

A write to NV_PGSP_QUEUE_HEAD also interrupts the GSP. Msgq v0 uses that write as the doorbell, so nova-core already declares NV_PGSP_QUEUE_HEAD.

Declare the other three, NV_PGSP_QUEUE_TAIL, NV_PGSP_MSGQ_HEAD and NV_PGSP_MSGQ_TAIL, each as a scalar at its queue 0 offset rather than as an array of eight.

---
 drivers/gpu/nova-core/gsp/regs.rs | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
drivers/gpu/nova-core/gsp/regs.rs +19 -0
index 3c410d65e8e4..fae7825f0846 100644
@@ -8,13 +8,32 @@
 };
 
 // PGSP
+// The GSP has eight numbered queues, each with its own four msgq pointer registers. nova-core
+// uses queue 0 only, so each register is declared as a scalar at its queue 0 offset.
 
 register! {
     base: NovaRegisters;
 
+    /// Write pointer of the CPU-to-GSP command queue, which the driver advances. A write to this
+    /// register also interrupts the GSP, so this register is also the doorbell.
     pub(super) NV_PGSP_QUEUE_HEAD(u32) @ 0x00110c00 {
         31:0    address;
     }
+
+    /// Read pointer of the CPU-to-GSP command queue, which the GSP advances.
+    pub(super) NV_PGSP_QUEUE_TAIL(u32) @ 0x00110c04 {
+        31:0    address;
+    }
+
+    /// Write pointer of the GSP-to-CPU message queue, which the GSP advances.
+    pub(super) NV_PGSP_MSGQ_HEAD(u32) @ 0x00110c80 {
+        31:0    address;
+    }
+
+    /// Read pointer of the GSP-to-CPU message queue, which the driver advances.
+    pub(super) NV_PGSP_MSGQ_TAIL(u32) @ 0x00110c84 {
+        31:0    address;
+    }
 }
 
 // PBUS
Signature · 1 line
2.55.0
#11 lore raw

Re: [PATCH v3 05/33] gpu: nova-core: regs: add msgq v2 BAR0 register declarations

Quoted 19 lines · John Hubbard

Msgq is the pair of ring buffers in shared memory through which the driver and GSP-RM communicate. The command queue carries commands from the driver to GSP-RM, and the message queue carries messages from GSP-RM to the driver. Each ring buffer has a write pointer and a read pointer.

Msgq v0, which the r570 firmware uses, keeps both pointers of each ring buffer in that ring buffer's header, in shared memory. Msgq v2, which the r000 firmware uses, keeps the four pointers, two per ring buffer, in four BAR0 registers instead:

    NV_PGSP_QUEUE_HEAD    command queue write pointer
    NV_PGSP_QUEUE_TAIL    command queue read pointer
    NV_PGSP_MSGQ_HEAD     message queue write pointer
    NV_PGSP_MSGQ_TAIL     message queue read pointer

The GSP numbers its queues 0 through 7, and each numbered queue is one such pair of ring buffers with its own four pointer registers, so the hardware has 32 pointer registers in all. Nova-core uses queue 0 only.

Quoted 6 lines

A write to NV_PGSP_QUEUE_HEAD also interrupts the GSP. Msgq v0 uses that write as the doorbell, so nova-core already declares NV_PGSP_QUEUE_HEAD.

Declare the other three, NV_PGSP_QUEUE_TAIL, NV_PGSP_MSGQ_HEAD and NV_PGSP_MSGQ_TAIL, each as a scalar at its queue 0 offset rather than as an array of eight.

I understand that at the moment we are only using the first of these registers (and NV_PGSP_QUEUE_HEAD was already declared that way), but technically they are arrays of 8 - let's take the opportunity to declare them accurately and stop deriving from the hardware definition.

#12 lore raw

PATCH v3 6/33 gpu: nova-core: gsp: ring the GSP doorbell from the queue memory

In reply to John Hubbard

A command reaches GSP-RM in two steps. The driver advances the command queue's write pointer, which publishes the command, and then writes NV_PGSP_QUEUE_HEAD, which interrupts the GSP so that it reads the queue. That register write is the doorbell. In msgq v0, the write pointer is in the queue's shared-memory header, so the two steps are two writes. In msgq v2, the write pointer is NV_PGSP_QUEUE_HEAD itself, so one register write does both.

Nova-core split the two steps across two types. The queue memory type advanced the write pointer in shared memory, and the command queue type then rang the doorbell through a BAR0 mapping that it held for that one purpose. The type that advanced the pointer had no BAR0 mapping, so it could not have made the msgq v2 pointer advance.

Move the BAR0 mapping into the queue memory type, and ring the doorbell at the end of the operation that advances the write pointer. The switch to msgq v2 then replaces that operation's two writes with the one register write. The switch also moves the command queue's read pointer and the message queue's two pointers into BAR0 registers, and the queue memory type is where those register reads and writes belong as well.

Assisted-by LLM
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 47 ++++++++++++++++---------------
 1 file changed, 24 insertions(+), 23 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +24 -23
index 9250d596a3e4..f4545e3b52b3 100644
@@ -239,11 +239,16 @@ unsafe impl FromBytes for GspMem {}
 ///   pointer and the GSP read pointer. This region is returned by [`Self::driver_write_area`].
 /// * The driver owns (i.e. can read from) the part of the GSP message queue between the CPU read
 ///   pointer and the GSP write pointer. This region is returned by [`Self::driver_read_area`].
-struct DmaGspMem<'a>(Coherent<'a, GspMem>);
+struct DmaGspMem<'a> {
+    /// The queues, mapped for the GSP.
+    mem: Coherent<'a, GspMem>,
+    /// MMIO mapping of PCI BAR0, for the doorbell register.
+    bar: Bar0<'a>,
+}
 
 impl<'a> DmaGspMem<'a> {
     /// Allocate a new instance and map it for `dev`.
-    fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
+    fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> {
         const MSGQ_SIZE: u32 = num::usize_into_u32::<{ size_of::<Msgq>() }>();
         const RX_HDR_OFF: u32 = num::usize_into_u32::<{ mem::offset_of!(Msgq, rx) }>();
 
@@ -254,7 +259,7 @@ fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
         let gsp_mem: Coherent<'_, _> = gsp_mem.into();
         PteArray::init(io_project!(gsp_mem, .ptes), gsp_mem.dma_address())?;
 
-        Ok(Self(gsp_mem))
+        Ok(Self { mem: gsp_mem, bar })
     }
 
     /// Returns the region of the CPU message queue that the driver is currently allowed to write
@@ -267,7 +272,7 @@ fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
         let rx = self.gsp_read_ptr();
 
         // Pointer to the first entry of the CPU message queue.
-        let data = ptr::project!(mut self.0.as_mut_ptr(), .cpuq.msgq.data[build: 0]);
+        let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);
 
         let (tail_end, wrap_end) = if rx == 0 {
             // The write area is non-wrapping, and stops at the second-to-last entry of the command
@@ -329,7 +334,7 @@ fn driver_write_area_size(&self) -> usize {
         let rx = self.cpu_read_ptr();
 
         // Pointer to the first entry of the GSP message queue.
-        let data = ptr::project!(self.0.as_ptr(), .gspq.msgq.data[build: 0]);
+        let data = ptr::project!(self.mem.as_ptr(), .gspq.msgq.data[build: 0]);
 
         let (tail_end, wrap_end) = if rx <= tx {
             // Read area is non-wrapping and stops right before `tx`.
@@ -413,7 +418,7 @@ fn allocate_command(&mut self, size: usize, timeout: Delta) -> Result<GspCommand
     //
     // - The returned value is within `0..MSGQ_NUM_PAGES`.
     fn gsp_write_ptr(&self) -> u32 {
-        let ptr = MsgqTxHeader::write_ptr(io_project!(self.0, .gspq.tx)) % MSGQ_NUM_PAGES;
+        let ptr = MsgqTxHeader::write_ptr(io_project!(self.mem, .gspq.tx)) % MSGQ_NUM_PAGES;
 
         // ORDERING: LOAD->LOAD ordering needed to order `gsp_write_ptr` read before data read.
         dma_mb(Read);
@@ -427,7 +432,7 @@ fn gsp_write_ptr(&self) -> u32 {
     //
     // - The returned value is within `0..MSGQ_NUM_PAGES`.
     fn gsp_read_ptr(&self) -> u32 {
-        let ptr = MsgqRxHeader::read_ptr(io_project!(self.0, .gspq.rx)) % MSGQ_NUM_PAGES;
+        let ptr = MsgqRxHeader::read_ptr(io_project!(self.mem, .gspq.rx)) % MSGQ_NUM_PAGES;
 
         // ORDERING: LOAD->STORE ordering needed to order `gsp_read_ptr` read before data write.
         dma_mb(Full);
@@ -441,7 +446,7 @@ fn gsp_read_ptr(&self) -> u32 {
     //
     // - The returned value is within `0..MSGQ_NUM_PAGES`.
     fn cpu_read_ptr(&self) -> u32 {
-        MsgqRxHeader::read_ptr(io_project!(self.0, .cpuq.rx)) % MSGQ_NUM_PAGES
+        MsgqRxHeader::read_ptr(io_project!(self.mem, .cpuq.rx)) % MSGQ_NUM_PAGES
     }
 
     // Informs the GSP that it can send `elem_count` new pages into the message queue.
@@ -449,7 +454,7 @@ fn advance_cpu_read_ptr(&mut self, elem_count: u32) {
         // ORDERING: LOAD->STORE ordering needed to order `cpu_read_ptr` write after data read.
         dma_mb(Full);
 
-        let rx = io_project!(self.0, .cpuq.rx);
+        let rx = io_project!(self.mem, .cpuq.rx);
         let rptr = MsgqRxHeader::read_ptr(rx).wrapping_add(elem_count) % MSGQ_NUM_PAGES;
         MsgqRxHeader::set_read_ptr(rx, rptr)
     }
@@ -460,17 +465,22 @@ fn advance_cpu_read_ptr(&mut self, elem_count: u32) {
     //
     // - The returned value is within `0..MSGQ_NUM_PAGES`.
     fn cpu_write_ptr(&self) -> u32 {
-        MsgqTxHeader::write_ptr(io_project!(self.0, .cpuq.tx)) % MSGQ_NUM_PAGES
+        MsgqTxHeader::write_ptr(io_project!(self.mem, .cpuq.tx)) % MSGQ_NUM_PAGES
     }
 
-    // Informs the GSP that it can process `elem_count` new pages from the command queue.
+    // Publishes `elem_count` more pages of the command queue to the GSP and rings the doorbell.
     fn advance_cpu_write_ptr(&mut self, elem_count: u32) {
         // ORDERING: STORE->STORE ordering needed to order `cpu_write_ptr` write after data write.
         dma_mb(Write);
 
-        let tx = io_project!(self.0, .cpuq.tx);
+        let tx = io_project!(self.mem, .cpuq.tx);
         let wptr = MsgqTxHeader::write_ptr(tx).wrapping_add(elem_count) % MSGQ_NUM_PAGES;
         MsgqTxHeader::set_write_ptr(tx, wptr);
+
+        // A write to the head register interrupts the GSP. The pointer itself is in the
+        // shared-memory header, so the value written does not matter.
+        self.bar
+            .write_reg(regs::NV_PGSP_QUEUE_HEAD::zeroed().with_address(0u32));
     }
 }
 
@@ -535,13 +545,12 @@ pub(crate) fn new(
         bar: Bar0<'cmdq>,
     ) -> impl PinInit<Self, Error> + 'cmdq {
         pin_init_scope(move || {
-            let gsp_mem = DmaGspMem::new(dev)?;
+            let gsp_mem = DmaGspMem::new(dev, bar)?;
 
             Ok(try_pin_init!(Self {
-                dma_addr: gsp_mem.0.dma_address(),
+                dma_addr: gsp_mem.mem.dma_address(),
                 inner <- new_mutex!(CmdqInner {
                     dev,
-                    bar,
                     gsp_mem,
                     seq: 0,
                     poisoned: Cell::new(false),
@@ -563,11 +572,6 @@ fn calculate_checksum<T: Iterator<Item = u8>>(it: T) -> u32 {
         ((sum64 >> 32) as u32) ^ (sum64 as u32)
     }
 
-    /// Notifies the GSP that we have updated the command queue pointers.
-    fn notify_gsp(bar: Bar0<'_>) {
-        bar.write_reg(regs::NV_PGSP_QUEUE_HEAD::zeroed().with_address(0u32));
-    }
-
     /// Sends `command` to the GSP and waits for the reply.
     ///
     /// Events that arrive before the reply are logged and consumed.
@@ -654,8 +658,6 @@ pub(crate) fn drain(&self) -> Result {
 struct CmdqInner<'a> {
     /// Device this command queue belongs to.
     dev: &'a device::Device,
-    /// MMIO mapping of PCI BAR0, for writing the GSP doorbell.
-    bar: Bar0<'a>,
     /// Current command sequence number.
     seq: u32,
     /// Set once a message fails framing or checksum validation. Every later receive fails, since
@@ -736,7 +738,6 @@ fn send_single_command<M>(&mut self, command: M) -> Result
         let elem_count = dst.header.element_count();
         self.seq += 1;
         self.gsp_mem.advance_cpu_write_ptr(elem_count);
-        Cmdq::notify_gsp(self.bar);
 
         Ok(())
     }
Signature · 1 line
2.55.0
#13 lore raw

PATCH v3 7/33 gpu: nova-core: gsp: make command allocation generic over the header

In reply to John Hubbard

The r000 firmware accepts GMC (GPU Management Controller) API commands, which open with a different element header from RPC commands. The two kinds of command go into the same command queue, so the wait for free space, the maximum element size and the split of a command across the end of the ring buffer are the same for both.

Nova-core's queue allocation named the RPC element header directly, so there was no way to reserve queue space for a command with another header.

Make the allocation generic over the header type, along with the handle that it returns for the command. The one existing caller passes an RPC element header and is unchanged.

No functional changes.

---
 drivers/gpu/nova-core/gsp/cmdq.rs | 26 ++++++++++++++++----------
 1 file changed, 16 insertions(+), 10 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +16 -10
index f4545e3b52b3..80e6e79c5f3c 100644
@@ -129,8 +129,8 @@ fn init_variable_payload(
         Ok(())
     }
 
-    /// Total size of the command (including its variable-length payload) without the
-    /// [`GspMsgElement`] header.
+    /// Total size of the command, its variable-length payload included, without the headers that
+    /// open the queue element.
     fn size(&self) -> usize {
         size_of::<Self::Command>() + self.variable_payload_len()
     }
@@ -374,14 +374,19 @@ fn driver_write_area_size(&self) -> usize {
     ///
     /// - `EMSGSIZE` if the command is larger than [`GSP_MSG_QUEUE_ELEMENT_SIZE_MAX`].
     /// - `ETIMEDOUT` if space does not become available within the timeout.
-    /// - `EIO` if the command header is not properly aligned.
-    fn allocate_command(&mut self, size: usize, timeout: Delta) -> Result<GspCommand<'_>> {
-        if size_of::<GspMsgElement>() + size > GSP_MSG_QUEUE_ELEMENT_SIZE_MAX {
+    /// - `EIO` if the first free slot is too short for the headers of type `H`, or misaligned for
+    ///   them.
+    fn allocate_command<H: FromBytes + AsBytes>(
+        &mut self,
+        size: usize,
+        timeout: Delta,
+    ) -> Result<GspCommand<'_, H>> {
+        if size_of::<H>() + size > GSP_MSG_QUEUE_ELEMENT_SIZE_MAX {
             return Err(EMSGSIZE);
         }
         read_poll_timeout(
             || Ok(self.driver_write_area_size()),
-            |available_bytes| *available_bytes >= size_of::<GspMsgElement>() + size,
+            |available_bytes| *available_bytes >= size_of::<H>() + size,
             Delta::from_micros(1),
             timeout,
         )?;
@@ -393,8 +398,7 @@ fn allocate_command(&mut self, size: usize, timeout: Delta) -> Result<GspCommand
             (slice_1.as_flattened_mut(), slice_2.as_flattened_mut())
         };
 
-        // Extract area for the `GspMsgElement`.
-        let (header, slice_1) = GspMsgElement::from_bytes_mut_prefix(slice_1).ok_or(EIO)?;
+        let (header, slice_1) = H::from_bytes_mut_prefix(slice_1).ok_or(EIO)?;
 
         // Create the contents area.
         let (slice_1, slice_2) = if slice_1.len() > size {
@@ -486,10 +490,12 @@ fn advance_cpu_write_ptr(&mut self, elem_count: u32) {
 
 /// A command ready to be sent on the command queue.
 ///
+/// `H` is the type of the headers that open the element, such as [`GspMsgElement`] for an RM RPC.
+///
 /// This is the type returned by [`DmaGspMem::allocate_command`].
-struct GspCommand<'a> {
+struct GspCommand<'a, H> {
     // Writable reference to the header of the command.
-    header: &'a mut GspMsgElement,
+    header: &'a mut H,
     // Writable slices to the contents of the command. The second slice is zero unless the command
     // loops over the command queue.
     contents: (&'a mut [u8], &'a mut [u8]),
Signature · 1 line
2.55.0
#14 lore raw

PATCH v3 8/33 gpu: nova-core: gsp: compute the queue regions from a count and a slot

In reply to John Hubbard

The r000 firmware uses msgq v2, the queue layout that keeps the queue pointers in BAR0 registers as counts that do not wrap at the ring size. The r570 firmware's layout keeps the pointers in shared memory as indices into the ring. The two layouts differ in where a pointer is read and in how the size of the region that the driver may write, and of the region that it may read, follows from a queue's write pointer and read pointer. Splitting a region across the end of the ring is the same in both, and whether a region wraps follows from the order of the two pointers.

The functions for the writable region and for the readable region each branched on the order of the write pointer and the read pointer. Each branch chose where the two slices ended, and the function then built the slices with open-coded pointer arithmetic. The SAFETY comments argued the slice bounds branch by branch, so the switch to msgq v2 would have had to rewrite the branches and the argument along with the pointer rules.

Compute the number of slots in a region and its start slot once, and split the ring at the start slot. The first slice ends at the end of the region or at the end of the ring, whichever comes first, and the second slice carries the rest.

No functional changes.

Assisted-by LLM
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 120 ++++++++++--------------------
 1 file changed, 41 insertions(+), 79 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +41 -79
index 80e6e79c5f3c..a1c9b7cce255 100644
@@ -262,107 +262,69 @@ fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> {
         Ok(Self { mem: gsp_mem, bar })
     }
 
-    /// Returns the region of the CPU message queue that the driver is currently allowed to write
-    /// to.
+    /// Returns the region of the CPU message queue that the driver may write to.
     ///
-    /// As the message queue is a circular buffer, the region may be discontiguous in memory. In
-    /// that case the second slice will have a non-zero length.
+    /// The ring wraps, so the region comes as two slices, and the second is empty unless the
+    /// region crosses the end of the ring.
     fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
-        let tx = self.cpu_write_ptr();
-        let rx = self.gsp_read_ptr();
+        let avail = num::u32_as_usize(self.free_slots());
+        let w_slot = num::u32_as_usize(self.cpu_write_ptr());
 
         // Pointer to the first entry of the CPU message queue.
         let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);
 
-        let (tail_end, wrap_end) = if rx == 0 {
-            // The write area is non-wrapping, and stops at the second-to-last entry of the command
-            // queue (to leave the last one empty).
-            (MSGQ_NUM_PAGES - 1, 0)
-        } else if rx <= tx {
-            // The write area wraps and continues until `rx - 1`.
-            (MSGQ_NUM_PAGES, rx - 1)
-        } else {
-            // The write area doesn't wrap and stops at `rx - 1`.
-            (rx - 1, 0)
-        };
-
         // SAFETY:
-        // - `data` was created from a valid pointer, and `rx` and `tx` are in the
-        //   `0..MSGQ_NUM_PAGES` range per the invariants of `cpu_write_ptr` and `gsp_read_ptr`,
-        //   thus the created slices are valid.
-        // - The area starting at `tx` and ending at `rx - 2` modulo `MSGQ_NUM_PAGES`,
-        //   inclusive, belongs to the driver for writing and is not accessed concurrently by
-        //   the GSP.
-        // - The caller holds a reference to `self` for as long as the returned slices are live,
-        //   meaning the CPU write pointer cannot be advanced and thus that the returned area
-        //   remains exclusive to the CPU for the duration of the slices.
-        // - The created slices point to non-overlapping sub-ranges of `data` in all
-        //   branches (in the `rx <= tx` case, the second slice ends at `rx - 1` which is strictly
-        //   less than `tx` where the first slice starts; in the other cases the second slice is
-        //   empty), so creating two `&mut` references from them does not violate aliasing rules.
-        unsafe {
-            (
-                core::slice::from_raw_parts_mut(
-                    data.add(num::u32_as_usize(tx)),
-                    num::u32_as_usize(tail_end - tx),
-                ),
-                core::slice::from_raw_parts_mut(data, num::u32_as_usize(wrap_end)),
-            )
-        }
+        // - `data` points to the `MSGQ_NUM_PAGES` initialized entries of the CPU message queue.
+        // - The returned slices cover the `avail` free slots from the write pointer on, which the
+        //   GSP does not read until `advance_cpu_write_ptr` publishes them.
+        // - `split_at_mut` gives two non-overlapping halves, and the `&mut self` borrow lasts as
+        //   long as the returned slices, so that no other call hands out the same region while
+        //   they live.
+        let data =
+            unsafe { core::slice::from_raw_parts_mut(data, num::u32_as_usize(MSGQ_NUM_PAGES)) };
+        let (before_w, after_w) = data.split_at_mut(w_slot);
+
+        let in_after = avail.min(after_w.len());
+        let in_before = avail - in_after;
+        (&mut after_w[..in_after], &mut before_w[..in_before])
     }
 
-    /// Returns the size of the region of the CPU message queue that the driver is currently allowed
-    /// to write to, in bytes.
-    fn driver_write_area_size(&self) -> usize {
+    /// Returns the number of command queue slots that the driver may still write.
+    fn free_slots(&self) -> u32 {
         let tx = self.cpu_write_ptr();
         let rx = self.gsp_read_ptr();
 
-        // `rx` and `tx` are both in `0..MSGQ_NUM_PAGES` per the invariants of `gsp_read_ptr` and
-        // `cpu_write_ptr`. The minimum value case is where `rx == 0` and `tx == MSGQ_NUM_PAGES -
-        // 1`, which gives `0 + MSGQ_NUM_PAGES - (MSGQ_NUM_PAGES - 1) - 1 == 0`.
-        let slots = (rx + MSGQ_NUM_PAGES - tx - 1) % MSGQ_NUM_PAGES;
-        num::u32_as_usize(slots) * GSP_PAGE_SIZE
+        // One slot always stays empty, so that a full ring and an empty ring differ in their
+        // pointers. `tx` is below `MSGQ_NUM_PAGES`, so the subtraction does not underflow.
+        (rx + MSGQ_NUM_PAGES - tx - 1) % MSGQ_NUM_PAGES
     }
 
-    /// Returns the region of the GSP message queue that the driver is currently allowed to read
-    /// from.
-    ///
-    /// As the message queue is a circular buffer, the region may be discontiguous in memory. In
-    /// that case the second slice will have a non-zero length.
+    /// Returns the number of bytes that the driver can still write to the command queue.
+    fn driver_write_area_size(&self) -> usize {
+        num::u32_as_usize(self.free_slots()) * GSP_PAGE_SIZE
+    }
+
+    /// Returns the region of the GSP message queue that the driver may read, as two slices
+    /// because the ring wraps.
     fn driver_read_area(&self) -> (&[[u8; GSP_PAGE_SIZE]], &[[u8; GSP_PAGE_SIZE]]) {
         let tx = self.gsp_write_ptr();
         let rx = self.cpu_read_ptr();
+        let avail = num::u32_as_usize((tx + MSGQ_NUM_PAGES - rx) % MSGQ_NUM_PAGES);
+        let r_slot = num::u32_as_usize(rx);
 
         // Pointer to the first entry of the GSP message queue.
         let data = ptr::project!(self.mem.as_ptr(), .gspq.msgq.data[build: 0]);
 
-        let (tail_end, wrap_end) = if rx <= tx {
-            // Read area is non-wrapping and stops right before `tx`.
-            (tx, 0)
-        } else {
-            // Read area is wrapping and stops right before `tx`.
-            (MSGQ_NUM_PAGES, tx)
-        };
-
         // SAFETY:
-        // - `data` was created from a valid pointer, and `rx` and `tx` are in the
-        //   `0..MSGQ_NUM_PAGES` range per the invariants of `gsp_write_ptr` and `cpu_read_ptr`,
-        //   thus the created slices are valid.
-        // - The area starting at `rx` and ending at `tx - 1` modulo `MSGQ_NUM_PAGES`,
-        //   inclusive, belongs to the driver for reading and is not accessed concurrently by
-        //   the GSP.
-        // - The caller holds a reference to `self` for as long as the returned slices are live,
-        //   meaning the CPU read pointer cannot be advanced and thus that the returned area
-        //   remains exclusive to the CPU for the duration of the slices.
-        unsafe {
-            (
-                core::slice::from_raw_parts(
-                    data.add(num::u32_as_usize(rx)),
-                    num::u32_as_usize(tail_end - rx),
-                ),
-                core::slice::from_raw_parts(data, num::u32_as_usize(wrap_end)),
-            )
-        }
+        // - `data` points to the `MSGQ_NUM_PAGES` initialized entries of the GSP message queue.
+        // - The returned slices cover the `avail` slots that the GSP has already written. The GSP
+        //   does not write them again until `advance_cpu_read_ptr` releases them.
+        let data = unsafe { core::slice::from_raw_parts(data, num::u32_as_usize(MSGQ_NUM_PAGES)) };
+        let (before_r, after_r) = data.split_at(r_slot);
+
+        let in_after = avail.min(after_r.len());
+        let in_before = avail - in_after;
+        (&after_r[..in_after], &before_r[..in_before])
     }
 
     /// Allocates a region on the command queue that is large enough to send a command of `size`
Signature · 1 line
2.55.0
#15 lore raw

Re: [PATCH v3 08/33] gpu: nova-core: gsp: compute the queue regions from a count and a slot

Quoted 23 lines · John Hubbard

The r000 firmware uses msgq v2, the queue layout that keeps the queue pointers in BAR0 registers as counts that do not wrap at the ring size. The r570 firmware's layout keeps the pointers in shared memory as indices into the ring. The two layouts differ in where a pointer is read and in how the size of the region that the driver may write, and of the region that it may read, follows from a queue's write pointer and read pointer. Splitting a region across the end of the ring is the same in both, and whether a region wraps follows from the order of the two pointers.

The functions for the writable region and for the readable region each branched on the order of the write pointer and the read pointer. Each branch chose where the two slices ended, and the function then built the slices with open-coded pointer arithmetic. The SAFETY comments argued the slice bounds branch by branch, so the switch to msgq v2 would have had to rewrite the branches and the argument along with the pointer rules.

Compute the number of slots in a region and its start slot once, and split the ring at the start slot. The first slice ends at the end of the region or at the end of the ring, whichever comes first, and the second slice carries the rest.

Quoted 7 lines

No functional changes.

Assisted-by LLM
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 120 ++++++++++--------------------
 1 file changed, 41 insertions(+), 79 deletions(-)

This looks like an improvement regardless of the r000 switch!

Quoted 7 lines
drivers/gpu/nova-core/gsp/cmdq.rs +0 -0
index 80e6e79c5f3c..a1c9b7cce255 100644
@@ -262,107 +262,69 @@ fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> {
         Ok(Self { mem: gsp_mem, bar })

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 268

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3 -4
     }
 
-    /// Returns the region of the CPU message queue that the driver is currently allowed to write
-    /// to.
+    /// Returns the region of the CPU message queue that the driver may write to.
     ///
-    /// As the message queue is a circular buffer, the region may be discontiguous in memory. In
-    /// that case the second slice will have a non-zero length.
+    /// The ring wraps, so the region comes as two slices, and the second is empty unless the
+    /// region crosses the end of the ring.

There is a recurring pattern in this series to drive-by rewrite comments when there is no real need to do so. The new comment is not even marginally better as we lose the temporal nature ("currently") of the borrow. This creates churn restating the same thing using different words and disrupts the diff, so can we avoid doing that unless the patch actually changes what the comment describes?

Quoted 43 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2 -35
     fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
-        let tx = self.cpu_write_ptr();
-        let rx = self.gsp_read_ptr();
+        let avail = num::u32_as_usize(self.free_slots());
+        let w_slot = num::u32_as_usize(self.cpu_write_ptr());
 
         // Pointer to the first entry of the CPU message queue.
         let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);
 
-        let (tail_end, wrap_end) = if rx == 0 {
-            // The write area is non-wrapping, and stops at the second-to-last entry of the command
-            // queue (to leave the last one empty).
-            (MSGQ_NUM_PAGES - 1, 0)
-        } else if rx <= tx {
-            // The write area wraps and continues until `rx - 1`.
-            (MSGQ_NUM_PAGES, rx - 1)
-        } else {
-            // The write area doesn't wrap and stops at `rx - 1`.
-            (rx - 1, 0)
-        };
-
         // SAFETY:
-        // - `data` was created from a valid pointer, and `rx` and `tx` are in the
-        //   `0..MSGQ_NUM_PAGES` range per the invariants of `cpu_write_ptr` and `gsp_read_ptr`,
-        //   thus the created slices are valid.
-        // - The area starting at `tx` and ending at `rx - 2` modulo `MSGQ_NUM_PAGES`,
-        //   inclusive, belongs to the driver for writing and is not accessed concurrently by
-        //   the GSP.
-        // - The caller holds a reference to `self` for as long as the returned slices are live,
-        //   meaning the CPU write pointer cannot be advanced and thus that the returned area
-        //   remains exclusive to the CPU for the duration of the slices.
-        // - The created slices point to non-overlapping sub-ranges of `data` in all
-        //   branches (in the `rx <= tx` case, the second slice ends at `rx - 1` which is strictly
-        //   less than `tx` where the first slice starts; in the other cases the second slice is
-        //   empty), so creating two `&mut` references from them does not violate aliasing rules.
-        unsafe {
-            (
-                core::slice::from_raw_parts_mut(
-                    data.add(num::u32_as_usize(tx)),
-                    num::u32_as_usize(tail_end - tx),
-                ),
-                core::slice::from_raw_parts_mut(data, num::u32_as_usize(wrap_end)),
-            )

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 285

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +9 -1
-        }
+        // - `data` points to the `MSGQ_NUM_PAGES` initialized entries of the CPU message queue.
+        // - The returned slices cover the `avail` free slots from the write pointer on, which the
+        //   GSP does not read until `advance_cpu_write_ptr` publishes them.
+        // - `split_at_mut` gives two non-overlapping halves, and the `&mut self` borrow lasts as
+        //   long as the returned slices, so that no other call hands out the same region while
+        //   they live.
+        let data =
+            unsafe { core::slice::from_raw_parts_mut(data, num::u32_as_usize(MSGQ_NUM_PAGES)) };
+        let (before_w, after_w) = data.split_at_mut(w_slot);

This creates a reference over the whole ring, including the parts owned by the GSP, which breaks the Coherent safety contract that the device must not be able to read or write to a live slice. So we'll need to call from_raw_parts_mut twice, with the correct sizes, instead of splitting.

(also split_at_mut is panicking and should have a PANIC: comment justifying why it cannot, but once the point above is addressed that call will go away).

I wanted to try it locally and ended up with something that seems to work, so let me share it to save some time:

    fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
        let avail = self.free_slots();
        let w_slot = self.cpu_write_ptr();

        // Pointer to the first entry of the CPU message queue.
        let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);

        let in_after = avail.min(MSGQ_NUM_PAGES - w_slot);
        let in_before = avail - in_after;

        // SAFETY:
        // - `data` was created from a valid pointer of `MSGQ_NUM_PAGES` entries.
        // - The `in_after` entries after `w_slot` belong to the `avail` entries that the driver is
        //   currently allowed to write.
        // - The `in_before` first entries belong to the `avail` entries that the driver is
        //   currently allowed to write.
        // - The slices do not overlap.
        unsafe {
            (
                core::slice::from_raw_parts_mut(
                    data.add(num::u32_as_usize(w_slot)),
                    num::u32_as_usize(in_after),
                ),
                core::slice::from_raw_parts_mut(data, num::u32_as_usize(in_before)),
            )
        }
    }

It has turned out quite short, which I like! I also opted to work with the original u32 until the very end, as it results in less conversions overall.

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 293

Quoted 11 lines
drivers/gpu/nova-core/gsp/cmdq.rs +6 -3
+
+        let in_after = avail.min(after_w.len());
+        let in_before = avail - in_after;
+        (&mut after_w[..in_after], &mut before_w[..in_before])
     }
 
-    /// Returns the size of the region of the CPU message queue that the driver is currently allowed
-    /// to write to, in bytes.
-    fn driver_write_area_size(&self) -> usize {
+    /// Returns the number of command queue slots that the driver may still write.
+    fn free_slots(&self) -> u32 {

The method name should specify which queue we are dealing with here, "free_slots" is too generic. And for symmetry the read side should also get the same helper, even if driver_read_area is the only user, as it makes the code easier to parse.

Quoted 20 lines
drivers/gpu/nova-core/gsp/cmdq.rs +5 -10
         let tx = self.cpu_write_ptr();
         let rx = self.gsp_read_ptr();
 
-        // `rx` and `tx` are both in `0..MSGQ_NUM_PAGES` per the invariants of `gsp_read_ptr` and
-        // `cpu_write_ptr`. The minimum value case is where `rx == 0` and `tx == MSGQ_NUM_PAGES -
-        // 1`, which gives `0 + MSGQ_NUM_PAGES - (MSGQ_NUM_PAGES - 1) - 1 == 0`.
-        let slots = (rx + MSGQ_NUM_PAGES - tx - 1) % MSGQ_NUM_PAGES;
-        num::u32_as_usize(slots) * GSP_PAGE_SIZE
+        // One slot always stays empty, so that a full ring and an empty ring differ in their
+        // pointers. `tx` is below `MSGQ_NUM_PAGES`, so the subtraction does not underflow.
+        (rx + MSGQ_NUM_PAGES - tx - 1) % MSGQ_NUM_PAGES
     }
 
-    /// Returns the region of the GSP message queue that the driver is currently allowed to read
-    /// from.
-    ///
-    /// As the message queue is a circular buffer, the region may be discontiguous in memory. In
-    /// that case the second slice will have a non-zero length.
+    /// Returns the number of bytes that the driver can still write to the command queue.
+    fn driver_write_area_size(&self) -> usize {

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 313

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +7 -0
+        num::u32_as_usize(self.free_slots()) * GSP_PAGE_SIZE
+    }
+
+    /// Returns the region of the GSP message queue that the driver may read, as two slices
+    /// because the ring wraps.
     fn driver_read_area(&self) -> (&[[u8; GSP_PAGE_SIZE]], &[[u8; GSP_PAGE_SIZE]]) {
         let tx = self.gsp_write_ptr();
         let rx = self.cpu_read_ptr();
+        let avail = num::u32_as_usize((tx + MSGQ_NUM_PAGES - rx) % MSGQ_NUM_PAGES);
+        let r_slot = num::u32_as_usize(rx);

Indeed, with a helper like free_slots for the read side we could get rid of tx and rx and spell what the code does more clearly, so I think that'd be a win.

The helper makes us read the CPU read ptr one extra time, but that's a negligible tradeoff for better code readability.

Quoted 26 lines
drivers/gpu/nova-core/gsp/cmdq.rs +0 -21
         // Pointer to the first entry of the GSP message queue.
         let data = ptr::project!(self.mem.as_ptr(), .gspq.msgq.data[build: 0]);
 
-        let (tail_end, wrap_end) = if rx <= tx {
-            // Read area is non-wrapping and stops right before `tx`.
-            (tx, 0)
-        } else {
-            // Read area is wrapping and stops right before `tx`.
-            (MSGQ_NUM_PAGES, tx)
-        };
-
         // SAFETY:
-        // - `data` was created from a valid pointer, and `rx` and `tx` are in the
-        //   `0..MSGQ_NUM_PAGES` range per the invariants of `gsp_write_ptr` and `cpu_read_ptr`,
-        //   thus the created slices are valid.
-        // - The area starting at `rx` and ending at `tx - 1` modulo `MSGQ_NUM_PAGES`,
-        //   inclusive, belongs to the driver for reading and is not accessed concurrently by
-        //   the GSP.
-        // - The caller holds a reference to `self` for as long as the returned slices are live,
-        //   meaning the CPU read pointer cannot be advanced and thus that the returned area
-        //   remains exclusive to the CPU for the duration of the slices.
-        unsafe {
-            (
-                core::slice::from_raw_parts(
-                    data.add(num::u32_as_usize(rx)),

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 323

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +5 -5
-                    num::u32_as_usize(tail_end - rx),
-                ),
-                core::slice::from_raw_parts(data, num::u32_as_usize(wrap_end)),
-            )
-        }
+        // - `data` points to the `MSGQ_NUM_PAGES` initialized entries of the GSP message queue.
+        // - The returned slices cover the `avail` slots that the GSP has already written. The GSP
+        //   does not write them again until `advance_cpu_read_ptr` releases them.
+        let data = unsafe { core::slice::from_raw_parts(data, num::u32_as_usize(MSGQ_NUM_PAGES)) };
+        let (before_r, after_r) = data.split_at(r_slot);

Same problem of ring ownership - we need to call from_raw_parts twice. The pattern used in driver_write_area should apply smoothly here as well.

reviewer
#16 lore raw

Re: [PATCH v3 08/33] gpu: nova-core: gsp: compute the queue regions from a count and a slot

Quoted 43 lines · Alexandre Courbot
Quoted 23 lines · John Hubbard

The r000 firmware uses msgq v2, the queue layout that keeps the queue pointers in BAR0 registers as counts that do not wrap at the ring size. The r570 firmware's layout keeps the pointers in shared memory as indices into the ring. The two layouts differ in where a pointer is read and in how the size of the region that the driver may write, and of the region that it may read, follows from a queue's write pointer and read pointer. Splitting a region across the end of the ring is the same in both, and whether a region wraps follows from the order of the two pointers.

The functions for the writable region and for the readable region each branched on the order of the write pointer and the read pointer. Each branch chose where the two slices ended, and the function then built the slices with open-coded pointer arithmetic. The SAFETY comments argued the slice bounds branch by branch, so the switch to msgq v2 would have had to rewrite the branches and the argument along with the pointer rules.

Compute the number of slots in a region and its start slot once, and split the ring at the start slot. The first slice ends at the end of the region or at the end of the ring, whichever comes first, and the second slice carries the rest.

Quoted 7 lines

No functional changes.

Assisted-by LLM
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 120 ++++++++++--------------------
 1 file changed, 41 insertions(+), 79 deletions(-)

This looks like an improvement regardless of the r000 switch!

Quoted 9 lines
drivers/gpu/nova-core/gsp/cmdq.rs +0 -0
index 80e6e79c5f3c..a1c9b7cce255 100644
@@ -262,107 +262,69 @@ fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> {
         Ok(Self { mem: gsp_mem, bar })
     }
 
Quoted 15 lines

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 268

Quoted 8 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3 -4
-    /// Returns the region of the CPU message queue that the driver is currently allowed to write
-    /// to.
+    /// Returns the region of the CPU message queue that the driver may write to.
     ///
-    /// As the message queue is a circular buffer, the region may be discontiguous in memory. In
-    /// that case the second slice will have a non-zero length.
+    /// The ring wraps, so the region comes as two slices, and the second is empty unless the
+    /// region crosses the end of the ring.

There is a recurring pattern in this series to drive-by rewrite comments when there is no real need to do so. The new comment is not even marginally better as we lose the temporal nature ("currently") of the borrow. This creates churn restating the same thing using different words and disrupts the diff, so can we avoid doing that unless the patch actually changes what the comment describes?

That's a pretty common thing for LLM to do :)

Quoted 96 lines
Quoted 44 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2 -35
     fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
-        let tx = self.cpu_write_ptr();
-        let rx = self.gsp_read_ptr();
+        let avail = num::u32_as_usize(self.free_slots());
+        let w_slot = num::u32_as_usize(self.cpu_write_ptr());
 
         // Pointer to the first entry of the CPU message queue.
         let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);
 
-        let (tail_end, wrap_end) = if rx == 0 {
-            // The write area is non-wrapping, and stops at the second-to-last entry of the command
-            // queue (to leave the last one empty).
-            (MSGQ_NUM_PAGES - 1, 0)
-        } else if rx <= tx {
-            // The write area wraps and continues until `rx - 1`.
-            (MSGQ_NUM_PAGES, rx - 1)
-        } else {
-            // The write area doesn't wrap and stops at `rx - 1`.
-            (rx - 1, 0)
-        };
-
         // SAFETY:
-        // - `data` was created from a valid pointer, and `rx` and `tx` are in the
-        //   `0..MSGQ_NUM_PAGES` range per the invariants of `cpu_write_ptr` and `gsp_read_ptr`,
-        //   thus the created slices are valid.
-        // - The area starting at `tx` and ending at `rx - 2` modulo `MSGQ_NUM_PAGES`,
-        //   inclusive, belongs to the driver for writing and is not accessed concurrently by
-        //   the GSP.
-        // - The caller holds a reference to `self` for as long as the returned slices are live,
-        //   meaning the CPU write pointer cannot be advanced and thus that the returned area
-        //   remains exclusive to the CPU for the duration of the slices.
-        // - The created slices point to non-overlapping sub-ranges of `data` in all
-        //   branches (in the `rx <= tx` case, the second slice ends at `rx - 1` which is strictly
-        //   less than `tx` where the first slice starts; in the other cases the second slice is
-        //   empty), so creating two `&mut` references from them does not violate aliasing rules.
-        unsafe {
-            (
-                core::slice::from_raw_parts_mut(
-                    data.add(num::u32_as_usize(tx)),
-                    num::u32_as_usize(tail_end - tx),
-                ),
-                core::slice::from_raw_parts_mut(data, num::u32_as_usize(wrap_end)),
-            )

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 285

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +9 -1
-        }
+        // - `data` points to the `MSGQ_NUM_PAGES` initialized entries of the CPU message queue.
+        // - The returned slices cover the `avail` free slots from the write pointer on, which the
+        //   GSP does not read until `advance_cpu_write_ptr` publishes them.
+        // - `split_at_mut` gives two non-overlapping halves, and the `&mut self` borrow lasts as
+        //   long as the returned slices, so that no other call hands out the same region while
+        //   they live.
+        let data =
+            unsafe { core::slice::from_raw_parts_mut(data, num::u32_as_usize(MSGQ_NUM_PAGES)) };
+        let (before_w, after_w) = data.split_at_mut(w_slot);

This creates a reference over the whole ring, including the parts owned by the GSP, which breaks the Coherent safety contract that the device must not be able to read or write to a live slice. So we'll need to call from_raw_parts_mut twice, with the correct sizes, instead of splitting.

(also split_at_mut is panicking and should have a PANIC: comment justifying why it cannot, but once the point above is addressed that call will go away).

I wanted to try it locally and ended up with something that seems to work, so let me share it to save some time:

    fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
        let avail = self.free_slots();
        let w_slot = self.cpu_write_ptr();

        // Pointer to the first entry of the CPU message queue.
        let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);

        let in_after = avail.min(MSGQ_NUM_PAGES - w_slot);
        let in_before = avail - in_after;

        // SAFETY:
        // - `data` was created from a valid pointer of `MSGQ_NUM_PAGES` entries.
        // - The `in_after` entries after `w_slot` belong to the `avail` entries that the driver is
        //   currently allowed to write.
        // - The `in_before` first entries belong to the `avail` entries that the driver is
        //   currently allowed to write.
        // - The slices do not overlap.
        unsafe {
            (
                core::slice::from_raw_parts_mut(
                    data.add(num::u32_as_usize(w_slot)),
                    num::u32_as_usize(in_after),
                ),
                core::slice::from_raw_parts_mut(data, num::u32_as_usize(in_before)),
            )
        }
    }
Quoted 3 lines

It has turned out quite short, which I like! I also opted to work with the original u32 until the very end, as it results in less conversions overall.

Possibly take some thing from the old projection syntax rework series?

https://lore.kernel.org/rust-for-linux/[email protected]/

Best,
Gary

#17 lore raw

Re: [PATCH v3 08/33] gpu: nova-core: gsp: compute the queue regions from a count and a slot

Quoted 60 lines · Gary Guo
Quoted 43 lines · Alexandre Courbot
Quoted 23 lines · John Hubbard

The r000 firmware uses msgq v2, the queue layout that keeps the queue pointers in BAR0 registers as counts that do not wrap at the ring size. The r570 firmware's layout keeps the pointers in shared memory as indices into the ring. The two layouts differ in where a pointer is read and in how the size of the region that the driver may write, and of the region that it may read, follows from a queue's write pointer and read pointer. Splitting a region across the end of the ring is the same in both, and whether a region wraps follows from the order of the two pointers.

The functions for the writable region and for the readable region each branched on the order of the write pointer and the read pointer. Each branch chose where the two slices ended, and the function then built the slices with open-coded pointer arithmetic. The SAFETY comments argued the slice bounds branch by branch, so the switch to msgq v2 would have had to rewrite the branches and the argument along with the pointer rules.

Compute the number of slots in a region and its start slot once, and split the ring at the start slot. The first slice ends at the end of the region or at the end of the ring, whichever comes first, and the second slice carries the rest.

Quoted 7 lines

No functional changes.

Assisted-by LLM
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 120 ++++++++++--------------------
 1 file changed, 41 insertions(+), 79 deletions(-)

This looks like an improvement regardless of the r000 switch!

Quoted 9 lines
drivers/gpu/nova-core/gsp/cmdq.rs +0 -0
index 80e6e79c5f3c..a1c9b7cce255 100644
@@ -262,107 +262,69 @@ fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> {
         Ok(Self { mem: gsp_mem, bar })
     }
 
Quoted 15 lines

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 268

Quoted 8 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3 -4
-    /// Returns the region of the CPU message queue that the driver is currently allowed to write
-    /// to.
+    /// Returns the region of the CPU message queue that the driver may write to.
     ///
-    /// As the message queue is a circular buffer, the region may be discontiguous in memory. In
-    /// that case the second slice will have a non-zero length.
+    /// The ring wraps, so the region comes as two slices, and the second is empty unless the
+    /// region crosses the end of the ring.

There is a recurring pattern in this series to drive-by rewrite comments when there is no real need to do so. The new comment is not even marginally better as we lose the temporal nature ("currently") of the borrow. This creates churn restating the same thing using different words and disrupts the diff, so can we avoid doing that unless the patch actually changes what the comment describes?

Quoted 1 line

That's a pretty common thing for LLM to do :)

We're lucky that one highlight of this revision was to remove AI comment churn. :)

Quoted 97 lines
Quoted 97 lines
Quoted 45 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2 -35
     fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
-        let tx = self.cpu_write_ptr();
-        let rx = self.gsp_read_ptr();
+        let avail = num::u32_as_usize(self.free_slots());
+        let w_slot = num::u32_as_usize(self.cpu_write_ptr());
 
         // Pointer to the first entry of the CPU message queue.
         let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);
 
-        let (tail_end, wrap_end) = if rx == 0 {
-            // The write area is non-wrapping, and stops at the second-to-last entry of the command
-            // queue (to leave the last one empty).
-            (MSGQ_NUM_PAGES - 1, 0)
-        } else if rx <= tx {
-            // The write area wraps and continues until `rx - 1`.
-            (MSGQ_NUM_PAGES, rx - 1)
-        } else {
-            // The write area doesn't wrap and stops at `rx - 1`.
-            (rx - 1, 0)
-        };
-
         // SAFETY:
-        // - `data` was created from a valid pointer, and `rx` and `tx` are in the
-        //   `0..MSGQ_NUM_PAGES` range per the invariants of `cpu_write_ptr` and `gsp_read_ptr`,
-        //   thus the created slices are valid.
-        // - The area starting at `tx` and ending at `rx - 2` modulo `MSGQ_NUM_PAGES`,
-        //   inclusive, belongs to the driver for writing and is not accessed concurrently by
-        //   the GSP.
-        // - The caller holds a reference to `self` for as long as the returned slices are live,
-        //   meaning the CPU write pointer cannot be advanced and thus that the returned area
-        //   remains exclusive to the CPU for the duration of the slices.
-        // - The created slices point to non-overlapping sub-ranges of `data` in all
-        //   branches (in the `rx <= tx` case, the second slice ends at `rx - 1` which is strictly
-        //   less than `tx` where the first slice starts; in the other cases the second slice is
-        //   empty), so creating two `&mut` references from them does not violate aliasing rules.
-        unsafe {
-            (
-                core::slice::from_raw_parts_mut(
-                    data.add(num::u32_as_usize(tx)),
-                    num::u32_as_usize(tail_end - tx),
-                ),
-                core::slice::from_raw_parts_mut(data, num::u32_as_usize(wrap_end)),
-            )

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 285

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +9 -1
-        }
+        // - `data` points to the `MSGQ_NUM_PAGES` initialized entries of the CPU message queue.
+        // - The returned slices cover the `avail` free slots from the write pointer on, which the
+        //   GSP does not read until `advance_cpu_write_ptr` publishes them.
+        // - `split_at_mut` gives two non-overlapping halves, and the `&mut self` borrow lasts as
+        //   long as the returned slices, so that no other call hands out the same region while
+        //   they live.
+        let data =
+            unsafe { core::slice::from_raw_parts_mut(data, num::u32_as_usize(MSGQ_NUM_PAGES)) };
+        let (before_w, after_w) = data.split_at_mut(w_slot);

This creates a reference over the whole ring, including the parts owned by the GSP, which breaks the Coherent safety contract that the device must not be able to read or write to a live slice. So we'll need to call from_raw_parts_mut twice, with the correct sizes, instead of splitting.

(also split_at_mut is panicking and should have a PANIC: comment justifying why it cannot, but once the point above is addressed that call will go away).

I wanted to try it locally and ended up with something that seems to work, so let me share it to save some time:

    fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
        let avail = self.free_slots();
        let w_slot = self.cpu_write_ptr();

        // Pointer to the first entry of the CPU message queue.
        let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);

        let in_after = avail.min(MSGQ_NUM_PAGES - w_slot);
        let in_before = avail - in_after;

        // SAFETY:
        // - `data` was created from a valid pointer of `MSGQ_NUM_PAGES` entries.
        // - The `in_after` entries after `w_slot` belong to the `avail` entries that the driver is
        //   currently allowed to write.
        // - The `in_before` first entries belong to the `avail` entries that the driver is
        //   currently allowed to write.
        // - The slices do not overlap.
        unsafe {
            (
                core::slice::from_raw_parts_mut(
                    data.add(num::u32_as_usize(w_slot)),
                    num::u32_as_usize(in_after),
                ),
                core::slice::from_raw_parts_mut(data, num::u32_as_usize(in_before)),
            )
        }
    }
Quoted 7 lines
Quoted 3 lines

It has turned out quite short, which I like! I also opted to work with the original u32 until the very end, as it results in less conversions overall.

Possibly take some thing from the old projection syntax rework series?

https://lore.kernel.org/rust-for-linux/[email protected]/

Oh yes, I forgot about this patch. Do you mean using ptr::project to create the final sub-slices, or am I missing something else?

reviewer
#18 lore raw

Re: [PATCH v3 08/33] gpu: nova-core: gsp: compute the queue regions from a count and a slot

Quoted 102 lines · Alexandre Courbot
Quoted 101 lines · Gary Guo
Quoted 99 lines · Alexandre Courbot
Quoted 43 lines · John Hubbard
     fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
drivers/gpu/nova-core/gsp/cmdq.rs +2 -35
-        let tx = self.cpu_write_ptr();
-        let rx = self.gsp_read_ptr();
+        let avail = num::u32_as_usize(self.free_slots());
+        let w_slot = num::u32_as_usize(self.cpu_write_ptr());
 
         // Pointer to the first entry of the CPU message queue.
         let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);
 
-        let (tail_end, wrap_end) = if rx == 0 {
-            // The write area is non-wrapping, and stops at the second-to-last entry of the command
-            // queue (to leave the last one empty).
-            (MSGQ_NUM_PAGES - 1, 0)
-        } else if rx <= tx {
-            // The write area wraps and continues until `rx - 1`.
-            (MSGQ_NUM_PAGES, rx - 1)
-        } else {
-            // The write area doesn't wrap and stops at `rx - 1`.
-            (rx - 1, 0)
-        };
-
         // SAFETY:
-        // - `data` was created from a valid pointer, and `rx` and `tx` are in the
-        //   `0..MSGQ_NUM_PAGES` range per the invariants of `cpu_write_ptr` and `gsp_read_ptr`,
-        //   thus the created slices are valid.
-        // - The area starting at `tx` and ending at `rx - 2` modulo `MSGQ_NUM_PAGES`,
-        //   inclusive, belongs to the driver for writing and is not accessed concurrently by
-        //   the GSP.
-        // - The caller holds a reference to `self` for as long as the returned slices are live,
-        //   meaning the CPU write pointer cannot be advanced and thus that the returned area
-        //   remains exclusive to the CPU for the duration of the slices.
-        // - The created slices point to non-overlapping sub-ranges of `data` in all
-        //   branches (in the `rx <= tx` case, the second slice ends at `rx - 1` which is strictly
-        //   less than `tx` where the first slice starts; in the other cases the second slice is
-        //   empty), so creating two `&mut` references from them does not violate aliasing rules.
-        unsafe {
-            (
-                core::slice::from_raw_parts_mut(
-                    data.add(num::u32_as_usize(tx)),
-                    num::u32_as_usize(tail_end - tx),
-                ),
-                core::slice::from_raw_parts_mut(data, num::u32_as_usize(wrap_end)),
-            )

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 285

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +9 -1
-        }
+        // - `data` points to the `MSGQ_NUM_PAGES` initialized entries of the CPU message queue.
+        // - The returned slices cover the `avail` free slots from the write pointer on, which the
+        //   GSP does not read until `advance_cpu_write_ptr` publishes them.
+        // - `split_at_mut` gives two non-overlapping halves, and the `&mut self` borrow lasts as
+        //   long as the returned slices, so that no other call hands out the same region while
+        //   they live.
+        let data =
+            unsafe { core::slice::from_raw_parts_mut(data, num::u32_as_usize(MSGQ_NUM_PAGES)) };
+        let (before_w, after_w) = data.split_at_mut(w_slot);

This creates a reference over the whole ring, including the parts owned by the GSP, which breaks the Coherent safety contract that the device must not be able to read or write to a live slice. So we'll need to call from_raw_parts_mut twice, with the correct sizes, instead of splitting.

(also split_at_mut is panicking and should have a PANIC: comment justifying why it cannot, but once the point above is addressed that call will go away).

I wanted to try it locally and ended up with something that seems to work, so let me share it to save some time:

    fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
        let avail = self.free_slots();
        let w_slot = self.cpu_write_ptr();

        // Pointer to the first entry of the CPU message queue.
        let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);

        let in_after = avail.min(MSGQ_NUM_PAGES - w_slot);
        let in_before = avail - in_after;

        // SAFETY:
        // - `data` was created from a valid pointer of `MSGQ_NUM_PAGES` entries.
        // - The `in_after` entries after `w_slot` belong to the `avail` entries that the driver is
        //   currently allowed to write.
        // - The `in_before` first entries belong to the `avail` entries that the driver is
        //   currently allowed to write.
        // - The slices do not overlap.
        unsafe {
            (
                core::slice::from_raw_parts_mut(
                    data.add(num::u32_as_usize(w_slot)),
                    num::u32_as_usize(in_after),
                ),
                core::slice::from_raw_parts_mut(data, num::u32_as_usize(in_before)),
            )
        }
    }

It has turned out quite short, which I like! I also opted to work with the original u32 until the very end, as it results in less conversions overall.

Quoted 6 lines
Quoted 3 lines

Possibly take some thing from the old projection syntax rework series?

https://lore.kernel.org/rust-for-linux/[email protected]/

Oh yes, I forgot about this patch. Do you mean using ptr::project to create the final sub-slices, or am I missing something else?

I think it's possible to use I/O projection on CoherentView and then you assert that it's not concurrently accessed by turning them from CoherentView to &mut [] using CoherentView::as_mut.

Best,
Gary

#19 lore raw

Re: [PATCH v3 08/33] gpu: nova-core: gsp: compute the queue regions from a count and a slot

In reply to Alexandre Courbot
Quoted 61 lines · Alexandre Courbot
Quoted 60 lines · Gary Guo
Quoted 58 lines · Alexandre Courbot
Quoted 23 lines · John Hubbard

The r000 firmware uses msgq v2, the queue layout that keeps the queue pointers in BAR0 registers as counts that do not wrap at the ring size. The r570 firmware's layout keeps the pointers in shared memory as indices into the ring. The two layouts differ in where a pointer is read and in how the size of the region that the driver may write, and of the region that it may read, follows from a queue's write pointer and read pointer. Splitting a region across the end of the ring is the same in both, and whether a region wraps follows from the order of the two pointers.

The functions for the writable region and for the readable region each branched on the order of the write pointer and the read pointer. Each branch chose where the two slices ended, and the function then built the slices with open-coded pointer arithmetic. The SAFETY comments argued the slice bounds branch by branch, so the switch to msgq v2 would have had to rewrite the branches and the argument along with the pointer rules.

Compute the number of slots in a region and its start slot once, and split the ring at the start slot. The first slice ends at the end of the region or at the end of the ring, whichever comes first, and the second slice carries the rest.

Quoted 7 lines

No functional changes.

Assisted-by LLM
---
  drivers/gpu/nova-core/gsp/cmdq.rs | 120 ++++++++++--------------------
  1 file changed, 41 insertions(+), 79 deletions(-)

This looks like an improvement regardless of the r000 switch!

Quoted 7 lines
drivers/gpu/nova-core/gsp/cmdq.rs +0 -0
index 80e6e79c5f3c..a1c9b7cce255 100644
@@ -262,107 +262,69 @@ fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> {
          Ok(Self { mem: gsp_mem, bar })

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 268

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3 -4
      }
 
-    /// Returns the region of the CPU message queue that the driver is currently allowed to write
-    /// to.
+    /// Returns the region of the CPU message queue that the driver may write to.
      ///
-    /// As the message queue is a circular buffer, the region may be discontiguous in memory. In
-    /// that case the second slice will have a non-zero length.
+    /// The ring wraps, so the region comes as two slices, and the second is empty unless the
+    /// region crosses the end of the ring.

There is a recurring pattern in this series to drive-by rewrite comments when there is no real need to do so. The new comment is not even marginally better as we lose the temporal nature ("currently") of the borrow. This creates churn restating the same thing using different words and disrupts the diff, so can we avoid doing that unless the patch actually changes what the comment describes?

Quoted 4 lines
Quoted 1 line

That's a pretty common thing for LLM to do :)

We're lucky that one highlight of this revision was to remove AI comment churn. :)

So true! :)

I'll take action to avoid this sort of thing in the future, sorry about that.

thanks,

Signature · 1 line
John Hubbard
Quoted 108 lines
Quoted 98 lines
Quoted 98 lines
Quoted 46 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2 -35
      fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
-        let tx = self.cpu_write_ptr();
-        let rx = self.gsp_read_ptr();
+        let avail = num::u32_as_usize(self.free_slots());
+        let w_slot = num::u32_as_usize(self.cpu_write_ptr());
 
          // Pointer to the first entry of the CPU message queue.
          let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);
 
-        let (tail_end, wrap_end) = if rx == 0 {
-            // The write area is non-wrapping, and stops at the second-to-last entry of the command
-            // queue (to leave the last one empty).
-            (MSGQ_NUM_PAGES - 1, 0)
-        } else if rx <= tx {
-            // The write area wraps and continues until `rx - 1`.
-            (MSGQ_NUM_PAGES, rx - 1)
-        } else {
-            // The write area doesn't wrap and stops at `rx - 1`.
-            (rx - 1, 0)
-        };
-
          // SAFETY:
-        // - `data` was created from a valid pointer, and `rx` and `tx` are in the
-        //   `0..MSGQ_NUM_PAGES` range per the invariants of `cpu_write_ptr` and `gsp_read_ptr`,
-        //   thus the created slices are valid.
-        // - The area starting at `tx` and ending at `rx - 2` modulo `MSGQ_NUM_PAGES`,
-        //   inclusive, belongs to the driver for writing and is not accessed concurrently by
-        //   the GSP.
-        // - The caller holds a reference to `self` for as long as the returned slices are live,
-        //   meaning the CPU write pointer cannot be advanced and thus that the returned area
-        //   remains exclusive to the CPU for the duration of the slices.
-        // - The created slices point to non-overlapping sub-ranges of `data` in all
-        //   branches (in the `rx <= tx` case, the second slice ends at `rx - 1` which is strictly
-        //   less than `tx` where the first slice starts; in the other cases the second slice is
-        //   empty), so creating two `&mut` references from them does not violate aliasing rules.
-        unsafe {
-            (
-                core::slice::from_raw_parts_mut(
-                    data.add(num::u32_as_usize(tx)),
-                    num::u32_as_usize(tail_end - tx),
-                ),
-                core::slice::from_raw_parts_mut(data, num::u32_as_usize(wrap_end)),
-            )

drivers/gpu/nova-core/gsp/cmdq.rs fn new(dev: &'a device::Device<device::Bound>, bar: Bar0<'a>) -> Result<Self> { · line 285

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +9 -1
-        }
+        // - `data` points to the `MSGQ_NUM_PAGES` initialized entries of the CPU message queue.
+        // - The returned slices cover the `avail` free slots from the write pointer on, which the
+        //   GSP does not read until `advance_cpu_write_ptr` publishes them.
+        // - `split_at_mut` gives two non-overlapping halves, and the `&mut self` borrow lasts as
+        //   long as the returned slices, so that no other call hands out the same region while
+        //   they live.
+        let data =
+            unsafe { core::slice::from_raw_parts_mut(data, num::u32_as_usize(MSGQ_NUM_PAGES)) };
+        let (before_w, after_w) = data.split_at_mut(w_slot);

This creates a reference over the whole ring, including the parts owned by the GSP, which breaks the Coherent safety contract that the device must not be able to read or write to a live slice. So we'll need to call from_raw_parts_mut twice, with the correct sizes, instead of splitting.

(also split_at_mut is panicking and should have a PANIC: comment justifying why it cannot, but once the point above is addressed that call will go away).

I wanted to try it locally and ended up with something that seems to work, so let me share it to save some time:

     fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) {
         let avail = self.free_slots();
         let w_slot = self.cpu_write_ptr();

         // Pointer to the first entry of the CPU message queue.
         let data = ptr::project!(mut self.mem.as_mut_ptr(), .cpuq.msgq.data[build: 0]);

         let in_after = avail.min(MSGQ_NUM_PAGES - w_slot);
         let in_before = avail - in_after;

         // SAFETY:
         // - `data` was created from a valid pointer of `MSGQ_NUM_PAGES` entries.
         // - The `in_after` entries after `w_slot` belong to the `avail` entries that the driver is
         //   currently allowed to write.
         // - The `in_before` first entries belong to the `avail` entries that the driver is
         //   currently allowed to write.
         // - The slices do not overlap.
         unsafe {
             (
                 core::slice::from_raw_parts_mut(
                     data.add(num::u32_as_usize(w_slot)),
                     num::u32_as_usize(in_after),
                 ),
                 core::slice::from_raw_parts_mut(data, num::u32_as_usize(in_before)),
             )
         }
     }
Quoted 7 lines
Quoted 3 lines

It has turned out quite short, which I like! I also opted to work with the original u32 until the very end, as it results in less conversions overall.

Possibly take some thing from the old projection syntax rework series?

https://lore.kernel.org/rust-for-linux/[email protected]/

Oh yes, I forgot about this patch. Do you mean using ptr::project to create the final sub-slices, or am I missing something else?

#20 lore raw

PATCH v3 9/33 gpu: nova-core: add GMC API message types

In reply to John Hubbard

With the r570 firmware, every element on the GSP queues is an RM RPC message, and the driver builds and decodes only that form. The r000 firmware adds a second kind of element on the same queues, the GMC API message. GMC is the GPU Management Controller, and its API carries GSP-RM's boot and management commands. GSP-RM's newer interfaces use the GMC API rather than RPC messages, its ABI is stable, and on r000 the boot protocol itself runs over it.

Every element opens with the same two transport headers. The first is an MCTP header. MCTP is the Management Component Transport Protocol, and this is its packet header. The second is an NVDM header, the NVIDIA vendor-defined message header, whose type field selects the header that
follows: the RPC header or the GMC API header. A GMC API header has a fixed size and carries the command id, the payload size and a sequence number. Its last word is the largest response that the sender accepts, and in a response the same word carries the status.

Nova-core's queue types named the RPC header directly, so there was no way to build a GMC element or to tell one from an RPC element.

Add the types that a GMC element needs:

* The queue element header, which holds the two transport headers and the element's lengths, as a type of its own.

* The two NVDM type values that the GSP queues use, one for RPC and one for GMC.

* The GMC API header, and the element header that opens a GMC element with it.

The GMC API header is written out field by field rather than wrapped around the struct from the generated bindings. The bindings put the request and response fields of that header in a union, so reading the status of a response through them requires unsafe code. A struct written out with the same layout reads the status without unsafe code, and static assertions check that its layout matches the bindings.

The types have no user yet. The following patches add the send and receive paths for GMC elements, and the driver keeps booting r570 over RPC until the patch that switches firmware.

---
 drivers/gpu/nova-core/gsp/fw.rs | 220 ++++++++++++++++++++++++++++++++
 drivers/gpu/nova-core/mctp.rs   |   4 +
 2 files changed, 224 insertions(+)
drivers/gpu/nova-core/gsp/fw.rs +220 -0
index 285c23cea771..1aca5ca82764 100644
@@ -50,6 +50,11 @@
         cmdq::Cmdq, //
         GSP_PAGE_SIZE,
     },
+    mctp::{
+        MctpHeader,
+        NvdmHeader,
+        NvdmType, //
+    },
     num::{
         self,
         FromSafeCast, //
@@ -889,6 +894,221 @@ unsafe impl AsBytes for GspMsgElement {}
 // are valid.
 unsafe impl FromBytes for GspMsgElement {}
 
+/// First word of every queue element: `"MCTP"` in ASCII.
+const MCTP_MAGIC: u32 = 0x4D43_5450;
+
+/// The queue element header that opens every queue element, whatever kind of message follows.
+///
+/// It holds an MCTP (Management Component Transport Protocol) header and an NVDM (NVIDIA
+/// vendor-defined message) header. The NVDM type selects the message header that follows: the RPC
+/// header or the GMC (GPU Management Controller) API header.
+///
+/// ```text
+///     +------------------------------------+
+///     | queue element header               |  QueueElementHeader: magic, element length, MCTP
+///     |                                    |  header, NVDM header, message length
+///     +------------------------------------+
+///     | message header                     |  the RPC header or the GMC API header. The NVDM
+///     +------------------------------------+  type selects between the two.
+///     | payload                            |  command-specific data
+///     +------------------------------------+
+/// ```
+#[repr(C)]
+pub(crate) struct QueueElementHeader {
+    magic: u32,
+    /// Length of the whole element: the queue element header, the message header and the
+    /// payload. Open RM calls it `mctpPayloadSize`.
+    element_len: u32,
+    mctp: MctpHeader,
+    nvdm: NvdmHeader,
+    /// Length of the message header and the payload, the queue element header excluded. Open RM
+    /// calls it `nvdmPayloadSize`.
+    message_len: u32,
+    reserved: u32,
+}
+
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, magic)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpMagic)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, element_len)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpPayloadSize)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, mctp)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpHeader)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, nvdm)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, nvdmHeader)
+);
+
+#[expect(dead_code)]
+impl QueueElementHeader {
+    /// Builds the queue element header of an element whose message header and payload together
+    /// take `message_len` bytes.
+    ///
+    /// # Errors
+    ///
+    /// - `EOVERFLOW` if a length does not fit its 32-bit field.
+    fn new(nvdm: NvdmType, message_len: usize) -> Result<Self> {
+        Ok(Self {
+            magic: MCTP_MAGIC,
+            element_len: size_of::<Self>()
+                .checked_add(message_len)
+                .ok_or(EOVERFLOW)?
+                .try_into()
+                .map_err(|_| EOVERFLOW)?,
+            mctp: MctpHeader::single_packet(),
+            nvdm: NvdmHeader::new(nvdm),
+            message_len: message_len.try_into().map_err(|_| EOVERFLOW)?,
+            reserved: 0,
+        })
+    }
+
+    /// Returns the length of the whole element, the queue element header included.
+    fn element_len(&self) -> usize {
+        num::u32_as_usize(self.element_len)
+    }
+
+    /// Returns the length of the payload that follows a message header of `message_header_len`
+    /// bytes.
+    fn payload_len(&self, message_header_len: usize) -> usize {
+        num::u32_as_usize(self.message_len).saturating_sub(message_header_len)
+    }
+
+    /// Returns the number of queue slots that this element occupies.
+    fn element_count(&self) -> u32 {
+        self.element_len
+            .div_ceil(num::usize_into_u32::<GSP_PAGE_SIZE>())
+    }
+}
+
+// SAFETY: All fields are integer types or transparent wrappers over one, with no padding.
+unsafe impl AsBytes for QueueElementHeader {}
+
+// SAFETY: All fields are integer types for which all bit patterns are valid.
+unsafe impl FromBytes for QueueElementHeader {}
+
+/// Header of a GMC API message.
+#[repr(C)]
+#[derive(Zeroable)]
+pub(crate) struct GmcApiHeader {
+    /// Command id in the low three bytes, flags in the high byte.
+    pub(crate) command: u32,
+    /// Payload size in bytes.
+    pub(crate) size: u32,
+    /// Sequence number that GSP-RM copies from a request into its response.
+    pub(crate) sequence: u64,
+    /// In a request, the largest response that the sender accepts. In a response, the `NV_STATUS`.
+    pub(crate) max_resp_or_status: u32,
+    reserved: [u32; 5],
+}
+
+static_assert!(size_of::<GmcApiHeader>() == size_of::<r000_00::GMCAPI_HEADER>());
+static_assert!(
+    core::mem::offset_of!(GmcApiHeader, command)
+        == core::mem::offset_of!(r000_00::GMCAPI_HEADER, command)
+);
+static_assert!(
+    core::mem::offset_of!(GmcApiHeader, size)
+        == core::mem::offset_of!(r000_00::GMCAPI_HEADER, size)
+);
+static_assert!(
+    core::mem::offset_of!(GmcApiHeader, sequence)
+        == core::mem::offset_of!(r000_00::GMCAPI_HEADER, sequence)
+);
+static_assert!(
+    core::mem::offset_of!(GmcApiHeader, max_resp_or_status)
+        == core::mem::offset_of!(r000_00::GMCAPI_HEADER, __bindgen_anon_1)
+);
+static_assert!(
+    core::mem::offset_of!(GmcApiHeader, reserved)
+        == core::mem::offset_of!(r000_00::GMCAPI_HEADER, reserved)
+);
+
+impl GmcApiHeader {
+    /// Returns the `NV_STATUS` that a response carries.
+    ///
+    /// The value is meaningful only on a response, which GSP-RM marks with a flag in the command
+    /// word. In a request, the same word holds the largest response that the sender accepts.
+    #[expect(dead_code)]
+    pub(crate) fn status(&self) -> u32 {
+        self.max_resp_or_status
+    }
+}
+
+// SAFETY: All fields are integer types with no uninitialized padding bytes.
+unsafe impl AsBytes for GmcApiHeader {}
+
+// SAFETY: All fields are integer types for which all bit patterns are valid.
+unsafe impl FromBytes for GmcApiHeader {}
+
+/// The headers that open a GMC API queue element: the queue element header and the GMC API
+/// header.
+#[repr(C)]
+pub(crate) struct GspGmcMsgElement {
+    element_header: QueueElementHeader,
+    pub(crate) gmc: GmcApiHeader,
+}
+
+// `AsBytes` below requires that no padding separates the two headers.
+static_assert!(
+    size_of::<GspGmcMsgElement>() == size_of::<QueueElementHeader>() + size_of::<GmcApiHeader>()
+);
+
+#[expect(dead_code)]
+impl GspGmcMsgElement {
+    /// Creates the queue element header and the GMC API header of a request that carries
+    /// `payload_size` bytes of payload.
+    ///
+    /// `max_response_size` is the largest response that the sender accepts, and zero for a request
+    /// that GSP-RM does not answer.
+    ///
+    /// # Errors
+    ///
+    /// - `EOVERFLOW` if a length does not fit its 32-bit field.
+    pub(crate) fn init(
+        command_id: u32,
+        sequence: u64,
+        payload_size: usize,
+        max_response_size: u32,
+    ) -> impl Init<Self, Error> {
+        try_init!(GspGmcMsgElement {
+            element_header: QueueElementHeader::new(
+                NvdmType::GmcApi,
+                size_of::<GmcApiHeader>()
+                    .checked_add(payload_size)
+                    .ok_or(EOVERFLOW)?,
+            )?,
+            gmc: GmcApiHeader {
+                command: command_id,
+                size: payload_size.try_into().map_err(|_| EOVERFLOW)?,
+                sequence,
+                max_resp_or_status: max_response_size,
+                reserved: [0; 5],
+            },
+        })
+    }
+
+    /// Returns the length of the whole element, both headers included.
+    pub(crate) fn length(&self) -> usize {
+        self.element_header.element_len()
+    }
+
+    /// Returns the number of queue slots that this element occupies.
+    pub(crate) fn element_count(&self) -> u32 {
+        self.element_header.element_count()
+    }
+}
+
+// SAFETY: All fields are integer types with no uninitialized padding bytes.
+unsafe impl AsBytes for GspGmcMsgElement {}
+
+// SAFETY: All fields are integer types for which all bit patterns are valid.
+unsafe impl FromBytes for GspGmcMsgElement {}
+
 /// Arguments for GSP startup.
 #[repr(transparent)]
 #[derive(Zeroable)]
drivers/gpu/nova-core/mctp.rs +4 -0
index a3872a740233..0eb964c74e32 100644
@@ -28,6 +28,10 @@ pub(crate) enum NvdmType with TryFrom<Bounded<u32, 8>> {
         Cot = 0x14,
         /// FSP command response.
         FspResponse = 0x15,
+        /// RPC message to or from GSP-RM.
+        RmRpc = 0x25,
+        /// GMC (GPU Management Controller) API message to or from GSP-RM.
+        GmcApi = 0x26,
     }
 }
 
Signature · 1 line
2.55.0
#21 lore raw

Re: [PATCH v3 09/33] gpu: nova-core: add GMC API message types

Quoted 22 lines · John Hubbard
drivers/gpu/nova-core/gsp/fw.rs +9 -0
+#[repr(C)]
+pub(crate) struct QueueElementHeader {
+    magic: u32,
+    /// Length of the whole element: the queue element header, the message header and the
+    /// payload. Open RM calls it `mctpPayloadSize`.
+    element_len: u32,
+    mctp: MctpHeader,
+    nvdm: NvdmHeader,
+    /// Length of the message header and the payload, the queue element header excluded. Open

RM
+    /// calls it nvdmPayloadSize.
+    message_len: u32,
+    reserved: u32,

drivers/gpu/nova-core/gsp/fw.rs +8 -0
+}
+
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, magic)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpMagic)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, element_len)

drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for GspMsgElement {} · line 945

Quoted 10 lines
drivers/gpu/nova-core/gsp/fw.rs +10 -0
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpPayloadSize)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, mctp)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpHeader)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, nvdm)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, nvdmHeader)
+);

Can you also static_assert! on the size of the struct?

Quoted 6 lines

+    /// Returns the length of the payload that follows a message header of +    /// Returns the length of the payload that follows a message header of message_header_len
+    /// bytes.
+    fn payload_len(&self, message_header_len: usize) -> usize {
+        num::u32_as_usize(self.message_len).saturating_sub(message_header_len)

Is it possible for message_header_len to exceed self.message_len? If so, then I think that warrants a comment. If not, well, then that should have a comment, too.

#22 lore raw

Re: [PATCH v3 09/33] gpu: nova-core: add GMC API message types

Quoted 27 lines · Timur Tabi
Quoted 26 lines · John Hubbard
drivers/gpu/nova-core/gsp/fw.rs +9 -0
+#[repr(C)]
+pub(crate) struct QueueElementHeader {
+    magic: u32,
+    /// Length of the whole element: the queue element header, the message header and the
+    /// payload. Open RM calls it `mctpPayloadSize`.
+    element_len: u32,
+    mctp: MctpHeader,
+    nvdm: NvdmHeader,
+    /// Length of the message header and the payload, the queue element header excluded. Open

RM
+    /// calls it nvdmPayloadSize.
+    message_len: u32,
+    reserved: u32,

drivers/gpu/nova-core/gsp/fw.rs +12 -0
+}
+
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, magic)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpMagic)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, element_len)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpPayloadSize)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, mctp)
Quoted 8 lines

drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for GspMsgElement {} · line 945

Quoted 6 lines

+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpHeader)

drivers/gpu/nova-core/gsp/fw.rs +5 -0
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, nvdm)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, nvdmHeader)
+);

Can you also static_assert! on the size of the struct?

Not directly, because it's got a union involved, but I've added in some assorted static_asserts that attempt to cover as much as can be asserted in this situation.

Open RM's layout:

  typedef struct {
      NvU32 mctpMagic;
      NvU32 mctpPayloadSize;
      NvU32 mctpHeader;
      NvU32 nvdmHeader;
      union {
          struct {
              GSP_MSG_QUEUE_ENCRYPTION_TAG encryptionTag;  /* 16 bytes */
              NvU32 nvdmPayloadSize;
              NvU32 reserved;
              NvU8  payload[];
          } withEncryption;
          struct {
              NvU32 nvdmPayloadSize;
              NvU32 reserved;
              NvU8  payload[];
          } noEncryption;
      };
  } GSP_MSG_QUEUE_ELEMENT;

QueueElementHeader uses the noEncryption layout.

Open RM has the same mismatch and defines the unencrypted size separately, as GSP_MSG_QUEUE_ELEMENT_SIZE_NO_ENCRYPTION, which is the offset of the union plus two words.

I've added these static asserts, for v4:

* The size of QueueElementHeader equals the offset of the union plus the size of the noEncryption struct.

* The offset of message_len equals the offset of the union plus the offset of nvdmPayloadSize within noEncryption.

* The offset of reserved equals the offset of the union plus the offset of reserved within noEncryption.

Quoted 10 lines
Quoted 7 lines

+    /// Returns the length of the payload that follows a message header of +    /// Returns the length of the payload that follows a message header of message_header_len
+    /// bytes.
+    fn payload_len(&self, message_header_len: usize) -> usize {
+        num::u32_as_usize(self.message_len).saturating_sub(message_header_len)

Is it possible for message_header_len to exceed self.message_len? If so, then I think that warrants a comment. If not, well, then that should have a comment, too.

Yes, it is possible.

So, in v4, I've made this return an Option<usize> in this patch, instead of waiting until later patches to do that.

The v4 doc comment on payload_len() now says that None means the message length in the queue element header is shorter than the message header.

thanks,

Signature · 1 line
John Hubbard
#23 lore raw

Re: [PATCH v3 09/33] gpu: nova-core: add GMC API message types

In reply to John Hubbard

On Fri Sep 18, 2026 at 10:06 AM JST, John Hubbard wrote:
<...>

Quoted 32 lines
drivers/gpu/nova-core/gsp/fw.rs +17 -0
index 285c23cea771..1aca5ca82764 100644
@@ -50,6 +50,11 @@
         cmdq::Cmdq, //
         GSP_PAGE_SIZE,
     },
+    mctp::{
+        MctpHeader,
+        NvdmHeader,
+        NvdmType, //
+    },
     num::{
         self,
         FromSafeCast, //
@@ -889,6 +894,221 @@ unsafe impl AsBytes for GspMsgElement {}
 // are valid.
 unsafe impl FromBytes for GspMsgElement {}
 
+/// First word of every queue element: `"MCTP"` in ASCII.
+const MCTP_MAGIC: u32 = 0x4D43_5450;
+
+/// The queue element header that opens every queue element, whatever kind of message follows.
+///
+/// It holds an MCTP (Management Component Transport Protocol) header and an NVDM (NVIDIA
+/// vendor-defined message) header. The NVDM type selects the message header that follows: the RPC
+/// header or the GMC (GPU Management Controller) API header.
+///
+/// ```text
+///     +------------------------------------+
+///     | queue element header               |  QueueElementHeader: magic, element length, MCTP

drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for GspMsgElement {} · line 918

Quoted 10 lines
drivers/gpu/nova-core/gsp/fw.rs +10 -0
+///     |                                    |  header, NVDM header, message length
+///     +------------------------------------+
+///     | message header                     |  the RPC header or the GMC API header. The NVDM
+///     +------------------------------------+  type selects between the two.
+///     | payload                            |  command-specific data
+///     +------------------------------------+
+/// ```
+#[repr(C)]
+pub(crate) struct QueueElementHeader {
+    magic: u32,

Do we want to mention that the expected value is MCTP_MAGIC?

drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for GspMsgElement {} · line 920

Quoted 2 lines
drivers/gpu/nova-core/gsp/fw.rs +2 -0
+    /// Length of the whole element: the queue element header, the message header and the
+    /// payload. Open RM calls it `mctpPayloadSize`.

We probably don't care what OpenRM (without a space :)) calls it. But why not use the same name, so the relationship becomes clear?

drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for GspMsgElement {} · line 926

Quoted 6 lines
drivers/gpu/nova-core/gsp/fw.rs +6 -0
+    element_len: u32,
+    mctp: MctpHeader,
+    nvdm: NvdmHeader,
+    /// Length of the message header and the payload, the queue element header excluded. Open RM
+    /// calls it `nvdmPayloadSize`.
+    message_len: u32,

Same here. Btw, reading at the comment, it sounds like message_len is always equal to element_len - size_of::<QueueElementHeader>? Or am I misreading?

Quoted 9 lines
drivers/gpu/nova-core/gsp/fw.rs +9 -0
+    reserved: u32,
+}
+
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, magic)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpMagic)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, element_len)

drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for GspMsgElement {} · line 945

Quoted 10 lines
drivers/gpu/nova-core/gsp/fw.rs +10 -0
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpPayloadSize)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, mctp)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, mctpHeader)
+);
+static_assert!(
+    core::mem::offset_of!(QueueElementHeader, nvdm)
+        == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, nvdmHeader)
+);

Mmm, that's not great. Basically we are redefining a new type that is mirroring a binding-generated type, and relying on these asserts to make sure the two types match. All that because GSP_MSG_QUEUE_ELEMENT has too long a size due to the encryption support part.

This is something where I would like to ask OpenRM to revise their definition so we can leverage the generated bindings properly, and end up with just

  pub(crate) struct QueueElementHeader(r000_00::GSP_MSG_QUEUE_ELEMENT);

But in the meantime, I guess defining our own type like this patch does is the only viable route. Let's add a (short) note explaining the reason for this though.

If we confirm the layout at build-time though, we should also assert the offsets of the members in the union - which IIUC from your reply to Timur you already did.

Quoted 24 lines
drivers/gpu/nova-core/gsp/fw.rs +24 -0
+
+#[expect(dead_code)]
+impl QueueElementHeader {
+    /// Builds the queue element header of an element whose message header and payload together
+    /// take `message_len` bytes.
+    ///
+    /// # Errors
+    ///
+    /// - `EOVERFLOW` if a length does not fit its 32-bit field.
+    fn new(nvdm: NvdmType, message_len: usize) -> Result<Self> {
+        Ok(Self {
+            magic: MCTP_MAGIC,
+            element_len: size_of::<Self>()
+                .checked_add(message_len)
+                .ok_or(EOVERFLOW)?
+                .try_into()
+                .map_err(|_| EOVERFLOW)?,
+            mctp: MctpHeader::single_packet(),
+            nvdm: NvdmHeader::new(nvdm),
+            message_len: message_len.try_into().map_err(|_| EOVERFLOW)?,
+            reserved: 0,
+        })
+    }
+

drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for GspMsgElement {} · line 979

Quoted 10 lines
drivers/gpu/nova-core/gsp/fw.rs +10 -0
+    /// Returns the length of the whole element, the queue element header included.
+    fn element_len(&self) -> usize {
+        num::u32_as_usize(self.element_len)
+    }
+
+    /// Returns the length of the payload that follows a message header of `message_header_len`
+    /// bytes.
+    fn payload_len(&self, message_header_len: usize) -> usize {
+        num::u32_as_usize(self.message_len).saturating_sub(message_header_len)
+    }

Passing the header length looks awkward and error-prone, and as discussed with Timur you then need to manage errors (which was done in the "add GMC transport receive path" patch rather than now).

There are only two callers of this, one per header type, let's make the caller responsible for subtracting their own header after they have matched against it instead of unconditionally subtracting an arbitrary amount here.

Quoted 9 lines
drivers/gpu/nova-core/gsp/fw.rs +9 -0
+
+    /// Returns the number of queue slots that this element occupies.
+    fn element_count(&self) -> u32 {
+        self.element_len
+            .div_ceil(num::usize_into_u32::<GSP_PAGE_SIZE>())
+    }
+}
+
+// SAFETY: All fields are integer types or transparent wrappers over one, with no padding.

drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for GspMsgElement {} · line 998

Quoted 10 lines
drivers/gpu/nova-core/gsp/fw.rs +10 -0
+unsafe impl AsBytes for QueueElementHeader {}
+
+// SAFETY: All fields are integer types for which all bit patterns are valid.
+unsafe impl FromBytes for QueueElementHeader {}
+
+/// Header of a GMC API message.
+#[repr(C)]
+#[derive(Zeroable)]
+pub(crate) struct GmcApiHeader {
+    /// Command id in the low three bytes, flags in the high byte.

... then this should be a bitfield type. :) Especially since I see we are doing some bit-masking in later patches. Commands can then be a nicely-defined enum used for the relevant field.

Quoted 21 lines
drivers/gpu/nova-core/gsp/fw.rs +21 -0
+    pub(crate) command: u32,
+    /// Payload size in bytes.
+    pub(crate) size: u32,
+    /// Sequence number that GSP-RM copies from a request into its response.
+    pub(crate) sequence: u64,
+    /// In a request, the largest response that the sender accepts. In a response, the `NV_STATUS`.
+    pub(crate) max_resp_or_status: u32,
+    reserved: [u32; 5],
+}
+
+static_assert!(size_of::<GmcApiHeader>() == size_of::<r000_00::GMCAPI_HEADER>());
+static_assert!(
+    core::mem::offset_of!(GmcApiHeader, command)
+        == core::mem::offset_of!(r000_00::GMCAPI_HEADER, command)
+);
+static_assert!(
+    core::mem::offset_of!(GmcApiHeader, size)
+        == core::mem::offset_of!(r000_00::GMCAPI_HEADER, size)
+);
+static_assert!(
+    core::mem::offset_of!(GmcApiHeader, sequence)

drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for GspMsgElement {} · line 1029

Quoted 10 lines
drivers/gpu/nova-core/gsp/fw.rs +10 -0
+        == core::mem::offset_of!(r000_00::GMCAPI_HEADER, sequence)
+);
+static_assert!(
+    core::mem::offset_of!(GmcApiHeader, max_resp_or_status)
+        == core::mem::offset_of!(r000_00::GMCAPI_HEADER, __bindgen_anon_1)
+);
+static_assert!(
+    core::mem::offset_of!(GmcApiHeader, reserved)
+        == core::mem::offset_of!(r000_00::GMCAPI_HEADER, reserved)
+);

So for this one the story is different than QueueElementHeader:
GMCAPI_HEADER has the right size and a layout that we can wrap, so here we have no excuse for not defining a newtype instead of doing this tedious checking.

I understand there is an union and this requires an unsafe block to read, but we would need exactly one, in the status method. Which imho is better than adding ~60 LoCs redefining what we already have and confirming what we already know.

Quoted 64 lines
drivers/gpu/nova-core/gsp/fw.rs +64 -0
+
+impl GmcApiHeader {
+    /// Returns the `NV_STATUS` that a response carries.
+    ///
+    /// The value is meaningful only on a response, which GSP-RM marks with a flag in the command
+    /// word. In a request, the same word holds the largest response that the sender accepts.
+    #[expect(dead_code)]
+    pub(crate) fn status(&self) -> u32 {
+        self.max_resp_or_status
+    }
+}
+
+// SAFETY: All fields are integer types with no uninitialized padding bytes.
+unsafe impl AsBytes for GmcApiHeader {}
+
+// SAFETY: All fields are integer types for which all bit patterns are valid.
+unsafe impl FromBytes for GmcApiHeader {}
+
+/// The headers that open a GMC API queue element: the queue element header and the GMC API
+/// header.
+#[repr(C)]
+pub(crate) struct GspGmcMsgElement {
+    element_header: QueueElementHeader,
+    pub(crate) gmc: GmcApiHeader,
+}
+
+// `AsBytes` below requires that no padding separates the two headers.
+static_assert!(
+    size_of::<GspGmcMsgElement>() == size_of::<QueueElementHeader>() + size_of::<GmcApiHeader>()
+);
+
+#[expect(dead_code)]
+impl GspGmcMsgElement {
+    /// Creates the queue element header and the GMC API header of a request that carries
+    /// `payload_size` bytes of payload.
+    ///
+    /// `max_response_size` is the largest response that the sender accepts, and zero for a request
+    /// that GSP-RM does not answer.
+    ///
+    /// # Errors
+    ///
+    /// - `EOVERFLOW` if a length does not fit its 32-bit field.
+    pub(crate) fn init(
+        command_id: u32,
+        sequence: u64,
+        payload_size: usize,
+        max_response_size: u32,
+    ) -> impl Init<Self, Error> {
+        try_init!(GspGmcMsgElement {
+            element_header: QueueElementHeader::new(
+                NvdmType::GmcApi,
+                size_of::<GmcApiHeader>()
+                    .checked_add(payload_size)
+                    .ok_or(EOVERFLOW)?,
+            )?,
+            gmc: GmcApiHeader {
+                command: command_id,
+                size: payload_size.try_into().map_err(|_| EOVERFLOW)?,
+                sequence,
+                max_resp_or_status: max_response_size,
+                reserved: [0; 5],
+            },
+        })
+    }

drivers/gpu/nova-core/gsp/fw.rs unsafe impl AsBytes for GspMsgElement {} · line 1103

Quoted 10 lines
drivers/gpu/nova-core/gsp/fw.rs +10 -0
+
+    /// Returns the length of the whole element, both headers included.
+    pub(crate) fn length(&self) -> usize {
+        self.element_header.element_len()
+    }
+
+    /// Returns the number of queue slots that this element occupies.
+    pub(crate) fn element_count(&self) -> u32 {
+        self.element_header.element_count()
+    }

Let's provide an element_header returning the header which the caller can then query instead of one proxy method per method of the header we want to access.

#24 lore raw

PATCH v3 10/33 gpu: nova-core: add GMC send path

In reply to John Hubbard

The r000 boot protocol has the driver send GSP_INIT, the request that carries the driver's configuration to GSP-RM, as a GMC command. GMC and RPC commands share the command queue and the RPC sequence counter, and a GMC element, unlike an RPC element, carries no checksum.

Nova-core's send path filled in RPC elements only, so there was no way to send a GMC command.

Add a send path for GMC commands. It has no caller yet. A following patch adds the GSP_INIT sender.

---
 drivers/gpu/nova-core/gsp/cmdq.rs | 43 +++++++++++++++++++++++++++++++
 drivers/gpu/nova-core/gsp/fw.rs   |  1 -
 2 files changed, 43 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/gsp/cmdq.rs +43 -0
index a1c9b7cce255..c0c3d8596b30 100644
@@ -54,6 +54,7 @@
     driver::Bar0,
     gsp::{
         fw::{
+            GspGmcMsgElement,
             GspMsgElement,
             MsgFunction,
             MsgqRxHeader,
@@ -749,6 +750,48 @@ fn poison(&self, reason: fmt::Arguments<'_>) -> Error {
         EIO
     }
 
+    /// Sends a GMC API request to the GSP.
+    ///
+    /// `payload` follows the GMC API header in the element, and `max_response_size` is the largest
+    /// response that the caller accepts. The request carries the next sequence number, which GSP-RM
+    /// copies into its response. The number is consumed even if the send fails.
+    ///
+    /// # Errors
+    ///
+    /// Errors from [`DmaGspMem::allocate_command`] are propagated as-is.
+    #[expect(dead_code)]
+    fn send_gmc(&mut self, command_id: u32, payload: &[u8], max_response_size: u32) -> Result {
+        let seq = self.seq;
+        self.seq = self.seq.wrapping_add(1);
+
+        let dst = self
+            .gsp_mem
+            .allocate_command::<GspGmcMsgElement>(payload.len(), Self::ALLOCATE_TIMEOUT)?;
+
+        let msg_element =
+            GspGmcMsgElement::init(command_id, u64::from(seq), payload.len(), max_response_size);
+        // SAFETY: `dst.header` is a valid reference, and not written if the initializer fails.
+        unsafe {
+            pin_init::raw_try_init(core::ptr::from_mut(dst.header), msg_element)?;
+        }
+
+        SBufferIter::new_writer([&mut dst.contents.0[..], &mut dst.contents.1[..]])
+            .write_all(payload)?;
+
+        dev_dbg!(
+            &self.dev,
+            "GSP GMC: send: seq# {}, command_id=0x{:x}, length=0x{:x}\n",
+            seq,
+            command_id,
+            dst.header.length(),
+        );
+
+        let elem_count = dst.header.element_count();
+        self.gsp_mem.advance_cpu_write_ptr(elem_count);
+
+        Ok(())
+    }
+
     /// Wait for a message to become available on the message queue.
     ///
     /// This works purely at the transport layer and does not interpret or validate the message
drivers/gpu/nova-core/gsp/fw.rs +0 -1
index 1aca5ca82764..75bc3d66f71f 100644
@@ -1058,7 +1058,6 @@ pub(crate) struct GspGmcMsgElement {
     size_of::<GspGmcMsgElement>() == size_of::<QueueElementHeader>() + size_of::<GmcApiHeader>()
 );
 
-#[expect(dead_code)]
 impl GspGmcMsgElement {
     /// Creates the queue element header and the GMC API header of a request that carries
     /// `payload_size` bytes of payload.
Signature · 1 line
2.55.0
#25 lore raw

Re: [PATCH v3 10/33] gpu: nova-core: add GMC send path

Quoted 37 lines · John Hubbard

The r000 boot protocol has the driver send GSP_INIT, the request that carries the driver's configuration to GSP-RM, as a GMC command. GMC and RPC commands share the command queue and the RPC sequence counter, and a GMC element, unlike an RPC element, carries no checksum.

Nova-core's send path filled in RPC elements only, so there was no way to send a GMC command.

Add a send path for GMC commands. It has no caller yet. A following patch adds the GSP_INIT sender.

---
 drivers/gpu/nova-core/gsp/cmdq.rs | 43 +++++++++++++++++++++++++++++++
 drivers/gpu/nova-core/gsp/fw.rs   |  1 -
 2 files changed, 43 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/gsp/cmdq.rs +2 -0
index a1c9b7cce255..c0c3d8596b30 100644
@@ -54,6 +54,7 @@
     driver::Bar0,
     gsp::{
         fw::{
+            GspGmcMsgElement,
             GspMsgElement,
             MsgFunction,
             MsgqRxHeader,
@@ -749,6 +750,48 @@ fn poison(&self, reason: fmt::Arguments<'_>) -> Error {
         EIO
     }
 
+    /// Sends a GMC API request to the GSP.

drivers/gpu/nova-core/gsp/cmdq.rs fn poison(&self, reason: fmt::Arguments<'_>) -> Error { · line 763

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +10 -0
+    ///
+    /// `payload` follows the GMC API header in the element, and `max_response_size` is the largest
+    /// response that the caller accepts. The request carries the next sequence number, which GSP-RM
+    /// copies into its response. The number is consumed even if the send fails.
+    ///
+    /// # Errors
+    ///
+    /// Errors from [`DmaGspMem::allocate_command`] are propagated as-is.
+    #[expect(dead_code)]
+    fn send_gmc(&mut self, command_id: u32, payload: &[u8], max_response_size: u32) -> Result {

This is basically a mirror of send_command for GMC commands (or rather send_single_command since GMC appears to not have split commands).

Only it's not quite as good: send_command is generic over its command using the CommandToGsp trait, which is nice as it establishes a relationship between commands and their expected responses. The GMC counterparts completely dismantle that and work with raw u32s, even though it would benefit even more from having structure, as I see later that each command (hard to tell though since we only have one at the moment) seems to have their own maximum response size, which could be an associated constant.

Looking down the series at gsp_init, it passes both the expected command ID and a function to decode the response to await_gmc_response from a dedicated helper, whereas RPCs just need to call send_command* and know whether to wait for a response, and how to decode it just through their type. That GMC is unable to function similarly is a serious step back.

I also want to understand whether we need to keep using RPC alongside GMC, because by the end of this series RPC is still there as dead code (except maybe for GSP events?) and if this code is here to stay then we need to factor out the send paths a bit more than that, and separate the two mechanisms more clearly.

Because right now both cmdq.rs and fw.rs have types and methods for handling both mixed together and that's quite messy. So if both are to coexist we should have gmc and rpc sub-modules to keep them properly separated.

#26 lore raw

PATCH v3 11/33 gpu: nova-core: add GMC transport receive path

In reply to John Hubbard

The r000 firmware posts GMC and RPC messages on the same queue. Behind the transport headers, a GMC element carries a GMC header instead of an RPC header.

Nova-core's receive path decoded RPC elements only.

Add a receive path for GMC elements. It validates the transport headers before it trusts the length that they declare, as Open RM does. The read pointer advances by that length, so a bad header leaves no way to find the next element. The receive path poisons the queue on a bad header, and every later receive fails until the device is reset. The GMC receive path has no caller yet.

---
 drivers/gpu/nova-core/gsp/cmdq.rs | 167 ++++++++++++++++++++++++++----
 drivers/gpu/nova-core/gsp/fw.rs   |  64 ++++++++++--
 drivers/gpu/nova-core/mctp.rs     |  14 ++-
 3 files changed, 214 insertions(+), 31 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +144 -23
index c0c3d8596b30..a1bf536dc109 100644
@@ -59,12 +59,14 @@
             MsgFunction,
             MsgqRxHeader,
             MsgqTxHeader,
+            QueueElementHeader,
             GSP_MSG_QUEUE_ELEMENT_SIZE_MAX, //
         },
         PteArray,
         GSP_PAGE_SHIFT,
         GSP_PAGE_SIZE, //
     },
+    mctp::NvdmType,
     num,
     sbuffer::SBufferIter, //
 };
@@ -475,6 +477,44 @@ struct GspMessage<'a> {
     contents: (&'a [u8], &'a [u8]),
 }
 
+/// A GMC (GPU Management Controller) API message ready to be processed from the message queue.
+///
+/// This is the message that [`QueueElement::Gmc`] carries.
+#[expect(dead_code)]
+struct GmcMessage<'a> {
+    // The queue element header and the GMC API header that open the element.
+    header: &'a GspGmcMsgElement,
+    // Slices to the payload that follows the GMC API header. The second slice is empty unless the
+    // payload wraps around the end of the message queue.
+    contents: (&'a [u8], &'a [u8]),
+}
+
+/// A queue element that has passed validation, decoded as an RPC message or as a GMC API message.
+///
+/// The queue element header holds an MCTP (Management Component Transport Protocol) header and an
+/// NVDM (NVIDIA vendor-defined message) header. The NVDM type selects between the two kinds of
+/// message.
+///
+/// This is the type returned by [`CmdqInner::wait_for_element`].
+enum QueueElement<'a> {
+    /// A GMC API message.
+    Gmc(GmcMessage<'a>),
+    /// An element whose NVDM type names another kind of message, such as an RM RPC. Only its
+    /// queue element header is decoded.
+    Other(&'a QueueElementHeader),
+}
+
+impl QueueElement<'_> {
+    /// Returns the number of queue slots that the element occupies.
+    #[expect(dead_code)]
+    fn element_count(&self) -> u32 {
+        match self {
+            Self::Gmc(message) => message.header.element_count(),
+            Self::Other(element_header) => element_header.element_count(),
+        }
+    }
+}
+
 /// GSP command queue.
 ///
 /// Provides the ability to send commands and receive messages from the GSP using a shared memory
@@ -838,29 +878,7 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
             header.length(),
         );
 
-        let payload_length = header.payload_length();
-
-        // Check that the driver read area is large enough for the message.
-        if slice_1.len() + slice_2.len() < payload_length {
-            return Err(self.poison(fmt!(
-                "message advertises {} payload bytes but only {} are readable",
-                payload_length,
-                slice_1.len() + slice_2.len()
-            )));
-        }
-
-        // Cut the message slices down to the actual length of the message.
-        let (slice_1, slice_2) = if slice_1.len() > payload_length {
-            // PANIC: we checked above that `slice_1` is at least as long as `payload_length`.
-            (slice_1.split_at(payload_length).0, &slice_2[0..0])
-        } else {
-            (
-                slice_1,
-                // PANIC: we checked above that `slice_1.len() + slice_2.len()` is at least as
-                // large as `payload_length`.
-                slice_2.split_at(payload_length - slice_1.len()).0,
-            )
-        };
+        let (slice_1, slice_2) = self.payload_slices(slice_1, slice_2, header.payload_length())?;
 
         // Validate checksum.
         if Cmdq::calculate_checksum(SBufferIter::new_reader([
@@ -1029,4 +1047,107 @@ fn drain(&mut self) -> Result {
 
         Ok(())
     }
+
+    /// Truncates the read area that follows the queue element header and the message header to
+    /// the `payload_length` bytes of payload.
+    ///
+    /// # Errors
+    ///
+    /// - `EIO` if fewer bytes than that are readable, which poisons the queue.
+    fn payload_slices<'a>(
+        &self,
+        slice_1: &'a [u8],
+        slice_2: &'a [u8],
+        payload_length: usize,
+    ) -> Result<(&'a [u8], &'a [u8])> {
+        if slice_1.len() + slice_2.len() < payload_length {
+            return Err(self.poison(fmt!(
+                "message advertises {} payload bytes but only {} are readable",
+                payload_length,
+                slice_1.len() + slice_2.len()
+            )));
+        }
+
+        Ok(if slice_1.len() > payload_length {
+            // PANIC: we checked above that `slice_1` is at least as long as `payload_length`.
+            (slice_1.split_at(payload_length).0, &slice_2[0..0])
+        } else {
+            (
+                slice_1,
+                // PANIC: we checked above that `slice_1.len() + slice_2.len()` is at least as
+                // large as `payload_length`.
+                slice_2.split_at(payload_length - slice_1.len()).0,
+            )
+        })
+    }
+
+    /// Waits for the next queue element and decodes it as an RPC message or as a GMC API message.
+    ///
+    /// ```text
+    ///     +------------------------------------+
+    ///     | queue element header: magic, MCTP  |  validated
+    ///     |   header, NVDM header, lengths     |
+    ///     +------------------------------------+
+    ///     | message header                     |  decoded as a GMC API header when the NVDM type
+    ///     +------------------------------------+  is GmcApi, and left undecoded otherwise
+    ///     | payload                            |  truncated to the length that the queue
+    ///     +------------------------------------+  element header declares
+    /// ```
+    ///
+    /// # Errors
+    ///
+    /// - `ETIMEDOUT` if no element arrives within `timeout`.
+    /// - `EIO` if the queue is already poisoned, or if the framing is invalid, which poisons it
+    ///   (see [`Self::poisoned`]).
+    #[expect(dead_code)]
+    fn wait_for_element(&self, timeout: Delta) -> Result<QueueElement<'_>> {
+        if self.poisoned.get() {
+            return Err(EIO);
+        }
+
+        let (slice_1, slice_2) = read_poll_timeout(
+            || Ok(self.gsp_mem.driver_read_area()),
+            |driver_area| !driver_area.0.is_empty(),
+            Delta::from_millis(1),
+            timeout,
+        )
+        .map(|(slice_1, slice_2)| (slice_1.as_flattened(), slice_2.as_flattened()))?;
+
+        let Some((element_header, _)) = QueueElementHeader::from_bytes_prefix(slice_1) else {
+            return Err(self.poison(fmt!(
+                "read area of {} bytes is shorter than a queue element header",
+                slice_1.len()
+            )));
+        };
+
+        if let Err(error) = element_header.validate() {
+            return Err(self.poison(fmt!(
+                "element has a bad queue element header ({:?}), declared length {}",
+                error,
+                element_header.element_len()
+            )));
+        }
+
+        if !element_header.is_nvdm_type(NvdmType::GmcApi) {
+            return Ok(QueueElement::Other(element_header));
+        }
+
+        let Some((header, slice_1)) = GspGmcMsgElement::from_bytes_prefix(slice_1) else {
+            return Err(self.poison(fmt!(
+                "read area of {} bytes is shorter than a GMC element header",
+                slice_1.len()
+            )));
+        };
+
+        let Some(payload_length) = header.payload_length() else {
+            return Err(self.poison(fmt!(
+                "GMC message seq# {} declares a message shorter than the GMC API header",
+                header.gmc.sequence
+            )));
+        };
+
+        let contents = self.payload_slices(slice_1, slice_2, payload_length)?;
+
+        Ok(QueueElement::Gmc(GmcMessage { header, contents }))
+    }
 }
drivers/gpu/nova-core/gsp/fw.rs +58 -6

92 lines not on this page · raw message

drivers/gpu/nova-core/mctp.rs +12 -2
index 0eb964c74e32..d2a7c6c02c35 100644
@@ -70,6 +70,11 @@ pub(crate) fn single_packet() -> Self {
     pub(crate) fn is_single_packet(self) -> bool {
         self.som().into_bool() && self.eom().into_bool()
     }
+
+    /// Returns `true` if this MCTP header carries [`Self::VERSION`].
+    pub(crate) fn has_expected_version(self) -> bool {
+        u32::from(self.version()) == Self::VERSION
+    }
 }
 
 /// MCTP message type for PCI vendor-defined messages.
@@ -96,10 +101,15 @@ pub(crate) fn new(nvdm_type: NvdmType) -> Self {
             .with_nvdm_type(nvdm_type)
     }
 
-    /// Validates this header against the expected NVIDIA NVDM format and type.
-    pub(crate) fn validate(self, expected_type: NvdmType) -> bool {
+    pub(crate) fn has_nvidia_vendor(self) -> bool {
         u8::from(self.msg_type()) == MSG_TYPE_VENDOR_PCI
             && u16::from(self.vendor_id()) == Vendor::NVIDIA.as_raw()
+    }
+
+    /// Returns `true` if this NVDM header names the NVIDIA vendor and the NVDM type
+    /// `expected_type`.
+    pub(crate) fn validate(self, expected_type: NvdmType) -> bool {
+        self.has_nvidia_vendor()
             && matches!(self.nvdm_type(), Ok(nvdm_type) if nvdm_type == expected_type)
     }
 }
Signature · 1 line
2.55.0
#27 lore raw

Re: [PATCH v3 11/33] gpu: nova-core: add GMC transport receive path

Quoted 12 lines · John Hubbard
drivers/gpu/nova-core/gsp/fw.rs +11 -0
+/// The check of [`QueueElementHeader::validate`] that a queue element header fails.
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum QueueElementHeaderError {
+    /// The first word is not `"MCTP"`.
+    BadMagic,
+    /// The MCTP header carries a version other than the one that this driver uses.
+    BadMctpVersion,
+    /// The NVDM header names a vendor other than NVIDIA, or a message type other than
+    /// vendor-defined.
+    BadNvdmVendor,
+    /// The element length is shorter than the queue element header and the message together,
Quoted 4 lines

or
+    /// above the maximum element size.
+    BadLength,
 }

Can you add a comment somewhere explaining why we're adding a new error type, instead of just using the standard error codes?

Quoted 6 lines

-    /// Validates this header against the expected NVIDIA NVDM format and type. -    pub(crate) fn validate(self, expected_type: NvdmType) -> bool { +    pub(crate) fn has_nvidia_vendor(self) -> bool { u8::from(self.msg_type()) == MSG_TYPE_VENDOR_PCI
             && u16::from(self.vendor_id()) == Vendor::NVIDIA.as_raw() +    }

When would we ever receive a non-Nvidia message? Normally this check is done if we're receiving messages from an external source.

#28 lore raw

Re: [PATCH v3 11/33] gpu: nova-core: add GMC transport receive path

Quoted 12 lines · Timur Tabi
Quoted 11 lines · John Hubbard
drivers/gpu/nova-core/gsp/fw.rs +10 -0
+/// The check of [`QueueElementHeader::validate`] that a queue element header fails.
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum QueueElementHeaderError {
+    /// The first word is not `"MCTP"`.
+    BadMagic,
+    /// The MCTP header carries a version other than the one that this driver uses.
+    BadMctpVersion,
+    /// The NVDM header names a vendor other than NVIDIA, or a message type other than
+    /// vendor-defined.
+    BadNvdmVendor,
Quoted 8 lines
Quoted 5 lines

+    /// The element length is shorter than the queue element header and the message together, or
+    /// above the maximum element size.
+    BadLength,
 }

Can you add a comment somewhere explaining why we're adding a new error type, instead of just using the standard error codes?

Yes. v4 adds a sentence to the enum's doc comment: the receive path logs the variant when it poisons the queue, so that the log names the check that failed. An errno carries one code and cannot.

Although now that the IRQ series removes queue poisoning, I need to reconsider this, since I expect IRQ to get merged before this series.

Quoted 10 lines
Quoted 7 lines

-    /// Validates this header against the expected NVIDIA NVDM format and type. -    pub(crate) fn validate(self, expected_type: NvdmType) -> bool { +    pub(crate) fn has_nvidia_vendor(self) -> bool { u8::from(self.msg_type()) == MSG_TYPE_VENDOR_PCI
             && u16::from(self.vendor_id()) == Vendor::NVIDIA.as_raw() +    }

When would we ever receive a non-Nvidia message? Normally this check is done if we're receiving messages from an external source.

No, never, at least, not from a working GSP-RM.

It is basically checking for message corruption.

The FSP receive path makes the same check, and so does Open RM's GspMsgQueueReceiveStatus() in 615.71.09.

v4 keeps it and adds the missing doc comment on has_nvidia_vendor().

thanks,

Signature · 1 line
John Hubbard
#29 lore raw

PATCH v3 12/33 gpu: nova-core: gsp: add GMC dispatch on receive

In reply to John Hubbard

The r000 boot protocol delivers its load-and-execute steps as GMC events, each named by a command id. A GMC element states its payload size twice, in the GMC header and in the queue element header, and GSP-RM writes both from the same payload.

Add a receive that passes a GMC element's command id and payload to a handler that the caller supplies, and that logs and drops an element that is not a GMC element. The read pointer advances past the element whether or not the handler accepts it, so that a handler receives each element once. An element whose two payload sizes differ has a corrupt header, and the driver cannot know which one is correct, so the receive poisons the queue rather than trust either size. This receive has no caller yet.

---
 drivers/gpu/nova-core/gsp/cmdq.rs | 104 ++++++++++++++++++++++++++++--
 drivers/gpu/nova-core/gsp/fw.rs   |   8 +++
 2 files changed, 107 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +99 -5
index a1bf536dc109..b202bd8185ba 100644
@@ -480,7 +480,6 @@ struct GspMessage<'a> {
 /// A GMC (GPU Management Controller) API message ready to be processed from the message queue.
 ///
 /// This is the message that [`QueueElement::Gmc`] carries.
-#[expect(dead_code)]
 struct GmcMessage<'a> {
     // The queue element header and the GMC API header that open the element.
     header: &'a GspGmcMsgElement,
@@ -506,7 +505,6 @@ enum QueueElement<'a> {
 
 impl QueueElement<'_> {
     /// Returns the number of queue slots that the element occupies.
-    #[expect(dead_code)]
     fn element_count(&self) -> u32 {
         match self {
             Self::Gmc(message) => message.header.element_count(),
@@ -627,6 +625,21 @@ pub(crate) fn send_command_no_wait<M>(&self, command: M) -> Result
         self.inner.lock().send_command(command)
     }
 
+    /// Receives one GMC event and passes its command id and payload slices to `handler`.
+    ///
+    /// This method may sleep while waiting. The queue mutex stays locked across the wait and the
+    /// `handler` call, so `handler` must not call back into this [`Cmdq`].
+    ///
+    /// See [`CmdqInner::receive_gmc_and_dispatch`] for the return value and the errors.
+    #[expect(dead_code)]
+    pub(crate) fn receive_gmc_and_dispatch<R>(
+        &self,
+        timeout: Delta,
+        handler: impl FnOnce(u32, &[u8], &[u8]) -> Result<Option<R>>,
+    ) -> Result<Option<R>> {
+        self.inner.lock().receive_gmc_and_dispatch(timeout, handler)
+    }
+
     /// Waits for an unsolicited GSP event of type `M`. Events that arrive before it are logged and
     /// consumed.
     ///
@@ -1097,9 +1110,9 @@ fn payload_slices<'a>(
     /// # Errors
     ///
     /// - `ETIMEDOUT` if no element arrives within `timeout`.
-    /// - `EIO` if the queue is already poisoned, or if the framing is invalid, which poisons it
-    ///   (see [`Self::poisoned`]).
-    #[expect(dead_code)]
+    /// - `EIO` if the queue is already poisoned, or if the framing is invalid, or if the GMC API
+    ///   header and the queue element header declare different payload sizes. Each of these
+    ///   poisons the queue (see [`Self::poisoned`]).
     fn wait_for_element(&self, timeout: Delta) -> Result<QueueElement<'_>> {
         if self.poisoned.get() {
             return Err(EIO);
@@ -1146,8 +1159,89 @@ fn wait_for_element(&self, timeout: Delta) -> Result<QueueElement<'_>> {
             )));
         };
 
+        // GSP-RM writes both sizes from the same payload, so a difference means that one of the
+        // two headers is corrupt, and the driver cannot know which.
+        if payload_length != num::u32_as_usize(header.gmc.size) {
+            return Err(self.poison(fmt!(
+                "GMC seq# {}: GMC API header declares {} payload bytes, element header {}",
+                header.gmc.sequence,
+                header.gmc.size,
+                payload_length
+            )));
+        }
+
         let contents = self.payload_slices(slice_1, slice_2, payload_length)?;
 
         Ok(QueueElement::Gmc(GmcMessage { header, contents }))
     }
+
+    /// Waits for the next queue element, passes it to `f`, and advances the read pointer past it.
+    ///
+    /// The read pointer advances whether `f` succeeds or fails, so that `f` is called once per
+    /// element. The element and its payload slices are valid only inside `f`.
+    ///
+    /// # Errors
+    ///
+    /// - `ETIMEDOUT` if `timeout` has elapsed before any element becomes available.
+    /// - `EIO` if the queue is poisoned or the element is invalid, as [`Self::wait_for_element`]
+    ///   describes.
+    ///
+    /// Errors from `f` are propagated as-is.
+    fn consume_element<R>(
+        &mut self,
+        timeout: Delta,
+        f: impl FnOnce(&Self, QueueElement<'_>) -> Result<R>,
+    ) -> Result<R> {
+        let element = self.wait_for_element(timeout)?;
+        let element_count = element.element_count();
+
+        let result = f(self, element);
+
+        self.gsp_mem.advance_cpu_read_ptr(element_count);
+
+        result
+    }
+
+    /// Receives the next queue element and, if it is a GMC element, passes it to `handler`.
+    ///
+    /// `handler` receives the command id and the payload that follows the GMC API header, as two
+    /// slices because the ring may wrap, and returns `None` for an element that it declines.
+    ///
+    /// Returns `Ok(None)` when `handler` declines the element or when the element is not a GMC
+    /// element.
+    ///
+    /// # Errors
+    ///
+    /// - `ETIMEDOUT` if no element arrives within `timeout`.
+    /// - `EIO` if the queue is poisoned or the queue element header is invalid, as
+    ///   [`Self::wait_for_element`] describes.
+    ///
+    /// Errors from `handler` are propagated as-is.
+    fn receive_gmc_and_dispatch<R>(
+        &mut self,
+        timeout: Delta,
+        handler: impl FnOnce(u32, &[u8], &[u8]) -> Result<Option<R>>,
+    ) -> Result<Option<R>> {
+        self.consume_element(timeout, |this, element| match element {
+            QueueElement::Other(_) => {
+                dev_warn!(&this.dev, "GSP GMC: dropping non-GMC queue element\n");
+
+                Ok(None)
+            }
+            QueueElement::Gmc(message) => {
+                let header = message.header;
+                let command_id = header.gmc.command_id();
+
+                dev_dbg!(
+                    &this.dev,
+                    "GSP GMC: event: seq# {}, command_id=0x{:x}, length=0x{:x}\n",
+                    header.gmc.sequence,
+                    command_id,
+                    header.length(),
+                );
+
+                handler(command_id, message.contents.0, message.contents.1)
+            }
+        })
+    }
 }
drivers/gpu/nova-core/gsp/fw.rs +8 -0
index 5548ca77f49b..f23d071f0e16 100644
@@ -1052,6 +1052,9 @@ pub(crate) struct GmcApiHeader {
     reserved: [u32; 5],
 }
 
+/// Bits of [`GmcApiHeader::command`] that hold the command id. The high byte holds flags.
+const GMCAPI_COMMAND_ID_MASK: u32 = 0x00ff_ffff;
+
 static_assert!(size_of::<GmcApiHeader>() == size_of::<r000_00::GMCAPI_HEADER>());
 static_assert!(
     core::mem::offset_of!(GmcApiHeader, command)
@@ -1075,6 +1078,11 @@ pub(crate) struct GmcApiHeader {
 );
 
 impl GmcApiHeader {
+    /// Returns the command id, without the flag byte.
+    pub(crate) fn command_id(&self) -> u32 {
+        self.command & GMCAPI_COMMAND_ID_MASK
+    }
+
     /// Returns the `NV_STATUS` that a response carries.
     ///
     /// The value is meaningful only on a response, which GSP-RM marks with a flag in the command
Signature · 1 line
2.55.0
#30 lore raw

Re: [PATCH v3 12/33] gpu: nova-core: gsp: add GMC dispatch on receive

Quoted 10 lines · John Hubbard

     /// Waits for an unsolicited GSP event of type M. Events that arrive before it are logged and
     /// consumed.
     ///

drivers/gpu/nova-core/gsp/cmdq.rs +0 -1
@@ -1097,9 +1110,9 @@ fn payload_slices<'a>(
      /// # Errors
      ///
      /// - `ETIMEDOUT` if no element arrives within `timeout`.
-    /// - `EIO` if the queue is already poisoned, or if the framing is invalid, which poisons
Quoted 7 lines

it
-    ///   (see [Self::poisoned]).
-    #[expect(dead_code)]
+    /// - EIO if the queue is already poisoned, or if the framing is invalid, or if the GMC API
+    ///   header and the queue element header declare different payload sizes. Each of these +    ///   poisons the queue (see [Self::poisoned]).

What does it mean for the size to be "declared"?

Quoted 10 lines

     fn wait_for_element(&self, timeout: Delta) -> Result<QueueElement<'_>> { if self.poisoned.get() {
             return Err(EIO);

(quoted diff) +0 -0
@@ -1146,8 +1159,89 @@ fn wait_for_element(&self, timeout: Delta) -> Result<QueueElement<'_>>
 {
              )));
          };


+        // GSP-RM writes both sizes from the same payload, so a difference means that one of the

Quoted 8 lines

+        // two headers is corrupt, and the driver cannot know which.
+        if payload_length != num::u32_as_usize(header.gmc.size) {
+            return Err(self.poison(fmt!(
+                "GMC seq# {}: GMC API header declares {} payload bytes, element header {}", +                header.gmc.sequence,
+                header.gmc.size,
+                payload_length
+            )));

This message doesn't clearly specify what the error is. How about something like:

"GMC API header declares payload size of {} bytes, but should be {}"

#31 lore raw

Re: [PATCH v3 12/33] gpu: nova-core: gsp: add GMC dispatch on receive

Quoted 12 lines · Timur Tabi
Quoted 11 lines · John Hubbard

     /// Waits for an unsolicited GSP event of type M. Events that arrive before it are logged and
     /// consumed.
     ///

drivers/gpu/nova-core/gsp/cmdq.rs +0 -1
@@ -1097,9 +1110,9 @@ fn payload_slices<'a>(
      /// # Errors
      ///
      /// - `ETIMEDOUT` if no element arrives within `timeout`.
-    /// - `EIO` if the queue is already poisoned, or if the framing is invalid, which poisons

it

Quoted 8 lines
Quoted 6 lines

-    ///   (see [Self::poisoned]).
-    #[expect(dead_code)]
+    /// - EIO if the queue is already poisoned, or if the framing is invalid, or if the GMC API
+    ///   header and the queue element header declare different payload sizes. Each of these +    ///   poisons the queue (see [Self::poisoned]).

What does it mean for the size to be "declared"?

Yuk! I have written it with better words, in v4, thanks.

Quoted 22 lines
Quoted 11 lines

     fn wait_for_element(&self, timeout: Delta) -> Result<QueueElement<'_>> { if self.poisoned.get() {
             return Err(EIO);

(quoted diff) +0 -0
@@ -1146,8 +1159,89 @@ fn wait_for_element(&self, timeout: Delta) -> Result<QueueElement<'_>>
 {
              )));
          };


+        // GSP-RM writes both sizes from the same payload, so a difference means that one of the

Quoted 8 lines

+        // two headers is corrupt, and the driver cannot know which.
+        if payload_length != num::u32_as_usize(header.gmc.size) {
+            return Err(self.poison(fmt!(
+                "GMC seq# {}: GMC API header declares {} payload bytes, element header {}", +                header.gmc.sequence,
+                header.gmc.size,
+                payload_length
+            )));

This message doesn't clearly specify what the error is. How about something like:

Quoted 1 line

"GMC API header declares payload size of {} bytes, but should be {}"

hmmm..."should be {}" assumes that the queue element header holds the right value, but the driver cannot know which of the two headers is corrupt.

How about this:

        return Err(self.poison(fmt!(
            "GMC element seq# {} has payload size {} in its GMC API header but {} in \
                its queue element header",
            header.gmc.sequence,
            header.gmc.size,
            payload_length
        )));

It names the element, states the fault as one sentence, and puts each number next to the header that it came from.

Sample output:

GSP receive: queue poisoned: GMC element seq# 7 has payload size 96 in its GMC API header but 80 in its queue element header

thanks,

Signature · 1 line
John Hubbard
#32 lore raw

Re: [PATCH v3 12/33] gpu: nova-core: gsp: add GMC dispatch on receive

Quoted 10 lines · John Hubbard

How about this:

        return Err(self.poison(fmt!(
            "GMC element seq# {} has payload size {} in its GMC API header but {} in \
                its queue element header",
            header.gmc.sequence,
            header.gmc.size,
            payload_length
        )));

Quoted 6 lines

It names the element, states the fault as one sentence, and puts each number next to the header that it came from.

Sample output:

  GSP receive: queue poisoned: GMC element seq# 7 has payload size 96 in its GMC API header but 80 in its queue element header

Sure, that's fine. My only concern was that the original text did not make it clear that the two numbers are supposed to be the same.

#33 lore raw

PATCH v3 13/33 gpu: nova-core: separate the generic falcon bootloader from FWSEC

In reply to John Hubbard

The generic falcon bootloader is a small program that loads a larger image into a falcon. The r000 boot protocol needs it to run an image that GSP-RM names in a load-and-execute event during boot.

Nova-core used the bootloader only to load FWSEC, so the bootloader code was part of the FWSEC code, and there was no way to run it on another image.

Move the bootloader into its own type, which FWSEC then uses.

Place the bootloader at the top of the falcon's IMEM, using the IMEM size that the HWCFG register reports, instead of assuming a 64 KiB IMEM.

---
 drivers/gpu/nova-core/falcon.rs               |  8 ++
 drivers/gpu/nova-core/firmware.rs             |  1 +
 .../nova-core/firmware/fwsec/bootloader.rs    | 63 ++----------
 .../gpu/nova-core/firmware/gen_bootloader.rs  | 99 +++++++++++++++++++
 drivers/gpu/nova-core/gsp/hal/tu102.rs        |  6 +-
 drivers/gpu/nova-core/regs.rs                 |  5 +
 6 files changed, 124 insertions(+), 58 deletions(-)
 create mode 100644 drivers/gpu/nova-core/firmware/gen_bootloader.rs
drivers/gpu/nova-core/falcon.rs +8 -0
index 9015de965a53..04e35cbcb6f0 100644
@@ -385,6 +385,14 @@ pub(crate) fn new(
         })
     }
 
+    /// Returns the size of this falcon's IMEM in bytes.
+    pub(crate) fn imem_size(&self) -> usize {
+        let blocks =
+            usize::from_safe_cast(*self.pfalcon.read(regs::NV_PFALCON_FALCON_HWCFG).imem_size());
+
+        blocks * MEM_BLOCK_ALIGNMENT
+    }
+
     /// Resets DMA-related registers.
     pub(crate) fn dma_reset(&self) {
         self.pfalcon.update(regs::NV_PFALCON_FBIF_CTL, |v| {
drivers/gpu/nova-core/firmware.rs +1 -0
index d8f6509a35d1..358c9b8db0b8 100644
@@ -24,6 +24,7 @@
 
 pub(crate) mod booter;
 pub(crate) mod fwsec;
+pub(crate) mod gen_bootloader;
 pub(crate) mod gsp;
 pub(crate) mod gsp_fmc;
 pub(crate) mod radix3;
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +7 -56

119 lines not on this page · raw message

drivers/gpu/nova-core/firmware/gen_bootloader.rs new file +99 -0

99 lines not on this page · raw message

drivers/gpu/nova-core/gsp/hal/tu102.rs +4 -2
index e90db1a23032..1b17ece53bd6 100644
@@ -165,7 +165,7 @@ fn run_fwsec_frts(
         )?;
 
         if self.needs_fwsec_bootloader {
-            let fwsec_frts_bl = FwsecFirmwareWithBl::new(fwsec_frts, dev, chipset)?;
+            let fwsec_frts_bl = FwsecFirmwareWithBl::new(fwsec_frts, dev, chipset, falcon)?;
             // Load and run the bootloader, which will load FWSEC-FRTS and run it.
             fwsec_frts_bl.run(dev, falcon)?;
         } else {
@@ -223,7 +223,9 @@ fn build_unload_bundle<'gpu>(
         // 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)?)
+            FwsecUnloadFirmware::WithBl(FwsecFirmwareWithBl::new(
+                fwsec_sb, dev, chipset, gsp_falcon,
+            )?)
         } else {
             FwsecUnloadFirmware::WithoutBl(fwsec_sb)
         };
drivers/gpu/nova-core/regs.rs +5 -0
index c6ba226dcfe3..69dd6526e469 100644
@@ -181,6 +181,11 @@ pub(crate) fn usable_fb_size(self) -> u64 {
         31:0    value => u32;
     }
 
+    pub(crate) NV_PFALCON_FALCON_HWCFG(u32) @ 0x00000108 {
+        /// Number of 256-byte blocks in this falcon's IMEM.
+        8:0     imem_size;
+    }
+
     pub(crate) NV_PFALCON_FALCON_DMACTL(u32) @ 0x0000010c {
         7:7     secure_stat => bool;
         6:3     dmaq_num;
Signature · 1 line
2.55.0
#34 lore raw

Re: [PATCH v3 13/33] gpu: nova-core: separate the generic falcon bootloader from FWSEC

Quoted 9 lines · John Hubbard
drivers/gpu/nova-core/falcon.rs +0 -0
index 9015de965a53..04e35cbcb6f0 100644
@@ -385,6 +385,14 @@ pub(crate) fn new(
          })
      }
Quoted 6 lines


+    /// Returns the size of this falcon's IMEM in bytes.
+    pub(crate) fn imem_size(&self) -> usize {
+        let blocks =
+ usize::from_safe_cast(*self.pfalcon.read(regs::NV_PFALCON_FALCON_HWCFG).imem_size());

Why is this *self instead of just self?

#35 lore raw

Re: [PATCH v3 13/33] gpu: nova-core: separate the generic falcon bootloader from FWSEC

Quoted 18 lines · Timur Tabi
Quoted 9 lines · John Hubbard
drivers/gpu/nova-core/falcon.rs +0 -0
index 9015de965a53..04e35cbcb6f0 100644
@@ -385,6 +385,14 @@ pub(crate) fn new(
          })
      }
Quoted 6 lines


+    /// Returns the size of this falcon's IMEM in bytes.
+    pub(crate) fn imem_size(&self) -> usize {
+        let blocks =
+ usize::from_safe_cast(*self.pfalcon.read(regs::NV_PFALCON_FALCON_HWCFG).imem_size());

Why is this *self instead of just self?

Because the star is not "attached" to self, actually. Because: A method call binds tighter than the unary operator, so the above is actually dereferencing the Bounded<u32, 9> that imem_size() returns.

However, in order to improve readability, I've changed this in v4, to use usize::from(...) instead, the form that the fb HALs already use for a register field. And also done that for the two GSP pointer reads in the big switch-over patch.

thanks,

Signature · 1 line
John Hubbard
#36 lore raw

Re: [PATCH v3 13/33] gpu: nova-core: separate the generic falcon bootloader from FWSEC

In reply to John Hubbard
Quoted 10 lines · John Hubbard

The generic falcon bootloader is a small program that loads a larger image into a falcon. The r000 boot protocol needs it to run an image that GSP-RM names in a load-and-execute event during boot.

Nova-core used the bootloader only to load FWSEC, so the bootloader code was part of the FWSEC code, and there was no way to run it on another image.

Move the bootloader into its own type, which FWSEC then uses.

Quoted 7 lines

Place the bootloader at the top of the falcon's IMEM, using the IMEM size that the HWCFG register reports, instead of assuming a 64 KiB IMEM.

This is a very good change to have even without the switch to r000 as it properly isolates the generic bootloader code. But this change alone is not the entire story: patch 16 is another part of it, and so are the bits of patch 17 that touch fwsec/bootloader.rs and gen_bootloader.rs. If you extract the relevant bits of patch 17 into a new patch then you have 3 commits that read perfectly once they are put in a sequence (i.e. the current patches 14 and 15 should be moved right after the extracted part of patch 17).

I've tried squashing these 3 patches into a single one and even that looks pretty decent with --color-moved, but it's also fine to keep 3 separate patches if you prefer.

Those patches also still seem to have some doccomment churn, please confirm whether changing the documentation is actually warranted.

Just one tiny nit on this patch below.

<...>

Quoted 37 lines
drivers/gpu/nova-core/firmware/gen_bootloader.rs new file +37 -0
+impl GenericBootloader {
+    /// Loads the generic bootloader image for `chipset`, placed in the last blocks of an IMEM of
+    /// `imem_size` bytes.
+    ///
+    /// # Errors
+    ///
+    /// - `EINVAL` if a required TLV field is absent or the image does not fit in IMEM.
+    /// - `ENOMEM` if the padded copy of the code cannot be allocated.
+    pub(crate) fn new(
+        dev: &device::Device<device::Bound>,
+        chipset: Chipset,
+        imem_size: usize,
+    ) -> Result<Self> {
+        let fw = request_tlv(dev, chipset, "gen_bootloader")?;
+        let tlv = Tlv::new(fw.data())?;
+        dev_dbg!(
+            dev,
+            "loaded generic bootloader firmware v{}\n",
+            tlv.get_string(b"VERS")?
+        );
+
+        let ucode = {
+            let blob = tlv.get_bytes(b"BLOB")?;
+            let code_size = usize::from_safe_cast(tlv.get_u32(b"CDSZ")?);
+            let code = blob.get(..code_size).ok_or(EINVAL)?;
+            let aligned_code_size = code_size
+                .align_up(Alignment::new::<{ falcon::MEM_BLOCK_ALIGNMENT }>())
+                .ok_or(EINVAL)?;
+
+            let mut ucode = KVec::with_capacity(aligned_code_size, GFP_KERNEL)?;
+            ucode.extend_from_slice(code, GFP_KERNEL)?;
+            ucode.resize(aligned_code_size, 0, GFP_KERNEL)?;
+
+            ucode
+        };
+
+        // The top of IMEM, above the blocks that the bootloader loads the image into.

drivers/gpu/nova-core/firmware/gen_bootloader.rs line 86

Quoted 10 lines
drivers/gpu/nova-core/firmware/gen_bootloader.rs new file +10 -0
+        let imem_dst_start = imem_size.checked_sub(ucode.len()).ok_or(EINVAL)?;
+
+        Ok(Self {
+            ucode,
+            imem_dst_start: u16::try_from(imem_dst_start)?,
+            start_tag: u16::try_from(tlv.get_u32(b"STRT")?)?,
+        })
+    }
+
+    pub(crate) fn boot_addr(&self) -> u32 {

Let's give a short documentation to this new method.

#37 lore raw

PATCH v3 14/33 gpu: nova-core: add the falcon DMA and suspend helpers for r000 boot

In reply to John Hubbard

The r000 boot protocol has two load-and-execute events. In each, GSP-RM names an image that it has placed in the framebuffer, and the driver copies the image into the GSP falcon's memory by DMA and runs it. The event supplies the image's framebuffer address, and the copy goes through a context DMA slot of the falcon's framebuffer interface. GSP-RM also reports that the GSP's RISC-V core has suspended through a bit in the falcon's MAILBOX0 register, rather than through the halted bit in CPUCTL, and the driver has to wait for that bit before it resets the falcon.

Nova-core's falcon DMA copied only from a DMA object that the driver had allocated, so there was no way to copy an image from an address that an event supplied. The shutdown path read the suspend bit inline, so there was no wait for it that a boot event handler could share.

Add a DMA transfer that copies from a caller-supplied source address through a caller-supplied context DMA slot. Add a check of the suspend bit and a wait built on it, and make the shutdown path use the check in place of its inline read.

---
 drivers/gpu/nova-core/falcon.rs   | 150 +++++++++++++++++++++++++++++-
 drivers/gpu/nova-core/gsp/boot.rs |   6 +-
 drivers/gpu/nova-core/regs.rs     |   2 +-
 3 files changed, 151 insertions(+), 7 deletions(-)
drivers/gpu/nova-core/falcon.rs +148 -2
index 04e35cbcb6f0..2a0fe86153aa 100644
@@ -5,6 +5,7 @@
 use hal::FalconHal;
 
 use kernel::{
+    bits,
     device,
     dma::{
         Coherent,
@@ -20,7 +21,7 @@
     },
     prelude::*,
     sizes::SZ_4K,
-    time::Delta,
+    time::Delta, //
 };
 
 use crate::{
@@ -43,6 +44,9 @@
 /// Alignment (in bytes) of falcon memory blocks.
 pub(crate) const MEM_BLOCK_ALIGNMENT: usize = 256;
 
+/// DMEM virtual address value that means "no virtual address assigned".
+const FLCN_DMEM_VA_INVALID: u32 = 0xffff_ffff;
+
 bounded_enum! {
     /// Revision number of a falcon core, used in the [`crate::regs::NV_PFALCON_FALCON_HWCFG1`]
     /// register.
@@ -132,12 +136,36 @@ pub(crate) enum FalconMem {
     /// Secure Instruction Memory.
     ImemSecure,
     /// Non-Secure Instruction Memory.
-    #[expect(unused)]
+    #[expect(dead_code)]
     ImemNonSecure,
     /// Data Memory.
     Dmem,
 }
 
+/// Where a raw falcon DMA transfer reads its image from, relative to the DMA base address.
+#[derive(Copy, Clone)]
+pub(crate) enum FalconDmaSrcOffset {
+    /// The image starts this many bytes past the DMA base address.
+    Offset(u32),
+    /// Virtual address of the image in the target memory. The DMA engine tags each loaded block
+    /// with this value and adds the tag to the base address, so the base address must be the
+    /// source address minus this value.
+    Va(u32),
+}
+
+impl FalconDmaSrcOffset {
+    /// Returns the source offset of a DMEM image at virtual address `dmem_va`, or the start of the
+    /// source when `dmem_va` is `FLCN_DMEM_VA_INVALID`.
+    #[expect(dead_code)]
+    pub(crate) fn from_dmem_va(dmem_va: u32) -> Self {
+        if dmem_va == FLCN_DMEM_VA_INVALID {
+            Self::Offset(0)
+        } else {
+            Self::Va(dmem_va)
+        }
+    }
+}
+
 bounded_enum! {
     /// Defines the Framebuffer Interface (FBIF) aperture type.
     /// This determines the memory type for external memory access during a DMA transfer, which is
@@ -600,6 +628,98 @@ fn dma_wr(
         Ok(())
     }
 
+    /// Transfers `len` bytes from `src_addr` into this falcon's `target_mem`.
+    ///
+    /// `src_addr` is a GPU physical address reached through the FBIF aperture, so the caller must
+    /// program `NV_PFALCON_FBIF_TRANSCFG` for `ctx_dma` before calling this.
+    ///
+    /// # Errors
+    ///
+    /// - `EINVAL` if `ctx_dma` is not a context DMA slot that the falcon has, or if `src_addr` is
+    ///   not 256-byte aligned.
+    /// - `ERANGE` if `src_addr` does not fit the `DMATRFBASE` register pair.
+    /// - `EOVERFLOW` if a per-block source or destination offset exceeds `u32`.
+    #[expect(dead_code)]
+    pub(crate) fn raw_dma_transfer(
+        &self,
+        ctx_dma: u32,
+        src_addr: u64,
+        target_mem: FalconMem,
+        src: FalconDmaSrcOffset,
+        dst_offset: u32,
+        len: u32,
+    ) -> Result {
+        const DMA_LEN: u32 = num::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();
+
+        if src_addr % u64::from(DMA_LEN) > 0 {
+            dev_err!(
+                self.dev,
+                "raw DMA: source address {:#x} not 256B-aligned\n",
+                src_addr
+            );
+            return Err(EINVAL);
+        }
+
+        if src_addr >> 40 > u64::from(regs::NV_PFALCON_FALCON_DMATRFBASE1::BASE_MASK) {
+            dev_err!(
+                self.dev,
+                "raw DMA: source address {:#x} does not fit DMATRFBASE\n",
+                src_addr
+            );
+            return Err(ERANGE);
+        }
+
+        // An IMEM block is always tagged with its source offset. A DMEM block is tagged only when
+        // `SET_DMTAG` is set, so a DMEM virtual address sets `SET_DMTAG`.
+        let (src_offset, set_dmtag) = match src {
+            FalconDmaSrcOffset::Offset(offset) => (offset, false),
+            FalconDmaSrcOffset::Va(va) => (va, target_mem == FalconMem::Dmem),
+        };
+
+        let num_transfers = len.div_ceil(DMA_LEN);
+
+        self.pfalcon
+            .write_reg(regs::NV_PFALCON_FALCON_DMATRFBASE::zeroed().with_base(
+                // CAST: this drops the upper bits on purpose. They are written to
+                // `NV_PFALCON_FALCON_DMATRFBASE1` next.
+                (src_addr >> 8) as u32,
+            ));
+        self.pfalcon.write_reg(
+            regs::NV_PFALCON_FALCON_DMATRFBASE1::zeroed().try_with_base(src_addr >> 40)?,
+        );
+
+        // The `CTXDMA` field holds exactly the indices of the falcon's `TRANSCFG` slots, so the
+        // field's range is the bound on the slot.
+        let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD::zeroed()
+            .with_size(DmaTrfCmdSize::Size256B)
+            .try_with_ctxdma(ctx_dma)
+            .map_err(|_| EINVAL)?
+            .with_falcon_mem(target_mem)
+            .with_set_dmtag(set_dmtag);
+
+        for pos in (0..num_transfers).map(|i| i * DMA_LEN) {
+            self.pfalcon.write_reg(
+                regs::NV_PFALCON_FALCON_DMATRFMOFFS::zeroed()
+                    .try_with_offs(dst_offset.checked_add(pos).ok_or(EOVERFLOW)?)?,
+            );
+            self.pfalcon.write_reg(
+                regs::NV_PFALCON_FALCON_DMATRFFBOFFS::zeroed()
+                    .with_offs(src_offset.checked_add(pos).ok_or(EOVERFLOW)?),
+            );
+
+            self.pfalcon.write_reg(cmd);
+
+            read_poll_timeout(
+                || Ok(self.pfalcon.read(regs::NV_PFALCON_FALCON_DMATRFCMD)),
+                |r| r.idle(),
+                Delta::ZERO,
+                Delta::from_secs(2),
+            )?;
+        }
+
+        Ok(())
+    }
+
     /// Perform a DMA load into `IMEM` and `DMEM` of `fw`, and prepare the falcon to run it.
     fn dma_load<F: FalconFirmware<Target = E> + FalconDmaLoadable>(&self, fw: &F) -> Result {
         // DMA object with firmware content as the source of the DMA engine.
@@ -653,6 +773,32 @@ pub(crate) fn wait_till_halted(&self) -> Result<()> {
         Ok(())
     }
 
+    /// Returns `true` if the RISC-V core has suspended.
+    pub(crate) fn is_processor_suspended(&self) -> bool {
+        const INTERRUPT_PROCESSOR_SUSPENDED: u32 = bits::bit_u32(31);
+
+        self.read_mailbox0() & INTERRUPT_PROCESSOR_SUSPENDED != 0
+    }
+
+    /// Waits until the RISC-V core has suspended.
+    ///
+    /// The caller must write `MAILBOX0` before starting the core, or this returns as soon as it
+    /// reads the previous suspend.
+    ///
+    /// # Errors
+    ///
+    /// - `ETIMEDOUT` if the core has not suspended within two seconds.
+    #[expect(dead_code)]
+    pub(crate) fn wait_for_processor_suspend(&self) -> Result {
+        read_poll_timeout(
+            || Ok(self.is_processor_suspended()),
+            |suspended| *suspended,
+            Delta::ZERO,
+            Delta::from_secs(2),
+        )
+        .map(|_| ())
+    }
+
     /// Start the falcon CPU.
     pub(crate) fn start(&self) -> Result<()> {
         match self.pfalcon.read(regs::NV_PFALCON_FALCON_CPUCTL).alias_en() {
drivers/gpu/nova-core/gsp/boot.rs +2 -4
index 4fb1b69ac9d5..8518248c9732 100644
@@ -2,7 +2,6 @@
 // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
 use kernel::{
-    bits,
     io::poll::read_poll_timeout,
     prelude::*,
     time::Delta,
@@ -94,10 +93,9 @@ fn shutdown_gsp(
         cmdq.send_command(commands::UnloadingGuestDriver::new(mode))?;
 
         // Wait until GSP signals it is suspended.
-        const LIBOS_INTERRUPT_PROCESSOR_SUSPENDED: u32 = bits::bit_u32(31);
         read_poll_timeout(
-            || Ok(gsp_falcon.read_mailbox0()),
-            |&mb0| mb0 & LIBOS_INTERRUPT_PROCESSOR_SUSPENDED != 0,
+            || Ok(gsp_falcon.is_processor_suspended()),
+            |suspended| *suspended,
             Delta::from_millis(10),
             Delta::from_secs(5),
         )
drivers/gpu/nova-core/regs.rs +1 -1
index 69dd6526e469..feb37de69be5 100644
@@ -203,7 +203,7 @@ pub(crate) fn usable_fb_size(self) -> u64 {
     }
 
     pub(crate) NV_PFALCON_FALCON_DMATRFCMD(u32) @ 0x00000118 {
-        16:16   set_dmtag;
+        16:16   set_dmtag => bool;
         14:12   ctxdma;
         10:8    size ?=> DmaTrfCmdSize;
         5:5     is_write => bool;
Signature · 1 line
2.55.0
#38 lore raw

Re: [PATCH v3 14/33] gpu: nova-core: add the falcon DMA and suspend helpers for r000 boot

Quoted 17 lines · John Hubbard

+    pub(crate) fn raw_dma_transfer(
+        &self,
+        ctx_dma: u32,
+        src_addr: u64,
+        target_mem: FalconMem,
+        src: FalconDmaSrcOffset,
+        dst_offset: u32,
+        len: u32,
+    ) -> Result {
+        const DMA_LEN: u32 = num::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>(); +
+        if src_addr % u64::from(DMA_LEN) > 0 {
+            dev_err!(
+                self.dev,
+                "raw DMA: source address {:#x} not 256B-aligned\n",

You use MEM_BLOCK_ALIGNMENT to determine the alignment, but you hard-code "256" in the error string.

#39 lore raw

Re: [PATCH v3 14/33] gpu: nova-core: add the falcon DMA and suspend helpers for r000 boot

Quoted 19 lines · Timur Tabi
Quoted 17 lines · John Hubbard

+    pub(crate) fn raw_dma_transfer(
+        &self,
+        ctx_dma: u32,
+        src_addr: u64,
+        target_mem: FalconMem,
+        src: FalconDmaSrcOffset,
+        dst_offset: u32,
+        len: u32,
+    ) -> Result {
+        const DMA_LEN: u32 = num::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>(); +
+        if src_addr % u64::from(DMA_LEN) > 0 {
+            dev_err!(
+                self.dev,
+                "raw DMA: source address {:#x} not 256B-aligned\n",

Quoted 2 lines

You use MEM_BLOCK_ALIGNMENT to determine the alignment, but you hard-code "256" in the error string.

OK, fixed in v4: the message formats the constant, and the doc comment cites MEM_BLOCK_ALIGNMENT in place of the number.

thanks,

Signature · 1 line
John Hubbard
#40 lore raw

Re: [PATCH v3 14/33] gpu: nova-core: add the falcon DMA and suspend helpers for r000 boot

In reply to John Hubbard

On Fri Sep 18, 2026 at 10:07 AM JST, John Hubbard wrote:
<...>

Quoted 11 lines
drivers/gpu/nova-core/falcon.rs +11 -0
+    /// Transfers `len` bytes from `src_addr` into this falcon's `target_mem`.
+    ///
+    /// `src_addr` is a GPU physical address reached through the FBIF aperture, so the caller must
+    /// program `NV_PFALCON_FBIF_TRANSCFG` for `ctx_dma` before calling this.
+    ///
+    /// # Errors
+    ///
+    /// - `EINVAL` if `ctx_dma` is not a context DMA slot that the falcon has, or if `src_addr` is
+    ///   not 256-byte aligned.
+    /// - `ERANGE` if `src_addr` does not fit the `DMATRFBASE` register pair.
+    /// - `EOVERFLOW` if a per-block source or destination offset exceeds `u32`.

drivers/gpu/nova-core/falcon.rs fn dma_wr( · line 651

Quoted 10 lines
drivers/gpu/nova-core/falcon.rs +10 -0
+    #[expect(dead_code)]
+    pub(crate) fn raw_dma_transfer(
+        &self,
+        ctx_dma: u32,
+        src_addr: u64,
+        target_mem: FalconMem,
+        src: FalconDmaSrcOffset,
+        dst_offset: u32,
+        len: u32,
+    ) -> Result {

So this method is an almost identical rewrite of dma_wr, except it works from the FB instead of sysmem. That's no justification for a new method, and dma_wr can be made capable of working with FB: change the dma_obj parameter to an enum type describing whether the source is FB or sysmem, with the relevant parameters for each variant as one commit, and bring the local improvements of your version (like the use of checked_add and support for DMA contexts) as separate commits.

<...>

Quoted 15 lines
drivers/gpu/nova-core/falcon.rs +15 -0
+    /// Returns `true` if the RISC-V core has suspended.
+    pub(crate) fn is_processor_suspended(&self) -> bool {
+        const INTERRUPT_PROCESSOR_SUSPENDED: u32 = bits::bit_u32(31);
+
+        self.read_mailbox0() & INTERRUPT_PROCESSOR_SUSPENDED != 0
+    }
+
+    /// Waits until the RISC-V core has suspended.
+    ///
+    /// The caller must write `MAILBOX0` before starting the core, or this returns as soon as it
+    /// reads the previous suspend.
+    ///
+    /// # Errors
+    ///
+    /// - `ETIMEDOUT` if the core has not suspended within two seconds.

drivers/gpu/nova-core/falcon.rs pub(crate) fn wait_till_halted(&self) -> Result<()> { · line 800

Quoted 10 lines
drivers/gpu/nova-core/falcon.rs +10 -0
+    #[expect(dead_code)]
+    pub(crate) fn wait_for_processor_suspend(&self) -> Result {
+        read_poll_timeout(
+            || Ok(self.is_processor_suspended()),
+            |suspended| *suspended,
+            Delta::ZERO,
+            Delta::from_secs(2),
+        )
+        .map(|_| ())
+    }

These two methods look firmware specific, and are only used in boot.rs, so I'd consider moving them there to not add ad-hoc code to this file that applies to all falcons.

Quoted 17 lines
drivers/gpu/nova-core/falcon.rs +1 -0
+
     /// Start the falcon CPU.
     pub(crate) fn start(&self) -> Result<()> {
         match self.pfalcon.read(regs::NV_PFALCON_FALCON_CPUCTL).alias_en() {
drivers/gpu/nova-core/gsp/boot.rs +0 -1
index 4fb1b69ac9d5..8518248c9732 100644
@@ -2,7 +2,6 @@
 // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
 use kernel::{
-    bits,
     io::poll::read_poll_timeout,
     prelude::*,
     time::Delta,

drivers/gpu/nova-core/gsp/boot.rs fn shutdown_gsp( · line 98

Quoted 9 lines
drivers/gpu/nova-core/gsp/boot.rs +2 -3
@@ -94,10 +93,9 @@ fn shutdown_gsp(
         cmdq.send_command(commands::UnloadingGuestDriver::new(mode))?;
 
         // Wait until GSP signals it is suspended.
-        const LIBOS_INTERRUPT_PROCESSOR_SUSPENDED: u32 = bits::bit_u32(31);
         read_poll_timeout(
-            || Ok(gsp_falcon.read_mailbox0()),
-            |&mb0| mb0 & LIBOS_INTERRUPT_PROCESSOR_SUSPENDED != 0,
+            || Ok(gsp_falcon.is_processor_suspended()),
+            |suspended| *suspended,

Yup, that bit seems to confirm the comment above. :)

#41 lore raw

PATCH v3 15/33 gpu: nova-core: add the r000 load-and-execute HS binary handler

In reply to John Hubbard

On GA102 and later, GSP-RM sends the driver a load-and-execute event during boot that requests the driver to run a Heavy-Secured (HS) binary on the GSP falcon. GSP-RM has placed the binary in the framebuffer, and the event carries the binary's addresses. Once the binary has halted, SEC2 restarts GSP-RM, in what Open RM calls the core resume.

Add the handler and the core resume. The handler copies the binary into the falcon through an FBIF (framebuffer interface) aperture that it programs for the load, starts the binary and waits for it to halt.

Put the falcons, the device and the boot parameters that the handler and the core resume share into one context struct.

---
 drivers/gpu/nova-core/falcon.rs     |  51 +++++-
 drivers/gpu/nova-core/falcon/gsp.rs |  10 +-
 drivers/gpu/nova-core/gsp/boot.rs   | 257 +++++++++++++++++++++++++++-
 drivers/gpu/nova-core/regs.rs       |   2 +
 drivers/gpu/nova-core/sbuffer.rs    |   1 -
 5 files changed, 311 insertions(+), 10 deletions(-)
drivers/gpu/nova-core/falcon.rs +47 -4
index 2a0fe86153aa..8ad28dce955e 100644
@@ -44,6 +44,10 @@
 /// Alignment (in bytes) of falcon memory blocks.
 pub(crate) const MEM_BLOCK_ALIGNMENT: usize = 256;
 
+/// `MAILBOX0` value that means "the falcon binary has not started". A binary that runs replaces
+/// it with its own status.
+pub(crate) const FLCN_ERR_BINARY_NOT_STARTED: u32 = 0xfe;
+
 /// DMEM virtual address value that means "no virtual address assigned".
 const FLCN_DMEM_VA_INVALID: u32 = 0xffff_ffff;
 
@@ -156,7 +160,6 @@ pub(crate) enum FalconDmaSrcOffset {
 impl FalconDmaSrcOffset {
     /// Returns the source offset of a DMEM image at virtual address `dmem_va`, or the start of the
     /// source when `dmem_va` is `FLCN_DMEM_VA_INVALID`.
-    #[expect(dead_code)]
     pub(crate) fn from_dmem_va(dmem_va: u32) -> Self {
         if dmem_va == FLCN_DMEM_VA_INVALID {
             Self::Offset(0)
@@ -192,6 +195,17 @@ pub(crate) enum FalconFbifMemType with From<Bounded<u32, 1>> {
     }
 }
 
+bounded_enum! {
+    /// Engine ID that the falcon's framebuffer interface (FBIF) tags a DMA transfer with.
+    #[derive(Debug, Copy, Clone)]
+    pub(crate) enum FalconFbifEngineIdFlag with From<Bounded<u32, 1>> {
+        /// The BAR2 engine ID of PCI function 0.
+        Bar2Fn0 = 0,
+        /// The falcon's own engine ID.
+        Own = 1,
+    }
+}
+
 const PFALCON_REGION_SIZE: usize = SZ_4K;
 const PFALCON2_REGION_SIZE: usize = SZ_4K;
 
@@ -394,7 +408,7 @@ pub(crate) struct Falcon<'a, E: FalconEngine> {
     bar: Bar0<'a>,
     // TODO: make private
     pub(crate) pfalcon: Mmio<'a, PFalconRegisters>,
-    pfalcon2: Mmio<'a, PFalcon2Registers>,
+    pub(crate) pfalcon2: Mmio<'a, PFalcon2Registers>,
 }
 
 impl<'a, E: FalconEngine + 'static> Falcon<'a, E> {
@@ -628,6 +642,37 @@ fn dma_wr(
         Ok(())
     }
 
+    /// Programs FBIF context DMA slot `ctx_dma` with the value that `configure` returns, runs `f`,
+    /// and restores the slot once `f` has returned `Ok`.
+    ///
+    /// The slot keeps the programmed value if `f` fails, since a falcon that `f` started and that
+    /// has not halted may still be reading through the aperture.
+    ///
+    /// # Errors
+    ///
+    /// - `EINVAL` if `ctx_dma` is not a context DMA slot that the falcon has.
+    ///
+    /// Errors from `f` are propagated as-is.
+    pub(crate) fn with_fbif_transcfg<R>(
+        &self,
+        ctx_dma: u32,
+        configure: impl FnOnce(regs::NV_PFALCON_FBIF_TRANSCFG) -> regs::NV_PFALCON_FBIF_TRANSCFG,
+        f: impl FnOnce() -> Result<R>,
+    ) -> Result<R> {
+        // The location type is not `Copy`, so each register access builds its own.
+        let transcfg =
+            || regs::NV_PFALCON_FBIF_TRANSCFG::try_at(usize::from_safe_cast(ctx_dma)).ok_or(EINVAL);
+
+        let saved = self.pfalcon.read(transcfg()?);
+        self.pfalcon.update(transcfg()?, configure);
+
+        let result = f()?;
+
+        self.pfalcon.update(transcfg()?, |_| saved);
+
+        Ok(result)
+    }
+
     /// Transfers `len` bytes from `src_addr` into this falcon's `target_mem`.
     ///
     /// `src_addr` is a GPU physical address reached through the FBIF aperture, so the caller must
@@ -639,7 +684,6 @@ fn dma_wr(
     ///   not 256-byte aligned.
     /// - `ERANGE` if `src_addr` does not fit the `DMATRFBASE` register pair.
     /// - `EOVERFLOW` if a per-block source or destination offset exceeds `u32`.
-    #[expect(dead_code)]
     pub(crate) fn raw_dma_transfer(
         &self,
         ctx_dma: u32,
@@ -788,7 +832,6 @@ pub(crate) fn is_processor_suspended(&self) -> bool {
     /// # Errors
     ///
     /// - `ETIMEDOUT` if the core has not suspended within two seconds.
-    #[expect(dead_code)]
     pub(crate) fn wait_for_processor_suspend(&self) -> Result {
         read_poll_timeout(
             || Ok(self.is_processor_suspended()),
drivers/gpu/nova-core/falcon/gsp.rs +7 -3
index dfa08bc6867c..70f7d55f9b59 100644
@@ -115,15 +115,19 @@ pub(crate) fn retrigger_intr(bar: Bar0<'_>, chipset: Chipset) {
 }
 
 impl<'a> Falcon<'a, Gsp> {
-    /// Checks if GSP reload/resume has completed during the boot process.
-    pub(crate) fn check_reload_completed(&self, timeout: Delta) -> Result<bool> {
+    /// Waits until the Boot Sequence Interface (BSI) reports that the GSP reload has completed.
+    ///
+    /// # Errors
+    ///
+    /// - `ETIMEDOUT` if the reload has not completed within `timeout`.
+    pub(crate) fn check_reload_completed(&self, timeout: Delta) -> Result {
         read_poll_timeout(
             || Ok(self.bar.read(regs::NV_PGC6_BSI_SECURE_SCRATCH_14)),
             |val| val.boot_stage_3_handoff(),
             Delta::ZERO,
             timeout,
         )
-        .map(|_| true)
+        .map(|_| ())
     }
 
     /// Returns whether the RISC-V branch privilege lockdown bit is set.
drivers/gpu/nova-core/gsp/boot.rs +255 -2

282 lines not on this page · raw message

drivers/gpu/nova-core/regs.rs +2 -0
index feb37de69be5..ec8e05dc3351 100644
@@ -18,6 +18,7 @@
         DmaTrfCmdSize,
         FalconCoreRev,
         FalconCoreRevSubversion,
+        FalconFbifEngineIdFlag,
         FalconFbifMemType,
         FalconFbifTarget,
         FalconMem,
@@ -286,6 +287,7 @@ pub(crate) fn usable_fb_size(self) -> u64 {
     }
 
     pub(crate) NV_PFALCON_FBIF_TRANSCFG(u32)[8] @ 0x00000600 {
+        16:16   engine_id_flag => FalconFbifEngineIdFlag;
         2:2     mem_type => FalconFbifMemType;
         1:0     target ?=> FalconFbifTarget;
     }
drivers/gpu/nova-core/sbuffer.rs +0 -1
index 3a41d224c77a..b8c01104c255 100644
@@ -146,7 +146,6 @@ fn get_slice(&mut self, len: usize) -> Option<&'a [u8]> {
 
     /// Ideally we would implement `Read`, but it is not available in `core`.
     /// So mimic `std::io::Read::read_exact`.
-    #[expect(unused)]
     pub(crate) fn read_exact(&mut self, mut dst: &mut [u8]) -> Result {
         while !dst.is_empty() {
             match self.get_slice(dst.len()) {
Signature · 1 line
2.55.0
#42 lore raw

PATCH v3 16/33 gpu: nova-core: move the bootloader DMEM descriptor out of FWSEC

In reply to John Hubbard

The generic falcon bootloader reads its load parameters from a descriptor that the driver places in DMEM. The r000 load-and-execute bootloader event carries such a descriptor, so its handler in the following patch needs the descriptor type.

The descriptor was defined in the FWSEC code, which was its only user.

Move the definition, unchanged, into the generic bootloader module. Its fields become pub(crate) so that the FWSEC code can still fill them in.

No functional changes.

Assisted-by LLM
---
 .../nova-core/firmware/fwsec/bootloader.rs    | 52 ++-----------------
 .../gpu/nova-core/firmware/gen_bootloader.rs  | 48 +++++++++++++++++
 2 files changed, 52 insertions(+), 48 deletions(-)
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +4 -48
index 1584a4b814d2..96ad223df16f 100644
@@ -35,60 +35,16 @@
     },
     firmware::{
         fwsec::FwsecFirmware,
-        gen_bootloader::GenericBootloader, //
+        gen_bootloader::{
+            BootloaderDmemDescV2,
+            GenericBootloader, //
+        },
     },
     gpu::Chipset,
     num::FromSafeCast, //
     regs,
 };
 
-/// Structure used by the boot-loader to load the rest of the code.
-///
-/// This has to be filled by the GPU driver and copied into DMEM at offset
-/// [`BootloaderDesc.dmem_load_off`].
-#[repr(C, packed)]
-#[derive(Debug, Clone)]
-struct BootloaderDmemDescV2 {
-    /// Reserved, should always be first element.
-    reserved: [u32; 4],
-    /// 16B signature for secure code, 0s if no secure code.
-    signature: [u32; 4],
-    /// DMA context used by the bootloader while loading code/data.
-    ctx_dma: u32,
-    /// 256B-aligned physical FB address where code is located.
-    code_dma_base: u64,
-    /// Offset from `code_dma_base` where the non-secure code is located.
-    ///
-    /// Also used as destination IMEM offset of non-secure code as the DMA firmware object is
-    /// expected to be a mirror image of its loaded state.
-    ///
-    /// Must be multiple of 256.
-    non_sec_code_off: u32,
-    /// Size of the non-secure code part.
-    non_sec_code_size: u32,
-    /// Offset from `code_dma_base` where the secure code is located (must be multiple of 256).
-    ///
-    /// Also used as destination IMEM offset of secure code as the DMA firmware object is expected
-    /// to be a mirror image of its loaded state.
-    ///
-    /// Must be multiple of 256.
-    sec_code_off: u32,
-    /// Size of the secure code part.
-    sec_code_size: u32,
-    /// Code entry point invoked by the bootloader after code is loaded.
-    code_entry_point: u32,
-    /// 256B-aligned physical FB address where data is located.
-    data_dma_base: u64,
-    /// Size of data block (should be multiple of 256B).
-    data_size: u32,
-    /// Number of arguments to be passed to the target firmware being loaded.
-    argc: u32,
-    /// Arguments to be passed to the target firmware being loaded.
-    argv: u32,
-}
-// SAFETY: This struct doesn't contain uninitialized bytes and doesn't have interior mutability.
-unsafe impl AsBytes for BootloaderDmemDescV2 {}
-
 /// Wrapper for [`FwsecFirmware`] that includes the bootloader performing the actual load
 /// operation.
 pub(crate) struct FwsecFirmwareWithBl<'a> {
drivers/gpu/nova-core/firmware/gen_bootloader.rs +48 -0

60 lines not on this page · raw message

Signature · 1 line
2.55.0
#43 lore raw

Re: [PATCH v3 16/33] gpu: nova-core: move the bootloader DMEM descriptor out of FWSEC

Quoted 7 lines · John Hubbard

The generic falcon bootloader reads its load parameters from a descriptor that the driver places in DMEM. The r000 load-and-execute bootloader event carries such a descriptor, so its handler in the following patch needs the descriptor type.

The descriptor was defined in the FWSEC code, which was its only user.

Quoted 7 lines

Move the definition, unchanged, into the generic bootloader module. Its fields become pub(crate) so that the FWSEC code can still fill them in.

No functional changes.

Assisted-by LLM

Just one ask for this one: since the descriptor has moved, all its fields are now pub(crate), which is not representative of how we actually use them as this visibility is only needed for fwsec/bootloader.rs to build its own instance.

Instead, can we keep the fields private, add accessors for the few that we actually need to read after construction (that's ctx_dma only IIUC), and add a constructor for fwsec to use? The constructor would just need to take imem_ns, imem_sec, dmem, and the code and data DMA bases (the ctx_dma being a constant).

This will turn the move into an actual move, while keeping more of the logic (construction) inside gen_bootloader.rs.

#44 lore raw

PATCH v3 17/33 gpu: nova-core: add the r000 load-and-execute bootloader handler

In reply to John Hubbard

On Turing and GA100, whose GSP boots through the generic falcon bootloader, GSP-RM sends a second kind of load-and-execute event. It requests the driver to run an image on the GSP falcon, and it carries a descriptor that holds the image's addresses. The driver does not copy the image itself. It loads the generic bootloader and the descriptor into the falcon, and the bootloader reads the descriptor from DMEM and copies the image, as in Open RM.

Add the handler. It runs the bootloader through the FBIF aperture that the descriptor's address space and cache attribute select, and it rejects the event on a chipset that boots without the bootloader.

Pair the bootloader with a descriptor as the firmware that the falcon loads by PIO, and load FWSEC through the same pairing in place of the FWSEC wrapper's own load implementation.

---
 .../nova-core/firmware/fwsec/bootloader.rs    |  53 ++------
 .../gpu/nova-core/firmware/gen_bootloader.rs  |  85 ++++++++++--
 drivers/gpu/nova-core/gsp/boot.rs             | 125 +++++++++++++++++-
 3 files changed, 209 insertions(+), 54 deletions(-)
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +8 -45
index 96ad223df16f..48e0c9672412 100644
@@ -16,22 +16,16 @@
         register::Array,
         Io, //
     },
-    prelude::*,
-    transmute::AsBytes,
+    prelude::*, //
 };
 
 use crate::{
     falcon::{
         gsp::Gsp,
         Falcon,
-        FalconBromParams,
         FalconDmaLoadable,
         FalconFbifMemType,
-        FalconFbifTarget,
-        FalconFirmware,
-        FalconPioDmemLoadTarget,
-        FalconPioImemLoadTarget,
-        FalconPioLoadable, //
+        FalconFbifTarget, //
     },
     firmware::{
         fwsec::FwsecFirmware,
@@ -50,16 +44,17 @@
 pub(crate) struct FwsecFirmwareWithBl<'a> {
     /// DMA object the bootloader will copy the firmware from.
     _firmware_dma: Coherent<'a, [u8]>,
+    /// The bootloader that copies the firmware.
     bootloader: GenericBootloader,
     /// Descriptor to be loaded into DMEM for the bootloader to read.
     dmem_desc: BootloaderDmemDescV2,
-    /// BROM parameters of the loaded firmware.
-    brom_params: FalconBromParams,
 }
 
 impl<'a> FwsecFirmwareWithBl<'a> {
-    /// Loads the bootloader firmware for `dev` and `chipset`, and wrap `firmware` so it can be
-    /// loaded using it.
+    /// Wraps `firmware` so that the generic bootloader can load it.
+    ///
+    /// The bootloader image for `chipset` is loaded here, to run from the last blocks of the
+    /// IMEM of `falcon`. The firmware is mapped for `dev`.
     pub(crate) fn new(
         firmware: FwsecFirmware,
         dev: &'a Device<device::Bound>,
@@ -141,7 +136,6 @@ pub(crate) fn new(
             _firmware_dma: firmware_dma,
             bootloader,
             dmem_desc,
-            brom_params: firmware.brom_params(),
         })
     }
 
@@ -155,7 +149,7 @@ pub(crate) fn run(&self, dev: &Device<device::Bound>, falcon: &Falcon<'_, Gsp>)
             .reset()
             .inspect_err(|e| dev_err!(dev, "Failed to reset GSP falcon: {:?}\n", e))?;
         falcon
-            .pio_load(self)
+            .pio_load(&self.bootloader.with_descriptor(&self.dmem_desc))
             .inspect_err(|e| dev_err!(dev, "Failed to load FWSEC firmware: {:?}\n", e))?;
 
         // Configure DMA index for the bootloader to fetch the FWSEC firmware from system memory.
@@ -179,34 +173,3 @@ pub(crate) fn run(&self, dev: &Device<device::Bound>, falcon: &Falcon<'_, Gsp>)
         }
     }
 }
-
-impl FalconFirmware for FwsecFirmwareWithBl<'_> {
-    type Target = Gsp;
-
-    fn brom_params(&self) -> FalconBromParams {
-        self.brom_params.clone()
-    }
-
-    fn boot_addr(&self) -> u32 {
-        // On V2 platforms, the boot address is extracted from the generic bootloader, because the
-        // gbl is what actually copies FWSEC into memory, so that is what needs to be booted.
-        self.bootloader.boot_addr()
-    }
-}
-
-impl FalconPioLoadable for FwsecFirmwareWithBl<'_> {
-    fn imem_sec_load_params(&self) -> Option<FalconPioImemLoadTarget<'_>> {
-        None
-    }
-
-    fn imem_ns_load_params(&self) -> Option<FalconPioImemLoadTarget<'_>> {
-        Some(self.bootloader.imem_load_params())
-    }
-
-    fn dmem_load_params(&self) -> FalconPioDmemLoadTarget<'_> {
-        FalconPioDmemLoadTarget {
-            data: self.dmem_desc.as_bytes(),
-            dst_start: 0,
-        }
-    }
-}
drivers/gpu/nova-core/firmware/gen_bootloader.rs +77 -8

118 lines not on this page · raw message

drivers/gpu/nova-core/gsp/boot.rs +124 -1

149 lines not on this page · raw message

Signature · 1 line
2.55.0
#45 lore raw

Re: [PATCH v3 17/33] gpu: nova-core: add the r000 load-and-execute bootloader handler

Quoted 19 lines · John Hubbard
(quoted diff) +0 -0
@@ -133,6 +141,75 @@ fn core_resume(&self) -> Result {
          Ok(())
      }


+    /// Runs the generic bootloader on the GSP falcon, as a GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER
+    /// event requests, and then restarts GSP-RM.
+    ///
+    /// The descriptor that the event carries names the image that the bootloader loads. +    ///
+    /// # Errors
+    ///
+    /// - EINVAL if this chipset boots without the generic bootloader, if the payload is shorter
+    ///   than the parameter block, if the descriptor is not the size that this driver defines for
+    ///   it, or if the event names a context DMA slot or an aperture that does not exist. +    /// - ETIMEDOUT if the RISC-V core does not suspend within two seconds, or the GSP falcon does

Quoted 8 lines

+    ///   not halt within two seconds of starting the image.
+    ///
+    /// Errors from [Self::core_resume] are propagated as-is.
+    #[expect(dead_code)]
+    fn handle_load_exec_bootloader(&self, payload_0: &[u8], payload_1: &[u8]) -> Result { +        let Self {
+            gsp_falcon, dev, ..
+        } = *self;

Why do you create local variables of two member of LoadExecContext? By doing this:

        let Self {
            gsp_falcon, dev, ..
        } = *self;

you force every member of LoadExecContext to implement Copy, even the ones you are not copying here.

drivers/gpu/nova-core/gsp/boot.rs fn core_resume(&self) -> Result { · line 178

Quoted 7 lines
drivers/gpu/nova-core/gsp/boot.rs +7 -0
+        if params.dmem_desc_size != BootloaderDmemDescV2::SIZE {
+            dev_err!(
+                dev,
+                "Load-exec descriptor is {} bytes, expected {}\n",
+                params.dmem_desc_size,
+                BootloaderDmemDescV2::SIZE
+            );

So here, why not just do self.dev?

#46 lore raw

Re: [PATCH v3 17/33] gpu: nova-core: add the r000 load-and-execute bootloader handler

Quoted 31 lines · Timur Tabi
Quoted 19 lines · John Hubbard
(quoted diff) +0 -0
@@ -133,6 +141,75 @@ fn core_resume(&self) -> Result {
          Ok(())
      }


+    /// Runs the generic bootloader on the GSP falcon, as a GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER
+    /// event requests, and then restarts GSP-RM.
+    ///
+    /// The descriptor that the event carries names the image that the bootloader loads. +    ///
+    /// # Errors
+    ///
+    /// - EINVAL if this chipset boots without the generic bootloader, if the payload is shorter
+    ///   than the parameter block, if the descriptor is not the size that this driver defines for
+    ///   it, or if the event names a context DMA slot or an aperture that does not exist. +    /// - ETIMEDOUT if the RISC-V core does not suspend within two seconds, or the GSP falcon does

Quoted 8 lines

+    ///   not halt within two seconds of starting the image.
+    ///
+    /// Errors from [Self::core_resume] are propagated as-is.
+    #[expect(dead_code)]
+    fn handle_load_exec_bootloader(&self, payload_0: &[u8], payload_1: &[u8]) -> Result { +        let Self {
+            gsp_falcon, dev, ..
+        } = *self;

Why do you create local variables of two member of LoadExecContext? By doing this:

Quoted 7 lines
        let Self {
            gsp_falcon, dev, ..
        } = *self;

you force every member of LoadExecContext to implement Copy, even the ones you are not copying here.

Oh, that's not true! The ".." skips the other items, so there is no such copying going on. Only the two named items are copied.

However, this is also just a little too unusual (Nova doesn't do this little trick anywhere else), so I'm taking your advice and just Not Doing It anymore, good call. :)

Quoted 9 lines

drivers/gpu/nova-core/gsp/boot.rs fn core_resume(&self) -> Result { · line 178

Quoted 7 lines
drivers/gpu/nova-core/gsp/boot.rs +7 -0
+        if params.dmem_desc_size != BootloaderDmemDescV2::SIZE {
+            dev_err!(
+                dev,
+                "Load-exec descriptor is {} bytes, expected {}\n",
+                params.dmem_desc_size,
+                BootloaderDmemDescV2::SIZE
+            );

So here, why not just do self.dev?

Yes, I'll go back to doing that.

thanks,

Signature · 1 line
John Hubbard
#47 lore raw

Re: [PATCH v3 17/33] gpu: nova-core: add the r000 load-and-execute bootloader handler

In reply to John Hubbard

On Fri Sep 18, 2026 at 10:07 AM JST, John Hubbard wrote:
<...>

drivers/gpu/nova-core/firmware/gen_bootloader.rs pub(crate) struct BootloaderDmemDescV2 { · line 86

Quoted 8 lines
drivers/gpu/nova-core/firmware/gen_bootloader.rs +4 -0
@@ -72,9 +80,18 @@ pub(crate) struct BootloaderDmemDescV2 {
     /// Arguments to be passed to the target firmware being loaded.
     pub(crate) argv: u32,
 }
+
+impl BootloaderDmemDescV2 {
+    /// Size of the descriptor in bytes, as the load-and-execute event states it.
+    pub(crate) const SIZE: u32 = num::usize_into_u32::<{ size_of::<BootloaderDmemDescV2>() }>();

This constant is only used locally in one method, so let's declare it there instead.

Quoted 12 lines
drivers/gpu/nova-core/firmware/gen_bootloader.rs +5 -0
+}
+
 // SAFETY: This struct doesn't contain uninitialized bytes and doesn't have interior mutability.
 unsafe impl AsBytes for BootloaderDmemDescV2 {}
 
+// SAFETY: This struct only contains integer types for which all bit patterns are valid.
+unsafe impl FromBytes for BootloaderDmemDescV2 {}
+
 /// The generic falcon bootloader image and its IMEM load parameters.
 pub(crate) struct GenericBootloader {
     /// Bootloader code, zero-padded to a whole number of falcon memory blocks.

drivers/gpu/nova-core/firmware/gen_bootloader.rs pub(crate) fn imem_load_params(&self) -> FalconPioImemLoadTarget<'_> { · line 166

Quoted 6 lines
drivers/gpu/nova-core/firmware/gen_bootloader.rs +3 -0
@@ -144,4 +161,56 @@ pub(crate) fn imem_load_params(&self) -> FalconPioImemLoadTarget<'_> {
             start_tag: self.start_tag,
         }
     }
+
+    /// Returns the bootloader and `descriptor` as one firmware that [`Falcon::pio_load`] accepts.
+    pub(crate) fn with_descriptor<'a>(

This makes us export the GenericBootloaderLoad type and is not used for anything but running the bootloader. How about converting this to a boot method?

If would need to take a few parameters like the FalconFbifTarget and mbox0 value, but that way we don't need to export GenericBootloaderLoad.

#48 lore raw

PATCH v3 18/33 gpu: nova-core: gsp: add the GMC boot event dispatcher

In reply to John Hubbard

The two load-and-execute events of the r000 boot protocol arrive as GMC events, each named by a command id.

Nova-core had a handler for each event, but no dispatcher that read the id and picked the handler, and each handler ended with its own copy of the core resume.

Add the dispatcher, and move the core resume out of the two handlers into it. Each handler now ends with the falcon halted, and the dispatcher runs the core resume once after whichever handler ran. The dispatcher has no caller yet.

---
 drivers/gpu/nova-core/gsp/boot.rs | 69 +++++++++++++++++++++++--------
 drivers/gpu/nova-core/gsp/fw.rs   | 10 +++++
 2 files changed, 62 insertions(+), 17 deletions(-)
drivers/gpu/nova-core/gsp/boot.rs +52 -17
index ee366d782218..c805b42dd7bc 100644
@@ -39,7 +39,11 @@
     },
     gsp::{
         cmdq::Cmdq,
-        commands, //
+        commands,
+        fw::{
+            GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER,
+            GMCAPI_CMD_EXEC_HS_BINARY, //
+        }, //
     },
     regs,
     sbuffer::SBufferIter, //
@@ -141,10 +145,51 @@ fn core_resume(&self) -> Result {
         Ok(())
     }
 
+    /// Runs the load-and-execute handler that `command_id` names on the event payload, which the
+    /// ring may have split in two, and then runs the core resume.
+    ///
+    /// # Errors
+    ///
+    /// - `EINVAL` if `command_id` is not a load-and-execute command.
+    ///
+    /// Errors from the handlers and from [`Self::core_resume`] are propagated as-is.
+    #[expect(dead_code)]
+    fn dispatch_gmc_boot_event(
+        &self,
+        command_id: u32,
+        payload_0: &[u8],
+        payload_1: &[u8],
+    ) -> Result {
+        let handled = match command_id {
+            GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER => {
+                self.handle_load_exec_bootloader(payload_0, payload_1)
+            }
+            GMCAPI_CMD_EXEC_HS_BINARY => self.handle_load_exec_hs_binary(payload_0, payload_1),
+            _ => {
+                dev_err!(
+                    self.dev,
+                    "Unexpected GMC boot event: command_id={:#010x}\n",
+                    command_id
+                );
+                return Err(EINVAL);
+            }
+        };
+
+        handled.and_then(|()| self.core_resume()).inspect_err(|e| {
+            dev_err!(
+                self.dev,
+                "GMC boot event {:#010x} failed: {:?}\n",
+                command_id,
+                e
+            );
+        })
+    }
+
     /// Runs the generic bootloader on the GSP falcon, as a `GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER`
-    /// event requests, and then restarts GSP-RM.
+    /// event requests.
     ///
-    /// The descriptor that the event carries names the image that the bootloader loads.
+    /// The descriptor that the event carries names the image that the bootloader loads. The GSP
+    /// falcon is left halted.
     ///
     /// # Errors
     ///
@@ -153,9 +198,6 @@ fn core_resume(&self) -> Result {
     ///   it, or if the event names a context DMA slot or an aperture that does not exist.
     /// - `ETIMEDOUT` if the RISC-V core does not suspend within two seconds, or the GSP falcon does
     ///   not halt within two seconds of starting the image.
-    ///
-    /// Errors from [`Self::core_resume`] are propagated as-is.
-    #[expect(dead_code)]
     fn handle_load_exec_bootloader(&self, payload_0: &[u8], payload_1: &[u8]) -> Result {
         let Self {
             gsp_falcon, dev, ..
@@ -205,16 +247,14 @@ fn handle_load_exec_bootloader(&self, payload_0: &[u8], payload_1: &[u8]) -> Res
 
                 Ok(())
             },
-        )?;
-
-        self.core_resume()
+        )
     }
 
     /// Runs a Heavy-Secured (HS) binary on the GSP falcon, as a `GMCAPI_CMD_EXEC_HS_BINARY` event
-    /// requests, and then restarts GSP-RM.
+    /// requests.
     ///
     /// GSP-RM has placed the binary in the framebuffer, and the falcon's boot ROM (BROM) verifies
-    /// the binary's signature before the binary runs.
+    /// the binary's signature before the binary runs. The GSP falcon is left halted.
     ///
     /// # Errors
     ///
@@ -222,9 +262,6 @@ fn handle_load_exec_bootloader(&self, payload_0: &[u8], payload_1: &[u8]) -> Res
     ///   fit the BROM register field.
     /// - `ETIMEDOUT` if the RISC-V core does not suspend within two seconds, or the GSP falcon does
     ///   not halt within two seconds of starting the binary.
-    ///
-    /// Errors from [`Self::core_resume`] are propagated as-is.
-    #[expect(dead_code)]
     fn handle_load_exec_hs_binary(&self, payload_0: &[u8], payload_1: &[u8]) -> Result {
         let Self {
             gsp_falcon, dev, ..
@@ -297,9 +334,7 @@ fn handle_load_exec_hs_binary(&self, payload_0: &[u8], payload_1: &[u8]) -> Resu
 
                 Ok(())
             },
-        )?;
-
-        self.core_resume()
+        )
     }
 }
 
drivers/gpu/nova-core/gsp/fw.rs +10 -0
index f23d071f0e16..e86283f67358 100644
@@ -1055,6 +1055,16 @@ pub(crate) struct GmcApiHeader {
 /// Bits of [`GmcApiHeader::command`] that hold the command id. The high byte holds flags.
 const GMCAPI_COMMAND_ID_MASK: u32 = 0x00ff_ffff;
 
+/// GMC event that requests the driver to run the generic falcon bootloader on the descriptor that
+/// the event carries.
+pub(crate) const GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER: u32 =
+    r000_00::GMCAPI_COMMANDS_GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER;
+
+/// GMC event that requests the driver to run a Heavy-Secured (HS) binary that GSP-RM has placed in
+/// the framebuffer.
+pub(crate) const GMCAPI_CMD_EXEC_HS_BINARY: u32 =
+    r000_00::GMCAPI_COMMANDS_GMCAPI_CMD_EXEC_HS_BINARY;
+
 static_assert!(size_of::<GmcApiHeader>() == size_of::<r000_00::GMCAPI_HEADER>());
 static_assert!(
     core::mem::offset_of!(GmcApiHeader, command)
Signature · 1 line
2.55.0
#49 lore raw

PATCH v3 19/33 gpu: nova-core: gsp: rename the static configuration type

In reply to John Hubbard

The following patches fill the type that holds GSP-RM's static GPU configuration from the r000 GSP_INIT reply, where no command fetches the configuration.

The type was named after the r570 command that fetched it.

Name the type after its contents.

No functional changes.

Assisted-by LLM
---
 drivers/gpu/nova-core/gpu.rs          |  4 ++--
 drivers/gpu/nova-core/gsp.rs          |  2 +-
 drivers/gpu/nova-core/gsp/commands.rs | 12 ++++++------
 3 files changed, 9 insertions(+), 9 deletions(-)
drivers/gpu/nova-core/gpu.rs +2 -2
index 9e0570e97cfe..e7f1458330b4 100644
@@ -34,7 +34,7 @@
     fsp::Fsp,
     gsp::{
         self,
-        commands::GetGspStaticInfoReply,
+        commands::GspStaticInfo,
         Gsp,
         GspBootContext, //
     },
@@ -314,7 +314,7 @@ pub(crate) struct Gpu<'gpu> {
     #[pin]
     _gsp_irq: GspIrq<'gpu>,
     /// Static GPU information as provided by the GSP.
-    gsp_static_info: GetGspStaticInfoReply,
+    gsp_static_info: GspStaticInfo,
     /// GPU memory manager owning memory management resources.
     ///
     /// Must be kept declared *before* `gsp_resources`, so that its components are dropped while
drivers/gpu/nova-core/gsp.rs +1 -1
index c9b7498639b7..6e7a057188c5 100644
@@ -221,7 +221,7 @@ pub(crate) fn new(
     }
 
     /// Query the GSP for the static GPU information.
-    pub(crate) fn get_static_info(&self) -> Result<commands::GetGspStaticInfoReply> {
+    pub(crate) fn get_static_info(&self) -> Result<commands::GspStaticInfo> {
         self.cmdq.send_command(commands::GetGspStaticInfo)
     }
 }
drivers/gpu/nova-core/gsp/commands.rs +6 -6
index a01ab14299c6..b3b28e397ebd 100644
@@ -197,7 +197,7 @@ pub(crate) fn wait_gsp_init_done(cmdq: &Cmdq<'_>) -> Result {
 impl CommandToGsp for GetGspStaticInfo {
     const FUNCTION: MsgFunction = MsgFunction::GetGspStaticInfo;
     type Command = fw::commands::GspStaticConfigInfo;
-    type Reply = GetGspStaticInfoReply;
+    type Reply = GspStaticInfo;
     type InitError = Infallible;
 
     fn init(&self) -> impl Init<Self::Command, Self::InitError> {
@@ -206,7 +206,7 @@ fn init(&self) -> impl Init<Self::Command, Self::InitError> {
 }
 
 /// The reply from the GSP to the [`GetGspStaticInfo`] command.
-pub(crate) struct GetGspStaticInfoReply {
+pub(crate) struct GspStaticInfo {
     gpu_name: [u8; 64],
     /// BAR1 Page Directory Entry base address.
     pub(crate) bar1_pde_base: u64,
@@ -216,7 +216,7 @@ pub(crate) struct GetGspStaticInfoReply {
     pub(crate) total_fb_end: u64,
 }
 
-impl MessageFromGsp for GetGspStaticInfoReply {
+impl MessageFromGsp for GspStaticInfo {
     const FUNCTION: MsgFunction = MsgFunction::GetGspStaticInfo;
     type Message = fw::commands::GspStaticConfigInfo;
     type InitError = Error;
@@ -231,7 +231,7 @@ fn read(
         }
         let total_fb_end = msg.total_fb_end().ok_or(EINVAL)?;
 
-        Ok(GetGspStaticInfoReply {
+        Ok(GspStaticInfo {
             gpu_name: msg.gpu_name_str(),
             bar1_pde_base: msg.bar1_pde_base(),
             usable_fb_regions,
@@ -240,7 +240,7 @@ fn read(
     }
 }
 
-/// Error type for [`GetGspStaticInfoReply::gpu_name`].
+/// Error type for [`GspStaticInfo::gpu_name`].
 #[derive(Debug)]
 pub(crate) enum GpuNameError {
     /// The GPU name string does not contain a null terminator.
@@ -251,7 +251,7 @@ pub(crate) enum GpuNameError {
     InvalidUtf8(Utf8Error),
 }
 
-impl GetGspStaticInfoReply {
+impl GspStaticInfo {
     /// Returns the name of the GPU as a string.
     ///
     /// Returns an error if the string given by the GSP does not contain a null terminator or
Signature · 1 line
2.55.0
#50 lore raw

PATCH v3 20/33 gpu: nova-core: gsp: return the static GPU configuration from boot

In reply to John Hubbard

Once GSP-RM has started, it reports the static GPU configuration: the GPU's name, its usable framebuffer regions and its BAR1 page directory. Everything that the driver builds on top of the GSP depends on that configuration. In the r000 boot protocol the configuration arrives as the reply to the request that ends boot, so the boot sequence holds it when it returns.

Nova-core fetched the configuration in a separate step after boot, once the interrupt handler was registered, so on r000 the boot sequence would have had to keep the reply for that step to read.

Return the configuration from the boot sequence together with the unload bundle, and drop the separate step.

Assisted-by LLM
---
 drivers/gpu/nova-core/gpu.rs          | 44 ++++++++++++++-------------
 drivers/gpu/nova-core/gsp.rs          | 13 +++++---
 drivers/gpu/nova-core/gsp/boot.rs     | 15 ++++++---
 drivers/gpu/nova-core/gsp/commands.rs |  2 +-
 4 files changed, 42 insertions(+), 32 deletions(-)
drivers/gpu/nova-core/gpu.rs +23 -21
index e7f1458330b4..0ed0f4722dc5 100644
@@ -34,7 +34,6 @@
     fsp::Fsp,
     gsp::{
         self,
-        commands::GspStaticInfo,
         Gsp,
         GspBootContext, //
     },
@@ -298,8 +297,15 @@ struct GspResources<'gpu> {
     /// GSP runtime data.
     #[pin]
     gsp: Gsp<'gpu>,
-    /// GSP unload firmware bundle, if any.
-    unload_bundle: Option<gsp::UnloadBundle<'gpu>>,
+    /// The static GPU configuration and the unload bundle that the boot sequence returned.
+    boot_result: gsp::BootResult<'gpu>,
+}
+
+impl GspResources<'_> {
+    /// Returns the static GPU configuration that GSP-RM reported at boot.
+    fn static_info(&self) -> &gsp::commands::GspStaticInfo {
+        &self.boot_result.static_info
+    }
 }
 
 /// Structure holding the resources required to operate the GPU.
@@ -313,8 +319,6 @@ pub(crate) struct Gpu<'gpu> {
     /// before the GSP is unloaded.
     #[pin]
     _gsp_irq: GspIrq<'gpu>,
-    /// Static GPU information as provided by the GSP.
-    gsp_static_info: GspStaticInfo,
     /// GPU memory manager owning memory management resources.
     ///
     /// Must be kept declared *before* `gsp_resources`, so that its components are dropped while
@@ -347,7 +351,7 @@ fn drop(self: Pin<&mut Self>) {
         let this = self.project();
         let device = *this.device;
         let bar = *this.bar;
-        let bundle = this.unload_bundle.take();
+        let bundle = this.boot_result.unload_bundle.take();
 
         let _ = this
             .gsp
@@ -416,10 +420,10 @@ pub(crate) fn new<'a>(
 
                 gsp <- Gsp::new(pdev, bar),
 
-                // This member must be initialized last, so the `UnloadBundle` can never be dropped
-                // from outside of the constructed `GspResources`, ensuring that the unload sequence
-                // is properly run in case of failure.
-                unload_bundle: gsp.boot(GspBootContext {
+                // This member must be initialized last, so that the unload bundle can never be
+                // dropped from outside the constructed `GspResources`, and the unload sequence runs
+                // on a failure.
+                boot_result: gsp.boot(GspBootContext {
                     pdev,
                     bar,
                     chipset: spec.chipset,
@@ -454,9 +458,8 @@ pub(crate) fn new<'a>(
                 gsp_resources.gsp.cmdq.drain()?;
             },
 
-            gsp_static_info: {
-                // Obtain and display basic GPU information.
-                let info = gsp_resources.gsp.get_static_info()?;
+            _: {
+                let info = gsp_resources.static_info();
                 match info.gpu_name() {
                     Ok(name) => dev_info!(dev, "GPU name: {}\n", name),
                     Err(e) => dev_warn!(dev, "GPU name unavailable: {:?}\n", e),
@@ -476,13 +479,12 @@ pub(crate) fn new<'a>(
                             / u64::SZ_1M
                     );
                 }
-
-                info
             },
 
             // Create GPU memory manager owning memory management resources.
             mm: {
-                let usable_vram = gsp_static_info.usable_fb_regions.first().ok_or(ENODEV)?;
+                let info = gsp_resources.static_info();
+                let usable_vram = info.usable_fb_regions.first().ok_or(ENODEV)?;
                 let buddy_params = GpuBuddyParams {
                     base_offset: usable_vram.start,
                     size: usable_vram.end - usable_vram.start,
@@ -493,13 +495,13 @@ pub(crate) fn new<'a>(
                     bar,
                     gsp_resources.spec.chipset,
                     buddy_params,
-                    VramAddress::from_raw(gsp_static_info.total_fb_end),
+                    VramAddress::from_raw(info.total_fb_end),
                 )?
             },
 
             // Create BAR1 user interface for CPU access to GPU virtual memory.
             bar_user: {
-                let pdb_addr = VramAddress::from_raw(gsp_static_info.bar1_pde_base);
+                let pdb_addr = VramAddress::from_raw(gsp_resources.static_info().bar1_pde_base);
                 let bar1_idx = crate::driver::bar1_resource_index(pdev)?;
                 let bar1_size = pdev.resource_len(bar1_idx)?;
                 Arc::pin_init(
@@ -520,14 +522,14 @@ pub(crate) fn new<'a>(
     pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device<device::Bound>) {
         let this = self.project();
         let dev = pdev.as_ref();
-        let regions = &this.gsp_static_info.usable_fb_regions;
+        let info = this.gsp_resources.static_info();
 
         if let Err(err) = crate::mm::selftest::run(
             dev,
             this.mm,
-            regions,
+            &info.usable_fb_regions,
             this.bar_user,
-            this.gsp_static_info.bar1_pde_base,
+            info.bar1_pde_base,
             this.spec.chipset,
         ) {
             dev_err!(dev, "self-tests failed: {:?}\n", err);
drivers/gpu/nova-core/gsp.rs +8 -5
index 6e7a057188c5..90b4c3380f11 100644
@@ -219,12 +219,15 @@ pub(crate) fn new(
             }))
         })
     }
-
-    /// Query the GSP for the static GPU information.
-    pub(crate) fn get_static_info(&self) -> Result<commands::GspStaticInfo> {
-        self.cmdq.send_command(commands::GetGspStaticInfo)
-    }
 }
 
 /// Opaque bundle required to unload the GSP. Created by [`Gsp::boot`], consumed by [`Gsp::unload`].
 pub(crate) struct UnloadBundle<'a>(KBox<dyn hal::UnloadBundle + 'a>);
+
+/// The results of [`Gsp::boot`]: the static GPU configuration and the unload bundle.
+pub(crate) struct BootResult<'a> {
+    /// The unload bundle for [`Gsp::unload`], if one could be built.
+    pub(crate) unload_bundle: Option<UnloadBundle<'a>>,
+    /// The static GPU configuration, as GSP-RM reported it at the end of boot.
+    pub(crate) static_info: commands::GspStaticInfo,
+}
drivers/gpu/nova-core/gsp/boot.rs +10 -5
index c805b42dd7bc..86a122438d44 100644
@@ -339,18 +339,18 @@ fn handle_load_exec_hs_binary(&self, payload_0: &[u8], payload_1: &[u8]) -> Resu
 }
 
 impl<'gsp> super::Gsp<'gsp> {
-    /// Attempt to boot the GSP.
+    /// Boots the GSP.
     ///
     /// This is a GPU-dependent and complex procedure that involves loading firmware files from
     /// user-space, patching them with signatures, and building firmware-specific intricate data
     /// structures that the GSP will use at runtime.
     ///
-    /// Upon return, the GSP is up and running, and its unload bundle (to be given as argument to
-    /// [`Self::unload`]) returned.
+    /// Returns, with the GSP running, the static configuration that GSP-RM reported and the
+    /// unload bundle for [`Self::unload`].
     pub(crate) fn boot(
         self: Pin<&mut Self>,
         mut ctx: super::GspBootContext<'_, 'gsp>,
-    ) -> Result<Option<super::UnloadBundle<'gsp>>> {
+    ) -> Result<super::BootResult<'gsp>> {
         let pdev = ctx.pdev;
         let chipset = ctx.chipset;
         let gsp_falcon = ctx.gsp_falcon;
@@ -398,7 +398,12 @@ pub(crate) fn boot(
         // Wait until GSP is fully initialized.
         commands::wait_gsp_init_done(&self.cmdq)?;
 
-        Ok(unload_guard.dismiss().1)
+        let static_info = self.cmdq.send_command(commands::GetGspStaticInfo)?;
+
+        Ok(super::BootResult {
+            unload_bundle: unload_guard.dismiss().1,
+            static_info,
+        })
     }
 
     /// Shut down the GSP and wait until it is offline.
drivers/gpu/nova-core/gsp/commands.rs +1 -1
index b3b28e397ebd..d866297fa0a5 100644
@@ -205,7 +205,7 @@ fn init(&self) -> impl Init<Self::Command, Self::InitError> {
     }
 }
 
-/// The reply from the GSP to the [`GetGspStaticInfo`] command.
+/// The static GPU configuration, which GSP-RM reports in reply to [`GetGspStaticInfo`].
 pub(crate) struct GspStaticInfo {
     gpu_name: [u8; 64],
     /// BAR1 Page Directory Entry base address.
Signature · 1 line
2.55.0
#51 lore raw

PATCH v3 21/33 gpu: nova-core: gsp: add the GSP_INIT request builder

In reply to John Hubbard

The r000 boot protocol replaces the system-info, registry and static-info commands with one GSP_INIT request, whose payload is an NVKV stream of key-value pairs.

Nova-core had the NVKV codec and the GSP_INIT schema, but no builder that filled the schema in from the PCI device.

Add the builder. It carries over the registry keys that the r570 registry command sent, and it reports the architecture that the kernel is built for. GSP-RM reads the GPU's PCI location as one word holding the domain, bus and device number. That word is not the bus, device and function triple that PCI_DEVID packs, so the builder assembles it rather than using PCI_DEVID.

---
 drivers/gpu/nova-core/gsp/commands.rs    |  23 +++++
 drivers/gpu/nova-core/gsp/fw/commands.rs | 110 +++++++++++++++++++++--
 2 files changed, 125 insertions(+), 8 deletions(-)
drivers/gpu/nova-core/gsp/commands.rs +23 -0
index d866297fa0a5..2c7965174445 100644
@@ -30,8 +30,14 @@
         },
         fw::{
             self,
+            commands::GspInitRequest,
             MsgFunction, //
         },
+        nvkv::{
+            Encodable,
+            EncodedStream,
+            Encoder, //
+        },
     },
     sbuffer::SBufferIter,
     vgpu::VgpuState, //
@@ -264,6 +270,23 @@ pub(crate) fn gpu_name(&self) -> core::result::Result<&str, GpuNameError> {
     }
 }
 
+/// Builds the NVKV-encoded payload of a `GSP_INIT` request for `pdev`.
+///
+/// # Errors
+///
+/// - `ENOMEM` if the request or the encoder buffer cannot be allocated.
+#[expect(dead_code)]
+pub(crate) fn build_gsp_init_payload(
+    pdev: &pci::Device<device::Bound>,
+    chipset: Chipset,
+    vgpu_state: VgpuState,
+) -> Result<EncodedStream> {
+    let mut encoder = Encoder::new();
+    GspInitRequest::new(pdev, chipset, vgpu_state)?.encode(&mut encoder)?;
+
+    Ok(encoder.finish())
+}
+
 pub(crate) use fw::commands::PowerStateLevel;
 
 /// The `UnloadingGuestDriver` command, used to shut down the GSP.
drivers/gpu/nova-core/gsp/fw/commands.rs +102 -8

163 lines not on this page · raw message

Signature · 1 line
2.55.0
#52 lore raw

Re: [PATCH v3 21/33] gpu: nova-core: gsp: add the GSP_INIT request builder

drivers/gpu/nova-core/gsp/fw/commands.rs impl VfInfo { · line 394

Quoted 13 lines · John Hubbard
drivers/gpu/nova-core/gsp/fw/commands.rs +3 -0
+/// Registry entries that the driver sends to GSP-RM on every boot.
+///
+/// `RMSecBusResetEnable` enables PCI secondary bus reset. `RMForcePcieConfigSave` makes GSP-

RM
+/// preserve PCI configuration registers across any PCI reset. RMDevidCheckIgnore lets GSP- RM

drivers/gpu/nova-core/gsp/fw/commands.rs +5 -0
+/// boot when the PCI device id is absent from its product name database.
+const REGISTRY_ENTRIES: &[(&[u8], u32)] = &[
+    (b"RMSecBusResetEnable\0", 1),
+    (b"RMForcePcieConfigSave\0", 1),
+    (b"RMDevidCheckIgnore\0", 1),

FYI, we may want to rethink RMDevidCheckIgnore for Nova. For Nouveau it was a big deal, because we were always lock on an older version of GSP-RM, so there's a chance that an older firmware could still support a newer GPU that isn't explicitly listed as supported in GSP-RM.

But considering the problems we had with GB20x and r570, we may want to make RMDevidCheckIgnore not the default.

I can submit a patch (once the dust with r615 settles) that makes it a command-line option, if you like.

#53 lore raw

Re: [PATCH v3 21/33] gpu: nova-core: gsp: add the GSP_INIT request builder

Quoted 19 lines · Timur Tabi

drivers/gpu/nova-core/gsp/fw/commands.rs impl VfInfo { · line 394

Quoted 13 lines · John Hubbard
drivers/gpu/nova-core/gsp/fw/commands.rs +3 -0
+/// Registry entries that the driver sends to GSP-RM on every boot.
+///
+/// `RMSecBusResetEnable` enables PCI secondary bus reset. `RMForcePcieConfigSave` makes GSP-

RM
+/// preserve PCI configuration registers across any PCI reset. RMDevidCheckIgnore lets GSP- RM

drivers/gpu/nova-core/gsp/fw/commands.rs +5 -0
+/// boot when the PCI device id is absent from its product name database.
+const REGISTRY_ENTRIES: &[(&[u8], u32)] = &[
+    (b"RMSecBusResetEnable\0", 1),
+    (b"RMForcePcieConfigSave\0", 1),
+    (b"RMDevidCheckIgnore\0", 1),

FYI, we may want to rethink RMDevidCheckIgnore for Nova. For Nouveau it was a big deal, because we were always lock on an older version of GSP-RM, so there's a chance that an older firmware could still support a newer GPU that isn't explicitly listed as supported in GSP-RM.

Quoted 2 lines

But considering the problems we had with GB20x and r570, we may want to make RMDevidCheckIgnore not the default.

Good point, but I'm not completely sure I'm making the correct choice yet:
should I remove RMDevidCheckIgnore here, or wait for your follow-up patch?

Quoted 3 lines

I can submit a patch (once the dust with r615 settles) that makes it a command-line option, if you like.

thanks,

Signature · 1 line
John Hubbard
#54 lore raw

Re: [PATCH v3 21/33] gpu: nova-core: gsp: add the GSP_INIT request builder

Quoted 20 lines · John Hubbard
Quoted 19 lines · Timur Tabi

drivers/gpu/nova-core/gsp/fw/commands.rs impl VfInfo { · line 394

Quoted 13 lines · John Hubbard
drivers/gpu/nova-core/gsp/fw/commands.rs +3 -0
+/// Registry entries that the driver sends to GSP-RM on every boot.
+///
+/// `RMSecBusResetEnable` enables PCI secondary bus reset. `RMForcePcieConfigSave` makes GSP-

RM
+/// preserve PCI configuration registers across any PCI reset. RMDevidCheckIgnore lets GSP- RM

drivers/gpu/nova-core/gsp/fw/commands.rs +5 -0
+/// boot when the PCI device id is absent from its product name database.
+const REGISTRY_ENTRIES: &[(&[u8], u32)] = &[
+    (b"RMSecBusResetEnable\0", 1),
+    (b"RMForcePcieConfigSave\0", 1),
+    (b"RMDevidCheckIgnore\0", 1),

FYI, we may want to rethink RMDevidCheckIgnore for Nova. For Nouveau it was a big deal, because we were always lock on an older version of GSP-RM, so there's a chance that an older firmware could still support a newer GPU that isn't explicitly listed as supported in GSP-RM.

Quoted 5 lines
Quoted 2 lines

But considering the problems we had with GB20x and r570, we may want to make RMDevidCheckIgnore not the default.

Good point, but I'm not completely sure I'm making the correct choice yet:
should I remove RMDevidCheckIgnore here, or wait for your follow-up patch?

No, don't remove it here. We need to investigate the impact of removing it. It would be a shame if this patchset randomly broke some GPU that needed this key.

Quoted 4 lines
Quoted 2 lines

I can submit a patch (once the dust with r615 settles) that makes it a command-line option, if you like.

thanks,

I'll add it to my to-do list.

#55 lore raw

Re: [PATCH v3 21/33] gpu: nova-core: gsp: add the GSP_INIT request builder

In reply to John Hubbard

On Fri Sep 18, 2026 at 10:07 AM JST, John Hubbard wrote:
<...>

Quoted 14 lines
drivers/gpu/nova-core/gsp/fw/commands.rs +14 -0
+    /// Creates the request for `dev`.
+    ///
+    /// The registry keys are [`REGISTRY_ENTRIES`], plus `RMSetSriovMode` when `vgpu_state` reports
+    /// that vGPU is enabled.
+    ///
+    /// # Errors
+    ///
+    /// - `ENOMEM` if the registry list cannot be allocated.
+    pub(crate) fn new(
+        dev: &pci::Device<device::Bound>,
+        chipset: Chipset,
+        vgpu_state: VgpuState,
+    ) -> Result<Self> {
+        let mut regkeys = KVVec::new();

drivers/gpu/nova-core/gsp/fw/commands.rs impl GspInitRequest { · line 430

Quoted 10 lines
drivers/gpu/nova-core/gsp/fw/commands.rs +10 -0
+        for &(name, value) in REGISTRY_ENTRIES {
+            regkeys.push(RegKey::new(name, value), GFP_KERNEL)?;
+        }
+        if matches!(vgpu_state, VgpuState::Enabled { .. }) {
+            regkeys.push(RegKey::new(b"RMSetSriovMode\0", 1), GFP_KERNEL)?;
+        }
+
+        let mirror = chipset.pci_config_mirror_range();
+        // `PCI_DEVID` packs the bus, device and function as the low half of a `Dbdf` does.
+        let dev_id = Dbdf::from(u32::from(dev.dev_id()));

This makes the build break: Dbdf is not created by this series or any of its listed dependencies, and comes from Zhi's series [1], which supposedly depends from this one - so we have a dependency cycle that needs to be broken somehow.

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

#56 lore raw

PATCH v3 22/33 gpu: nova-core: gsp: send GSP_INIT and decode its reply

In reply to John Hubbard

GSP-RM answers GSP_INIT only once it has finished starting. To finish starting, GSP-RM first raises the load-and-execute events and waits for the driver to service them. So the code that waits for the reply has to service those events while waiting.

Add the GSP_INIT sender and the wait for its reply. The wait passes each event that arrives before the reply to a handler that the caller supplies, and it keeps one deadline from the send however many events arrive, as the RPC reply wait does. Decode the reply into the static configuration type that the boot sequence already returns, so that the rest of the driver reads the same configuration whichever firmware produced it.

---
 drivers/gpu/nova-core/gsp/cmdq.rs        | 108 +++++++++++++++++++----
 drivers/gpu/nova-core/gsp/commands.rs    |  99 ++++++++++++++++++++-
 drivers/gpu/nova-core/gsp/fw.rs          |   7 +-
 drivers/gpu/nova-core/gsp/fw/commands.rs |  55 ++++++++++--
 4 files changed, 241 insertions(+), 28 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +91 -17
index b202bd8185ba..f64a97736ed7 100644
@@ -625,19 +625,38 @@ pub(crate) fn send_command_no_wait<M>(&self, command: M) -> Result
         self.inner.lock().send_command(command)
     }
 
-    /// Receives one GMC event and passes its command id and payload slices to `handler`.
+    /// Waits for the response to the GMC request with command id `command_id`, and passes every
+    /// other GMC element that arrives first to `on_other`.
     ///
-    /// This method may sleep while waiting. The queue mutex stays locked across the wait and the
-    /// `handler` call, so `handler` must not call back into this [`Cmdq`].
+    /// This method may sleep while waiting. The queue mutex stays locked across the whole wait and
+    /// across the `on_other` and `decode` calls, so neither may call back into this [`Cmdq`].
     ///
-    /// See [`CmdqInner::receive_gmc_and_dispatch`] for the return value and the errors.
-    #[expect(dead_code)]
-    pub(crate) fn receive_gmc_and_dispatch<R>(
+    /// See [`CmdqInner::await_gmc_response`] for the return value and the errors.
+    pub(crate) fn await_gmc_response<R>(
         &self,
-        timeout: Delta,
-        handler: impl FnOnce(u32, &[u8], &[u8]) -> Result<Option<R>>,
-    ) -> Result<Option<R>> {
-        self.inner.lock().receive_gmc_and_dispatch(timeout, handler)
+        command_id: u32,
+        on_other: impl FnMut(&GspGmcMsgElement, &[u8], &[u8]) -> Result,
+        decode: impl FnMut(&[u8], &[u8]) -> Result<R>,
+    ) -> Result<R> {
+        self.inner
+            .lock()
+            .await_gmc_response(command_id, on_other, decode)
+    }
+
+    /// Sends a GMC API request to the GSP without waiting for the response.
+    ///
+    /// # Errors
+    ///
+    /// Errors from [`DmaGspMem::allocate_command`] are propagated as-is.
+    pub(crate) fn send_gmc_no_wait(
+        &self,
+        command_id: u32,
+        payload: &[u8],
+        max_response_size: u32,
+    ) -> Result {
+        self.inner
+            .lock()
+            .send_gmc(command_id, payload, max_response_size)
     }
 
     /// Waits for an unsolicited GSP event of type `M`. Events that arrive before it are logged and
@@ -812,7 +831,6 @@ fn poison(&self, reason: fmt::Arguments<'_>) -> Error {
     /// # Errors
     ///
     /// Errors from [`DmaGspMem::allocate_command`] are propagated as-is.
-    #[expect(dead_code)]
     fn send_gmc(&mut self, command_id: u32, payload: &[u8], max_response_size: u32) -> Result {
         let seq = self.seq;
         self.seq = self.seq.wrapping_add(1);
@@ -1204,8 +1222,9 @@ fn consume_element<R>(
 
     /// Receives the next queue element and, if it is a GMC element, passes it to `handler`.
     ///
-    /// `handler` receives the command id and the payload that follows the GMC API header, as two
-    /// slices because the ring may wrap, and returns `None` for an element that it declines.
+    /// `handler` receives the headers that open the element and the payload that follows the GMC
+    /// API header, as two slices because the ring may wrap, and returns `None` for an element that
+    /// it declines.
     ///
     /// Returns `Ok(None)` when `handler` declines the element or when the element is not a GMC
     /// element.
@@ -1220,7 +1239,7 @@ fn consume_element<R>(
     fn receive_gmc_and_dispatch<R>(
         &mut self,
         timeout: Delta,
-        handler: impl FnOnce(u32, &[u8], &[u8]) -> Result<Option<R>>,
+        handler: impl FnOnce(&GspGmcMsgElement, &[u8], &[u8]) -> Result<Option<R>>,
     ) -> Result<Option<R>> {
         self.consume_element(timeout, |this, element| match element {
             QueueElement::Other(_) => {
@@ -1230,18 +1249,73 @@ fn receive_gmc_and_dispatch<R>(
             }
             QueueElement::Gmc(message) => {
                 let header = message.header;
-                let command_id = header.gmc.command_id();
 
                 dev_dbg!(
                     &this.dev,
                     "GSP GMC: event: seq# {}, command_id=0x{:x}, length=0x{:x}\n",
                     header.gmc.sequence,
-                    command_id,
+                    header.gmc.command_id(),
                     header.length(),
                 );
 
-                handler(command_id, message.contents.0, message.contents.1)
+                handler(header, message.contents.0, message.contents.1)
             }
         })
     }
+
+    /// Waits for the response to the GMC request with command id `command_id`, up to
+    /// [`Cmdq::RECEIVE_TIMEOUT`] from the call.
+    ///
+    /// The response's payload is passed to `decode`, as two slices because the ring may wrap.
+    /// Every other GMC element that arrives first is passed to `on_other` with the headers that
+    /// open it and its payload slices, and any other element is logged. Neither kind of element
+    /// extends the deadline.
+    ///
+    /// # Errors
+    ///
+    /// - `ETIMEDOUT` if the response does not arrive before the deadline, however many other
+    ///   elements arrive while waiting.
+    /// - `EIO` if the queue is poisoned or an element fails framing validation (see
+    ///   [`Self::wait_for_element`]), or if the response carries a failure status.
+    ///
+    /// Errors from `on_other` and `decode` are propagated as-is.
+    fn await_gmc_response<R>(
+        &mut self,
+        command_id: u32,
+        mut on_other: impl FnMut(&GspGmcMsgElement, &[u8], &[u8]) -> Result,
+        mut decode: impl FnMut(&[u8], &[u8]) -> Result<R>,
+    ) -> Result<R> {
+        let dev = self.dev;
+        let deadline = Instant::<Monotonic>::now() + Cmdq::RECEIVE_TIMEOUT;
+        loop {
+            let remaining = deadline - Instant::<Monotonic>::now();
+            if remaining.is_negative() {
+                break Err(ETIMEDOUT);
+            }
+
+            let response =
+                self.receive_gmc_and_dispatch(remaining, |header, payload_0, payload_1| {
+                    if header.gmc.command_id() != command_id {
+                        return on_other(header, payload_0, payload_1).map(|()| None);
+                    }
+
+                    let status = header.gmc.status();
+                    if status != 0 {
+                        dev_err!(
+                            dev,
+                            "GSP GMC: command 0x{:x} failed, status={:#x}\n",
+                            command_id,
+                            status
+                        );
+                        return Err(EIO);
+                    }
+
+                    decode(payload_0, payload_1).map(Some)
+                })?;
+
+            if let Some(response) = response {
+                break Ok(response);
+            }
+        }
+    }
 }
drivers/gpu/nova-core/gsp/commands.rs +96 -3

115 lines not on this page · raw message

drivers/gpu/nova-core/gsp/fw.rs +5 -2
index e86283f67358..cc0bc8f8ae87 100644
@@ -1048,13 +1048,17 @@ pub(crate) struct GmcApiHeader {
     /// Sequence number that GSP-RM copies from a request into its response.
     pub(crate) sequence: u64,
     /// In a request, the largest response that the sender accepts. In a response, the `NV_STATUS`.
-    pub(crate) max_resp_or_status: u32,
+    max_resp_or_status: u32,
     reserved: [u32; 5],
 }
 
 /// Bits of [`GmcApiHeader::command`] that hold the command id. The high byte holds flags.
 const GMCAPI_COMMAND_ID_MASK: u32 = 0x00ff_ffff;
 
+/// GMC request that carries the system information and registry keys to GSP-RM. GSP-RM answers
+/// it with the static GPU configuration once it has finished starting.
+pub(crate) const GMCAPI_CMD_GSP_INIT: u32 = r000_00::GMCAPI_COMMANDS_GMCAPI_CMD_GSP_INIT;
+
 /// GMC event that requests the driver to run the generic falcon bootloader on the descriptor that
 /// the event carries.
 pub(crate) const GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER: u32 =
@@ -1097,7 +1101,6 @@ pub(crate) fn command_id(&self) -> u32 {
     ///
     /// The value is meaningful only on a response, which GSP-RM marks with a flag in the command
     /// word. In a request, the same word holds the largest response that the sender accepts.
-    #[expect(dead_code)]
     pub(crate) fn status(&self) -> u32 {
         self.max_resp_or_status
     }
drivers/gpu/nova-core/gsp/fw/commands.rs +49 -6

74 lines not on this page · raw message

Signature · 1 line
2.55.0
#57 lore raw

PATCH v3 23/33 gpu: nova-core: add LIBOS3 log buffers and state monitor buffer

In reply to John Hubbard

GSP-RM runs on LIBOS, and each LIBOS task logs into a buffer that the driver provides and names in the init argument array. The r000 firmware runs LIBOS3, which has six logging tasks, and LIBOS3 also expects one more page, the state monitor buffer, in which GSP-RM reports its own state.

Nova-core allocated log buffers for three of the six tasks, and no state monitor buffer.

Allocate the three missing log buffers and the state monitor buffer, name every log buffer in the init argument array, and give each new log a debugfs file next to the existing ones. The switch to r000 passes the state monitor buffer to GSP-RM.

---
 drivers/gpu/nova-core/gsp.rs | 129 ++++++++++++++++++++++++++---------
 1 file changed, 98 insertions(+), 31 deletions(-)
drivers/gpu/nova-core/gsp.rs +98 -31
index 90b4c3380f11..a8aec431b0b1 100644
@@ -80,7 +80,6 @@ pub(crate) fn dev(&self) -> &'gpu device::Device<device::Bound> {
 
 /// Number of GSP pages to use in a RM log buffer.
 const RM_LOG_BUFFER_NUM_PAGES: usize = 0x10;
-const LOG_BUFFER_SIZE: usize = RM_LOG_BUFFER_NUM_PAGES * GSP_PAGE_SIZE;
 
 /// Array of page table entries, as understood by the GSP bootloader.
 #[repr(C)]
@@ -116,9 +115,19 @@ fn init(view: CoherentView<'_, Self>, start: DmaAddress) -> Result<()> {
 /// then pp points to index into the buffer where the next logging entry will
 /// be written. Therefore, the logging data is valid if:
 ///   1 <= pp < sizeof(buffer)/sizeof(u64)
-struct LogBuffer<'a>(Coherent<'a, [u8; LOG_BUFFER_SIZE]>);
+struct LogBuffer<'a, const NUM_PAGES: usize>(Coherent<'a, [[u8; GSP_PAGE_SIZE]; NUM_PAGES]>);
 
-impl<'a> LogBuffer<'a> {
+/// A log buffer at the default size, [`RM_LOG_BUFFER_NUM_PAGES`] pages.
+///
+/// Matches the registry defaults for the init, interrupt, RM and MNOC tasks
+/// (`NV_REG_STR_RM_GSP_LOG_BUFFER_SIZE_TASK_*_DEFAULT`).
+type TaskLogBuffer<'a> = LogBuffer<'a, RM_LOG_BUFFER_NUM_PAGES>;
+
+/// A single-page log buffer, the size of the logs of the root task and of the RM state monitor
+/// task.
+type SmallLogBuffer<'a> = LogBuffer<'a, 1>;
+
+impl<'a, const NUM_PAGES: usize> LogBuffer<'a, NUM_PAGES> {
     /// Creates a new `LogBuffer` mapped on `dev`.
     fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
         let obj = Self(Coherent::zeroed(dev, GFP_KERNEL)?);
@@ -127,22 +136,90 @@ fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
 
         let pte_view = io_project!(
             obj.0,
-            [build: size_of::<u64>()..][build: ..RM_LOG_BUFFER_NUM_PAGES * size_of::<u64>()]
+            [build: 0][build: size_of::<u64>()..][build: ..NUM_PAGES * size_of::<u64>()]
         )
-        .try_cast::<PteArray<RM_LOG_BUFFER_NUM_PAGES>>()?;
+        .try_cast::<PteArray<NUM_PAGES>>()?;
         PteArray::init(pte_view, start_addr)?;
 
         Ok(obj)
     }
 }
 
+/// The log buffers to which GSP-RM writes its debug output, one per LIBOS3 task.
 struct LogBuffers<'a> {
-    /// Init log buffer.
-    loginit: LogBuffer<'a>,
-    /// Interrupts log buffer.
-    logintr: LogBuffer<'a>,
-    /// RM log buffer.
-    logrm: LogBuffer<'a>,
+    /// Init task.
+    loginit: TaskLogBuffer<'a>,
+    /// Interrupt task.
+    logintr: TaskLogBuffer<'a>,
+    /// RM task.
+    logrm: TaskLogBuffer<'a>,
+    /// MNOC task.
+    logmnoc: TaskLogBuffer<'a>,
+    /// Root task.
+    logroot: SmallLogBuffer<'a>,
+    /// RM state monitor task.
+    logrmon: SmallLogBuffer<'a>,
+}
+
+impl<'a> LogBuffers<'a> {
+    /// Number of log buffers.
+    const COUNT: usize = 6;
+
+    /// Allocates the six log buffers, mapped on `dev`.
+    fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
+        Ok(Self {
+            loginit: TaskLogBuffer::new(dev)?,
+            logintr: TaskLogBuffer::new(dev)?,
+            logrm: TaskLogBuffer::new(dev)?,
+            logmnoc: TaskLogBuffer::new(dev)?,
+            logroot: SmallLogBuffer::new(dev)?,
+            logrmon: SmallLogBuffer::new(dev)?,
+        })
+    }
+
+    /// Fills the first [`Self::COUNT`] entries of `libos` with the log buffers, under the names
+    /// that GSP-RM looks them up by.
+    fn init_arguments(
+        &self,
+        libos: &mut CoherentBox<'_, [LibosMemoryRegionInitArgument]>,
+    ) -> Result {
+        libos.init_at(
+            0,
+            LibosMemoryRegionInitArgument::new("LOGINIT", &self.loginit.0),
+        )?;
+        libos.init_at(
+            1,
+            LibosMemoryRegionInitArgument::new("LOGINTR", &self.logintr.0),
+        )?;
+        libos.init_at(
+            2,
+            LibosMemoryRegionInitArgument::new("LOGRM", &self.logrm.0),
+        )?;
+        libos.init_at(
+            3,
+            LibosMemoryRegionInitArgument::new("LOGMNOC", &self.logmnoc.0),
+        )?;
+        libos.init_at(
+            4,
+            LibosMemoryRegionInitArgument::new("LOGROOT", &self.logroot.0),
+        )?;
+        libos.init_at(
+            5,
+            LibosMemoryRegionInitArgument::new("LOGRMON", &self.logrmon.0),
+        )?;
+
+        Ok(())
+    }
+
+    /// Exposes each log buffer as a binary file in `dir`, under the lowercase form of its name.
+    fn register_debugfs<'data>(&'data self, dir: &debugfs::ScopedDir<'data, '_>) {
+        dir.read_binary_file(c"loginit", &self.loginit.0);
+        dir.read_binary_file(c"logintr", &self.logintr.0);
+        dir.read_binary_file(c"logrm", &self.logrm.0);
+        dir.read_binary_file(c"logmnoc", &self.logmnoc.0);
+        dir.read_binary_file(c"logroot", &self.logroot.0);
+        dir.read_binary_file(c"logrmon", &self.logrmon.0);
+    }
 }
 
 /// GSP runtime data.
@@ -158,6 +235,8 @@ pub(crate) struct Gsp<'gsp> {
     pub(crate) cmdq: Cmdq<'gsp>,
     /// RM arguments.
     rmargs: Coherent<'gsp, GspArgumentsPadded>,
+    /// Buffer in which GSP-RM reports its own state.
+    rm_state_monitor: Coherent<'gsp, [u8; GSP_PAGE_SIZE]>,
 }
 
 impl<'gsp> Gsp<'gsp> {
@@ -168,17 +247,12 @@ pub(crate) fn new(
     ) -> impl PinInit<Self, Error> + 'gsp {
         pin_init::pin_init_scope(move || {
             let dev = pdev.as_ref();
+            let log_buffers = LogBuffers::new(dev)?;
 
-            let loginit = LogBuffer::new(dev)?;
-            let logintr = LogBuffer::new(dev)?;
-            let logrm = LogBuffer::new(dev)?;
-
-            // Initialise the logging structures. The OpenRM equivalents are in:
-            // _kgspInitLibosLoggingStructures (allocates memory for buffers)
-            // kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array)
             Ok(try_pin_init!(Self {
                 cmdq <- Cmdq::new(dev, bar),
                 rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
+                rm_state_monitor: Coherent::zeroed(dev, GFP_KERNEL)?,
                 libos: {
                     let mut libos = CoherentBox::zeroed_slice(
                         dev,
@@ -186,20 +260,15 @@ pub(crate) fn new(
                         GFP_KERNEL,
                     )?;
 
-                    libos.init_at(0, LibosMemoryRegionInitArgument::new("LOGINIT", &loginit.0))?;
-                    libos.init_at(1, LibosMemoryRegionInitArgument::new("LOGINTR", &logintr.0))?;
-                    libos.init_at(2, LibosMemoryRegionInitArgument::new("LOGRM", &logrm.0))?;
-                    libos.init_at(3, LibosMemoryRegionInitArgument::new("RMARGS", rmargs))?;
+                    log_buffers.init_arguments(&mut libos)?;
+                    libos.init_at(
+                        LogBuffers::COUNT,
+                        LibosMemoryRegionInitArgument::new("RMARGS", rmargs),
+                    )?;
 
                     libos.into()
                 },
                 logs <- {
-                    let log_buffers = LogBuffers {
-                        loginit,
-                        logintr,
-                        logrm,
-                    };
-
                     #[allow(static_mut_refs)]
                     // SAFETY: `DEBUGFS_ROOT` is created before driver registration and cleared
                     // after driver unregistration, so no probe() can race with its modification.
@@ -211,9 +280,7 @@ pub(crate) fn new(
                         .expect("DEBUGFS_ROOT not initialized");
 
                     log_parent.scope(log_buffers, dev.name(), |logs, dir| {
-                        dir.read_binary_file(c"loginit", &logs.loginit.0);
-                        dir.read_binary_file(c"logintr", &logs.logintr.0);
-                        dir.read_binary_file(c"logrm", &logs.logrm.0);
+                        logs.register_debugfs(dir)
                     })
                 },
             }))
Signature · 1 line
2.55.0
#58 lore raw

Re: [PATCH v3 23/33] gpu: nova-core: add LIBOS3 log buffers and state monitor buffer

Quoted 3 lines · John Hubbard

GSP-RM runs on LIBOS, and each LIBOS task logs into a buffer that the driver provides and names in the init argument array. The r000 firmware runs LIBOS3,

Even on Turing? I thought Turing/GA100 still use LIBOS2, which is why there are two GSP-RM firmware binaries.

#59 lore raw

Re: [PATCH v3 23/33] gpu: nova-core: add LIBOS3 log buffers and state monitor buffer

Quoted 7 lines · Timur Tabi
Quoted 3 lines · John Hubbard

GSP-RM runs on LIBOS, and each LIBOS task logs into a buffer that the driver provides and names in the init argument array. The r000 firmware runs LIBOS3,

Even on Turing? I thought Turing/GA100 still use LIBOS2, which is why there are two GSP-RM firmware binaries.

Oh yes, that's correct, Turing and GA100 run LIBOS2.

v4 corrects the commit message and the doc comment on the log buffers:
the r000 firmware runs LIBOS3 on GA102 and later, and LIBOS2 on Turing and GA100, and LIBOS2 maps only the init and RM log buffers and skips the names that it does not have.

thanks,

Signature · 1 line
John Hubbard
#60 lore raw

PATCH v3 24/33 gpu: nova-core: add the ucodes firmware loader

In reply to John Hubbard

The r000 GSP firmware includes a ucodes image, microcode that GSP-RM loads at run time from a buffer that the driver maps for it. The image is described by a TLV whose FILE tag names a separate file and whose SIZE tag gives that file's length, which is the convention that the GSP firmware image already uses.

The GSP firmware wrapper open-coded the reading of the FILE and SIZE tags, so the ucodes loader could not share it.

Move the reading of the two tags into the TLV parser, and add the ucodes loader on top of the parser. The loader maps the image through a radix3 page table, as the GSP firmware image is mapped, and the image is required on every chipset that nova-core supports. The loader has no caller until the switch to r000.

---
 drivers/gpu/nova-core/firmware.rs         |  7 ++-
 drivers/gpu/nova-core/firmware/bindata.rs | 59 +++++++++++++++++++++++
 drivers/gpu/nova-core/firmware/gsp.rs     | 15 ++----
 drivers/gpu/nova-core/firmware/tlv.rs     | 40 +++++++++++++--
 4 files changed, 105 insertions(+), 16 deletions(-)
 create mode 100644 drivers/gpu/nova-core/firmware/bindata.rs
drivers/gpu/nova-core/firmware.rs +6 -1
index 358c9b8db0b8..d7ba03184ad5 100644
@@ -22,6 +22,7 @@
     num::IntoSafeCast, //
 };
 
+pub(crate) mod bindata;
 pub(crate) mod booter;
 pub(crate) mod fwsec;
 pub(crate) mod gen_bootloader;
@@ -349,7 +350,11 @@ const fn make_entry_chipset(self, chipset: gpu::Chipset) -> Self {
         let mut this = self
             .make_entry_file(name, "gsp_bootloader.tlv")
             .make_entry_file(name, "gsp.tlv")
-            .make_entry_file(name, "gsp.bin");
+            .make_entry_file(name, "gsp.bin")
+            .make_entry_file(name, "ucodes.tlv")
+            // The metadata's FILE tag gives the image's real file name at run time. This static
+            // entry names the usual one.
+            .make_entry_file(name, "ucodes.bin");
 
         // Add the firmware files specific to the GSP boot method of `chipset`.
         let boot_files = boot_firmware_files(chipset);
drivers/gpu/nova-core/firmware/bindata.rs new file +59 -0

59 lines not on this page · raw message

drivers/gpu/nova-core/firmware/gsp.rs +3 -12
index 341a8b19aa38..a2db7b6ba131 100644
@@ -6,9 +6,7 @@
         Coherent,
         DmaAddress, //
     },
-    firmware,
-    prelude::*,
-    str::CString,
+    prelude::*, //
 };
 
 use crate::{
@@ -20,8 +18,7 @@
             Tlv,
         },
     },
-    gpu::Chipset,
-    num::FromSafeCast,
+    gpu::Chipset, //
 };
 
 /// The GSP firmware image, its signatures, and the GSP bootloader.
@@ -48,13 +45,7 @@ pub(crate) fn new(
             let tlv = Tlv::new(firmware.data())?;
             dev_dbg!(dev, "loaded gsp firmware v{}\n", tlv.get_string(b"VERS")?);
 
-            let size = usize::from_safe_cast(tlv.get_u32(b"SIZE")?);
-            let mut fw_vvec = VVec::zeroed(size, GFP_KERNEL).map_err(|_| ENOMEM)?;
-
-            let chip_name = chipset.name();
-            let file = tlv.get_string(b"FILE")?;
-            let filename = CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{file}"))?;
-            firmware::request_into_buf(&filename, dev, fw_vvec.as_mut_slice())?;
+            let fw_vvec = tlv.load_file(dev, chipset)?;
 
             let signatures = Coherent::from_slice(dev, tlv.get_bytes(b"SIGN")?, GFP_KERNEL)?;
 
drivers/gpu/nova-core/firmware/tlv.rs +37 -3
index 7b879f13a61e..7f278903dc8b 100644
@@ -4,6 +4,7 @@
 use kernel::{
     device,
     firmware,
+    fmt,
     prelude::*,
     str::CString, //
 };
@@ -13,15 +14,18 @@
     num::*, //
 };
 
+/// Returns the path of `file` in `chipset`'s GSP firmware directory.
+fn gsp_firmware_path(chipset: gpu::Chipset, file: fmt::Arguments<'_>) -> Result<CString> {
+    CString::try_from_fmt(fmt!("nvidia/{}/gsp/{}", chipset.name(), file))
+}
+
 /// Requests the GPU firmware TLV `name` suitable for `chipset`.
 pub(crate) fn request_tlv(
     dev: &device::Device,
     chipset: gpu::Chipset,
     name: &str,
 ) -> Result<firmware::Firmware> {
-    let chip_name = chipset.name();
-
-    let filename = CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{name}.tlv"))?;
+    let filename = gsp_firmware_path(chipset, fmt!("{name}.tlv"))?;
 
     dev_dbg!(dev, "loading firmware image {:?}\n", &filename);
 
@@ -198,6 +202,36 @@ fn iter(&self) -> TlvIter<'_, 'a> {
         self.iter().find(|b| b.tag == *tag).ok_or(EINVAL)
     }
 
+    /// Loads the file that the `FILE` tag names from `chipset`'s GSP firmware directory.
+    ///
+    /// The `SIZE` tag gives the file's length, and the returned buffer is that long.
+    ///
+    /// # Errors
+    ///
+    /// - `EINVAL` if `FILE` or `SIZE` is absent, or `FILE` does not hold a valid string.
+    /// - `ENODATA` if `SIZE` is zero.
+    /// - `ENOMEM` if the buffer cannot be allocated.
+    ///
+    /// Errors from the firmware request, `ENOENT` in particular, are propagated as-is.
+    pub(crate) fn load_file(
+        &self,
+        dev: &device::Device,
+        chipset: gpu::Chipset,
+    ) -> Result<VVec<u8>> {
+        let file = self.get_string(b"FILE")?;
+        let path = gsp_firmware_path(chipset, fmt!("{file}"))?;
+
+        let size = usize::from_safe_cast(self.get_u32(b"SIZE")?);
+        if size == 0 {
+            return Err(ENODATA);
+        }
+
+        let mut data = VVec::zeroed(size, GFP_KERNEL).map_err(|_| ENOMEM)?;
+        firmware::request_into_buf(&path, dev, data.as_mut_slice())?;
+
+        Ok(data)
+    }
+
     /// Return a slice of bytes.
     ///
     /// Returns `EINVAL` if the value is empty.
Signature · 1 line
2.55.0
#61 lore raw

PATCH v3 25/33 gpu: nova-core: gsp: let the GSP HAL load the generic bootloader

In reply to John Hubbard

Turing and GA100 boot the GSP through the generic falcon bootloader. On those chipsets the r000 GSP-RM raises a load-and-execute event that requests a bootloader run, and the handler for that event runs the bootloader that the boot sequence supplies. Whether a chipset boots through the bootloader is a property of the TU102 HAL: a field of its two instances, set for Turing and GA100 and clear for the other Ampere chipsets and for Ada.

Only the TU102 HAL tested that field, to choose how to load FWSEC. The boot sequence had no way to obtain the bootloader for the handler without a second list of the chipsets.

Add a HAL method that loads the generic bootloader. The TU102 HAL loads it when its field is set, and every other HAL returns no bootloader. The method has no caller until the switch to r000.

Assisted-by LLM
---
 drivers/gpu/nova-core/gsp/hal.rs       | 28 ++++++++++++++++++++++++--
 drivers/gpu/nova-core/gsp/hal/tu102.rs | 14 +++++++++++++
 2 files changed, 40 insertions(+), 2 deletions(-)
drivers/gpu/nova-core/gsp/hal.rs +26 -2
index d8329f6fcc65..8c2a8abcb187 100644
@@ -5,10 +5,16 @@
 mod gh100;
 mod tu102;
 
-use kernel::prelude::*;
+use kernel::{
+    device,
+    prelude::*, //
+};
 
 use crate::{
-    firmware::gsp::GspFirmware,
+    firmware::{
+        gen_bootloader::GenericBootloader,
+        gsp::GspFirmware, //
+    },
     gpu::{
         Architecture,
         Chipset, //
@@ -42,6 +48,24 @@ fn boot<'gpu>(
         gsp_fw: &GspFirmware<'gpu>,
     ) -> Result<Option<super::UnloadBundle<'gpu>>>;
 
+    /// Loads the generic falcon bootloader for the chipsets whose GSP boots through it.
+    ///
+    /// The bootloader runs from the last blocks of an IMEM of `imem_size` bytes. On every other
+    /// chipset this returns `None`.
+    ///
+    /// # Errors
+    ///
+    /// Errors from loading the bootloader image are propagated as-is.
+    #[expect(dead_code)]
+    fn generic_bootloader(
+        &self,
+        _dev: &device::Device<device::Bound>,
+        _chipset: Chipset,
+        _imem_size: usize,
+    ) -> Result<Option<GenericBootloader>> {
+        Ok(None)
+    }
+
     /// Performs HAL-specific post-GSP boot tasks.
     ///
     /// This method is called by the GSP boot code after the GSP is confirmed to be running, and
drivers/gpu/nova-core/gsp/hal/tu102.rs +14 -0
index 1b17ece53bd6..32931fd0b7cf 100644
@@ -31,6 +31,7 @@
             FwsecCommand,
             FwsecFirmware, //
         },
+        gen_bootloader::GenericBootloader,
         gsp::GspFirmware, //
     },
     gpu::Chipset,
@@ -316,6 +317,19 @@ fn boot<'gpu>(
         Ok(unload_guard.dismiss())
     }
 
+    fn generic_bootloader(
+        &self,
+        dev: &device::Device<device::Bound>,
+        chipset: Chipset,
+        imem_size: usize,
+    ) -> Result<Option<GenericBootloader>> {
+        if !self.needs_fwsec_bootloader {
+            return Ok(None);
+        }
+
+        GenericBootloader::new(dev, chipset, imem_size).map(Some)
+    }
+
     fn post_boot(
         &self,
         gsp: &Gsp<'_>,
Signature · 1 line
2.55.0
#62 lore raw

PATCH v3 26/33 gpu: nova-core: gsp: add the GSP_SUSPEND request

In reply to John Hubbard

The r000 firmware suspends GSP-RM on a GSP_SUSPEND request, a GMC API command whose payload is one word of flags. The one flag marks a suspend that is a power management transition, S3 or hibernate, rather than a full unload. GSP-RM sends no response on the message queue. It reports the completed suspend in the GSP falcon's MAILBOX0 register instead.

Add the request, and send it without waiting for a response. The request has no caller until the following switch to r000 sends it in place of the r570 unload RPC.

Assisted-by LLM
---
 drivers/gpu/nova-core/gsp/commands.rs    | 15 ++++++++++++-
 drivers/gpu/nova-core/gsp/fw.rs          |  4 ++++
 drivers/gpu/nova-core/gsp/fw/commands.rs | 27 ++++++++++++++++++++++++
 3 files changed, 45 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/gsp/commands.rs +14 -1
index 74ae92428cad..00ff3271a46e 100644
@@ -37,7 +37,8 @@
             },
             GspGmcMsgElement,
             MsgFunction,
-            GMCAPI_CMD_GSP_INIT, //
+            GMCAPI_CMD_GSP_INIT,
+            GMCAPI_CMD_GSP_SUSPEND, //
         },
         nvkv::{
             Decoder,
@@ -382,6 +383,18 @@ fn decode_gsp_init_reply(payload_0: &[u8], payload_1: &[u8]) -> Result<GspStatic
 
 pub(crate) use fw::commands::PowerStateLevel;
 
+/// Sends `GSP_SUSPEND`, which GSP-RM does not answer (see [`GMCAPI_CMD_GSP_SUSPEND`]).
+///
+/// # Errors
+///
+/// Errors from [`Cmdq::send_gmc_no_wait`] are propagated as-is.
+#[expect(dead_code)]
+pub(crate) fn gsp_suspend(cmdq: &Cmdq<'_>, level: PowerStateLevel) -> Result {
+    let params = fw::commands::GspSuspend::new(level);
+
+    cmdq.send_gmc_no_wait(GMCAPI_CMD_GSP_SUSPEND, AsBytes::as_bytes(&params), 0)
+}
+
 /// The `UnloadingGuestDriver` command, used to shut down the GSP.
 ///
 /// Only used within the `gsp` module.
drivers/gpu/nova-core/gsp/fw.rs +4 -0
index cc0bc8f8ae87..ee582cbde5f6 100644
@@ -1069,6 +1069,10 @@ pub(crate) struct GmcApiHeader {
 pub(crate) const GMCAPI_CMD_EXEC_HS_BINARY: u32 =
     r000_00::GMCAPI_COMMANDS_GMCAPI_CMD_EXEC_HS_BINARY;
 
+/// GMC request for GSP-RM to suspend. GSP-RM sends no response, and reports the completed
+/// suspend in the GSP falcon's `MAILBOX0` instead.
+pub(crate) const GMCAPI_CMD_GSP_SUSPEND: u32 = r000_00::GMCAPI_COMMANDS_GMCAPI_CMD_GSP_SUSPEND;
+
 static_assert!(size_of::<GmcApiHeader>() == size_of::<r000_00::GMCAPI_HEADER>());
 static_assert!(
     core::mem::offset_of!(GmcApiHeader, command)
drivers/gpu/nova-core/gsp/fw/commands.rs +27 -0
index 748639942fe1..4e6c712637b0 100644
@@ -225,6 +225,33 @@ pub(crate) fn is_power_transition(self) -> bool {
     }
 }
 
+/// Set in [`GspSuspend::flags`] when the suspend is a power management transition (S3 or
+/// hibernate) rather than a full unload.
+const GMCAPI_GSP_SUSPEND_FLAGS_PM_TRANSITION: u64 = 1 << 0;
+
+/// Payload of the `GSP_SUSPEND` GMC command.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Zeroable)]
+pub(crate) struct GspSuspend {
+    flags: u64,
+}
+
+impl GspSuspend {
+    /// Creates a `GSP_SUSPEND` payload for the given [`PowerStateLevel`].
+    pub(crate) fn new(level: PowerStateLevel) -> Self {
+        Self {
+            flags: if level.is_power_transition() {
+                GMCAPI_GSP_SUSPEND_FLAGS_PM_TRANSITION
+            } else {
+                0
+            },
+        }
+    }
+}
+
+// SAFETY: The single field is an integer type, and the struct has no padding.
+unsafe impl AsBytes for GspSuspend {}
+
 /// Payload of the `UnloadingGuestDriver` command and message.
 #[repr(transparent)]
 #[derive(Clone, Copy, Debug, Zeroable)]
Signature · 1 line
2.55.0
#63 lore raw

PATCH v3 27/33 gpu: nova-core: switch to the r000 GSP firmware

In reply to John Hubbard

The r000 firmware changes five things about how GSP-RM and the driver exchange messages:

* A queue element opens with the MCTP and NVDM transport headers and carries no checksum.

* Msgq v2 keeps the four queue pointers in BAR0 registers, and the write to the command queue head register is also the doorbell.

* The load-and-execute boot steps arrive as GMC events rather than as RPC events.

* One GSP_INIT request replaces the system-info, registry and static-info commands, and its reply replaces the init-done event.

* GSP-RM suspends on a GSP_SUSPEND command and never answers it, where r570 answered an UnloadingGuestDriver RPC.

It also requires two more buffers from the driver at boot, the ucodes image and a page in which GSP-RM reports its own state, and it reserves more framebuffer for itself: a larger region for the PMU, the GPU's power management unit, on GB100, and a larger heap outside the WPR, the write-protected region, on GB20x.

Only one firmware runs at a time, so a driver that had made some of these changes but not the others would not boot. Switch all of them together, and change the driver's bindings alias so that it names the r000 module.

Give the queue its own copies of the four pointers, as Open RM's msgq library does. A GSP reset zeroes the pointer registers, so the driver writes its two pointers out from its copies, and it keeps the last value that it read of each GSP pointer and uses that value until GSP-RM writes the register again. The pointers count elements without wrapping at the ring size. A ring is empty when its two pointers are equal and full when they differ by the ring size, so the ring no longer keeps one slot empty.

Load the ucodes image at boot and give GSP-RM its location in the boot arguments. GSP-RM reads the image only while it starts, so the image is freed when the boot sequence returns. The TU102 HAL loads the generic falcon bootloader for the load-and-execute handler on the chipsets that boot through it.

Suspend GSP-RM with the GSP_SUSPEND request in place of the unload RPC. GSP-RM posts messages while it suspends, and the shutdown path runs after the GSP event interrupt is freed, so drain the queue while polling for the suspend.

Three things then have no caller:

* The CPU sequencer, which ran the register scripts that r570's GSP-RM sent as RPC events.

* The wait for the init-done event.

* The four RPC commands that GSP_INIT and GSP_SUSPEND replace.

Remove all three. Mark the RPC send-and-wait paths dead rather than removing them: no caller waits for an RPC reply any more, but the RPC commands that the driver sends once GSP-RM is up, which later series add, use them unchanged.

Assisted-by LLM
---
 Documentation/gpu/nova/core/interrupts.rst |  11 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs      |  24 +-
 drivers/gpu/nova-core/fb/hal/gb202.rs      |   6 +-
 drivers/gpu/nova-core/firmware/bindata.rs  |   1 -
 drivers/gpu/nova-core/gsp.rs               |   9 +-
 drivers/gpu/nova-core/gsp/boot.rs          |  47 +-
 drivers/gpu/nova-core/gsp/cmdq.rs          | 247 ++++-----
 drivers/gpu/nova-core/gsp/commands.rs      | 253 +---------
 drivers/gpu/nova-core/gsp/fw.rs            | 559 ++++++---------------
 drivers/gpu/nova-core/gsp/fw/commands.rs   | 198 +-------
 drivers/gpu/nova-core/gsp/hal.rs           |  14 -
 drivers/gpu/nova-core/gsp/hal/tu102.rs     |  12 -
 drivers/gpu/nova-core/gsp/sequencer.rs     | 379 --------------
 drivers/gpu/nova-core/sbuffer.rs           |   1 +
 14 files changed, 324 insertions(+), 1437 deletions(-)
 delete mode 100644 drivers/gpu/nova-core/gsp/sequencer.rs
Documentation/gpu/nova/core/interrupts.rst +5 -6
index 280dcf97688a..fdcd789cf4f9 100644
@@ -450,7 +450,7 @@ thread to drain the queue::
 A halt and a posted message can be pending together, so the top half services
 every cause that the status reports.
 
-A drain fails when a message's framing or checksum is bad, which poisons the
+A drain fails when an element's framing is bad, and the bad framing poisons the
 queue (see "Draining the GSP-to-CPU queue"). Every later event would fail the
 same way, so the IRQ thread disables vector 155 and logs the failure, which
 leaves the queue unserviced until the device is reset.
@@ -582,11 +582,10 @@ The read pointer advances past every message, whether it matched, was an event,
 or matched but failed to decode, so a message is never left at the queue head
 for the next receive to parse again.
 
-Corrupt framing is the exception. A message's length is inside the region that
-the checksum covers, so once the framing or the checksum fails there is no
-trustworthy length with which to skip the message. Such a failure poisons the
-queue: nova-core logs it once, and every later receive fails with ``EIO`` until
-the device is reset.
+Corrupt framing is the exception. An element that fails framing validation has
+no trustworthy length, so the read pointer cannot advance past it. Such a
+failure poisons the queue: nova-core logs it once, and every later receive
+fails with ``EIO`` until the device is reset.
 
 The polling path and the IRQ thread both read the queue under the command-queue
 mutex. Replies and events share one queue and one read pointer, so one lock is
drivers/gpu/nova-core/fb/hal/gb100.rs +21 -3
index 9fa094939600..33a00fc12aaa 100644
@@ -79,10 +79,28 @@ fn write_sysmem_flush_page_gb100(hshub0: Mmio<'_, regs::Hshub0Registers>, addr:
     hshub0.write_reg(regs::NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_LO::zeroed().with_adr(addr_lo));
 }
 
-// This PMU reservation size is r570-specific.
+/// PMU backing store.
+const PMU_BACKING_STORE_SIZE: usize = 9 * SZ_1M;
+
+/// PMU surfaces, `kpmuReservedMemorySurfacesSizeGet` in Open RM.
+const PMU_SURFACES_SIZE: usize = SZ_16M + SZ_256K;
+
+/// Miscellaneous PMU memory.
+const PMU_MISC_SIZE: usize = SZ_4K;
+
+/// Alignment of the PMU reserved region, `KPMU_RESERVED_MEMORY_ALIGNMENT` in Open RM.
+const PMU_RESERVED_MEMORY_ALIGNMENT: Alignment = Alignment::new::<SZ_128K>();
+
+/// PMU region above FRTS: the backing store, the surfaces and the miscellaneous memory, aligned to
+/// [`PMU_RESERVED_MEMORY_ALIGNMENT`].
+const PMU_RESERVED_SIZE: usize = const_align_up(
+    PMU_BACKING_STORE_SIZE + PMU_SURFACES_SIZE + PMU_MISC_SIZE,
+    PMU_RESERVED_MEMORY_ALIGNMENT,
+)
+.unwrap();
+
 pub(super) const fn pmu_reserved_size_gb100() -> u32 {
-    usize_into_u32::<{ const_align_up(SZ_8M + SZ_16M + SZ_4K, Alignment::new::<SZ_128K>()).unwrap() }>(
-    )
+    usize_into_u32::<PMU_RESERVED_SIZE>()
 }
 
 impl FbHal for Gb100 {
drivers/gpu/nova-core/fb/hal/gb202.rs +3 -3
index 4341ecf36188..345179063b30 100644
@@ -72,9 +72,9 @@ fn pmu_reserved_size(&self) -> u32 {
     }
 
     fn non_wpr_heap_size(&self) -> u64 {
-        // Non-WPR heap for GB20x (see Open RM: kgspGetNonWprHeapSize, GB202+).
-        // This size is r570-specific.
-        u64::SZ_2M + u64::SZ_128K
+        // Non-WPR heap for GB20x (see Open RM: kgspGetNonWprHeapSize, GB202+). This size is
+        // r000-specific.
+        3 * u64::SZ_1M
     }
 
     fn frts_size(&self) -> u64 {
drivers/gpu/nova-core/firmware/bindata.rs +0 -1
index 410cb741273c..12a8e74cc11c 100644
@@ -26,7 +26,6 @@ pub(crate) struct UcodesImage<'a> {
     radix3: Pin<KBox<Radix3<'a>>>,
 }
 
-#[expect(dead_code)]
 impl<'a> UcodesImage<'a> {
     /// Loads the ucodes image that the `ucodes` metadata file names, and maps it for `dev`.
     ///
drivers/gpu/nova-core/gsp.rs +6 -3
index a8aec431b0b1..85967119cd7e 100644
@@ -26,7 +26,6 @@
 mod fw;
 mod nvkv;
 mod regs;
-mod sequencer;
 
 pub(crate) use fw::{
     GspFmcBootParams,
@@ -251,8 +250,12 @@ pub(crate) fn new(
 
             Ok(try_pin_init!(Self {
                 cmdq <- Cmdq::new(dev, bar),
-                rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
                 rm_state_monitor: Coherent::zeroed(dev, GFP_KERNEL)?,
+                rmargs: Coherent::init(
+                    dev,
+                    GFP_KERNEL,
+                    GspArgumentsPadded::new(&cmdq, rm_state_monitor),
+                )?,
                 libos: {
                     let mut libos = CoherentBox::zeroed_slice(
                         dev,
@@ -295,6 +298,6 @@ pub(crate) fn new(
 pub(crate) struct BootResult<'a> {
     /// The unload bundle for [`Gsp::unload`], if one could be built.
     pub(crate) unload_bundle: Option<UnloadBundle<'a>>,
-    /// The static GPU configuration, as GSP-RM reported it at the end of boot.
+    /// The static GPU configuration, as decoded from the `GSP_INIT` reply.
     pub(crate) static_info: commands::GspStaticInfo,
 }
drivers/gpu/nova-core/gsp/boot.rs +33 -14

92 lines not on this page · raw message

drivers/gpu/nova-core/gsp/cmdq.rs +110 -137

443 lines not on this page · raw message

drivers/gpu/nova-core/gsp/commands.rs +3 -250

308 lines not on this page · raw message

drivers/gpu/nova-core/gsp/fw.rs +140 -419

770 lines not on this page · raw message

drivers/gpu/nova-core/gsp/fw/commands.rs +2 -196

220 lines not on this page · raw message

drivers/gpu/nova-core/gsp/hal.rs +0 -14
index 8c2a8abcb187..b23beb6e2907 100644
@@ -56,7 +56,6 @@ fn boot<'gpu>(
     /// # Errors
     ///
     /// Errors from loading the bootloader image are propagated as-is.
-    #[expect(dead_code)]
     fn generic_bootloader(
         &self,
         _dev: &device::Device<device::Bound>,
@@ -65,19 +64,6 @@ fn generic_bootloader(
     ) -> Result<Option<GenericBootloader>> {
         Ok(None)
     }
-
-    /// Performs HAL-specific post-GSP boot tasks.
-    ///
-    /// 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: &mut GspBootContext<'_, '_>,
-        _gsp_fw: &GspFirmware<'_>,
-    ) -> Result {
-        Ok(())
-    }
 }
 
 /// Returns the names of the firmware files required to boot the GSP of `chipset`, in addition to
drivers/gpu/nova-core/gsp/hal/tu102.rs +0 -12
index 32931fd0b7cf..265039b8ff55 100644
@@ -41,7 +41,6 @@
             UnloadBundle, //
         },
         regs,
-        sequencer::GspSequencer,
         Gsp,
         GspBootContext,
         GspFwWprMeta, //
@@ -329,17 +328,6 @@ fn generic_bootloader(
 
         GenericBootloader::new(dev, chipset, imem_size).map(Some)
     }
-
-    fn post_boot(
-        &self,
-        gsp: &Gsp<'_>,
-        ctx: &mut GspBootContext<'_, '_>,
-        gsp_fw: &GspFirmware<'_>,
-    ) -> Result {
-        GspSequencer::run(&gsp.cmdq, ctx, &gsp.libos, gsp_fw.bootloader.app_version)?;
-
-        Ok(())
-    }
 }
 
 /// The TU102 HAL requires the use of the FWSEC bootloader.
drivers/gpu/nova-core/gsp/sequencer.rs deleted +0 -379

379 lines not on this page · raw message

drivers/gpu/nova-core/sbuffer.rs +1 -0
index b8c01104c255..f2cb9276b6e8 100644
@@ -164,6 +164,7 @@ pub(crate) fn read_exact(&mut self, mut dst: &mut [u8]) -> Result {
     /// Read all the remaining data into a [`KVec`].
     ///
     /// `self` will be empty after this operation.
+    #[expect(unused)]
     pub(crate) fn flush_into_kvec(&mut self, flags: kernel::alloc::Flags) -> Result<KVec<u8>> {
         let mut buf = KVec::<u8>::new();
 
Signature · 1 line
2.55.0
#64 lore raw

Re: [PATCH v3 27/33] gpu: nova-core: switch to the r000 GSP firmware

drivers/gpu/nova-core/fb/hal/gb100.rs fn write_sysmem_flush_page_gb100(hshub0: Mmio<'_, regs::Hshub0Registers>, addr: · line 83

Quoted 10 lines · John Hubbard
drivers/gpu/nova-core/fb/hal/gb100.rs +0 -0
@@ -79,10 +79,28 @@ fn write_sysmem_flush_page_gb100(hshub0: Mmio<'_, regs::Hshub0Registers>, addr:
      hshub0.write_reg(regs::NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_LO::zeroed().with_adr(addr_lo));
  }

drivers/gpu/nova-core/fb/hal/gb100.rs +2 -1
-// This PMU reservation size is r570-specific.
+/// PMU backing store.
+const PMU_BACKING_STORE_SIZE: usize = 9 * SZ_1M;

I don't see this comment or value removed/changed in this patchset, so is it really 570- specific?

#65 lore raw

Re: [PATCH v3 27/33] gpu: nova-core: switch to the r000 GSP firmware

Quoted 14 lines · Timur Tabi

drivers/gpu/nova-core/fb/hal/gb100.rs fn write_sysmem_flush_page_gb100(hshub0: Mmio<'_, regs::Hshub0Registers>, addr: · line 83

Quoted 10 lines · John Hubbard
drivers/gpu/nova-core/fb/hal/gb100.rs +0 -0
@@ -79,10 +79,28 @@ fn write_sysmem_flush_page_gb100(hshub0: Mmio<'_, regs::Hshub0Registers>, addr:
      hshub0.write_reg(regs::NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_LO::zeroed().with_adr(addr_lo));
  }

drivers/gpu/nova-core/fb/hal/gb100.rs +2 -1
-// This PMU reservation size is r570-specific.
+/// PMU backing store.
+const PMU_BACKING_STORE_SIZE: usize = 9 * SZ_1M;

I don't see this comment or value removed/changed in this patchset, so is it really 570- specific?

Yes, it was r570-specific, and this patch is where it changes: the hunk removes the comment and replaces the value.

In 570.144 the PMU region is:

* 8 MiB of backing store
* 16 MiB of surfaces
* 4 KiB of miscellaneous memory
* all aligned to 128 KiB.

In 615.71.09 the backing store is 9 MiB and the surfaces are 16 MiB + 256 KiB.

(v4 adds the before and after sizes to the commit message.)

thanks,

Signature · 1 line
John Hubbard
#66 lore raw

Re: [PATCH v3 27/33] gpu: nova-core: switch to the r000 GSP firmware

Quoted 19 lines · John Hubbard
Quoted 14 lines · Timur Tabi

drivers/gpu/nova-core/fb/hal/gb100.rs fn write_sysmem_flush_page_gb100(hshub0: Mmio<'_, regs::Hshub0Registers>, addr: · line 83

Quoted 10 lines · John Hubbard
drivers/gpu/nova-core/fb/hal/gb100.rs +0 -0
@@ -79,10 +79,28 @@ fn write_sysmem_flush_page_gb100(hshub0: Mmio<'_, regs::Hshub0Registers>, addr:
      hshub0.write_reg(regs::NV_PFB_HSHUB_EG_PCIE_FLUSH_SYSMEM_ADDR_LO::zeroed().with_adr(addr_lo));
  }

drivers/gpu/nova-core/fb/hal/gb100.rs +2 -1
-// This PMU reservation size is r570-specific.
+/// PMU backing store.
+const PMU_BACKING_STORE_SIZE: usize = 9 * SZ_1M;

I don't see this comment or value removed/changed in this patchset, so is it really 570- specific?

Yes, it was r570-specific, and this patch is where it changes: the hunk removes the comment and replaces the value.

Quoted 8 lines

In 570.144 the PMU region is:

* 8 MiB of backing store
* 16 MiB of surfaces
* 4 KiB of miscellaneous memory
* all aligned to 128 KiB.

In 615.71.09 the backing store is 9 MiB and the surfaces are 16 MiB + 256 KiB.

On 615, the backing store is 0x950000, not 9 MiB:

NvU32
kpmuReservedMemoryBackingStoreSizeGet_IMPL
(
KernelPmu *pKernelPmu
)

{
    if (kpmuGetIsSelfInit(pKernelPmu))
    {
        //
        // MMINTS-TODO: cross-reference with this when reserving memory
        // in pmu_20.c
        //
        return 0x950000;
    }

    if (kpmuGetIsSelfInit(pKernelPmu))
    {
        //
        // MMINTS-TODO: cross-reference with this when reserving memory
        // in pmu_20.c
        //
        return 0x900000;
    }

    return 0U;
}

kpmuGetIsSelfInit() returns True on GB100 and later, and False otherwise. The second if- statement is never entered, because this is just some #ifdef weirdness when OpenRM was generated.

#67 lore raw

PATCH v3 28/33 gpu: nova-core: gsp: make the GSP_INIT reply the static configuration

In reply to John Hubbard

The boot sequence returns the static GPU configuration, the GPU's name, its usable framebuffer regions and its BAR1 page directory base, to the rest of the driver. On r000 that configuration is the decoded GSP_INIT reply.

The configuration type came from the r570 boot protocol, where the reader of the r570 static-info reply filled it from a C struct. The GSP_INIT decoder filled the same type by copying the name and the usable regions out of the decoded reply. The decoder failed the boot with EINVAL when the reply reported no framebuffer region. With the r570 reader gone, that copy was the type's only purpose.

Make the decoded reply the static configuration type, and read the configuration through its accessors. The accessor for the usable regions yields an iterator, so the regions are no longer copied into a vector. A reply that reports no framebuffer region now fails with ENODEV when the driver creates its memory manager.

Assisted-by LLM
---
 drivers/gpu/nova-core/gpu.rs             | 16 +++---
 drivers/gpu/nova-core/gsp/commands.rs    | 70 ++----------------------
 drivers/gpu/nova-core/gsp/fw/commands.rs | 41 +++++++++++---
 drivers/gpu/nova-core/mm.rs              |  4 +-
 4 files changed, 48 insertions(+), 83 deletions(-)
drivers/gpu/nova-core/gpu.rs +8 -8
index 0ed0f4722dc5..fd1a74913d7c 100644
@@ -465,16 +465,16 @@ pub(crate) fn new<'a>(
                     Err(e) => dev_warn!(dev, "GPU name unavailable: {:?}\n", e),
                 }
 
-                if !info.usable_fb_regions.is_empty() {
+                if info.usable_fb_regions().next().is_some() {
                     dev_dbg!(dev, "Usable FB regions:\n");
-                    for region in &info.usable_fb_regions {
+                    for region in info.usable_fb_regions() {
                         dev_dbg!(dev, "  - {:#x?}\n", region);
                     }
 
                     dev_dbg!(
                         dev,
                         "Total usable VRAM: {} MiB\n",
-                        info.usable_fb_regions.iter().fold(0u64, |res, region| res
+                        info.usable_fb_regions().fold(0u64, |res, region| res
                             .saturating_add(region.end - region.start))
                             / u64::SZ_1M
                     );
@@ -484,7 +484,7 @@ pub(crate) fn new<'a>(
             // Create GPU memory manager owning memory management resources.
             mm: {
                 let info = gsp_resources.static_info();
-                let usable_vram = info.usable_fb_regions.first().ok_or(ENODEV)?;
+                let usable_vram = info.usable_fb_regions().next().ok_or(ENODEV)?;
                 let buddy_params = GpuBuddyParams {
                     base_offset: usable_vram.start,
                     size: usable_vram.end - usable_vram.start,
@@ -495,13 +495,13 @@ pub(crate) fn new<'a>(
                     bar,
                     gsp_resources.spec.chipset,
                     buddy_params,
-                    VramAddress::from_raw(info.total_fb_end),
+                    VramAddress::from_raw(info.total_fb_end().ok_or(ENODEV)?),
                 )?
             },
 
             // Create BAR1 user interface for CPU access to GPU virtual memory.
             bar_user: {
-                let pdb_addr = VramAddress::from_raw(gsp_resources.static_info().bar1_pde_base);
+                let pdb_addr = VramAddress::from_raw(gsp_resources.static_info().bar1_pde_base());
                 let bar1_idx = crate::driver::bar1_resource_index(pdev)?;
                 let bar1_size = pdev.resource_len(bar1_idx)?;
                 Arc::pin_init(
@@ -527,9 +527,9 @@ pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device<device::Bou
         if let Err(err) = crate::mm::selftest::run(
             dev,
             this.mm,
-            &info.usable_fb_regions,
+            info.usable_fb_regions(),
             this.bar_user,
-            info.bar1_pde_base,
+            info.bar1_pde_base(),
             this.spec.chipset,
         ) {
             dev_err!(dev, "self-tests failed: {:?}\n", err);
drivers/gpu/nova-core/gsp/commands.rs +6 -64

104 lines not on this page · raw message

drivers/gpu/nova-core/gsp/fw/commands.rs +32 -9

72 lines not on this page · raw message

drivers/gpu/nova-core/mm.rs +2 -2
index a5bc4042577b..ea85c821f0e2 100644
@@ -308,7 +308,7 @@ pub(crate) mod selftest {
     pub(crate) fn run(
         dev: &device::Device<device::Bound>,
         mm: &mut GpuMm<'_>,
-        usable_fb_regions: &[Range<u64>],
+        mut usable_fb_regions: impl Iterator<Item = Range<u64>>,
         bar_user: &Arc<bar_user::BarUser<'_>>,
         bar1_pdb: u64,
         chipset: Chipset,
@@ -316,7 +316,7 @@ pub(crate) fn run(
         // VRAM span the self-tests are free to overwrite, from the chosen test base.
         const SELFTEST_SPAN: u64 = u64::SZ_64M;
 
-        let base = usable_fb_regions.iter().find_map(|region| {
+        let base = usable_fb_regions.find_map(|region| {
             // Tests rely on this being 8 byte aligned for checking misalignment handling.
             let base = region.start.align_up(Alignment::new::<8>())?;
             (base.checked_add(SELFTEST_SPAN)? <= region.end).then_some(base)
Signature · 1 line
2.55.0
#68 lore raw

PATCH v3 29/33 gpu: nova-core: firmware: delete the r570 bindings

In reply to John Hubbard

The switch to the r000 firmware left the r570 bindings with no reference anywhere in the driver, but the r570 bindings module stayed declared and its generated definitions were still compiled.

Delete the r570 bindings module, along with the last comment that named r570.

---
 drivers/gpu/nova-core/fsp.rs                  |    3 +-
 drivers/gpu/nova-core/gsp/fw.rs               |    1 -
 drivers/gpu/nova-core/gsp/fw/r570_144.rs      |   31 -
 .../gpu/nova-core/gsp/fw/r570_144/bindings.rs | 1060 -----------------
 4 files changed, 2 insertions(+), 1093 deletions(-)
 delete mode 100644 drivers/gpu/nova-core/gsp/fw/r570_144.rs
 delete mode 100644 drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
drivers/gpu/nova-core/fsp.rs +2 -1
index b738dcabcdef..02521db56e03 100644
@@ -259,7 +259,8 @@ fn frts_vidmem_offset(hal: &dyn hal::FspHal, fb_info: &FbSizes) -> Result<u64> {
         // As per OpenRM's `kfspPrepareBootCommands_GH100`.
         if fb_info.pmu_reserved_size != 0 {
             offset = (offset + u64::from(fb_info.pmu_reserved_size))
-                // The 2 MiB alignment is r570-specific.
+                // This must be aligned to WPR alignment, which is 128 KiB, and must also be at
+                // least 128 KiB. 2 MiB satisfies both.
                 .align_up(Alignment::new::<SZ_2M>())
                 .ok_or(EINVAL)?;
         }
drivers/gpu/nova-core/gsp/fw.rs +0 -1
index 0876e2cb785d..14271fbe0c25 100644
@@ -3,7 +3,6 @@
 
 pub(crate) mod commands;
 mod r000_00;
-mod r570_144;
 
 // Alias to avoid repeating the version number with every use.
 use r000_00 as bindings;
drivers/gpu/nova-core/gsp/fw/r570_144.rs deleted +0 -31
deleted file mode 100644
index 2e6f0d298756..000000000000
@@ -1,31 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0
-
-//! Firmware bindings.
-//!
-//! Imports the generated bindings by `bindgen`.
-//!
-//! This module may not be directly used. Please abstract or re-export the needed symbols in the
-//! parent module instead.
-
-#![allow(
-    dead_code,
-    clippy::all,
-    clippy::undocumented_unsafe_blocks,
-    clippy::ptr_as_ptr,
-    clippy::ref_as_ptr,
-    missing_docs,
-    non_camel_case_types,
-    non_upper_case_globals,
-    non_snake_case,
-    improper_ctypes,
-    unreachable_pub,
-    unsafe_op_in_unsafe_fn
-)]
-use kernel::ffi;
-use pin_init::MaybeZeroable;
-
-include!("r570_144/bindings.rs");
-
-// SAFETY: This type has a size of zero, so its inclusion into another type should not affect their
-// ability to implement `Zeroable`.
-unsafe impl<T> kernel::prelude::Zeroable for __IncompleteArrayField<T> {}
drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs deleted +0 -1060

1,060 lines not on this page · raw message

Signature · 1 line
2.55.0
#69 lore raw

PATCH v3 30/33 gpu: nova-core: match GSP RPC replies by sequence, not just function

In reply to John Hubbard

GSP-RM copies a command's RPC sequence number into its reply, alongside the function code. The r570 firmware leaves that field zero, and the r000 firmware fills it in.

Nova-core matched a reply on the function code alone and never set the sequence in a command, so a reply to a command that had already timed out could satisfy a later command with the same function code.

Write the sequence number into every RPC command, and require both the function code and the sequence to match before accepting a reply. An unsolicited event answers no command, so a caller that waits for an event still matches on the function code alone. A message with the expected function code and a stale sequence is a late reply rather than an event, so it is logged and dropped.

Assisted-by LLM
---
 Documentation/gpu/nova/core/interrupts.rst |  9 ++-
 drivers/gpu/nova-core/gsp/cmdq.rs          | 94 ++++++++++++++--------
 drivers/gpu/nova-core/gsp/fw.rs            | 13 ++-
 3 files changed, 77 insertions(+), 39 deletions(-)
Documentation/gpu/nova/core/interrupts.rst +6 -3
index fdcd789cf4f9..8519c73e9989 100644
@@ -574,9 +574,12 @@ function code says which it is.
   receive trace at debug level already records every message's arrival with
   its sequence number, function code, and length.
 
-The sequence number takes no part in the match, because the GSP does not echo
-the command's sequence number on every reply. On r570 the reply to
-``UnloadingGuestDriver`` carries sequence 0.
+A command's reply must carry the RPC sequence number that nova-core wrote into
+the command, as well as its function code. A message with the awaited function
+code and a different sequence number is a stale reply to a command that already
+timed out, so it is logged at warning level and dropped rather than classified
+as an event. An unsolicited event answers no command, so a caller awaiting one
+matches on the function code alone.
 
 The read pointer advances past every message, whether it matched, was an event,
 or matched but failed to decode, so a message is never left at the queue head
drivers/gpu/nova-core/gsp/cmdq.rs +62 -32

245 lines not on this page · raw message

drivers/gpu/nova-core/gsp/fw.rs +9 -4
index 14271fbe0c25..ced7da14c0b2 100644
@@ -470,13 +470,14 @@ fn new() -> Self {
 }
 
 impl bindings::rpc_message_header_v {
-    fn init(cmd_size: usize, function: MsgFunction) -> impl Init<Self, Error> {
+    fn init(sequence: u32, cmd_size: usize, function: MsgFunction) -> impl Init<Self, Error> {
         type RpcMessageHeader = bindings::rpc_message_header_v;
 
         try_init!(RpcMessageHeader {
             header_version: MsgHeaderVersion::new().into(),
             signature: bindings::NV_VGPU_MSG_SIGNATURE_VALID,
             function: function.into(),
+            sequence,
             length: size_of::<Self>()
                 .checked_add(cmd_size)
                 .ok_or(EOVERFLOW)
@@ -503,8 +504,12 @@ pub(crate) struct GspMsgElement {
 
 impl GspMsgElement {
     /// Creates the queue element header and the RPC header of a command with a `cmd_size`-byte
-    /// payload.
-    pub(crate) fn init(cmd_size: usize, function: MsgFunction) -> impl Init<Self, Error> {
+    /// payload and the RPC sequence number `rpc_seq`.
+    pub(crate) fn init(
+        rpc_seq: u32,
+        cmd_size: usize,
+        function: MsgFunction,
+    ) -> impl Init<Self, Error> {
         type RpcMessageHeader = bindings::rpc_message_header_v;
 
         try_init!(GspMsgElement {
@@ -514,7 +519,7 @@ pub(crate) fn init(cmd_size: usize, function: MsgFunction) -> impl Init<Self, Er
                     .checked_add(cmd_size)
                     .ok_or(EOVERFLOW)?,
             )?,
-            rpc <- RpcMessageHeader::init(cmd_size, function),
+            rpc <- RpcMessageHeader::init(rpc_seq, cmd_size, function),
         })
     }
 
Signature · 1 line
2.55.0
#70 lore raw

Re: [PATCH v3 30/33] gpu: nova-core: match GSP RPC replies by sequence, not just function

On Fri Sep 18, 2026 at 10:07 AM JST, John Hubbard wrote:
<...>

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +1 -1
@@ -663,7 +665,7 @@ pub(crate) fn await_msg<M: MessageFromGsp>(&self) -> Result<M>
         // This allows all error types, including `Infallible`, to be used for `M::InitError`.
         Error: From<M::InitError>,
     {
-        self.inner.lock().await_msg()
+        self.inner.lock().await_msg(None)
     }
 
     /// Logs and consumes every message the GSP has already posted, and returns without waiting for

drivers/gpu/nova-core/gsp/cmdq.rs pub(crate) fn drain(&self) -> Result { · line 692

Quoted 8 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3 -2
@@ -685,8 +687,9 @@ pub(crate) fn drain(&self) -> Result {
 struct CmdqInner<'a> {
     /// Device this command queue belongs to.
     dev: &'a device::Device,
-    /// Current command sequence number.
-    seq: u32,
+    /// Next RPC sequence number, advanced once per command, however many messages the command is
+    /// split into.
+    rpc_seq: u32,

This renaming of seq into rpc_seq does not seem to serve any purpose and introduces a lot of churn.

drivers/gpu/nova-core/gsp/cmdq.rs impl CmdqInner<'_> { · line 717

Quoted 9 lines
drivers/gpu/nova-core/gsp/cmdq.rs +1 -1
     /// Set once a message fails framing validation. Every later receive fails, since
     /// the bad message cannot be skipped. See "Draining the GSP-to-CPU queue" in
     /// `Documentation/gpu/nova/core/interrupts.rst`.
@@ -711,7 +714,7 @@ impl CmdqInner<'_> {
     ///   written to by its [`CommandToGsp::init_variable_payload`] method.
     ///
     /// Error codes returned by the command initializers are propagated as-is.
-    fn send_single_command<M>(&mut self, command: M) -> Result
+    fn send_single_command<M>(&mut self, command: M, rpc_seq: u32) -> Result

Passing rpc_seq here looks wrong since we already should have that data available from self. And IIUC it's also easily avoidable by increasing self.rpc_seq *after* the split state handling in send_command (running it in a closure to capture the result if we also want to increase in case or error).

#71 lore raw

PATCH v3 31/33 gpu: nova-core: gsp: split the reply match out of the RPC receive path

In reply to John Hubbard

GSP-RM posts RPC and GMC messages on one queue, so a receive path has to decode each element by its kind before it can match an RPC reply.

The RPC receive path matched the reply inline, in the function that also waited for the element and advanced the read pointer past it. A dispatch on the element kind in that function would have nested the whole match one level deeper.

Move the match into a helper of its own, which decodes the awaited reply or logs the message. The receive path keeps the wait and the read pointer advance.

The following patch adds the dispatch.

No functional changes.

Assisted-by LLM
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 58 ++++++++++++++++++++++---------
 1 file changed, 41 insertions(+), 17 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +41 -17
index fc26c7d8aac0..2258c4f2cfd1 100644
@@ -915,12 +915,8 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
 
     /// Receives a message from the GSP.
     ///
-    /// A message whose function code is `M::FUNCTION` is decoded and returned. Any other message
-    /// is logged as an event.
-    ///
-    /// With `expected_seq` set, the message must carry that RPC sequence number too. A message
-    /// with the expected function code and a different sequence is a stale reply to a command
-    /// that already timed out, so it is logged and dropped rather than classified as an event.
+    /// [`Self::match_rpc_reply`] decodes the message as the awaited reply of type `M`, or logs it.
+    /// `expected_seq` narrows the match.
     ///
     /// The read pointer advances past the message in every case, including a decode failure.
     ///
@@ -942,13 +938,48 @@ fn receive_msg<M: MessageFromGsp>(
         Error: From<M::InitError>,
     {
         let message = self.wait_for_msg(timeout)?;
+
+        // An early return here would leave the read pointer on this message.
+        let result = self.match_rpc_reply::<M>(&message, expected_seq);
+
+        // Advance the read pointer past this message.
+        self.gsp_mem.advance_cpu_read_ptr(u32::try_from(
+            message.header.length().div_ceil(GSP_PAGE_SIZE),
+        )?);
+
+        result
+    }
+
+    /// Decodes `message` as the awaited reply of type `M`, or logs it.
+    ///
+    /// A message whose function code is `M::FUNCTION` is decoded and returned. Any other message
+    /// is logged as an event.
+    ///
+    /// With `expected_seq` set, the message must carry that RPC sequence number too. A message
+    /// with the expected function code and a different sequence is a stale reply to a command
+    /// that already timed out, so it is logged as stale rather than as an event.
+    ///
+    /// # Errors
+    ///
+    /// - `EIO` if the matched message is too short for `M::Message`.
+    /// - `ENOMSG` if the message is not the awaited reply.
+    ///
+    /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
+    fn match_rpc_reply<M: MessageFromGsp>(
+        &self,
+        message: &GspMessage<'_>,
+        expected_seq: Option<u32>,
+    ) -> Result<M>
+    where
+        // This allows all error types, including `Infallible`, to be used for `M::InitError`.
+        Error: From<M::InitError>,
+    {
         let function = message.header.function();
         let seq = message.header.sequence();
         let func_matches = matches!(function, Ok(f) if f == M::FUNCTION);
         let matched = func_matches && expected_seq.is_none_or(|expected| seq == expected);
 
-        // An early return here would leave the read pointer on this message.
-        let result = if matched {
+        if matched {
             match M::Message::from_bytes_prefix(message.contents.0) {
                 Some((cmd, contents_1)) => {
                     let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]);
@@ -984,20 +1015,13 @@ fn receive_msg<M: MessageFromGsp>(
             }
 
             Err(ENOMSG)
-        };
-
-        // Advance the read pointer past this message.
-        self.gsp_mem.advance_cpu_read_ptr(u32::try_from(
-            message.header.length().div_ceil(GSP_PAGE_SIZE),
-        )?);
-
-        result
+        }
     }
 
     /// Receives a message of type `M`, waiting up to [`Cmdq::RECEIVE_TIMEOUT`] from the call.
     ///
     /// Any other message that arrives first is logged as an event and does not extend the
-    /// deadline. `expected_seq` narrows the match as [`Self::receive_msg`] describes.
+    /// deadline. `expected_seq` narrows the match as [`Self::match_rpc_reply`] describes.
     ///
     /// # Errors
     ///
Signature · 1 line
2.55.0
#72 lore raw

PATCH v3 32/33 gpu: nova-core: gsp: decode queue elements by their NVDM type

In reply to John Hubbard

GSP-RM posts RPC and GMC messages on one queue. Every element opens with the same transport headers, whose NVDM type selects whether an RPC header or a GMC header follows.

Each receive path assumed the header of its own kind. An RPC wait read a GMC element through the RPC header layout, where the GMC sequence number occupies the function code's field, so a GMC response looked like the RPC no-op and was consumed silently, and a GMC event looked like an unknown function. The GMC wait logged an RPC element as a dropped element, so an OS error record posted during the GSP_INIT wait was never logged as an error.

Decode every element once, at the transport level, and dispatch on its NVDM type, so that each receive path decodes its own kind and logs the other kind as what it is. An element whose NVDM type the queue does not use poisons the queue, as bad framing does.

The r000 GSP-RM posts no element for the path that the driver is not waiting in, but the protocol allows it, so both receive paths must accept both kinds.

Assisted-by LLM
---
 Documentation/gpu/nova/core/interrupts.rst |  31 +-
 drivers/gpu/nova-core/gsp/cmdq.rs          | 334 +++++++++++----------
 drivers/gpu/nova-core/gsp/fw.rs            |  30 +-
 3 files changed, 201 insertions(+), 194 deletions(-)
Documentation/gpu/nova/core/interrupts.rst +19 -12
index 8519c73e9989..fa124bc8ca05 100644
@@ -562,17 +562,23 @@ GSP.
 Draining the GSP-to-CPU queue
 -----------------------------
 
-The queue carries command replies and unsolicited events, and a message's
-function code says which it is.
+The queue carries RPC messages and GMC messages. GMC is the GPU Management
+Controller, and its API is ABI-stable. Every element opens with the same queue
+element header, which holds the MCTP and NVDM headers, and the NVDM type in
+that header selects which kind of message header follows. An RPC message is a
+command reply or an unsolicited event, and the two differ in the function code.
 
 * A function code that matches the awaited reply: the message is decoded and
   returned to the caller that sent the command.
-* Anything else is an event. An OS error record and a robust-channel record
-  are logged at error level, and an unrecognized function code at warning
-  level. The other known events (GSP logs, libos prints, assertion records,
-  lifecycle notices) need no action and get no line of their own, because the
-  receive trace at debug level already records every message's arrival with
-  its sequence number, function code, and length.
+* Any other RPC message is an event. An OS error record and a robust-channel
+  record are logged at error level, and an unrecognized function code at
+  warning level. The other known events (GSP logs, LIBOS prints, assertion
+  records, lifecycle notices) need no action and get no line of their own,
+  because the receive trace at debug level already records every message's
+  arrival with its sequence number, function code, and length.
+* A GMC message carries a command id in place of a function code. Only the
+  ``GSP_INIT`` wait during boot claims GMC messages, so one that arrives
+  anywhere else is logged at warning level and dropped.
 
 A command's reply must carry the RPC sequence number that nova-core wrote into
 the command, as well as its function code. A message with the awaited function
@@ -585,10 +591,11 @@ The read pointer advances past every message, whether it matched, was an event,
 or matched but failed to decode, so a message is never left at the queue head
 for the next receive to parse again.
 
-Corrupt framing is the exception. An element that fails framing validation has
-no trustworthy length, so the read pointer cannot advance past it. Such a
-failure poisons the queue: nova-core logs it once, and every later receive
-fails with ``EIO`` until the device is reset.
+Corrupt framing is the exception. An element that fails framing validation, or
+that carries an NVDM type that the queue does not use, has no trustworthy
+length, so the read pointer cannot advance past it. Such a failure poisons the
+queue: nova-core logs it once, and every later receive fails with ``EIO`` until
+the device is reset.
 
 The polling path and the IRQ thread both read the queue under the command-queue
 mutex. Replies and events share one queue and one read pointer, so one lock is
drivers/gpu/nova-core/gsp/cmdq.rs +173 -161

504 lines not on this page · raw message

drivers/gpu/nova-core/gsp/fw.rs +9 -21
index ced7da14c0b2..f3dff49af2bf 100644
@@ -535,23 +535,6 @@ pub(crate) fn length(&self) -> usize {
         self.element_header.element_len()
     }
 
-    /// Validates the queue element header and that the element is long enough to hold the RPC
-    /// header after it.
-    ///
-    /// # Errors
-    ///
-    /// - `EIO` if [`QueueElementHeader::validate`] fails, or if the declared element length is
-    ///   shorter than the two headers together.
-    pub(crate) fn validate_framing(&self) -> Result {
-        self.element_header.validate().map_err(|_| EIO)?;
-
-        if self.length() < size_of::<Self>() {
-            return Err(EIO);
-        }
-
-        Ok(())
-    }
-
     // Returns the sequence number of the message.
     pub(crate) fn sequence(&self) -> u32 {
         self.rpc.sequence
@@ -665,6 +648,15 @@ pub(crate) fn element_count(&self) -> u32 {
             .div_ceil(num::usize_into_u32::<GSP_PAGE_SIZE>())
     }
 
+    /// Returns the NVDM type.
+    ///
+    /// # Errors
+    ///
+    /// - `EINVAL` if the field holds no known NVDM type.
+    pub(crate) fn nvdm_type(&self) -> Result<NvdmType> {
+        self.nvdm.nvdm_type()
+    }
+
     /// Validates the queue element header.
     ///
     /// Returns the first check that fails as a [`QueueElementHeaderError`].
@@ -692,10 +684,6 @@ pub(crate) fn validate(&self) -> Result<(), QueueElementHeaderError> {
 
         Ok(())
     }
-
-    pub(crate) fn is_nvdm_type(&self, nvdm_type: NvdmType) -> bool {
-        self.nvdm.validate(nvdm_type)
-    }
 }
 
 /// The check of [`QueueElementHeader::validate`] that a queue element header fails.
Signature · 1 line
2.55.0
#73 lore raw

PATCH v3 33/33 gpu: nova-core: gsp: match a GMC response by flag, id and sequence

In reply to John Hubbard

From: Zhi Wang <[email protected]>

GSP-RM marks a response with a flag bit in the GMC command word, and it echoes back the RPC sequence number that the request carried. An event carries neither, and an event can name any command id. The r000 GSP-RM raises no event that names the GSP_INIT id.

Nova-core matched the GSP_INIT reply on the command id alone. The receive path would have decoded an event that named the same id as the reply, and dropped the real reply, so only the absence of such an event kept the boot working.

Return the sequence number that a GMC send used, and require the response flag, the command id and that sequence to match before decoding a reply. A command that GSP-RM does not answer goes through its own send path, which has no sequence to return.

---
 drivers/gpu/nova-core/gsp/cmdq.rs     | 44 ++++++++++++++++++---------
 drivers/gpu/nova-core/gsp/commands.rs |  8 +++--
 drivers/gpu/nova-core/gsp/fw.rs       | 26 +++++++++++++---
 3 files changed, 55 insertions(+), 23 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +29 -15
index 2664ace70ef8..dd0b3dfc6f37 100644
@@ -642,8 +642,8 @@ pub(crate) fn send_command_no_wait<M>(&self, command: M) -> Result
         self.inner.lock().send_command(command).map(|_| ())
     }
 
-    /// Waits for the response to the GMC request with command id `command_id`, and passes every
-    /// other GMC element that arrives first to `on_other`.
+    /// Waits for the response to the GMC request with command id `command_id` and RPC sequence
+    /// number `sequence`, and passes every other GMC element that arrives first to `on_other`.
     ///
     /// This method may sleep while waiting. The queue mutex stays locked across the whole wait and
     /// across the `on_other` and `decode` calls, so neither may call back into this [`Cmdq`].
@@ -652,16 +652,19 @@ pub(crate) fn send_command_no_wait<M>(&self, command: M) -> Result
     pub(crate) fn await_gmc_response<R>(
         &self,
         command_id: u32,
+        sequence: u32,
         on_other: impl FnMut(&GspGmcMsgElement, &[u8], &[u8]) -> Result,
         decode: impl FnMut(&[u8], &[u8]) -> Result<R>,
     ) -> Result<R> {
         self.inner
             .lock()
-            .await_gmc_response(command_id, on_other, decode)
+            .await_gmc_response(command_id, sequence, on_other, decode)
     }
 
     /// Sends a GMC API request to the GSP without waiting for the response.
     ///
+    /// Returns the RPC sequence number that the request carries.
+    ///
     /// # Errors
     ///
     /// Errors from [`DmaGspMem::allocate_command`] are propagated as-is.
@@ -670,12 +673,24 @@ pub(crate) fn send_gmc_no_wait(
         command_id: u32,
         payload: &[u8],
         max_response_size: u32,
-    ) -> Result {
+    ) -> Result<u32> {
         self.inner
             .lock()
             .send_gmc(command_id, payload, max_response_size)
     }
 
+    /// Sends a GMC API request that GSP-RM does not answer.
+    ///
+    /// # Errors
+    ///
+    /// Errors from [`DmaGspMem::allocate_command`] are propagated as-is.
+    pub(crate) fn send_gmc_no_reply(&self, command_id: u32, payload: &[u8]) -> Result {
+        self.inner
+            .lock()
+            .send_gmc(command_id, payload, 0)
+            .map(|_| ())
+    }
+
     /// Waits for an unsolicited GSP event of type `M`. Events that arrive before it are logged and
     /// consumed.
     ///
@@ -844,10 +859,12 @@ fn poison(&self, reason: fmt::Arguments<'_>) -> Error {
     /// response that the caller accepts. The request carries the next RPC sequence number, which
     /// GSP-RM copies into its response. The number is consumed even if the send fails.
     ///
+    /// Returns the RPC sequence number that the request carries.
+    ///
     /// # Errors
     ///
     /// Errors from [`DmaGspMem::allocate_command`] are propagated as-is.
-    fn send_gmc(&mut self, command_id: u32, payload: &[u8], max_response_size: u32) -> Result {
+    fn send_gmc(&mut self, command_id: u32, payload: &[u8], max_response_size: u32) -> Result<u32> {
         let rpc_seq = self.rpc_seq;
         self.rpc_seq = self.rpc_seq.wrapping_add(1);
 
@@ -855,12 +872,8 @@ fn send_gmc(&mut self, command_id: u32, payload: &[u8], max_response_size: u32)
             .gsp_mem
             .allocate_command::<GspGmcMsgElement>(payload.len(), Self::ALLOCATE_TIMEOUT)?;
 
-        let msg_element = GspGmcMsgElement::init(
-            command_id,
-            u64::from(rpc_seq),
-            payload.len(),
-            max_response_size,
-        );
+        let msg_element =
+            GspGmcMsgElement::init(command_id, rpc_seq, payload.len(), max_response_size);
         // SAFETY: `dst.header` is a valid reference, and not written if the initializer fails.
         unsafe {
             pin_init::raw_try_init(core::ptr::from_mut(dst.header), msg_element)?;
@@ -880,7 +893,7 @@ fn send_gmc(&mut self, command_id: u32, payload: &[u8], max_response_size: u32)
         let elem_count = dst.header.element_count();
         self.gsp_mem.advance_cpu_write_ptr(elem_count);
 
-        Ok(())
+        Ok(rpc_seq)
     }
 
     /// Receives an element from the GSP.
@@ -1302,8 +1315,8 @@ fn receive_gmc_and_dispatch<R>(
         })
     }
 
-    /// Waits for the response to the GMC request with command id `command_id`, up to
-    /// [`Cmdq::RECEIVE_TIMEOUT`] from the call.
+    /// Waits for the response to the GMC request with command id `command_id` and RPC sequence
+    /// number `sequence`, up to [`Cmdq::RECEIVE_TIMEOUT`] from the call.
     ///
     /// The response's payload is passed to `decode`, as two slices because the ring may wrap.
     /// Every other GMC element that arrives first is passed to `on_other` with the headers that
@@ -1321,6 +1334,7 @@ fn receive_gmc_and_dispatch<R>(
     fn await_gmc_response<R>(
         &mut self,
         command_id: u32,
+        sequence: u32,
         mut on_other: impl FnMut(&GspGmcMsgElement, &[u8], &[u8]) -> Result,
         mut decode: impl FnMut(&[u8], &[u8]) -> Result<R>,
     ) -> Result<R> {
@@ -1334,7 +1348,7 @@ fn await_gmc_response<R>(
 
             let response =
                 self.receive_gmc_and_dispatch(remaining, |header, payload_0, payload_1| {
-                    if header.gmc.command_id() != command_id {
+                    if !header.gmc.is_response_to(command_id, sequence) {
                         return on_other(header, payload_0, payload_1).map(|()| None);
                     }
 
drivers/gpu/nova-core/gsp/commands.rs +5 -3
index 128d6f8dcb43..f1a3c0613e70 100644
@@ -79,10 +79,12 @@ pub(crate) fn gsp_init(
     // Qualified because `zerocopy::IntoBytes` also gives `[T]` an `as_bytes`.
     let payload = AsBytes::as_bytes(payload);
 
-    cmdq.send_gmc_no_wait(GMCAPI_CMD_GSP_INIT, payload, GSP_INIT_MAX_RESPONSE_SIZE)?;
+    let sequence =
+        cmdq.send_gmc_no_wait(GMCAPI_CMD_GSP_INIT, payload, GSP_INIT_MAX_RESPONSE_SIZE)?;
 
     cmdq.await_gmc_response(
         GMCAPI_CMD_GSP_INIT,
+        sequence,
         on_unsolicited_element,
         decode_gsp_init_reply,
     )
@@ -124,9 +126,9 @@ fn decode_gsp_init_reply(payload_0: &[u8], payload_1: &[u8]) -> Result<GspStatic
 ///
 /// # Errors
 ///
-/// Errors from [`Cmdq::send_gmc_no_wait`] are propagated as-is.
+/// Errors from [`Cmdq::send_gmc_no_reply`] are propagated as-is.
 pub(crate) fn gsp_suspend(cmdq: &Cmdq<'_>, level: PowerStateLevel) -> Result {
     let params = fw::commands::GspSuspend::new(level);
 
-    cmdq.send_gmc_no_wait(GMCAPI_CMD_GSP_SUSPEND, AsBytes::as_bytes(&params), 0)
+    cmdq.send_gmc_no_reply(GMCAPI_CMD_GSP_SUSPEND, AsBytes::as_bytes(&params))
 }
drivers/gpu/nova-core/gsp/fw.rs +21 -5
index f3dff49af2bf..f7e83e75e53e 100644
@@ -725,6 +725,9 @@ pub(crate) struct GmcApiHeader {
 /// Bits of [`GmcApiHeader::command`] that hold the command id. The high byte holds flags.
 const GMCAPI_COMMAND_ID_MASK: u32 = 0x00ff_ffff;
 
+/// Flag bit of [`GmcApiHeader::command`] that GSP-RM sets on a response.
+const GMCAPI_COMMAND_FLAGS_RESPONSE: u32 = 0x0100_0000;
+
 /// GMC request that carries the system information and registry keys to GSP-RM. GSP-RM answers
 /// it with the static GPU configuration once it has finished starting.
 pub(crate) const GMCAPI_CMD_GSP_INIT: u32 = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_GSP_INIT;
@@ -771,13 +774,26 @@ pub(crate) fn command_id(&self) -> u32 {
         self.command & GMCAPI_COMMAND_ID_MASK
     }
 
+    /// Returns `true` if GSP-RM sent this header as a response rather than an event.
+    fn is_response(&self) -> bool {
+        self.command & GMCAPI_COMMAND_FLAGS_RESPONSE != 0
+    }
+
     /// Returns the `NV_STATUS` that a response carries.
     ///
-    /// The value is meaningful only on a response, which GSP-RM marks with a flag in the command
-    /// word. In a request, the same word holds the largest response that the sender accepts.
+    /// The value is meaningful only when [`Self::is_response`] is `true`. In a request, the same
+    /// word holds the largest response that the sender accepts.
     pub(crate) fn status(&self) -> u32 {
         self.max_resp_or_status
     }
+
+    /// Returns `true` if this header answers the request with command id `command_id` and RPC
+    /// sequence number `sequence`.
+    pub(crate) fn is_response_to(&self, command_id: u32, sequence: u32) -> bool {
+        self.is_response()
+            && self.command_id() == command_id
+            && self.sequence == u64::from(sequence)
+    }
 }
 
 // SAFETY: All fields are integer types with no uninitialized padding bytes.
@@ -801,7 +817,7 @@ pub(crate) struct GspGmcMsgElement {
 
 impl GspGmcMsgElement {
     /// Creates the queue element header and the GMC API header of a request that carries
-    /// `payload_size` bytes of payload.
+    /// `payload_size` bytes of payload under the RPC sequence number `sequence`.
     ///
     /// `max_response_size` is the largest response that the sender accepts, and zero for a request
     /// that GSP-RM does not answer.
@@ -811,7 +827,7 @@ impl GspGmcMsgElement {
     /// - `EOVERFLOW` if a length does not fit its 32-bit field.
     pub(crate) fn init(
         command_id: u32,
-        sequence: u64,
+        sequence: u32,
         payload_size: usize,
         max_response_size: u32,
     ) -> impl Init<Self, Error> {
@@ -825,7 +841,7 @@ pub(crate) fn init(
             gmc: GmcApiHeader {
                 command: command_id,
                 size: payload_size.try_into().map_err(|_| EOVERFLOW)?,
-                sequence,
+                sequence: u64::from(sequence),
                 max_resp_or_status: max_response_size,
                 reserved: [0; 5],
             },
Signature · 1 line
2.55.0
#74 lore raw

Re: [PATCH v3 33/33] gpu: nova-core: gsp: match a GMC response by flag, id and sequence

On Fri Sep 18, 2026 at 10:07 AM JST, John Hubbard wrote:
<...>

Quoted 11 lines

// SAFETY: All fields are integer types with no uninitialized padding bytes.

drivers/gpu/nova-core/gsp/fw.rs +1 -1
@@ -801,7 +817,7 @@ pub(crate) struct GspGmcMsgElement {
 
 impl GspGmcMsgElement {
     /// Creates the queue element header and the GMC API header of a request that carries
-    /// `payload_size` bytes of payload.
+    /// `payload_size` bytes of payload under the RPC sequence number `sequence`.
     ///
     /// `max_response_size` is the largest response that the sender accepts, and zero for a request
     /// that GSP-RM does not answer.

drivers/gpu/nova-core/gsp/fw.rs impl GspGmcMsgElement { · line 830

Quoted 5 lines
drivers/gpu/nova-core/gsp/fw.rs +1 -1
@@ -811,7 +827,7 @@ impl GspGmcMsgElement {
     /// - `EOVERFLOW` if a length does not fit its 32-bit field.
     pub(crate) fn init(
         command_id: u32,
-        sequence: u64,
+        sequence: u32,

Why are we changing the type of sequence here? u64 is the correct type as it's the one that is stored in the GMC header eventually.

This patch (and the previous one IIUC) repair defects introduced earlier in the very same series. Let's please settle on the right shape from the get-go.

Reviewed-by on the v3 series
#75 lore raw
In reply to John Hubbard
Quoted 5 lines · John Hubbard

This series moves nova-core from the r570 GSP (GPU System Processor) firmware onto the ABI that the r615 and later firmware releases share. The driver calls that ABI "r000", because the firmware files carry no version number in their names.

I took another look at this patchset made a few minor comments. So FWIW:

I will test it next week.

#76 lore raw
Quoted 7 lines · Timur Tabi
Quoted 5 lines · John Hubbard

This series moves nova-core from the r570 GSP (GPU System Processor) firmware onto the ABI that the r615 and later firmware releases share. The driver calls that ABI "r000", because the firmware files carry no version number in their names.

Quoted 5 lines

I took another look at this patchset made a few minor comments. So FWIW:

I will test it next week.

Thanks for the reviews!

thanks,

Signature · 1 line
John Hubbard