Skip to contentSkip to conversation

nova-core: GPU interrupt support and GSP event delivery

PATCH Superseded John Hubbard 4 participants 39 messages Aug 8 – Aug 14

Subsystems (9)

v1 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

cover nova-core: GPU interrupt support and GSP event delivery

This series adds support for GIN, the GPU Interrupt and Notification unit and the GPU's interrupt controller, so that GSP events reach the driver as interrupts instead of only when the driver polls.

The series builds the path from the bottom up: the GIN register definitions, a type-state API for walking the two-level tree, a per-architecture HAL for the tree size and the rearm method, and a PCI vector allocation sized to the subtrees nova-core services. On top of that sits a threaded handler on the GSP notification vector, whose top half touches only registers and whose IRQ thread drains the message queue.

Driving that queue from an interrupt rather than from a polling loop exposed three problems polling had hidden, so patches 10 through 13 fix those before the handler arrives in patch 14.

A few rust/ changes were needed first, patches 1 through 3.

Patch 17 adds interrupts.rst, which is the place to start.

Joel Fernandes wrote the first versions of the tree API and the self-test, and Will Pierce reviewed the interrupt work and the document.

Based on drm-rust-next plus Danilo Krummrich's "rust: irq: make Registration compatible with lifetime-bound drivers".

There is a git branch with the patches as applied to drm-rust-next:

https://github.com/johnhubbard/linux/tree/nova-core-gin-interrupt-tree-v0/

Testing: the 14 KUnit tests this series adds all pass. Probe succeeds with the delivery self-test enabled on TU117 (Turing), GA104 (Ampere), and GB202 (Blackwell). All three were granted MSI rather than MSI-X, so the pre-Hopper configuration-mirror rearm and the Hopper-plus TOP cycle both ran on hardware. Only KUnit covers the MSI-X per-subtree rearm.

An earlier version of this series has serviced real GSP events, in a setup where the GSP posts them after probe. This version has not been re-tested there yet. Patch 15's reordering runs on Turing without regression, but the two races it closes are timing-dependent and I did not reproduce either one.

One known gap: driver_read_area still reads the GSP producer pointer with no acquire barrier. Gary Guo's barrier series puts dma_mb(Read) at exactly that point [1], so let's just wait for his fix to land.

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

Joel Fernandes (3):
rust: sync: completion: add wait_for_completion_timeout()
gpu: nova-core: allocate PCI MSI vector during probe
gpu: nova-core: add the GIN interrupt tree API

John Hubbard (14):
rust: pci: expose the whole interrupt vector allocation
rust: pci: expose the allocated interrupt type
gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers
gpu: nova-core: add the per-architecture GIN CPU interrupt HAL
gpu: nova-core: allocate interrupt vectors for the serviced subtrees
gpu: nova-core: add an interrupt delivery self-test
gpu: nova-core: dispatch GSP events instead of discarding them
gpu: nova-core: match GSP RPC replies by sequence, not just function
gpu: nova-core: recover the GSP receive path from corrupt framing
gpu: nova-core: bound a GSP wait by a single deadline
gpu: nova-core: drive GSP events with the SWGEN0 interrupt
gpu: nova-core: retrigger the GSP falcon and clear every latched cause
gpu: nova-core: add KUnit tests for the interrupt tree and HALs
gpu: nova-core: document the GIN interrupt controller and GSP events

 Documentation/gpu/nova/core/interrupts.rst  | 686 ++++++++++++++++++++
 Documentation/gpu/nova/index.rst            |   1 +
 drivers/gpu/nova-core/Kconfig               |  15 +
 drivers/gpu/nova-core/driver.rs             |  54 +-
 drivers/gpu/nova-core/falcon/gsp.rs         |  71 +-
 drivers/gpu/nova-core/falcon/hal.rs         |  32 +
 drivers/gpu/nova-core/gpu.rs                |  28 +-
 drivers/gpu/nova-core/gsp.rs                |  17 +-
 drivers/gpu/nova-core/gsp/cmdq.rs           | 286 ++++++--
 drivers/gpu/nova-core/gsp/commands.rs       |   8 +-
 drivers/gpu/nova-core/gsp/fw.rs             |  13 +-
 drivers/gpu/nova-core/gsp/sequencer.rs      |   8 +-
 drivers/gpu/nova-core/irq.rs                |  99 +++
 drivers/gpu/nova-core/irq/doorbell_test.rs  | 328 ++++++++++
 drivers/gpu/nova-core/irq/gsp.rs            | 254 ++++++++
 drivers/gpu/nova-core/irq/hal.rs            | 215 ++++++
 drivers/gpu/nova-core/irq/hal/gh100.rs      |  30 +
 drivers/gpu/nova-core/irq/hal/tu102.rs      |  29 +
 drivers/gpu/nova-core/irq/interrupt_tree.rs | 425 ++++++++++++
 drivers/gpu/nova-core/nova_core.rs          |   1 +
 drivers/gpu/nova-core/regs.rs               |  95 +++
 rust/helpers/pci.c                          |  11 +
 rust/kernel/pci.rs                          |   1 +
 rust/kernel/pci/irq.rs                      | 143 ++--
 rust/kernel/sync/completion.rs              |  34 +-
 25 files changed, 2737 insertions(+), 147 deletions(-)
 create mode 100644 Documentation/gpu/nova/core/interrupts.rst
 create mode 100644 drivers/gpu/nova-core/irq.rs
 create mode 100644 drivers/gpu/nova-core/irq/doorbell_test.rs
 create mode 100644 drivers/gpu/nova-core/irq/gsp.rs
 create mode 100644 drivers/gpu/nova-core/irq/hal.rs
 create mode 100644 drivers/gpu/nova-core/irq/hal/gh100.rs
 create mode 100644 drivers/gpu/nova-core/irq/hal/tu102.rs
 create mode 100644 drivers/gpu/nova-core/irq/interrupt_tree.rs

base-commit: 4c9ba407018e8deb06dbc643112bac8f40404f95
prerequisite-patch-id: 63224325d5ec73f06517bb35f8c366a086bbea19

Signature · 1 line
2.55.0
#1 lore raw

PATCH 1/17 rust: sync: completion: add wait_for_completion_timeout()

From: Joel Fernandes <[email protected]>

A driver that runs an interrupt self-test during probe waits for the handler to fire. wait_for_completion() has no timeout, so a broken interrupt path stalls probe indefinitely. Add a timeout variant of wait_for_completion().

Document the type invariant that Completion always holds an initialized struct completion, and cite it in the SAFETY comments.

[jhubbard: return the remaining jiffies, document the type invariant,
cite it in the SAFETY comments]

---
 rust/kernel/sync/completion.rs | 34 +++++++++++++++++++++++++++++++---
 1 file changed, 31 insertions(+), 3 deletions(-)
rust/kernel/sync/completion.rs +31 -3
index 35ff049ff078..b443c4999493 100644
@@ -6,13 +6,22 @@
 //!
 //! C header: [`include/linux/completion.h`](srctree/include/linux/completion.h)
 
-use crate::{bindings, prelude::*, types::Opaque};
+use crate::{
+    bindings,
+    prelude::*,
+    time::Jiffies,
+    types::Opaque, //
+};
 
 /// Synchronization primitive to signal when a certain task has been completed.
 ///
 /// The [`Completion`] synchronization primitive signals when a certain task has been completed by
 /// waking up other tasks that have been queued up to wait for the [`Completion`] to be completed.
 ///
+/// # Invariants
+///
+/// `inner` always holds an initialized `struct completion`.
+///
 /// # Examples
 ///
 /// ```
@@ -96,7 +105,8 @@ fn as_raw(&self) -> *mut bindings::completion {
     /// completion is permanently done, i.e. signals all current and future waiters.
     #[inline]
     pub fn complete_all(&self) {
-        // SAFETY: `self.as_raw()` is a pointer to a valid `struct completion`.
+        // SAFETY: By the type invariant, `self.as_raw()` is a pointer to an initialized
+        // `struct completion`.
         unsafe { bindings::complete_all(self.as_raw()) };
     }
 
@@ -108,7 +118,25 @@ pub fn complete_all(&self) {
     /// See also [`Completion::complete_all`].
     #[inline]
     pub fn wait_for_completion(&self) {
-        // SAFETY: `self.as_raw()` is a pointer to a valid `struct completion`.
+        // SAFETY: By the type invariant, `self.as_raw()` is a pointer to an initialized
+        // `struct completion`.
         unsafe { bindings::wait_for_completion(self.as_raw()) };
     }
+
+    /// Wait for completion of a task, with a timeout.
+    ///
+    /// This method waits for the completion of a task, or until `timeout` elapses. It is not
+    /// interruptible. Returns the number of jiffies left when the task completed, or [`None`] if
+    /// `timeout` elapsed first.
+    ///
+    /// See also [`Completion::complete_all`].
+    #[inline]
+    pub fn wait_for_completion_timeout(&self, timeout: Jiffies) -> Option<Jiffies> {
+        // SAFETY: By the type invariant, `self.as_raw()` is a pointer to an initialized
+        // `struct completion`.
+        match unsafe { bindings::wait_for_completion_timeout(self.as_raw(), timeout) } {
+            0 => None,
+            remaining => Some(remaining),
+        }
+    }
 }
Signature · 1 line
2.55.0
#2 lore raw

Re: [PATCH 01/17] rust: sync: completion: add wait_for_completion_timeout()

Quoted 9 lines · John Hubbard

From: Joel Fernandes <[email protected]>

A driver that runs an interrupt self-test during probe waits for the handler to fire. wait_for_completion() has no timeout, so a broken interrupt path stalls probe indefinitely. Add a timeout variant of wait_for_completion().

Document the type invariant that Completion always holds an initialized struct completion, and cite it in the SAFETY comments.

That last paragraph (and the associated hunks below) are a different thing, and should be its own patch.

<...>

Quoted 23 lines

/// Synchronization primitive to signal when a certain task has been completed. ///
/// The [Completion] synchronization primitive signals when a certain task has been completed by /// waking up other tasks that have been queued up to wait for the [Completion] to be completed. ///

rust/kernel/sync/completion.rs +6 -1
+/// # Invariants
+///
+/// `inner` always holds an initialized `struct completion`.
+///
 /// # Examples
 ///
 /// ```
@@ -96,7 +105,8 @@ fn as_raw(&self) -> *mut bindings::completion {
     /// completion is permanently done, i.e. signals all current and future waiters.
     #[inline]
     pub fn complete_all(&self) {
-        // SAFETY: `self.as_raw()` is a pointer to a valid `struct completion`.
+        // SAFETY: By the type invariant, `self.as_raw()` is a pointer to an initialized
+        // `struct completion`.
         unsafe { bindings::complete_all(self.as_raw()) };
     }
 

rust/kernel/sync/completion.rs pub fn complete_all(&self) { · line 124

Quoted 8 lines
rust/kernel/sync/completion.rs +2 -1
@@ -108,7 +118,25 @@ pub fn complete_all(&self) {
     /// See also [`Completion::complete_all`].
     #[inline]
     pub fn wait_for_completion(&self) {
-        // SAFETY: `self.as_raw()` is a pointer to a valid `struct completion`.
+        // SAFETY: By the type invariant, `self.as_raw()` is a pointer to an initialized
+        // `struct completion`.
         unsafe { bindings::wait_for_completion(self.as_raw()) };
     }

These hunks are what should be extracted, or even dropped as wait_for_completion_timeout doesn't add any extra requirement for them.

#3 lore raw

Re: [PATCH 01/17] rust: sync: completion: add wait_for_completion_timeout()

Quoted 8 lines · Alexandre Courbot
Quoted 7 lines · John Hubbard

From: Joel Fernandes <[email protected]>

A driver that runs an interrupt self-test during probe waits for the handler to fire. wait_for_completion() has no timeout, so a broken interrupt path stalls probe indefinitely. Add a timeout variant of wait_for_completion().

Quoted 5 lines
Quoted 2 lines

Document the type invariant that Completion always holds an initialized struct completion, and cite it in the SAFETY comments.

That last paragraph (and the associated hunks below) are a different thing, and should be its own patch.

OK.

Quoted 24 lines

<...>

Quoted 22 lines

/// Synchronization primitive to signal when a certain task has been completed. ///
/// The [Completion] synchronization primitive signals when a certain task has been completed by /// waking up other tasks that have been queued up to wait for the [Completion] to be completed. ///

rust/kernel/sync/completion.rs +6 -1
+/// # Invariants
+///
+/// `inner` always holds an initialized `struct completion`.
+///
  /// # Examples
  ///
  /// ```
@@ -96,7 +105,8 @@ fn as_raw(&self) -> *mut bindings::completion {
      /// completion is permanently done, i.e. signals all current and future waiters.
      #[inline]
      pub fn complete_all(&self) {
-        // SAFETY: `self.as_raw()` is a pointer to a valid `struct completion`.
+        // SAFETY: By the type invariant, `self.as_raw()` is a pointer to an initialized
+        // `struct completion`.
          unsafe { bindings::complete_all(self.as_raw()) };
      }
 
Quoted 13 lines

rust/kernel/sync/completion.rs pub fn complete_all(&self) { · line 124

Quoted 9 lines
rust/kernel/sync/completion.rs +2 -1
@@ -108,7 +118,25 @@ pub fn complete_all(&self) {
      /// See also [`Completion::complete_all`].
      #[inline]
      pub fn wait_for_completion(&self) {
-        // SAFETY: `self.as_raw()` is a pointer to a valid `struct completion`.
+        // SAFETY: By the type invariant, `self.as_raw()` is a pointer to an initialized
+        // `struct completion`.
          unsafe { bindings::wait_for_completion(self.as_raw()) };
      }

These hunks are what should be extracted, or even dropped as wait_for_completion_timeout doesn't add any extra requirement for them.

OK, I'll just drop those entirely.

thanks,

Signature · 1 line
John Hubbard
#4 lore raw

PATCH 2/17 rust: pci: expose the whole interrupt vector allocation

In reply to John Hubbard

A PCI driver that allocates several interrupt vectors registers one handler per vector, so it needs the number of vectors the PCI core allocated and access to each vector. The Rust abstraction discarded the count and returned only the first and last vector.

Return a handle to the allocation. The handle reports how many vectors there are, and resolves a vector index to the Linux IRQ number a handler is registered on.

Assisted-by Cursor:claude-opus-5
---
 rust/kernel/pci.rs     |   1 +
 rust/kernel/pci/irq.rs | 123 ++++++++++++++++++++++++-----------------
 2 files changed, 74 insertions(+), 50 deletions(-)
rust/kernel/pci.rs +1 -0
index 9f19ccd5905c..2f58b284efff 100644
@@ -49,6 +49,7 @@
     Normal, //
 };
 pub use self::irq::{
+    IrqAllocation,
     IrqType,
     IrqTypes,
     IrqVector, //
rust/kernel/pci/irq.rs +73 -50

202 lines not on this page · raw message

Signature · 1 line
2.55.0
maintainer
#5 lore raw

Re: [PATCH 02/17] rust: pci: expose the whole interrupt vector allocation

Quoted 14 lines · John Hubbard
rust/kernel/pci/irq.rs +13 -0
+/// An allocation of PCI interrupt vectors for a device.
+///
+/// [`Device::alloc_irq_vectors`] allocates the vectors and returns this handle. The vectors are
+/// numbered `0..count`, and [`Self::vector`] resolves one of those indices to the Linux IRQ
+/// number that delivers it.
+///
+/// # Invariants
+///
+/// `dev` has an allocation of `count` interrupt vectors.
+#[derive(Clone, Copy)]
+pub struct IrqAllocation<'a> {
+    dev: &'a Device<Bound>,
+    count: NonZero<u32>,
 }

[...]

rust/kernel/pci/irq.rs impl IrqVectorRegistration { · line 165

Quoted 13 lines
rust/kernel/pci/irq.rs +2 -2
@@ -128,13 +156,13 @@ impl IrqVectorRegistration {
     /// Allocate and register IRQ vectors for the given PCI device.
     ///
     /// Allocates IRQ vectors and registers them with devres for automatic cleanup.
-    /// Returns a range of valid IRQ vectors.
+    /// Returns a handle to the allocated IRQ vectors.
     fn register<'a>(
         dev: &'a Device<Bound>,
         min_vecs: u32,
         max_vecs: u32,
         irq_types: IrqTypes,
-    ) -> Result<RangeInclusive<IrqVector<'a>>> {
+    ) -> Result<IrqAllocation<'a>> {

Please see the second part in [1].

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

#6 lore raw

PATCH 3/17 rust: pci: expose the allocated interrupt type

In reply to John Hubbard

A PCI driver can accept INTx, MSI, or MSI-X, and how it acknowledges an interrupt can depend on which one the PCI core picks. The Rust abstraction never reported the choice, so a driver had to assume, and of course a wrong assumption would lead to a broken interrupt delivery setup.

Report the type that the PCI core selected.

Assisted-by Cursor:claude-opus-5
---
 rust/helpers/pci.c     | 11 +++++++++++
 rust/kernel/pci/irq.rs | 30 ++++++++++++++++++++++++++----
 2 files changed, 37 insertions(+), 4 deletions(-)
rust/helpers/pci.c +11 -0
index 4ebf256dff23..87ccd0cec69f 100644
@@ -24,6 +24,17 @@ __rust_helper bool rust_helper_dev_is_pci(const struct device *dev)
 	return dev_is_pci(dev);
 }
 
+__rust_helper unsigned int rust_helper_pci_irq_type(struct pci_dev *pdev)
+{
+	if (pdev->msix_enabled)
+		return PCI_IRQ_MSIX;
+
+	if (pdev->msi_enabled)
+		return PCI_IRQ_MSI;
+
+	return PCI_IRQ_INTX;
+}
+
 #ifndef CONFIG_PCI_IOV
 __rust_helper unsigned int
 rust_helper_pci_sriov_get_totalvfs(struct pci_dev *pdev)
rust/kernel/pci/irq.rs +26 -4
index 66723a43491b..10c728cd139e 100644
@@ -100,11 +100,12 @@ fn from(vector: IrqVector<'a>) -> Self {
 ///
 /// # Invariants
 ///
-/// `dev` has an allocation of `count` interrupt vectors.
+/// `dev` has an allocation of `count` interrupt vectors of type `irq_type`.
 #[derive(Clone, Copy)]
 pub struct IrqAllocation<'a> {
     dev: &'a Device<Bound>,
     count: NonZero<u32>,
+    irq_type: IrqType,
 }
 
 impl<'a> IrqAllocation<'a> {
@@ -115,6 +116,15 @@ pub fn count(&self) -> NonZero<u32> {
         self.count
     }
 
+    /// Returns the interrupt type the PCI core selected.
+    ///
+    /// [`Device::alloc_irq_vectors`] takes a set of acceptable types and picks one of them, so a
+    /// driver whose behavior depends on the type asks for it here rather than assuming. Every
+    /// vector of the allocation has this type.
+    pub fn irq_type(&self) -> IrqType {
+        self.irq_type
+    }
+
     /// Resolves the vector at `index` to the Linux IRQ number that delivers it.
     ///
     /// # Errors
@@ -177,9 +187,21 @@ fn register<'a>(
         // `pci_alloc_irq_vectors` returns the number of vectors it allocated.
         let count = NonZero::new(ret as u32).ok_or(EINVAL)?;
 
-        // INVARIANT: `pci_alloc_irq_vectors` allocated `count` vectors for `dev`, numbered
-        // from 0.
-        let vectors = IrqAllocation { dev, count };
+        // SAFETY: `dev.as_raw()` is a valid pointer to a `struct pci_dev`.
+        let irq_type = match unsafe { bindings::pci_irq_type(dev.as_raw()) } {
+            bindings::PCI_IRQ_MSIX => IrqType::MsiX,
+            bindings::PCI_IRQ_MSI => IrqType::Msi,
+            // The helper returns `PCI_IRQ_INTX` when neither MSI nor MSI-X is enabled.
+            _ => IrqType::Intx,
+        };
+
+        // INVARIANT: `pci_alloc_irq_vectors` allocated `count` vectors of `irq_type` for `dev`,
+        // numbered from 0.
+        let vectors = IrqAllocation {
+            dev,
+            count,
+            irq_type,
+        };
 
         // INVARIANT: The IRQ vector allocation for `dev` above was successful.
         let irq_vecs = Self { dev: dev.into() };
Signature · 1 line
2.55.0
maintainer
#7 lore raw

Re: [PATCH 03/17] rust: pci: expose the allocated interrupt type

Quoted 8 lines · John Hubbard
rust/helpers/pci.c +0 -0
index 4ebf256dff23..87ccd0cec69f 100644
@@ -24,6 +24,17 @@ __rust_helper bool rust_helper_dev_is_pci(const struct device *dev)
 	return dev_is_pci(dev);
 }
 

rust/helpers/pci.c __rust_helper bool rust_helper_dev_is_pci(const struct device *dev) · line 36

Quoted 10 lines
rust/helpers/pci.c +10 -0
+__rust_helper unsigned int rust_helper_pci_irq_type(struct pci_dev *pdev)
+{
+	if (pdev->msix_enabled)
+		return PCI_IRQ_MSIX;
+
+	if (pdev->msi_enabled)
+		return PCI_IRQ_MSI;
+
+	return PCI_IRQ_INTX;
+}

Rust helpers should only be transparent wrappers of existing functions / macros.

In this case this can be easily lifeted to include/linux/pci.h, as it should be a useful addition in general.

On the one hand there's already open-coded variants of this in drivers (such as in [1]), and on the other hand I think it is not that great that drivers access fields like msix_enabled directly.

Related to that, msix_enabled and msi_enabled are fields within a C bitfield of struct pci_device, so accessing this under just the Bound device context is formally UB (though in practice it shouldn't be an issue).

However, this makes me notice that pci_alloc_irq_vectors() and pci_free_irq_vectors() both mutate those fields.

Consequently, IrqVectorRegistration::register() is technically unsound by requiring a Device<Bound> and instead has to require a Device<Core>, such that the C bitfield access is protected by the device lock.

Now, I think that there's already fields in the struct pci_dev C bitfield, which are not protected with the device lock (such as block_cfg_access or ats_enabled), so this is already racy regardless.

However, even if that wouldn't be the case, pci_alloc_irq_vectors() has valid use-cases outside of bus callbacks, i.e. where the device lock is not held, e.g. in [2] where it is called from a work item during device recovery.

IOW, just using the Core is the wrong solution (and insufficient anyway); Bound is the correct context, but we need to fix the C bitfield issue.

I've also reported this in [3] for the is_busmaster field and it led to the patch in [4]. However, I still think that there's quite some more fields in the C bitfield that should be converted to bitops.

We recently had a similar rework [5] in driver-core that I suggested for similar reasons. While not every field would have actually needed bitops, I think it is simpler to just use bitops and be safe.

[1] https://elixir.bootlin.com/linux/v7.1.7/source/drivers/net/ethernet/aquantia/atlantic/aq_pci_func.c#L196
[2] https://elixir.bootlin.com/linux/v7.1.7/source/drivers/net/ethernet/mellanox/mlx5/core/pci_irq.c#L773
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/
[5] https://lore.kernel.org/all/[email protected]/

rust/helpers/pci.c fn register<'a>(

Quoted 4 lines
rust/helpers/pci.c +0 -0
     /// Resolves the vector at `index` to the Linux IRQ number that delivers it.
     ///
     /// # Errors
@@ -177,9 +187,21 @@ fn register<'a>(

Currently this function still uses devres::register(), but we should change it to return Self being constrained to the lifetime of the &Device<Bound>.

This way the IrqAllocation type goes away and the IrqType and cound can be directly on the IrqVectorRegistration type.

It also allows drivers to explicitly manage the lifetime of an IrqVectorRegistration, which is something typically used by net and block drivers.

Note that this also requires a borrow chain where irq::Registration keeps the pci::IrqVectorRegistration alive.

This could be done with adding a generic on IrqRequest which defaults to () for non-PCI stuff.

If you prefer, I can also send a patch for this that you could incorporate into your patch series, so it doesn't conflict.

Thanks,
Danilo

Quoted 21 lines
rust/helpers/pci.c +15 -3
         // `pci_alloc_irq_vectors` returns the number of vectors it allocated.
         let count = NonZero::new(ret as u32).ok_or(EINVAL)?;
 
-        // INVARIANT: `pci_alloc_irq_vectors` allocated `count` vectors for `dev`, numbered
-        // from 0.
-        let vectors = IrqAllocation { dev, count };
+        // SAFETY: `dev.as_raw()` is a valid pointer to a `struct pci_dev`.
+        let irq_type = match unsafe { bindings::pci_irq_type(dev.as_raw()) } {
+            bindings::PCI_IRQ_MSIX => IrqType::MsiX,
+            bindings::PCI_IRQ_MSI => IrqType::Msi,
+            // The helper returns `PCI_IRQ_INTX` when neither MSI nor MSI-X is enabled.
+            _ => IrqType::Intx,
+        };
+
+        // INVARIANT: `pci_alloc_irq_vectors` allocated `count` vectors of `irq_type` for `dev`,
+        // numbered from 0.
+        let vectors = IrqAllocation {
+            dev,
+            count,
+            irq_type,
+        };
#8 lore raw

Re: [PATCH 03/17] rust: pci: expose the allocated interrupt type

Quoted 22 lines · Danilo Krummrich
Quoted 8 lines · John Hubbard
rust/helpers/pci.c +0 -0
index 4ebf256dff23..87ccd0cec69f 100644
@@ -24,6 +24,17 @@ __rust_helper bool rust_helper_dev_is_pci(const struct device *dev)
  	return dev_is_pci(dev);
  }
 

rust/helpers/pci.c __rust_helper bool rust_helper_dev_is_pci(const struct device *dev) · line 36

Quoted 10 lines
rust/helpers/pci.c +10 -0
+__rust_helper unsigned int rust_helper_pci_irq_type(struct pci_dev *pdev)
+{
+	if (pdev->msix_enabled)
+		return PCI_IRQ_MSIX;
+
+	if (pdev->msi_enabled)
+		return PCI_IRQ_MSI;
+
+	return PCI_IRQ_INTX;
+}

Rust helpers should only be transparent wrappers of existing functions / macros.

Quoted 2 lines

In this case this can be easily lifeted to include/linux/pci.h, as it should be a useful addition in general.

Will do.

Quoted 35 lines

On the one hand there's already open-coded variants of this in drivers (such as in [1]), and on the other hand I think it is not that great that drivers access fields like msix_enabled directly.

Related to that, msix_enabled and msi_enabled are fields within a C bitfield of struct pci_device, so accessing this under just the Bound device context is formally UB (though in practice it shouldn't be an issue).

However, this makes me notice that pci_alloc_irq_vectors() and pci_free_irq_vectors() both mutate those fields.

Consequently, IrqVectorRegistration::register() is technically unsound by requiring a Device<Bound> and instead has to require a Device<Core>, such that the C bitfield access is protected by the device lock.

Now, I think that there's already fields in the struct pci_dev C bitfield, which are not protected with the device lock (such as block_cfg_access or ats_enabled), so this is already racy regardless.

However, even if that wouldn't be the case, pci_alloc_irq_vectors() has valid use-cases outside of bus callbacks, i.e. where the device lock is not held, e.g. in [2] where it is called from a work item during device recovery.

IOW, just using the Core is the wrong solution (and insufficient anyway); Bound is the correct context, but we need to fix the C bitfield issue.

I've also reported this in [3] for the is_busmaster field and it led to the patch in [4]. However, I still think that there's quite some more fields in the C bitfield that should be converted to bitops.

We recently had a similar rework [5] in driver-core that I suggested for similar reasons. While not every field would have actually needed bitops, I think it is simpler to just use bitops and be safe.

Quoted 5 lines

[1] https://elixir.bootlin.com/linux/v7.1.7/source/drivers/net/ethernet/aquantia/atlantic/aq_pci_func.c#L196
[2] https://elixir.bootlin.com/linux/v7.1.7/source/drivers/net/ethernet/mellanox/mlx5/core/pci_irq.c#L773
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/
[5] https://lore.kernel.org/all/[email protected]/

An interesting read, thanks for the write-up and the references!

OK, so I'll leave things using Device<Bound>.

Quoted 16 lines

rust/helpers/pci.c fn register<'a>(

Quoted 5 lines
rust/helpers/pci.c +0 -0
      /// Resolves the vector at `index` to the Linux IRQ number that delivers it.
      ///
      /// # Errors
@@ -177,9 +187,21 @@ fn register<'a>(

Currently this function still uses devres::register(), but we should change it to return Self being constrained to the lifetime of the &Device<Bound>.

This way the IrqAllocation type goes away and the IrqType and cound can be directly on the IrqVectorRegistration type.

It also allows drivers to explicitly manage the lifetime of an IrqVectorRegistration, which is something typically used by net and block drivers.

Quoted 8 lines

Note that this also requires a borrow chain where irq::Registration keeps the pci::IrqVectorRegistration alive.

This could be done with adding a generic on IrqRequest which defaults to () for non-PCI stuff.

If you prefer, I can also send a patch for this that you could incorporate into your patch series, so it doesn't conflict.

Yes, please. Then my patches 2 and 3 collapse into a single patch that adds count(), irq_type() and an index-to-IrqVector accessor. Or, they go away entirely if you end up putting those on the type yourself.

thanks,

Signature · 1 line
John Hubbard
maintainer
#9 lore raw

Re: [PATCH 03/17] rust: pci: expose the allocated interrupt type

Quoted 3 lines · John Hubbard

Yes, please. Then my patches 2 and 3 collapse into a single patch that adds count(), irq_type() and an index-to-IrqVector accessor. Or, they go away entirely if you end up putting those on the type yourself.

I sent out a patch series [1] for this, applied your nova-core patches on top of it and resolved the conflicts with the diff below (also pushed a branch in [2]).

Note that I optimized for a clean diff and not for optimal code. I think there are more improvements we can make; I will comment on the corresponding patches of this series.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://git.kernel.org/pub/scm/linux/kernel/git/dakr/linux.git/log/?h=nova/irq

drivers/gpu/nova-core/driver.rs +22 -17
index 3fbf117a99ee..21d7df0744ed 100644
@@ -20,7 +20,10 @@
 
 use crate::{
     gpu::Gpu,
-    irq::gsp::GspIrq, //
+    irq::{
+        gsp::GspIrq,
+        SubtreeVectors, //
+    },
 };
 
 /// Counter for generating unique auxiliary device IDs.
@@ -39,6 +42,12 @@ pub(crate) struct NovaCore<'bound> {
     bar: pci::Bar<'bound, BAR0_SIZE>,
     #[allow(clippy::type_complexity)]
     _reg: auxiliary::Registration<'bound, ForLt!(())>,
+    /// Self-referential borrow of `vectors`, so this does not have to be repeated in the
+    /// constructor. Will go away with self-referential pin-init.
+    vectors_ref: &'bound SubtreeVectors<'bound>,
+    /// PCI interrupt vector allocation. Dropped last (struct field drop order).
+    #[pin]
+    vectors: SubtreeVectors<'bound>,
 }
 
 pub(crate) struct NovaCoreDriver;
@@ -87,38 +96,34 @@ fn probe<'bound>(
             pdev.enable_device_mem()?;
             pdev.set_master();
 
-            // A PCI device has one interrupt vector allocation, so it is made here for every
-            // subtree nova-core services, and each handler takes the vector for its own subtree.
-            let vectors = crate::irq::alloc_vectors(pdev, crate::irq::gsp::GSP_SUBTREE)?;
-            let gsp_vector = vectors.vector_for(crate::irq::gsp::GSP_SUBTREE)?;
-            let irq_type = vectors.irq_type();
-
             Ok(try_pin_init!(NovaCore {
+                vectors: crate::irq::alloc_vectors(pdev, crate::irq::gsp::GSP_SUBTREE)?,
+                // SAFETY: `vectors` is initialized above, lives at a pinned stable address, and
+                // is dropped after all fields that use `vectors_ref` (struct field drop order).
+                vectors_ref: unsafe { &*core::ptr::from_ref(vectors.as_ref().get_ref()) },
                 bar: pdev.iomap_region_sized::<BAR0_SIZE>(0, c"nova-core/bar0")?,
                 // TODO: Use `&bar` self-referential pin-init syntax once available.
                 //
                 // SAFETY: `bar` is initialized before this expression is evaluated
                 // (`try_pin_init!()` initializes fields in the order they appear here), lives at a
                 // pinned stable address, and is dropped after `gpu` (struct field drop order).
-                gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) }, vectors),
+                gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) }, vectors_ref),
                 // Quiesce the interrupt tree before registering the handler below.
                 _: {
                     // SAFETY: as for the `bar` borrow above.
                     let bar = unsafe { &*core::ptr::from_ref(bar) };
-                    crate::irq::gsp::quiesce(bar, gpu.chipset(), irq_type);
+                    crate::irq::gsp::quiesce(bar, gpu.chipset(), vectors_ref.irq_type());
                 },
                 // Register the permanent GSP SWGEN0 handler before enabling the interrupt.
                 //
-                // SAFETY: `bar` is initialized before this expression is evaluated, lives at a
-                // pinned stable address, and is dropped after `_gsp_irq` (declared first, so
-                // dropped first), so the handler's borrow stays valid for its whole lifetime.
-                // `_gsp_irq` is stored in `NovaCore`, whose `Drop` runs `free_irq`, so the
-                // registration is never leaked.
+                // SAFETY: `bar` and `vectors` are initialized and pinned (see above). `_gsp_irq`
+                // is declared before `vectors` in the struct, so it is dropped first, ensuring
+                // `free_irq` runs before the vectors are freed. The registration is stored in
+                // `NovaCore` and never leaked.
                 _gsp_irq <- unsafe {
                     GspIrq::new(
                         pdev,
-                        gsp_vector,
-                        irq_type,
+                        vectors_ref,
                         &*core::ptr::from_ref(bar),
                         gpu.cmdq(),
                         gpu.chipset(),
@@ -129,7 +134,7 @@ fn probe<'bound>(
                 _: {
                     // SAFETY: as for the `bar` borrow above.
                     let bar = unsafe { &*core::ptr::from_ref(bar) };
-                    crate::irq::gsp::enable(bar, gpu.chipset(), irq_type);
+                    crate::irq::gsp::enable(bar, gpu.chipset(), vectors_ref.irq_type());
                     gpu.cmdq().drain()?;
                 },
                 _reg: auxiliary::Registration::new(
drivers/gpu/nova-core/gpu.rs +1 -1
index 9700eff6db86..11a66a597298 100644
@@ -339,7 +339,7 @@ pub(crate) fn cmdq(&self) -> Arc<Cmdq> {
     pub(crate) fn new(
         pdev: &'gpu pci::Device<device::Core<'_>>,
         bar: Bar0<'gpu>,
-        vectors: SubtreeVectors<'gpu>,
+        vectors: &'gpu SubtreeVectors<'gpu>,
     ) -> impl PinInit<Self, Error> + 'gpu {
         let dev = pdev.as_ref();
 
drivers/gpu/nova-core/irq.rs +9 -6
index ddf322f2e623..6f2ab85ccdc9 100644
@@ -16,6 +16,7 @@
 
 use kernel::{
     device::Bound,
+    irq,
     pci::{
         self,
         IrqType,
@@ -28,9 +29,8 @@
 ///
 /// MSI-X raises a separate table entry per subtree, so subtree `N` arrives on entry `N`. MSI has a
 /// single message that every subtree raises, so all of them arrive on the one allocated entry.
-#[derive(Clone, Copy)]
 pub(crate) struct SubtreeVectors<'a> {
-    vectors: pci::IrqAllocation<'a>,
+    vectors: pci::IrqVectorRegistration<'a>,
     /// `TOP` bit of every subtree nova-core services.
     serviced: u32,
 }
@@ -41,18 +41,21 @@ pub(crate) fn irq_type(&self) -> IrqType {
         self.vectors.irq_type()
     }
 
-    /// Returns the vector that delivers `subtree`, a single `TOP` bit of the form
-    /// `interrupt_tree::vector_subtree_mask` returns.
+    /// Returns an [`irq::IrqRequest`] for the vector that delivers `subtree`.
     ///
     /// # Errors
     ///
     /// `EINVAL` if `subtree` names anything other than a single subtree nova-core services.
-    pub(crate) fn vector_for(&self, subtree: u32) -> Result<pci::IrqVector<'a>> {
+    pub(crate) fn request_for(
+        &self,
+        subtree: u32,
+    ) -> Result<irq::IrqRequest<'_, &'_ pci::IrqVectorRegistration<'_>>> {
         if subtree.count_ones() != 1 || subtree & self.serviced == 0 {
             return Err(EINVAL);
         }
 
-        self.vectors.vector(entry_index(self.irq_type(), subtree))
+        self.vectors
+            .request(entry_index(self.irq_type(), subtree) as usize)
     }
 }
 
drivers/gpu/nova-core/irq/doorbell_test.rs +17 -4
index bfdfee732892..2c123d0cdc52 100644
@@ -144,7 +144,13 @@ struct SelftestGuard<'a, 'r> {
     bar: Bar0<'a>,
     tree: Tree,
     doorbell: LeafIndex,
-    reg: Option<Pin<KBox<irq::Registration<'r, DoorbellTestHandler<'a>>>>>,
+    reg: Option<
+        Pin<
+            KBox<
+                irq::Registration<'r, DoorbellTestHandler<'a>, &'r pci::IrqVectorRegistration<'r>>,
+            >,
+        >,
+    >,
 }
 
 impl<'a, 'r> SelftestGuard<'a, 'r> {
@@ -195,11 +201,11 @@ pub(crate) fn run_selftest<'a>(
     pdev: &'a pci::Device<Bound>,
     bar: Bar0<'a>,
     chipset: Chipset,
-    vectors: SubtreeVectors<'_>,
+    vectors: &'a SubtreeVectors<'a>,
 ) -> Result {
     // The interrupt type decides how the handler rearms delivery, so the tree takes it from
     // probe's allocation.
-    let vector = vectors.vector_for(DOORBELL_SUBTREE)?;
+    let request = vectors.request_for(DOORBELL_SUBTREE)?;
     let irq_type = vectors.irq_type();
     let tree = Tree::new(chipset, irq_type, DOORBELL_SUBTREE);
     let doorbell = LeafIndex::new::<DOORBELL_LEAF>();
@@ -252,7 +258,14 @@ pub(crate) fn run_selftest<'a>(
         // SAFETY: the registration is owned by `guard` below and dropped before this function
         // returns, so its `Drop` (which calls `free_irq()`) always runs and the registration is
         // never leaked or `mem::forget`-ed.
-        unsafe { pdev.request_irq(vector, irq::Flags::TRIGGER_NONE, c"nova-core", handler_init) },
+        unsafe {
+            irq::Registration::new(
+                request,
+                irq::Flags::TRIGGER_NONE,
+                c"nova-core",
+                handler_init,
+            )
+        },
         GFP_KERNEL,
     )?;
 
drivers/gpu/nova-core/irq/gsp.rs +7 -8
index ecd716b92d4e..558f944c4c0d 100644
@@ -202,22 +202,21 @@ fn handle_threaded(&self) -> irq::IrqReturn {
 #[pin_data(PinnedDrop)]
 pub(crate) struct GspIrq<'a> {
     #[pin]
-    reg: irq::ThreadedRegistration<'a, GspInterrupt<'a>>,
+    reg: irq::ThreadedRegistration<'a, GspInterrupt<'a>, &'a pci::IrqVectorRegistration<'a>>,
     /// Borrowed BAR0 and the interrupt tree, used by the teardown to disable the GSP source.
     bar: Bar0<'a>,
     tree: Tree,
 }
 
 impl<'a> GspIrq<'a> {
-    /// Registers the GSP SWGEN0 threaded handler on `vector`.
+    /// Registers the GSP SWGEN0 threaded handler for the GSP subtree in `vectors`.
     ///
     /// # Safety
     ///
     /// The caller must not leak the returned value: its [`Drop`] runs `free_irq`.
     pub(crate) unsafe fn new(
         pdev: &'a pci::Device<device::Bound>,
-        vector: pci::IrqVector<'a>,
-        irq_type: pci::IrqType,
+        vectors: &'a super::SubtreeVectors<'a>,
         bar: Bar0<'a>,
         cmdq: Arc<Cmdq>,
         chipset: Chipset,
@@ -227,15 +226,15 @@ pub(crate) unsafe fn new(
             // SAFETY: the caller guarantees the returned `GspIrq` is not leaked, so this
             // registration's `Drop` (`free_irq`) always runs.
             reg <- unsafe {
-                pdev.request_threaded_irq(
-                    vector,
+                irq::ThreadedRegistration::new(
+                    vectors.request_for(GSP_SUBTREE)?,
                     irq::Flags::TRIGGER_NONE,
                     c"nova-core",
-                    GspInterrupt::new(bar, cmdq, chipset, irq_type, dev),
+                    GspInterrupt::new(bar, cmdq, chipset, vectors.irq_type(), dev),
                 )
             },
             bar,
-            tree: Tree::new(chipset, irq_type, GSP_SUBTREE),
+            tree: Tree::new(chipset, vectors.irq_type(), GSP_SUBTREE),
         })
     }
 }
#10 lore raw

Re: [PATCH 03/17] rust: pci: expose the allocated interrupt type

Quoted 7 lines · Danilo Krummrich
Quoted 3 lines · John Hubbard

Yes, please. Then my patches 2 and 3 collapse into a single patch that adds count(), irq_type() and an index-to-IrqVector accessor. Or, they go away entirely if you end up putting those on the type yourself.

I sent out a patch series [1] for this, applied your nova-core patches on top of it and resolved the conflicts with the diff below (also pushed a branch in [2]).

Great, I saw that. I'm going to try it out, and review it, asap.

Quoted 4 lines

Note that I optimized for a clean diff and not for optimal code. I think there are more improvements we can make; I will comment on the corresponding patches of this series.

ack

Quoted 4 lines

[1] https://lore.kernel.org/all/[email protected]/
[2] https://git.kernel.org/pub/scm/linux/kernel/git/dakr/linux.git/log/?h=nova/irq

thanks,

Signature · 1 line
John Hubbard
#11 lore raw

Re: [PATCH 03/17] rust: pci: expose the allocated interrupt type

In reply to Danilo Krummrich
Quoted 11 lines · Danilo Krummrich
Quoted 3 lines · John Hubbard

Yes, please. Then my patches 2 and 3 collapse into a single patch that adds count(), irq_type() and an index-to-IrqVector accessor. Or, they go away entirely if you end up putting those on the type yourself.

I sent out a patch series [1] for this, applied your nova-core patches on top of it and resolved the conflicts with the diff below (also pushed a branch in [2]).

Note that I optimized for a clean diff and not for optimal code. I think there are more improvements we can make; I will comment on the corresponding patches of this series.

I've folded your series and the fixups into a v2 work-in-progress branch, here:

https://github.com/johnhubbard/linux/tree/nova-core-gin-interrupt-tree-v2

Let me know if it would be better for me to post that now, given that the earlier parts are all different now.

thanks,

Signature · 1 line
John Hubbard
maintainer
#12 lore raw

Re: [PATCH 03/17] rust: pci: expose the allocated interrupt type

Quoted 13 lines · John Hubbard
Quoted 11 lines · Danilo Krummrich
Quoted 3 lines · John Hubbard

Yes, please. Then my patches 2 and 3 collapse into a single patch that adds count(), irq_type() and an index-to-IrqVector accessor. Or, they go away entirely if you end up putting those on the type yourself.

I sent out a patch series [1] for this, applied your nova-core patches on top of it and resolved the conflicts with the diff below (also pushed a branch in [2]).

Note that I optimized for a clean diff and not for optimal code. I think there are more improvements we can make; I will comment on the corresponding patches of this series.

Quoted 6 lines

I've folded your series and the fixups into a v2 work-in-progress branch, here:

https://github.com/johnhubbard/linux/tree/nova-core-gin-interrupt-tree-v2

Let me know if it would be better for me to post that now, given that the earlier parts are all different now.

Thanks! I think it's fine as is, will go over the series on Thursday.

I've sent a v2 (and updated the branch I shared previously), as I think preserving the source of IRQ via the anchor type doesn't really add a lot of value and keeping IrqVector as a new type over IrqRequest turns out nicer. The changes required from v1 to v2 should be minimal.

#13 lore raw

PATCH 4/17 gpu: nova-core: allocate PCI MSI vector during probe

In reply to John Hubbard

From: Joel Fernandes <[email protected]>

Allocate a single PCI MSI interrupt vector in the probe path.

Try MSI/MSI-X first. If that fails (possible in broken VFIO setups), fall back to INTx with a dev_warn so the issue is visible in dmesg. The allocation is devres-managed and automatically freed on unbind.

---
 drivers/gpu/nova-core/gpu.rs       |  6 ++++++
 drivers/gpu/nova-core/irq.rs       | 26 ++++++++++++++++++++++++++
 drivers/gpu/nova-core/nova_core.rs |  1 +
 3 files changed, 33 insertions(+)
 create mode 100644 drivers/gpu/nova-core/irq.rs
drivers/gpu/nova-core/gpu.rs +6 -0
index 42a4cd7971fa..5efeba056f1b 100644
@@ -29,6 +29,7 @@
         Gsp,
         GspBootContext, //
     },
+    irq,
     regs,
     vgpu::VgpuManager, //
 };
@@ -386,6 +387,11 @@ pub(crate) fn new(
                 })?,
             }),
 
+            // Allocate a PCI interrupt vector.
+            _: {
+                let _irq_vector = irq::alloc_vector(pdev)?;
+            },
+
             gsp_static_info: {
                 // Obtain and display basic GPU information.
                 let info = gsp_resources.gsp.get_static_info(bar)?;
drivers/gpu/nova-core/irq.rs new file +26 -0
new file mode 100644
index 000000000000..48900c734cb6
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use kernel::{
+    device::Bound,
+    pci::{
+        self,
+        IrqType,
+        IrqTypes, //
+    },
+    prelude::*,
+};
+
+pub(crate) fn alloc_vector(pdev: &pci::Device<Bound>) -> Result<pci::IrqVector<'_>> {
+    let msi_types = IrqTypes::default().with(IrqType::Msi).with(IrqType::MsiX);
+
+    let irq_vectors = match pdev.alloc_irq_vectors(1, 1, msi_types) {
+        Ok(vecs) => vecs,
+        Err(_) => {
+            dev_warn!(pdev.as_ref(), "MSI not available, falling back to INTx\n");
+            pdev.alloc_irq_vectors(1, 1, IrqTypes::default().with(IrqType::Intx))?
+        }
+    };
+
+    irq_vectors.vector(0)
+}
drivers/gpu/nova-core/nova_core.rs +1 -0
index 35a8b1214b0e..68b5abfe494d 100644
@@ -17,6 +17,7 @@
 mod fsp;
 mod gpu;
 mod gsp;
+mod irq;
 mod mctp;
 #[macro_use]
 mod num;
Signature · 1 line
2.55.0
maintainer
#14 lore raw

Re: [PATCH 04/17] gpu: nova-core: allocate PCI MSI vector during probe

Quoted 5 lines · John Hubbard

Allocate a single PCI MSI interrupt vector in the probe path.

Try MSI/MSI-X first. If that fails (possible in broken VFIO setups), fall back to INTx with a dev_warn so the issue is visible in dmesg. The allocation is devres-managed and automatically freed on unbind.

[...]

drivers/gpu/nova-core/irq.rs line 15

Quoted 2 lines
drivers/gpu/nova-core/irq.rs new file +2 -0
+pub(crate) fn alloc_vector(pdev: &pci::Device<Bound>) -> Result<pci::IrqVector<'_>> {
+    let msi_types = IrqTypes::default().with(IrqType::Msi).with(IrqType::MsiX);

I was about to ask if we really need to bother with MSI and shouln't just go for MSI-X only.

But then saw that the commit message mentions broken VFIO setups; can you expand on this a bit? Which setups is the commit message referring to?

Quoted 11 lines
drivers/gpu/nova-core/irq.rs new file +11 -0
+
+    let irq_vectors = match pdev.alloc_irq_vectors(1, 1, msi_types) {
+        Ok(vecs) => vecs,
+        Err(_) => {
+            dev_warn!(pdev.as_ref(), "MSI not available, falling back to INTx\n");
+            pdev.alloc_irq_vectors(1, 1, IrqTypes::default().with(IrqType::Intx))?
+        }
+    };
+
+    irq_vectors.vector(0)
+}
maintainer
#15 lore raw

Re: [PATCH 04/17] gpu: nova-core: allocate PCI MSI vector during probe

Quoted 11 lines · Danilo Krummrich
Quoted 5 lines · John Hubbard

Allocate a single PCI MSI interrupt vector in the probe path.

Try MSI/MSI-X first. If that fails (possible in broken VFIO setups), fall back to INTx with a dev_warn so the issue is visible in dmesg. The allocation is devres-managed and automatically freed on unbind.

[...]

drivers/gpu/nova-core/irq.rs line 15

Quoted 2 lines
drivers/gpu/nova-core/irq.rs new file +2 -0
+pub(crate) fn alloc_vector(pdev: &pci::Device<Bound>) -> Result<pci::IrqVector<'_>> {
+    let msi_types = IrqTypes::default().with(IrqType::Msi).with(IrqType::MsiX);

BTW, we should convert this to use impl_flags so this becomes IrqType::Msi | IrqType::MsiX.

Best,
Gary

Quoted 6 lines

I was about to ask if we really need to bother with MSI and shouln't just go for MSI-X only.

But then saw that the commit message mentions broken VFIO setups; can you expand on this a bit? Which setups is the commit message referring to?

#16 lore raw

Re: [PATCH 04/17] gpu: nova-core: allocate PCI MSI vector during probe

In reply to Danilo Krummrich
Quoted 7 lines · Danilo Krummrich
Quoted 5 lines · John Hubbard

Allocate a single PCI MSI interrupt vector in the probe path.

Try MSI/MSI-X first. If that fails (possible in broken VFIO setups), fall back to INTx with a dev_warn so the issue is visible in dmesg. The allocation is devres-managed and automatically freed on unbind.

Quoted 7 lines

[...]

drivers/gpu/nova-core/irq.rs line 15

Quoted 2 lines
drivers/gpu/nova-core/irq.rs new file +2 -0
+pub(crate) fn alloc_vector(pdev: &pci::Device<Bound>) -> Result<pci::IrqVector<'_>> {
+    let msi_types = IrqTypes::default().with(IrqType::Msi).with(IrqType::MsiX);

I was about to ask if we really need to bother with MSI and shouln't just go for MSI-X only.

I have an expensive, recent motherboard in my test machine, and it seems to only expose MSI for my Turing, Ampere and Blackwell GPUs, in the non-SRIOV configuration. So I'm thinking that MSI-X only would not work.

Quoted 3 lines

But then saw that the commit message mentions broken VFIO setups; can you expand on this a bit? Which setups is the commit message referring to?

On Zhi Wang's Big Branch of Everything, he is able to run Windows guests in a vGPU VM on top of nova-core. That system requires MSI-X. And I broke it with an earlier internal version of this patchset.

That information probably leaked into my commit message here. I can remove it. Because I don't think it is based on anything else.

Quoted 13 lines

drivers/gpu/nova-core/irq.rs line 26

Quoted 12 lines
drivers/gpu/nova-core/irq.rs new file +11 -0
+
+    let irq_vectors = match pdev.alloc_irq_vectors(1, 1, msi_types) {
+        Ok(vecs) => vecs,
+        Err(_) => {
+            dev_warn!(pdev.as_ref(), "MSI not available, falling back to INTx\n");
+            pdev.alloc_irq_vectors(1, 1, IrqTypes::default().with(IrqType::Intx))?
+        }
+    };
+
+    irq_vectors.vector(0)
+}

thanks,

Signature · 1 line
John Hubbard
maintainer
#17 lore raw

Re: [PATCH 04/17] gpu: nova-core: allocate PCI MSI vector during probe

Quoted 13 lines · John Hubbard
Quoted 12 lines · Danilo Krummrich
Quoted 5 lines · John Hubbard

Allocate a single PCI MSI interrupt vector in the probe path.

Try MSI/MSI-X first. If that fails (possible in broken VFIO setups), fall back to INTx with a dev_warn so the issue is visible in dmesg. The allocation is devres-managed and automatically freed on unbind.

[...]

Quoted 2 lines
drivers/gpu/nova-core/irq.rs new file +2 -0
+pub(crate) fn alloc_vector(pdev: &pci::Device<Bound>) -> Result<pci::IrqVector<'_>> {
+    let msi_types = IrqTypes::default().with(IrqType::Msi).with(IrqType::MsiX);
Quoted 6 lines
Quoted 2 lines

I was about to ask if we really need to bother with MSI and shouln't just go for MSI-X only.

I have an expensive, recent motherboard in my test machine, and it seems to only expose MSI for my Turing, Ampere and Blackwell GPUs, in the non-SRIOV configuration. So I'm thinking that MSI-X only would not work.

Interesting, I just checked one of my Ada and one of my Ampere GPUs and neither reports MSI-X in the capabilities. Other devices show up with MSI-X though...

Are we sure it's not an endpoint limitation? I really thought it's not.

Quoted 9 lines
Quoted 2 lines

But then saw that the commit message mentions broken VFIO setups; can you expand on this a bit? Which setups is the commit message referring to?

On Zhi Wang's Big Branch of Everything, he is able to run Windows guests in a vGPU VM on top of nova-core. That system requires MSI-X. And I broke it with an earlier internal version of this patchset.

That information probably leaked into my commit message here. I can remove it. Because I don't think it is based on anything else.

So I guess we can also drop the INTx fallback? AFAIK SR-IOV VFs won't work with INTx anyway.

Quoted 11 lines
Quoted 11 lines
Quoted 11 lines
drivers/gpu/nova-core/irq.rs new file +11 -0
+
+    let irq_vectors = match pdev.alloc_irq_vectors(1, 1, msi_types) {
+        Ok(vecs) => vecs,
+        Err(_) => {
+            dev_warn!(pdev.as_ref(), "MSI not available, falling back to INTx\n");
+            pdev.alloc_irq_vectors(1, 1, IrqTypes::default().with(IrqType::Intx))?
+        }
+    };
+
+    irq_vectors.vector(0)
+}
#18 lore raw

Re: [PATCH 04/17] gpu: nova-core: allocate PCI MSI vector during probe

Quoted 3 lines · Danilo Krummrich
Quoted 2 lines · John Hubbard
Quoted 1 line · Danilo Krummrich

On Sat Aug 8, 2026 at 5:11 AM CEST, John Hubbard wrote:

...

Quoted 11 lines
Quoted 6 lines
Quoted 2 lines

I was about to ask if we really need to bother with MSI and shouln't just go for MSI-X only.

I have an expensive, recent motherboard in my test machine, and it seems to only expose MSI for my Turing, Ampere and Blackwell GPUs, in the non-SRIOV configuration. So I'm thinking that MSI-X only would not work.

Interesting, I just checked one of my Ada and one of my Ampere GPUs and neither reports MSI-X in the capabilities. Other devices show up with MSI-X though...

Are we sure it's not an endpoint limitation? I really thought it's not.

I haven't really dug into it, because it seems very clear that regardless of the answer, we need to support both MSI and MSI-X in nova-core, right?

Quoted 8 lines
Quoted 8 lines
Quoted 3 lines

But then saw that the commit message mentions broken VFIO setups; can you expand on this a bit? Which setups is the commit message referring to?

On Zhi Wang's Big Branch of Everything, he is able to run Windows guests in a vGPU VM on top of nova-core. That system requires MSI-X. And I broke it with an earlier internal version of this patchset.

Quoted 6 lines
Quoted 2 lines

That information probably leaked into my commit message here. I can remove it. Because I don't think it is based on anything else.

So I guess we can also drop the INTx fallback? AFAIK SR-IOV VFs won't work with INTx anyway.

We could drop it. It's there mainly on General Principles, not because today's GPUs use it.

thanks,

Signature · 1 line
John Hubbard
maintainer
#19 lore raw

Re: [PATCH 04/17] gpu: nova-core: allocate PCI MSI vector during probe

Quoted 12 lines · John Hubbard
Quoted 3 lines · Danilo Krummrich
Quoted 2 lines · John Hubbard
Quoted 1 line · Danilo Krummrich

On Sat Aug 8, 2026 at 5:11 AM CEST, John Hubbard wrote:

...

Quoted 7 lines
Quoted 6 lines
Quoted 2 lines

I was about to ask if we really need to bother with MSI and shouln't just go for MSI-X only.

I have an expensive, recent motherboard in my test machine, and it seems to only expose MSI for my Turing, Ampere and Blackwell GPUs, in the non-SRIOV configuration. So I'm thinking that MSI-X only would not work.

Quoted 7 lines
Quoted 4 lines

Interesting, I just checked one of my Ada and one of my Ampere GPUs and neither reports MSI-X in the capabilities. Other devices show up with MSI-X though...

Are we sure it's not an endpoint limitation? I really thought it's not.

I haven't really dug into it, because it seems very clear that regardless of the answer, we need to support both MSI and MSI-X in nova-core, right?

Apparently we do, and I'm a bit surprised by that. But it would still be interesting to know what's the constraint, as this seems to be an endpoint limitation. IOW, how can I exercise the MSI-X code?

Quoted 15 lines
Quoted 7 lines
Quoted 7 lines
Quoted 2 lines

But then saw that the commit message mentions broken VFIO setups; can you expand on this a bit? Which setups is the commit message referring to?

On Zhi Wang's Big Branch of Everything, he is able to run Windows guests in a vGPU VM on top of nova-core. That system requires MSI-X. And I broke it with an earlier internal version of this patchset.

Quoted 6 lines
Quoted 2 lines

That information probably leaked into my commit message here. I can remove it. Because I don't think it is based on anything else.

So I guess we can also drop the INTx fallback? AFAIK SR-IOV VFs won't work with INTx anyway.

We could drop it. It's there mainly on General Principles, not because today's GPUs use it.

#20 lore raw

Re: [PATCH 04/17] gpu: nova-core: allocate PCI MSI vector during probe

Quoted 16 lines · Danilo Krummrich
Quoted 15 lines · John Hubbard
Quoted 3 lines · Danilo Krummrich
Quoted 2 lines · John Hubbard
Quoted 1 line · Danilo Krummrich

On Sat Aug 8, 2026 at 5:11 AM CEST, John Hubbard wrote:

...

Quoted 10 lines
Quoted 6 lines
Quoted 2 lines

I was about to ask if we really need to bother with MSI and shouln't just go for MSI-X only.

I have an expensive, recent motherboard in my test machine, and it seems to only expose MSI for my Turing, Ampere and Blackwell GPUs, in the non-SRIOV configuration. So I'm thinking that MSI-X only would not work.

Interesting, I just checked one of my Ada and one of my Ampere GPUs and neither reports MSI-X in the capabilities. Other devices show up with MSI-X though...

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

Are we sure it's not an endpoint limitation? I really thought it's not.

I haven't really dug into it, because it seems very clear that regardless of the answer, we need to support both MSI and MSI-X in nova-core, right?

Apparently we do, and I'm a bit surprised by that. But it would still be interesting to know what's the constraint, as this seems to be an endpoint limitation. IOW, how can I exercise the MSI-X code?

I'm reasonably sure that it involves changing the BIOS settings, because that's how I enabled the vGPU case about a year or so ago, when I was verifying that this test machine could support the vGPU configuration.

And I vaguely recall some Kconfig settings as well.

At some point, the machine started reporting lots of VFs, instead just the PFs. But I don't remember what these each reported as far as MSI or MSI-X.

thanks,

Signature · 1 line
John Hubbard
maintainer
#21 lore raw

Re: [PATCH 04/17] gpu: nova-core: allocate PCI MSI vector during probe

In reply to John Hubbard
Quoted 11 lines · John Hubbard

From: Joel Fernandes <[email protected]>

Allocate a single PCI MSI interrupt vector in the probe path.

Try MSI/MSI-X first. If that fails (possible in broken VFIO setups), fall back to INTx with a dev_warn so the issue is visible in dmesg. The allocation is devres-managed and automatically freed on unbind.

I think this patch can just be dropped, the corresponding code is removed in patch 8 and AFAICS doesn't really serve a purpose in between.

#22 lore raw

Re: [PATCH 04/17] gpu: nova-core: allocate PCI MSI vector during probe

Quoted 9 lines · Danilo Krummrich
Quoted 8 lines · John Hubbard

From: Joel Fernandes <[email protected]>

Allocate a single PCI MSI interrupt vector in the probe path.

Try MSI/MSI-X first. If that fails (possible in broken VFIO setups), fall back to INTx with a dev_warn so the issue is visible in dmesg. The allocation is devres-managed and automatically freed on unbind.

Quoted 6 lines
Quoted 3 lines

I think this patch can just be dropped, the corresponding code is removed in patch 8 and AFAICS doesn't really serve a purpose in between.

OK, will do.

thanks,

Signature · 1 line
John Hubbard
#23 lore raw

PATCH 5/17 gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers

In reply to John Hubbard

GIN is the GPU's interrupt controller. It records interrupt sources in a two-level tree and signals the CPU over PCI when an enabled vector becomes pending. Add the CPU tree registers needed to receive GSP interrupts and to run the software-triggered interrupt self-test.

A pre-Hopper GPU that signals over MSI requires delivery to be rearmed after each interrupt, by a write to the MSI end-of-interrupt register. Add that register.

Assisted-by Cursor:claude-opus-5
---
 drivers/gpu/nova-core/regs.rs | 71 +++++++++++++++++++++++++++++++++++
 1 file changed, 71 insertions(+)
drivers/gpu/nova-core/regs.rs +71 -0
index caeef4d85874..1db92d36c5ac 100644
@@ -456,6 +456,64 @@ pub(crate) fn mem_scrubbing_done(self) -> bool {
     }
 }
 
+// GIN, the GPU's interrupt controller: the CPU interrupt tree.
+//
+// These registers are the two-level CPU interrupt tree at the
+// `NV_VIRTUAL_FUNCTION_PRIV` aperture (base `0x00b8_0000`), which any function
+// uses to reach its own tree. The leaf arrays have 16 entries, the widest tree
+// on any supported part. Pre-Hopper parts implement the first eight, and the
+// interrupt HAL supplies the count for a given architecture. See
+// `Documentation/gpu/nova/core/interrupts.rst`.
+
+register! {
+    /// Latched state of the 32 vectors that belong to one leaf, one bit per vector.
+    ///
+    /// A read yields the vectors currently latched in leaf `i`. Vector `v` occupies bit `v % 32`
+    /// of leaf `v / 32`. Each bit is write-1-to-clear, and a write of `0` does not affect the
+    /// value. Each bit must be cleared before its vector is serviced.
+    pub(crate) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF(u32)[16] @ 0x00b81000 {}
+
+    /// Enables individual vectors within one leaf.
+    ///
+    /// Each `1` written enables the matching vector for delivery to the CPU. Zero bits leave
+    /// their vector as it was.
+    pub(crate) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_EN_SET(u32)[16] @ 0x00b81200 {}
+
+    /// Disables individual vectors within one leaf.
+    ///
+    /// Each `1` written disables the matching vector. The enable governs delivery alone: a
+    /// disabled vector still latches in `LEAF`.
+    pub(crate) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_EN_CLEAR(u32)[16] @ 0x00b81400 {}
+
+    /// Enables whole subtrees at the top of the tree.
+    ///
+    /// Bit `N` covers subtree `N`, which spans leaves `2N` and `2N + 1`. Each `1` written enables
+    /// that subtree for delivery to the CPU, and zero bits leave their subtree as it was.
+    ///
+    /// Hardware defines a single-element array here, and its one element covers subtrees 0 through
+    /// 31, every subtree of the widest supported tree. nova-core declares it as a scalar.
+    pub(crate) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_SET(u32) @ 0x00b81608 {}
+
+    /// Disables whole subtrees at the top of the tree.
+    ///
+    /// Bit `N` covers subtree `N`. Each `1` written disables that subtree, and zero bits leave
+    /// their subtree as it was.
+    ///
+    /// Hardware defines a single-element array here, and its one element covers subtrees 0 through
+    /// 31, every subtree of the widest supported tree. nova-core declares it as a scalar.
+    pub(crate) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_CLEAR(u32) @ 0x00b81610 {}
+
+    /// Latches a vector from software.
+    ///
+    /// The vector named in the `vector` field latches in its `LEAF` register exactly as a hardware
+    /// source would latch it, and then reaches the CPU under the same enable conditions. The
+    /// register is write-only. Every supported part implements it.
+    pub(crate) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_TRIGGER(u32) @ 0x00b81640 {
+        /// Vector to latch.
+        11:0    vector;
+    }
+}
+
 // The modules below provide registers that are not identical on all supported chips. They should
 // only be used in HAL modules.
 
@@ -471,6 +529,19 @@ pub(crate) mod gm107 {
     }
 }
 
+pub(crate) mod tu102 {
+    use kernel::io::register;
+
+    // PCI configuration-space mirror.
+
+    register! {
+        /// MSI end-of-interrupt register.
+        ///
+        /// A `u32` write rearms MSI delivery on pre-Hopper GPUs. The value is ignored.
+        pub(crate) NV_XVE_CYA_2(u32) @ 0x0008_8704 {}
+    }
+}
+
 pub(crate) mod ga100 {
     use kernel::io::register;
 
Signature · 1 line
2.55.0
maintainer
#24 lore raw

Re: [PATCH 05/17] gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers

Quoted 1 line · John Hubbard

+register! {

[...]

Quoted 1 line

+}

I think all of those should only be required from irq/, so let's move them to irq/regs.rs

#25 lore raw

Re: [PATCH 05/17] gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers

Quoted 9 lines · Danilo Krummrich
Quoted 1 line · John Hubbard

+register! {

[...]

Quoted 1 line

+}

I think all of those should only be required from irq/, so let's move them to irq/regs.rs

OK, will do.

thanks,

Signature · 1 line
John Hubbard
#26 lore raw

PATCH 6/17 gpu: nova-core: add the GIN interrupt tree API

In reply to John Hubbard

From: Joel Fernandes <[email protected]>

Servicing a GIN leaf has a required order: read its pending bits, then clear them. Clearing a leaf before reading it discards every vector latched in it, and nothing reports the loss.

Add an API for one PCIe function's CPU interrupt tree. The leaf handle carries that order as a type state, so the wrong order does not compile.

The CPU doorbell self-test added later in this series is the first user.

[jhubbard: use the canonical NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*
register names, name the module interrupt_tree with a Tree type, drop the type state from the Top handle, take the leaf count from the chipset, define the vector encoding here, reject a trigger for a vector outside the tree, and read every implemented leaf in drain() rather than descending from the TOP registers, which cannot see a vector that latched while disabled]

---
 drivers/gpu/nova-core/irq.rs                |   2 +
 drivers/gpu/nova-core/irq/interrupt_tree.rs | 257 ++++++++++++++++++++
 drivers/gpu/nova-core/nova_core.rs          |   1 +
 3 files changed, 260 insertions(+)
 create mode 100644 drivers/gpu/nova-core/irq/interrupt_tree.rs
drivers/gpu/nova-core/irq.rs +2 -0
index 48900c734cb6..b70efc239334 100644
@@ -11,6 +11,8 @@
     prelude::*,
 };
 
+mod interrupt_tree;
+
 pub(crate) fn alloc_vector(pdev: &pci::Device<Bound>) -> Result<pci::IrqVector<'_>> {
     let msi_types = IrqTypes::default().with(IrqType::Msi).with(IrqType::MsiX);
 
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +257 -0

257 lines not on this page · raw message

drivers/gpu/nova-core/nova_core.rs +1 -0
index 68b5abfe494d..dfd11dfe562c 100644
@@ -17,6 +17,7 @@
 mod fsp;
 mod gpu;
 mod gsp;
+#[expect(dead_code)]
 mod irq;
 mod mctp;
 #[macro_use]
Signature · 1 line
2.55.0
maintainer
#27 lore raw

Re: [PATCH 06/17] gpu: nova-core: add the GIN interrupt tree API

Quoted 13 lines · John Hubbard

From: Joel Fernandes <[email protected]>

Servicing a GIN leaf has a required order: read its pending bits, then clear them. Clearing a leaf before reading it discards every vector latched in it, and nothing reports the loss.

Add an API for one PCIe function's CPU interrupt tree. The leaf handle carries that order as a type state, so the wrong order does not compile.

The CPU doorbell self-test added later in this series is the first user.

Quoted 8 lines

[jhubbard: use the canonical NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*
register names, name the module interrupt_tree with a Tree type, drop the type state from the Top handle, take the leaf count from the chipset, define the vector encoding here, reject a trigger for a vector outside the tree, and read every implemented leaf in drain() rather than descending from the TOP registers, which cannot see a vector that latched while disabled]

It would make more sense if this patch is merged into patch 8 after the HAL is introduced in patch 7.

(The newtypes mentioned below need their own commit first though, as they'd also be used by the HAL.)

Quoted 12 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +12 -0
+/// Index of a leaf register, bounded to the `0..16` range covered by the leaf register arrays.
+pub(super) type LeafIndex = Bounded<usize, 4>;
+
+/// Maps an interrupt `vector` to its position in the tree: the leaf that carries it
+/// (`vector / 32`) and the bit index within that leaf (`vector % 32`).
+///
+/// The returned leaf is a raw index. [`LeafIndex::try_new`] bounds it to the leaf register
+/// arrays, and the architecture's leaf count is a separate, narrower bound.
+pub(super) const fn vector_leaf_bit(vector: u32) -> (usize, u32) {
+    (crate::num::u32_as_usize(vector / 32), vector % 32)
+}
+

drivers/gpu/nova-core/irq/interrupt_tree.rs line 59

Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +10 -0
+/// Maps an interrupt `vector` to the `TOP` enable mask of the subtree that carries it.
+///
+/// A subtree covers two adjacent leaves, so the vector's leaf is in subtree `vector / 64`. The
+/// result has that subtree's bit set, in the form `TOP_EN_SET` and `TOP_EN_CLEAR` take as a
+/// value.
+///
+/// The result is not validated against the subtrees that the architecture supports.
+pub(super) const fn vector_subtree_mask(vector: u32) -> u32 {
+    1 << (vector / 64)
+}

I think we use new types for those. I'm thinking of:

	struct GinVector(u32);

	impl GinVector {
	    const fn leaf_index(&self) -> LeafIndex { ... }
	    const fn leaf_mask(&self) -> LeafMask { ... }
	    const fn subtree(&self) -> Subtree { ... }
	}

With additional new types LeafMask and Subtree.

This removes the need for

	const GSP_LEAF: usize = GSP_LOC.0;
	const GSP_BIT: u32 = 1 << GSP_LOC.1;

and subsequent

	LeafIndex::new::<GSP_LEAF>()

Subtree should represent a single TOP bit produced by GinVector::subtree().

This way Subtree already carries the invariant we need and we get rid of the runtime count_ones() check in SubtreeVectors::request_for().

The semantics of serviced is different and can be represented by a SubtreeSet type, so the check becomes serviced.contains(subtree).

Now, there's already an existing Subtree type, which represents an index. But I think we should just get rid of it, as it doesn't really add any value. The two methods it implements, iter_leaves() and iter_pending_leaves(), are rather Tree methods.

If we add Subtree::index() they can still take a Subtree argument, but I'm not sure it's worth. They are only called by drain(), which creates this new type from a raw value, just to immediately convert it back to a raw value. So, here I'd just work with the raw value.

Quoted 6 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +6 -0
+
+/// Type state of a [`Leaf`] handle: `Idle` before its pending bits are read, `Pending` after.
+pub(super) trait State: private::Sealed {}
+
+/// State in which the handle holds no pending bits.
+pub(super) struct Idle;

drivers/gpu/nova-core/irq/interrupt_tree.rs line 75

Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +10 -0
+impl State for Idle {}
+
+/// State holding the pending bits read from hardware.
+pub(super) struct Pending {
+    pending_bits: u32,
+}
+impl State for Pending {}
+
+mod private {
+    pub(in crate::irq) trait Sealed {}

This can just be pub.

drivers/gpu/nova-core/irq/interrupt_tree.rs line 81

Quoted 6 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +6 -0
+    impl Sealed for super::Idle {}
+    impl Sealed for super::Pending {}
+}
+
+/// The GIN CPU interrupt tree for a single PCIe function.
+#[derive(Clone)]

I think we don't need Clone on this, I know it is used in the doorbell test, but we can simplify the doorbell test significantly by getting rid of the custom SelftestGuard and replace it with

	struct SelftestResources<'a, 'r> {
	    _leaf_guard: LeafEnableGuard<'a>,
	    reg: Pin<KBox<irq::Registration<'r, DoorbellTestHandler<'a>>>>,
	    _top_guard: TopEnableGuard<'a>,
	}

Note that a LeafEnableGuard will also be very useful for the GspIrq introduced later.

	pub(crate) struct GspIrq<'a> {
	    #[pin]
	    reg: irq::ThreadedRegistration<'a, GspInterrupt<'a>>,
	    bar: Bar0<'a>,
	    tree: Tree,
	}

just becomes

	pub(crate) struct GspIrq<'a> {
	    _leaf_guard: LeafEnableGuard<'a>,
	    #[pin]
	    reg: irq::ThreadedRegistration<'a, GspInterrupt<'a>>,
	}

And the open-coded destructor of GspIrq goes away.

drivers/gpu/nova-core/irq/interrupt_tree.rs line 84

Quoted 3 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +3 -0
+pub(super) struct Tree {
+    /// Number of implemented leaves in this tree, either 8 or 16.
+    num_leaves: usize,

If it is really just one or the other, maybe worth to consider something like:

	#[repr(usize)]
	enum LeafCount {
	    Eight = 8,
	    Sixteen = 16,
	}
	
	impl LeafCount {
	    const fn into_raw(self) -> usize {
	        self as usize
	    }
	
	    const fn subtree_count(self) -> usize {
	        self.into_raw() / 2
	    }

	    const fn subtree_set(self) -> SubtreeSet {
	        SubtreeSet((1u32 << self.subtree_count()) - 1)
	    }
	}

A HAL can then only ever pick an expected leaf count.

drivers/gpu/nova-core/irq/interrupt_tree.rs line 86

Quoted 2 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +2 -0
+    /// Mask of subtree bits the architecture implements.
+    subtree_mask: u32,

This should be SubtreeSet.

Quoted 28 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +28 -0
+}
+
+impl Tree {
+    /// Creates a `Tree` sized for `chipset`.
+    pub(super) fn new(chipset: Chipset) -> Self {
+        let num_leaves = match chipset.arch() {
+            Architecture::Turing | Architecture::Ampere | Architecture::Ada => 8,
+            Architecture::Hopper | Architecture::BlackwellGB10x | Architecture::BlackwellGB20x => {
+                16
+            }
+        };
+
+        Self {
+            num_leaves,
+            // Each subtree covers two leaves, so one bit per pair of leaves.
+            subtree_mask: (1u32 << (num_leaves / 2)) - 1,
+        }
+    }
+
+    /// Returns a [`Top`] handle for this tree.
+    pub(super) fn top(&self) -> Top {
+        Top {
+            subtree_mask: self.subtree_mask,
+        }
+    }
+
+    /// Returns a [`Leaf`] handle in the [`Idle`] state for `index`.
+    pub(super) fn leaf(&self, index: LeafIndex) -> Leaf<Idle> {

drivers/gpu/nova-core/irq/interrupt_tree.rs line 124

Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +10 -0
+        Leaf::from_index(index)
+    }
+
+    /// Injects a software interrupt for `vector` via the trigger register.
+    ///
+    /// # Errors
+    ///
+    /// `EINVAL` if `vector` lies outside this tree (`vector >= num_leaves * 32`). `EOVERFLOW` if
+    /// `vector` does not fit in the trigger register's vector field.
+    pub(super) fn trigger(&self, bar: Bar0<'_>, vector: u32) -> Result {

Most methods take a Bar0 argument. I think it would be cleaner if the Tree constructor would just take a Bar0 and store it within the tree.

In case this gets into the way of some tests, we can also have a TreeInner type.

Quoted 1 line

+ if crate::num::u32_as_usize(vector) >= self.num_leaves * 32 {

This check could be replaced by:

	impl GinVector {
	    const fn validate(self, leaves: LeafCount) -> Result {
	        if self.as_raw() >= leaves.vector_count() { return Err(EINVAL) }
	        Ok(())
	    }
	}

so this becomes

	vector.validate(self.leaf_count)?;
Quoted 19 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +19 -0
+/// View of a single interrupt leaf.
+pub(super) struct Leaf<S: State = Idle> {
+    index: LeafIndex,
+    state: S,
+}
+
+// The `try_at(...)` calls below cannot fail: `LeafIndex` is `Bounded<usize, 4>`, so its value is
+// in 0..16, and every leaf register array has 16 elements.
+impl Leaf<Idle> {
+    /// Creates a [`Leaf`] handle for `index`.
+    pub(super) fn from_index(index: LeafIndex) -> Self {
+        Leaf { index, state: Idle }
+    }
+
+    /// Enables the vectors set in `vectors` for this leaf (`LEAF_EN_SET`).
+    ///
+    /// This is the per-vector counterpart of [`Top::enable`], which enables a whole subtree.
+    pub(super) fn enable(&self, bar: Bar0<'_>, vectors: u32) {
+        if let Some(loc) = CPU_INTR_LEAF_EN_SET::try_at(self.index.get()) {

drivers/gpu/nova-core/irq/interrupt_tree.rs line 229

Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +10 -0
+            bar.write(loc, vectors.into());
+        }
+    }
+
+    /// Disables the vectors set in `vectors` for this leaf (`LEAF_EN_CLEAR`).
+    pub(super) fn disable(&self, bar: Bar0<'_>, vectors: u32) {
+        if let Some(loc) = CPU_INTR_LEAF_EN_CLEAR::try_at(self.index.get()) {
+            bar.write(loc, vectors.into());
+        }
+    }

IIUC, the type state exists only to guard clear_pending() from being called before read_pending() has been called?

In this case, enable() and disable() are orthogonal and do not participate in the state machine.

If that holds, I'd probably move enable(), disable() and enable_guarded() to Tree or just remove the type state and make Leaf<Pending> a new type. (One can obtain a new Leaf<Idle> while still having a Leaf<Pending> anyways.)

Also, does the type state really properly fulfill its purpose? Once I called read_pending() once I can hold on to Leaf<Pending> for as long as I want and call clear_pending() for as often as I want, right?

I think the idea is that the read_pending() then clear_pending() sequence must run within the interrupt handler?

So, I assume that we rather want read_pending() to take a token that only lives for irq::ThreadedHandler::handle() and have a LeafPending that borrows from this token?

I wonder if the core IRQ code should provide such a token in handle() and handle_threaded().

This way we can enforce that certain things can only be executed in an IRQ handler and that certain sequences like read and clear pending must complete within a single execution of an IRQ.

Quoted 28 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +28 -0
+
+    /// Reads this leaf's pending bits and transitions to [`Pending`].
+    pub(super) fn read_pending(self, bar: Bar0<'_>) -> Leaf<Pending> {
+        let pending_bits = CPU_INTR_LEAF::try_at(self.index.get())
+            .map(|loc| bar.read(loc).into_raw())
+            .unwrap_or(0);
+        Leaf {
+            index: self.index,
+            state: Pending { pending_bits },
+        }
+    }
+}
+
+impl Leaf<Pending> {
+    /// Returns the pending bits read from hardware.
+    pub(super) fn pending_bits(&self) -> u32 {
+        self.state.pending_bits
+    }
+
+    /// Clears every pending vector by writing its bits back (write-1-to-clear).
+    pub(super) fn clear_pending(&self, bar: Bar0<'_>) {
+        if self.state.pending_bits != 0 {
+            if let Some(loc) = CPU_INTR_LEAF::try_at(self.index.get()) {
+                bar.write(loc, self.state.pending_bits.into());
+            }
+        }
+    }
+}
#28 lore raw

PATCH 7/17 gpu: nova-core: add the per-architecture GIN CPU interrupt HAL

In reply to John Hubbard

GIN, the GPU Interrupt and Notification unit, is the GPU's interrupt controller. Each PCIe function has its own tree, whose leaf count depends on the GPU family.

Message-signaled delivery stops after each edge until the CPU rearms it, and the rearm write differs by family and interrupt type:

* Pre-Hopper MSI writes an EOI through the BAR0 PCI configuration space mirror.

* MSI for Hopper and later cycles the TOP enable bits of every serviced subtree.

* MSI-X on any family cycles the bits of the handler's own subtree.

Provide the leaf count and the rearm method through a per-architecture interrupt HAL.

Assisted-by Cursor:claude-opus-5
---
 drivers/gpu/nova-core/irq.rs           |  12 ++-
 drivers/gpu/nova-core/irq/hal.rs       | 113 +++++++++++++++++++++++++
 drivers/gpu/nova-core/irq/hal/gh100.rs |  30 +++++++
 drivers/gpu/nova-core/irq/hal/tu102.rs |  29 +++++++
 4 files changed, 182 insertions(+), 2 deletions(-)
 create mode 100644 drivers/gpu/nova-core/irq/hal.rs
 create mode 100644 drivers/gpu/nova-core/irq/hal/gh100.rs
 create mode 100644 drivers/gpu/nova-core/irq/hal/tu102.rs
drivers/gpu/nova-core/irq.rs +10 -2
index b70efc239334..ef77066e0514 100644
@@ -1,6 +1,16 @@
 // SPDX-License-Identifier: GPL-2.0
 // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
+//! GPU interrupt support.
+//!
+//! GIN, the GPU Interrupt and Notification unit, is the GPU's interrupt controller: a two-level
+//! tree of pending and enable registers, one tree per PCIe function.
+//!
+//! See `Documentation/gpu/nova/core/interrupts.rst`.
+
+mod hal;
+mod interrupt_tree;
+
 use kernel::{
     device::Bound,
     pci::{
@@ -11,8 +21,6 @@
     prelude::*,
 };
 
-mod interrupt_tree;
-
 pub(crate) fn alloc_vector(pdev: &pci::Device<Bound>) -> Result<pci::IrqVector<'_>> {
     let msi_types = IrqTypes::default().with(IrqType::Msi).with(IrqType::MsiX);
 
drivers/gpu/nova-core/irq/hal.rs new file +113 -0

113 lines not on this page · raw message

drivers/gpu/nova-core/irq/hal/gh100.rs new file +30 -0
new file mode 100644
index 000000000000..69bd092e38b5
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use kernel::pci::IrqType;
+
+use super::{
+    CpuInterruptHal,
+    PciIrqRearmMethod, //
+};
+
+/// GIN parameters for Hopper and Blackwell, which implement a 16-leaf CPU tree. Only 12 leaves
+/// carry sources.
+struct Gh100;
+
+impl CpuInterruptHal for Gh100 {
+    fn num_leaves(&self) -> usize {
+        16
+    }
+
+    fn pci_irq_rearm_method(&self, irq_type: IrqType) -> Option<PciIrqRearmMethod> {
+        match irq_type {
+            IrqType::Intx => None,
+            IrqType::Msi => Some(PciIrqRearmMethod::TopEnableCycleServiced),
+            IrqType::MsiX => Some(PciIrqRearmMethod::TopEnableCycleSubtree),
+        }
+    }
+}
+
+const GH100: Gh100 = Gh100;
+pub(super) const GH100_HAL: &dyn CpuInterruptHal = &GH100;
drivers/gpu/nova-core/irq/hal/tu102.rs new file +29 -0
new file mode 100644
index 000000000000..590f0dc9a701
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use kernel::pci::IrqType;
+
+use super::{
+    CpuInterruptHal,
+    PciIrqRearmMethod, //
+};
+
+/// GIN parameters for Turing, Ampere, and Ada, which implement an 8-leaf CPU tree.
+struct Tu102;
+
+impl CpuInterruptHal for Tu102 {
+    fn num_leaves(&self) -> usize {
+        8
+    }
+
+    fn pci_irq_rearm_method(&self, irq_type: IrqType) -> Option<PciIrqRearmMethod> {
+        match irq_type {
+            IrqType::Intx => None,
+            IrqType::Msi => Some(PciIrqRearmMethod::ConfigMirrorEoi),
+            IrqType::MsiX => Some(PciIrqRearmMethod::TopEnableCycleSubtree),
+        }
+    }
+}
+
+const TU102: Tu102 = Tu102;
+pub(super) const TU102_HAL: &dyn CpuInterruptHal = &TU102;
Signature · 1 line
2.55.0
#29 lore raw

PATCH 8/17 gpu: nova-core: allocate interrupt vectors for the serviced subtrees

In reply to John Hubbard

Every subtree nova-core enables at TOP needs an allocated PCI vector with a handler on it. How many vectors that takes depends on the type the PCI core grants. MSI has one message that every subtree raises, so one vector serves the whole tree. MSI-X gives each subtree its own table entry, and Linux masks every entry a driver does not allocate. A serviced subtree with no entry of its own loses the interrupts it raises, while its GIN leaf and TOP bits read pending and enabled.

nova-core allocated one vector at probe, and the tree enabled every implemented subtree.

Size the allocation to the serviced set: MSI-X entries up to the highest serviced subtree, falling back to a single MSI. Drop the INTx fallback, since nova-core does not share a level-triggered line. Enable only the serviced subtrees at TOP, and take the leaf count and the rearm method from the interrupt HAL when the tree is built.

Assisted-by Cursor:claude-opus-5
---
 drivers/gpu/nova-core/gpu.rs                |  6 --
 drivers/gpu/nova-core/irq.rs                | 78 ++++++++++++++++++---
 drivers/gpu/nova-core/irq/hal.rs            |  2 -
 drivers/gpu/nova-core/irq/interrupt_tree.rs | 68 +++++++++++-------
 4 files changed, 111 insertions(+), 43 deletions(-)
drivers/gpu/nova-core/gpu.rs +0 -6
index 5efeba056f1b..42a4cd7971fa 100644
@@ -29,7 +29,6 @@
         Gsp,
         GspBootContext, //
     },
-    irq,
     regs,
     vgpu::VgpuManager, //
 };
@@ -387,11 +386,6 @@ pub(crate) fn new(
                 })?,
             }),
 
-            // Allocate a PCI interrupt vector.
-            _: {
-                let _irq_vector = irq::alloc_vector(pdev)?;
-            },
-
             gsp_static_info: {
                 // Obtain and display basic GPU information.
                 let info = gsp_resources.gsp.get_static_info(bar)?;
drivers/gpu/nova-core/irq.rs +69 -9

85 lines not on this page · raw message

drivers/gpu/nova-core/irq/hal.rs +0 -2
index 8de2f6e536c2..cf2d1aa080fa 100644
@@ -50,7 +50,6 @@ impl PciIrqRearmMethod {
     /// `serviced` holds the `TOP` bit of every subtree the driver services, and `subtree` holds
     /// the bit of the one subtree the calling handler serves. Each method uses whichever of the
     /// two its interrupt type delivers on, so both are required.
-    #[expect(dead_code)]
     pub(super) fn rearm(self, bar: Bar0<'_>, serviced: u32, subtree: u32) {
         let subtrees = match self {
             // The written value is ignored, so any write rearms delivery.
@@ -98,7 +97,6 @@ fn implemented_subtrees(&self) -> u32 {
     ///
     /// `None` means that `irq_type` needs no rearm write. That is the case for `INTx`, which is
     /// level-triggered, and which nova-core does not allocate.
-    #[expect(dead_code)]
     fn pci_irq_rearm_method(&self, irq_type: IrqType) -> Option<PciIrqRearmMethod>;
 }
 
drivers/gpu/nova-core/irq/interrupt_tree.rs +42 -26

115 lines not on this page · raw message

Signature · 1 line
2.55.0
#30 lore raw

PATCH 9/17 gpu: nova-core: add an interrupt delivery self-test

In reply to John Hubbard

A GPU interrupt can be lost in the MSI or MSI-X allocation, in the GIN tree's enable bits, or in the rearm. Every one of those failures looks the same to the driver: no interrupt arrives, and nothing in the symptom says which one broke.

Add an optional probe-time self-test that injects the CPU doorbell through the GIN software trigger. One injection would pass even with a broken rearm, because the first message-signaled interrupt arrives whether the driver rearms or not. The test injects twice, and waits for the first handler to rearm before it injects again.

Run it before GSP boot on a quiesced tree, and fail probe unless exactly two deliveries arrive, each delivery finds only the doorbell pending, and the leaf ends clear. Under MSI-X the injected subtree has its own table entry, so the delivery exercises that entry too.

---
 drivers/gpu/nova-core/Kconfig               |  15 +
 drivers/gpu/nova-core/gpu.rs                |   8 +
 drivers/gpu/nova-core/irq.rs                |   2 +
 drivers/gpu/nova-core/irq/doorbell_test.rs  | 324 ++++++++++++++++++++
 drivers/gpu/nova-core/irq/interrupt_tree.rs |  13 +
 drivers/gpu/nova-core/nova_core.rs          |   2 +-
 6 files changed, 363 insertions(+), 1 deletion(-)
 create mode 100644 drivers/gpu/nova-core/irq/doorbell_test.rs
drivers/gpu/nova-core/Kconfig +15 -0
index f918f69e0599..7198fae6b6f4 100644
@@ -15,3 +15,18 @@ config NOVA_CORE
 	  This driver is work in progress and may not be functional.
 
 	  If M is selected, the module will be called nova-core.
+
+config NOVA_CORE_IRQ_SELFTEST
+	bool "Nova Core interrupt delivery self-test"
+	depends on NOVA_CORE
+	help
+	  Run an interrupt delivery self-test during nova-core probe. It
+	  injects a known vector through the GPU interrupt controller's
+	  software trigger and confirms the interrupt reaches the driver's
+	  handler, validating the PCI interrupt path from the GPU to the CPU
+	  with no dependency on GSP firmware. The result is printed to dmesg.
+
+	  If the test fails, the PCI probe fails and the driver does not load.
+
+	  This is intended for driver bring-up and for debugging PCI, MSI, or
+	  passthrough setups. If unsure, say N.
drivers/gpu/nova-core/gpu.rs +8 -0
index 42a4cd7971fa..d5df0ebf67ae 100644
@@ -347,6 +347,14 @@ pub(crate) fn new(
                     .inspect_err(|_| dev_err!(dev, "GFW boot did not complete\n"))?;
             },
 
+            // Validate the MSI interrupt path before booting GSP, when the self-test is
+            // enabled. This runs on a quiesced interrupt tree with no GSP state present, so it
+            // never observes or clears GSP or PRIV_RING interrupts.
+            _: {
+                #[cfg(CONFIG_NOVA_CORE_IRQ_SELFTEST)]
+                crate::irq::doorbell_test::run_selftest(pdev, bar, spec.chipset)?;
+            },
+
             // Initialize this early because `gsp_resources` depends on it.
             sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?,
 
drivers/gpu/nova-core/irq.rs +2 -0
index 2f0e2644b9bd..5b449759b333 100644
@@ -8,6 +8,8 @@
 //!
 //! See `Documentation/gpu/nova/core/interrupts.rst`.
 
+#[cfg(CONFIG_NOVA_CORE_IRQ_SELFTEST)]
+pub(crate) mod doorbell_test;
 mod hal;
 mod interrupt_tree;
 
drivers/gpu/nova-core/irq/doorbell_test.rs new file +324 -0

324 lines not on this page · raw message

drivers/gpu/nova-core/irq/interrupt_tree.rs +13 -0
index 51add9f33c89..73f5afadea3e 100644
@@ -270,4 +270,17 @@ pub(super) fn clear_pending(&self, bar: Bar0<'_>) {
             }
         }
     }
+
+    /// Clears the vectors set in `vectors` (write-1-to-clear), leaving every other pending bit
+    /// set.
+    ///
+    /// A handler that services one vector uses this rather than [`Self::clear_pending`], which
+    /// clears every vector the leaf had pending.
+    pub(super) fn clear_vectors(&self, bar: Bar0<'_>, vectors: u32) {
+        if vectors != 0 {
+            if let Some(loc) = CPU_INTR_LEAF::try_at(self.index.get()) {
+                bar.write(loc, vectors.into());
+            }
+        }
+    }
 }
drivers/gpu/nova-core/nova_core.rs +1 -1
index dfd11dfe562c..65ce547bd44e 100644
@@ -17,7 +17,7 @@
 mod fsp;
 mod gpu;
 mod gsp;
-#[expect(dead_code)]
+#[cfg_attr(not(CONFIG_NOVA_CORE_IRQ_SELFTEST), expect(dead_code))]
 mod irq;
 mod mctp;
 #[macro_use]
Signature · 1 line
2.55.0
#31 lore raw

PATCH 10/17 gpu: nova-core: dispatch GSP events instead of discarding them

In reply to John Hubbard

The GSP posts unsolicited messages onto the same queue that carries command replies: logs, OS error and robust-channel records, and lifecycle notices.

Anything that was not the reply a caller awaited was discarded, and an unrecognized function code aborted the in-flight command, so the GSP's error reports never reached the log.

Route every non-reply message to a dispatcher, which logs the error records and leaves the in-flight command waiting for its reply. The dispatch runs on the existing command and wait loops, so events are handled during normal operation before any interrupt exists. Event payloads, such as XID numbers and log contents, are not decoded.

Assisted-by Cursor:claude-opus-5
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 64 ++++++++++++++++++++++++-------
 1 file changed, 51 insertions(+), 13 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +51 -13
index f0f28b6ded7a..0df52df1da89 100644
@@ -547,11 +547,11 @@ fn notify_gsp(bar: Bar0<'_>) {
 
     /// Sends `command` to the GSP and waits for the reply.
     ///
-    /// Messages with non-matching function codes are silently consumed until the expected reply
-    /// arrives.
+    /// A message read while waiting that is not the reply goes to
+    /// [`CmdqInner::dispatch_event`].
     ///
-    /// The queue is locked for the entire send+receive cycle to ensure that no other command can
-    /// be interleaved.
+    /// The queue is locked for the entire send+receive cycle, so no other command can be
+    /// interleaved.
     ///
     /// # Errors
     ///
@@ -805,8 +805,10 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
 
     /// Receive a message from the GSP.
     ///
-    /// The expected message type is specified using the `M` generic parameter. If the pending
-    /// message has a different function code, `ERANGE` is returned and the message is consumed.
+    /// The expected message type is specified using the `M` generic parameter. A message whose
+    /// function code matches is decoded and returned. Any other message, whether its function code
+    /// is a different one or is unrecognized, goes to [`Self::dispatch_event`] and `ERANGE` is
+    /// returned.
     ///
     /// The read pointer is always advanced past the message, regardless of whether it matched.
     ///
@@ -815,8 +817,7 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
     /// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available.
     /// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the
     ///   message queue.
-    /// - `EINVAL` if the function code of the message was not recognized.
-    /// - `ERANGE` if the message had a recognized but non-matching function code.
+    /// - `ERANGE` if the message was not the awaited reply.
     ///
     /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
     fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
@@ -825,11 +826,13 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
         Error: From<M::InitError>,
     {
         let message = self.wait_for_msg(timeout)?;
-        let function = message.header.function().map_err(|_| EINVAL)?;
+        let function = message.header.function();
+        let seq = message.header.sequence();
+        let matched = matches!(function, Ok(f) if f == M::FUNCTION);
 
-        // Extract the message. Store the result as we want to advance the read pointer even in
-        // case of failure.
-        let result = if function == M::FUNCTION {
+        // Bind the result rather than returning early. The read pointer must advance past this
+        // message on every path.
+        let result = if matched {
             let (cmd, contents_1) = M::Message::from_bytes_prefix(message.contents.0).ok_or(EIO)?;
             let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]);
 
@@ -840,7 +843,7 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
                         dev_warn!(
                             &self.dev,
                             "GSP message {:?} has unprocessed data\n",
-                            function
+                            M::FUNCTION
                         );
                     }
                 })
@@ -853,6 +856,41 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
             message.header.length().div_ceil(GSP_PAGE_SIZE),
         )?);
 
+        if !matched {
+            self.dispatch_event(function, seq);
+        }
+
         result
     }
+
+    /// Routes a GSP message that is not the reply a caller is waiting for.
+    ///
+    /// GSP-reported errors are logged at error level and unrecognized function codes at warning
+    /// level. Every other known function code is consumed without a log line, because the RPC
+    /// receive trace in [`Self::wait_for_msg`] already records its arrival.
+    fn dispatch_event(&self, function: Result<MsgFunction, u32>, seq: u32) {
+        match function {
+            Ok(MsgFunction::OsErrorLog) => {
+                dev_err!(&self.dev, "GSP reported an OS error (seq {})\n", seq);
+            }
+            Ok(MsgFunction::RcTriggered) => {
+                dev_err!(
+                    &self.dev,
+                    "GSP triggered robust-channel recovery (seq {})\n",
+                    seq
+                );
+            }
+            // GSP logs, libos prints, NoCat assertion records, and the other known event codes.
+            // None of them requires action.
+            Ok(_) => {}
+            Err(raw) => {
+                dev_warn!(
+                    &self.dev,
+                    "unknown GSP message function {:#x} (seq {})\n",
+                    raw,
+                    seq
+                );
+            }
+        }
+    }
 }
Signature · 1 line
2.55.0
#32 lore raw

PATCH 11/17 gpu: nova-core: match GSP RPC replies by sequence, not just function

In reply to John Hubbard

The GSP replies to a command by echoing that command's function code and its RPC sequence number.

nova-core matched replies on the function alone and never set the sequence, so a reply for a command that had already timed out could satisfy a later command using the same function.

Give the RPC sequence its own counter, separate from the per-element transport sequence, set it on every command, and require both the function and the sequence to match before accepting a reply. A message with the expected function but a stale sequence is logged and dropped, not mistaken for the reply or dispatched as an event. A caller awaiting an unsolicited event still matches on the function alone.

Assisted-by Cursor:claude-opus-5
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 89 ++++++++++++++++++++-----------
 drivers/gpu/nova-core/gsp/fw.rs   | 13 +++--
 2 files changed, 67 insertions(+), 35 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +59 -30
index 0df52df1da89..3224079abf7e 100644
@@ -521,7 +521,8 @@ pub(crate) fn new(dev: &device::Device<device::Bound>) -> impl PinInit<Self, Err
                 inner <- new_mutex!(CmdqInner {
                     dev: dev.into(),
                     gsp_mem,
-                    seq: 0,
+                    elem_seq: 0,
+                    rpc_seq: 0,
                 }),
             }))
         })
@@ -569,10 +570,10 @@ 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)?;
+        let expected_seq = inner.send_command(bar, command)?;
 
         loop {
-            match inner.receive_msg::<M::Reply>(Self::RECEIVE_TIMEOUT) {
+            match inner.receive_msg::<M::Reply>(Self::RECEIVE_TIMEOUT, Some(expected_seq)) {
                 Ok(reply) => break Ok(reply),
                 Err(ERANGE) => continue,
                 Err(e) => break Err(e),
@@ -594,18 +595,19 @@ pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul
         M: CommandToGsp<Reply = NoReply>,
         Error: From<M::InitError>,
     {
-        self.inner.lock().send_command(bar, command)
+        self.inner.lock().send_command(bar, command).map(|_| ())
     }
 
     /// Receive a message from the GSP.
     ///
-    /// See [`CmdqInner::receive_msg`] for details.
+    /// Matches on the function code alone, for a caller awaiting an unsolicited GSP event rather
+    /// than a reply to a command. See [`CmdqInner::receive_msg`].
     pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
     where
         // This allows all error types, including `Infallible`, to be used for `M::InitError`.
         Error: From<M::InitError>,
     {
-        self.inner.lock().receive_msg(timeout)
+        self.inner.lock().receive_msg(timeout, None)
     }
 }
 
@@ -613,8 +615,13 @@ pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
 struct CmdqInner {
     /// Device this command queue belongs to.
     dev: ARef<device::Device>,
-    /// Current command sequence number.
-    seq: u32,
+    /// Next transport sequence number for a queue element (the `seqNum` field). Advances once per
+    /// queue element, including each continuation record.
+    elem_seq: u32,
+    /// Next RPC sequence number. The GSP echoes it in a command's reply, which lets
+    /// [`CmdqInner::receive_msg`] match that reply to the awaiting command. Advances once per
+    /// logical command.
+    rpc_seq: u32,
     /// Memory area shared with the GSP for communicating commands and messages.
     gsp_mem: DmaGspMem,
 }
@@ -633,7 +640,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, bar: Bar0<'_>, command: M, rpc_seq: u32) -> Result
     where
         M: CommandToGsp,
         // This allows all error types, including `Infallible`, to be used for `M::InitError`.
@@ -650,7 +657,7 @@ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
         let (cmd, payload_1) = M::Command::from_bytes_mut_prefix(dst.contents.0).ok_or(EIO)?;
 
         // Fill the header and command in-place.
-        let msg_element = GspMsgElement::init(self.seq, size_in_bytes, M::FUNCTION);
+        let msg_element = GspMsgElement::init(self.elem_seq, rpc_seq, size_in_bytes, M::FUNCTION);
         // SAFETY: `msg_header` and `cmd` are valid references, and not touched if the initializer
         // fails.
         unsafe {
@@ -678,23 +685,25 @@ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
         dev_dbg!(
             &self.dev,
             "GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n",
-            self.seq,
+            rpc_seq,
             M::FUNCTION,
             dst.header.length(),
         );
 
         // All set - update the write pointer and inform the GSP of the new command.
         let elem_count = dst.header.element_count();
-        self.seq += 1;
+        self.elem_seq = self.elem_seq.wrapping_add(1);
         self.gsp_mem.advance_cpu_write_ptr(elem_count);
         Cmdq::notify_gsp(bar);
 
         Ok(())
     }
 
-    /// Sends `command` to the GSP.
+    /// Sends `command` to the GSP and returns the RPC sequence number assigned to it.
     ///
-    /// The command may be split into multiple messages if it is large.
+    /// The command may be split into multiple messages if it is large. The GSP echoes the
+    /// sequence number in the reply, so a caller passes it to [`Self::receive_msg`] to match the
+    /// reply to this command.
     ///
     /// # Errors
     ///
@@ -703,24 +712,26 @@ 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, bar: Bar0<'_>, command: M) -> Result<u32>
     where
         M: CommandToGsp,
         Error: From<M::InitError>,
     {
+        let rpc_seq = self.rpc_seq;
+        self.rpc_seq = self.rpc_seq.wrapping_add(1);
+
         match SplitState::new(command)? {
-            SplitState::Single(command) => self.send_single_command(bar, command),
+            SplitState::Single(command) => self.send_single_command(bar, command, rpc_seq)?,
             SplitState::Split(command, mut continuations) => {
-                self.send_single_command(bar, command)?;
+                self.send_single_command(bar, command, rpc_seq)?;
 
                 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<'_>>(bar, continuation, rpc_seq)?;
                 }
-
-                Ok(())
             }
         }
+
+        Ok(rpc_seq)
     }
 
     /// Wait for a message to become available on the message queue.
@@ -805,10 +816,14 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
 
     /// Receive a message from the GSP.
     ///
-    /// The expected message type is specified using the `M` generic parameter. A message whose
-    /// function code matches is decoded and returned. Any other message, whether its function code
-    /// is a different one or is unrecognized, goes to [`Self::dispatch_event`] and `ERANGE` is
-    /// returned.
+    /// The expected message type is given by the `M` generic parameter. With `expected_seq` set,
+    /// the message must also carry that RPC sequence number to count as the awaited reply. With
+    /// `None`, the function code alone decides the match.
+    ///
+    /// A matching message is decoded and returned. A message carrying the expected function code
+    /// with a different sequence is a stale reply to a command that already timed out, and is
+    /// logged and dropped. Any other message goes to [`Self::dispatch_event`]. Both non-matching
+    /// cases return `ERANGE`.
     ///
     /// The read pointer is always advanced past the message, regardless of whether it matched.
     ///
@@ -820,7 +835,11 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
     /// - `ERANGE` if the message was not the awaited reply.
     ///
     /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
-    fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
+    fn receive_msg<M: MessageFromGsp>(
+        &mut self,
+        timeout: Delta,
+        expected_seq: Option<u32>,
+    ) -> Result<M>
     where
         // This allows all error types, including `Infallible`, to be used for `M::InitError`.
         Error: From<M::InitError>,
@@ -828,10 +847,10 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
         let message = self.wait_for_msg(timeout)?;
         let function = message.header.function();
         let seq = message.header.sequence();
-        let matched = matches!(function, Ok(f) if f == M::FUNCTION);
+        let func_matches = matches!(function, Ok(f) if f == M::FUNCTION);
+        let matched = func_matches && expected_seq.is_none_or(|expected| seq == expected);
 
-        // Bind the result rather than returning early. The read pointer must advance past this
-        // message on every path.
+        // Every path must advance the read pointer past this message.
         let result = if matched {
             let (cmd, contents_1) = M::Message::from_bytes_prefix(message.contents.0).ok_or(EIO)?;
             let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]);
@@ -857,7 +876,17 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
         )?);
 
         if !matched {
-            self.dispatch_event(function, seq);
+            if func_matches {
+                dev_warn!(
+                    &self.dev,
+                    "GSP RPC: dropping stale {:?} reply (seq {}, awaiting {:?})\n",
+                    M::FUNCTION,
+                    seq,
+                    expected_seq,
+                );
+            } else {
+                self.dispatch_event(function, seq);
+            }
         }
 
         result
drivers/gpu/nova-core/gsp/fw.rs +8 -5
index 05f54fee6186..0b01c81ec092 100644
@@ -782,13 +782,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)
@@ -813,25 +814,27 @@ impl GspMsgElement {
     ///
     /// # Arguments
     ///
-    /// * `sequence` - Sequence number of the message.
+    /// * `elem_seq` - Transport sequence number of the queue element (`seqNum`).
+    /// * `rpc_seq` - RPC sequence number, echoed by the GSP in the reply.
     /// * `cmd_size` - Size of the command (not including the message element), in bytes.
     /// * `function` - Function of the message.
     pub(crate) fn init(
-        sequence: u32,
+        elem_seq: u32,
+        rpc_seq: u32,
         cmd_size: usize,
         function: MsgFunction,
     ) -> impl Init<Self, Error> {
         type RpcMessageHeader = bindings::rpc_message_header_v;
         type InnerGspMsgElement = bindings::GSP_MSG_QUEUE_ELEMENT;
         let init_inner = try_init!(InnerGspMsgElement {
-            seqNum: sequence,
+            seqNum: elem_seq,
             elemCount: size_of::<Self>()
                 .checked_add(cmd_size)
                 .ok_or(EOVERFLOW)?
                 .div_ceil(GSP_PAGE_SIZE)
                 .try_into()
                 .map_err(|_| EOVERFLOW)?,
-            rpc <- RpcMessageHeader::init(cmd_size, function),
+            rpc <- RpcMessageHeader::init(rpc_seq, cmd_size, function),
             ..Zeroable::init_zeroed()
         });
 
Signature · 1 line
2.55.0
#33 lore raw

PATCH 12/17 gpu: nova-core: recover the GSP receive path from corrupt framing

In reply to John Hubbard

A GSP message carries its length inside the checksummed region, so once the framing or the checksum fails, the length cannot be trusted to skip the message.

Two paths left a bad message at the queue head. A framing or checksum failure returned without advancing the read pointer, so every later receive re-parsed the same message. A validly framed message whose typed payload failed to decode returned early and did the same.

Poison the queue on a framing or checksum failure, and fail every later receive, so the bad head is parsed once and recovery requires a reset. Advance the read pointer past a validly framed message whether or not its payload decodes.

Assisted-by Cursor:claude-opus-5
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 63 ++++++++++++++++++++-----------
 1 file changed, 41 insertions(+), 22 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +41 -22
index 3224079abf7e..fc4c229b8b9a 100644
@@ -3,6 +3,7 @@
 mod continuation;
 
 use core::{
+    cell::Cell,
     mem,
     sync::atomic::{
         fence,
@@ -523,6 +524,7 @@ pub(crate) fn new(dev: &device::Device<device::Bound>) -> impl PinInit<Self, Err
                     gsp_mem,
                     elem_seq: 0,
                     rpc_seq: 0,
+                    poisoned: Cell::new(false),
                 }),
             }))
         })
@@ -622,6 +624,12 @@ struct CmdqInner {
     /// [`CmdqInner::receive_msg`] match that reply to the awaiting command. Advances once per
     /// logical command.
     rpc_seq: u32,
+    /// Set once a message with corrupt framing or a bad checksum is seen. Such a message has an
+    /// untrusted length, so the queue cannot be advanced past it, and every later receive fails
+    /// until the queue is torn down and reset.
+    ///
+    /// A [`Cell`], so the shared-borrow read path [`Self::wait_for_msg`] can set it.
+    poisoned: Cell<bool>,
     /// Memory area shared with the GSP for communicating commands and messages.
     gsp_mem: DmaGspMem,
 }
@@ -748,11 +756,13 @@ fn send_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result<u32>
     /// # Errors
     ///
     /// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available.
-    /// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the
-    ///   message queue.
-    ///
-    /// Error codes returned by the message constructor are propagated as-is.
+    /// - `EIO` if the framing or the checksum is invalid, or the queue was already poisoned by an
+    ///   earlier such failure. Either failure poisons the queue, so recovery requires a reset.
     fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
+        if self.poisoned.get() {
+            return Err(EIO);
+        }
+
         // Wait for a message to arrive from the GSP.
         let (slice_1, slice_2) = read_poll_timeout(
             || Ok(self.gsp_mem.driver_read_area()),
@@ -763,7 +773,10 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
         .map(|(slice_1, slice_2)| (slice_1.as_flattened(), slice_2.as_flattened()))?;
 
         // Extract the `GspMsgElement`.
-        let (header, slice_1) = GspMsgElement::from_bytes_prefix(slice_1).ok_or(EIO)?;
+        let Some((header, slice_1)) = GspMsgElement::from_bytes_prefix(slice_1) else {
+            self.poisoned.set(true);
+            return Err(EIO);
+        };
 
         dev_dbg!(
             &self.dev,
@@ -777,6 +790,7 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
 
         // Check that the driver read area is large enough for the message.
         if slice_1.len() + slice_2.len() < payload_length {
+            self.poisoned.set(true);
             return Err(EIO);
         }
 
@@ -805,6 +819,7 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
                 "GSP RPC: receive: Call {} - bad checksum\n",
                 header.sequence()
             );
+            self.poisoned.set(true);
             return Err(EIO);
         }
 
@@ -830,8 +845,8 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
     /// # Errors
     ///
     /// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available.
-    /// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the
-    ///   message queue.
+    /// - `EIO` if the queue is poisoned or the message fails framing or checksum validation (see
+    ///   [`Self::wait_for_msg`]), or if the matched message is too short for `M::Message`.
     /// - `ERANGE` if the message was not the awaited reply.
     ///
     /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
@@ -850,22 +865,26 @@ fn receive_msg<M: MessageFromGsp>(
         let func_matches = matches!(function, Ok(f) if f == M::FUNCTION);
         let matched = func_matches && expected_seq.is_none_or(|expected| seq == expected);
 
-        // Every path must advance the read pointer past this message.
+        // Every path must advance the read pointer past this message, including a failed decode.
         let result = if matched {
-            let (cmd, contents_1) = M::Message::from_bytes_prefix(message.contents.0).ok_or(EIO)?;
-            let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]);
-
-            M::read(cmd, &mut sbuffer)
-                .map_err(|e| e.into())
-                .inspect(|_| {
-                    if !sbuffer.is_empty() {
-                        dev_warn!(
-                            &self.dev,
-                            "GSP message {:?} has unprocessed data\n",
-                            M::FUNCTION
-                        );
-                    }
-                })
+            match M::Message::from_bytes_prefix(message.contents.0) {
+                Some((cmd, contents_1)) => {
+                    let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]);
+
+                    M::read(cmd, &mut sbuffer)
+                        .map_err(|e| e.into())
+                        .inspect(|_| {
+                            if !sbuffer.is_empty() {
+                                dev_warn!(
+                                    &self.dev,
+                                    "GSP message {:?} has unprocessed data\n",
+                                    M::FUNCTION
+                                );
+                            }
+                        })
+                }
+                None => Err(EIO),
+            }
         } else {
             Err(ERANGE)
         };
Signature · 1 line
2.55.0
#34 lore raw

PATCH 13/17 gpu: nova-core: bound a GSP wait by a single deadline

In reply to John Hubbard

The GSP posts unsolicited events on the same queue it posts replies on, so a caller waiting for one message dispatches whatever else arrives first and reads again.

Each of those reads started a fresh five-second timeout, so a steady stream of events extended the wait without bound.

Compute one absolute deadline when the wait begins and pass the time remaining to each read, so the whole wait is bounded however many events arrive first.

GSP boot waits for two unsolicited events. Move that loop into a helper so both take the same bound.

Assisted-by Cursor:claude-opus-5
---
 drivers/gpu/nova-core/gsp/cmdq.rs      | 52 ++++++++++++++++++++++----
 drivers/gpu/nova-core/gsp/commands.rs  |  8 +---
 drivers/gpu/nova-core/gsp/sequencer.rs |  8 +---
 3 files changed, 46 insertions(+), 22 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +44 -8
index fc4c229b8b9a..76d51155c49f 100644
@@ -30,7 +30,11 @@
         aref::ARef,
         Mutex, //
     },
-    time::Delta,
+    time::{
+        Delta,
+        Instant,
+        Monotonic, //
+    },
     transmute::{
         AsBytes,
         FromBytes, //
@@ -558,8 +562,9 @@ fn notify_gsp(bar: Bar0<'_>) {
     ///
     /// # Errors
     ///
-    /// - `ETIMEDOUT` if space does not become available to send the command, or if the reply is
-    ///   not received within the timeout.
+    /// - `ETIMEDOUT` if space does not become available to send the command, or if the reply does
+    ///   not arrive within [`Self::RECEIVE_TIMEOUT`] of the send, however many events are
+    ///   dispatched while waiting.
     /// - `EIO` if the variable payload requested by the command has not been entirely
     ///   written to by its [`CommandToGsp::init_variable_payload`] method.
     ///
@@ -574,8 +579,13 @@ pub(crate) fn send_command<M>(&self, bar: Bar0<'_>, command: M) -> Result<M::Rep
         let mut inner = self.inner.lock();
         let expected_seq = inner.send_command(bar, command)?;
 
+        let deadline = Instant::<Monotonic>::now() + Self::RECEIVE_TIMEOUT;
         loop {
-            match inner.receive_msg::<M::Reply>(Self::RECEIVE_TIMEOUT, Some(expected_seq)) {
+            let remaining = deadline - Instant::<Monotonic>::now();
+            if remaining.is_negative() {
+                break Err(ETIMEDOUT);
+            }
+            match inner.receive_msg::<M::Reply>(remaining, Some(expected_seq)) {
                 Ok(reply) => break Ok(reply),
                 Err(ERANGE) => continue,
                 Err(e) => break Err(e),
@@ -600,17 +610,43 @@ pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul
         self.inner.lock().send_command(bar, command).map(|_| ())
     }
 
-    /// Receive a message from the GSP.
+    /// Receive a message from the GSP, matching on the function code alone.
     ///
-    /// Matches on the function code alone, for a caller awaiting an unsolicited GSP event rather
-    /// than a reply to a command. See [`CmdqInner::receive_msg`].
-    pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
+    /// Returns `ERANGE` if the message that arrives is not of type `M`. See
+    /// [`CmdqInner::receive_msg`].
+    fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
     where
         // This allows all error types, including `Infallible`, to be used for `M::InitError`.
         Error: From<M::InitError>,
     {
         self.inner.lock().receive_msg(timeout, None)
     }
+
+    /// Waits for an unsolicited GSP event of type `M`, dispatching any other event that arrives
+    /// first.
+    ///
+    /// # Errors
+    ///
+    /// - `ETIMEDOUT` if the event does not arrive within [`Self::RECEIVE_TIMEOUT`] of the call,
+    ///   however many other events are dispatched while waiting.
+    pub(crate) fn await_msg<M: MessageFromGsp>(&self) -> Result<M>
+    where
+        // This allows all error types, including `Infallible`, to be used for `M::InitError`.
+        Error: From<M::InitError>,
+    {
+        let deadline = Instant::<Monotonic>::now() + Self::RECEIVE_TIMEOUT;
+        loop {
+            let remaining = deadline - Instant::<Monotonic>::now();
+            if remaining.is_negative() {
+                break Err(ETIMEDOUT);
+            }
+            match self.receive_msg::<M>(remaining) {
+                Ok(msg) => break Ok(msg),
+                Err(ERANGE) => continue,
+                Err(e) => break Err(e),
+            }
+        }
+    }
 }
 
 /// Inner mutex protected state of [`Cmdq`].
drivers/gpu/nova-core/gsp/commands.rs +1 -7
index ffc25fd8c47b..61fe93db9e7e 100644
@@ -188,13 +188,7 @@ fn read(
 
 /// Waits for GSP initialization to complete.
 pub(crate) fn wait_gsp_init_done(cmdq: &Cmdq) -> Result {
-    loop {
-        match cmdq.receive_msg::<GspInitDone>(Cmdq::RECEIVE_TIMEOUT) {
-            Ok(_) => break Ok(()),
-            Err(ERANGE) => continue,
-            Err(e) => break Err(e),
-        }
-    }
+    cmdq.await_msg::<GspInitDone>().map(|_| ())
 }
 
 /// The `GetGspStaticInfo` command.
drivers/gpu/nova-core/gsp/sequencer.rs +1 -7
index bcad1421953a..e2f1da129d8f 100644
@@ -343,13 +343,7 @@ pub(crate) fn run(
         libos: &'a Coherent<[LibosMemoryRegionInitArgument]>,
         bootloader_app_version: u32,
     ) -> Result {
-        let seq_info = loop {
-            match cmdq.receive_msg::<GspSequence>(Cmdq::RECEIVE_TIMEOUT) {
-                Ok(seq_info) => break seq_info,
-                Err(ERANGE) => continue,
-                Err(e) => return Err(e),
-            }
-        };
+        let seq_info = cmdq.await_msg::<GspSequence>()?;
 
         let sequencer = GspSequencer {
             bar: ctx.bar,
Signature · 1 line
2.55.0
#35 lore raw

PATCH 14/17 gpu: nova-core: drive GSP events with the SWGEN0 interrupt

In reply to John Hubbard

The GSP posts events, logs and error records to the GSP-to-CPU queue and raises the falcon SWGEN0 output. GSP boot polls for its own notifications, which leaves the latch set and pending bits in the tree.

nova-core drained the queue only while polling for a command reply, so an event sat unread until the next command was sent.

Service the queue from a threaded handler on the GSP notification vector. The top half runs in hard interrupt context and touches only
registers: it clears the GIN leaf, takes the falcon's SWGEN0 latch and rearms PCI delivery. Draining the queue takes the command-queue mutex, which can sleep, so the top half wakes the IRQ thread to do it.

Quiesce the tree, clear the latch and rearm PCI delivery before registering the handler, so none of that boot state reaches it. Pre-Hopper MSI rearms through a configuration-space write that the tree drain does not perform, and an interrupt delivered before probe leaves delivery un-armed.

Move the vector allocation out of the self-test and into probe, because the vectors are allocated once for the whole PCI device rather than per handler. The self-test and the GSP handler each take the vector for the subtree they service.

Assisted-by Cursor:claude-opus-5
---
 drivers/gpu/nova-core/driver.rs             |  54 ++++-
 drivers/gpu/nova-core/falcon/gsp.rs         |  35 ++-
 drivers/gpu/nova-core/gpu.rs                |  22 +-
 drivers/gpu/nova-core/gsp.rs                |  17 +-
 drivers/gpu/nova-core/gsp/cmdq.rs           |  42 ++++
 drivers/gpu/nova-core/irq.rs                |   1 +
 drivers/gpu/nova-core/irq/doorbell_test.rs  |  30 +--
 drivers/gpu/nova-core/irq/gsp.rs            | 239 ++++++++++++++++++++
 drivers/gpu/nova-core/irq/interrupt_tree.rs |  18 ++
 drivers/gpu/nova-core/nova_core.rs          |   1 -
 drivers/gpu/nova-core/regs.rs               |   4 +
 11 files changed, 433 insertions(+), 30 deletions(-)
 create mode 100644 drivers/gpu/nova-core/irq/gsp.rs
drivers/gpu/nova-core/driver.rs +50 -4
index 5738d4ac521b..3fbf117a99ee 100644
@@ -18,13 +18,22 @@
     types::ForLt,
 };
 
-use crate::gpu::Gpu;
+use crate::{
+    gpu::Gpu,
+    irq::gsp::GspIrq, //
+};
 
 /// Counter for generating unique auxiliary device IDs.
 static AUXILIARY_ID_COUNTER: Atomic<u32> = Atomic::new(0);
 
 #[pin_data]
 pub(crate) struct NovaCore<'bound> {
+    /// GSP event interrupt registration.
+    ///
+    /// Declared first so it is dropped first: `free_irq` runs (waiting out any in-flight handler)
+    /// before the GSP is unloaded (`gpu`) or the BAR mapping is released (`bar`).
+    #[pin]
+    _gsp_irq: GspIrq<'bound>,
     #[pin]
     pub(crate) gpu: Gpu<'bound>,
     bar: pci::Bar<'bound, BAR0_SIZE>,
@@ -78,14 +87,51 @@ fn probe<'bound>(
             pdev.enable_device_mem()?;
             pdev.set_master();
 
+            // A PCI device has one interrupt vector allocation, so it is made here for every
+            // subtree nova-core services, and each handler takes the vector for its own subtree.
+            let vectors = crate::irq::alloc_vectors(pdev, crate::irq::gsp::GSP_SUBTREE)?;
+            let gsp_vector = vectors.vector_for(crate::irq::gsp::GSP_SUBTREE)?;
+            let irq_type = vectors.irq_type();
+
             Ok(try_pin_init!(NovaCore {
                 bar: pdev.iomap_region_sized::<BAR0_SIZE>(0, c"nova-core/bar0")?,
                 // TODO: Use `&bar` self-referential pin-init syntax once available.
                 //
                 // SAFETY: `bar` is initialized before this expression is evaluated
-                // (`try_pin_init!()` initializes fields in declaration order), lives at a pinned
-                // stable address, and is dropped after `gpu` (struct field drop order).
-                gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) }),
+                // (`try_pin_init!()` initializes fields in the order they appear here), lives at a
+                // pinned stable address, and is dropped after `gpu` (struct field drop order).
+                gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) }, vectors),
+                // Quiesce the interrupt tree before registering the handler below.
+                _: {
+                    // SAFETY: as for the `bar` borrow above.
+                    let bar = unsafe { &*core::ptr::from_ref(bar) };
+                    crate::irq::gsp::quiesce(bar, gpu.chipset(), irq_type);
+                },
+                // Register the permanent GSP SWGEN0 handler before enabling the interrupt.
+                //
+                // SAFETY: `bar` is initialized before this expression is evaluated, lives at a
+                // pinned stable address, and is dropped after `_gsp_irq` (declared first, so
+                // dropped first), so the handler's borrow stays valid for its whole lifetime.
+                // `_gsp_irq` is stored in `NovaCore`, whose `Drop` runs `free_irq`, so the
+                // registration is never leaked.
+                _gsp_irq <- unsafe {
+                    GspIrq::new(
+                        pdev,
+                        gsp_vector,
+                        irq_type,
+                        &*core::ptr::from_ref(bar),
+                        gpu.cmdq(),
+                        gpu.chipset(),
+                    )
+                },
+                // Enable the GSP notification now that the handler is registered, then drain any
+                // messages the GSP posted during boot before relying on the interrupt.
+                _: {
+                    // SAFETY: as for the `bar` borrow above.
+                    let bar = unsafe { &*core::ptr::from_ref(bar) };
+                    crate::irq::gsp::enable(bar, gpu.chipset(), irq_type);
+                    gpu.cmdq().drain()?;
+                },
                 _reg: auxiliary::Registration::new(
                     pdev.as_ref(),
                     c"nova-drm",
drivers/gpu/nova-core/falcon/gsp.rs +31 -4
index ae32f401aeb0..f9d9e8e0386b 100644
@@ -14,6 +14,7 @@
 };
 
 use crate::{
+    driver::Bar0,
     falcon::{
         Falcon,
         FalconEngine,
@@ -36,14 +37,40 @@ impl RegisterBase<PFalcon2Base> for Gsp {
 
 impl FalconEngine for Gsp {}
 
+impl Gsp {
+    /// Clears the GSP falcon SWGEN0 interrupt latch.
+    ///
+    /// The latch holds until it is cleared, and the GSP drives no new edge into the interrupt
+    /// tree while it is set, so a caller that consumed a notification by any means other than the
+    /// interrupt handler must clear it or no further notification is delivered.
+    pub(crate) fn clear_swgen0_intr(bar: Bar0<'_>) {
+        bar.write(
+            WithBase::of::<Self>(),
+            regs::NV_PFALCON_FALCON_IRQSCLR::zeroed().with_swgen0(true),
+        );
+    }
+
+    /// Reads the GSP falcon interrupt status, clearing the SWGEN0 latch if it was set.
+    ///
+    /// Returns the status as it was read, before the clear. The GSP raises SWGEN0 when it has
+    /// posted messages in the GSP-to-CPU queue. The interrupt tree routes every falcon cause to
+    /// a single vector, so the rest of the status identifies a cause other than a posted message.
+    pub(crate) fn take_swgen0_intr(bar: Bar0<'_>) -> regs::NV_PFALCON_FALCON_IRQSTAT {
+        let status = bar.read(regs::NV_PFALCON_FALCON_IRQSTAT::of::<Self>());
+
+        if status.swgen0() {
+            Self::clear_swgen0_intr(bar);
+        }
+
+        status
+    }
+}
+
 impl<'a> Falcon<'a, Gsp> {
     /// Clears the SWGEN0 bit in the Falcon's IRQ status clear register to
     /// allow GSP to signal CPU for processing new messages in message queue.
     pub(crate) fn clear_swgen0_intr(&self) {
-        self.bar.write(
-            WithBase::of::<Gsp>(),
-            regs::NV_PFALCON_FALCON_IRQSCLR::zeroed().with_swgen0(true),
-        );
+        Gsp::clear_swgen0_intr(self.bar);
     }
 
     /// Checks if GSP reload/resume has completed during the boot process.
drivers/gpu/nova-core/gpu.rs +20 -2
index d5df0ebf67ae..9700eff6db86 100644
@@ -10,7 +10,8 @@
     num::Bounded,
     pci,
     prelude::*,
-    sizes::SizeConstants, //
+    sizes::SizeConstants,
+    sync::Arc, //
 };
 
 use crate::{
@@ -25,10 +26,12 @@
     fsp::Fsp,
     gsp::{
         self,
+        cmdq::Cmdq,
         commands::GetGspStaticInfoReply,
         Gsp,
         GspBootContext, //
     },
+    irq::SubtreeVectors,
     regs,
     vgpu::VgpuManager, //
 };
@@ -323,12 +326,27 @@ fn drop(self: Pin<&mut Self>) {
 }
 
 impl<'gpu> Gpu<'gpu> {
+    /// Returns the chipset this GPU was identified as.
+    pub(crate) fn chipset(&self) -> Chipset {
+        self.spec.chipset
+    }
+
+    /// Returns a shared handle to the GSP command queue.
+    pub(crate) fn cmdq(&self) -> Arc<Cmdq> {
+        self.gsp_resources.gsp.cmdq()
+    }
+
     pub(crate) fn new(
         pdev: &'gpu pci::Device<device::Core<'_>>,
         bar: Bar0<'gpu>,
+        vectors: SubtreeVectors<'gpu>,
     ) -> impl PinInit<Self, Error> + 'gpu {
         let dev = pdev.as_ref();
 
+        // `vectors` exists for the interrupt self-test below, which this configuration omits.
+        #[cfg(not(CONFIG_NOVA_CORE_IRQ_SELFTEST))]
+        let _ = vectors;
+
         try_pin_init!(Self {
             spec: Spec::new(dev, bar).inspect(|spec| {
                 dev_info!(dev,"NVIDIA ({})\n", spec);
@@ -352,7 +370,7 @@ pub(crate) fn new(
             // never observes or clears GSP or PRIV_RING interrupts.
             _: {
                 #[cfg(CONFIG_NOVA_CORE_IRQ_SELFTEST)]
-                crate::irq::doorbell_test::run_selftest(pdev, bar, spec.chipset)?;
+                crate::irq::doorbell_test::run_selftest(pdev, bar, spec.chipset, vectors)?;
             },
 
             // Initialize this early because `gsp_resources` depends on it.
drivers/gpu/nova-core/gsp.rs +11 -6
index 13f361406a6c..43eec3f4f573 100644
@@ -18,7 +18,8 @@
         Io, //
     },
     pci,
-    prelude::*, //
+    prelude::*,
+    sync::Arc, //
 };
 
 pub(crate) mod cmdq;
@@ -152,9 +153,8 @@ pub(crate) struct Gsp {
     /// Log buffers, optionally exposed via debugfs.
     #[pin]
     logs: debugfs::Scope<LogBuffers>,
-    /// Command queue.
-    #[pin]
-    pub(crate) cmdq: Cmdq,
+    /// Command queue, shared with the GSP event interrupt handler.
+    pub(crate) cmdq: Arc<Cmdq>,
     /// RM arguments.
     rmargs: Coherent<GspArgumentsPadded>,
 }
@@ -173,8 +173,8 @@ pub(crate) fn new(pdev: &pci::Device<device::Bound>) -> impl PinInit<Self, Error
             // _kgspInitLibosLoggingStructures (allocates memory for buffers)
             // kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array)
             Ok(try_pin_init!(Self {
-                cmdq <- Cmdq::new(dev),
-                rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
+                cmdq: Arc::pin_init(Cmdq::new(dev), GFP_KERNEL)?,
+                rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(cmdq.as_ref()))?,
                 libos: {
                     let mut libos = CoherentBox::zeroed_slice(
                         dev,
@@ -220,6 +220,11 @@ pub(crate) fn new(pdev: &pci::Device<device::Bound>) -> impl PinInit<Self, Error
     pub(crate) fn get_static_info(&self, bar: Bar0<'_>) -> Result<commands::GetGspStaticInfoReply> {
         self.cmdq.send_command(bar, commands::GetGspStaticInfo)
     }
+
+    /// Returns a shared handle to the GSP command queue.
+    pub(crate) fn cmdq(&self) -> Arc<Cmdq> {
+        self.cmdq.clone()
+    }
 }
 
 /// Opaque bundle required to unload the GSP. Created by [`Gsp::boot`], consumed by [`Gsp::unload`].
drivers/gpu/nova-core/gsp/cmdq.rs +42 -0

52 lines not on this page · raw message

drivers/gpu/nova-core/irq.rs +1 -0
index 5b449759b333..ddf322f2e623 100644
@@ -10,6 +10,7 @@
 
 #[cfg(CONFIG_NOVA_CORE_IRQ_SELFTEST)]
 pub(crate) mod doorbell_test;
+pub(crate) mod gsp;
 mod hal;
 mod interrupt_tree;
 
drivers/gpu/nova-core/irq/doorbell_test.rs +17 -13
index fae770339fd7..bfdfee732892 100644
@@ -28,11 +28,14 @@
     time, //
 };
 
-use super::interrupt_tree::{
-    vector_leaf_bit,
-    vector_subtree_mask,
-    LeafIndex,
-    Tree, //
+use super::{
+    interrupt_tree::{
+        vector_leaf_bit,
+        vector_subtree_mask,
+        LeafIndex,
+        Tree, //
+    },
+    SubtreeVectors, //
 };
 use crate::{
     driver::Bar0,
@@ -56,8 +59,8 @@
 
 /// Subtree carrying the doorbell vector, and the only subtree this test services.
 ///
-/// Derived from the vector so that changing `DOORBELL_VECTOR` moves the allocation, the subtree it
-/// enables, and the handler together.
+/// Derived from the vector so that changing `DOORBELL_VECTOR` moves the subtree it enables and the
+/// handler together.
 const DOORBELL_SUBTREE: u32 = vector_subtree_mask(DOORBELL_VECTOR);
 
 /// Index of the subtree carrying the doorbell vector. Under MSI-X this is also the index of the
@@ -184,17 +187,18 @@ fn drop(&mut self) {
 ///
 /// # Errors
 ///
-/// `EIO` if the doorbell is already pending before the test, if the delivery count is not two, if
-/// the doorbell bit is still set once the source is stopped, or if either delivery found a pending
-/// bit other than the doorbell. `ETIMEDOUT` if either delivery does not arrive within the timeout.
+/// `EINVAL` if the doorbell's subtree is not one nova-core services. `EIO` if the doorbell is
+/// already pending before the test, if the delivery count is not two, if the doorbell bit is still
+/// set once the source is stopped, or if either delivery found a pending bit other than the
+/// doorbell. `ETIMEDOUT` if either delivery does not arrive within the timeout.
 pub(crate) fn run_selftest<'a>(
     pdev: &'a pci::Device<Bound>,
     bar: Bar0<'a>,
     chipset: Chipset,
+    vectors: SubtreeVectors<'_>,
 ) -> Result {
-    // The allocated interrupt type decides how the handler rearms delivery, so the vectors are
-    // allocated before the tree is built.
-    let vectors = super::alloc_vectors(pdev, DOORBELL_SUBTREE)?;
+    // The interrupt type decides how the handler rearms delivery, so the tree takes it from
+    // probe's allocation.
     let vector = vectors.vector_for(DOORBELL_SUBTREE)?;
     let irq_type = vectors.irq_type();
     let tree = Tree::new(chipset, irq_type, DOORBELL_SUBTREE);
drivers/gpu/nova-core/irq/gsp.rs new file +239 -0

239 lines not on this page · raw message

drivers/gpu/nova-core/irq/interrupt_tree.rs +18 -0
index 73f5afadea3e..f4f1494cddba 100644
@@ -135,6 +135,8 @@ pub(super) fn leaf(&self, index: LeafIndex) -> Leaf<Idle> {
     ///
     /// `EINVAL` if `vector` lies outside this tree (`vector >= num_leaves * 32`). `EOVERFLOW` if
     /// `vector` does not fit in the trigger register's vector field.
+    // Only the interrupt self-test injects a software interrupt.
+    #[cfg_attr(not(CONFIG_NOVA_CORE_IRQ_SELFTEST), expect(dead_code))]
     pub(super) fn trigger(&self, bar: Bar0<'_>, vector: u32) -> Result {
         if crate::num::u32_as_usize(vector) >= self.num_leaves * 32 {
             return Err(EINVAL);
@@ -143,6 +145,22 @@ pub(super) fn trigger(&self, bar: Bar0<'_>, vector: u32) -> Result {
         Ok(())
     }
 
+    /// Disables every vector in every implemented leaf (`LEAF_EN_CLEAR`).
+    ///
+    /// Boot, or a driver that ran before this one, can leave leaf enables set for vectors
+    /// nova-core does not service, and such a vector delivers to nova-core's handler once its
+    /// subtree is enabled.
+    ///
+    /// This clears enables outside the subtrees nova-core services, so it is a probe-time
+    /// operation only.
+    pub(super) fn disable_all_leaves(&self, bar: Bar0<'_>) {
+        for index in 0..self.num_leaves {
+            if let Some(index) = LeafIndex::try_new(index) {
+                self.leaf(index).disable(bar, u32::MAX);
+            }
+        }
+    }
+
     /// Clears every pending bit in every implemented leaf.
     ///
     /// Disables this tree's serviced subtrees at `TOP` across the walk, then enables them,
drivers/gpu/nova-core/nova_core.rs +0 -1
index 65ce547bd44e..68b5abfe494d 100644
@@ -17,7 +17,6 @@
 mod fsp;
 mod gpu;
 mod gsp;
-#[cfg_attr(not(CONFIG_NOVA_CORE_IRQ_SELFTEST), expect(dead_code))]
 mod irq;
 mod mctp;
 #[macro_use]
drivers/gpu/nova-core/regs.rs +4 -0
index 1db92d36c5ac..2a0489472a66 100644
@@ -196,6 +196,10 @@ pub(crate) fn usable_fb_size(self) -> u64 {
         4:4     halt => bool;
     }
 
+    pub(crate) NV_PFALCON_FALCON_IRQSTAT(u32) @ PFalconBase + 0x00000008 {
+        6:6     swgen0 => bool;
+    }
+
     pub(crate) NV_PFALCON_FALCON_MAILBOX0(u32) @ PFalconBase + 0x00000040 {
         31:0    value => u32;
     }
Signature · 1 line
2.55.0
#36 lore raw

PATCH 15/17 gpu: nova-core: retrigger the GSP falcon and clear every latched cause

In reply to John Hubbard

A falcon signals the interrupt tree when its set of enabled causes goes from empty to non-empty. While any enabled cause stays latched, later causes produce no signal, and Turing falcons have no INTR_RETRIGGER register with which to supply one.

The GSP handler cleared its GIN leaf bit and then cleared the falcon's SWGEN0 latch. A cause that arrived between the two left no record: the leaf clear discarded it, and the falcon had nothing left to signal. Swapping the two clears moves the window rather than closing it.

The handler serviced SWGEN0 or reported an unserviceable cause, never both, so a HALT co-pending with SWGEN0 stayed latched. nova-core's probe cleared the SWGEN0 latch before draining the tree, so a message posted in between set a leaf bit that the drain then erased. In every case the GSP went silent for the life of the device.

Write the falcon's INTR_RETRIGGER register after every clear of the GSP vector. That supplies the missing signal from whatever causes remain enabled. Turing falcons have no such register, so skip the write there.

Handle every cause the falcon reports on one invocation, masking the ones with no recovery path so the re-emit does not raise them again. Clear the SWGEN0 latch after the tree drain instead of before it. Neither of these depends on INTR_RETRIGGER, so both apply on Turing.

Assisted-by Cursor:claude-opus-5
---
 drivers/gpu/nova-core/falcon/gsp.rs | 36 ++++++++++++++++++
 drivers/gpu/nova-core/falcon/hal.rs |  8 ++++
 drivers/gpu/nova-core/irq/gsp.rs    | 57 ++++++++++++++++++-----------
 drivers/gpu/nova-core/regs.rs       | 20 ++++++++++
 4 files changed, 100 insertions(+), 21 deletions(-)
drivers/gpu/nova-core/falcon/gsp.rs +36 -0
index f9d9e8e0386b..6ee5c1ef1af7 100644
@@ -16,11 +16,13 @@
 use crate::{
     driver::Bar0,
     falcon::{
+        hal,
         Falcon,
         FalconEngine,
         PFalcon2Base,
         PFalconBase, //
     },
+    gpu::Chipset,
     regs,
 };
 
@@ -64,6 +66,40 @@ pub(crate) fn take_swgen0_intr(bar: Bar0<'_>) -> regs::NV_PFALCON_FALCON_IRQSTAT
 
         status
     }
+
+    /// Masks and clears every interrupt cause set in `status`.
+    ///
+    /// A masked cause leaves the falcon's enabled set, so it neither raises the tree again nor
+    /// holds that set non-empty.
+    pub(crate) fn mask_and_clear_intr(bar: Bar0<'_>, status: regs::NV_PFALCON_FALCON_IRQSTAT) {
+        let causes = status.into_raw();
+
+        bar.write(
+            WithBase::of::<Self>(),
+            regs::NV_PFALCON_FALCON_IRQMCLR::zeroed().with_value(causes),
+        );
+        bar.write(
+            WithBase::of::<Self>(),
+            regs::NV_PFALCON_FALCON_IRQSCLR::from(causes),
+        );
+    }
+
+    /// Re-emits the falcon's enabled interrupt causes into the interrupt tree.
+    ///
+    /// The falcon signals the tree on a transition of its enabled causes, so clearing the tree
+    /// leaf while a cause is still latched leaves no transition and no further vector.
+    ///
+    /// Does nothing on Turing, whose falcons do not implement the register.
+    pub(crate) fn retrigger_intr(bar: Bar0<'_>, chipset: Chipset) {
+        if !hal::has_intr_retrigger(chipset) {
+            return;
+        }
+
+        bar.write(
+            WithBase::of::<Self>().at(0),
+            regs::NV_PFALCON_FALCON_INTR_RETRIGGER::zeroed().with_trigger(true),
+        );
+    }
 }
 
 impl<'a> Falcon<'a, Gsp> {
drivers/gpu/nova-core/falcon/hal.rs +8 -0
index 7e532889a1f4..f0828b32aebb 100644
@@ -72,6 +72,14 @@ fn signature_reg_fuse_version(
     fn load_method(&self) -> LoadMethod;
 }
 
+/// Returns whether `chipset`'s falcons implement `NV_PFALCON_FALCON_INTR_RETRIGGER`.
+///
+/// Turing falcons do not. Ampere and later do, including GA100, whose falcon otherwise uses the
+/// Turing HAL, so this is keyed on the architecture rather than provided through [`FalconHal`].
+pub(crate) fn has_intr_retrigger(chipset: Chipset) -> bool {
+    !matches!(chipset.arch(), Architecture::Turing)
+}
+
 /// Returns a boxed falcon HAL adequate for `chipset`.
 ///
 /// We use a heap-allocated trait object instead of a statically defined one because the
drivers/gpu/nova-core/irq/gsp.rs +36 -21

101 lines not on this page · raw message

drivers/gpu/nova-core/regs.rs +20 -0
index 2a0489472a66..01fde2c5e5a6 100644
@@ -200,6 +200,15 @@ pub(crate) fn usable_fb_size(self) -> u64 {
         6:6     swgen0 => bool;
     }
 
+    /// Masks interrupt causes at the falcon, one bit per cause, in the layout of
+    /// `NV_PFALCON_FALCON_IRQSTAT`.
+    ///
+    /// A masked cause is excluded from the enabled set the falcon signals on, so it cannot be
+    /// raised again by `NV_PFALCON_FALCON_INTR_RETRIGGER`.
+    pub(crate) NV_PFALCON_FALCON_IRQMCLR(u32) @ PFalconBase + 0x00000014 {
+        31:0    value => u32;
+    }
+
     pub(crate) NV_PFALCON_FALCON_MAILBOX0(u32) @ PFalconBase + 0x00000040 {
         31:0    value => u32;
     }
@@ -327,6 +336,17 @@ pub(crate) fn usable_fb_size(self) -> u64 {
         0:0     reset => bool;
     }
 
+    /// Re-emits the falcon's enabled interrupt causes into the interrupt tree.
+    ///
+    /// Write-only. A falcon signals the tree on a transition of its enabled causes, so a handler
+    /// that cleared the tree leaf while a cause was still latched has left no transition behind,
+    /// and this write supplies one. Turing falcons do not implement this register.
+    ///
+    /// OpenRM declares two elements and uses only the first.
+    pub(crate) NV_PFALCON_FALCON_INTR_RETRIGGER(u32)[2] @ PFalconBase + 0x000003e8 {
+        0:0     trigger => bool;
+    }
+
     pub(crate) NV_PFALCON_FBIF_TRANSCFG(u32)[8] @ PFalconBase + 0x00000600 {
         2:2     mem_type => FalconFbifMemType;
         1:0     target ?=> FalconFbifTarget;
Signature · 1 line
2.55.0
#37 lore raw

PATCH 16/17 gpu: nova-core: add KUnit tests for the interrupt tree and HALs

In reply to John Hubbard

Neither the per-architecture interrupt policy nor the vector arithmetic touches hardware, so KUnit can cover both without a GPU.

Add three suites:

* nova_core_gin_tree covers the leaf index bounds, the subtree-to-leaf mapping and its out-of-range filtering, the vector encoding, the masking of subtrees an architecture does not implement, and that every supported chipset implements the subtree carrying the GSP notification.

* nova_core_gin_hal covers the tree size on each family, and the rearm method for each combination of family and interrupt type.

* nova_core_falcon_hal covers the falcon retrigger gate. It is keyed on the architecture rather than the HAL, because GA100 shares the Turing HAL but does have the register.

Assisted-by Cursor:claude-opus-5
---
 drivers/gpu/nova-core/falcon/hal.rs         |  24 ++++
 drivers/gpu/nova-core/irq/hal.rs            | 106 ++++++++++++++++-
 drivers/gpu/nova-core/irq/interrupt_tree.rs | 121 ++++++++++++++++++++
 3 files changed, 250 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/falcon/hal.rs +24 -0
index f0828b32aebb..6bff9fea1a79 100644
@@ -107,3 +107,27 @@ pub(super) fn falcon_hal<E: FalconEngine + 'static>(
 
     Ok(hal)
 }
+
+#[kunit_tests(nova_core_falcon_hal)]
+mod tests {
+    use super::*;
+
+    /// Only Turing falcons lack the interrupt retrigger register. GA100 has it even though
+    /// [`falcon_hal`] gives GA100 the Turing HAL, which is why the gate is keyed on the
+    /// architecture instead.
+    #[test]
+    fn intr_retrigger_gate_per_arch() {
+        assert!(!has_intr_retrigger(Chipset::TU102));
+
+        for chipset in [
+            Chipset::GA100,
+            Chipset::GA102,
+            Chipset::AD102,
+            Chipset::GH100,
+            Chipset::GB100,
+            Chipset::GB202,
+        ] {
+            assert!(has_intr_retrigger(chipset));
+        }
+    }
+}
drivers/gpu/nova-core/irq/hal.rs +105 -1

115 lines not on this page · raw message

drivers/gpu/nova-core/irq/interrupt_tree.rs +121 -0

124 lines not on this page · raw message

Signature · 1 line
2.55.0
#38 lore raw

PATCH 17/17 gpu: nova-core: document the GIN interrupt controller and GSP events

In reply to John Hubbard

The hardware behind nova-core's interrupt support is not obvious from the code. Delivery is edge-triggered and needs a rearm after every interrupt, the rearm operation differs by GPU family and PCI interrupt type, and a vector that latched while disabled is invisible in the TOP summary register. Three different numbers are also all called a vector, in GIN, the MSI-X table, and the Linux IRQ API.

Add a design document covering the two-level register tree, how it reaches the CPU under MSI and MSI-X, and the rules those behaviors impose on a handler. It also covers the GSP event: the falcon retrigger, the handoff from boot-time polling to interrupts, and how its messages are classified. A glossary names each term after the register or the specification that defines it.

Assisted-by Cursor:claude-opus-5
---
 Documentation/gpu/nova/core/interrupts.rst | 686 +++++++++++++++++++++
 Documentation/gpu/nova/index.rst           |   1 +
 2 files changed, 687 insertions(+)
 create mode 100644 Documentation/gpu/nova/core/interrupts.rst
Documentation/gpu/nova/core/interrupts.rst new file +686 -0
new file mode 100644
index 000000000000..d7ddbfd6a0af
@@ -0,0 +1,686 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+=================================================
+GPU interrupt handling: GIN and the GSP event
+=================================================
+
+This document describes how nova-core receives interrupts from the GPU on Turing
+and later parts. It covers the GPU Interrupt and Notification unit (GIN), which
+is the GPU's interrupt controller, and the GSP event interrupt.
+
+Throughout, *CPU* means the CPU and the nova-core driver running on it. The GPU
+also has on-chip processors that run their own firmware and receive their own
+interrupts, and the GSP (GPU System Processor) is one of them.
+
+The register names in this document are the names from the GPU hardware
+reference headers. The CPU tree's registers live in the per-function
+``NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*`` aperture on every supported part, and
+the controller itself has a second name on pre-Hopper parts (see "Register
+naming").
+
+Terminology
+===========
+
+Three different numbers are all called a "vector" in the surrounding material.
+This document gives each one its own name and never uses "vector" on its own.
+
+GIN vector
+    The GPU-internal interrupt source number, 0 through 511 on Hopper. It is a
+    bit address within the tree: leaf ``vector / 32``, bit ``vector % 32``. The
+    CPU doorbell is GIN vector 129 and the GSP event is GIN vector 155.
+
+MSI-X entry
+    An index into the device's MSI-X table, 0 through 7 on Hopper. Linux's
+    ``struct msix_entry`` names its Linux IRQ number ``.vector``, which is a
+    third meaning.
+
+Linux IRQ number
+    What ``request_irq()`` takes, obtained from ``pci_irq_vector()``.
+
+The remaining terms, each named for the register or the specification that owns
+it:
+
+enable / disable a GIN vector
+    ``LEAF_EN_SET`` and ``LEAF_EN_CLEAR``.
+
+enable / disable a subtree
+    ``TOP_EN_SET`` and ``TOP_EN_CLEAR``.
+
+serviced subtree
+    A subtree nova-core enables and has a handler for.
+
+rearm
+    Restoring PCI interrupt delivery after servicing an interrupt. It is a
+    ``TOP_EN`` disable-then-enable cycle everywhere except under pre-Hopper
+    MSI, where it is a write to the end-of-interrupt (EOI) register in the BAR0
+    configuration-space mirror (see "Rearming PCI interrupt delivery").
+
+mask
+    Reserved for the two places hardware and the PCI specification use the
+    word: the MSI-X per-entry Vector Control mask bit, which Linux owns, and
+    the falcon cause masks. It never names a GIN enable.
+
+latched, pending
+    A ``LEAF`` bit records its source whether or not the GIN vector is enabled.
+    A disabled vector's pending bit never appears in ``TOP``.
+
+clear a leaf vector
+    Write a 1 to the vector's bit in ``LEAF``. Open RM spells the same
+    operation ``intrClearLeafVector_HAL``.
+
+pending bits
+    The plain bitmask value read from a ``LEAF`` register.
+
+unit
+    A generic interrupt-raising block. "Engine" is reserved for the blocks that
+    do usermode work: GR, CE, NVDEC, and the like.
+
+The GIN controller
+==================
+
+A GPU has many interrupt sources: the GSP, copy engines, the graphics engine,
+video decode and encode, the MMU fault path, timers, and others. Each one has a
+GIN vector number, which is internal to the controller and is not a PCI vector
+index.
+
+GIN records which vectors are pending in its own two-level register tree and
+raises the PCI interrupt when an enabled vector becomes pending. The CPU's
+handler reads that tree to tell the sources apart, clears the pending vectors,
+and runs the work for each.
+
+How the tree reaches the CPU over PCI
+-------------------------------------
+
+How many PCI interrupts the tree needs depends on the interrupt type Linux
+grants.
+
+MSI has a single message, and every subtree raises that one message. One
+allocated vector serves the whole tree.
+
+MSI-X raises a separate table entry per subtree, so a subtree's interrupts
+arrive on the table entry whose index is the subtree number. Linux masks each
+table entry a driver did not allocate, and a masked entry sends no message: the
+request sets a bit in the pending-bit array and waits for an unmask that never
+comes. A driver that leaves out the entry its subtree raises loses every
+interrupt on that subtree, and loses it silently, with the GIN leaf and TOP
+registers showing the vector pending and enabled while no handler runs.
+
+The serviced-subtree invariant
+------------------------------
+
+Every subtree enabled at TOP must have an allocated PCI vector with a registered
+handler.
+
+MSI satisfies this with one message that every subtree raises. MSI-X needs one
+allocated, unmasked entry per serviced subtree, and a PCI allocation cannot be
+sparse, so it runs from entry 0 through the highest serviced subtree::
+
+    MSI-X, with subtree 2 serviced:
+
+      subtree 0  ->  entry 0   allocated, no handler, stays masked
+      subtree 1  ->  entry 1   allocated, no handler, stays masked
+      subtree 2  ->  entry 2   handler here, and its rearm covers subtree 2
+
+    MSI, with any serviced set:
+
+      every serviced subtree  ->  the one allocated vector, whose handler's
+                                  rearm covers the whole serviced set
+
+The entries allocated below a serviced subtree that the driver does not service
+cost nothing: Linux unmasks an entry only when its interrupt is requested, and a
+disabled subtree raises nothing.
+
+nova-core services exactly one subtree, subtree 2, because both the vectors it
+uses are in leaf 4: the GSP event (155) and the self-test doorbell (129). That
+is also the subtree the resource manager assigns to its ``UVM_SHARED`` interrupt
+category on every chipset nova-core supports.
+
+Interrupt trees
+===============
+
+GIN keeps a separate interrupt tree for each place an interrupt can be sent to:
+
+* One tree per PCIe function. The Physical Function (PF) has a tree, and each
+  Virtual Function (VF) has a tree.
+* One tree per on-chip microcontroller that receives interrupts, starting with
+  the GSP.
+
+Each destination reaches its own tree through its own BAR0 and cannot reach any
+other tree. GSP firmware selects the tree each unit's interrupt is sent to.
+
+nova-core services the CPU tree of one function. The VF trees and the
+microcontroller trees belong to firmware or to virtual functions.
+
+The two-level tree
+==================
+
+Each tree has two levels. The bottom level is the LEAF registers, which hold one
+pending bit per vector. The top level is the single TOP register, which
+summarizes the leaves.
+
+* Each ``LEAF(i)`` is a 32-bit register holding the pending bits for vectors
+  ``i * 32`` through ``i * 32 + 31``. A set bit means that vector is pending.
+* ``TOP`` is a single 32-bit read-only register. Each of its bits summarizes one
+  *subtree*, which is a pair of adjacent leaves. TOP bit ``N`` reflects
+  ``LEAF[2N]`` and ``LEAF[2N + 1]`` as filtered by their leaf enables, so a
+  vector that latched while disabled does not appear in TOP.
+
+A subtree is two leaves, so a part with L leaves has L / 2 subtrees and uses
+that many TOP bits. An 8-leaf part uses TOP bits 0 through 3, and the other 28
+bits always read 0. A 16-leaf part uses TOP bits 0 through 7::
+
+    TOP  (one 32-bit register, and an 8-leaf part uses only bits 0..3)
+
+      bit 0  ->  subtree 0  ->  LEAF[0], LEAF[1]   vectors   0..63
+      bit 1  ->  subtree 1  ->  LEAF[2], LEAF[3]   vectors  64..127
+      bit 2  ->  subtree 2  ->  LEAF[4], LEAF[5]   vectors 128..191
+      bit 3  ->  subtree 3  ->  LEAF[6], LEAF[7]   vectors 192..255
+      bits 4..31: always 0 on an 8-leaf part (a 16-leaf part uses bits 0..7)
+
+    A LEAF is one 32-bit register, one bit per vector. For example, LEAF[4]
+    holds vectors 128..159:
+
+      bit 1  = vector 129  (CPU doorbell)
+      bit 27 = vector 155  (GSP event)
+
+Registers
+---------
+
+All the registers are 32 bits, defined in ``regs.rs`` under the
+``NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*`` names. The leaf registers are arrays
+indexed by leaf number:
+
+* ``LEAF(i)`` holds the pending bits for the vectors in leaf ``i``. Reading
+  returns the pending bits, and writing a 1 to a bit clears that vector
+  (write-1-to-clear).
+* ``LEAF_EN_SET(i)`` and ``LEAF_EN_CLEAR(i)`` enable and disable individual
+  vectors in leaf ``i``.
+* ``TOP`` is the read-only summary: bit N is set when an enabled vector is
+  pending in ``LEAF[2N]`` or ``LEAF[2N + 1]``. A vector that latched while its
+  leaf enable was clear does not appear.
+* ``TOP_EN_SET`` and ``TOP_EN_CLEAR`` enable and disable subtrees.
+* ``LEAF_TRIGGER`` makes a vector pending in software. The self-test uses it.
+
+Mapping a vector to the tree
+----------------------------
+
+Each vector occupies one bit of one leaf, and each leaf belongs to one
+subtree::
+
+    leaf    = v / 32
+    bit     = v % 32
+    subtree = leaf / 2
+
+Both of the vectors nova-core names by number fall in leaf 4: vector 129 at bit
+1 and vector 155 at bit 27, so both arrive under subtree 2.
+
+Enabling and clearing
+---------------------
+
+Each bit of a set or clear register acts on its own: writing a 1 performs the
+action for that bit, and writing a 0 leaves the bit's state alone. No caller
+ever needs a read-modify-write.
+
+* ``LEAF(i)`` is write-1-to-clear. Reading returns the pending bits. Each bit
+  must be cleared before its vector is serviced.
+* ``LEAF_EN_SET(i)`` and ``LEAF_EN_CLEAR(i)`` enable and disable individual
+  vectors in a leaf.
+* ``TOP_EN_SET`` and ``TOP_EN_CLEAR`` enable and disable whole subtrees.
+
+A vector reaches the CPU only when both its leaf enable bit and its subtree's
+TOP enable bit are set. The leaf enable governs delivery and the TOP summary,
+but not the latch: a disabled vector still latches its LEAF bit, and that bit is
+visible only by reading the leaf directly.
+
+How a unit interrupt reaches the CPU
+====================================
+
+A unit does not write a LEAF register itself. Each unit has an interrupt routing
+register, and GSP firmware programs it once at boot. Firmware writes three
+things into it: the unit's VECTOR (which leaf bit it uses), its GFID (which tree
+to post to: the PF or a specific VF), and its destination flags (which consumers
+get it: the CPU, the GSP, or another on-chip microcontroller).
+
+Later, when a unit has an event, three things happen in turn::
+
+    1. The unit sends an interrupt message to GIN, carrying the VECTOR, GFID,
+       and destination flags from its routing register.
+    2. GIN sets bit (VECTOR % 32) in LEAF[VECTOR / 32], in the tree that the
+       GFID and destination flags select.
+    3. If that vector is enabled and its subtree is enabled, GIN raises the PCI
+       interrupt to the CPU.
+
+Because firmware assigns the vectors, nova-core does not hardcode which vector
+belongs to which unit. The one exception nova-core relies on is the GSP event
+vector, which firmware pins to a fixed number (see "The GSP event vector").
+
+Edge behavior and rearm
+=======================
+
+The pieces behave as follows:
+
+* A LEAF bit is a latch. It is set on the rising edge of its source and stays set
+  until the CPU writes a 1 to it. A source that stays high does not set the bit
+  again.
+* TOP is read-only and reports the subtree's *enabled* pending state. A vector
+  that latched while its leaf enable was clear does not appear in TOP.
+* LEAF_EN and TOP_EN are CPU-controlled enables that allow or block delivery.
+* GIN raises the PCI interrupt for subtree N when the subtree's enabled pending
+  state goes from low to high::
+
+    Per vector, in leaf i at bit b:
+        LEAF[i][b] AND LEAF_EN[i][b]
+
+    Per subtree N, across its leaves 2N and 2N + 1:
+        OR of every enabled pending bit  ->  TOP[N]
+
+    Delivery for subtree N:
+        TOP[N] AND TOP_EN[N]  ->  rising edge  ->  PCI interrupt
+
+    TOP_EN applies below TOP, so disabling a subtree halts delivery and leaves
+    what TOP reports unchanged.
+
+Because a disabled vector is invisible in TOP, code that must find every pending
+bit cannot descend from TOP. It has to read the leaves directly. Open RM does
+the same: its stalling-interrupt path never reads TOP, and instead walks every
+subtree it implements reading LEAF registers.
+
+Because delivery is edge-triggered, writing ``TOP_EN_SET`` while an enabled leaf
+bit is still set produces a new edge. A full tree walk uses this: after it
+clears the leaves, it writes ``TOP_EN_SET`` so an interrupt that arrived during
+servicing is still delivered.
+
+A unit that holds an internal level signal high does not produce a new leaf edge
+after the CPU clears the bit, so rearming alone does not re-deliver it. Such
+units have an ``INTR_RETRIGGER`` register that forces a new edge.
+
+Retriggering a falcon
+---------------------
+
+A falcon signals the tree on a transition of its enabled interrupt causes.
+Clearing the tree leaf while a cause is still latched leaves no transition, so
+the vector stays clear however many further causes arrive. Both clear orders
+have that window, so a handler on a falcon vector writes ``INTR_RETRIGGER`` on
+every path that services the vector.
+
+That re-emit must not be able to raise a cause that nothing clears. A cause the
+handler does not service is removed from the falcon's enabled set with
+``IRQMCLR`` and cleared with ``IRQSCLR`` before the re-emit.
+
+``INTR_RETRIGGER`` is absent on Turing falcons and present from GA100 onward, so
+the write is conditional on the architecture. A Turing handler cannot supply a
+transition that went missing, so it must leave no cause latched: it reads the
+status once and takes every cause that status reports, rather than stopping at
+the first one it recognizes. A cause left behind holds the falcon's enabled set
+non-empty, and no later cause from that falcon signals the tree at all.
+
+One window stays open on Turing. A cause that arrives between the status read
+and the clears is not in the status, so it stays latched after the tree leaf has
+been cleared. Open RM has the same window: ``kgspService_TU102`` ends with
+``kflcnIntrRetrigger``, which is implemented from GA100 onward and does nothing
+on Turing.
+
+Rearming PCI interrupt delivery
+-------------------------------
+
+Clearing the GIN state is not enough. A message-signaled interrupt is
+delivered once per edge, and the PCI side delivers no further interrupt until the
+CPU rearms it. Which operation does that depends on the GPU family and on the
+interrupt type Linux granted:
+
+==================  =====  ===========================================
+Architecture        Type   Rearm operation
+==================  =====  ===========================================
+Turing through Ada  MSI    write the configuration-mirror EOI register
+Hopper and later    MSI    clear then set the serviced TOP enables
+Any                 MSI-X  clear then set the handler's own TOP enable
+==================  =====  ===========================================
+
+The MSI forms cover every serviced subtree, because one message serves all of
+them. The MSI-X form covers one subtree, because each serviced subtree has its
+own table entry and its own handler.
+
+INTx is level-triggered and needs no rearm write. nova-core does not allocate it,
+so it never reaches a handler.
+
+A handler must rearm once per delivered interrupt, on every path that services
+one. A handler that skips the rearm receives no further interrupts at all.
+
+The rearm is separate from the TOP restore at the end of a full tree walk, even
+though two of the three forms write the same registers. The walk clears TOP_EN
+on entry so that it can read and clear without new interrupts arriving, and sets
+it again on exit. For the two enable-cycle forms that restore also rearms, but
+pre-Hopper MSI rearms through the configuration mirror, which the walk never
+writes, so the startup sequence rearms explicitly after the walk.
+
+Servicing an interrupt
+======================
+
+nova-core services the tree in one of two ways, depending on which code handles
+the interrupt.
+
+The GSP event handler services one vector, so it leaves its subtree enabled and
+reads and clears only its own leaf bit, touching a single leaf per interrupt.
+
+The startup drain walks the whole tree instead, because it must clear whatever is
+pending across every subtree rather than one known vector. It disables the
+subtrees, clears every pending leaf, then enables them again.
+
+The drain reads every implemented leaf rather than descending from TOP. Boot
+latches vectors while they are still disabled, and those bits do not appear in
+TOP, so a TOP-driven walk would skip exactly the state the drain has to clear.
+
+The two paths as register operations::
+
+    Full tree walk (the one-time startup drain):
+        write TOP_EN_CLEAR = serviced        disable, to stop new interrupts
+        for each implemented subtree N, for i in {2N, 2N+1}:
+            pending = read LEAF[i]           pending vectors in this leaf
+            write LEAF[i] = pending          clear (write-1-to-clear)
+        write TOP_EN_SET = serviced          restore TOP_EN
+
+    Notification, subtree stays enabled (the GSP event handler, and the
+    self-test, which deliberately mirrors it):
+        pending = read LEAF[gsp_leaf]        is our vector's bit set?
+        write LEAF[gsp_leaf] = GSP_BIT       clear only our bit
+        rearm PCI interrupt delivery         see "Rearming PCI interrupt
+                                             delivery"
+
+Two rules for the full walk:
+
+* Clear every pending leaf bit, including bits nova-core does not handle. An
+  uncleared bit holds its subtree in the pending state, and restoring TOP_EN
+  over it produces a delivery edge straight away. The walk writes back every bit
+  it read.
+* Restore TOP_EN only after clearing every pending leaf. Otherwise a still-set
+  bit raises the interrupt again while the walk is still running.
+
+The notification path clears one bit, so a vector pending alongside it in the
+same leaf keeps its bit and stays pending for whoever services it. Both paths
+must rearm PCI delivery for the interrupt they serviced.
+
+Interrupts and notifications
+============================
+
+Two kinds of source use the tree:
+
+* An interrupt means a unit needs servicing.
+* A notification means a unit is reporting that something happened, such as a log
+  record or completed work.
+
+The GSP event is a notification. Its handler leaves the subtree enabled and
+clears only the GSP leaf bit.
+
+The hardware manuals also split the vector space into "stall" and "nonstall"
+ranges. Those name address ranges rather than describing behavior. nova-core
+does not service the stall range.
+
+Per-architecture differences
+============================
+
+The tree is the same on every supported GPU except for its size, and there are
+only two sizes, split at Hopper:
+
+===================  ======  ========  ====================
+GPUs                 Leaves  Subtrees  Implemented subtrees
+===================  ======  ========  ====================
+Turing, Ampere, Ada  8       4         ``0x0f``
+Hopper and later     16      8         ``0xff``
+===================  ======  ========  ====================
+
+Only the lower eight leaves exist before Hopper, so TOP bits 4 through 31 read
+zero there. Hopper and later have 16 leaves, though sources do not populate all
+of them.
+
+The implemented subtrees bound which TOP bits mean anything. That set is wider
+than the set nova-core enables, which is the subtrees it services, per the
+serviced-subtree invariant. The startup drain still reads every implemented
+leaf, because a vector that latched while disabled is invisible in TOP and can
+be in any leaf.
+
+The HAL provides the leaf count, and the subtree count (leaves / 2) and the
+implemented-subtree set derive from it. The rearm method is the HAL's other
+per-architecture value.
+
+Multi-die parts
+===============
+
+On multi-die parts the controller is replicated per die, with an aggregation
+level above the per-die TOP registers. nova-core services the CPU tree of one
+function on a single-die part, so it does not drive the aggregation level.
+
+The GSP event
+=============
+
+When the GSP has output for the CPU (log records, error records, and other
+events), it writes the messages into the GSP-to-CPU queue in shared memory and
+raises SWGEN0, one of the software-generated interrupt outputs of the GSP
+microcontroller (a "falcon" in NVIDIA hardware). SWGEN0 is routed through a GIN
+vector, so it reaches the CPU as a PCI interrupt::
+
+    GSP writes messages into the GSP-to-CPU queue
+    GSP raises SWGEN0
+    GIN sets the GSP leaf bit, and the subtree becomes pending
+    PCI interrupt -> Linux IRQ -> nova-core top half, in IRQ context, which
+                                 must not sleep:
+        read the GSP leaf bit and clear it (subtree stays enabled)
+        read the GSP falcon IRQ status, clearing SWGEN0 if it was set
+        for every other cause that status reports: report it, then remove it
+            from the falcon's enabled set and clear it
+        retrigger the falcon
+        rearm PCI interrupt delivery
+        wake the IRQ thread if SWGEN0 was set
+    IRQ thread, which may sleep: take the command-queue lock and drain the
+        GSP-to-CPU queue, routing each message
+
+A halt and a posted message can be pending together, so the top half handles
+every cause the status reports rather than choosing between them (see
+"Retriggering a falcon").
+
+The interrupt is only the trigger to drain the queue. A thread polling for a
+command reply routes the messages it reads through the same classifier (see
+"Draining and classifying the GSP-to-CPU queue").
+
+If the drain fails, the queue cannot advance past the message it could not parse,
+so every later notification would repeat the same failure. The IRQ thread
+disables the GSP vector before reporting the failure, which leaves the queue
+unserviced until the device is reset.
+
+Enabling the GSP event
+----------------------
+
+SWGEN0 is a latch, and the GSP drives no new edge into the tree while it stays
+set. GSP boot consumes its notifications by polling the queue, which leaves the
+latch set and leaves stale state in the tree, so the handoff from polling to
+interrupts has a required order::
+
+    disable every implemented vector    drop enables left by boot or by a
+                                        driver that ran before this one
+    drain the tree (full walk)          clear stale GIN state from boot
+    clear the SWGEN0 latch              so the next assertion makes an edge
+    rearm PCI interrupt delivery        the walk does not do it under
+                                        pre-Hopper MSI
+    register the threaded IRQ handler   nothing can reach it yet
+    enable the GSP vector at its leaf   deliveries become possible here
+    drain the GSP-to-CPU queue          messages posted before the clear
+
+Clearing the latch makes the first interrupt possible. Messages the GSP posted
+before that clear produce no interrupt, so the queue drain follows.
+
+The tree is quiesced before the handler is registered. Registering unmasks the
+PCI interrupt, and a leaf enable that boot left set would reach a handler that
+services one vector and has no way to service any other. Open RM clears all
+leaf enables at the same point for the same reason.
+
+The latch is cleared after the tree walk, not before. The walk erases every leaf
+bit, so a message posted between an earlier clear and the walk would leave the
+latch set with nothing in the tree to show for it, and on Turing no later
+message would signal the tree at all. Clearing last can instead leave the GSP
+vector pending with the latch already clear, so enabling the vector delivers one
+interrupt whose ``IRQSTAT`` reads zero. The queue drain that follows reads the
+message.
+
+The GSP event vector
+--------------------
+
+The GSP event uses a fixed vector, ``GSP_INTR_0_VECTOR`` (155), on Turing
+through Blackwell. Vector 155 is leaf 4, bit 27, subtree 2. nova-core enables
+that leaf bit and services it, with no runtime vector discovery.
+
+A full unit-to-vector table can be fetched from the GSP by RPC. nova-core does
+not fetch it, because a pinned vector needs no lookup.
+
+Draining and classifying the GSP-to-CPU queue
+=============================================
+
+The queue carries both command replies and unsolicited events. Each message is
+routed by its function code and its RPC sequence number, into one of three
+classes:
+
+* Function code and sequence both match the awaited reply. The message is
+  decoded and returned to the caller that sent the command.
+* The function code matches but the sequence does not. This is a reply to a
+  command that already timed out, so it is logged at warning level and dropped
+  rather than satisfying a later command that reused the same function code.
+* Anything else is an unsolicited event. OS-error and robust-channel records are
+  logged at error level. An unrecognized function code is logged at warning
+  level. Other known events (GSP logs, libos prints, assertion records,
+  lifecycle notices) need no action and are not logged again, because the RPC
+  receive trace already records their arrival.
+
+The read pointer advances past the message in all three cases, and also when a
+matched message fails 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 carries its length inside the
+region 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 and every later receive fails, which the IRQ thread reports before
+disabling the GSP vector.
+
+The classifier is a fixed set of function codes rather than a handler registry.
+The events that need action are handled directly in it.
+
+Both the polling path and the IRQ thread route messages through this classifier
+under the command-queue lock. Replies and events share one queue and one set of
+read pointers, so one lock covers the whole drain. A thread waiting for a reply
+dispatches any event it reads first and keeps waiting, under a single deadline
+for the whole wait rather than a fresh timeout after each message.
+
+One lock means a drain waits for an in-flight command's receive to finish or
+time out. For log and error records that delay does not matter.
+
+Design notes
+============
+
+Register naming
+---------------
+
+nova-core uses the ``NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*`` names for the CPU
+tree on both pre-Hopper and Hopper-plus parts. Any function reaches its own tree
+through that aperture. The Hopper-plus central aperture (``NV_GIN_CPU_INTR_*``)
+configures other functions and is not used by the CPU path.
+
+The controller has two names in the hardware headers and in Open RM.
+``NV_CTRL`` names the tree on pre-Hopper parts, and ``NV_GIN`` names the
+Hopper+ unit that contains the tree along with arbiter logic. This document
+calls the controller GIN throughout, because the tree nova-core drives is the
+same on every supported part.
+
+Type-state tree API
+-------------------
+
+Servicing a leaf has a required order: read its pending bits, then clear them.
+The code encodes the two stages as distinct types (``Idle`` and ``Pending``) so
+that clearing a leaf before reading it does not compile. ``Top`` carries no type
+state, because enabling and disabling a subtree can happen in any order.
+
+The types order the calls on a single handle. They are not a lock and they do
+not coordinate the tree as a whole. Nothing stops two walks from running against
+the tree at once. nova-core does not run concurrent walks: the GSP event handler
+touches only its own leaf and never walks the tree, and the only whole-tree
+walk, the startup drain, runs once during probe.
+
+Threaded handler
+----------------
+
+The drain sleeps: it takes the command-queue mutex and walks shared memory, so it
+cannot run in hard-IRQ context. nova-core uses a threaded IRQ handler. The top
+half clears the GIN leaf, takes every cause the falcon reports, rearms delivery,
+and wakes the IRQ thread if SWGEN0 was among them. The thread takes the lock and
+drains the queue. The self-test does no sleeping work and uses a non-threaded
+handler with a completion.
+
+Shared BAR0 mapping
+-------------------
+
+The GPU, the self-test, and the GSP event handler read the same BAR0 registers.
+nova-core keeps one BAR0 mapping and lets each of them borrow it. An interrupt
+handler is torn down when the device unbinds, so it only runs while the mapping
+is alive.
+
+Self-test
+=========
+
+The self-test runs during driver probe. It registers a real interrupt handler
+and confirms that an interrupt injected at the GPU is delivered all the way to
+that handler, so it needs a working GPU and PCI interrupt path. It is gated by
+``CONFIG_NOVA_CORE_IRQ_SELFTEST`` and runs before GSP boot, so it never touches
+GSP interrupt state.
+
+The parts with no hardware dependency are covered by KUnit tests instead: the
+vector encoding, the subtree and leaf arithmetic, and the per-architecture rearm
+policy.
+
+The test drives ``LEAF_TRIGGER``, a hardware register that every supported part
+implements. Writing a vector number to it latches that vector exactly as its
+unit would, after which the vector takes the ordinary path to the CPU under the
+ordinary enables.
+
+The test drives vector 129, at leaf 4 bit 1. It registers a handler for that
+vector and triggers it twice, waiting for the first delivery before triggering
+the second. Its handler deliberately mirrors the notification path: it clears
+only its own leaf bit and rearms PCI interrupt delivery, rather than walking the
+tree.
+
+The two interrupts cannot coalesce into one, because the second is triggered
+only after the first handler has finished. A handler that fails to rearm times
+out on the second delivery instead of passing. A single delivery serviced by a
+full tree walk cannot detect that, because the walk's own TOP_EN restore
+produces an edge by itself.
+
+The test passes only if both deliveries arrive, each one finds the doorbell bit
+and nothing else pending in the leaf, and the leaf is clear once the source is
+stopped. Anything else fails probe. Requiring the exact mask on the second
+delivery shows that the first handler's clear reached the hardware. The test
+runs before GSP boot on a leaf the drain has just cleared, so no other vector in
+that leaf can be active and the exact mask costs nothing.
+
+The test borrows the allocation that probe made for the serviced subtrees rather
+than allocating its own, and looks up the vector for the doorbell's own subtree.
+A doorbell vector moved to a subtree nova-core does not service fails that
+lookup, and with it the self-test and probe, rather than being misrouted
+silently.
+
+The test exercises the interrupt path from the GPU to the handler without GSP
+firmware, which is useful when bringing up PCI, MSI, MSI-X, and passthrough
+setups. Under MSI-X a pass also shows that the per-subtree table entry routing
+works, since the delivery arrives on the entry belonging to the serviced
+subtree.
+
+Virtualization
+==============
+
+The per-function trees, the GFID routing, and the central ``NV_GIN`` aperture
+support virtualization: each VF gets its own tree, and the PF or firmware routes
+a unit's interrupt to the right function. MIG (multi-instance GPU) partitioning
+adds more structure. nova-core services the CPU tree of one function, and
+implements no VF tree management, GFID routing, or MIG support.
+
+References
+==========
+
+* nova-core source: the register definitions in ``regs.rs``, the interrupt HAL
+  and tree API in the ``irq`` module, and the GSP command queue in the ``gsp``
+  module.
Documentation/gpu/nova/index.rst +1 -0
index 2afa58e8f08d..2130d1caf4c3 100644
@@ -34,3 +34,4 @@ vGPU manager VFIO driver and the nova-drm driver.
    core/fwsec
    core/falcon
    core/tlv
+   core/interrupts
Signature · 1 line
2.55.0