NVIDIA GPU driver infrastructure
 help / color / mirror / Atom feed
* [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery
@ 2026-09-03  3:14 John Hubbard
  2026-09-03  3:15 ` [PATCH v3 01/14] rust: pci: declare IrqType and IrqTypes with impl_flags John Hubbard
                   ` (13 more replies)
  0 siblings, 14 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:14 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard

I'm posting a v3 because Alexandre's and Danilo's reviews prompted a
number of significant changes, and it's time for a refresh.

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

The design uses a threaded IRQ handler. The top half touches only GPU
registers, while the threaded bottom half drains the message queue.

Fine-grained locking is left for a follow-up patchset. I'm working on
that next. For now, there is just a big ugly lock around anything that
even gets close to the GSP message queue. :)

This is based on drm-rust-next, which now includes Danilo Krummrich's
PCI interrupt-vector series. v3 carries no prerequisite commits.

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-v3/

Changes in v3:

* Dropped "match GSP RPC replies by sequence, not just function" from
  this series, and moved it to the r000 firmware series, where the GSP
  does match on sequence. The GSP matches sequence numbers only on r580
  and later. On r570, the UnloadingGuestDriver reply arrives with
  sequence 0, so matching on it made module unload time out. Alexandre
  hit this while unloading the module, and I reproduced it after adding
  an unload step to my test suite. (Alexandre)

* Split "retrigger the GSP falcon and clear every latched cause". The
  new falcon registers are now in a patch before the SWGEN0 patch, and
  the handler changes are in the SWGEN0 patch, so nothing is added and
  then rewritten one patch later. (Alexandre)

* Moved the vector and subtree newtypes before the register
  definitions, so the registers use those types from the start. Moved
  the interrupt-tree changes out of the self-test patch and into the
  tree patch, so the self-test patch adds only the test, its Kconfig
  option, and the line that gates a dead-code annotation on that
  option. (Alexandre)

* GinVector now contains a Bounded<u32, 9>, so every GinVector value is
  below 512 by construction. leaf_index() shifts and casts the value,
  with no from_expr() or build_assert!(). The trigger register write
  needs no fallible field setter. LEAF_INDEX_MASK is gone. (Alexandre)

* GIN registers declare their fields as LeafMask and SubtreeSet, with
  conversions to and from Bounded<u32, 32>. Every tree write uses
  zeroed().with_...(), so the field types prevent a SubtreeSet from
  being written where a LeafMask belongs. Leaf accesses use Bounded's
  Deref and the build-time-checked at(), so the try_at() and
  unwrap_or(0) pairs are gone. GinVector::validate is const again, and
  the LeafCount casts have CAST comments. (Alexandre)

* nova-core now defines its own MsiType, with Msi and MsiX only, rather
  than using PCI's IrqType, which also includes INTx. SubtreeVectors
  stores the MsiType, the HAL's rearm method is no longer an Option,
  and the INTx match arms are gone. (Alexandre)

* Tree::new returns EINVAL for a subtree the architecture does not
  implement. drain() leaves TOP disabled for its caller. One iterator
  walks every implemented leaf, replacing the nested subtree and leaf
  loops. request_for computes its entry index inline. (Alexandre)

* The self-test disables every leaf before draining, and uses one Tree,
  which it reaches through the registered handler. That gives
  disable_all_leaves a caller, so its dead-code annotation is gone.
  (Alexandre)

* Renamed dispatch_event to classify_event. A non-matching message
  reaches it through the existing else branch, so the second check of
  the same condition is gone, and send_command's documentation no
  longer names a private type. A poison() helper logs the reason and
  returns EIO. (Alexandre)

* await_msg takes the queue lock once for the entire wait, so a
  concurrent send_command cannot consume the awaited event. The outer
  Cmdq::receive_msg wrapper is gone, and the errors it propagated are
  documented. (Alexandre)

* The GPU owns its interrupt now. After GSP boot, Gpu quiesces the
  tree, registers the handler, and drains the queue that the GSP filled
  during boot. Gpu allocates the vectors as well. The handler borrows
  the command queue and the device instead of taking an Arc and an
  ARef. The chipset accessor, the command-queue accessor, and the
  unsafe BAR lifetime conversion are gone. (Alexandre, Danilo)

* The tree reset is now a SubtreeVectors method, which resets the tree
  that its own vector allocation covers. The vestigial SWGEN0 clear
  during falcon construction is gone, along with the Falcon method that
  wrapped it. GspInterrupt no longer uses pin-data, and its constructor
  returns Self. (Alexandre)

* The top half intersects IRQSTAT with PRISCV_RISCV_IRQMASK and
  PRISCV_RISCV_IRQDEST, as Open RM does. It sees only the causes routed
  to the host, leaves the firmware's own causes alone, and clears the
  latch of a host cause it cannot service. It masks nothing, because
  PRISCV_RISCV_IRQMASK is read-only to the host and FALCON_IRQMASK does
  not control host routing on a RISC-V falcon. (Alexandre)

* I found one more problem while reworking the series, rather than in
  review. The subtree has to stay enabled at TOP while the handler is
  registered. The startup tree walk leaves TOP disabled, and the
  pre-Hopper MSI rearm is a configuration-space write that does not
  enable it, so nothing enabled it and the GSP vector never reached the
  CPU on that path.

* The interrupt document's glossary defines leaf, subtree and tree, and
  the entry for a disabled vector now says that its pending bit does
  not set the subtree's TOP bit. Register imports use a module glob,
  commit-message bullets start at column 1, and Alexandre's Reviewed-by
  is on the two rust patches. (Alexandre)

* The document dropped its description of matching a reply by sequence
  number, along with the patch that added it, and it no longer says
  that the startup tree walk restores the TOP enables. The rest is an
  editing pass: the register list was written out twice, so it is one
  section now, and I rewrote the sentences that needed two readings.

Tested on Turing (TU117), Ampere (GA104) and Blackwell (GB202): probe
and chipset identification, the interrupt self-test, a GSP name query
over the command queue, driver unload/reload, and the KUnit suites.


Joel Fernandes (2):
  rust: sync: completion: add wait_for_completion_timeout()
  gpu: nova-core: add the GIN interrupt tree and allocate its vectors

John Hubbard (12):
  rust: pci: declare IrqType and IrqTypes with impl_flags
  gpu: nova-core: add the GIN vector and subtree newtypes
  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: add an interrupt delivery self-test
  gpu: nova-core: log GSP events instead of discarding them
  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: add the falcon interrupt status and routing registers
  gpu: nova-core: drive GSP events with the SWGEN0 interrupt
  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  | 716 ++++++++++++++++++++
 Documentation/gpu/nova/index.rst            |   1 +
 drivers/gpu/nova-core/Kconfig               |  15 +
 drivers/gpu/nova-core/falcon/gsp.rs         |  71 +-
 drivers/gpu/nova-core/falcon/hal.rs         |  92 ++-
 drivers/gpu/nova-core/gpu.rs                |  68 +-
 drivers/gpu/nova-core/gsp.rs                |   2 +-
 drivers/gpu/nova-core/gsp/cmdq.rs           | 241 +++++--
 drivers/gpu/nova-core/gsp/commands.rs       |   8 +-
 drivers/gpu/nova-core/gsp/sequencer.rs      |   8 +-
 drivers/gpu/nova-core/irq.rs                | 163 +++++
 drivers/gpu/nova-core/irq/doorbell_test.rs  | 301 ++++++++
 drivers/gpu/nova-core/irq/gsp.rs            | 239 +++++++
 drivers/gpu/nova-core/irq/hal.rs            | 170 +++++
 drivers/gpu/nova-core/irq/hal/gh100.rs      |  29 +
 drivers/gpu/nova-core/irq/hal/tu102.rs      |  28 +
 drivers/gpu/nova-core/irq/interrupt_tree.rs | 664 ++++++++++++++++++
 drivers/gpu/nova-core/irq/regs.rs           |  91 +++
 drivers/gpu/nova-core/nova_core.rs          |   1 +
 drivers/gpu/nova-core/regs.rs               |  66 ++
 rust/kernel/pci/irq.rs                      |  68 +-
 rust/kernel/sync/completion.rs              |  23 +-
 22 files changed, 2942 insertions(+), 123 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
 create mode 100644 drivers/gpu/nova-core/irq/regs.rs


base-commit: 6cb331644c441ff4101a4f8726283a6ed0d5947e
-- 
2.55.0


^ permalink raw reply	[flat|nested] 27+ messages in thread

* [PATCH v3 01/14] rust: pci: declare IrqType and IrqTypes with impl_flags
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:15 ` [PATCH v3 02/14] rust: sync: completion: add wait_for_completion_timeout() John Hubbard
                   ` (12 subsequent siblings)
  13 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard

The kernel provides impl_flags! for declaring a bitmask type alongside
the enum of its individual flags, generating the bit operators and the
containment queries.

IrqTypes open-coded that pattern with a with() builder, so a caller
naming two interrupt types chained two calls onto IrqTypes::default().

Declare both types through impl_flags!, so the same set reads as
IrqType::Msi | IrqType::MsiX.

Suggested-by: Gary Guo <gary@garyguo.net>
Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 rust/kernel/pci/irq.rs | 68 +++++++++++++-----------------------------
 1 file changed, 21 insertions(+), 47 deletions(-)

diff --git a/rust/kernel/pci/irq.rs b/rust/kernel/pci/irq.rs
index 6741046ec1c0..f074aad7f1d8 100644
--- a/rust/kernel/pci/irq.rs
+++ b/rust/kernel/pci/irq.rs
@@ -13,27 +13,26 @@
 };
 use core::num::NonZero;
 
-/// IRQ type flags for PCI interrupt allocation.
-#[derive(Debug, Clone, Copy)]
-pub enum IrqType {
-    /// INTx interrupts.
-    Intx,
-    /// Message Signaled Interrupts (MSI).
-    Msi,
-    /// Extended Message Signaled Interrupts (MSI-X).
-    MsiX,
-}
-
-impl IrqType {
-    /// Convert to the corresponding kernel flags.
-    const fn as_raw(self) -> u32 {
-        match self {
-            IrqType::Intx => bindings::PCI_IRQ_INTX,
-            IrqType::Msi => bindings::PCI_IRQ_MSI,
-            IrqType::MsiX => bindings::PCI_IRQ_MSIX,
-        }
+crate::impl_flags!(
+    /// Set of IRQ types that can be used for PCI interrupt allocation.
+    #[derive(Debug, Clone, Copy, Default)]
+    pub struct IrqTypes(u32);
+
+    /// IRQ type flags for PCI interrupt allocation.
+    #[derive(Debug, Clone, Copy)]
+    pub enum IrqType {
+        /// INTx interrupts.
+        Intx = bindings::PCI_IRQ_INTX,
+
+        /// Message Signaled Interrupts (MSI).
+        Msi = bindings::PCI_IRQ_MSI,
+
+        /// Extended Message Signaled Interrupts (MSI-X).
+        MsiX = bindings::PCI_IRQ_MSIX,
     }
+);
 
+impl IrqType {
     /// Construct from raw value.
     #[inline]
     const fn from_raw(raw: u32) -> Self {
@@ -45,33 +44,10 @@ const fn from_raw(raw: u32) -> Self {
     }
 }
 
-/// Set of IRQ types that can be used for PCI interrupt allocation.
-#[derive(Debug, Clone, Copy, Default)]
-pub struct IrqTypes(u32);
-
 impl IrqTypes {
     /// Create a set containing all IRQ types (MSI-X, MSI, and INTx).
     pub const fn all() -> Self {
-        Self(bindings::PCI_IRQ_ALL_TYPES)
-    }
-
-    /// Build a set of IRQ types.
-    ///
-    /// # Examples
-    ///
-    /// ```ignore
-    /// // Create a set with only MSI and MSI-X (no INTx interrupts).
-    /// let msi_only = IrqTypes::default()
-    ///     .with(IrqType::Msi)
-    ///     .with(IrqType::MsiX);
-    /// ```
-    pub const fn with(self, irq_type: IrqType) -> Self {
-        Self(self.0 | irq_type.as_raw())
-    }
-
-    /// Get the raw flags value.
-    const fn as_raw(self) -> u32 {
-        self.0
+        Self(Self::all_bits())
     }
 }
 
@@ -203,9 +179,7 @@ impl Device<device::Bound> {
     /// let vectors = dev.alloc_irq_vectors(1, 32, pci::IrqTypes::all())?;
     ///
     /// // Allocate MSI or MSI-X only (no INTx interrupts).
-    /// let msi_only = pci::IrqTypes::default()
-    ///     .with(pci::IrqType::Msi)
-    ///     .with(pci::IrqType::MsiX);
+    /// let msi_only = pci::IrqType::Msi | pci::IrqType::MsiX;
     /// let vectors = dev.alloc_irq_vectors(4, 16, msi_only)?;
     /// # Ok(())
     /// # }
@@ -222,7 +196,7 @@ pub fn alloc_irq_vectors(
         // - `pci_alloc_irq_vectors` internally validates all other parameters
         //   and returns error codes.
         let ret = unsafe {
-            bindings::pci_alloc_irq_vectors(self.as_raw(), min_vecs, max_vecs, irq_types.as_raw())
+            bindings::pci_alloc_irq_vectors(self.as_raw(), min_vecs, max_vecs, u32::from(irq_types))
         };
         to_result(ret)?;
 
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 02/14] rust: sync: completion: add wait_for_completion_timeout()
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
  2026-09-03  3:15 ` [PATCH v3 01/14] rust: pci: declare IrqType and IrqTypes with impl_flags John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:15 ` [PATCH v3 03/14] gpu: nova-core: add the GIN vector and subtree newtypes John Hubbard
                   ` (11 subsequent siblings)
  13 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, Joel Fernandes, John Hubbard

From: Joel Fernandes <joelagnelf@nvidia.com>

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().

Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[jhubbard: return the remaining jiffies]
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 rust/kernel/sync/completion.rs | 23 ++++++++++++++++++++++-
 1 file changed, 22 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/sync/completion.rs b/rust/kernel/sync/completion.rs
index 35ff049ff078..7e8b3c1c880e 100644
--- a/rust/kernel/sync/completion.rs
+++ b/rust/kernel/sync/completion.rs
@@ -6,7 +6,12 @@
 //!
 //! 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.
 ///
@@ -111,4 +116,20 @@ pub fn wait_for_completion(&self) {
         // SAFETY: `self.as_raw()` is a pointer to a valid `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: `self.as_raw()` is a pointer to a valid `struct completion`.
+        match unsafe { bindings::wait_for_completion_timeout(self.as_raw(), timeout) } {
+            0 => None,
+            remaining => Some(remaining),
+        }
+    }
 }
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 03/14] gpu: nova-core: add the GIN vector and subtree newtypes
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
  2026-09-03  3:15 ` [PATCH v3 01/14] rust: pci: declare IrqType and IrqTypes with impl_flags John Hubbard
  2026-09-03  3:15 ` [PATCH v3 02/14] rust: sync: completion: add wait_for_completion_timeout() John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:15 ` [PATCH v3 04/14] gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers John Hubbard
                   ` (10 subsequent siblings)
  13 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard

A GIN vector's number fixes its position in the interrupt tree: it
latches in leaf vector / 32 at bit vector % 32, in subtree vector / 64.
A tree implements either 8 or 16 leaves, which sets both its subtree
count and its highest usable vector.

Each of those is a bare bit pattern, so a leaf mask and a TOP bit are
interchangeable to the compiler.

Add a type for each: a vector, a leaf index, a set of vectors within one
leaf, one subtree, a set of subtrees, and a leaf count. A vector
converts to its own leaf, bit and subtree. A leaf count yields the
subtree set it implements.

Suggested-by: Danilo Krummrich <dakr@kernel.org>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/irq.rs                |  11 +
 drivers/gpu/nova-core/irq/interrupt_tree.rs | 242 ++++++++++++++++++++
 drivers/gpu/nova-core/nova_core.rs          |   2 +
 3 files changed, 255 insertions(+)
 create mode 100644 drivers/gpu/nova-core/irq.rs
 create mode 100644 drivers/gpu/nova-core/irq/interrupt_tree.rs

diff --git a/drivers/gpu/nova-core/irq.rs b/drivers/gpu/nova-core/irq.rs
new file mode 100644
index 000000000000..f27952ff747b
--- /dev/null
+++ b/drivers/gpu/nova-core/irq.rs
@@ -0,0 +1,11 @@
+// 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 interrupt_tree;
diff --git a/drivers/gpu/nova-core/irq/interrupt_tree.rs b/drivers/gpu/nova-core/irq/interrupt_tree.rs
new file mode 100644
index 000000000000..5aa447cf0ec4
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/interrupt_tree.rs
@@ -0,0 +1,242 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! Vector addressing in the GIN CPU interrupt tree.
+//!
+//! A vector's number fixes where it latches: leaf `vector / 32` at bit `vector % 32`, and that
+//! leaf belongs to subtree `vector / 64`. The types here keep those three views apart, so a leaf
+//! index, a set of vectors within one leaf, and a `TOP` bit cannot stand in for one another.
+
+use kernel::{
+    num::Bounded,
+    prelude::*, //
+};
+
+use crate::num;
+
+/// Number of bits a leaf index occupies, covering the `0..16` leaf register arrays.
+const LEAF_INDEX_BITS: u32 = 4;
+
+/// Index of a leaf register, bounded to the `0..16` range covered by the leaf register arrays.
+pub(super) type LeafIndex = Bounded<usize, LEAF_INDEX_BITS>;
+
+/// Number of vectors one leaf register carries, one per bit.
+const VECTORS_PER_LEAF: u32 = 32;
+
+/// Number of leaves one subtree covers.
+const LEAVES_PER_SUBTREE: u32 = 2;
+
+/// Number of bits that address any vector the widest supported tree carries.
+const VECTOR_BITS: u32 = 9;
+
+const _: () = assert!(1 << VECTOR_BITS == LeafCount::Sixteen.vector_count());
+
+/// Width of the vector field in the leaf trigger register.
+const TRIGGER_VECTOR_BITS: u32 = 12;
+
+/// Number of leaves a tree implements.
+///
+/// Every supported part implements one of these two counts, and the interrupt HAL names the one
+/// its architecture uses.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+#[repr(usize)]
+pub(super) enum LeafCount {
+    /// Turing through Ada.
+    Eight = 8,
+
+    /// Hopper and later.
+    Sixteen = 16,
+}
+
+impl LeafCount {
+    /// Returns the number of leaves.
+    pub(super) const fn into_u32(self) -> u32 {
+        // CAST: both discriminants are 16 or below.
+        self as u32
+    }
+
+    /// Returns the number of leaves, in the type that indexes the leaf register arrays.
+    pub(super) const fn into_raw(self) -> usize {
+        num::u32_as_usize(self.into_u32())
+    }
+
+    /// Returns the number of subtrees, each of which covers two leaves.
+    pub(super) const fn subtree_count(self) -> u32 {
+        self.into_u32() / LEAVES_PER_SUBTREE
+    }
+
+    /// Returns the set of every subtree a tree of this size implements.
+    pub(super) const fn subtree_set(self) -> SubtreeSet {
+        SubtreeSet((1u32 << self.subtree_count()) - 1)
+    }
+
+    /// Returns the number of vectors a tree of this size carries.
+    pub(super) const fn vector_count(self) -> u32 {
+        self.into_u32() * VECTORS_PER_LEAF
+    }
+}
+
+/// Set of vectors within one leaf, one bit per vector.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(super) struct LeafMask(u32);
+
+impl LeafMask {
+    /// Returns the mask with every vector of the leaf set.
+    pub(super) const fn all() -> Self {
+        Self(u32::MAX)
+    }
+
+    /// Returns the mask holding the vectors set in `raw`.
+    pub(super) const fn from_raw(raw: u32) -> Self {
+        Self(raw)
+    }
+
+    /// Returns the mask as the value the leaf registers take.
+    pub(super) const fn into_raw(self) -> u32 {
+        self.0
+    }
+
+    /// Returns whether no vector is set.
+    pub(super) const fn is_empty(self) -> bool {
+        self.0 == 0
+    }
+
+    /// Returns whether every vector set in `other` is also set here.
+    pub(super) const fn contains(self, other: Self) -> bool {
+        self.0 & other.0 == other.0
+    }
+}
+
+/// One subtree, named by its `TOP` bit.
+///
+/// # Invariants
+///
+/// Exactly one bit is set.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(super) struct Subtree(u32);
+
+impl Subtree {
+    /// Returns this subtree's index within the tree.
+    ///
+    /// Under MSI-X this is also the index of the allocated entry the subtree raises.
+    pub(super) const fn index(self) -> u32 {
+        self.0.trailing_zeros()
+    }
+
+    /// Returns the subtree as the value the `TOP` enable registers take.
+    pub(super) const fn into_raw(self) -> u32 {
+        self.0
+    }
+}
+
+/// Set of subtrees, one bit per subtree, in the layout the `TOP` enable registers take.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(super) struct SubtreeSet(u32);
+
+impl SubtreeSet {
+    /// Returns whether `subtree` belongs to this set.
+    pub(super) const fn contains(self, subtree: Subtree) -> bool {
+        self.0 & subtree.into_raw() != 0
+    }
+
+    /// Returns whether the set holds no subtree.
+    pub(super) const fn is_empty(self) -> bool {
+        self.0 == 0
+    }
+
+    /// Returns the subtrees present in both sets.
+    pub(super) const fn intersection(self, other: Self) -> Self {
+        Self(self.0 & other.0)
+    }
+
+    /// Returns the number of subtrees counted from subtree `0` through the highest one in this
+    /// set, which is `0` for an empty set.
+    pub(super) const fn span(self) -> u32 {
+        u32::BITS - self.0.leading_zeros()
+    }
+}
+
+impl From<Subtree> for SubtreeSet {
+    fn from(subtree: Subtree) -> Self {
+        Self(subtree.into_raw())
+    }
+}
+
+/// A GIN interrupt vector, bounded to the widest tree any supported part implements.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(super) struct GinVector(Bounded<u32, VECTOR_BITS>);
+
+impl GinVector {
+    /// Returns the vector numbered `VECTOR`.
+    ///
+    /// Fails at build time if `VECTOR` lies outside the widest tree any supported part
+    /// implements.
+    pub(super) const fn new<const VECTOR: u32>() -> Self {
+        Self(Bounded::<u32, VECTOR_BITS>::new::<VECTOR>())
+    }
+
+    /// Returns the vector number.
+    pub(super) const fn into_raw(self) -> u32 {
+        self.0.get()
+    }
+
+    /// Returns the leaf that carries this vector.
+    pub(super) fn leaf_index(self) -> LeafIndex {
+        // CALC: `self.0 / VECTORS_PER_LEAF`.
+        self.0.shr::<{ VECTORS_PER_LEAF.ilog2() }, _>().cast()
+    }
+
+    /// Returns this vector's bit within its leaf.
+    pub(super) const fn leaf_mask(self) -> LeafMask {
+        LeafMask(1 << (self.0.get() % VECTORS_PER_LEAF))
+    }
+
+    /// Returns the subtree that carries this vector.
+    pub(super) const fn subtree(self) -> Subtree {
+        // INVARIANT: a shift of `1` leaves exactly one bit set.
+        Subtree(1 << (self.0.get() / (VECTORS_PER_LEAF * LEAVES_PER_SUBTREE)))
+    }
+
+    /// Checks that this vector lies within a tree of `leaves` leaves.
+    ///
+    /// # Errors
+    ///
+    /// `EINVAL` if the vector lies beyond the last leaf such a tree implements.
+    pub(super) const fn validate(self, leaves: LeafCount) -> Result {
+        if self.0.get() >= leaves.vector_count() {
+            return Err(EINVAL);
+        }
+
+        Ok(())
+    }
+}
+
+impl From<Bounded<u32, 32>> for LeafMask {
+    fn from(vectors: Bounded<u32, 32>) -> Self {
+        Self(vectors.get())
+    }
+}
+
+impl From<LeafMask> for Bounded<u32, 32> {
+    fn from(vectors: LeafMask) -> Self {
+        vectors.0.into()
+    }
+}
+
+impl From<Bounded<u32, 32>> for SubtreeSet {
+    fn from(subtrees: Bounded<u32, 32>) -> Self {
+        Self(subtrees.get())
+    }
+}
+
+impl From<SubtreeSet> for Bounded<u32, 32> {
+    fn from(subtrees: SubtreeSet) -> Self {
+        subtrees.0.into()
+    }
+}
+
+impl From<GinVector> for Bounded<u32, TRIGGER_VECTOR_BITS> {
+    fn from(vector: GinVector) -> Self {
+        vector.0.extend()
+    }
+}
diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
index 35a8b1214b0e..dfd11dfe562c 100644
--- a/drivers/gpu/nova-core/nova_core.rs
+++ b/drivers/gpu/nova-core/nova_core.rs
@@ -17,6 +17,8 @@
 mod fsp;
 mod gpu;
 mod gsp;
+#[expect(dead_code)]
+mod irq;
 mod mctp;
 #[macro_use]
 mod num;
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 04/14] gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (2 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 03/14] gpu: nova-core: add the GIN vector and subtree newtypes John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:15 ` [PATCH v3 05/14] gpu: nova-core: add the per-architecture GIN CPU interrupt HAL John Hubbard
                   ` (9 subsequent siblings)
  13 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard, Will Pierce

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.

Declare each leaf and TOP field with the vector or subtree type it
carries, so a set of subtrees cannot be written to a register that takes
a leaf mask.

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
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/irq.rs      |  1 +
 drivers/gpu/nova-core/irq/regs.rs | 91 +++++++++++++++++++++++++++++++
 2 files changed, 92 insertions(+)
 create mode 100644 drivers/gpu/nova-core/irq/regs.rs

diff --git a/drivers/gpu/nova-core/irq.rs b/drivers/gpu/nova-core/irq.rs
index f27952ff747b..3066ceeb850c 100644
--- a/drivers/gpu/nova-core/irq.rs
+++ b/drivers/gpu/nova-core/irq.rs
@@ -9,3 +9,4 @@
 //! See `Documentation/gpu/nova/core/interrupts.rst`.
 
 mod interrupt_tree;
+mod regs;
diff --git a/drivers/gpu/nova-core/irq/regs.rs b/drivers/gpu/nova-core/irq/regs.rs
new file mode 100644
index 000000000000..4bb7825207c9
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/regs.rs
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use kernel::io::register;
+
+use super::interrupt_tree::{
+    LeafMask,
+    SubtreeSet, //
+};
+
+// 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(super) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF(u32)[16] @ 0x00b81000 {
+        /// Vectors latched in this leaf.
+        31:0    vectors => LeafMask;
+    }
+
+    /// 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(super) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_EN_SET(u32)[16] @ 0x00b81200 {
+        /// Vectors to enable.
+        31:0    vectors => LeafMask;
+    }
+
+    /// 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(super) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_EN_CLEAR(u32)[16] @ 0x00b81400 {
+        /// Vectors to disable.
+        31:0    vectors => LeafMask;
+    }
+
+    /// 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(super) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_SET(u32) @ 0x00b81608 {
+        /// Subtrees to enable.
+        31:0    subtrees => SubtreeSet;
+    }
+
+    /// 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(super) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_CLEAR(u32) @ 0x00b81610 {
+        /// Subtrees to disable.
+        31:0    subtrees => SubtreeSet;
+    }
+
+    /// 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(super) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_TRIGGER(u32) @ 0x00b81640 {
+        /// Vector to latch.
+        11:0    vector;
+    }
+}
+
+// PCI configuration-space mirror, pre-Hopper only.
+
+register! {
+    /// MSI end-of-interrupt register.
+    ///
+    /// A `u32` write rearms MSI delivery on pre-Hopper GPUs. The value is ignored.
+    pub(super) NV_XVE_CYA_2(u32) @ 0x0008_8704 {}
+}
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 05/14] gpu: nova-core: add the per-architecture GIN CPU interrupt HAL
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (3 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 04/14] gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:15 ` [PATCH v3 06/14] gpu: nova-core: add the GIN interrupt tree and allocate its vectors John Hubbard
                   ` (8 subsequent siblings)
  13 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard, Will Pierce

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, and name the interrupt type with nova-core's own two
variants rather than the PCI core's three, which include the
level-triggered INTx that nova-core never allocates.

Assisted-by: Cursor:claude-opus-5
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/irq.rs           |  14 ++++
 drivers/gpu/nova-core/irq/hal.rs       | 106 +++++++++++++++++++++++++
 drivers/gpu/nova-core/irq/hal/gh100.rs |  29 +++++++
 drivers/gpu/nova-core/irq/hal/tu102.rs |  28 +++++++
 4 files changed, 177 insertions(+)
 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

diff --git a/drivers/gpu/nova-core/irq.rs b/drivers/gpu/nova-core/irq.rs
index 3066ceeb850c..d21dee1b89a0 100644
--- a/drivers/gpu/nova-core/irq.rs
+++ b/drivers/gpu/nova-core/irq.rs
@@ -8,5 +8,19 @@
 //!
 //! See `Documentation/gpu/nova/core/interrupts.rst`.
 
+mod hal;
 mod interrupt_tree;
 mod regs;
+
+/// The message-signaled interrupt type a vector allocation obtained.
+///
+/// nova-core allocates MSI-X or MSI and nothing else, so the level-triggered INTx that
+/// [`kernel::pci::IrqType`] also names has no representation here.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) enum MsiType {
+    /// One message, raised by every subtree of the tree.
+    Msi,
+
+    /// One table entry per subtree.
+    MsiX,
+}
diff --git a/drivers/gpu/nova-core/irq/hal.rs b/drivers/gpu/nova-core/irq/hal.rs
new file mode 100644
index 000000000000..1ea677e37e56
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/hal.rs
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! Per-architecture properties of the GIN CPU interrupt tree.
+
+mod gh100;
+mod tu102;
+
+use kernel::{
+    io::Io,
+    prelude::*, //
+};
+
+use crate::{
+    driver::Bar0,
+    gpu::{
+        Architecture,
+        Chipset, //
+    }, //
+};
+
+use super::{
+    interrupt_tree::{
+        LeafCount,
+        Subtree,
+        SubtreeSet, //
+    },
+    regs,
+    MsiType, //
+};
+
+/// Register write that restores PCI interrupt delivery to the CPU.
+///
+/// A message-signaled interrupt is delivered once per edge, and the PCI side delivers no further
+/// interrupt until the CPU rearms it. A handler that returns without this write receives no more
+/// interrupts.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(super) enum PciIrqRearmMethod {
+    /// The MSI end-of-interrupt register in the BAR0 PCI configuration-space mirror, used by
+    /// MSI on pre-Hopper GPUs.
+    ConfigMirrorEoi,
+
+    /// A clear then a set of the `TOP` enable bits of every serviced subtree, which produces the
+    /// edge that delivers the next interrupt.
+    ///
+    /// MSI has a single message that every subtree raises, so the rearm covers the whole serviced
+    /// set.
+    TopEnableCycleServiced,
+
+    /// The same enable cycle, restricted to the one subtree the handler serves.
+    ///
+    /// MSI-X gives each subtree its own table entry and its own handler.
+    TopEnableCycleSubtree,
+}
+
+impl PciIrqRearmMethod {
+    /// Performs this method's register write.
+    ///
+    /// `serviced` holds every subtree the driver services, and `subtree` is the one subtree the
+    /// calling handler serves. Each method uses whichever of the two its interrupt type delivers
+    /// on, so both are required.
+    pub(super) fn rearm(self, bar: Bar0<'_>, serviced: SubtreeSet, subtree: Subtree) {
+        let subtrees = match self {
+            // The written value is ignored, so any write rearms delivery.
+            Self::ConfigMirrorEoi => {
+                bar.write(regs::NV_XVE_CYA_2, 0u32.into());
+                return;
+            }
+            Self::TopEnableCycleServiced => serviced,
+            Self::TopEnableCycleSubtree => SubtreeSet::from(subtree),
+        };
+
+        bar.write_reg(
+            regs::NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_CLEAR::zeroed().with_subtrees(subtrees),
+        );
+        bar.write_reg(
+            regs::NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_SET::zeroed().with_subtrees(subtrees),
+        );
+    }
+}
+
+/// Per-architecture properties of the GIN CPU interrupt tree.
+///
+/// The tree size and the method that rearms PCI interrupt delivery differ by family.
+///
+/// See `Documentation/gpu/nova/core/interrupts.rst`.
+pub(super) trait CpuInterruptHal {
+    /// Returns the number of leaves the CPU tree implements.
+    ///
+    /// [`LeafCount::subtree_set`] gives the subtrees behind them, and
+    /// [`LeafCount::vector_count`] the vectors they carry.
+    fn leaf_count(&self) -> LeafCount;
+
+    /// Returns the method that rearms PCI interrupt delivery for `msi_type`.
+    fn pci_irq_rearm_method(&self, msi_type: MsiType) -> PciIrqRearmMethod;
+}
+
+/// Returns the [`CpuInterruptHal`] for `chipset`.
+pub(super) fn cpu_interrupt_hal(chipset: Chipset) -> &'static dyn CpuInterruptHal {
+    match chipset.arch() {
+        Architecture::Turing | Architecture::Ampere | Architecture::Ada => tu102::TU102_HAL,
+        Architecture::Hopper | Architecture::BlackwellGB10x | Architecture::BlackwellGB20x => {
+            gh100::GH100_HAL
+        }
+    }
+}
diff --git a/drivers/gpu/nova-core/irq/hal/gh100.rs b/drivers/gpu/nova-core/irq/hal/gh100.rs
new file mode 100644
index 000000000000..10744ac3ab77
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/hal/gh100.rs
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use super::{
+    CpuInterruptHal,
+    LeafCount,
+    MsiType,
+    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 leaf_count(&self) -> LeafCount {
+        LeafCount::Sixteen
+    }
+
+    fn pci_irq_rearm_method(&self, msi_type: MsiType) -> PciIrqRearmMethod {
+        match msi_type {
+            MsiType::Msi => PciIrqRearmMethod::TopEnableCycleServiced,
+            MsiType::MsiX => PciIrqRearmMethod::TopEnableCycleSubtree,
+        }
+    }
+}
+
+const GH100: Gh100 = Gh100;
+pub(super) const GH100_HAL: &dyn CpuInterruptHal = &GH100;
diff --git a/drivers/gpu/nova-core/irq/hal/tu102.rs b/drivers/gpu/nova-core/irq/hal/tu102.rs
new file mode 100644
index 000000000000..fb8ded59c792
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/hal/tu102.rs
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use super::{
+    CpuInterruptHal,
+    LeafCount,
+    MsiType,
+    PciIrqRearmMethod, //
+};
+
+/// GIN parameters for Turing, Ampere, and Ada, which implement an 8-leaf CPU tree.
+struct Tu102;
+
+impl CpuInterruptHal for Tu102 {
+    fn leaf_count(&self) -> LeafCount {
+        LeafCount::Eight
+    }
+
+    fn pci_irq_rearm_method(&self, msi_type: MsiType) -> PciIrqRearmMethod {
+        match msi_type {
+            MsiType::Msi => PciIrqRearmMethod::ConfigMirrorEoi,
+            MsiType::MsiX => PciIrqRearmMethod::TopEnableCycleSubtree,
+        }
+    }
+}
+
+const TU102: Tu102 = Tu102;
+pub(super) const TU102_HAL: &dyn CpuInterruptHal = &TU102;
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 06/14] gpu: nova-core: add the GIN interrupt tree and allocate its vectors
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (4 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 05/14] gpu: nova-core: add the per-architecture GIN CPU interrupt HAL John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:15 ` [PATCH v3 07/14] gpu: nova-core: add an interrupt delivery self-test John Hubbard
                   ` (7 subsequent siblings)
  13 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, Joel Fernandes, John Hubbard, Will Pierce

From: Joel Fernandes <joelagnelf@nvidia.com>

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.

The driver must also allocate a PCI vector for every subtree it enables
at TOP, and register a handler on that vector. MSI-X gives each subtree
its own table entry. Linux masks every entry the driver did not
allocate. An enabled subtree with no entry of its own raises interrupts
that never arrive, and its leaf and TOP bits stay pending and enabled.
MSI instead has one message that the whole tree raises, so a single
entry serves every subtree.

Add an API for one PCIe function's CPU interrupt tree, in which reading
a leaf yields the handle that clears it, and building a tree fails if it
names a subtree the architecture does not implement. Size the vector
allocation to the serviced subtrees, requesting MSI-X entries up to the
highest serviced subtree and falling back to a single MSI rather than a
shared INTx line.

Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
[jhubbard: name the module interrupt_tree with a Tree type that owns the
 BAR mapping, use the canonical NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*
 register names, express vectors, leaves and subtrees as newtypes, let
 the read of a leaf produce the handle that clears it, add the enable
 guards, take the leaf count and the rearm method from the interrupt
 HAL, and read every implemented leaf in drain() rather than descending
 from the TOP registers, which cannot see a vector that latched while
 disabled]
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/irq.rs                |  95 +++++++
 drivers/gpu/nova-core/irq/hal.rs            |   8 +-
 drivers/gpu/nova-core/irq/interrupt_tree.rs | 291 +++++++++++++++++++-
 3 files changed, 386 insertions(+), 8 deletions(-)

diff --git a/drivers/gpu/nova-core/irq.rs b/drivers/gpu/nova-core/irq.rs
index d21dee1b89a0..f6ba883d72c5 100644
--- a/drivers/gpu/nova-core/irq.rs
+++ b/drivers/gpu/nova-core/irq.rs
@@ -12,6 +12,23 @@
 mod interrupt_tree;
 mod regs;
 
+use kernel::{
+    device::Bound,
+    irq,
+    pci::{
+        self,
+        IrqType, //
+    },
+    prelude::*, //
+};
+
+use crate::num;
+
+use interrupt_tree::{
+    Subtree,
+    SubtreeSet, //
+};
+
 /// The message-signaled interrupt type a vector allocation obtained.
 ///
 /// nova-core allocates MSI-X or MSI and nothing else, so the level-triggered INTx that
@@ -24,3 +41,81 @@ pub(crate) enum MsiType {
     /// One table entry per subtree.
     MsiX,
 }
+
+/// The PCI interrupt vector that delivers each serviced subtree.
+///
+/// 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.
+pub(crate) struct SubtreeVectors<'a> {
+    vectors: pci::IrqVectorRegistration<'a>,
+    /// Every subtree nova-core services.
+    serviced: SubtreeSet,
+    /// The type [`alloc_vectors`] obtained, which fixes both the entry each subtree raises and the
+    /// rearm write its handler owes.
+    msi_type: MsiType,
+}
+
+impl SubtreeVectors<'_> {
+    /// Returns the interrupt type these vectors were allocated as.
+    pub(crate) fn msi_type(&self) -> MsiType {
+        self.msi_type
+    }
+
+    /// Returns an [`irq::IrqRequest`] for the vector that delivers `subtree`.
+    ///
+    /// MSI-X gives subtree `N` its own table entry `N`. MSI raises its one message from every
+    /// subtree, and nova-core allocates a single entry for it.
+    ///
+    /// # Errors
+    ///
+    /// `EINVAL` if `subtree` is not one nova-core services.
+    pub(crate) fn request_for(&self, subtree: Subtree) -> Result<irq::IrqRequest<'_>> {
+        if !self.serviced.contains(subtree) {
+            return Err(EINVAL);
+        }
+
+        let entry = match self.msi_type {
+            MsiType::MsiX => num::u32_as_usize(subtree.index()),
+            MsiType::Msi => 0,
+        };
+
+        self.vectors.index(entry).map(Into::into)
+    }
+}
+
+/// Allocates the interrupt vectors that the subtrees in `serviced` require.
+///
+/// Every subtree nova-core enables at `TOP` must have an allocated vector with a registered
+/// handler, or the interrupts it raises are lost. Linux masks every MSI-X entry a driver did not
+/// allocate, so the MSI-X request covers every entry up to the highest serviced subtree. A part
+/// whose MSI-X table is smaller than that falls back to a single MSI, which serves the whole tree.
+///
+/// # Errors
+///
+/// `EINVAL` if `serviced` is empty. The error from the MSI request if neither type can be
+/// allocated.
+pub(crate) fn alloc_vectors(
+    pdev: &pci::Device<Bound>,
+    serviced: SubtreeSet,
+) -> Result<SubtreeVectors<'_>> {
+    if serviced.is_empty() {
+        return Err(EINVAL);
+    }
+
+    // One entry per subtree up to and including the highest serviced one.
+    let entries = serviced.span();
+
+    let (vectors, msi_type) = pdev
+        .alloc_irq_vectors(entries, entries, IrqType::MsiX.into())
+        .map(|vectors| (vectors, MsiType::MsiX))
+        .or_else(|_| {
+            pdev.alloc_irq_vectors(1, 1, IrqType::Msi.into())
+                .map(|vectors| (vectors, MsiType::Msi))
+        })?;
+
+    Ok(SubtreeVectors {
+        vectors,
+        serviced,
+        msi_type,
+    })
+}
diff --git a/drivers/gpu/nova-core/irq/hal.rs b/drivers/gpu/nova-core/irq/hal.rs
index 1ea677e37e56..07604458dbbb 100644
--- a/drivers/gpu/nova-core/irq/hal.rs
+++ b/drivers/gpu/nova-core/irq/hal.rs
@@ -25,7 +25,7 @@
         Subtree,
         SubtreeSet, //
     },
-    regs,
+    regs::*,
     MsiType, //
 };
 
@@ -63,7 +63,7 @@ pub(super) fn rearm(self, bar: Bar0<'_>, serviced: SubtreeSet, subtree: Subtree)
         let subtrees = match self {
             // The written value is ignored, so any write rearms delivery.
             Self::ConfigMirrorEoi => {
-                bar.write(regs::NV_XVE_CYA_2, 0u32.into());
+                bar.write(NV_XVE_CYA_2, 0u32.into());
                 return;
             }
             Self::TopEnableCycleServiced => serviced,
@@ -71,10 +71,10 @@ pub(super) fn rearm(self, bar: Bar0<'_>, serviced: SubtreeSet, subtree: Subtree)
         };
 
         bar.write_reg(
-            regs::NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_CLEAR::zeroed().with_subtrees(subtrees),
+            NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_CLEAR::zeroed().with_subtrees(subtrees),
         );
         bar.write_reg(
-            regs::NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_SET::zeroed().with_subtrees(subtrees),
+            NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_SET::zeroed().with_subtrees(subtrees),
         );
     }
 }
diff --git a/drivers/gpu/nova-core/irq/interrupt_tree.rs b/drivers/gpu/nova-core/irq/interrupt_tree.rs
index 5aa447cf0ec4..0b4dc2fc8ea8 100644
--- a/drivers/gpu/nova-core/irq/interrupt_tree.rs
+++ b/drivers/gpu/nova-core/irq/interrupt_tree.rs
@@ -1,18 +1,42 @@
 // SPDX-License-Identifier: GPL-2.0
 // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 
-//! Vector addressing in the GIN CPU interrupt tree.
+//! The GIN CPU interrupt tree for one PCIe function.
 //!
 //! A vector's number fixes where it latches: leaf `vector / 32` at bit `vector % 32`, and that
 //! leaf belongs to subtree `vector / 64`. The types here keep those three views apart, so a leaf
 //! index, a set of vectors within one leaf, and a `TOP` bit cannot stand in for one another.
+//!
+//! Servicing a 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. Only
+//! [`Tree::read_pending`] produces a [`LeafPending`], and only a [`LeafPending`] can clear, so the
+//! wrong order does not compile.
+//!
+//! Serializing access to the tree is the caller's responsibility.
 
 use kernel::{
+    io::{
+        register::Array,
+        Io, //
+    },
     num::Bounded,
     prelude::*, //
 };
 
-use crate::num;
+use crate::{
+    driver::Bar0,
+    gpu::Chipset,
+    num, //
+};
+
+use super::{
+    hal::{
+        cpu_interrupt_hal,
+        PciIrqRearmMethod, //
+    },
+    regs::*,
+    MsiType, //
+};
 
 /// Number of bits a leaf index occupies, covering the `0..16` leaf register arrays.
 const LEAF_INDEX_BITS: u32 = 4;
@@ -113,7 +137,7 @@ pub(super) const fn contains(self, other: Self) -> bool {
 ///
 /// Exactly one bit is set.
 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub(super) struct Subtree(u32);
+pub(crate) struct Subtree(u32);
 
 impl Subtree {
     /// Returns this subtree's index within the tree.
@@ -131,7 +155,7 @@ pub(super) const fn into_raw(self) -> u32 {
 
 /// Set of subtrees, one bit per subtree, in the layout the `TOP` enable registers take.
 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub(super) struct SubtreeSet(u32);
+pub(crate) struct SubtreeSet(u32);
 
 impl SubtreeSet {
     /// Returns whether `subtree` belongs to this set.
@@ -240,3 +264,262 @@ fn from(vector: GinVector) -> Self {
         vector.0.extend()
     }
 }
+
+/// Clears the enables of the vectors set in `vectors` for `leaf` (`LEAF_EN_CLEAR`).
+///
+/// Shared by [`Tree::disable_leaf`] and by [`LeafEnableGuard`]'s [`Drop`], which has no tree to
+/// reach through.
+fn clear_leaf_enables(bar: Bar0<'_>, leaf: LeafIndex, vectors: LeafMask) {
+    bar.write(
+        NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_EN_CLEAR::at(*leaf),
+        NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_EN_CLEAR::zeroed().with_vectors(vectors),
+    );
+}
+
+/// Clears the `TOP` enables of every subtree in `serviced` (`TOP_EN_CLEAR`).
+fn clear_top_enables(bar: Bar0<'_>, serviced: SubtreeSet) {
+    bar.write_reg(NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_CLEAR::zeroed().with_subtrees(serviced));
+}
+
+/// Clears the pending vectors set in `vectors` for `leaf` (write-1-to-clear).
+fn clear_leaf_pending(bar: Bar0<'_>, leaf: LeafIndex, vectors: LeafMask) {
+    if !vectors.is_empty() {
+        bar.write(
+            NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF::at(*leaf),
+            NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF::zeroed().with_vectors(vectors),
+        );
+    }
+}
+
+/// Returns every leaf a tree of `leaves` leaves implements.
+fn implemented_leaves(leaves: LeafCount) -> impl Iterator<Item = LeafIndex> {
+    (0..leaves.into_raw()).filter_map(LeafIndex::try_new)
+}
+
+/// The GIN CPU interrupt tree for a single PCIe function.
+pub(super) struct Tree<'a> {
+    /// Borrowed BAR0, through which every tree register is reached.
+    bar: Bar0<'a>,
+    /// Number of leaves this tree implements.
+    leaves: LeafCount,
+    /// The subtrees this tree enables and services.
+    serviced: SubtreeSet,
+    /// Method that rearms PCI interrupt delivery.
+    rearm: PciIrqRearmMethod,
+}
+
+impl<'a> Tree<'a> {
+    /// Creates a `Tree` for `chipset` covering `serviced`, with the rearm method that `msi_type`
+    /// requires.
+    ///
+    /// Each serviced subtree must have an allocated PCI vector and a registered handler, which
+    /// [`super::alloc_vectors`] sizes the allocation for.
+    ///
+    /// # Errors
+    ///
+    /// `EINVAL` if `serviced` names a subtree this architecture does not implement. Such a subtree
+    /// has no `TOP` bit, so nothing would deliver the vectors behind it.
+    pub(super) fn new(
+        bar: Bar0<'a>,
+        chipset: Chipset,
+        msi_type: MsiType,
+        serviced: SubtreeSet,
+    ) -> Result<Self> {
+        let hal = cpu_interrupt_hal(chipset);
+        let leaves = hal.leaf_count();
+
+        if serviced.intersection(leaves.subtree_set()) != serviced {
+            return Err(EINVAL);
+        }
+
+        Ok(Self {
+            bar,
+            leaves,
+            serviced,
+            rearm: hal.pci_irq_rearm_method(msi_type),
+        })
+    }
+
+    /// Rearms PCI interrupt delivery to the CPU after servicing `subtree`, the one subtree the
+    /// calling handler serves.
+    ///
+    /// A handler must call this before it returns, or it receives no further interrupts.
+    pub(super) fn rearm_pci_irq(&self, subtree: Subtree) {
+        self.rearm.rearm(self.bar, self.serviced, subtree);
+    }
+
+    /// Enables this tree's serviced subtrees (`TOP_EN_SET`).
+    pub(super) fn enable_top(&self) {
+        self.bar.write_reg(
+            NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_SET::zeroed().with_subtrees(self.serviced),
+        );
+    }
+
+    /// Disables this tree's serviced subtrees (`TOP_EN_CLEAR`).
+    pub(super) fn disable_top(&self) {
+        clear_top_enables(self.bar, self.serviced);
+    }
+
+    /// Enables this tree's serviced subtrees until the returned guard drops.
+    pub(super) fn enable_top_guarded(&self) -> TopEnableGuard<'a> {
+        self.enable_top();
+
+        TopEnableGuard {
+            bar: self.bar,
+            serviced: self.serviced,
+        }
+    }
+
+    /// Enables the vectors set in `vectors` for `leaf` (`LEAF_EN_SET`).
+    ///
+    /// This is the per-vector counterpart of [`Self::enable_top`], which enables whole subtrees.
+    pub(super) fn enable_leaf(&self, leaf: LeafIndex, vectors: LeafMask) {
+        self.bar.write(
+            NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_EN_SET::at(*leaf),
+            NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_EN_SET::zeroed().with_vectors(vectors),
+        );
+    }
+
+    /// Disables the vectors set in `vectors` for `leaf` (`LEAF_EN_CLEAR`).
+    pub(super) fn disable_leaf(&self, leaf: LeafIndex, vectors: LeafMask) {
+        clear_leaf_enables(self.bar, leaf, vectors);
+    }
+
+    /// Enables `vectors` for `leaf` until the returned guard drops.
+    pub(super) fn enable_leaf_guarded(
+        &self,
+        leaf: LeafIndex,
+        vectors: LeafMask,
+    ) -> LeafEnableGuard<'a> {
+        self.enable_leaf(leaf, vectors);
+
+        LeafEnableGuard {
+            bar: self.bar,
+            leaf,
+            vectors,
+        }
+    }
+
+    /// Reads the vectors pending in `leaf`.
+    pub(super) fn read_pending(&self, leaf: LeafIndex) -> LeafPending<'a> {
+        let pending = self
+            .bar
+            .read(NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF::at(*leaf))
+            .vectors();
+
+        LeafPending {
+            bar: self.bar,
+            leaf,
+            pending,
+        }
+    }
+
+    /// Injects a software interrupt for `vector` via the trigger register.
+    ///
+    /// # Errors
+    ///
+    /// `EINVAL` if `vector` lies outside this tree.
+    // Only the interrupt self-test injects a software interrupt.
+    #[expect(dead_code)]
+    pub(super) fn trigger(&self, vector: GinVector) -> Result {
+        vector.validate(self.leaves)?;
+        self.bar.write_reg(
+            NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_TRIGGER::zeroed().with_vector(vector),
+        );
+
+        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) {
+        for leaf in implemented_leaves(self.leaves) {
+            self.disable_leaf(leaf, LeafMask::all());
+        }
+    }
+
+    /// Clears every pending bit in every implemented leaf.
+    ///
+    /// Disables this tree's serviced subtrees at `TOP` for the walk and leaves them disabled, so a
+    /// caller that wants delivery enables them itself once it is ready to receive. The leaves
+    /// cleared reach subtrees the driver does not service, and the `TOP_EN` write does not.
+    ///
+    /// Call `drain()` only during probe. It must not run concurrently with an interrupt handler.
+    pub(super) fn drain(&self) {
+        self.disable_top();
+
+        // `TOP` summarizes enabled leaf bits, so a vector that latched while it was disabled does
+        // not appear there.
+        for leaf in implemented_leaves(self.leaves) {
+            let pending = self.read_pending(leaf);
+            if !pending.vectors().is_empty() {
+                pending.clear();
+            }
+        }
+    }
+}
+
+/// The vectors read pending from one leaf.
+///
+/// Holding one is the proof that the leaf was read, which is what [`Self::clear`] and
+/// [`Self::clear_vectors`] require.
+pub(super) struct LeafPending<'a> {
+    bar: Bar0<'a>,
+    leaf: LeafIndex,
+    pending: LeafMask,
+}
+
+impl LeafPending<'_> {
+    /// Returns the vectors that were pending.
+    pub(super) fn vectors(&self) -> LeafMask {
+        self.pending
+    }
+
+    /// Clears every vector that was pending, by writing its bits back (write-1-to-clear).
+    pub(super) fn clear(&self) {
+        self.clear_vectors(self.pending);
+    }
+
+    /// 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`], which clears
+    /// every vector the leaf had pending.
+    pub(super) fn clear_vectors(&self, vectors: LeafMask) {
+        clear_leaf_pending(self.bar, self.leaf, vectors);
+    }
+}
+
+/// Keeps a leaf's vectors enabled for as long as it is held.
+///
+/// Dropping it disables the same vectors, so an error path cannot leave a source enabled with no
+/// handler behind it.
+pub(super) struct LeafEnableGuard<'a> {
+    bar: Bar0<'a>,
+    leaf: LeafIndex,
+    vectors: LeafMask,
+}
+
+impl Drop for LeafEnableGuard<'_> {
+    fn drop(&mut self) {
+        clear_leaf_enables(self.bar, self.leaf, self.vectors);
+    }
+}
+
+/// Keeps a tree's serviced subtrees enabled at `TOP` for as long as it is held.
+pub(super) struct TopEnableGuard<'a> {
+    bar: Bar0<'a>,
+    serviced: SubtreeSet,
+}
+
+impl Drop for TopEnableGuard<'_> {
+    fn drop(&mut self) {
+        clear_top_enables(self.bar, self.serviced);
+    }
+}
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 07/14] gpu: nova-core: add an interrupt delivery self-test
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (5 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 06/14] gpu: nova-core: add the GIN interrupt tree and allocate its vectors John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:29   ` sashiko-bot
  2026-09-03  3:15 ` [PATCH v3 08/14] gpu: nova-core: log GSP events instead of discarding them John Hubbard
                   ` (6 subsequent siblings)
  13 siblings, 1 reply; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard, Will Pierce, Joel Fernandes

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.

Allocate the PCI interrupt vectors alongside the GPU's other resources
rather than in the test, because the vectors are allocated once for the
whole PCI device rather than per handler. The test takes the vector for
the subtree it services.

Assisted-by: Cursor:claude-opus-5
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Co-developed-by: Joel Fernandes <joelagnelf@nvidia.com>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/Kconfig               |  15 +
 drivers/gpu/nova-core/gpu.rs                |  25 ++
 drivers/gpu/nova-core/irq.rs                |   9 +
 drivers/gpu/nova-core/irq/doorbell_test.rs  | 301 ++++++++++++++++++++
 drivers/gpu/nova-core/irq/interrupt_tree.rs |   2 +-
 drivers/gpu/nova-core/nova_core.rs          |   2 +-
 6 files changed, 352 insertions(+), 2 deletions(-)
 create mode 100644 drivers/gpu/nova-core/irq/doorbell_test.rs

diff --git a/drivers/gpu/nova-core/Kconfig b/drivers/gpu/nova-core/Kconfig
index f918f69e0599..7198fae6b6f4 100644
--- a/drivers/gpu/nova-core/Kconfig
+++ b/drivers/gpu/nova-core/Kconfig
@@ -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.
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index e1ac8ee9ba4d..8a9bc4baf9ac 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -29,6 +29,7 @@
         Gsp,
         GspBootContext, //
     },
+    irq::SubtreeVectors,
     vgpu::VgpuManager, //
 };
 
@@ -292,6 +293,12 @@ pub(crate) struct Gpu<'gpu> {
     /// Must be kept declared *after* `gsp_resources`, as the latter's `PinnedDrop` implementation
     /// requires the sysmem flush page to be in place.
     sysmem_flush: SysmemFlush<'gpu>,
+    /// 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: &'gpu SubtreeVectors<'gpu>,
+    /// PCI interrupt vector allocation. Dropped last (struct field drop order).
+    #[pin]
+    vectors: SubtreeVectors<'gpu>,
 }
 
 #[pinned_drop]
@@ -330,6 +337,12 @@ pub(crate) fn new<'a>(
         let dev = pdev.as_ref();
 
         try_pin_init!(Self {
+            vectors: crate::irq::alloc_vectors(pdev, crate::irq::SERVICED_SUBTREE.into())?,
+
+            // SAFETY: `vectors` is initialized above, lives at a pinned stable address, and is
+            // dropped after every field that uses `vectors_ref` (struct field drop order).
+            vectors_ref: unsafe { &*core::ptr::from_ref(vectors.as_ref().get_ref()) },
+
             spec: Spec::new(dev, bar).inspect(|spec| {
                 dev_info!(dev,"NVIDIA ({})\n", spec);
             })?,
@@ -347,6 +360,18 @@ pub(crate) fn new<'a>(
                     .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.
+            _: {
+                // `vectors_ref` exists for the self-test below, which this configuration omits.
+                #[cfg(not(CONFIG_NOVA_CORE_IRQ_SELFTEST))]
+                let _ = vectors_ref;
+
+                #[cfg(CONFIG_NOVA_CORE_IRQ_SELFTEST)]
+                crate::irq::doorbell_test::run_selftest(pdev, bar, spec.chipset, vectors_ref)?;
+            },
+
             // Initialize this early because `gsp_resources` depends on it.
             sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?,
 
diff --git a/drivers/gpu/nova-core/irq.rs b/drivers/gpu/nova-core/irq.rs
index f6ba883d72c5..f44897692b74 100644
--- a/drivers/gpu/nova-core/irq.rs
+++ b/drivers/gpu/nova-core/irq.rs
@@ -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;
 mod regs;
@@ -25,10 +27,17 @@
 use crate::num;
 
 use interrupt_tree::{
+    GinVector,
     Subtree,
     SubtreeSet, //
 };
 
+/// The subtree nova-core allocates PCI vectors for.
+///
+/// Every source nova-core services latches in this one subtree, so a single allocation covers all
+/// of them.
+pub(crate) const SERVICED_SUBTREE: Subtree = GinVector::new::<129>().subtree();
+
 /// The message-signaled interrupt type a vector allocation obtained.
 ///
 /// nova-core allocates MSI-X or MSI and nothing else, so the level-triggered INTx that
diff --git a/drivers/gpu/nova-core/irq/doorbell_test.rs b/drivers/gpu/nova-core/irq/doorbell_test.rs
new file mode 100644
index 000000000000..a232a83b62f6
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/doorbell_test.rs
@@ -0,0 +1,301 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! Interrupt delivery self-test, driven through the CPU doorbell vector.
+//!
+//! Exercises the whole PCI interrupt path (GPU to PCIe to CPU to handler) with no GSP dependency:
+//! it injects a known vector through the GIN software trigger and confirms the handler runs. Two
+//! interrupts are triggered one at a time, which also covers the rearm that every delivery after
+//! the first depends on. Gated behind `CONFIG_NOVA_CORE_IRQ_SELFTEST` and run before GSP boot, so
+//! it never observes or clears GSP interrupt state.
+//!
+//! See `Documentation/gpu/nova/core/interrupts.rst`.
+
+use core::pin::Pin;
+
+use kernel::{
+    device::Bound,
+    irq,
+    pci,
+    prelude::*,
+    sync::{
+        atomic::{
+            Atomic,
+            Relaxed, //
+        },
+        Completion, //
+    },
+    time, //
+};
+
+use super::{
+    interrupt_tree::{
+        GinVector,
+        LeafEnableGuard,
+        LeafMask,
+        Subtree,
+        TopEnableGuard,
+        Tree, //
+    },
+    SubtreeVectors, //
+};
+
+use crate::{
+    driver::Bar0,
+    gpu::Chipset, //
+};
+
+/// Fixed vector for the CPU doorbell.
+///
+/// The resource manager pins the CPU doorbell to this vector on every supported chip, so nova-core
+/// uses the constant directly instead of discovering it at runtime.
+const DOORBELL_VECTOR: GinVector = GinVector::new::<129>();
+
+/// Subtree carrying the doorbell vector, and the only subtree this test services.
+///
+/// Derived from the vector so that changing `DOORBELL_VECTOR` moves the subtree it enables and the
+/// handler together.
+const DOORBELL_SUBTREE: Subtree = DOORBELL_VECTOR.subtree();
+
+/// Time allowed for each of the two deliveries to arrive.
+const DELIVERY_TIMEOUT_MS: time::Msecs = 1000;
+
+/// Interrupt handler installed by the self-test.
+///
+/// Services the doorbell the way a notification source is serviced: it clears its own leaf bit and
+/// rearms PCI interrupt delivery, leaving the rest of the tree untouched. It records the leaf's
+/// pending bits seen on each of the first two deliveries and signals the matching completion.
+#[pin_data]
+struct DoorbellTestHandler<'a> {
+    /// The interrupt tree, which carries the borrowed BAR0 that register access needs.
+    tree: Tree<'a>,
+    /// Signalled by the first delivery.
+    #[pin]
+    first: Completion,
+    /// Signalled by the second delivery.
+    #[pin]
+    second: Completion,
+    /// Count of deliveries this handler has serviced.
+    irq_count: Atomic<u32>,
+    /// Doorbell leaf's pending bits observed on the first delivery.
+    first_pending: Atomic<u32>,
+    /// Doorbell leaf's pending bits observed on the second delivery.
+    second_pending: Atomic<u32>,
+}
+
+impl irq::Handler for DoorbellTestHandler<'_> {
+    fn handle(&self) -> irq::IrqReturn {
+        // Clear only this handler's own bit and leave `TOP_EN` alone. A full walk disables and
+        // enables the tree, which produces a delivery edge by itself and would hide a missing PCI
+        // interrupt rearm.
+        let leaf = self.tree.read_pending(DOORBELL_VECTOR.leaf_index());
+        let pending = leaf.vectors();
+        if !pending.contains(DOORBELL_VECTOR.leaf_mask()) {
+            self.tree.rearm_pci_irq(DOORBELL_SUBTREE);
+            return irq::IrqReturn::None;
+        }
+        leaf.clear_vectors(DOORBELL_VECTOR.leaf_mask());
+
+        let count = self.irq_count.fetch_add(1, Relaxed);
+
+        // Rearm before signalling, so delivery is possible again by the time the waiting thread
+        // triggers the next vector.
+        self.tree.rearm_pci_irq(DOORBELL_SUBTREE);
+
+        match count {
+            0 => {
+                self.first_pending.store(pending.into_raw(), Relaxed);
+                self.first.complete_all();
+            }
+            1 => {
+                self.second_pending.store(pending.into_raw(), Relaxed);
+                self.second.complete_all();
+            }
+            _ => (),
+        }
+
+        irq::IrqReturn::Handled
+    }
+}
+
+/// Everything the running self-test owns, torn down in declaration order.
+///
+/// That order is what every exit path, including an early error, needs: disabling the leaf stops
+/// new deliveries, dropping the registration runs `free_irq()`, which waits for a handler still in
+/// flight, and only then are the tree's subtrees disabled, so a late handler cannot rearm them.
+struct SelftestResources<'a, 'r> {
+    _leaf_guard: LeafEnableGuard<'a>,
+    reg: Pin<KBox<irq::Registration<'r, DoorbellTestHandler<'a>>>>,
+    _top_guard: TopEnableGuard<'a>,
+}
+
+impl<'a> SelftestResources<'a, '_> {
+    /// Returns the registered handler.
+    fn handler(&self) -> &DoorbellTestHandler<'a> {
+        self.reg.handler()
+    }
+
+    /// Disables the doorbell source and waits for a handler already running on another CPU.
+    ///
+    /// On return no further delivery can reach the handler, so its counters and the doorbell
+    /// leaf hold their final values.
+    fn quiesce_source(&self) {
+        self.handler()
+            .tree
+            .disable_leaf(DOORBELL_VECTOR.leaf_index(), DOORBELL_VECTOR.leaf_mask());
+        self.reg.synchronize();
+    }
+}
+
+/// Runs the interrupt delivery self-test.
+///
+/// Quiesces the interrupt tree, registers a temporary handler, and injects the doorbell vector
+/// through the GIN software trigger twice, one delivery at a time. This validates the PCI
+/// interrupt path from GIN to the ISR without GSP firmware, including the rearm without which only
+/// the first interrupt would arrive. The handler, its IRQ registration, and all tree state are
+/// torn down before this returns.
+///
+/// # Errors
+///
+/// `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: &'a SubtreeVectors<'a>,
+) -> Result {
+    // The interrupt type decides how the handler rearms delivery, so the tree takes it from
+    // probe's allocation.
+    let request = vectors.request_for(DOORBELL_SUBTREE)?;
+    let msi_type = vectors.msi_type();
+    let tree = Tree::new(bar, chipset, msi_type, DOORBELL_SUBTREE.into())?;
+    let doorbell = DOORBELL_VECTOR.leaf_index();
+    let doorbell_mask = DOORBELL_VECTOR.leaf_mask();
+
+    // Under MSI-X the subtree index is also the table entry the delivery arrives on, so a pass
+    // shows that the per-subtree routing works. Under MSI every subtree shares one entry.
+    dev_info!(
+        pdev.as_ref(),
+        "interrupt self-test: starting on vector {}, subtree {}, with {:?}\n",
+        DOORBELL_VECTOR.into_raw(),
+        DOORBELL_SUBTREE.index(),
+        msi_type,
+    );
+
+    // No delivery may reach the CPU before a handler is registered, and a vector left enabled by
+    // boot would fail the pending checks below. `drain` leaves the top level disabled.
+    tree.disable_all_leaves();
+    tree.drain();
+
+    // A delivery can be credited to the trigger below only if the vector starts out clear, so
+    // refuse to run otherwise.
+    let pre_pending = tree.read_pending(doorbell).vectors();
+    if pre_pending.contains(doorbell_mask) {
+        dev_warn!(
+            pdev.as_ref(),
+            "interrupt self-test: failed, vector {} already pending (leaf[{}] pending {:#x})\n",
+            DOORBELL_VECTOR.into_raw(),
+            doorbell.get(),
+            pre_pending.into_raw(),
+        );
+        return Err(EIO);
+    }
+
+    let handler_init = try_pin_init!(DoorbellTestHandler {
+        tree,
+        first <- Completion::new(),
+        second <- Completion::new(),
+        irq_count: Atomic::new(0),
+        first_pending: Atomic::new(0),
+        second_pending: Atomic::new(0),
+    }? Error);
+
+    // Register the handler before allowing any source to fire.
+    let reg = KBox::pin_init(
+        // SAFETY: the registration is owned by `resources` 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 {
+            irq::Registration::new(
+                request,
+                irq::Flags::TRIGGER_NONE,
+                c"nova-core",
+                handler_init,
+            )
+        },
+        GFP_KERNEL,
+    )?;
+
+    // From here every exit must tear down the source, the registration, and the tree. The fields
+    // are initialized in the order the hardware requires, which is the reverse of the declaration
+    // order that tears them down: the handler is registered above before either source is
+    // enabled, the leaf next, and the top level last.
+    let resources = SelftestResources {
+        _leaf_guard: reg
+            .handler()
+            .tree
+            .enable_leaf_guarded(doorbell, doorbell_mask),
+        _top_guard: reg.handler().tree.enable_top_guarded(),
+        reg,
+    };
+    let handler = resources.handler();
+
+    handler.tree.trigger(DOORBELL_VECTOR)?;
+    let mut completed = handler
+        .first
+        .wait_for_completion_timeout(time::msecs_to_jiffies(DELIVERY_TIMEOUT_MS))
+        .is_some();
+
+    // Trigger the second interrupt only once the first handler has cleared its leaf bit and
+    // rearmed, so the two cannot coalesce into one delivery and a handler that never rearms
+    // cannot pass.
+    if completed {
+        handler.tree.trigger(DOORBELL_VECTOR)?;
+        completed = handler
+            .second
+            .wait_for_completion_timeout(time::msecs_to_jiffies(DELIVERY_TIMEOUT_MS))
+            .is_some();
+    }
+
+    // Stop the source and wait out any handler still running, so the values read below are the
+    // final ones.
+    resources.quiesce_source();
+
+    let count = handler.irq_count.load(Relaxed);
+    let first_pending = LeafMask::from_raw(handler.first_pending.load(Relaxed));
+    let second_pending = LeafMask::from_raw(handler.second_pending.load(Relaxed));
+    let residual = handler.tree.read_pending(doorbell).vectors();
+
+    // The self-test runs before GSP boot on a leaf that `drain` has just cleared, and nothing
+    // triggers the vector after the second delivery, so each delivery must find the doorbell bit
+    // and nothing else, and the leaf must end clear.
+    if completed
+        && count == 2
+        && first_pending == doorbell_mask
+        && second_pending == doorbell_mask
+        && !residual.contains(doorbell_mask)
+    {
+        dev_info!(
+            pdev.as_ref(),
+            "interrupt self-test: passed, subtree {}, {} deliveries\n",
+            DOORBELL_SUBTREE.index(),
+            count,
+        );
+        Ok(())
+    } else {
+        dev_warn!(
+            pdev.as_ref(),
+            "interrupt self-test: failed, {} of 2 deliveries, leaf[{}] pending {:#x} and {:#x}, \
+             {:#x} left set\n",
+            count,
+            doorbell.get(),
+            first_pending.into_raw(),
+            second_pending.into_raw(),
+            residual.into_raw(),
+        );
+        Err(if completed { EIO } else { ETIMEDOUT })
+    }
+}
diff --git a/drivers/gpu/nova-core/irq/interrupt_tree.rs b/drivers/gpu/nova-core/irq/interrupt_tree.rs
index 0b4dc2fc8ea8..f27f0137dffe 100644
--- a/drivers/gpu/nova-core/irq/interrupt_tree.rs
+++ b/drivers/gpu/nova-core/irq/interrupt_tree.rs
@@ -420,7 +420,7 @@ pub(super) fn read_pending(&self, leaf: LeafIndex) -> LeafPending<'a> {
     ///
     /// `EINVAL` if `vector` lies outside this tree.
     // Only the interrupt self-test injects a software interrupt.
-    #[expect(dead_code)]
+    #[cfg_attr(not(CONFIG_NOVA_CORE_IRQ_SELFTEST), expect(dead_code))]
     pub(super) fn trigger(&self, vector: GinVector) -> Result {
         vector.validate(self.leaves)?;
         self.bar.write_reg(
diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
index dfd11dfe562c..65ce547bd44e 100644
--- a/drivers/gpu/nova-core/nova_core.rs
+++ b/drivers/gpu/nova-core/nova_core.rs
@@ -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]
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 08/14] gpu: nova-core: log GSP events instead of discarding them
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (6 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 07/14] gpu: nova-core: add an interrupt delivery self-test John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:15 ` [PATCH v3 09/14] gpu: nova-core: recover the GSP receive path from corrupt framing John Hubbard
                   ` (5 subsequent siblings)
  13 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, 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.

Log every non-reply message according to its function code, and leave
the in-flight command waiting for its reply. The logging runs on the
existing command and wait loops, so events reach the log 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
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 58 +++++++++++++++++++++++++------
 1 file changed, 47 insertions(+), 11 deletions(-)

diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index 14a711307654..5572224db233 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -556,8 +556,8 @@ 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 is logged if it is an error record, and
+    /// ignored otherwise.
     ///
     /// The queue is locked for the entire send+receive cycle to ensure that no other command can
     /// be interleaved.
@@ -814,8 +814,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::classify_event`] and `ERANGE` is
+    /// returned.
     ///
     /// The read pointer is always advanced past the message, regardless of whether it matched.
     ///
@@ -824,8 +826,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>
@@ -834,11 +835,12 @@ 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();
 
-        // 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 matches!(function, Ok(f) if f == M::FUNCTION) {
             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]);
 
@@ -849,11 +851,13 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
                         dev_warn!(
                             &self.dev,
                             "GSP message {:?} has unprocessed data\n",
-                            function
+                            M::FUNCTION
                         );
                     }
                 })
         } else {
+            self.classify_event(function, seq);
+
             Err(ERANGE)
         };
 
@@ -864,4 +868,36 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
 
         result
     }
+
+    /// Logs a GSP message that is not the reply a caller is waiting for, according to what its
+    /// function code reports.
+    ///
+    /// 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 classify_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
+                );
+            }
+        }
+    }
 }
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 09/14] gpu: nova-core: recover the GSP receive path from corrupt framing
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (7 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 08/14] gpu: nova-core: log GSP events instead of discarding them John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-04 10:53   ` Alexandre Courbot
  2026-09-03  3:15 ` [PATCH v3 10/14] gpu: nova-core: bound a GSP wait by a single deadline John Hubbard
                   ` (4 subsequent siblings)
  13 siblings, 1 reply; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, 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, log what was
inconsistent, 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
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/gsp/cmdq.rs | 96 +++++++++++++++++++++----------
 1 file changed, 66 insertions(+), 30 deletions(-)

diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index 5572224db233..ce4d6a111e68 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -2,7 +2,10 @@
 
 mod continuation;
 
-use core::mem;
+use core::{
+    cell::Cell,
+    mem, //
+};
 
 use kernel::{
     device,
@@ -11,6 +14,7 @@
         CoherentBox,
         DmaAddress, //
     },
+    fmt,
     io::{
         io_project,
         poll::read_poll_timeout,
@@ -531,6 +535,7 @@ pub(crate) fn new(dev: &device::Device<device::Bound>) -> impl PinInit<Self, Err
                     dev: dev.into(),
                     gsp_mem,
                     seq: 0,
+                    poisoned: Cell::new(false),
                 }),
             }))
         })
@@ -624,6 +629,12 @@ struct CmdqInner {
     dev: ARef<device::Device>,
     /// Current command sequence number.
     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,
 }
@@ -732,6 +743,19 @@ fn send_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
         }
     }
 
+    /// Marks the queue unusable and returns the error every later receive fails with.
+    ///
+    /// `reason` names the inconsistency. Without it the failure is invisible, because the queue
+    /// just stops producing messages.
+    ///
+    /// Takes `&self` so the shared-borrow read path [`Self::wait_for_msg`] can call it.
+    fn poison(&self, reason: fmt::Arguments<'_>) -> Error {
+        dev_err!(&self.dev, "GSP RPC: receive: queue poisoned: {}\n", reason);
+        self.poisoned.set(true);
+
+        EIO
+    }
+
     /// Wait for a message to become available on the message queue.
     ///
     /// This works purely at the transport layer and does not interpret or validate the message
@@ -746,11 +770,13 @@ fn send_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
     /// # 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()),
@@ -761,7 +787,12 @@ 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 {
+            return Err(self.poison(fmt!(
+                "read area of {} bytes is shorter than a message header",
+                slice_1.len()
+            )));
+        };
 
         dev_dbg!(
             &self.dev,
@@ -775,7 +806,11 @@ 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 {
-            return Err(EIO);
+            return Err(self.poison(fmt!(
+                "message advertises {} payload bytes but only {} are readable",
+                payload_length,
+                slice_1.len() + slice_2.len()
+            )));
         }
 
         // Cut the message slices down to the actual length of the message.
@@ -798,12 +833,10 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
             slice_2,
         ])) != 0
         {
-            dev_err!(
-                &self.dev,
-                "GSP RPC: receive: Call {} - bad checksum\n",
+            return Err(self.poison(fmt!(
+                "message with sequence {} has a bad checksum",
                 header.sequence()
-            );
-            return Err(EIO);
+            )));
         }
 
         Ok(GspMessage {
@@ -824,8 +857,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.
@@ -838,23 +871,26 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
         let function = message.header.function();
         let seq = message.header.sequence();
 
-        // 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, including a failed decode.
         let result = if matches!(function, Ok(f) if f == M::FUNCTION) {
-            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 {
             self.classify_event(function, seq);
 
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 10/14] gpu: nova-core: bound a GSP wait by a single deadline
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (8 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 09/14] gpu: nova-core: recover the GSP receive path from corrupt framing John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-04 11:13   ` Alexandre Courbot
  2026-09-03  3:15 ` [PATCH v3 11/14] gpu: nova-core: add the falcon interrupt status and routing registers John Hubbard
                   ` (3 subsequent siblings)
  13 siblings, 1 reply; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard

The GSP posts unsolicited events on the same queue it posts replies on,
so a caller waiting for one message logs 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. The wait also released
the queue lock between reads, so a command sent from another thread
could consume the awaited event and leave the waiter to time out.

Compute one absolute deadline when the wait begins and pass the time
remaining to each read, and hold the queue lock across the whole wait,
so the wait is bounded however many events arrive first and no other
caller can take the event it waits for.

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
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/gsp/cmdq.rs      | 50 +++++++++++++++++++++-----
 drivers/gpu/nova-core/gsp/commands.rs  |  8 +----
 drivers/gpu/nova-core/gsp/sequencer.rs |  8 +----
 3 files changed, 44 insertions(+), 22 deletions(-)

diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index ce4d6a111e68..a0f995faaee5 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -33,7 +33,11 @@
         },
         Mutex, //
     },
-    time::Delta,
+    time::{
+        Delta,
+        Instant,
+        Monotonic, //
+    },
     transmute::{
         AsBytes,
         FromBytes, //
@@ -569,8 +573,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 arrive
+    ///   while waiting.
     /// - `EIO` if the variable payload requested by the command has not been entirely
     ///   written to by its [`CommandToGsp::init_variable_payload`] method.
     ///
@@ -585,8 +590,13 @@ pub(crate) fn send_command<M>(&self, bar: Bar0<'_>, command: M) -> Result<M::Rep
         let mut inner = self.inner.lock();
         inner.send_command(bar, command)?;
 
+        let deadline = Instant::<Monotonic>::now() + Self::RECEIVE_TIMEOUT;
         loop {
-            match inner.receive_msg::<M::Reply>(Self::RECEIVE_TIMEOUT) {
+            let remaining = deadline - Instant::<Monotonic>::now();
+            if remaining.is_negative() {
+                break Err(ETIMEDOUT);
+            }
+            match inner.receive_msg::<M::Reply>(remaining) {
                 Ok(reply) => break Ok(reply),
                 Err(ERANGE) => continue,
                 Err(e) => break Err(e),
@@ -611,15 +621,39 @@ pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul
         self.inner.lock().send_command(bar, command)
     }
 
-    /// Receive a message from the GSP.
+    /// Waits for an unsolicited GSP event of type `M`, logging any other event that arrives
+    /// first.
+    ///
+    /// The queue is locked for the whole wait, for up to [`Self::RECEIVE_TIMEOUT`], so a
+    /// concurrent command cannot consume the awaited event.
     ///
-    /// See [`CmdqInner::receive_msg`] for details.
-    pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
+    /// # Errors
+    ///
+    /// - `ETIMEDOUT` if the event does not arrive within [`Self::RECEIVE_TIMEOUT`] of the call,
+    ///   however many other events arrive while waiting.
+    /// - `EIO` if the queue is poisoned or a message fails framing or checksum validation (see
+    ///   [`CmdqInner::wait_for_msg`]).
+    ///
+    /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
+    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>,
     {
-        self.inner.lock().receive_msg(timeout)
+        let mut inner = self.inner.lock();
+
+        let deadline = Instant::<Monotonic>::now() + Self::RECEIVE_TIMEOUT;
+        loop {
+            let remaining = deadline - Instant::<Monotonic>::now();
+            if remaining.is_negative() {
+                break Err(ETIMEDOUT);
+            }
+            match inner.receive_msg::<M>(remaining) {
+                Ok(msg) => break Ok(msg),
+                Err(ERANGE) => continue,
+                Err(e) => break Err(e),
+            }
+        }
     }
 }
 
diff --git a/drivers/gpu/nova-core/gsp/commands.rs b/drivers/gpu/nova-core/gsp/commands.rs
index ffc25fd8c47b..61fe93db9e7e 100644
--- a/drivers/gpu/nova-core/gsp/commands.rs
+++ b/drivers/gpu/nova-core/gsp/commands.rs
@@ -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.
diff --git a/drivers/gpu/nova-core/gsp/sequencer.rs b/drivers/gpu/nova-core/gsp/sequencer.rs
index bcad1421953a..e2f1da129d8f 100644
--- a/drivers/gpu/nova-core/gsp/sequencer.rs
+++ b/drivers/gpu/nova-core/gsp/sequencer.rs
@@ -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,
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 11/14] gpu: nova-core: add the falcon interrupt status and routing registers
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (9 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 10/14] gpu: nova-core: bound a GSP wait by a single deadline John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:15 ` [PATCH v3 12/14] gpu: nova-core: drive GSP events with the SWGEN0 interrupt John Hubbard
                   ` (2 subsequent siblings)
  13 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard, Will Pierce

A falcon latches every interrupt cause in IRQSTAT, whichever target the
cause is routed to. On a RISC-V falcon each cause goes either to the
core itself or to the host, and PRISCV_RISCV_IRQMASK and
PRISCV_RISCV_IRQDEST select between them. Open RM intersects the three
registers to get the causes pending for the host.

A falcon signals the interrupt tree on a transition of the causes routed
to the host, so a handler that clears the tree leaf while a cause is
still latched leaves no transition behind. INTR_RETRIGGER supplies one,
and Turing falcons do not implement it.

Add all four, ahead of the GSP event handler that reads them. GA102
moved the routing pair and GA100 kept the Turing offsets, so those two
go in per-chip register modules rather than the common one.

Assisted-by: Cursor:claude-opus-5
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/regs.rs | 66 +++++++++++++++++++++++++++++++++++
 1 file changed, 66 insertions(+)

diff --git a/drivers/gpu/nova-core/regs.rs b/drivers/gpu/nova-core/regs.rs
index 3422b49df7a7..502712e9c161 100644
--- a/drivers/gpu/nova-core/regs.rs
+++ b/drivers/gpu/nova-core/regs.rs
@@ -120,6 +120,14 @@ pub(crate) fn usable_fb_size(self) -> u64 {
         4:4     halt => bool;
     }
 
+    /// Interrupt causes latched at the falcon, one bit per cause.
+    ///
+    /// A cause appears here whoever it is routed to, so a handler on the host side has to
+    /// intersect it with the routing registers to get the causes routed to the host.
+    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;
     }
@@ -247,6 +255,18 @@ pub(crate) fn usable_fb_size(self) -> u64 {
         0:0     reset => bool;
     }
 
+    /// Re-emits the falcon's latched interrupt causes into the interrupt tree.
+    ///
+    /// Write-only. A falcon signals the tree on a transition of the causes routed to the host, 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.
+    ///
+    /// Open RM 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;
@@ -395,6 +415,29 @@ pub(crate) mod gm107 {
     }
 }
 
+pub(crate) mod tu102 {
+    use kernel::io::register;
+
+    use crate::falcon::PFalcon2Base;
+
+    // PRISCV
+    //
+    // The two registers below select which of a RISC-V falcon's interrupt causes reach the host,
+    // in the layout of `NV_PFALCON_FALCON_IRQSTAT`. GA100 uses these offsets as well.
+
+    register! {
+        /// Causes the RISC-V core enables. Read-only to the host.
+        pub(crate) NV_PRISCV_RISCV_IRQMASK(u32) @ PFalcon2Base + 0x000002b4 {
+            31:0    value => u32;
+        }
+
+        /// Causes routed to the host rather than to the RISC-V core itself.
+        pub(crate) NV_PRISCV_RISCV_IRQDEST(u32) @ PFalcon2Base + 0x000002b8 {
+            31:0    value => u32;
+        }
+    }
+}
+
 pub(crate) mod ga100 {
     use kernel::io::register;
 
@@ -407,6 +450,29 @@ pub(crate) mod ga100 {
     }
 }
 
+pub(crate) mod ga102 {
+    use kernel::io::register;
+
+    use crate::falcon::PFalcon2Base;
+
+    // PRISCV
+    //
+    // GA102 moved the two routing registers. GA100 kept the Turing offsets, so this pair covers
+    // GA102 and later rather than the whole Ampere architecture.
+
+    register! {
+        /// Causes the RISC-V core enables. Read-only to the host.
+        pub(crate) NV_PRISCV_RISCV_IRQMASK(u32) @ PFalcon2Base + 0x00000528 {
+            31:0    value => u32;
+        }
+
+        /// Causes routed to the host rather than to the RISC-V core itself.
+        pub(crate) NV_PRISCV_RISCV_IRQDEST(u32) @ PFalcon2Base + 0x0000052c {
+            31:0    value => u32;
+        }
+    }
+}
+
 pub(crate) const NV_THERM_I2CS_SCRATCH_FSP_BOOT_COMPLETE_STATUS_SUCCESS: u32 = 0xff;
 
 pub(crate) mod gh100 {
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 12/14] gpu: nova-core: drive GSP events with the SWGEN0 interrupt
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (10 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 11/14] gpu: nova-core: add the falcon interrupt status and routing registers John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:28   ` sashiko-bot
  2026-09-03  3:15 ` [PATCH v3 13/14] gpu: nova-core: add KUnit tests for the interrupt tree and HALs John Hubbard
  2026-09-03  3:15 ` [PATCH v3 14/14] gpu: nova-core: document the GIN interrupt controller and GSP events John Hubbard
  13 siblings, 1 reply; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard, Will Pierce

The GSP posts events, logs and error records to the GSP-to-CPU queue and
raises the falcon SWGEN0 output. A falcon signals the interrupt tree
only on a transition of the causes it routes to the host, and IRQSTAT
also reports the causes the falcon keeps for its own RISC-V core. GSP
boot polls for its own notifications, so it leaves the SWGEN0 latch set
and leaves pending bits behind 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 causes pending for the
host, writes INTR_RETRIGGER so that a cause arriving while the top half
runs still signals the tree, 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.

Intersect IRQSTAT with the RISC-V routing registers the way Open RM
does, so the firmware's own causes are left alone. Clear the latch of a
host cause that is not a posted message, since nova-core has no recovery
path for one and the retrigger would raise it again.

Put the interrupt setup on the GPU rather than in the driver's probe.
The handler is then torn down before the queue it drains is freed, and
before the GSP is unloaded. Quiesce the tree and clear the latch before
registering, so no boot state reaches the handler, and keep the subtree
enabled at TOP for as long as the handler is registered. Quiescing
disables the subtree, and under pre-Hopper MSI the rearm is a
configuration-space write that never enables it again.

Assisted-by: Cursor:claude-opus-5
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/falcon/gsp.rs         |  71 +++++-
 drivers/gpu/nova-core/falcon/hal.rs         |  49 +++-
 drivers/gpu/nova-core/gpu.rs                |  47 +++-
 drivers/gpu/nova-core/gsp.rs                |   2 +-
 drivers/gpu/nova-core/gsp/cmdq.rs           |  41 ++++
 drivers/gpu/nova-core/irq.rs                |  51 ++++-
 drivers/gpu/nova-core/irq/gsp.rs            | 239 ++++++++++++++++++++
 drivers/gpu/nova-core/irq/interrupt_tree.rs |   8 +
 drivers/gpu/nova-core/nova_core.rs          |   1 -
 9 files changed, 483 insertions(+), 26 deletions(-)
 create mode 100644 drivers/gpu/nova-core/irq/gsp.rs

diff --git a/drivers/gpu/nova-core/falcon/gsp.rs b/drivers/gpu/nova-core/falcon/gsp.rs
index ae32f401aeb0..9e7d332fa77c 100644
--- a/drivers/gpu/nova-core/falcon/gsp.rs
+++ b/drivers/gpu/nova-core/falcon/gsp.rs
@@ -14,12 +14,15 @@
 };
 
 use crate::{
+    driver::Bar0,
     falcon::{
+        hal,
         Falcon,
         FalconEngine,
         PFalcon2Base,
         PFalconBase, //
     },
+    gpu::Chipset,
     regs,
 };
 
@@ -36,16 +39,72 @@ impl RegisterBase<PFalcon2Base> for Gsp {
 
 impl FalconEngine for Gsp {}
 
-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>(),
+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 causes pending for the host, clearing the SWGEN0 latch if
+    /// it was set.
+    ///
+    /// Returns the causes as they were read, before the clear. The GSP raises SWGEN0 when it has
+    /// posted messages in the GSP-to-CPU queue, so any other cause here is something else, for
+    /// example a HALT from a GSP crash. Causes the falcon routes to its own RISC-V core belong to
+    /// the firmware and are excluded.
+    pub(crate) fn take_host_intr(
+        bar: Bar0<'_>,
+        chipset: Chipset,
+    ) -> regs::NV_PFALCON_FALCON_IRQSTAT {
+        let latched = bar.read(regs::NV_PFALCON_FALCON_IRQSTAT::of::<Self>());
+        let status = regs::NV_PFALCON_FALCON_IRQSTAT::from(
+            latched.into_raw() & hal::host_intr_routing::<Self>(bar, chipset),
+        );
+
+        if status.swgen0() {
+            Self::clear_swgen0_intr(bar);
+        }
+
+        status
+    }
+
+    /// Clears the latch of every interrupt cause set in `status`.
+    ///
+    /// A cause left latched holds the falcon's host-routed set non-empty, and the falcon signals
+    /// the tree only on a transition of that set.
+    pub(crate) fn clear_intr(bar: Bar0<'_>, status: regs::NV_PFALCON_FALCON_IRQSTAT) {
+        bar.write(
+            WithBase::of::<Self>(),
+            regs::NV_PFALCON_FALCON_IRQSCLR::from(status.into_raw()),
+        );
+    }
+
+    /// Re-emits the falcon's host-routed interrupt causes into the interrupt tree.
+    ///
+    /// The falcon signals the tree on a transition of those 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> {
     /// Checks if GSP reload/resume has completed during the boot process.
     pub(crate) fn check_reload_completed(&self, timeout: Delta) -> Result<bool> {
         read_poll_timeout(
diff --git a/drivers/gpu/nova-core/falcon/hal.rs b/drivers/gpu/nova-core/falcon/hal.rs
index 7e532889a1f4..5272b3b63ae4 100644
--- a/drivers/gpu/nova-core/falcon/hal.rs
+++ b/drivers/gpu/nova-core/falcon/hal.rs
@@ -1,8 +1,15 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use kernel::prelude::*;
+use kernel::{
+    io::{
+        register::WithBase,
+        Io, //
+    },
+    prelude::*, //
+};
 
 use crate::{
+    driver::Bar0,
     falcon::{
         Falcon,
         FalconBromParams,
@@ -12,6 +19,7 @@
         Architecture,
         Chipset, //
     },
+    regs,
 };
 
 mod ga102;
@@ -72,6 +80,45 @@ 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 whether `chipset` carries the RISC-V interrupt routing registers at the Turing
+/// offsets.
+///
+/// GA102 moved `NV_PRISCV_RISCV_IRQMASK` and `NV_PRISCV_RISCV_IRQDEST`, and GA100 kept the Turing
+/// offsets, which is also why [`falcon_hal`] gives GA100 the Turing HAL.
+fn has_turing_riscv_routing(chipset: Chipset) -> bool {
+    matches!(chipset.arch(), Architecture::Turing) || chipset == Chipset::GA100
+}
+
+/// Returns the interrupt causes a RISC-V falcon on `chipset` routes to the host, in the layout of
+/// `NV_PFALCON_FALCON_IRQSTAT`.
+///
+/// A cause reaches the host only if the RISC-V core both enables it and directs it there, which
+/// `NV_PRISCV_RISCV_IRQMASK` and `NV_PRISCV_RISCV_IRQDEST` say. Every other latched cause belongs
+/// to the firmware running on the core.
+pub(crate) fn host_intr_routing<E: FalconEngine>(bar: Bar0<'_>, chipset: Chipset) -> u32 {
+    if has_turing_riscv_routing(chipset) {
+        bar.read(regs::tu102::NV_PRISCV_RISCV_IRQMASK::of::<E>())
+            .value()
+            & bar
+                .read(regs::tu102::NV_PRISCV_RISCV_IRQDEST::of::<E>())
+                .value()
+    } else {
+        bar.read(regs::ga102::NV_PRISCV_RISCV_IRQMASK::of::<E>())
+            .value()
+            & bar
+                .read(regs::ga102::NV_PRISCV_RISCV_IRQDEST::of::<E>())
+                .value()
+    }
+}
+
 /// Returns a boxed falcon HAL adequate for `chipset`.
 ///
 /// We use a heap-allocated trait object instead of a statically defined one because the
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 8a9bc4baf9ac..763f1b633d32 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -29,7 +29,10 @@
         Gsp,
         GspBootContext, //
     },
-    irq::SubtreeVectors,
+    irq::{
+        gsp::GspIrq,
+        SubtreeVectors, //
+    },
     vgpu::VgpuManager, //
 };
 
@@ -282,6 +285,12 @@ struct GspResources<'gpu> {
 #[pin_data]
 pub(crate) struct Gpu<'gpu> {
     spec: Spec,
+    /// GSP event interrupt registration.
+    ///
+    /// Declared before `gsp_resources` so it is dropped first: `free_irq` runs, waiting out any
+    /// in-flight handler, before the queue it drains goes away and before the GSP is unloaded.
+    #[pin]
+    _gsp_irq: GspIrq<'gpu>,
     /// Static GPU information as provided by the GSP.
     gsp_static_info: GetGspStaticInfoReply,
     /// GSP and its resources.
@@ -337,7 +346,7 @@ pub(crate) fn new<'a>(
         let dev = pdev.as_ref();
 
         try_pin_init!(Self {
-            vectors: crate::irq::alloc_vectors(pdev, crate::irq::SERVICED_SUBTREE.into())?,
+            vectors: crate::irq::alloc_vectors(pdev, crate::irq::gsp::GSP_SUBTREE.into())?,
 
             // SAFETY: `vectors` is initialized above, lives at a pinned stable address, and is
             // dropped after every field that uses `vectors_ref` (struct field drop order).
@@ -382,12 +391,7 @@ pub(crate) fn new<'a>(
 
                 bar,
 
-                gsp_falcon: Falcon::new(
-                    dev,
-                    spec.chipset,
-                    bar
-                )
-                .inspect(|falcon| falcon.clear_swgen0_intr())?,
+                gsp_falcon: Falcon::new(dev, spec.chipset, bar)?,
 
                 sec2_falcon: Falcon::new(dev, spec.chipset, bar)?,
 
@@ -411,6 +415,33 @@ pub(crate) fn new<'a>(
                 })?,
             }),
 
+            // Clear the interrupt state GSP boot left behind, before registering the handler
+            // below.
+            _: {
+                crate::irq::gsp::quiesce(bar, gsp_resources.spec.chipset, vectors_ref)?;
+            },
+
+            // Register the permanent GSP SWGEN0 handler, which enables the interrupt.
+            //
+            // SAFETY: the command queue lives in `gsp_resources`, which is initialized above and
+            // pinned. `_gsp_irq` is declared before `gsp_resources` and `vectors`, so it is
+            // dropped first, ensuring `free_irq` runs before either the queue or the vectors go
+            // away. The registration is stored in `Gpu` and never leaked.
+            _gsp_irq <- unsafe {
+                GspIrq::new(
+                    pdev,
+                    vectors_ref,
+                    bar,
+                    &*core::ptr::from_ref(&gsp_resources.gsp.cmdq),
+                    gsp_resources.spec.chipset,
+                )
+            },
+
+            // Drain the messages the GSP posted during boot, before relying on the interrupt.
+            _: {
+                gsp_resources.gsp.cmdq.drain()?;
+            },
+
             gsp_static_info: {
                 // Obtain and display basic GPU information.
                 let info = gsp_resources.gsp.get_static_info(bar)?;
diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs
index 13f361406a6c..47dfea78175d 100644
--- a/drivers/gpu/nova-core/gsp.rs
+++ b/drivers/gpu/nova-core/gsp.rs
@@ -152,7 +152,7 @@ pub(crate) struct Gsp {
     /// Log buffers, optionally exposed via debugfs.
     #[pin]
     logs: debugfs::Scope<LogBuffers>,
-    /// Command queue.
+    /// Command queue, borrowed by the GSP event interrupt handler.
     #[pin]
     pub(crate) cmdq: Cmdq,
     /// RM arguments.
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index a0f995faaee5..ec254d6fe2c0 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -655,6 +655,18 @@ pub(crate) fn await_msg<M: MessageFromGsp>(&self) -> Result<M>
             }
         }
     }
+
+    /// Drains every message currently pending in the GSP-to-CPU queue.
+    ///
+    /// Logs each message the GSP has already posted according to its function code, and returns
+    /// without waiting for more.
+    ///
+    /// # Errors
+    ///
+    /// Propagates a receive error, in particular the `EIO` of a queue poisoned by corrupt framing.
+    pub(crate) fn drain(&self) -> Result {
+        self.inner.lock().drain()
+    }
 }
 
 /// Inner mutex protected state of [`Cmdq`].
@@ -970,4 +982,33 @@ fn classify_event(&self, function: Result<MsgFunction, u32>, seq: u32) {
             }
         }
     }
+
+    /// Drains all messages currently pending in the GSP-to-CPU queue.
+    ///
+    /// Reads whatever the GSP has already posted and stops once the queue is empty. There is no
+    /// awaited reply during a drain, so every message goes to [`Self::classify_event`].
+    ///
+    /// # Errors
+    ///
+    /// Returns the receive error that stopped the drain, in particular the `EIO` of a queue
+    /// poisoned by corrupt framing (see [`Self::wait_for_msg`]).
+    fn drain(&mut self) -> Result {
+        while !self.gsp_mem.driver_read_area().0.is_empty() {
+            // A message is available, so this returns without waiting.
+            let msg = self.wait_for_msg(Delta::ZERO)?;
+
+            let pages =
+                u32::try_from(msg.header.length().div_ceil(GSP_PAGE_SIZE)).map_err(|_| {
+                    dev_err!(&self.dev, "GSP drain: message length overflow\n");
+                    EIO
+                })?;
+            let function = msg.header.function();
+            let seq = msg.header.sequence();
+
+            self.gsp_mem.advance_cpu_read_ptr(pages);
+            self.classify_event(function, seq);
+        }
+
+        Ok(())
+    }
 }
diff --git a/drivers/gpu/nova-core/irq.rs b/drivers/gpu/nova-core/irq.rs
index f44897692b74..50d8abb735c1 100644
--- a/drivers/gpu/nova-core/irq.rs
+++ b/drivers/gpu/nova-core/irq.rs
@@ -10,6 +10,7 @@
 
 #[cfg(CONFIG_NOVA_CORE_IRQ_SELFTEST)]
 pub(crate) mod doorbell_test;
+pub(crate) mod gsp;
 mod hal;
 mod interrupt_tree;
 mod regs;
@@ -24,20 +25,18 @@
     prelude::*, //
 };
 
-use crate::num;
+use crate::{
+    driver::Bar0,
+    gpu::Chipset,
+    num, //
+};
 
 use interrupt_tree::{
-    GinVector,
     Subtree,
-    SubtreeSet, //
+    SubtreeSet,
+    Tree, //
 };
 
-/// The subtree nova-core allocates PCI vectors for.
-///
-/// Every source nova-core services latches in this one subtree, so a single allocation covers all
-/// of them.
-pub(crate) const SERVICED_SUBTREE: Subtree = GinVector::new::<129>().subtree();
-
 /// The message-signaled interrupt type a vector allocation obtained.
 ///
 /// nova-core allocates MSI-X or MSI and nothing else, so the level-triggered INTx that
@@ -70,6 +69,40 @@ pub(crate) fn msi_type(&self) -> MsiType {
         self.msi_type
     }
 
+    /// Returns the interrupt tree these vectors deliver, as `chipset` implements it.
+    ///
+    /// # Errors
+    ///
+    /// `EINVAL` if this architecture does not implement a subtree these vectors service.
+    fn tree<'b>(&self, bar: Bar0<'b>, chipset: Chipset) -> Result<Tree<'b>> {
+        Tree::new(bar, chipset, self.msi_type, self.serviced)
+    }
+
+    /// Resets the interrupt tree these vectors deliver.
+    ///
+    /// Disables every vector in every implemented leaf, clears every pending bit, and rearms PCI
+    /// interrupt delivery. On return no vector is enabled, so the tree delivers nothing.
+    ///
+    /// The rearm covers pre-Hopper MSI, where an interrupt delivered before probe leaves delivery
+    /// un-armed with no handler to have rearmed it.
+    ///
+    /// Call this only during probe. It must not run concurrently with an interrupt handler.
+    ///
+    /// # Errors
+    ///
+    /// `EINVAL` if this architecture does not implement a subtree these vectors service.
+    pub(crate) fn reset_tree(&self, bar: Bar0<'_>, chipset: Chipset) -> Result {
+        let tree = self.tree(bar, chipset)?;
+
+        tree.disable_all_leaves();
+        tree.drain();
+        for subtree in self.serviced.iter() {
+            tree.rearm_pci_irq(subtree);
+        }
+
+        Ok(())
+    }
+
     /// Returns an [`irq::IrqRequest`] for the vector that delivers `subtree`.
     ///
     /// MSI-X gives subtree `N` its own table entry `N`. MSI raises its one message from every
diff --git a/drivers/gpu/nova-core/irq/gsp.rs b/drivers/gpu/nova-core/irq/gsp.rs
new file mode 100644
index 000000000000..174488565f79
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/gsp.rs
@@ -0,0 +1,239 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! GSP event (SWGEN0) interrupt handling.
+//!
+//! The GSP firmware raises SWGEN0 when it has posted messages in the GSP-to-CPU queue. That
+//! signal reaches the CPU as a PCI interrupt through the GIN tree. This module provides the
+//! threaded IRQ handler for it. The top half services the GIN leaf and the falcon's latched
+//! causes, and the IRQ thread drains the message queue.
+//!
+//! See `Documentation/gpu/nova/core/interrupts.rst`.
+
+use kernel::{
+    device,
+    irq,
+    pci,
+    prelude::*, //
+};
+
+use super::{
+    interrupt_tree::{
+        GinVector,
+        LeafEnableGuard,
+        Subtree,
+        TopEnableGuard,
+        Tree, //
+    },
+    SubtreeVectors, //
+};
+use crate::{
+    driver::Bar0,
+    falcon::gsp::Gsp as GspFalcon,
+    gpu::Chipset,
+    gsp::cmdq::Cmdq, //
+};
+
+/// Fixed GSP notification vector.
+///
+/// GSP-RM pins the GSP SWGEN0 notification to this vector on every supported chip, so nova-core
+/// uses the constant directly instead of discovering it at runtime. The leaf and bit serviced by
+/// the handler are derived from it.
+const GSP_INTR_0_VECTOR: GinVector = GinVector::new::<155>();
+
+/// Subtree carrying the GSP notification vector, and the only subtree nova-core services.
+///
+/// Probe allocates PCI vectors for this subtree, and the GSP handler names it as the subtree it
+/// serves, both when it takes its vector and when it rearms.
+pub(crate) const GSP_SUBTREE: Subtree = GSP_INTR_0_VECTOR.subtree();
+
+/// Clears the interrupt state that GSP boot left behind.
+///
+/// Resets the tree `vectors` covers, then clears the falcon's SWGEN0 latch. On return no vector
+/// is enabled, so the tree delivers nothing.
+///
+/// # Errors
+///
+/// `EINVAL` if this architecture does not implement a subtree `vectors` services.
+pub(crate) fn quiesce(bar: Bar0<'_>, chipset: Chipset, vectors: &SubtreeVectors<'_>) -> Result {
+    vectors.reset_tree(bar, chipset)?;
+    // GSP boot consumes its notifications by polling the queue, which leaves SWGEN0 latched, and
+    // the GSP drives no new signal while it is set. The clear comes after the tree reset, which
+    // erases every leaf bit and would erase the one a message posted since the clear had set.
+    GspFalcon::clear_swgen0_intr(bar);
+
+    Ok(())
+}
+
+/// Threaded IRQ handler for the GSP SWGEN0 event.
+///
+/// The top half clears the GIN leaf and takes the falcon causes pending for the host. The IRQ
+/// thread drains the GSP-to-CPU message queue, which takes the command-queue lock.
+pub(crate) struct GspInterrupt<'a> {
+    /// Borrowed BAR0, for falcon register access from interrupt context.
+    bar: Bar0<'a>,
+    /// The GSP command queue, drained by the IRQ thread.
+    cmdq: &'a Cmdq,
+    /// The GIN interrupt tree for this chipset.
+    tree: Tree<'a>,
+    /// Chipset, for the falcon retrigger and the routing registers, which both differ by
+    /// architecture.
+    chipset: Chipset,
+    /// Device, for logging from interrupt context without taking the command-queue lock.
+    dev: &'a device::Device,
+}
+
+impl<'a> GspInterrupt<'a> {
+    /// Creates the handler for `chipset`, borrowing `bar` and `cmdq` from the rest of the driver.
+    fn new(
+        bar: Bar0<'a>,
+        cmdq: &'a Cmdq,
+        tree: Tree<'a>,
+        chipset: Chipset,
+        dev: &'a device::Device,
+    ) -> Self {
+        Self {
+            bar,
+            cmdq,
+            tree,
+            chipset,
+            dev,
+        }
+    }
+}
+
+impl irq::ThreadedHandler for GspInterrupt<'_> {
+    /// Top half: clears the GIN leaf, takes every falcon cause pending for the host, and rearms
+    /// PCI interrupt delivery.
+    fn handle(&self) -> irq::ThreadedIrqReturn {
+        let bar = self.bar;
+
+        // Only service our own vector: require the GSP bit in the leaf and clear just that bit, so
+        // a co-pending vector in the same leaf stays pending for whoever services it. The subtree
+        // stays enabled, so there is no whole-tree disable and enable.
+        let leaf = self.tree.read_pending(GSP_INTR_0_VECTOR.leaf_index());
+        if !leaf.vectors().contains(GSP_INTR_0_VECTOR.leaf_mask()) {
+            // Nothing to service, but nova-core is the only consumer of this PCI interrupt, so
+            // skipping the rearm here would silence every later interrupt as well.
+            self.tree.rearm_pci_irq(GSP_SUBTREE);
+            return irq::ThreadedIrqReturn::None;
+        }
+        leaf.clear_vectors(GSP_INTR_0_VECTOR.leaf_mask());
+
+        let status = GspFalcon::take_host_intr(bar, self.chipset);
+
+        // A cause left latched holds the falcon's host-routed set non-empty, and the falcon
+        // signals the tree only on a transition of that set, so no later SWGEN0 would signal.
+        let unserviceable = status.with_swgen0(false);
+        if unserviceable.into_raw() != 0 {
+            // nova-core has no recovery path for a cause other than a posted message, for example
+            // a HALT from a GSP crash, so report it rather than discarding it.
+            dev_err!(
+                &self.dev,
+                "unserviceable GSP falcon interrupt, IRQSTAT {:#x}\n",
+                status.into_raw()
+            );
+            GspFalcon::clear_intr(bar, unserviceable);
+        }
+
+        // The leaf clear above consumed the tree's record of this interrupt, and the falcon signals
+        // the tree only on a transition of its host-routed causes, so a cause that arrived while
+        // this handler ran would never reach the CPU. Re-emit to supply that transition.
+        GspFalcon::retrigger_intr(bar, self.chipset);
+
+        // Delivery resumes only after this, so it must happen on every path that services the
+        // vector, including the fault path above.
+        self.tree.rearm_pci_irq(GSP_SUBTREE);
+
+        // SWGEN0 is the message-queue notification, so wake the IRQ thread to drain it.
+        if status.swgen0() {
+            irq::ThreadedIrqReturn::WakeThread
+        } else {
+            irq::ThreadedIrqReturn::Handled
+        }
+    }
+
+    /// IRQ thread: drains the GSP-to-CPU message queue.
+    fn handle_threaded(&self) -> irq::IrqReturn {
+        if let Err(e) = self.cmdq.drain() {
+            // A queue that fails to drain cannot advance past the message that failed, so every
+            // later notification would repeat this failure. Disable the source instead.
+            self.tree.disable_leaf(
+                GSP_INTR_0_VECTOR.leaf_index(),
+                GSP_INTR_0_VECTOR.leaf_mask(),
+            );
+            dev_err!(
+                &self.dev,
+                "GSP event drain failed ({:?}), the message queue is no longer serviced\n",
+                e
+            );
+        }
+        irq::IrqReturn::Handled
+    }
+}
+
+/// The registered GSP event interrupt.
+///
+/// The fields tear down in declaration order, which is the order this needs: disabling the leaf
+/// stops new deliveries, `free_irq` then waits for a handler still in flight, and only then is
+/// the subtree disabled at `TOP`, so a late handler cannot rearm it.
+#[pin_data]
+pub(crate) struct GspIrq<'a> {
+    _leaf_guard: LeafEnableGuard<'a>,
+    #[pin]
+    reg: irq::ThreadedRegistration<'a, GspInterrupt<'a>>,
+    _top_guard: TopEnableGuard<'a>,
+}
+
+impl<'a> GspIrq<'a> {
+    /// Registers the GSP SWGEN0 threaded handler for the GSP subtree in `vectors`, then enables
+    /// the subtree and the GSP notification vector.
+    ///
+    /// # Errors
+    ///
+    /// `EINVAL` if this architecture does not implement the subtree carrying the GSP
+    /// notification, or if `vectors` does not service it.
+    ///
+    /// # 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>,
+        vectors: &'a SubtreeVectors<'a>,
+        bar: Bar0<'a>,
+        cmdq: &'a Cmdq,
+        chipset: Chipset,
+    ) -> impl PinInit<Self, Error> + 'a {
+        let dev = pdev.as_ref();
+
+        // The fields below are initialized in the opposite order to the one they are declared in,
+        // so that the handler is registered before anything it serves is enabled.
+        try_pin_init!(Self {
+            // SAFETY: the caller guarantees the returned `GspIrq` is not leaked, so this
+            // registration's `Drop` (`free_irq`) always runs.
+            reg <- unsafe {
+                irq::ThreadedRegistration::new(
+                    vectors.request_for(GSP_SUBTREE)?,
+                    irq::Flags::TRIGGER_NONE,
+                    c"nova-core",
+                    Ok(GspInterrupt::new(
+                        bar,
+                        cmdq,
+                        vectors.tree(bar, chipset)?,
+                        chipset,
+                        dev,
+                    )),
+                )
+            },
+            // Under pre-Hopper MSI the rearm is a configuration-space write, so nothing else
+            // restores the `TOP` enables that the tree reset cleared.
+            _top_guard: reg.handler().tree.enable_top_guarded(),
+            // A message posted during `quiesce` latches this leaf bit while the vector is still
+            // disabled, so enabling it raises that interrupt rather than losing the message.
+            _leaf_guard: reg.handler().tree.enable_leaf_guarded(
+                GSP_INTR_0_VECTOR.leaf_index(),
+                GSP_INTR_0_VECTOR.leaf_mask(),
+            ),
+        })
+    }
+}
diff --git a/drivers/gpu/nova-core/irq/interrupt_tree.rs b/drivers/gpu/nova-core/irq/interrupt_tree.rs
index f27f0137dffe..62c0bbda61b2 100644
--- a/drivers/gpu/nova-core/irq/interrupt_tree.rs
+++ b/drivers/gpu/nova-core/irq/interrupt_tree.rs
@@ -178,6 +178,14 @@ pub(super) const fn intersection(self, other: Self) -> Self {
     pub(super) const fn span(self) -> u32 {
         u32::BITS - self.0.leading_zeros()
     }
+
+    /// Returns the subtrees of this set, lowest index first.
+    pub(super) fn iter(self) -> impl Iterator<Item = Subtree> {
+        // INVARIANT: a shift of `1` leaves exactly one bit set.
+        (0..u32::BITS)
+            .map(|index| Subtree(1 << index))
+            .filter(move |subtree| self.contains(*subtree))
+    }
 }
 
 impl From<Subtree> for SubtreeSet {
diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
index 65ce547bd44e..68b5abfe494d 100644
--- a/drivers/gpu/nova-core/nova_core.rs
+++ b/drivers/gpu/nova-core/nova_core.rs
@@ -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]
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 13/14] gpu: nova-core: add KUnit tests for the interrupt tree and HALs
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (11 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 12/14] gpu: nova-core: drive GSP events with the SWGEN0 interrupt John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  2026-09-03  3:15 ` [PATCH v3 14/14] gpu: nova-core: document the GIN interrupt controller and GSP events John Hubbard
  13 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard, Will Pierce

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 vector arithmetic: the leaf index
  bounds, the leaves and subtrees a leaf count implies, the leaf and bit
  a vector maps to, the check that rejects a vector outside the tree,
  the subtree-set operations and iteration, 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 family and MSI type.

* nova_core_falcon_hal covers two per-chipset falcon gates: whether the
  interrupt retrigger register exists, and where the RISC-V interrupt
  routing registers sit. GA100 falls on a different side of each, and
  shares the Turing HAL, so neither gate can be keyed on the HAL.

Assisted-by: Cursor:claude-opus-5
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 drivers/gpu/nova-core/falcon/hal.rs         |  43 +++++++
 drivers/gpu/nova-core/irq/hal.rs            |  64 ++++++++++
 drivers/gpu/nova-core/irq/interrupt_tree.rs | 131 ++++++++++++++++++++
 3 files changed, 238 insertions(+)

diff --git a/drivers/gpu/nova-core/falcon/hal.rs b/drivers/gpu/nova-core/falcon/hal.rs
index 5272b3b63ae4..aa89b553ef53 100644
--- a/drivers/gpu/nova-core/falcon/hal.rs
+++ b/drivers/gpu/nova-core/falcon/hal.rs
@@ -146,3 +146,46 @@ 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));
+        }
+    }
+
+    /// GA102 moved the RISC-V interrupt routing registers. GA100 kept the Turing offsets even
+    /// though it is Ampere, so the two gates in this module do not agree on GA100.
+    #[test]
+    fn riscv_routing_offsets_split_at_ga102() {
+        for chipset in [Chipset::TU102, Chipset::TU116, Chipset::GA100] {
+            assert!(has_turing_riscv_routing(chipset));
+        }
+
+        for chipset in [
+            Chipset::GA102,
+            Chipset::AD102,
+            Chipset::GH100,
+            Chipset::GB100,
+            Chipset::GB202,
+        ] {
+            assert!(!has_turing_riscv_routing(chipset));
+        }
+    }
+}
diff --git a/drivers/gpu/nova-core/irq/hal.rs b/drivers/gpu/nova-core/irq/hal.rs
index 07604458dbbb..e844ade089e5 100644
--- a/drivers/gpu/nova-core/irq/hal.rs
+++ b/drivers/gpu/nova-core/irq/hal.rs
@@ -104,3 +104,67 @@ pub(super) fn cpu_interrupt_hal(chipset: Chipset) -> &'static dyn CpuInterruptHa
         }
     }
 }
+
+#[kunit_tests(nova_core_gin_hal)]
+mod tests {
+    use super::*;
+
+    use crate::gpu::Chipset;
+
+    /// Pre-Hopper parts have an 8-leaf tree.
+    #[test]
+    fn pre_hopper_tree_size() {
+        for chipset in [Chipset::TU102, Chipset::GA102, Chipset::AD102] {
+            assert_eq!(cpu_interrupt_hal(chipset).leaf_count(), LeafCount::Eight);
+        }
+    }
+
+    /// Hopper and later implement a 16-leaf tree.
+    #[test]
+    fn hopper_plus_tree_size() {
+        for chipset in [Chipset::GH100, Chipset::GB100, Chipset::GB202] {
+            assert_eq!(cpu_interrupt_hal(chipset).leaf_count(), LeafCount::Sixteen);
+        }
+    }
+
+    /// Only pre-Hopper MSI rearms through the configuration-space mirror. MSI on Hopper and later
+    /// cycles the `TOP` enables of every serviced subtree.
+    #[test]
+    fn msi_rearm_method_per_arch() {
+        for chipset in [Chipset::TU102, Chipset::GA102, Chipset::AD102] {
+            let hal = cpu_interrupt_hal(chipset);
+            assert_eq!(
+                hal.pci_irq_rearm_method(MsiType::Msi),
+                PciIrqRearmMethod::ConfigMirrorEoi
+            );
+        }
+
+        for chipset in [Chipset::GH100, Chipset::GB100, Chipset::GB202] {
+            let hal = cpu_interrupt_hal(chipset);
+            assert_eq!(
+                hal.pci_irq_rearm_method(MsiType::Msi),
+                PciIrqRearmMethod::TopEnableCycleServiced
+            );
+        }
+    }
+
+    /// MSI-X gives each subtree its own table entry, so on every architecture its rearm cycles
+    /// only the subtree the handler serves.
+    #[test]
+    fn msix_rearms_one_subtree_on_every_arch() {
+        for chipset in [
+            Chipset::TU102,
+            Chipset::GA102,
+            Chipset::AD102,
+            Chipset::GH100,
+            Chipset::GB100,
+            Chipset::GB202,
+        ] {
+            let hal = cpu_interrupt_hal(chipset);
+            assert_eq!(
+                hal.pci_irq_rearm_method(MsiType::MsiX),
+                PciIrqRearmMethod::TopEnableCycleSubtree
+            );
+        }
+    }
+}
diff --git a/drivers/gpu/nova-core/irq/interrupt_tree.rs b/drivers/gpu/nova-core/irq/interrupt_tree.rs
index 62c0bbda61b2..a6da9900f9da 100644
--- a/drivers/gpu/nova-core/irq/interrupt_tree.rs
+++ b/drivers/gpu/nova-core/irq/interrupt_tree.rs
@@ -531,3 +531,134 @@ fn drop(&mut self) {
         clear_top_enables(self.bar, self.serviced);
     }
 }
+
+#[kunit_tests(nova_core_gin_tree)]
+mod tests {
+    use super::*;
+
+    /// A leaf index is a `Bounded<usize, 4>`, so it accepts 0..=15 and rejects 16.
+    #[test]
+    fn leaf_index_bounds() {
+        assert!(LeafIndex::try_new(0).is_some());
+        assert!(LeafIndex::try_new(15).is_some());
+        assert!(LeafIndex::try_new(16).is_none());
+    }
+
+    /// A leaf count yields one subtree per pair of leaves, and 32 vectors per leaf.
+    #[test]
+    fn leaf_count_derives_subtrees_and_vectors() {
+        assert_eq!(LeafCount::Eight.subtree_count(), 4);
+        assert_eq!(
+            Bounded::<u32, 32>::from(LeafCount::Eight.subtree_set()).get(),
+            0x0f
+        );
+        assert_eq!(LeafCount::Eight.vector_count(), 256);
+
+        assert_eq!(LeafCount::Sixteen.subtree_count(), 8);
+        assert_eq!(
+            Bounded::<u32, 32>::from(LeafCount::Sixteen.subtree_set()).get(),
+            0xff
+        );
+        assert_eq!(LeafCount::Sixteen.vector_count(), 512);
+    }
+
+    /// A tree enumerates every leaf it implements, in order, and no more.
+    #[test]
+    fn implemented_leaves_covers_the_tree() {
+        for (count, expected) in [(LeafCount::Eight, 8usize), (LeafCount::Sixteen, 16)] {
+            let mut seen = 0;
+
+            for (index, leaf) in implemented_leaves(count).enumerate() {
+                assert_eq!(leaf.get(), index);
+                seen += 1;
+            }
+
+            assert_eq!(seen, expected);
+        }
+    }
+
+    /// A vector maps to its leaf, its bit within that leaf, and its subtree. The fixed doorbell
+    /// (129) and GSP (155) vectors share a subtree, so one allocation and one enabled subtree
+    /// serve both.
+    #[test]
+    fn vector_maps_to_leaf_bit_and_subtree() {
+        let doorbell = GinVector::new::<129>();
+        let gsp = GinVector::new::<155>();
+
+        assert_eq!(doorbell.leaf_index().get(), 4);
+        assert_eq!(doorbell.leaf_mask().into_raw(), 1 << 1);
+        assert_eq!(doorbell.subtree().index(), 2);
+
+        assert_eq!(gsp.leaf_index().get(), 4);
+        assert_eq!(gsp.leaf_mask().into_raw(), 1 << 27);
+        assert_eq!(gsp.subtree().index(), 2);
+
+        assert_eq!(doorbell.subtree(), gsp.subtree());
+    }
+
+    /// Both fixed vectors lie within the 8-leaf tree, so every supported part carries them.
+    #[test]
+    fn fixed_vectors_fit_the_narrowest_tree() {
+        assert!(GinVector::new::<129>().validate(LeafCount::Eight).is_ok());
+        assert!(GinVector::new::<155>().validate(LeafCount::Eight).is_ok());
+
+        // The first vector beyond an 8-leaf tree.
+        assert!(GinVector::new::<256>().validate(LeafCount::Eight).is_err());
+        assert!(GinVector::new::<256>().validate(LeafCount::Sixteen).is_ok());
+    }
+
+    /// A subtree set reports membership, intersection, and how far it extends from subtree 0.
+    #[test]
+    fn subtree_set_operations() {
+        let gsp = GinVector::new::<155>().subtree();
+
+        assert!(LeafCount::Eight.subtree_set().contains(gsp));
+        assert!(!LeafCount::Eight.subtree_set().is_empty());
+
+        // Subtree 2 is the highest the GSP needs, so an MSI-X request covers entries 0 through 2.
+        assert_eq!(SubtreeSet::from(gsp).span(), 3);
+
+        // Hopper implements every subtree an 8-leaf tree does.
+        assert_eq!(
+            LeafCount::Sixteen
+                .subtree_set()
+                .intersection(LeafCount::Eight.subtree_set()),
+            LeafCount::Eight.subtree_set()
+        );
+    }
+
+    /// Iterating a subtree set yields each of its subtrees once, lowest index first, and yields
+    /// nothing for an empty set.
+    #[test]
+    fn subtree_set_iterates_its_members() {
+        assert!(LeafCount::Eight
+            .subtree_set()
+            .iter()
+            .map(Subtree::index)
+            .eq([0u32, 1, 2, 3]));
+
+        let gsp = SubtreeSet::from(GinVector::new::<155>().subtree());
+        assert!(gsp.iter().map(Subtree::index).eq([2u32]));
+
+        let empty = SubtreeSet::from(Bounded::<u32, 32>::new::<0>());
+        assert_eq!(empty.iter().count(), 0);
+    }
+
+    /// Every supported chipset implements the subtree that carries the GSP notification.
+    #[test]
+    fn gsp_subtree_is_implemented_everywhere() {
+        for chipset in [
+            Chipset::TU102,
+            Chipset::GA102,
+            Chipset::AD102,
+            Chipset::GH100,
+            Chipset::GB100,
+            Chipset::GB202,
+        ] {
+            assert!(cpu_interrupt_hal(chipset)
+                .leaf_count()
+                .subtree_set()
+                .contains(crate::irq::gsp::GSP_SUBTREE));
+        }
+    }
+}
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* [PATCH v3 14/14] gpu: nova-core: document the GIN interrupt controller and GSP events
  2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
                   ` (12 preceding siblings ...)
  2026-09-03  3:15 ` [PATCH v3 13/14] gpu: nova-core: add KUnit tests for the interrupt tree and HALs John Hubbard
@ 2026-09-03  3:15 ` John Hubbard
  13 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:15 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot
  Cc: Timur Tabi, Alistair Popple, Eliot Courtney, Zhi Wang,
	David Airlie, Simona Vetter, Bjorn Helgaas, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
	nova-gpu, LKML, John Hubbard, Will Pierce

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 sets no bit 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 an
interrupt reaches the CPU under MSI and MSI-X, and the rules that
delivery imposes on a handler. It also covers the GSP event: which of
the falcon's interrupt causes reach the host and which belong to the
firmware, the falcon retrigger, the handoff from boot-time polling to
interrupts, and how the GSP's messages are classified. A glossary
defines the tree's three levels and names every other term after the
register or the specification that owns it.

Assisted-by: Cursor:claude-opus-5
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
 Documentation/gpu/nova/core/interrupts.rst | 716 +++++++++++++++++++++
 Documentation/gpu/nova/index.rst           |   1 +
 2 files changed, 717 insertions(+)
 create mode 100644 Documentation/gpu/nova/core/interrupts.rst

diff --git a/Documentation/gpu/nova/core/interrupts.rst b/Documentation/gpu/nova/core/interrupts.rst
new file mode 100644
index 000000000000..60d24adbcf06
--- /dev/null
+++ b/Documentation/gpu/nova/core/interrupts.rst
@@ -0,0 +1,716 @@
+.. 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 are in the per-function
+``NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*`` aperture on every supported part, and
+the controller has a different name in the pre-Hopper headers (see "Register
+naming").
+
+Terminology
+===========
+
+The GPU hardware documentation, Open RM, and the Linux PCI API all use the word
+"vector", each for a different number. This document gives each one its own
+name, and a bare "vector" always means a GIN vector.
+
+GIN vector
+    The GPU-internal interrupt source number, 0 through 511 on Hopper. It
+    addresses one bit of one leaf (see "Mapping a vector to the tree"). 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. One entry covers one subtree, so a
+    Hopper part uses entries 0 through 7.
+
+Linux IRQ number
+    What ``request_irq()`` takes, obtained from ``pci_irq_vector()``. Linux's
+    ``struct msix_entry`` calls this number ``.vector`` as well.
+
+The three levels of the controller itself, innermost first:
+
+leaf
+    One ``LEAF`` register. Each of its 32 bits is the pending bit of one GIN
+    vector. A pre-Hopper tree has 8 leaves, and a Hopper-plus tree has 16.
+
+subtree
+    Two consecutive leaves, summarized by one bit of ``TOP``. A driver enables
+    and disables whole subtrees, and under MSI-X every interrupt from one
+    subtree arrives on one MSI-X entry.
+
+tree
+    One ``TOP`` register and the leaves beneath it. Every PCIe function has its
+    own tree, and nova-core drives the CPU tree of one function.
+
+The remaining terms, each named for the register or the specification that owns
+it:
+
+enable / disable a GIN vector
+    Writes to ``LEAF_EN_SET`` and ``LEAF_EN_CLEAR``.
+
+enable / disable a subtree
+    Writes to ``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 (see
+    "Rearming PCI interrupt delivery").
+
+mask
+    Reserved for the two places where 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
+    Two names for one state, a ``LEAF`` bit that is set. The bit is set when its
+    source asserts, whether or not the GIN vector is enabled. A pending bit for
+    a disabled vector does not set the subtree's bit in ``TOP``.
+
+clear a leaf vector
+    Write a 1 to the vector's bit in ``LEAF``. Open RM calls 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 in a subtree
+that had none 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 interrupt vectors the tree needs depends on the interrupt type
+Linux grants.
+
+MSI has a single message, and every subtree raises that one message. One
+allocated PCI 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 leaves an
+entry masked until a driver requests its Linux IRQ number, and a masked entry
+sends no message: the GPU records the interrupt in the MSI-X pending-bit array,
+where it waits to be unmasked. An entry the driver never requests is never
+unmasked, so a driver that enables a subtree without requesting that subtree's
+entry loses every interrupt from it, and loses them silently: the GIN leaf and
+TOP registers show 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 its single message. 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 PCI vector, whose
+                                  handler's rearm covers the whole serviced set
+
+An allocated entry whose subtree the driver does not service costs nothing,
+because the entry stays masked and a disabled subtree raises no interrupt.
+
+nova-core services exactly one subtree. Both vectors it uses, the GSP event
+(155) and the self-test doorbell (129), are in leaf 4, which belongs to subtree
+2. That is also the subtree GSP-RM 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 register aperture and
+cannot reach another destination's tree. GSP firmware selects the tree each
+unit's interrupt is sent to.
+
+nova-core services the CPU tree of one function. A VF tree belongs to that
+virtual function, and a microcontroller tree belongs to the firmware running on
+that microcontroller.
+
+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 a 16-leaf part
+uses bits 0 through 7. The remaining bits always read 0::
+
+    TOP  (one 32-bit register, shown here for an 8-leaf part)
+
+      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
+
+    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)
+
+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
+
+Registers
+---------
+
+All the registers are 32 bits, defined under the
+``NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*`` names in the ``irq`` module's
+``regs.rs``. 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). A handler clears a bit before it services that vector,
+  because clearing afterwards would discard an assertion that arrived while the
+  handler ran.
+* ``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]``.
+* ``TOP_EN_SET`` and ``TOP_EN_CLEAR`` enable and disable whole subtrees.
+* ``LEAF_TRIGGER`` makes a vector pending in software. The self-test uses it.
+
+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.
+
+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 reading the
+leaf is the only way to see that bit.
+
+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
+receive the interrupt: 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, with two exceptions. Firmware pins the GSP event and the
+CPU doorbell to fixed numbers on every supported chip, so nova-core names both
+by number (see "The GSP event vector" and "Self-test").
+
+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.
+* 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 is applied after the TOP summary, so disabling a subtree stops
+    delivery without changing what TOP reports.
+
+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 reads the
+LEAF registers of every subtree it implements.
+
+Because delivery is edge-triggered, writing ``TOP_EN_SET`` while an enabled leaf
+bit is still set produces a new edge. A ``TOP_EN`` cycle rearms delivery on that
+edge, and a pending bit left uncleared delivers an interrupt as soon as its
+subtree is enabled again.
+
+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 when its set of host-routed interrupt causes goes from
+empty to non-empty. Clearing the tree leaf while a host-routed cause is still
+latched keeps that set non-empty, so no further cause sets the vector and the
+interrupt is lost. Clearing the tree leaf first or the falcon latch first makes
+no difference to that loss, so a handler on a falcon vector writes
+``INTR_RETRIGGER`` on every path that services the vector.
+
+``IRQSTAT`` latches every interrupt cause in the falcon, including the causes
+routed to the falcon's own RISC-V core and owned by the firmware running on it.
+A host handler owns only the causes that both ``PRISCV_RISCV_IRQMASK`` and
+``PRISCV_RISCV_IRQDEST`` select, so it intersects ``IRQSTAT`` with both of them
+before it reads a cause or clears one. Open RM computes the same intersection in
+``kflcnRiscvReadIntrStatus``. GA100 keeps the Turing offsets for both registers
+and GA102 moved them, so the offsets change at GA102 rather than at the Ampere
+boundary.
+
+The ``INTR_RETRIGGER`` write must not be able to raise a cause that nothing
+clears. Before the re-emit, the handler uses ``IRQSCLR`` to clear the latch of
+every host cause it read. The handler masks no cause:
+``PRISCV_RISCV_IRQMASK`` is read-only to the host, and ``FALCON_IRQMASK`` does
+not gate host routing on a RISC-V falcon.
+
+``INTR_RETRIGGER`` is absent on Turing falcons and present from GA100 onward, so
+the write is conditional on the architecture. A Turing handler cannot re-create
+a transition it has lost, so it must leave no host cause latched: it reads the
+host-routed status once and takes every cause that status reports, rather than
+stopping at the first one it recognizes. A cause left behind keeps the
+host-routed 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 after the handler has read
+the status is not in the value the handler clears, 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.
+
+nova-core allocates MSI-X or MSI and nothing else. The level-triggered INTx that
+``kernel::pci::IrqType`` also names has no representation in the driver, so the
+table above has no row for it.
+
+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_EN writes a full tree walk performs. The walk
+clears TOP_EN on entry, so that it can read and clear the leaves with no new
+interrupts arriving, and it leaves TOP_EN cleared for its caller to enable once
+the caller is ready for deliveries. That clear is not a rearm, and 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, and leaves the subtrees disabled.
+
+The drain reads every implemented leaf rather than descending from TOP, because
+sources latch vectors during boot while those vectors are still disabled, and
+TOP does not show those bits.
+
+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 leaf i:
+            pending = read LEAF[i]           pending vectors in this leaf
+            write LEAF[i] = pending          clear (write-1-to-clear)
+        (returns with TOP_EN still clear)
+
+    Notification, subtree stays enabled (the GSP event handler, and the
+    self-test, which deliberately mirrors it):
+        pending = read LEAF[gsp_leaf]        is the handler's bit set?
+        write LEAF[gsp_leaf] = gsp_bit       clear that one bit
+        rearm PCI interrupt delivery         see "Rearming PCI interrupt
+                                             delivery"
+
+The walk writes back every bit it read, so it clears every pending leaf bit,
+including the bits nova-core does not handle. An uncleared bit holds its subtree
+in the pending state, and enabling that subtree again would deliver an interrupt
+straight away for a vector that no handler services.
+
+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 rearm PCI interrupt delivery. A handler rearms for the interrupt it
+has just serviced. The startup path rearms after the walk, because an interrupt
+delivered before probe would have left delivery un-armed, with no handler
+present to rearm it.
+
+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, and its handler takes the notification path
+above.
+
+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``
+===================  ======  ========  ====================
+
+Sources do not populate every leaf of a 16-leaf tree. The startup drain reads
+every implemented leaf anyway, because a vector can be pending in any of them.
+
+The implemented-subtree set is wider than the set nova-core enables, which holds
+only the subtrees it services. A subtree the architecture does not implement has
+no TOP bit to deliver its vectors, so building a tree that services one fails
+with ``EINVAL``.
+
+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 causes routed to the host, clearing SWGEN0 if it
+            was set
+        for every other host cause the status reports: report it, then clear
+            its latch
+        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 and reports 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 both
+the latch set and 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
+    rearm PCI interrupt delivery        required under pre-Hopper MSI, where
+                                        nothing else does it
+    clear the SWGEN0 latch              so the next assertion makes an edge
+    register the threaded IRQ handler   nothing can reach it yet
+    enable the GSP subtree at TOP       the walk left it disabled
+    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 vector that boot left enabled would then deliver to 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. Clearing it first would
+let a message posted before the walk set the latch again, along with the GSP
+leaf bit. The walk then erases the leaf bit while the latch stays set, and a set
+latch holds the falcon's host-routed set non-empty, so 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 subtree is enabled at ``TOP`` once the handler is registered, and disabled
+again only after ``free_irq()`` has returned. Disabling it earlier would let a
+handler still in flight rearm it, leaving the subtree enabled with no handler
+behind it. The explicit enable is required because the walk leaves ``TOP``
+disabled, and under pre-Hopper MSI the rearm is a configuration-space write that
+does not enable it again.
+
+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 into one of two classes:
+
+* The function code matches the awaited reply. The message is decoded and
+  returned to the caller that sent the command.
+* 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 the classifier does not log them,
+  because the RPC receive trace already records their arrival.
+
+The RPC sequence number appears in the receive trace and takes no part in the
+match, because the GSP does not echo the sequence number of the command on every
+reply. On r570 the reply to ``UnloadingGuestDriver`` carries sequence 0.
+
+The read pointer advances past the message in both 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.
+
+The classifier is a fixed set of function codes rather than a handler registry,
+and it logs the events that need attention.
+
+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
+passes each event that arrives before that reply to the classifier and keeps
+waiting, under a single deadline for the whole wait rather than a fresh timeout
+after each message.
+
+With one lock, 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.
+
+Tree API
+--------
+
+Servicing a leaf has a required order: read its pending bits, then clear them.
+Reading a leaf produces the handle that clears it, so clearing a leaf before
+reading it does not compile. Enabling and disabling a vector or a subtree has no
+such order, so the tree provides those as methods of its own, with no handle
+involved.
+
+The handle orders the calls that service one leaf. It is not a lock and it does
+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 queue 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, and the sequence under "The GSP event" shows which work each half
+does. 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. One delivery would prove nothing
+about the rearm, and a handler that walked the tree would prove nothing either:
+on every configuration except pre-Hopper MSI the rearm is a ``TOP_EN`` cycle, so
+a walk that enabled ``TOP`` again would rearm delivery whether the handler asked
+for it or not.
+
+The test passes only if both deliveries arrive, each one finds the doorbell bit
+and nothing else pending in the leaf, and the doorbell bit 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 starts by disabling every vector in every implemented leaf and draining the
+tree, and it runs before GSP boot, so no other vector in the doorbell's 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.
+If the doorbell moved to a subtree nova-core does not service, that lookup
+fails, and the self-test and probe fail with it. The interrupt is not 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 ``irq`` module holds the GIN register definitions, the
+  interrupt HAL, and the tree API. The falcon interrupt registers are in the
+  top-level ``regs.rs``, and the GSP command queue is in the ``gsp`` module.
diff --git a/Documentation/gpu/nova/index.rst b/Documentation/gpu/nova/index.rst
index 2afa58e8f08d..2130d1caf4c3 100644
--- a/Documentation/gpu/nova/index.rst
+++ b/Documentation/gpu/nova/index.rst
@@ -34,3 +34,4 @@ vGPU manager VFIO driver and the nova-drm driver.
    core/fwsec
    core/falcon
    core/tlv
+   core/interrupts
-- 
2.55.0


^ permalink raw reply related	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 12/14] gpu: nova-core: drive GSP events with the SWGEN0 interrupt
  2026-09-03  3:15 ` [PATCH v3 12/14] gpu: nova-core: drive GSP events with the SWGEN0 interrupt John Hubbard
@ 2026-09-03  3:28   ` sashiko-bot
  2026-09-03  3:55     ` John Hubbard
  0 siblings, 1 reply; 27+ messages in thread
From: sashiko-bot @ 2026-09-03  3:28 UTC (permalink / raw)
  To: John Hubbard, Danilo Krummrich, Alexandre Courbot
  Cc: Alistair Popple, Bjorn Helgaas, Alex Gaynor, Eliot Courtney,
	Benno Lossin, Zhi Wang, David Airlie, Alexandre Courbot,
	Timur Tabi, Will Pierce, Björn Roy Baron, Boqun Feng,
	Trevor Gross, Gary Guo, nova-gpu, Andreas Hindborg, Simona Vetter,
	Alice Ryhl, LKML, Danilo Krummrich, Miguel Ojeda

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] Unserviceable GSP falcon interrupts cause an infinite interrupt storm and CPU soft lockup.
--

commit e6648318ceeb9312972b220805b21b9370c7409e
Author: John Hubbard <jhubbard@nvidia.com>

gpu: nova-core: drive GSP events with the SWGEN0 interrupt
    
This commit implements threaded IRQ handling for the GSP SWGEN0 event in
nova-core. It replaces polling with an interrupt handler that drains the
GSP-to-CPU message queue and clears the GIN leaf in hardirq context.

> diff --git a/drivers/gpu/nova-core/irq/gsp.rs b/drivers/gpu/nova-core/irq/gsp.rs
> new file mode 100644
> index 0000000000000..174488565f790
> --- /dev/null
> +++ b/drivers/gpu/nova-core/irq/gsp.rs

[ ... ]

> +impl irq::ThreadedHandler for GspInterrupt<'_> {
> +    /// Top half: clears the GIN leaf, takes every falcon cause pending for the host, and rearms
> +    /// PCI interrupt delivery.
> +    fn handle(&self) -> irq::ThreadedIrqReturn {
> +        let bar = self.bar;
> +
> +        // Only service our own vector: require the GSP bit in the leaf and clear just that bit, so
> +        // a co-pending vector in the same leaf stays pending for whoever services it. The subtree
> +        // stays enabled, so there is no whole-tree disable and enable.
> +        let leaf = self.tree.read_pending(GSP_INTR_0_VECTOR.leaf_index());
> +        if !leaf.vectors().contains(GSP_INTR_0_VECTOR.leaf_mask()) {
> +            // Nothing to service, but nova-core is the only consumer of this PCI interrupt, so
> +            // skipping the rearm here would silence every later interrupt as well.
> +            self.tree.rearm_pci_irq(GSP_SUBTREE);
> +            return irq::ThreadedIrqReturn::None;
> +        }
> +        leaf.clear_vectors(GSP_INTR_0_VECTOR.leaf_mask());
> +
> +        let status = GspFalcon::take_host_intr(bar, self.chipset);
> +
> +        // A cause left latched holds the falcon's host-routed set non-empty, and the falcon
> +        // signals the tree only on a transition of that set, so no later SWGEN0 would signal.
> +        let unserviceable = status.with_swgen0(false);
> +        if unserviceable.into_raw() != 0 {
> +            // nova-core has no recovery path for a cause other than a posted message, for example
> +            // a HALT from a GSP crash, so report it rather than discarding it.
> +            dev_err!(
> +                &self.dev,
> +                "unserviceable GSP falcon interrupt, IRQSTAT {:#x}\n",
> +                status.into_raw()
> +            );
> +            GspFalcon::clear_intr(bar, unserviceable);
> +        }
> +
> +        // The leaf clear above consumed the tree's record of this interrupt, and the falcon signals
> +        // the tree only on a transition of its host-routed causes, so a cause that arrived while
> +        // this handler ran would never reach the CPU. Re-emit to supply that transition.
> +        GspFalcon::retrigger_intr(bar, self.chipset);
> +
> +        // Delivery resumes only after this, so it must happen on every path that services the
> +        // vector, including the fault path above.
> +        self.tree.rearm_pci_irq(GSP_SUBTREE);

[Severity: High]
Does this lead to an interrupt storm if the GSP remains in a fault state like a
HALT or WDT timeout?

If there is no recovery path to reset the GSP, wouldn't the unserviceable
interrupt immediately re-latch after GspFalcon::clear_intr() is called?

The subsequent calls to GspFalcon::retrigger_intr() and self.tree.rearm_pci_irq()
would then force a new edge to the GIN tree and re-enable PCI delivery,
potentially trapping the CPU in an endless loop servicing the same unserviceable
interrupt.

Could the GIN leaf source be disabled here instead when encountering an
unrecoverable fault?

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20260903031514.1515905-1-jhubbard@nvidia.com?part=12

^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 07/14] gpu: nova-core: add an interrupt delivery self-test
  2026-09-03  3:15 ` [PATCH v3 07/14] gpu: nova-core: add an interrupt delivery self-test John Hubbard
@ 2026-09-03  3:29   ` sashiko-bot
  2026-09-03  3:57     ` John Hubbard
  0 siblings, 1 reply; 27+ messages in thread
From: sashiko-bot @ 2026-09-03  3:29 UTC (permalink / raw)
  To: Danilo Krummrich, Alexandre Courbot, John Hubbard
  Cc: Will Pierce, Alex Gaynor, Bjorn Helgaas, Boqun Feng, Zhi Wang,
	Alexandre Courbot, Simona Vetter, Gary Guo, Joel Fernandes,
	Timur Tabi, Andreas Hindborg, Danilo Krummrich, Alice Ryhl,
	Trevor Gross, David Airlie, LKML, Miguel Ojeda, Alistair Popple,
	nova-gpu, Björn Roy Baron, Benno Lossin, Eliot Courtney

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] The `vectors_ref` field introduces a self-referential struct using a reference derived from a short-lived macro-local `&mut` binding. `try_pin_init!` provides access to previously initialized fields via local variable bindings, which expire at the end of the initialization closure. Taking a reference from this local variable and artificially extending its lifetime to `'gpu` via `unsafe { &*... }` violates strict aliasing rules (Stacked Borrows / Tree Borrows). When the closure returns, the local variable goes out of scope, its provenance tag is popped, and `vectors_ref` becomes a dangling pointer under the Rust memory model. Furthermore, the `pin-init` crate explicitly documents: "IMPORTANT: You are not allowed to create references to fields of the struct inside of the initializer."
--

commit 9bb2c0e6b8faa56d9fead3fb4f99c60340b45be0
Author: John Hubbard <jhubbard@nvidia.com>

gpu: nova-core: add an interrupt delivery self-test

Add an optional probe-time self-test that injects the CPU doorbell
through the GIN software trigger. It confirms the interrupt reaches
the driver's handler to validate the PCI interrupt path without GSP firmware.

> diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
> index e1ac8ee9ba4db..8a9bc4baf9ac0 100644
> --- a/drivers/gpu/nova-core/gpu.rs
> +++ b/drivers/gpu/nova-core/gpu.rs

[ ... ]

> @@ -330,6 +337,12 @@ pub(crate) fn new<'a>(
>          let dev = pdev.as_ref();
>  
>          try_pin_init!(Self {
> +            vectors: crate::irq::alloc_vectors(pdev, crate::irq::SERVICED_SUBTREE.into())?,
> +
> +            // SAFETY: `vectors` is initialized above, lives at a pinned stable address, and is
> +            // dropped after every field that uses `vectors_ref` (struct field drop order).
> +            vectors_ref: unsafe { &*core::ptr::from_ref(vectors.as_ref().get_ref()) },

[Severity: High]
Does this create a dangling pointer under the Rust memory model?

`try_pin_init!` provides access to previously initialized fields via local
variable bindings, which expire at the end of the initialization closure.
Taking a reference from this local variable and artificially extending its
lifetime to `'gpu` via `unsafe { &*... }` violates strict aliasing rules
(Stacked Borrows / Tree Borrows).

When the closure returns, the local variable goes out of scope, its
provenance tag is popped, and `vectors_ref` becomes a dangling pointer.
The `pin-init` crate also explicitly documents that creating references to
fields of the struct inside the initializer is not allowed.

> +
>              spec: Spec::new(dev, bar).inspect(|spec| {
>                  dev_info!(dev,"NVIDIA ({})\n", spec);
>              })?,

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20260903031514.1515905-1-jhubbard@nvidia.com?part=7

^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 12/14] gpu: nova-core: drive GSP events with the SWGEN0 interrupt
  2026-09-03  3:28   ` sashiko-bot
@ 2026-09-03  3:55     ` John Hubbard
  2026-09-04  1:53       ` John Hubbard
  0 siblings, 1 reply; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:55 UTC (permalink / raw)
  To: sashiko-reviews, Danilo Krummrich, Alexandre Courbot
  Cc: Alistair Popple, Bjorn Helgaas, Alex Gaynor, Eliot Courtney,
	Benno Lossin, Zhi Wang, David Airlie, Timur Tabi, Will Pierce,
	Björn Roy Baron, Boqun Feng, Trevor Gross, Gary Guo,
	nova-gpu, Andreas Hindborg, Simona Vetter, Alice Ryhl, LKML,
	Miguel Ojeda

On 9/2/26 8:28 PM, sashiko-bot@kernel.org wrote:
...

> [Severity: High]
> Does this lead to an interrupt storm if the GSP remains in a fault state like a
> HALT or WDT timeout?

Well, maybe. I can't rule this out at first reading, anyway. I'll take
a closer look.

> 
> If there is no recovery path to reset the GSP, wouldn't the unserviceable
> interrupt immediately re-latch after GspFalcon::clear_intr() is called?
> 
> The subsequent calls to GspFalcon::retrigger_intr() and self.tree.rearm_pci_irq()
> would then force a new edge to the GIN tree and re-enable PCI delivery,
> potentially trapping the CPU in an endless loop servicing the same unserviceable
> interrupt.
> 
> Could the GIN leaf source be disabled here instead when encountering an
> unrecoverable fault?
> 

thanks,
-- 
John Hubbard


^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 07/14] gpu: nova-core: add an interrupt delivery self-test
  2026-09-03  3:29   ` sashiko-bot
@ 2026-09-03  3:57     ` John Hubbard
  0 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-03  3:57 UTC (permalink / raw)
  To: sashiko-reviews, Danilo Krummrich, Alexandre Courbot
  Cc: Will Pierce, Alex Gaynor, Bjorn Helgaas, Boqun Feng, Zhi Wang,
	Simona Vetter, Gary Guo, Joel Fernandes, Timur Tabi,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, David Airlie, LKML,
	Miguel Ojeda, Alistair Popple, nova-gpu, Björn Roy Baron,
	Benno Lossin, Eliot Courtney

On 9/2/26 8:29 PM, sashiko-bot@kernel.org wrote:
...
>> @@ -330,6 +337,12 @@ pub(crate) fn new<'a>(
>>          let dev = pdev.as_ref();
>>  
>>          try_pin_init!(Self {
>> +            vectors: crate::irq::alloc_vectors(pdev, crate::irq::SERVICED_SUBTREE.into())?,
>> +
>> +            // SAFETY: `vectors` is initialized above, lives at a pinned stable address, and is
>> +            // dropped after every field that uses `vectors_ref` (struct field drop order).
>> +            vectors_ref: unsafe { &*core::ptr::from_ref(vectors.as_ref().get_ref()) },
> 
> [Severity: High]
> Does this create a dangling pointer under the Rust memory model?

Probably not. Perhaps Sashiko doesn't know about pin_init yet. :)


> 
> `try_pin_init!` provides access to previously initialized fields via local
> variable bindings, which expire at the end of the initialization closure.
> Taking a reference from this local variable and artificially extending its
> lifetime to `'gpu` via `unsafe { &*... }` violates strict aliasing rules
> (Stacked Borrows / Tree Borrows).
> 
> When the closure returns, the local variable goes out of scope, its
> provenance tag is popped, and `vectors_ref` becomes a dangling pointer.
> The `pin-init` crate also explicitly documents that creating references to
> fields of the struct inside the initializer is not allowed.
> 
>> +
>>              spec: Spec::new(dev, bar).inspect(|spec| {
>>                  dev_info!(dev,"NVIDIA ({})\n", spec);
>>              })?,
> 

thanks,
-- 
John Hubbard


^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 12/14] gpu: nova-core: drive GSP events with the SWGEN0 interrupt
  2026-09-03  3:55     ` John Hubbard
@ 2026-09-04  1:53       ` John Hubbard
  0 siblings, 0 replies; 27+ messages in thread
From: John Hubbard @ 2026-09-04  1:53 UTC (permalink / raw)
  To: sashiko-reviews, Danilo Krummrich, Alexandre Courbot
  Cc: Alistair Popple, Bjorn Helgaas, Alex Gaynor, Eliot Courtney,
	Benno Lossin, Zhi Wang, David Airlie, Timur Tabi, Will Pierce,
	Björn Roy Baron, Boqun Feng, Trevor Gross, Gary Guo,
	nova-gpu, Andreas Hindborg, Simona Vetter, Alice Ryhl, LKML,
	Miguel Ojeda

On 9/2/26 8:55 PM, John Hubbard wrote:
> On 9/2/26 8:28 PM, sashiko-bot@kernel.org wrote:
> ...
> 
>> [Severity: High]
>> Does this lead to an interrupt storm if the GSP remains in a fault state like a
>> HALT or WDT timeout?
> 
> Well, maybe. I can't rule this out at first reading, anyway. I'll take
> a closer look.

OK, so yes, this is a bug, good catch. This patch series was merrily
reenabling interrupts without regard to whether the clear actually
worked. So yes, interrupt storm if the GPU/GSP just leaves an interrupt
source enabled.

Easy enough to fix, and I've applied a fix locally for it.

Along the way I have become acutely unhappy with the "90% correct,
10% just Portlandia-style weird" form of some of the code comments
in my series, sigh.

On one hand, the code is correct (well, aside from this issue here).
On the other hand the comment quality is off just enough to make me
absolutely insane.

I'm working on it. :)


thanks,
-- 
John Hubbard


^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 09/14] gpu: nova-core: recover the GSP receive path from corrupt framing
  2026-09-03  3:15 ` [PATCH v3 09/14] gpu: nova-core: recover the GSP receive path from corrupt framing John Hubbard
@ 2026-09-04 10:53   ` Alexandre Courbot
  2026-09-04 11:17     ` Gary Guo
  0 siblings, 1 reply; 27+ messages in thread
From: Alexandre Courbot @ 2026-09-04 10:53 UTC (permalink / raw)
  To: John Hubbard
  Cc: Danilo Krummrich, Timur Tabi, Alistair Popple, Eliot Courtney,
	Zhi Wang, David Airlie, Simona Vetter, Bjorn Helgaas,
	Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, nova-gpu, LKML

On Thu Sep 3, 2026 at 12:15 PM JST, John Hubbard wrote:
<...>
> @@ -838,23 +871,26 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
>          let function = message.header.function();
>          let seq = message.header.sequence();
>  
> -        // 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, including a failed decode.
>          let result = if matches!(function, Ok(f) if f == M::FUNCTION) {
> -            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),

This error path is the only one without a warning. How about:

    None => Err(EIO)
        .inspect_err(|_| dev_warn!(&self.dev, "GSP message {:?} too short\n", M::FUNCTION)),

^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 10/14] gpu: nova-core: bound a GSP wait by a single deadline
  2026-09-03  3:15 ` [PATCH v3 10/14] gpu: nova-core: bound a GSP wait by a single deadline John Hubbard
@ 2026-09-04 11:13   ` Alexandre Courbot
  2026-09-04 11:26     ` Gary Guo
  0 siblings, 1 reply; 27+ messages in thread
From: Alexandre Courbot @ 2026-09-04 11:13 UTC (permalink / raw)
  To: John Hubbard
  Cc: Danilo Krummrich, Timur Tabi, Alistair Popple, Eliot Courtney,
	Zhi Wang, David Airlie, Simona Vetter, Bjorn Helgaas,
	Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, nova-gpu, LKML

On Thu Sep 3, 2026 at 12:15 PM JST, John Hubbard wrote:
<...>
> @@ -611,15 +621,39 @@ pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul
>          self.inner.lock().send_command(bar, command)
>      }
>  
> -    /// Receive a message from the GSP.
> +    /// Waits for an unsolicited GSP event of type `M`, logging any other event that arrives
> +    /// first.
> +    ///
> +    /// The queue is locked for the whole wait, for up to [`Self::RECEIVE_TIMEOUT`], so a
> +    /// concurrent command cannot consume the awaited event.
>      ///
> -    /// See [`CmdqInner::receive_msg`] for details.
> -    pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
> +    /// # Errors
> +    ///
> +    /// - `ETIMEDOUT` if the event does not arrive within [`Self::RECEIVE_TIMEOUT`] of the call,
> +    ///   however many other events arrive while waiting.
> +    /// - `EIO` if the queue is poisoned or a message fails framing or checksum validation (see
> +    ///   [`CmdqInner::wait_for_msg`]).

Let's not mention private methods in public documentation.

> +    ///
> +    /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
> +    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>,
>      {
> -        self.inner.lock().receive_msg(timeout)
> +        let mut inner = self.inner.lock();
> +
> +        let deadline = Instant::<Monotonic>::now() + Self::RECEIVE_TIMEOUT;
> +        loop {
> +            let remaining = deadline - Instant::<Monotonic>::now();
> +            if remaining.is_negative() {
> +                break Err(ETIMEDOUT);
> +            }
> +            match inner.receive_msg::<M>(remaining) {
> +                Ok(msg) => break Ok(msg),
> +                Err(ERANGE) => continue,
> +                Err(e) => break Err(e),
> +            }
> +        }

This block and the one from `send_command` are strictly identical - we
should factor them out.

The right place for this seems to be a new method in `CmdqInner`:

    fn await_msg<M: MessageFromGsp>(&mut self) -> Result<M> ...

Then this `await_msg` simply becomes:

    self.inner.lock().await_msg()

While `send_command` is simplified to:

    let mut inner = self.inner.lock();
    inner.send_command(bar, command)?;
    inner.await_msg()

^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 09/14] gpu: nova-core: recover the GSP receive path from corrupt framing
  2026-09-04 10:53   ` Alexandre Courbot
@ 2026-09-04 11:17     ` Gary Guo
  2026-09-04 13:45       ` Alexandre Courbot
  0 siblings, 1 reply; 27+ messages in thread
From: Gary Guo @ 2026-09-04 11:17 UTC (permalink / raw)
  To: Alexandre Courbot, John Hubbard
  Cc: Danilo Krummrich, Timur Tabi, Alistair Popple, Eliot Courtney,
	Zhi Wang, David Airlie, Simona Vetter, Bjorn Helgaas,
	Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, nova-gpu, LKML

On Fri Sep 4, 2026 at 11:53 AM BST, Alexandre Courbot wrote:
> On Thu Sep 3, 2026 at 12:15 PM JST, John Hubbard wrote:
> <...>
>> @@ -838,23 +871,26 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
>>          let function = message.header.function();
>>          let seq = message.header.sequence();
>>  
>> -        // 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, including a failed decode.
>>          let result = if matches!(function, Ok(f) if f == M::FUNCTION) {
>> -            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),
>
> This error path is the only one without a warning. How about:
>
>     None => Err(EIO)
>         .inspect_err(|_| dev_warn!(&self.dev, "GSP message {:?} too short\n", M::FUNCTION)),

I don't see why we want to use `inspect_err` here (just to make it an oneliner?)

Please do

    None => {
        dev_warn!(&self.dev, "GSP message {:?} too short\n", M::FUNCTION);
        Err(EIO)
    }

Instead.

Thanks,
Gary



^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 10/14] gpu: nova-core: bound a GSP wait by a single deadline
  2026-09-04 11:13   ` Alexandre Courbot
@ 2026-09-04 11:26     ` Gary Guo
  2026-09-04 13:32       ` Alexandre Courbot
  0 siblings, 1 reply; 27+ messages in thread
From: Gary Guo @ 2026-09-04 11:26 UTC (permalink / raw)
  To: Alexandre Courbot, John Hubbard
  Cc: Danilo Krummrich, Timur Tabi, Alistair Popple, Eliot Courtney,
	Zhi Wang, David Airlie, Simona Vetter, Bjorn Helgaas,
	Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, nova-gpu, LKML

On Fri Sep 4, 2026 at 12:13 PM BST, Alexandre Courbot wrote:
> On Thu Sep 3, 2026 at 12:15 PM JST, John Hubbard wrote:
> <...>
>> @@ -611,15 +621,39 @@ pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul
>>          self.inner.lock().send_command(bar, command)
>>      }
>>  
>> -    /// Receive a message from the GSP.
>> +    /// Waits for an unsolicited GSP event of type `M`, logging any other event that arrives
>> +    /// first.
>> +    ///
>> +    /// The queue is locked for the whole wait, for up to [`Self::RECEIVE_TIMEOUT`], so a
>> +    /// concurrent command cannot consume the awaited event.
>>      ///
>> -    /// See [`CmdqInner::receive_msg`] for details.
>> -    pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
>> +    /// # Errors
>> +    ///
>> +    /// - `ETIMEDOUT` if the event does not arrive within [`Self::RECEIVE_TIMEOUT`] of the call,
>> +    ///   however many other events arrive while waiting.
>> +    /// - `EIO` if the queue is poisoned or a message fails framing or checksum validation (see
>> +    ///   [`CmdqInner::wait_for_msg`]).
>
> Let's not mention private methods in public documentation.
>
>> +    ///
>> +    /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
>> +    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>,
>>      {
>> -        self.inner.lock().receive_msg(timeout)
>> +        let mut inner = self.inner.lock();
>> +
>> +        let deadline = Instant::<Monotonic>::now() + Self::RECEIVE_TIMEOUT;
>> +        loop {
>> +            let remaining = deadline - Instant::<Monotonic>::now();
>> +            if remaining.is_negative() {
>> +                break Err(ETIMEDOUT);
>> +            }
>> +            match inner.receive_msg::<M>(remaining) {
>> +                Ok(msg) => break Ok(msg),
>> +                Err(ERANGE) => continue,
>> +                Err(e) => break Err(e),
>> +            }
>> +        }
>
> This block and the one from `send_command` are strictly identical - we
> should factor them out.
>
> The right place for this seems to be a new method in `CmdqInner`:
>
>     fn await_msg<M: MessageFromGsp>(&mut self) -> Result<M> ...
>
> Then this `await_msg` simply becomes:
>
>     self.inner.lock().await_msg()
>
> While `send_command` is simplified to:
>
>     let mut inner = self.inner.lock();
>     inner.send_command(bar, command)?;
>     inner.await_msg()

Unless I misunderstand the GSP code, the unmatched message is not discarded, but
rather the caller returns from inner code, and drops the lock so other waiters
of GSP message can have a chance to take the inner lock and receive the message
so then get the non-matched message out of the way. So your suggestion would
cause `await_msg` to never complete in such cases?

If my understanding of this is correct, then this code should just be moved to
the outer `receive_msg`, because all callers of it have the same loop and I
think it's a wanted behaviour anyway.

BTW, ERANGE is a very bad error code to mean "the message had a recognized but
non-matching function code".

Best,
Gary


^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 10/14] gpu: nova-core: bound a GSP wait by a single deadline
  2026-09-04 11:26     ` Gary Guo
@ 2026-09-04 13:32       ` Alexandre Courbot
  2026-09-04 13:41         ` Gary Guo
  0 siblings, 1 reply; 27+ messages in thread
From: Alexandre Courbot @ 2026-09-04 13:32 UTC (permalink / raw)
  To: Gary Guo
  Cc: John Hubbard, Danilo Krummrich, Timur Tabi, Alistair Popple,
	Eliot Courtney, Zhi Wang, David Airlie, Simona Vetter,
	Bjorn Helgaas, Miguel Ojeda, Alex Gaynor, Boqun Feng,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, nova-gpu, LKML

On Fri Sep 4, 2026 at 8:26 PM JST, Gary Guo wrote:
> On Fri Sep 4, 2026 at 12:13 PM BST, Alexandre Courbot wrote:
>> On Thu Sep 3, 2026 at 12:15 PM JST, John Hubbard wrote:
>> <...>
>>> @@ -611,15 +621,39 @@ pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul
>>>          self.inner.lock().send_command(bar, command)
>>>      }
>>>  
>>> -    /// Receive a message from the GSP.
>>> +    /// Waits for an unsolicited GSP event of type `M`, logging any other event that arrives
>>> +    /// first.
>>> +    ///
>>> +    /// The queue is locked for the whole wait, for up to [`Self::RECEIVE_TIMEOUT`], so a
>>> +    /// concurrent command cannot consume the awaited event.
>>>      ///
>>> -    /// See [`CmdqInner::receive_msg`] for details.
>>> -    pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
>>> +    /// # Errors
>>> +    ///
>>> +    /// - `ETIMEDOUT` if the event does not arrive within [`Self::RECEIVE_TIMEOUT`] of the call,
>>> +    ///   however many other events arrive while waiting.
>>> +    /// - `EIO` if the queue is poisoned or a message fails framing or checksum validation (see
>>> +    ///   [`CmdqInner::wait_for_msg`]).
>>
>> Let's not mention private methods in public documentation.
>>
>>> +    ///
>>> +    /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
>>> +    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>,
>>>      {
>>> -        self.inner.lock().receive_msg(timeout)
>>> +        let mut inner = self.inner.lock();
>>> +
>>> +        let deadline = Instant::<Monotonic>::now() + Self::RECEIVE_TIMEOUT;
>>> +        loop {
>>> +            let remaining = deadline - Instant::<Monotonic>::now();
>>> +            if remaining.is_negative() {
>>> +                break Err(ETIMEDOUT);
>>> +            }
>>> +            match inner.receive_msg::<M>(remaining) {
>>> +                Ok(msg) => break Ok(msg),
>>> +                Err(ERANGE) => continue,
>>> +                Err(e) => break Err(e),
>>> +            }
>>> +        }
>>
>> This block and the one from `send_command` are strictly identical - we
>> should factor them out.
>>
>> The right place for this seems to be a new method in `CmdqInner`:
>>
>>     fn await_msg<M: MessageFromGsp>(&mut self) -> Result<M> ...
>>
>> Then this `await_msg` simply becomes:
>>
>>     self.inner.lock().await_msg()
>>
>> While `send_command` is simplified to:
>>
>>     let mut inner = self.inner.lock();
>>     inner.send_command(bar, command)?;
>>     inner.await_msg()
>
> Unless I misunderstand the GSP code, the unmatched message is not discarded, but
> rather the caller returns from inner code, and drops the lock so other waiters
> of GSP message can have a chance to take the inner lock and receive the message
> so then get the non-matched message out of the way. So your suggestion would
> cause `await_msg` to never complete in such cases?
>
> If my understanding of this is correct, then this code should just be moved to
> the outer `receive_msg`, because all callers of it have the same loop and I
> think it's a wanted behaviour anyway.

I don't really understand what you mean here. There is no concept of
other waiters at the moment, and `receive_msg` unconditionally advances
the read pointer. In effect, the queue is working in a synchronous
manner (which is the design of the queue itself, not a Nova limitation)
so there can be only one expected reply after a message has been
successfully sent.

I think once we move to the newer firmware we will want to add more
sophisticated message dispatchers, but for now this simple
implementation does what we need.

As for my comment, please check with the code - it's really about
factoring out a block of code without any runtime side-effect.

>
> BTW, ERANGE is a very bad error code to mean "the message had a recognized but
> non-matching function code".

Maybe we can change this to `ENOMSG`. This will need to be its own patch
though.

^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 10/14] gpu: nova-core: bound a GSP wait by a single deadline
  2026-09-04 13:32       ` Alexandre Courbot
@ 2026-09-04 13:41         ` Gary Guo
  0 siblings, 0 replies; 27+ messages in thread
From: Gary Guo @ 2026-09-04 13:41 UTC (permalink / raw)
  To: Alexandre Courbot, Gary Guo
  Cc: John Hubbard, Danilo Krummrich, Timur Tabi, Alistair Popple,
	Eliot Courtney, Zhi Wang, David Airlie, Simona Vetter,
	Bjorn Helgaas, Miguel Ojeda, Alex Gaynor, Boqun Feng,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, nova-gpu, LKML

On Fri Sep 4, 2026 at 2:32 PM BST, Alexandre Courbot wrote:
> On Fri Sep 4, 2026 at 8:26 PM JST, Gary Guo wrote:
>> On Fri Sep 4, 2026 at 12:13 PM BST, Alexandre Courbot wrote:
>>> On Thu Sep 3, 2026 at 12:15 PM JST, John Hubbard wrote:
>>> <...>
>>>> @@ -611,15 +621,39 @@ pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul
>>>>          self.inner.lock().send_command(bar, command)
>>>>      }
>>>>  
>>>> -    /// Receive a message from the GSP.
>>>> +    /// Waits for an unsolicited GSP event of type `M`, logging any other event that arrives
>>>> +    /// first.
>>>> +    ///
>>>> +    /// The queue is locked for the whole wait, for up to [`Self::RECEIVE_TIMEOUT`], so a
>>>> +    /// concurrent command cannot consume the awaited event.
>>>>      ///
>>>> -    /// See [`CmdqInner::receive_msg`] for details.
>>>> -    pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
>>>> +    /// # Errors
>>>> +    ///
>>>> +    /// - `ETIMEDOUT` if the event does not arrive within [`Self::RECEIVE_TIMEOUT`] of the call,
>>>> +    ///   however many other events arrive while waiting.
>>>> +    /// - `EIO` if the queue is poisoned or a message fails framing or checksum validation (see
>>>> +    ///   [`CmdqInner::wait_for_msg`]).
>>>
>>> Let's not mention private methods in public documentation.
>>>
>>>> +    ///
>>>> +    /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
>>>> +    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>,
>>>>      {
>>>> -        self.inner.lock().receive_msg(timeout)
>>>> +        let mut inner = self.inner.lock();
>>>> +
>>>> +        let deadline = Instant::<Monotonic>::now() + Self::RECEIVE_TIMEOUT;
>>>> +        loop {
>>>> +            let remaining = deadline - Instant::<Monotonic>::now();
>>>> +            if remaining.is_negative() {
>>>> +                break Err(ETIMEDOUT);
>>>> +            }
>>>> +            match inner.receive_msg::<M>(remaining) {
>>>> +                Ok(msg) => break Ok(msg),
>>>> +                Err(ERANGE) => continue,
>>>> +                Err(e) => break Err(e),
>>>> +            }
>>>> +        }
>>>
>>> This block and the one from `send_command` are strictly identical - we
>>> should factor them out.
>>>
>>> The right place for this seems to be a new method in `CmdqInner`:
>>>
>>>     fn await_msg<M: MessageFromGsp>(&mut self) -> Result<M> ...
>>>
>>> Then this `await_msg` simply becomes:
>>>
>>>     self.inner.lock().await_msg()
>>>
>>> While `send_command` is simplified to:
>>>
>>>     let mut inner = self.inner.lock();
>>>     inner.send_command(bar, command)?;
>>>     inner.await_msg()
>>
>> Unless I misunderstand the GSP code, the unmatched message is not discarded, but
>> rather the caller returns from inner code, and drops the lock so other waiters
>> of GSP message can have a chance to take the inner lock and receive the message
>> so then get the non-matched message out of the way. So your suggestion would
>> cause `await_msg` to never complete in such cases?
>>
>> If my understanding of this is correct, then this code should just be moved to
>> the outer `receive_msg`, because all callers of it have the same loop and I
>> think it's a wanted behaviour anyway.
>
> I don't really understand what you mean here. There is no concept of
> other waiters at the moment, and `receive_msg` unconditionally advances
> the read pointer. In effect, the queue is working in a synchronous
> manner (which is the design of the queue itself, not a Nova limitation)
> so there can be only one expected reply after a message has been
> successfully sent.
>
> I think once we move to the newer firmware we will want to add more
> sophisticated message dispatchers, but for now this simple
> implementation does what we need.

I did misread the `receive_msg` code. I read `Err(ERANGE)` as `Err(ERANGE)?` so
I thought the pointer was no incremented in such case.

So everything makes sense to me now.

Best,
Gary

>
> As for my comment, please check with the code - it's really about
> factoring out a block of code without any runtime side-effect.
>
>>
>> BTW, ERANGE is a very bad error code to mean "the message had a recognized but
>> non-matching function code".
>
> Maybe we can change this to `ENOMSG`. This will need to be its own patch
> though.



^ permalink raw reply	[flat|nested] 27+ messages in thread

* Re: [PATCH v3 09/14] gpu: nova-core: recover the GSP receive path from corrupt framing
  2026-09-04 11:17     ` Gary Guo
@ 2026-09-04 13:45       ` Alexandre Courbot
  0 siblings, 0 replies; 27+ messages in thread
From: Alexandre Courbot @ 2026-09-04 13:45 UTC (permalink / raw)
  To: Gary Guo
  Cc: John Hubbard, Danilo Krummrich, Timur Tabi, Alistair Popple,
	Eliot Courtney, Zhi Wang, David Airlie, Simona Vetter,
	Bjorn Helgaas, Miguel Ojeda, Alex Gaynor, Boqun Feng,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, nova-gpu, LKML

On Fri Sep 4, 2026 at 8:17 PM JST, Gary Guo wrote:
> On Fri Sep 4, 2026 at 11:53 AM BST, Alexandre Courbot wrote:
>> On Thu Sep 3, 2026 at 12:15 PM JST, John Hubbard wrote:
>> <...>
>>> @@ -838,23 +871,26 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
>>>          let function = message.header.function();
>>>          let seq = message.header.sequence();
>>>  
>>> -        // 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, including a failed decode.
>>>          let result = if matches!(function, Ok(f) if f == M::FUNCTION) {
>>> -            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),
>>
>> This error path is the only one without a warning. How about:
>>
>>     None => Err(EIO)
>>         .inspect_err(|_| dev_warn!(&self.dev, "GSP message {:?} too short\n", M::FUNCTION)),
>
> I don't see why we want to use `inspect_err` here (just to make it an oneliner?)
>
> Please do
>
>     None => {
>         dev_warn!(&self.dev, "GSP message {:?} too short\n", M::FUNCTION);
>         Err(EIO)
>     }
>
> Instead.

Yeah looking again at my suggestion it seems a bit nonsensical to use
`inspect_err` from an environment where it will trigger unconditionally.
Shorter is not always better. Let's use your version.

^ permalink raw reply	[flat|nested] 27+ messages in thread

end of thread, other threads:[~2026-09-04 13:46 UTC | newest]

Thread overview: 27+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-09-03  3:14 [PATCH v3 00/14] nova-core: GPU interrupt support and GSP event delivery John Hubbard
2026-09-03  3:15 ` [PATCH v3 01/14] rust: pci: declare IrqType and IrqTypes with impl_flags John Hubbard
2026-09-03  3:15 ` [PATCH v3 02/14] rust: sync: completion: add wait_for_completion_timeout() John Hubbard
2026-09-03  3:15 ` [PATCH v3 03/14] gpu: nova-core: add the GIN vector and subtree newtypes John Hubbard
2026-09-03  3:15 ` [PATCH v3 04/14] gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers John Hubbard
2026-09-03  3:15 ` [PATCH v3 05/14] gpu: nova-core: add the per-architecture GIN CPU interrupt HAL John Hubbard
2026-09-03  3:15 ` [PATCH v3 06/14] gpu: nova-core: add the GIN interrupt tree and allocate its vectors John Hubbard
2026-09-03  3:15 ` [PATCH v3 07/14] gpu: nova-core: add an interrupt delivery self-test John Hubbard
2026-09-03  3:29   ` sashiko-bot
2026-09-03  3:57     ` John Hubbard
2026-09-03  3:15 ` [PATCH v3 08/14] gpu: nova-core: log GSP events instead of discarding them John Hubbard
2026-09-03  3:15 ` [PATCH v3 09/14] gpu: nova-core: recover the GSP receive path from corrupt framing John Hubbard
2026-09-04 10:53   ` Alexandre Courbot
2026-09-04 11:17     ` Gary Guo
2026-09-04 13:45       ` Alexandre Courbot
2026-09-03  3:15 ` [PATCH v3 10/14] gpu: nova-core: bound a GSP wait by a single deadline John Hubbard
2026-09-04 11:13   ` Alexandre Courbot
2026-09-04 11:26     ` Gary Guo
2026-09-04 13:32       ` Alexandre Courbot
2026-09-04 13:41         ` Gary Guo
2026-09-03  3:15 ` [PATCH v3 11/14] gpu: nova-core: add the falcon interrupt status and routing registers John Hubbard
2026-09-03  3:15 ` [PATCH v3 12/14] gpu: nova-core: drive GSP events with the SWGEN0 interrupt John Hubbard
2026-09-03  3:28   ` sashiko-bot
2026-09-03  3:55     ` John Hubbard
2026-09-04  1:53       ` John Hubbard
2026-09-03  3:15 ` [PATCH v3 13/14] gpu: nova-core: add KUnit tests for the interrupt tree and HALs John Hubbard
2026-09-03  3:15 ` [PATCH v3 14/14] gpu: nova-core: document the GIN interrupt controller and GSP events John Hubbard

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox