* [PATCH v2 01/15] rust: pci: declare IrqType and IrqTypes with impl_flags
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
@ 2026-08-29 1:22 ` John Hubbard
2026-08-29 1:22 ` [PATCH v2 02/15] rust: sync: completion: add wait_for_completion_timeout() John Hubbard
` (14 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:22 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>
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 [flat|nested] 18+ messages in thread* [PATCH v2 02/15] rust: sync: completion: add wait_for_completion_timeout()
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
2026-08-29 1:22 ` [PATCH v2 01/15] rust: pci: declare IrqType and IrqTypes with impl_flags John Hubbard
@ 2026-08-29 1:22 ` John Hubbard
2026-08-29 1:22 ` [PATCH v2 03/15] gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers John Hubbard
` (13 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:22 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().
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 [flat|nested] 18+ messages in thread* [PATCH v2 03/15] gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
2026-08-29 1:22 ` [PATCH v2 01/15] rust: pci: declare IrqType and IrqTypes with impl_flags John Hubbard
2026-08-29 1:22 ` [PATCH v2 02/15] rust: sync: completion: add wait_for_completion_timeout() John Hubbard
@ 2026-08-29 1:22 ` John Hubbard
2026-08-29 1:22 ` [PATCH v2 04/15] gpu: nova-core: add the GIN vector and subtree newtypes John Hubbard
` (12 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:22 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.
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 | 11 +++++
drivers/gpu/nova-core/irq/regs.rs | 71 ++++++++++++++++++++++++++++++
drivers/gpu/nova-core/nova_core.rs | 1 +
3 files changed, 83 insertions(+)
create mode 100644 drivers/gpu/nova-core/irq.rs
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
new file mode 100644
index 000000000000..6656a1a23d59
--- /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 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..a01a78d197bd
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/regs.rs
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use kernel::io::register;
+
+// 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 {}
+
+ /// 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 {}
+
+ /// 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 {}
+
+ /// 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 {}
+
+ /// 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 {}
+
+ /// 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 {}
+}
diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
index 35a8b1214b0e..68b5abfe494d 100644
--- a/drivers/gpu/nova-core/nova_core.rs
+++ b/drivers/gpu/nova-core/nova_core.rs
@@ -17,6 +17,7 @@
mod fsp;
mod gpu;
mod gsp;
+mod irq;
mod mctp;
#[macro_use]
mod num;
--
2.55.0
^ permalink raw reply [flat|nested] 18+ messages in thread* [PATCH v2 04/15] gpu: nova-core: add the GIN vector and subtree newtypes
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (2 preceding siblings ...)
2026-08-29 1:22 ` [PATCH v2 03/15] gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers John Hubbard
@ 2026-08-29 1:22 ` John Hubbard
2026-08-29 1:22 ` [PATCH v2 05/15] gpu: nova-core: add the per-architecture GIN CPU interrupt HAL John Hubbard
` (11 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:22 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 | 1 +
drivers/gpu/nova-core/irq/interrupt_tree.rs | 209 ++++++++++++++++++++
drivers/gpu/nova-core/nova_core.rs | 1 +
3 files changed, 211 insertions(+)
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
index 6656a1a23d59..3066ceeb850c 100644
--- a/drivers/gpu/nova-core/irq.rs
+++ b/drivers/gpu/nova-core/irq.rs
@@ -8,4 +8,5 @@
//!
//! See `Documentation/gpu/nova/core/interrupts.rst`.
+mod interrupt_tree;
mod regs;
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..da24f3d35893
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/interrupt_tree.rs
@@ -0,0 +1,209 @@
+// 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::*, //
+};
+
+/// Index of a leaf register, bounded to the `0..16` range covered by the leaf register arrays.
+pub(super) type LeafIndex = Bounded<usize, 4>;
+
+/// 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;
+
+/// Mask that bounds a leaf index to the leaf register arrays.
+const LEAF_INDEX_MASK: usize = LeafCount::Sixteen.into_raw() - 1;
+
+/// 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_raw(self) -> usize {
+ self as usize
+ }
+
+ /// Returns the number of subtrees, each of which covers two leaves.
+ pub(super) const fn subtree_count(self) -> u32 {
+ self as 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 as 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()
+ }
+
+ /// Returns the set as the value the `TOP` enable registers take.
+ pub(super) const fn into_raw(self) -> u32 {
+ self.0
+ }
+}
+
+impl From<Subtree> for SubtreeSet {
+ fn from(subtree: Subtree) -> Self {
+ Self(subtree.into_raw())
+ }
+}
+
+/// A GIN interrupt vector.
+///
+/// # Invariants
+///
+/// The vector lies within the widest tree any supported part implements.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(super) struct GinVector(u32);
+
+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 {
+ build_assert!(VECTOR < LeafCount::Sixteen.vector_count());
+
+ // INVARIANT: `VECTOR` is within the widest supported tree.
+ Self(VECTOR)
+ }
+
+ /// Returns the vector number.
+ pub(super) const fn into_raw(self) -> u32 {
+ self.0
+ }
+
+ /// Returns the leaf that carries this vector.
+ pub(super) fn leaf_index(self) -> LeafIndex {
+ // By the type invariant the quotient is already below 16, so the mask changes nothing. It
+ // is what proves the bound to `from_expr`.
+ LeafIndex::from_expr(crate::num::u32_as_usize(self.0 / VECTORS_PER_LEAF) & LEAF_INDEX_MASK)
+ }
+
+ /// Returns this vector's bit within its leaf.
+ pub(super) const fn leaf_mask(self) -> LeafMask {
+ LeafMask(1 << (self.0 % 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 / (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 >= leaves.vector_count() {
+ return Err(EINVAL);
+ }
+
+ Ok(())
+ }
+}
diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
index 68b5abfe494d..dfd11dfe562c 100644
--- a/drivers/gpu/nova-core/nova_core.rs
+++ b/drivers/gpu/nova-core/nova_core.rs
@@ -17,6 +17,7 @@
mod fsp;
mod gpu;
mod gsp;
+#[expect(dead_code)]
mod irq;
mod mctp;
#[macro_use]
--
2.55.0
^ permalink raw reply [flat|nested] 18+ messages in thread* [PATCH v2 05/15] gpu: nova-core: add the per-architecture GIN CPU interrupt HAL
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (3 preceding siblings ...)
2026-08-29 1:22 ` [PATCH v2 04/15] gpu: nova-core: add the GIN vector and subtree newtypes John Hubbard
@ 2026-08-29 1:22 ` John Hubbard
2026-08-29 1:25 ` [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (10 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:22 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.
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/hal.rs | 111 +++++++++++++++++++++++++
drivers/gpu/nova-core/irq/hal/gh100.rs | 31 +++++++
drivers/gpu/nova-core/irq/hal/tu102.rs | 30 +++++++
4 files changed, 173 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..02ecfc47f4d0 100644
--- a/drivers/gpu/nova-core/irq.rs
+++ b/drivers/gpu/nova-core/irq.rs
@@ -8,5 +8,6 @@
//!
//! See `Documentation/gpu/nova/core/interrupts.rst`.
+mod hal;
mod interrupt_tree;
mod regs;
diff --git a/drivers/gpu/nova-core/irq/hal.rs b/drivers/gpu/nova-core/irq/hal.rs
new file mode 100644
index 000000000000..ee354859b965
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/hal.rs
@@ -0,0 +1,111 @@
+// 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,
+ pci::IrqType, //
+};
+
+use crate::{
+ driver::Bar0,
+ gpu::{
+ Architecture,
+ Chipset, //
+ }, //
+};
+
+use super::{
+ interrupt_tree::{
+ LeafCount,
+ Subtree,
+ SubtreeSet, //
+ },
+ regs, //
+};
+
+/// 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(
+ regs::NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_CLEAR,
+ subtrees.into_raw().into(),
+ );
+ bar.write(
+ regs::NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_SET,
+ subtrees.into_raw().into(),
+ );
+ }
+}
+
+/// Per-architecture properties of the GIN CPU interrupt tree.
+///
+/// The tree size and the method that rearms PCI interrupt delivery differ by family. The tree
+/// walk, the vector encoding, and the read-and-clear sequence do not, and are in generic code.
+///
+/// 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 `irq_type`.
+ ///
+ /// `None` means that `irq_type` needs no rearm write. That is the case for `INTx`, which is
+ /// level-triggered, and which nova-core does not allocate.
+ fn pci_irq_rearm_method(&self, irq_type: IrqType) -> Option<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..32b9b4a01adb
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/hal/gh100.rs
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use kernel::pci::IrqType;
+
+use super::{
+ CpuInterruptHal,
+ LeafCount,
+ 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, irq_type: IrqType) -> Option<PciIrqRearmMethod> {
+ match irq_type {
+ IrqType::Intx => None,
+ IrqType::Msi => Some(PciIrqRearmMethod::TopEnableCycleServiced),
+ IrqType::MsiX => Some(PciIrqRearmMethod::TopEnableCycleSubtree),
+ }
+ }
+}
+
+const GH100: Gh100 = Gh100;
+pub(super) const GH100_HAL: &dyn CpuInterruptHal = &GH100;
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..e22eb37906a8
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/hal/tu102.rs
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use kernel::pci::IrqType;
+
+use super::{
+ CpuInterruptHal,
+ LeafCount,
+ 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, irq_type: IrqType) -> Option<PciIrqRearmMethod> {
+ match irq_type {
+ IrqType::Intx => None,
+ IrqType::Msi => Some(PciIrqRearmMethod::ConfigMirrorEoi),
+ IrqType::MsiX => Some(PciIrqRearmMethod::TopEnableCycleSubtree),
+ }
+ }
+}
+
+const TU102: Tu102 = Tu102;
+pub(super) const TU102_HAL: &dyn CpuInterruptHal = &TU102;
--
2.55.0
^ permalink raw reply [flat|nested] 18+ messages in thread* Re: [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (4 preceding siblings ...)
2026-08-29 1:22 ` [PATCH v2 05/15] gpu: nova-core: add the per-architecture GIN CPU interrupt HAL John Hubbard
@ 2026-08-29 1:25 ` John Hubbard
2026-08-29 1:35 ` John Hubbard
2026-08-29 1:33 ` [PATCH v2 06/15] gpu: nova-core: add the GIN interrupt tree and allocate its vectors John Hubbard
` (9 subsequent siblings)
15 siblings, 1 reply; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:25 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
On 8/28/26 6:22 PM, John Hubbard wrote:
> I'm posting a v2 because there have been some significant changes, as a
> result of the v1 review, plus Danilo's new IRQ commits that I've rebased
> onto.
There was a failure in git-send-email part way through. I'll attempt to
resend, once I figure out what went wrong.
Only the cover letter and the first 4 patches got sent.
thanks,
--
John Hubbard
>
> 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, plus the six commits of Danilo
> Krummrich's PCI interrupt-vector series [1], which I've cherry-picked
> from mainline for now.
>
> 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-v2/
>
> Changes in v2:
>
> * Rebased onto current drm-rust-next. The PCI interrupt-vector rework
> that v1 patches 2 and 3 proposed is in mainline now as Danilo's series
> [1], so both are dropped. This series carries those six commits as
> prerequisites until drm-rust-next picks them up.
>
> * nova-core uses the merged API: the driver's device data owns the
> vector allocation under an explicit lifetime rather than through
> devres, and each handler takes an IrqRequest for its own subtree's
> vector.
>
> * Dropped "allocate PCI MSI vector during probe" (v1 patch 4). What it
> added is replaced by patch 6, and its commit message justified MSI
> with a VFIO claim that does not hold. nova-core still allocates MSI-X
> or MSI, and no longer falls back to INTx. (Danilo)
>
> * Dropped the type-invariant documentation and the SAFETY rewrites from
> the wait_for_completion_timeout() patch, leaving only the new method
> itself. (Alexandre)
>
> * New: declare pci::IrqType and IrqTypes with impl_flags, so a call site
> reads IrqType::MsiX | IrqType::Msi. (Gary)
>
> * New: the GIN vector and subtree newtypes. A vector, a leaf index, a
> set of vectors within one leaf, one subtree, a set of subtrees, and a
> leaf count are separate types now, so a leaf mask cannot be passed
> where a TOP bit belongs. The HAL returns a LeafCount rather than a
> usize. GSP_LEAF and GSP_BIT are gone, along with the
> LeafIndex::new::<GSP_LEAF>() calls. (Danilo)
>
> * Merged the tree API patch into the vector allocation patch, and moved
> both after the HAL. Tree owns the BAR mapping, so no tree method takes
> a bar argument. The Leaf<Idle>/Leaf<Pending> type state gives way to a
> LeafPending newtype that only Tree::read_pending hands out, and enable
> and disable are Tree methods. (Danilo)
>
> * Added LeafEnableGuard and TopEnableGuard. The self-test's teardown
> guard and GspIrq's open-coded destructor are both gone, and probe no
> longer needs a separate interrupt-enable step. (Danilo)
>
> * Moved the GIN and MSI EOI register definitions to irq/regs.rs.
> (Danilo)
>
> * 13 KUnit tests rather than 14. The tree tests now cover the newtypes,
> and testing those needs no BAR mapping. One test went away because a
> leaf count derives its subtree set by construction.
>
> Tested on Turing, Ampere, Blackwell GPUs.
>
> One known gap: driver_read_area still reads the GSP producer pointer
> with no acquire barrier. Gary Guo's barrier series puts dma_mb(Read) at
> exactly that point [2], so let's just wait for his fix to land.
>
> [1] https://lore.kernel.org/all/20260813165234.620555-1-dakr@kernel.org/
> [2] https://lore.kernel.org/all/20260609-rust-barrier-v2-4-30fcc48e1cd0@garyguo.net/
>
>
> 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 (13):
> rust: pci: declare IrqType and IrqTypes with impl_flags
> gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers
> gpu: nova-core: add the GIN vector and subtree newtypes
> gpu: nova-core: add the per-architecture GIN CPU interrupt HAL
> gpu: nova-core: add an interrupt delivery self-test
> gpu: nova-core: dispatch GSP events instead of discarding them
> gpu: nova-core: match GSP RPC replies by sequence, not just function
> gpu: nova-core: recover the GSP receive path from corrupt framing
> gpu: nova-core: bound a GSP wait by a single deadline
> gpu: nova-core: drive GSP events with the SWGEN0 interrupt
> gpu: nova-core: retrigger the GSP falcon and clear every latched cause
> gpu: nova-core: add KUnit tests for the interrupt tree and HALs
> gpu: nova-core: document the GIN interrupt controller and GSP events
>
> Documentation/gpu/nova/core/interrupts.rst | 686 ++++++++++++++++++++
> Documentation/gpu/nova/index.rst | 1 +
> drivers/gpu/nova-core/Kconfig | 15 +
> drivers/gpu/nova-core/driver.rs | 55 +-
> drivers/gpu/nova-core/falcon/gsp.rs | 71 +-
> drivers/gpu/nova-core/falcon/hal.rs | 32 +
> drivers/gpu/nova-core/gpu.rs | 28 +-
> drivers/gpu/nova-core/gsp.rs | 17 +-
> drivers/gpu/nova-core/gsp/cmdq.rs | 286 ++++++--
> drivers/gpu/nova-core/gsp/commands.rs | 8 +-
> drivers/gpu/nova-core/gsp/fw.rs | 13 +-
> drivers/gpu/nova-core/gsp/sequencer.rs | 8 +-
> drivers/gpu/nova-core/irq.rs | 105 +++
> drivers/gpu/nova-core/irq/doorbell_test.rs | 298 +++++++++
> drivers/gpu/nova-core/irq/gsp.rs | 232 +++++++
> drivers/gpu/nova-core/irq/hal.rs | 192 ++++++
> drivers/gpu/nova-core/irq/hal/gh100.rs | 31 +
> drivers/gpu/nova-core/irq/hal/tu102.rs | 30 +
> drivers/gpu/nova-core/irq/interrupt_tree.rs | 615 ++++++++++++++++++
> drivers/gpu/nova-core/irq/regs.rs | 71 ++
> drivers/gpu/nova-core/nova_core.rs | 1 +
> drivers/gpu/nova-core/regs.rs | 24 +
> rust/kernel/pci/irq.rs | 68 +-
> rust/kernel/sync/completion.rs | 23 +-
> 24 files changed, 2767 insertions(+), 143 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
>
^ permalink raw reply [flat|nested] 18+ messages in thread* Re: [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery
2026-08-29 1:25 ` [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
@ 2026-08-29 1:35 ` John Hubbard
0 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:35 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
On 8/28/26 6:25 PM, John Hubbard wrote:
> On 8/28/26 6:22 PM, John Hubbard wrote:
>> I'm posting a v2 because there have been some significant changes, as a
>> result of the v1 review, plus Danilo's new IRQ commits that I've rebased
>> onto.
>
> There was a failure in git-send-email part way through. I'll attempt to
> resend, once I figure out what went wrong.
>
> Only the cover letter and the first 4 patches got sent.
>
OK, it was an unexplained, intermittent failure, so instead of re-sending,
I simply sent the reset of the series, which worked this time (!).
So the whole series is intact, now. whew.
thanks,
--
John Hubbard
^ permalink raw reply [flat|nested] 18+ messages in thread
* [PATCH v2 06/15] gpu: nova-core: add the GIN interrupt tree and allocate its vectors
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (5 preceding siblings ...)
2026-08-29 1:25 ` [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
@ 2026-08-29 1:33 ` John Hubbard
2026-08-29 1:33 ` [PATCH v2 07/15] gpu: nova-core: add an interrupt delivery self-test John Hubbard
` (8 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:33 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. 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 | 89 ++++++
drivers/gpu/nova-core/irq/interrupt_tree.rs | 284 +++++++++++++++++++-
2 files changed, 369 insertions(+), 4 deletions(-)
diff --git a/drivers/gpu/nova-core/irq.rs b/drivers/gpu/nova-core/irq.rs
index 02ecfc47f4d0..c6bf1dbacabe 100644
--- a/drivers/gpu/nova-core/irq.rs
+++ b/drivers/gpu/nova-core/irq.rs
@@ -11,3 +11,92 @@
mod hal;
mod interrupt_tree;
mod regs;
+
+use kernel::{
+ device::Bound,
+ irq,
+ pci::{
+ self,
+ IrqType, //
+ },
+ prelude::*, //
+};
+
+use interrupt_tree::{
+ Subtree,
+ SubtreeSet, //
+};
+
+/// 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,
+}
+
+impl SubtreeVectors<'_> {
+ /// Returns the interrupt type the PCI core selected for these vectors.
+ pub(crate) fn irq_type(&self) -> IrqType {
+ self.vectors.irq_type()
+ }
+
+ /// Returns an [`irq::IrqRequest`] for the vector that delivers `subtree`.
+ ///
+ /// # 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);
+ }
+
+ self.vectors
+ .index(entry_index(self.irq_type(), subtree))
+ .map(Into::into)
+ }
+}
+
+/// Returns the index of the allocated entry that `subtree` raises.
+///
+/// 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. nova-core never allocates INTx.
+fn entry_index(irq_type: IrqType, subtree: Subtree) -> usize {
+ match irq_type {
+ IrqType::MsiX => crate::num::u32_as_usize(subtree.index()),
+ IrqType::Msi | IrqType::Intx => 0,
+ }
+}
+
+/// 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.
+/// nova-core does not fall back to a shared INTx line.
+///
+/// # 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 = match pdev.alloc_irq_vectors(entries, entries, IrqType::MsiX.into()) {
+ Ok(vectors) => vectors,
+ Err(_) => pdev.alloc_irq_vectors(1, 1, IrqType::Msi.into())?,
+ };
+
+ Ok(SubtreeVectors { vectors, serviced })
+}
diff --git a/drivers/gpu/nova-core/irq/interrupt_tree.rs b/drivers/gpu/nova-core/irq/interrupt_tree.rs
index da24f3d35893..523b26d55137 100644
--- a/drivers/gpu/nova-core/irq/interrupt_tree.rs
+++ b/drivers/gpu/nova-core/irq/interrupt_tree.rs
@@ -1,17 +1,49 @@
// 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,
+ pci::IrqType,
prelude::*, //
};
+use crate::{
+ driver::Bar0,
+ gpu::Chipset, //
+};
+
+use super::{
+ hal::{
+ cpu_interrupt_hal,
+ PciIrqRearmMethod, //
+ },
+ regs::{
+ NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF as CPU_INTR_LEAF,
+ NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_EN_CLEAR as CPU_INTR_LEAF_EN_CLEAR,
+ NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_EN_SET as CPU_INTR_LEAF_EN_SET,
+ NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_TRIGGER as CPU_INTR_LEAF_TRIGGER,
+ NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_CLEAR as CPU_INTR_TOP_EN_CLEAR,
+ NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_SET as CPU_INTR_TOP_EN_SET, //
+ }, //
+};
+
/// Index of a leaf register, bounded to the `0..16` range covered by the leaf register arrays.
pub(super) type LeafIndex = Bounded<usize, 4>;
@@ -97,7 +129,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.
@@ -115,7 +147,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.
@@ -199,7 +231,7 @@ pub(super) const fn subtree(self) -> Subtree {
/// # Errors
///
/// `EINVAL` if the vector lies beyond the last leaf such a tree implements.
- pub(super) const fn validate(self, leaves: LeafCount) -> Result {
+ pub(super) fn validate(self, leaves: LeafCount) -> Result {
if self.0 >= leaves.vector_count() {
return Err(EINVAL);
}
@@ -207,3 +239,247 @@ pub(super) const fn validate(self, leaves: LeafCount) -> Result {
Ok(())
}
}
+
+/// Returns the leaves that subtree `index` covers.
+///
+/// An index beyond the leaf register arrays yields nothing rather than panicking.
+fn subtree_leaves(index: u32) -> impl Iterator<Item = LeafIndex> {
+ let first = index * LEAVES_PER_SUBTREE;
+
+ (first..first + LEAVES_PER_SUBTREE)
+ .filter_map(|leaf| LeafIndex::try_new(crate::num::u32_as_usize(leaf)))
+}
+
+/// 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, or `None` if the interrupt type needs no rearm
+ /// write.
+ rearm: Option<PciIrqRearmMethod>,
+}
+
+impl<'a> Tree<'a> {
+ /// Creates a `Tree` for `chipset` covering `serviced`, with the rearm method that `irq_type`
+ /// requires.
+ ///
+ /// Each serviced subtree must have an allocated PCI vector and a registered handler, which
+ /// [`super::alloc_vectors`] sizes the allocation for. Subtrees the architecture does not
+ /// implement are dropped.
+ pub(super) fn new(
+ bar: Bar0<'a>,
+ chipset: Chipset,
+ irq_type: IrqType,
+ serviced: SubtreeSet,
+ ) -> Self {
+ let hal = cpu_interrupt_hal(chipset);
+ let leaves = hal.leaf_count();
+
+ Self {
+ bar,
+ leaves,
+ serviced: serviced.intersection(leaves.subtree_set()),
+ rearm: hal.pci_irq_rearm_method(irq_type),
+ }
+ }
+
+ /// Returns the subtrees this tree services.
+ pub(super) fn serviced(&self) -> SubtreeSet {
+ self.serviced
+ }
+
+ /// 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) {
+ if let Some(method) = self.rearm {
+ method.rearm(self.bar, self.serviced, subtree);
+ }
+ }
+
+ /// Enables this tree's serviced subtrees (`TOP_EN_SET`).
+ pub(super) fn enable_top(&self) {
+ self.bar
+ .write(CPU_INTR_TOP_EN_SET, self.serviced.into_raw().into());
+ }
+
+ /// Disables this tree's serviced subtrees (`TOP_EN_CLEAR`).
+ pub(super) fn disable_top(&self) {
+ self.bar
+ .write(CPU_INTR_TOP_EN_CLEAR, self.serviced.into_raw().into());
+ }
+
+ /// Enables this tree's serviced subtrees until the returned guard drops.
+ pub(super) fn enable_top_guarded(&self) -> TopEnableGuard<'_> {
+ self.enable_top();
+
+ TopEnableGuard { tree: self }
+ }
+
+ /// 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) {
+ if let Some(loc) = CPU_INTR_LEAF_EN_SET::try_at(leaf.get()) {
+ self.bar.write(loc, vectors.into_raw().into());
+ }
+ }
+
+ /// Disables the vectors set in `vectors` for `leaf` (`LEAF_EN_CLEAR`).
+ pub(super) fn disable_leaf(&self, leaf: LeafIndex, vectors: LeafMask) {
+ if let Some(loc) = CPU_INTR_LEAF_EN_CLEAR::try_at(leaf.get()) {
+ self.bar.write(loc, vectors.into_raw().into());
+ }
+ }
+
+ /// Enables `vectors` for `leaf` until the returned guard drops.
+ pub(super) fn enable_leaf_guarded(
+ &self,
+ leaf: LeafIndex,
+ vectors: LeafMask,
+ ) -> LeafEnableGuard<'_> {
+ self.enable_leaf(leaf, vectors);
+
+ LeafEnableGuard {
+ tree: self,
+ leaf,
+ vectors,
+ }
+ }
+
+ /// Reads the vectors pending in `leaf`.
+ pub(super) fn read_pending(&self, leaf: LeafIndex) -> LeafPending<'_> {
+ let pending = CPU_INTR_LEAF::try_at(leaf.get())
+ .map(|loc| self.bar.read(loc).into_raw())
+ .unwrap_or(0);
+
+ LeafPending {
+ tree: self,
+ leaf,
+ pending: LeafMask::from_raw(pending),
+ }
+ }
+
+ /// Injects a software interrupt for `vector` via the trigger register.
+ ///
+ /// # Errors
+ ///
+ /// `EINVAL` if `vector` lies outside this tree. `EOVERFLOW` if `vector` does not fit in the
+ /// trigger register's vector field.
+ // Only the interrupt self-test injects a software interrupt.
+ #[cfg_attr(not(CONFIG_NOVA_CORE_IRQ_SELFTEST), expect(dead_code))]
+ pub(super) fn trigger(&self, vector: GinVector) -> Result {
+ vector.validate(self.leaves)?;
+ self.bar
+ .write_reg(CPU_INTR_LEAF_TRIGGER::zeroed().try_with_vector(vector.into_raw())?);
+
+ 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 index in 0..self.leaves.into_raw() {
+ if let Some(leaf) = LeafIndex::try_new(index) {
+ self.disable_leaf(leaf, LeafMask::all());
+ }
+ }
+ }
+
+ /// Clears every pending bit in every implemented leaf.
+ ///
+ /// Disables this tree's serviced subtrees at `TOP` across the walk, then enables them,
+ /// whatever their state on entry. The leaves cleared reach subtrees the driver does not
+ /// service, and the `TOP_EN` writes do 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 index in 0..self.leaves.subtree_count() {
+ for leaf in subtree_leaves(index) {
+ let pending = self.read_pending(leaf);
+ if !pending.vectors().is_empty() {
+ pending.clear();
+ }
+ }
+ }
+
+ self.enable_top();
+ }
+}
+
+/// 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> {
+ tree: &'a Tree<'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) {
+ if !vectors.is_empty() {
+ if let Some(loc) = CPU_INTR_LEAF::try_at(self.leaf.get()) {
+ self.tree.bar.write(loc, vectors.into_raw().into());
+ }
+ }
+ }
+}
+
+/// 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> {
+ tree: &'a Tree<'a>,
+ leaf: LeafIndex,
+ vectors: LeafMask,
+}
+
+impl Drop for LeafEnableGuard<'_> {
+ fn drop(&mut self) {
+ self.tree.disable_leaf(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> {
+ tree: &'a Tree<'a>,
+}
+
+impl Drop for TopEnableGuard<'_> {
+ fn drop(&mut self) {
+ self.tree.disable_top();
+ }
+}
--
2.55.0
^ permalink raw reply [flat|nested] 18+ messages in thread* [PATCH v2 07/15] gpu: nova-core: add an interrupt delivery self-test
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (6 preceding siblings ...)
2026-08-29 1:33 ` [PATCH v2 06/15] gpu: nova-core: add the GIN interrupt tree and allocate its vectors John Hubbard
@ 2026-08-29 1:33 ` John Hubbard
2026-08-29 1:33 ` [PATCH v2 08/15] gpu: nova-core: dispatch GSP events instead of discarding them John Hubbard
` (7 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:33 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.
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 | 8 +
drivers/gpu/nova-core/irq.rs | 2 +
drivers/gpu/nova-core/irq/doorbell_test.rs | 294 ++++++++++++++++++++
drivers/gpu/nova-core/irq/interrupt_tree.rs | 73 +++--
drivers/gpu/nova-core/nova_core.rs | 2 +-
6 files changed, 367 insertions(+), 27 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 9e4232645a7e..589b4b210a22 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -347,6 +347,14 @@ pub(crate) fn new(
.inspect_err(|_| dev_err!(dev, "GFW boot did not complete\n"))?;
},
+ // Validate the MSI interrupt path before booting GSP, when the self-test is
+ // enabled. This runs on a quiesced interrupt tree with no GSP state present, so it
+ // never observes or clears GSP or PRIV_RING interrupts.
+ _: {
+ #[cfg(CONFIG_NOVA_CORE_IRQ_SELFTEST)]
+ crate::irq::doorbell_test::run_selftest(pdev, bar, spec.chipset)?;
+ },
+
// Initialize this early because `gsp_resources` depends on it.
sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?,
diff --git a/drivers/gpu/nova-core/irq.rs b/drivers/gpu/nova-core/irq.rs
index c6bf1dbacabe..37dea5abf833 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;
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..3fd8b26e135e
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/doorbell_test.rs
@@ -0,0 +1,294 @@
+// 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, //
+};
+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 allocation, 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
+///
+/// `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,
+) -> Result {
+ // The allocated interrupt type decides how the handler rearms delivery, so the vectors are
+ // allocated before the tree is built.
+ let vectors = super::alloc_vectors(pdev, DOORBELL_SUBTREE.into())?;
+ let request = vectors.request_for(DOORBELL_SUBTREE)?;
+ let irq_type = vectors.irq_type();
+ let tree = Tree::new(bar, chipset, irq_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(),
+ irq_type,
+ );
+
+ // No delivery may reach the CPU before a handler is registered. `drain` enables the top level
+ // as the last step of its cycle, so disable it again afterward.
+ tree.disable_leaf(doorbell, doorbell_mask);
+ tree.drain();
+ tree.disable_top();
+
+ // 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 {
+ reg,
+ _leaf_guard: tree.enable_leaf_guarded(doorbell, doorbell_mask),
+ _top_guard: tree.enable_top_guarded(),
+ };
+ 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 = 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 523b26d55137..1d26ca408dc3 100644
--- a/drivers/gpu/nova-core/irq/interrupt_tree.rs
+++ b/drivers/gpu/nova-core/irq/interrupt_tree.rs
@@ -240,6 +240,30 @@ pub(super) fn validate(self, leaves: LeafCount) -> Result {
}
}
+/// 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) {
+ if let Some(loc) = CPU_INTR_LEAF_EN_CLEAR::try_at(leaf.get()) {
+ bar.write(loc, vectors.into_raw().into());
+ }
+}
+
+/// Clears the `TOP` enables of every subtree in `serviced` (`TOP_EN_CLEAR`).
+fn clear_top_enables(bar: Bar0<'_>, serviced: SubtreeSet) {
+ bar.write(CPU_INTR_TOP_EN_CLEAR, serviced.into_raw().into());
+}
+
+/// 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() {
+ if let Some(loc) = CPU_INTR_LEAF::try_at(leaf.get()) {
+ bar.write(loc, vectors.into_raw().into());
+ }
+ }
+}
+
/// Returns the leaves that subtree `index` covers.
///
/// An index beyond the leaf register arrays yields nothing rather than panicking.
@@ -251,6 +275,10 @@ fn subtree_leaves(index: u32) -> impl Iterator<Item = LeafIndex> {
}
/// The GIN CPU interrupt tree for a single PCIe function.
+///
+/// Copying one is copying a borrowed BAR pointer and three small values, which an interrupt
+/// handler needs so that it owns a tree of its own.
+#[derive(Clone, Copy)]
pub(super) struct Tree<'a> {
/// Borrowed BAR0, through which every tree register is reached.
bar: Bar0<'a>,
@@ -287,11 +315,6 @@ pub(super) fn new(
}
}
- /// Returns the subtrees this tree services.
- pub(super) fn serviced(&self) -> SubtreeSet {
- self.serviced
- }
-
/// Rearms PCI interrupt delivery to the CPU after servicing `subtree`, the one subtree the
/// calling handler serves.
///
@@ -310,15 +333,17 @@ pub(super) fn enable_top(&self) {
/// Disables this tree's serviced subtrees (`TOP_EN_CLEAR`).
pub(super) fn disable_top(&self) {
- self.bar
- .write(CPU_INTR_TOP_EN_CLEAR, self.serviced.into_raw().into());
+ 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<'_> {
+ pub(super) fn enable_top_guarded(&self) -> TopEnableGuard<'a> {
self.enable_top();
- TopEnableGuard { tree: self }
+ TopEnableGuard {
+ bar: self.bar,
+ serviced: self.serviced,
+ }
}
/// Enables the vectors set in `vectors` for `leaf` (`LEAF_EN_SET`).
@@ -332,9 +357,7 @@ pub(super) fn enable_leaf(&self, leaf: LeafIndex, vectors: LeafMask) {
/// Disables the vectors set in `vectors` for `leaf` (`LEAF_EN_CLEAR`).
pub(super) fn disable_leaf(&self, leaf: LeafIndex, vectors: LeafMask) {
- if let Some(loc) = CPU_INTR_LEAF_EN_CLEAR::try_at(leaf.get()) {
- self.bar.write(loc, vectors.into_raw().into());
- }
+ clear_leaf_enables(self.bar, leaf, vectors);
}
/// Enables `vectors` for `leaf` until the returned guard drops.
@@ -342,24 +365,24 @@ pub(super) fn enable_leaf_guarded(
&self,
leaf: LeafIndex,
vectors: LeafMask,
- ) -> LeafEnableGuard<'_> {
+ ) -> LeafEnableGuard<'a> {
self.enable_leaf(leaf, vectors);
LeafEnableGuard {
- tree: self,
+ bar: self.bar,
leaf,
vectors,
}
}
/// Reads the vectors pending in `leaf`.
- pub(super) fn read_pending(&self, leaf: LeafIndex) -> LeafPending<'_> {
+ pub(super) fn read_pending(&self, leaf: LeafIndex) -> LeafPending<'a> {
let pending = CPU_INTR_LEAF::try_at(leaf.get())
.map(|loc| self.bar.read(loc).into_raw())
.unwrap_or(0);
LeafPending {
- tree: self,
+ bar: self.bar,
leaf,
pending: LeafMask::from_raw(pending),
}
@@ -389,6 +412,7 @@ pub(super) fn trigger(&self, vector: GinVector) -> Result {
///
/// This clears enables outside the subtrees nova-core services, so it is a probe-time
/// operation only.
+ #[expect(dead_code)]
pub(super) fn disable_all_leaves(&self) {
for index in 0..self.leaves.into_raw() {
if let Some(leaf) = LeafIndex::try_new(index) {
@@ -427,7 +451,7 @@ pub(super) fn drain(&self) {
/// 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> {
- tree: &'a Tree<'a>,
+ bar: Bar0<'a>,
leaf: LeafIndex,
pending: LeafMask,
}
@@ -449,11 +473,7 @@ pub(super) fn clear(&self) {
/// 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) {
- if !vectors.is_empty() {
- if let Some(loc) = CPU_INTR_LEAF::try_at(self.leaf.get()) {
- self.tree.bar.write(loc, vectors.into_raw().into());
- }
- }
+ clear_leaf_pending(self.bar, self.leaf, vectors);
}
}
@@ -462,24 +482,25 @@ pub(super) fn clear_vectors(&self, vectors: LeafMask) {
/// 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> {
- tree: &'a Tree<'a>,
+ bar: Bar0<'a>,
leaf: LeafIndex,
vectors: LeafMask,
}
impl Drop for LeafEnableGuard<'_> {
fn drop(&mut self) {
- self.tree.disable_leaf(self.leaf, self.vectors);
+ 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> {
- tree: &'a Tree<'a>,
+ bar: Bar0<'a>,
+ serviced: SubtreeSet,
}
impl Drop for TopEnableGuard<'_> {
fn drop(&mut self) {
- self.tree.disable_top();
+ clear_top_enables(self.bar, self.serviced);
}
}
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 [flat|nested] 18+ messages in thread* [PATCH v2 08/15] gpu: nova-core: dispatch GSP events instead of discarding them
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (7 preceding siblings ...)
2026-08-29 1:33 ` [PATCH v2 07/15] gpu: nova-core: add an interrupt delivery self-test John Hubbard
@ 2026-08-29 1:33 ` John Hubbard
2026-08-29 1:33 ` [PATCH v2 09/15] gpu: nova-core: match GSP RPC replies by sequence, not just function John Hubbard
` (6 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:33 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.
Route every non-reply message to a dispatcher, which logs the error
records and leaves the in-flight command waiting for its reply. The
dispatch runs on the existing command and wait loops, so events are
handled during normal operation before any interrupt exists. Event
payloads, such as XID numbers and log contents, are not decoded.
Assisted-by: Cursor:claude-opus-5
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
drivers/gpu/nova-core/gsp/cmdq.rs | 64 ++++++++++++++++++++++++-------
1 file changed, 51 insertions(+), 13 deletions(-)
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index f0f28b6ded7a..0df52df1da89 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -547,11 +547,11 @@ fn notify_gsp(bar: Bar0<'_>) {
/// Sends `command` to the GSP and waits for the reply.
///
- /// Messages with non-matching function codes are silently consumed until the expected reply
- /// arrives.
+ /// A message read while waiting that is not the reply goes to
+ /// [`CmdqInner::dispatch_event`].
///
- /// The queue is locked for the entire send+receive cycle to ensure that no other command can
- /// be interleaved.
+ /// The queue is locked for the entire send+receive cycle, so no other command can be
+ /// interleaved.
///
/// # Errors
///
@@ -805,8 +805,10 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
/// Receive a message from the GSP.
///
- /// The expected message type is specified using the `M` generic parameter. If the pending
- /// message has a different function code, `ERANGE` is returned and the message is consumed.
+ /// The expected message type is specified using the `M` generic parameter. A message whose
+ /// function code matches is decoded and returned. Any other message, whether its function code
+ /// is a different one or is unrecognized, goes to [`Self::dispatch_event`] and `ERANGE` is
+ /// returned.
///
/// The read pointer is always advanced past the message, regardless of whether it matched.
///
@@ -815,8 +817,7 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
/// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available.
/// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the
/// message queue.
- /// - `EINVAL` if the function code of the message was not recognized.
- /// - `ERANGE` if the message had a recognized but non-matching function code.
+ /// - `ERANGE` if the message was not the awaited reply.
///
/// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
@@ -825,11 +826,13 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
Error: From<M::InitError>,
{
let message = self.wait_for_msg(timeout)?;
- let function = message.header.function().map_err(|_| EINVAL)?;
+ let function = message.header.function();
+ let seq = message.header.sequence();
+ let matched = matches!(function, Ok(f) if f == M::FUNCTION);
- // Extract the message. Store the result as we want to advance the read pointer even in
- // case of failure.
- let result = if function == M::FUNCTION {
+ // Bind the result rather than returning early. The read pointer must advance past this
+ // message on every path.
+ let result = if matched {
let (cmd, contents_1) = M::Message::from_bytes_prefix(message.contents.0).ok_or(EIO)?;
let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]);
@@ -840,7 +843,7 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
dev_warn!(
&self.dev,
"GSP message {:?} has unprocessed data\n",
- function
+ M::FUNCTION
);
}
})
@@ -853,6 +856,41 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
message.header.length().div_ceil(GSP_PAGE_SIZE),
)?);
+ if !matched {
+ self.dispatch_event(function, seq);
+ }
+
result
}
+
+ /// Routes a GSP message that is not the reply a caller is waiting for.
+ ///
+ /// GSP-reported errors are logged at error level and unrecognized function codes at warning
+ /// level. Every other known function code is consumed without a log line, because the RPC
+ /// receive trace in [`Self::wait_for_msg`] already records its arrival.
+ fn dispatch_event(&self, function: Result<MsgFunction, u32>, seq: u32) {
+ match function {
+ Ok(MsgFunction::OsErrorLog) => {
+ dev_err!(&self.dev, "GSP reported an OS error (seq {})\n", seq);
+ }
+ Ok(MsgFunction::RcTriggered) => {
+ dev_err!(
+ &self.dev,
+ "GSP triggered robust-channel recovery (seq {})\n",
+ seq
+ );
+ }
+ // GSP logs, libos prints, NoCat assertion records, and the other known event codes.
+ // None of them requires action.
+ Ok(_) => {}
+ Err(raw) => {
+ dev_warn!(
+ &self.dev,
+ "unknown GSP message function {:#x} (seq {})\n",
+ raw,
+ seq
+ );
+ }
+ }
+ }
}
--
2.55.0
^ permalink raw reply [flat|nested] 18+ messages in thread* [PATCH v2 09/15] gpu: nova-core: match GSP RPC replies by sequence, not just function
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (8 preceding siblings ...)
2026-08-29 1:33 ` [PATCH v2 08/15] gpu: nova-core: dispatch GSP events instead of discarding them John Hubbard
@ 2026-08-29 1:33 ` John Hubbard
2026-08-29 1:33 ` [PATCH v2 10/15] gpu: nova-core: recover the GSP receive path from corrupt framing John Hubbard
` (5 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:33 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 replies to a command by echoing that command's function code and
its RPC sequence number.
nova-core matched replies on the function alone and never set the
sequence, so a reply for a command that had already timed out could
satisfy a later command using the same function.
Give the RPC sequence its own counter, separate from the per-element
transport sequence, set it on every command, and require both the
function and the sequence to match before accepting a reply. A message
with the expected function but a stale sequence is logged and dropped,
not mistaken for the reply or dispatched as an event. A caller awaiting
an unsolicited event still matches on the function alone.
Assisted-by: Cursor:claude-opus-5
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
drivers/gpu/nova-core/gsp/cmdq.rs | 89 ++++++++++++++++++++-----------
drivers/gpu/nova-core/gsp/fw.rs | 13 +++--
2 files changed, 67 insertions(+), 35 deletions(-)
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index 0df52df1da89..3224079abf7e 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -521,7 +521,8 @@ pub(crate) fn new(dev: &device::Device<device::Bound>) -> impl PinInit<Self, Err
inner <- new_mutex!(CmdqInner {
dev: dev.into(),
gsp_mem,
- seq: 0,
+ elem_seq: 0,
+ rpc_seq: 0,
}),
}))
})
@@ -569,10 +570,10 @@ pub(crate) fn send_command<M>(&self, bar: Bar0<'_>, command: M) -> Result<M::Rep
Error: From<<M::Reply as MessageFromGsp>::InitError>,
{
let mut inner = self.inner.lock();
- inner.send_command(bar, command)?;
+ let expected_seq = inner.send_command(bar, command)?;
loop {
- match inner.receive_msg::<M::Reply>(Self::RECEIVE_TIMEOUT) {
+ match inner.receive_msg::<M::Reply>(Self::RECEIVE_TIMEOUT, Some(expected_seq)) {
Ok(reply) => break Ok(reply),
Err(ERANGE) => continue,
Err(e) => break Err(e),
@@ -594,18 +595,19 @@ pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul
M: CommandToGsp<Reply = NoReply>,
Error: From<M::InitError>,
{
- self.inner.lock().send_command(bar, command)
+ self.inner.lock().send_command(bar, command).map(|_| ())
}
/// Receive a message from the GSP.
///
- /// See [`CmdqInner::receive_msg`] for details.
+ /// Matches on the function code alone, for a caller awaiting an unsolicited GSP event rather
+ /// than a reply to a command. See [`CmdqInner::receive_msg`].
pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
where
// This allows all error types, including `Infallible`, to be used for `M::InitError`.
Error: From<M::InitError>,
{
- self.inner.lock().receive_msg(timeout)
+ self.inner.lock().receive_msg(timeout, None)
}
}
@@ -613,8 +615,13 @@ pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
struct CmdqInner {
/// Device this command queue belongs to.
dev: ARef<device::Device>,
- /// Current command sequence number.
- seq: u32,
+ /// Next transport sequence number for a queue element (the `seqNum` field). Advances once per
+ /// queue element, including each continuation record.
+ elem_seq: u32,
+ /// Next RPC sequence number. The GSP echoes it in a command's reply, which lets
+ /// [`CmdqInner::receive_msg`] match that reply to the awaiting command. Advances once per
+ /// logical command.
+ rpc_seq: u32,
/// Memory area shared with the GSP for communicating commands and messages.
gsp_mem: DmaGspMem,
}
@@ -633,7 +640,7 @@ impl CmdqInner {
/// written to by its [`CommandToGsp::init_variable_payload`] method.
///
/// Error codes returned by the command initializers are propagated as-is.
- fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
+ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M, rpc_seq: u32) -> Result
where
M: CommandToGsp,
// This allows all error types, including `Infallible`, to be used for `M::InitError`.
@@ -650,7 +657,7 @@ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
let (cmd, payload_1) = M::Command::from_bytes_mut_prefix(dst.contents.0).ok_or(EIO)?;
// Fill the header and command in-place.
- let msg_element = GspMsgElement::init(self.seq, size_in_bytes, M::FUNCTION);
+ let msg_element = GspMsgElement::init(self.elem_seq, rpc_seq, size_in_bytes, M::FUNCTION);
// SAFETY: `msg_header` and `cmd` are valid references, and not touched if the initializer
// fails.
unsafe {
@@ -678,23 +685,25 @@ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
dev_dbg!(
&self.dev,
"GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n",
- self.seq,
+ rpc_seq,
M::FUNCTION,
dst.header.length(),
);
// All set - update the write pointer and inform the GSP of the new command.
let elem_count = dst.header.element_count();
- self.seq += 1;
+ self.elem_seq = self.elem_seq.wrapping_add(1);
self.gsp_mem.advance_cpu_write_ptr(elem_count);
Cmdq::notify_gsp(bar);
Ok(())
}
- /// Sends `command` to the GSP.
+ /// Sends `command` to the GSP and returns the RPC sequence number assigned to it.
///
- /// The command may be split into multiple messages if it is large.
+ /// The command may be split into multiple messages if it is large. The GSP echoes the
+ /// sequence number in the reply, so a caller passes it to [`Self::receive_msg`] to match the
+ /// reply to this command.
///
/// # Errors
///
@@ -703,24 +712,26 @@ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
/// written to by its [`CommandToGsp::init_variable_payload`] method.
///
/// Error codes returned by the command initializers are propagated as-is.
- fn send_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result
+ fn send_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result<u32>
where
M: CommandToGsp,
Error: From<M::InitError>,
{
+ let rpc_seq = self.rpc_seq;
+ self.rpc_seq = self.rpc_seq.wrapping_add(1);
+
match SplitState::new(command)? {
- SplitState::Single(command) => self.send_single_command(bar, command),
+ SplitState::Single(command) => self.send_single_command(bar, command, rpc_seq)?,
SplitState::Split(command, mut continuations) => {
- self.send_single_command(bar, command)?;
+ self.send_single_command(bar, command, rpc_seq)?;
while let Some(continuation) = continuations.next() {
- // Turbofish needed because the compiler cannot infer M here.
- self.send_single_command::<ContinuationRecord<'_>>(bar, continuation)?;
+ self.send_single_command::<ContinuationRecord<'_>>(bar, continuation, rpc_seq)?;
}
-
- Ok(())
}
}
+
+ Ok(rpc_seq)
}
/// Wait for a message to become available on the message queue.
@@ -805,10 +816,14 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
/// Receive a message from the GSP.
///
- /// The expected message type is specified using the `M` generic parameter. A message whose
- /// function code matches is decoded and returned. Any other message, whether its function code
- /// is a different one or is unrecognized, goes to [`Self::dispatch_event`] and `ERANGE` is
- /// returned.
+ /// The expected message type is given by the `M` generic parameter. With `expected_seq` set,
+ /// the message must also carry that RPC sequence number to count as the awaited reply. With
+ /// `None`, the function code alone decides the match.
+ ///
+ /// A matching message is decoded and returned. A message carrying the expected function code
+ /// with a different sequence is a stale reply to a command that already timed out, and is
+ /// logged and dropped. Any other message goes to [`Self::dispatch_event`]. Both non-matching
+ /// cases return `ERANGE`.
///
/// The read pointer is always advanced past the message, regardless of whether it matched.
///
@@ -820,7 +835,11 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
/// - `ERANGE` if the message was not the awaited reply.
///
/// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
- fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
+ fn receive_msg<M: MessageFromGsp>(
+ &mut self,
+ timeout: Delta,
+ expected_seq: Option<u32>,
+ ) -> Result<M>
where
// This allows all error types, including `Infallible`, to be used for `M::InitError`.
Error: From<M::InitError>,
@@ -828,10 +847,10 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
let message = self.wait_for_msg(timeout)?;
let function = message.header.function();
let seq = message.header.sequence();
- let matched = matches!(function, Ok(f) if f == M::FUNCTION);
+ let func_matches = matches!(function, Ok(f) if f == M::FUNCTION);
+ let matched = func_matches && expected_seq.is_none_or(|expected| seq == expected);
- // Bind the result rather than returning early. The read pointer must advance past this
- // message on every path.
+ // Every path must advance the read pointer past this message.
let result = if matched {
let (cmd, contents_1) = M::Message::from_bytes_prefix(message.contents.0).ok_or(EIO)?;
let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]);
@@ -857,7 +876,17 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
)?);
if !matched {
- self.dispatch_event(function, seq);
+ if func_matches {
+ dev_warn!(
+ &self.dev,
+ "GSP RPC: dropping stale {:?} reply (seq {}, awaiting {:?})\n",
+ M::FUNCTION,
+ seq,
+ expected_seq,
+ );
+ } else {
+ self.dispatch_event(function, seq);
+ }
}
result
diff --git a/drivers/gpu/nova-core/gsp/fw.rs b/drivers/gpu/nova-core/gsp/fw.rs
index 05f54fee6186..0b01c81ec092 100644
--- a/drivers/gpu/nova-core/gsp/fw.rs
+++ b/drivers/gpu/nova-core/gsp/fw.rs
@@ -782,13 +782,14 @@ fn new() -> Self {
}
impl bindings::rpc_message_header_v {
- fn init(cmd_size: usize, function: MsgFunction) -> impl Init<Self, Error> {
+ fn init(sequence: u32, cmd_size: usize, function: MsgFunction) -> impl Init<Self, Error> {
type RpcMessageHeader = bindings::rpc_message_header_v;
try_init!(RpcMessageHeader {
header_version: MsgHeaderVersion::new().into(),
signature: bindings::NV_VGPU_MSG_SIGNATURE_VALID,
function: function.into(),
+ sequence,
length: size_of::<Self>()
.checked_add(cmd_size)
.ok_or(EOVERFLOW)
@@ -813,25 +814,27 @@ impl GspMsgElement {
///
/// # Arguments
///
- /// * `sequence` - Sequence number of the message.
+ /// * `elem_seq` - Transport sequence number of the queue element (`seqNum`).
+ /// * `rpc_seq` - RPC sequence number, echoed by the GSP in the reply.
/// * `cmd_size` - Size of the command (not including the message element), in bytes.
/// * `function` - Function of the message.
pub(crate) fn init(
- sequence: u32,
+ elem_seq: u32,
+ rpc_seq: u32,
cmd_size: usize,
function: MsgFunction,
) -> impl Init<Self, Error> {
type RpcMessageHeader = bindings::rpc_message_header_v;
type InnerGspMsgElement = bindings::GSP_MSG_QUEUE_ELEMENT;
let init_inner = try_init!(InnerGspMsgElement {
- seqNum: sequence,
+ seqNum: elem_seq,
elemCount: size_of::<Self>()
.checked_add(cmd_size)
.ok_or(EOVERFLOW)?
.div_ceil(GSP_PAGE_SIZE)
.try_into()
.map_err(|_| EOVERFLOW)?,
- rpc <- RpcMessageHeader::init(cmd_size, function),
+ rpc <- RpcMessageHeader::init(rpc_seq, cmd_size, function),
..Zeroable::init_zeroed()
});
--
2.55.0
^ permalink raw reply [flat|nested] 18+ messages in thread* [PATCH v2 10/15] gpu: nova-core: recover the GSP receive path from corrupt framing
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (9 preceding siblings ...)
2026-08-29 1:33 ` [PATCH v2 09/15] gpu: nova-core: match GSP RPC replies by sequence, not just function John Hubbard
@ 2026-08-29 1:33 ` John Hubbard
2026-08-29 1:33 ` [PATCH v2 11/15] gpu: nova-core: bound a GSP wait by a single deadline John Hubbard
` (4 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:33 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, 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 | 63 ++++++++++++++++++++-----------
1 file changed, 41 insertions(+), 22 deletions(-)
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index 3224079abf7e..fc4c229b8b9a 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -3,6 +3,7 @@
mod continuation;
use core::{
+ cell::Cell,
mem,
sync::atomic::{
fence,
@@ -523,6 +524,7 @@ pub(crate) fn new(dev: &device::Device<device::Bound>) -> impl PinInit<Self, Err
gsp_mem,
elem_seq: 0,
rpc_seq: 0,
+ poisoned: Cell::new(false),
}),
}))
})
@@ -622,6 +624,12 @@ struct CmdqInner {
/// [`CmdqInner::receive_msg`] match that reply to the awaiting command. Advances once per
/// logical command.
rpc_seq: u32,
+ /// Set once a message with corrupt framing or a bad checksum is seen. Such a message has an
+ /// untrusted length, so the queue cannot be advanced past it, and every later receive fails
+ /// until the queue is torn down and reset.
+ ///
+ /// A [`Cell`], so the shared-borrow read path [`Self::wait_for_msg`] can set it.
+ poisoned: Cell<bool>,
/// Memory area shared with the GSP for communicating commands and messages.
gsp_mem: DmaGspMem,
}
@@ -748,11 +756,13 @@ fn send_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result<u32>
/// # Errors
///
/// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available.
- /// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the
- /// message queue.
- ///
- /// Error codes returned by the message constructor are propagated as-is.
+ /// - `EIO` if the framing or the checksum is invalid, or the queue was already poisoned by an
+ /// earlier such failure. Either failure poisons the queue, so recovery requires a reset.
fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
+ if self.poisoned.get() {
+ return Err(EIO);
+ }
+
// Wait for a message to arrive from the GSP.
let (slice_1, slice_2) = read_poll_timeout(
|| Ok(self.gsp_mem.driver_read_area()),
@@ -763,7 +773,10 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
.map(|(slice_1, slice_2)| (slice_1.as_flattened(), slice_2.as_flattened()))?;
// Extract the `GspMsgElement`.
- let (header, slice_1) = GspMsgElement::from_bytes_prefix(slice_1).ok_or(EIO)?;
+ let Some((header, slice_1)) = GspMsgElement::from_bytes_prefix(slice_1) else {
+ self.poisoned.set(true);
+ return Err(EIO);
+ };
dev_dbg!(
&self.dev,
@@ -777,6 +790,7 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
// Check that the driver read area is large enough for the message.
if slice_1.len() + slice_2.len() < payload_length {
+ self.poisoned.set(true);
return Err(EIO);
}
@@ -805,6 +819,7 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
"GSP RPC: receive: Call {} - bad checksum\n",
header.sequence()
);
+ self.poisoned.set(true);
return Err(EIO);
}
@@ -830,8 +845,8 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
/// # Errors
///
/// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available.
- /// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the
- /// message queue.
+ /// - `EIO` if the queue is poisoned or the message fails framing or checksum validation (see
+ /// [`Self::wait_for_msg`]), or if the matched message is too short for `M::Message`.
/// - `ERANGE` if the message was not the awaited reply.
///
/// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
@@ -850,22 +865,26 @@ fn receive_msg<M: MessageFromGsp>(
let func_matches = matches!(function, Ok(f) if f == M::FUNCTION);
let matched = func_matches && expected_seq.is_none_or(|expected| seq == expected);
- // Every path must advance the read pointer past this message.
+ // Every path must advance the read pointer past this message, including a failed decode.
let result = if matched {
- let (cmd, contents_1) = M::Message::from_bytes_prefix(message.contents.0).ok_or(EIO)?;
- let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]);
-
- M::read(cmd, &mut sbuffer)
- .map_err(|e| e.into())
- .inspect(|_| {
- if !sbuffer.is_empty() {
- dev_warn!(
- &self.dev,
- "GSP message {:?} has unprocessed data\n",
- M::FUNCTION
- );
- }
- })
+ match M::Message::from_bytes_prefix(message.contents.0) {
+ Some((cmd, contents_1)) => {
+ let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]);
+
+ M::read(cmd, &mut sbuffer)
+ .map_err(|e| e.into())
+ .inspect(|_| {
+ if !sbuffer.is_empty() {
+ dev_warn!(
+ &self.dev,
+ "GSP message {:?} has unprocessed data\n",
+ M::FUNCTION
+ );
+ }
+ })
+ }
+ None => Err(EIO),
+ }
} else {
Err(ERANGE)
};
--
2.55.0
^ permalink raw reply [flat|nested] 18+ messages in thread* [PATCH v2 11/15] gpu: nova-core: bound a GSP wait by a single deadline
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (10 preceding siblings ...)
2026-08-29 1:33 ` [PATCH v2 10/15] gpu: nova-core: recover the GSP receive path from corrupt framing John Hubbard
@ 2026-08-29 1:33 ` John Hubbard
2026-08-29 1:33 ` [PATCH v2 12/15] gpu: nova-core: drive GSP events with the SWGEN0 interrupt John Hubbard
` (3 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:33 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 dispatches whatever else arrives
first and reads again.
Each of those reads started a fresh five-second timeout, so a steady
stream of events extended the wait without bound.
Compute one absolute deadline when the wait begins and pass the time
remaining to each read, so the whole wait is bounded however many events
arrive first.
GSP boot waits for two unsolicited events. Move that loop into a helper
so both take the same bound.
Assisted-by: Cursor:claude-opus-5
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
drivers/gpu/nova-core/gsp/cmdq.rs | 52 ++++++++++++++++++++++----
drivers/gpu/nova-core/gsp/commands.rs | 8 +---
drivers/gpu/nova-core/gsp/sequencer.rs | 8 +---
3 files changed, 46 insertions(+), 22 deletions(-)
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index fc4c229b8b9a..76d51155c49f 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -30,7 +30,11 @@
aref::ARef,
Mutex, //
},
- time::Delta,
+ time::{
+ Delta,
+ Instant,
+ Monotonic, //
+ },
transmute::{
AsBytes,
FromBytes, //
@@ -558,8 +562,9 @@ fn notify_gsp(bar: Bar0<'_>) {
///
/// # Errors
///
- /// - `ETIMEDOUT` if space does not become available to send the command, or if the reply is
- /// not received within the timeout.
+ /// - `ETIMEDOUT` if space does not become available to send the command, or if the reply does
+ /// not arrive within [`Self::RECEIVE_TIMEOUT`] of the send, however many events are
+ /// dispatched while waiting.
/// - `EIO` if the variable payload requested by the command has not been entirely
/// written to by its [`CommandToGsp::init_variable_payload`] method.
///
@@ -574,8 +579,13 @@ pub(crate) fn send_command<M>(&self, bar: Bar0<'_>, command: M) -> Result<M::Rep
let mut inner = self.inner.lock();
let expected_seq = inner.send_command(bar, command)?;
+ let deadline = Instant::<Monotonic>::now() + Self::RECEIVE_TIMEOUT;
loop {
- match inner.receive_msg::<M::Reply>(Self::RECEIVE_TIMEOUT, Some(expected_seq)) {
+ let remaining = deadline - Instant::<Monotonic>::now();
+ if remaining.is_negative() {
+ break Err(ETIMEDOUT);
+ }
+ match inner.receive_msg::<M::Reply>(remaining, Some(expected_seq)) {
Ok(reply) => break Ok(reply),
Err(ERANGE) => continue,
Err(e) => break Err(e),
@@ -600,17 +610,43 @@ pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul
self.inner.lock().send_command(bar, command).map(|_| ())
}
- /// Receive a message from the GSP.
+ /// Receive a message from the GSP, matching on the function code alone.
///
- /// Matches on the function code alone, for a caller awaiting an unsolicited GSP event rather
- /// than a reply to a command. See [`CmdqInner::receive_msg`].
- pub(crate) fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
+ /// Returns `ERANGE` if the message that arrives is not of type `M`. See
+ /// [`CmdqInner::receive_msg`].
+ fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M>
where
// This allows all error types, including `Infallible`, to be used for `M::InitError`.
Error: From<M::InitError>,
{
self.inner.lock().receive_msg(timeout, None)
}
+
+ /// Waits for an unsolicited GSP event of type `M`, dispatching any other event that arrives
+ /// first.
+ ///
+ /// # Errors
+ ///
+ /// - `ETIMEDOUT` if the event does not arrive within [`Self::RECEIVE_TIMEOUT`] of the call,
+ /// however many other events are dispatched while waiting.
+ pub(crate) fn await_msg<M: MessageFromGsp>(&self) -> Result<M>
+ where
+ // This allows all error types, including `Infallible`, to be used for `M::InitError`.
+ Error: From<M::InitError>,
+ {
+ let deadline = Instant::<Monotonic>::now() + Self::RECEIVE_TIMEOUT;
+ loop {
+ let remaining = deadline - Instant::<Monotonic>::now();
+ if remaining.is_negative() {
+ break Err(ETIMEDOUT);
+ }
+ match self.receive_msg::<M>(remaining) {
+ Ok(msg) => break Ok(msg),
+ Err(ERANGE) => continue,
+ Err(e) => break Err(e),
+ }
+ }
+ }
}
/// Inner mutex protected state of [`Cmdq`].
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 [flat|nested] 18+ messages in thread* [PATCH v2 12/15] gpu: nova-core: drive GSP events with the SWGEN0 interrupt
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (11 preceding siblings ...)
2026-08-29 1:33 ` [PATCH v2 11/15] gpu: nova-core: bound a GSP wait by a single deadline John Hubbard
@ 2026-08-29 1:33 ` John Hubbard
2026-08-29 1:33 ` [PATCH v2 13/15] gpu: nova-core: retrigger the GSP falcon and clear every latched cause John Hubbard
` (2 subsequent siblings)
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:33 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. GSP boot polls for its own
notifications, which leaves the latch set and pending bits in the tree.
nova-core drained the queue only while polling for a command reply, so
an event sat unread until the next command was sent.
Service the queue from a threaded handler on the GSP notification
vector. The top half runs in hard interrupt context and touches only
registers: it clears the GIN leaf, takes the falcon's SWGEN0 latch and
rearms PCI delivery. Draining the queue takes the command-queue mutex,
which can sleep, so the top half wakes the IRQ thread to do it.
Quiesce the tree, clear the latch and rearm PCI delivery before
registering the handler, so none of that boot state reaches it.
Pre-Hopper MSI rearms through a configuration-space write that the tree
drain does not perform, and an interrupt delivered before probe leaves
delivery un-armed.
Move the vector allocation out of the self-test and into probe, because
the vectors are allocated once for the whole PCI device rather than per
handler. The self-test and the GSP handler each take the vector for the
subtree they service.
Assisted-by: Cursor:claude-opus-5
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
drivers/gpu/nova-core/driver.rs | 55 ++++-
drivers/gpu/nova-core/falcon/gsp.rs | 35 +++-
drivers/gpu/nova-core/gpu.rs | 22 +-
drivers/gpu/nova-core/gsp.rs | 17 +-
drivers/gpu/nova-core/gsp/cmdq.rs | 42 ++++
drivers/gpu/nova-core/irq.rs | 1 +
drivers/gpu/nova-core/irq/doorbell_test.rs | 34 ++--
drivers/gpu/nova-core/irq/gsp.rs | 215 ++++++++++++++++++++
drivers/gpu/nova-core/irq/interrupt_tree.rs | 1 -
drivers/gpu/nova-core/nova_core.rs | 1 -
drivers/gpu/nova-core/regs.rs | 4 +
11 files changed, 394 insertions(+), 33 deletions(-)
create mode 100644 drivers/gpu/nova-core/irq/gsp.rs
diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver.rs
index 5738d4ac521b..3b713d621bd1 100644
--- a/drivers/gpu/nova-core/driver.rs
+++ b/drivers/gpu/nova-core/driver.rs
@@ -18,18 +18,36 @@
types::ForLt,
};
-use crate::gpu::Gpu;
+use crate::{
+ gpu::Gpu,
+ irq::{
+ gsp::GspIrq,
+ SubtreeVectors, //
+ },
+};
/// Counter for generating unique auxiliary device IDs.
static AUXILIARY_ID_COUNTER: Atomic<u32> = Atomic::new(0);
#[pin_data]
pub(crate) struct NovaCore<'bound> {
+ /// GSP event interrupt registration.
+ ///
+ /// Declared first so it is dropped first: `free_irq` runs (waiting out any in-flight handler)
+ /// before the GSP is unloaded (`gpu`) or the BAR mapping is released (`bar`).
+ #[pin]
+ _gsp_irq: GspIrq<'bound>,
#[pin]
pub(crate) gpu: Gpu<'bound>,
bar: pci::Bar<'bound, BAR0_SIZE>,
#[allow(clippy::type_complexity)]
_reg: auxiliary::Registration<'bound, ForLt!(())>,
+ /// Self-referential borrow of `vectors`, so this does not have to be repeated in the
+ /// constructor. Will go away with self-referential pin-init.
+ vectors_ref: &'bound SubtreeVectors<'bound>,
+ /// PCI interrupt vector allocation. Dropped last (struct field drop order).
+ #[pin]
+ vectors: SubtreeVectors<'bound>,
}
pub(crate) struct NovaCoreDriver;
@@ -79,13 +97,42 @@ fn probe<'bound>(
pdev.set_master();
Ok(try_pin_init!(NovaCore {
+ 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 all fields that use `vectors_ref` (struct field drop order).
+ vectors_ref: unsafe { &*core::ptr::from_ref(vectors.as_ref().get_ref()) },
bar: pdev.iomap_region_sized::<BAR0_SIZE>(0, c"nova-core/bar0")?,
// TODO: Use `&bar` self-referential pin-init syntax once available.
//
// SAFETY: `bar` is initialized before this expression is evaluated
- // (`try_pin_init!()` initializes fields in declaration order), lives at a pinned
- // stable address, and is dropped after `gpu` (struct field drop order).
- gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) }),
+ // (`try_pin_init!()` initializes fields in the order they appear here), lives at a
+ // pinned stable address, and is dropped after `gpu` (struct field drop order).
+ gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) }, vectors_ref),
+ // Quiesce the interrupt tree before registering the handler below.
+ _: {
+ // SAFETY: as for the `bar` borrow above.
+ let bar = unsafe { &*core::ptr::from_ref(bar) };
+ crate::irq::gsp::quiesce(bar, gpu.chipset(), vectors_ref.irq_type());
+ },
+ // Register the permanent GSP SWGEN0 handler, which enables the interrupt.
+ //
+ // SAFETY: `bar` and `vectors` are initialized and pinned (see above). `_gsp_irq`
+ // is declared before `vectors` in the struct, so it is dropped first, ensuring
+ // `free_irq` runs before the vectors are freed. The registration is stored in
+ // `NovaCore` and never leaked.
+ _gsp_irq <- unsafe {
+ GspIrq::new(
+ pdev,
+ vectors_ref,
+ &*core::ptr::from_ref(bar),
+ gpu.cmdq(),
+ gpu.chipset(),
+ )
+ },
+ // Drain the messages the GSP posted during boot, before relying on the interrupt.
+ _: {
+ gpu.cmdq().drain()?;
+ },
_reg: auxiliary::Registration::new(
pdev.as_ref(),
c"nova-drm",
diff --git a/drivers/gpu/nova-core/falcon/gsp.rs b/drivers/gpu/nova-core/falcon/gsp.rs
index ae32f401aeb0..f9d9e8e0386b 100644
--- a/drivers/gpu/nova-core/falcon/gsp.rs
+++ b/drivers/gpu/nova-core/falcon/gsp.rs
@@ -14,6 +14,7 @@
};
use crate::{
+ driver::Bar0,
falcon::{
Falcon,
FalconEngine,
@@ -36,14 +37,40 @@ impl RegisterBase<PFalcon2Base> for Gsp {
impl FalconEngine for Gsp {}
+impl Gsp {
+ /// Clears the GSP falcon SWGEN0 interrupt latch.
+ ///
+ /// The latch holds until it is cleared, and the GSP drives no new edge into the interrupt
+ /// tree while it is set, so a caller that consumed a notification by any means other than the
+ /// interrupt handler must clear it or no further notification is delivered.
+ pub(crate) fn clear_swgen0_intr(bar: Bar0<'_>) {
+ bar.write(
+ WithBase::of::<Self>(),
+ regs::NV_PFALCON_FALCON_IRQSCLR::zeroed().with_swgen0(true),
+ );
+ }
+
+ /// Reads the GSP falcon interrupt status, clearing the SWGEN0 latch if it was set.
+ ///
+ /// Returns the status as it was read, before the clear. The GSP raises SWGEN0 when it has
+ /// posted messages in the GSP-to-CPU queue. The interrupt tree routes every falcon cause to
+ /// a single vector, so the rest of the status identifies a cause other than a posted message.
+ pub(crate) fn take_swgen0_intr(bar: Bar0<'_>) -> regs::NV_PFALCON_FALCON_IRQSTAT {
+ let status = bar.read(regs::NV_PFALCON_FALCON_IRQSTAT::of::<Self>());
+
+ if status.swgen0() {
+ Self::clear_swgen0_intr(bar);
+ }
+
+ status
+ }
+}
+
impl<'a> Falcon<'a, Gsp> {
/// Clears the SWGEN0 bit in the Falcon's IRQ status clear register to
/// allow GSP to signal CPU for processing new messages in message queue.
pub(crate) fn clear_swgen0_intr(&self) {
- self.bar.write(
- WithBase::of::<Gsp>(),
- regs::NV_PFALCON_FALCON_IRQSCLR::zeroed().with_swgen0(true),
- );
+ Gsp::clear_swgen0_intr(self.bar);
}
/// Checks if GSP reload/resume has completed during the boot process.
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 589b4b210a22..932e39e012f0 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -10,7 +10,8 @@
num::Bounded,
pci,
prelude::*,
- sizes::SizeConstants, //
+ sizes::SizeConstants,
+ sync::Arc, //
};
use crate::{
@@ -25,10 +26,12 @@
fsp::Fsp,
gsp::{
self,
+ cmdq::Cmdq,
commands::GetGspStaticInfoReply,
Gsp,
GspBootContext, //
},
+ irq::SubtreeVectors,
vgpu::VgpuManager, //
};
@@ -323,12 +326,27 @@ fn drop(self: Pin<&mut Self>) {
}
impl<'gpu> Gpu<'gpu> {
+ /// Returns the chipset this GPU was identified as.
+ pub(crate) fn chipset(&self) -> Chipset {
+ self.spec.chipset
+ }
+
+ /// Returns a shared handle to the GSP command queue.
+ pub(crate) fn cmdq(&self) -> Arc<Cmdq> {
+ self.gsp_resources.gsp.cmdq()
+ }
+
pub(crate) fn new(
pdev: &'gpu pci::Device<device::Core<'_>>,
bar: Bar0<'gpu>,
+ vectors: &'gpu SubtreeVectors<'gpu>,
) -> impl PinInit<Self, Error> + 'gpu {
let dev = pdev.as_ref();
+ // `vectors` exists for the interrupt self-test below, which this configuration omits.
+ #[cfg(not(CONFIG_NOVA_CORE_IRQ_SELFTEST))]
+ let _ = vectors;
+
try_pin_init!(Self {
spec: Spec::new(dev, bar).inspect(|spec| {
dev_info!(dev,"NVIDIA ({})\n", spec);
@@ -352,7 +370,7 @@ pub(crate) fn new(
// never observes or clears GSP or PRIV_RING interrupts.
_: {
#[cfg(CONFIG_NOVA_CORE_IRQ_SELFTEST)]
- crate::irq::doorbell_test::run_selftest(pdev, bar, spec.chipset)?;
+ crate::irq::doorbell_test::run_selftest(pdev, bar, spec.chipset, vectors)?;
},
// Initialize this early because `gsp_resources` depends on it.
diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs
index 13f361406a6c..43eec3f4f573 100644
--- a/drivers/gpu/nova-core/gsp.rs
+++ b/drivers/gpu/nova-core/gsp.rs
@@ -18,7 +18,8 @@
Io, //
},
pci,
- prelude::*, //
+ prelude::*,
+ sync::Arc, //
};
pub(crate) mod cmdq;
@@ -152,9 +153,8 @@ pub(crate) struct Gsp {
/// Log buffers, optionally exposed via debugfs.
#[pin]
logs: debugfs::Scope<LogBuffers>,
- /// Command queue.
- #[pin]
- pub(crate) cmdq: Cmdq,
+ /// Command queue, shared with the GSP event interrupt handler.
+ pub(crate) cmdq: Arc<Cmdq>,
/// RM arguments.
rmargs: Coherent<GspArgumentsPadded>,
}
@@ -173,8 +173,8 @@ pub(crate) fn new(pdev: &pci::Device<device::Bound>) -> impl PinInit<Self, Error
// _kgspInitLibosLoggingStructures (allocates memory for buffers)
// kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array)
Ok(try_pin_init!(Self {
- cmdq <- Cmdq::new(dev),
- rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
+ cmdq: Arc::pin_init(Cmdq::new(dev), GFP_KERNEL)?,
+ rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(cmdq.as_ref()))?,
libos: {
let mut libos = CoherentBox::zeroed_slice(
dev,
@@ -220,6 +220,11 @@ pub(crate) fn new(pdev: &pci::Device<device::Bound>) -> impl PinInit<Self, Error
pub(crate) fn get_static_info(&self, bar: Bar0<'_>) -> Result<commands::GetGspStaticInfoReply> {
self.cmdq.send_command(bar, commands::GetGspStaticInfo)
}
+
+ /// Returns a shared handle to the GSP command queue.
+ pub(crate) fn cmdq(&self) -> Arc<Cmdq> {
+ self.cmdq.clone()
+ }
}
/// Opaque bundle required to unload the GSP. Created by [`Gsp::boot`], consumed by [`Gsp::unload`].
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index 76d51155c49f..ac3e6642031a 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -647,6 +647,18 @@ pub(crate) fn await_msg<M: MessageFromGsp>(&self) -> Result<M>
}
}
}
+
+ /// Drains and dispatches every message currently pending in the GSP-to-CPU queue.
+ ///
+ /// Routes each message the GSP has already posted through [`CmdqInner::dispatch_event`] 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`].
@@ -977,4 +989,34 @@ fn dispatch_event(&self, function: Result<MsgFunction, u32>, seq: u32) {
}
}
}
+
+ /// Drains and dispatches all messages currently pending in the GSP-to-CPU queue.
+ ///
+ /// Processes whatever the GSP has already posted, dispatching each message as an event, and
+ /// stops once the queue is empty. There is no awaited reply during a drain, so every message
+ /// is routed to [`Self::dispatch_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.dispatch_event(function, seq);
+ }
+
+ Ok(())
+ }
}
diff --git a/drivers/gpu/nova-core/irq.rs b/drivers/gpu/nova-core/irq.rs
index 37dea5abf833..cced226a7582 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;
diff --git a/drivers/gpu/nova-core/irq/doorbell_test.rs b/drivers/gpu/nova-core/irq/doorbell_test.rs
index 3fd8b26e135e..c9712fa1bd18 100644
--- a/drivers/gpu/nova-core/irq/doorbell_test.rs
+++ b/drivers/gpu/nova-core/irq/doorbell_test.rs
@@ -28,13 +28,16 @@
time, //
};
-use super::interrupt_tree::{
- GinVector,
- LeafEnableGuard,
- LeafMask,
- Subtree,
- TopEnableGuard,
- Tree, //
+use super::{
+ interrupt_tree::{
+ GinVector,
+ LeafEnableGuard,
+ LeafMask,
+ Subtree,
+ TopEnableGuard,
+ Tree, //
+ },
+ SubtreeVectors, //
};
use crate::{
driver::Bar0,
@@ -49,8 +52,8 @@
/// Subtree carrying the doorbell vector, and the only subtree this test services.
///
-/// Derived from the vector so that changing `DOORBELL_VECTOR` moves the allocation, the subtree it
-/// enables, and the handler together.
+/// Derived from the vector so that changing `DOORBELL_VECTOR` moves the subtree it enables and the
+/// handler together.
const DOORBELL_SUBTREE: Subtree = DOORBELL_VECTOR.subtree();
/// Time allowed for each of the two deliveries to arrive.
@@ -153,17 +156,18 @@ fn quiesce_source(&self) {
///
/// # Errors
///
-/// `EIO` if the doorbell is already pending before the test, if the delivery count is not two, if
-/// the doorbell bit is still set once the source is stopped, or if either delivery found a pending
-/// bit other than the doorbell. `ETIMEDOUT` if either delivery does not arrive within the timeout.
+/// `EINVAL` if the doorbell's subtree is not one nova-core services. `EIO` if the doorbell is
+/// already pending before the test, if the delivery count is not two, if the doorbell bit is still
+/// set once the source is stopped, or if either delivery found a pending bit other than the
+/// doorbell. `ETIMEDOUT` if either delivery does not arrive within the timeout.
pub(crate) fn run_selftest<'a>(
pdev: &'a pci::Device<Bound>,
bar: Bar0<'a>,
chipset: Chipset,
+ vectors: &'a SubtreeVectors<'a>,
) -> Result {
- // The allocated interrupt type decides how the handler rearms delivery, so the vectors are
- // allocated before the tree is built.
- let vectors = super::alloc_vectors(pdev, DOORBELL_SUBTREE.into())?;
+ // 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 irq_type = vectors.irq_type();
let tree = Tree::new(bar, chipset, irq_type, DOORBELL_SUBTREE.into());
diff --git a/drivers/gpu/nova-core/irq/gsp.rs b/drivers/gpu/nova-core/irq/gsp.rs
new file mode 100644
index 000000000000..6366380eef98
--- /dev/null
+++ b/drivers/gpu/nova-core/irq/gsp.rs
@@ -0,0 +1,215 @@
+// 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 SWGEN0 latch,
+//! and the IRQ thread drains the message queue.
+//!
+//! See `Documentation/gpu/nova/core/interrupts.rst`.
+
+use kernel::{
+ device, irq, pci,
+ prelude::*,
+ sync::{
+ aref::ARef,
+ Arc, //
+ },
+};
+
+use super::{
+ interrupt_tree::{
+ GinVector,
+ LeafEnableGuard,
+ Subtree,
+ Tree, //
+ },
+ SubtreeVectors, //
+};
+use crate::{
+ driver::Bar0,
+ falcon::gsp::Gsp as GspFalcon,
+ gpu::Chipset,
+ gsp::cmdq::Cmdq, //
+};
+
+/// Fixed GSP notification vector.
+///
+/// The resource manager 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.
+///
+/// Disables every vector in every implemented leaf, clears the falcon's SWGEN0 latch, clears the
+/// tree's pending bits, and rearms PCI interrupt delivery. On return no vector is enabled, so the
+/// tree delivers nothing.
+pub(crate) fn quiesce(bar: Bar0<'_>, chipset: Chipset, irq_type: pci::IrqType) {
+ let tree = Tree::new(bar, chipset, irq_type, GSP_SUBTREE.into());
+ tree.disable_all_leaves();
+ // GSP boot consumes its notifications by polling the queue, which leaves SWGEN0 latched.
+ // Clear it before the tree drain below, so the drain clears the tree state the clear sets.
+ // Messages already posted raise no interrupt of their own, and the caller's queue drain
+ // covers them.
+ GspFalcon::clear_swgen0_intr(bar);
+ tree.drain();
+ // The `TOP_EN` cycle in `drain` is the rearm for the two enable-cycle methods, but pre-Hopper
+ // MSI rearms through a configuration-space write instead. An interrupt delivered before probe
+ // leaves delivery un-armed on that path, with no handler to have rearmed it.
+ tree.rearm_pci_irq(GSP_SUBTREE);
+}
+
+/// Threaded IRQ handler for the GSP SWGEN0 event.
+///
+/// The top half clears the GIN leaf and reads the falcon SWGEN0 latch. The IRQ thread drains the
+/// GSP-to-CPU message queue, which takes the command-queue lock.
+#[pin_data]
+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: Arc<Cmdq>,
+ /// The GIN interrupt tree for this chipset.
+ tree: Tree<'a>,
+ /// Device, for logging from interrupt context without taking the command-queue lock.
+ dev: ARef<device::Device>,
+}
+
+impl<'a> GspInterrupt<'a> {
+ /// Creates the handler for `chipset`, borrowing `bar` and sharing `cmdq` with the rest of the
+ /// driver.
+ pub(crate) fn new(
+ bar: Bar0<'a>,
+ cmdq: Arc<Cmdq>,
+ chipset: Chipset,
+ irq_type: pci::IrqType,
+ dev: ARef<device::Device>,
+ ) -> impl PinInit<Self, Error> + 'a {
+ try_pin_init!(Self {
+ bar,
+ cmdq,
+ tree: Tree::new(bar, chipset, irq_type, GSP_SUBTREE.into()),
+ dev,
+ }? Error)
+ }
+}
+
+impl irq::ThreadedHandler for GspInterrupt<'_> {
+ /// Top half: clears the GIN leaf, takes the falcon SWGEN0 latch, and rearms PCI interrupt
+ /// delivery.
+ fn handle(&self) -> irq::ThreadedIrqReturn {
+ // 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());
+
+ // SWGEN0 is the message-queue notification, so wake the IRQ thread to drain it.
+ let status = GspFalcon::take_swgen0_intr(self.bar);
+ let ret = if status.swgen0() {
+ irq::ThreadedIrqReturn::WakeThread
+ } else {
+ // The tree routes every falcon cause to this vector, so something other than a posted
+ // message fired it, for example a HALT from a GSP crash. There is no recovery path for
+ // those causes, so report the status rather than discarding it.
+ dev_err!(
+ &self.dev,
+ "GSP interrupt with no SWGEN0, falcon IRQSTAT {:#x}\n",
+ status.into_raw()
+ );
+ irq::ThreadedIrqReturn::Handled
+ };
+
+ // 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);
+
+ ret
+ }
+
+ /// IRQ thread: drains and dispatches 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: dropping the guard
+/// disables the GSP vector, and only then does `reg` drop and run `free_irq`. That closes the
+/// window, including a probe partial-unwind, in which an interrupt could be delivered to a handler
+/// being freed.
+#[pin_data]
+pub(crate) struct GspIrq<'a> {
+ _leaf_guard: LeafEnableGuard<'a>,
+ #[pin]
+ reg: irq::ThreadedRegistration<'a, GspInterrupt<'a>>,
+}
+
+impl<'a> GspIrq<'a> {
+ /// Registers the GSP SWGEN0 threaded handler for the GSP subtree in `vectors`, then enables
+ /// the GSP notification vector.
+ ///
+ /// # 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: Arc<Cmdq>,
+ chipset: Chipset,
+ ) -> impl PinInit<Self, Error> + 'a {
+ let dev: ARef<device::Device> = pdev.as_ref().into();
+ let tree = Tree::new(bar, chipset, vectors.irq_type(), GSP_SUBTREE.into());
+
+ // The fields below are initialized in the opposite order to the one they are declared in,
+ // so that the handler is registered before the vector 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",
+ GspInterrupt::new(bar, cmdq, chipset, vectors.irq_type(), dev),
+ )
+ },
+ // 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: 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 1d26ca408dc3..02077184fd17 100644
--- a/drivers/gpu/nova-core/irq/interrupt_tree.rs
+++ b/drivers/gpu/nova-core/irq/interrupt_tree.rs
@@ -412,7 +412,6 @@ pub(super) fn trigger(&self, vector: GinVector) -> Result {
///
/// This clears enables outside the subtrees nova-core services, so it is a probe-time
/// operation only.
- #[expect(dead_code)]
pub(super) fn disable_all_leaves(&self) {
for index in 0..self.leaves.into_raw() {
if let Some(leaf) = LeafIndex::try_new(index) {
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]
diff --git a/drivers/gpu/nova-core/regs.rs b/drivers/gpu/nova-core/regs.rs
index 3422b49df7a7..e360a6d25c60 100644
--- a/drivers/gpu/nova-core/regs.rs
+++ b/drivers/gpu/nova-core/regs.rs
@@ -120,6 +120,10 @@ pub(crate) fn usable_fb_size(self) -> u64 {
4:4 halt => bool;
}
+ pub(crate) NV_PFALCON_FALCON_IRQSTAT(u32) @ PFalconBase + 0x00000008 {
+ 6:6 swgen0 => bool;
+ }
+
pub(crate) NV_PFALCON_FALCON_MAILBOX0(u32) @ PFalconBase + 0x00000040 {
31:0 value => u32;
}
--
2.55.0
^ permalink raw reply [flat|nested] 18+ messages in thread* [PATCH v2 13/15] gpu: nova-core: retrigger the GSP falcon and clear every latched cause
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (12 preceding siblings ...)
2026-08-29 1:33 ` [PATCH v2 12/15] gpu: nova-core: drive GSP events with the SWGEN0 interrupt John Hubbard
@ 2026-08-29 1:33 ` John Hubbard
2026-08-29 1:33 ` [PATCH v2 14/15] gpu: nova-core: add KUnit tests for the interrupt tree and HALs John Hubbard
2026-08-29 1:33 ` [PATCH v2 15/15] gpu: nova-core: document the GIN interrupt controller and GSP events John Hubbard
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:33 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 signals the interrupt tree when its set of enabled causes goes
from empty to non-empty. While any enabled cause stays latched, later
causes produce no signal, and Turing falcons have no INTR_RETRIGGER
register with which to supply one.
The GSP handler cleared its GIN leaf bit and then cleared the falcon's
SWGEN0 latch. A cause that arrived between the two left no record: the
leaf clear discarded it, and the falcon had nothing left to signal.
Swapping the two clears moves the window rather than closing it.
The handler serviced SWGEN0 or reported an unserviceable cause, never
both, so a HALT co-pending with SWGEN0 stayed latched. nova-core's probe
cleared the SWGEN0 latch before draining the tree, so a message posted
in between set a leaf bit that the drain then erased. In every case the
GSP went silent for the life of the device.
Write the falcon's INTR_RETRIGGER register after every clear of the GSP
vector. That supplies the missing signal from whatever causes remain
enabled. Turing falcons have no such register, so skip the write there.
Handle every cause the falcon reports on one invocation, masking the
ones with no recovery path so the re-emit does not raise them again.
Clear the SWGEN0 latch after the tree drain instead of before it.
Neither of these depends on INTR_RETRIGGER, so both apply on Turing.
Assisted-by: Cursor:claude-opus-5
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
drivers/gpu/nova-core/falcon/gsp.rs | 36 +++++++++++++++++
drivers/gpu/nova-core/falcon/hal.rs | 8 ++++
drivers/gpu/nova-core/irq/gsp.rs | 61 ++++++++++++++++++-----------
drivers/gpu/nova-core/regs.rs | 20 ++++++++++
4 files changed, 103 insertions(+), 22 deletions(-)
diff --git a/drivers/gpu/nova-core/falcon/gsp.rs b/drivers/gpu/nova-core/falcon/gsp.rs
index f9d9e8e0386b..6ee5c1ef1af7 100644
--- a/drivers/gpu/nova-core/falcon/gsp.rs
+++ b/drivers/gpu/nova-core/falcon/gsp.rs
@@ -16,11 +16,13 @@
use crate::{
driver::Bar0,
falcon::{
+ hal,
Falcon,
FalconEngine,
PFalcon2Base,
PFalconBase, //
},
+ gpu::Chipset,
regs,
};
@@ -64,6 +66,40 @@ pub(crate) fn take_swgen0_intr(bar: Bar0<'_>) -> regs::NV_PFALCON_FALCON_IRQSTAT
status
}
+
+ /// Masks and clears every interrupt cause set in `status`.
+ ///
+ /// A masked cause leaves the falcon's enabled set, so it neither raises the tree again nor
+ /// holds that set non-empty.
+ pub(crate) fn mask_and_clear_intr(bar: Bar0<'_>, status: regs::NV_PFALCON_FALCON_IRQSTAT) {
+ let causes = status.into_raw();
+
+ bar.write(
+ WithBase::of::<Self>(),
+ regs::NV_PFALCON_FALCON_IRQMCLR::zeroed().with_value(causes),
+ );
+ bar.write(
+ WithBase::of::<Self>(),
+ regs::NV_PFALCON_FALCON_IRQSCLR::from(causes),
+ );
+ }
+
+ /// Re-emits the falcon's enabled interrupt causes into the interrupt tree.
+ ///
+ /// The falcon signals the tree on a transition of its enabled causes, so clearing the tree
+ /// leaf while a cause is still latched leaves no transition and no further vector.
+ ///
+ /// Does nothing on Turing, whose falcons do not implement the register.
+ pub(crate) fn retrigger_intr(bar: Bar0<'_>, chipset: Chipset) {
+ if !hal::has_intr_retrigger(chipset) {
+ return;
+ }
+
+ bar.write(
+ WithBase::of::<Self>().at(0),
+ regs::NV_PFALCON_FALCON_INTR_RETRIGGER::zeroed().with_trigger(true),
+ );
+ }
}
impl<'a> Falcon<'a, Gsp> {
diff --git a/drivers/gpu/nova-core/falcon/hal.rs b/drivers/gpu/nova-core/falcon/hal.rs
index 7e532889a1f4..f0828b32aebb 100644
--- a/drivers/gpu/nova-core/falcon/hal.rs
+++ b/drivers/gpu/nova-core/falcon/hal.rs
@@ -72,6 +72,14 @@ fn signature_reg_fuse_version(
fn load_method(&self) -> LoadMethod;
}
+/// Returns whether `chipset`'s falcons implement `NV_PFALCON_FALCON_INTR_RETRIGGER`.
+///
+/// Turing falcons do not. Ampere and later do, including GA100, whose falcon otherwise uses the
+/// Turing HAL, so this is keyed on the architecture rather than provided through [`FalconHal`].
+pub(crate) fn has_intr_retrigger(chipset: Chipset) -> bool {
+ !matches!(chipset.arch(), Architecture::Turing)
+}
+
/// Returns a boxed falcon HAL adequate for `chipset`.
///
/// We use a heap-allocated trait object instead of a statically defined one because the
diff --git a/drivers/gpu/nova-core/irq/gsp.rs b/drivers/gpu/nova-core/irq/gsp.rs
index 6366380eef98..a1030d66cc70 100644
--- a/drivers/gpu/nova-core/irq/gsp.rs
+++ b/drivers/gpu/nova-core/irq/gsp.rs
@@ -50,18 +50,17 @@
/// Clears the interrupt state that GSP boot left behind.
///
-/// Disables every vector in every implemented leaf, clears the falcon's SWGEN0 latch, clears the
-/// tree's pending bits, and rearms PCI interrupt delivery. On return no vector is enabled, so the
-/// tree delivers nothing.
+/// Disables every vector in every implemented leaf, clears the tree's pending bits, clears the
+/// falcon's SWGEN0 latch, and rearms PCI interrupt delivery. On return no vector is enabled, so
+/// the tree delivers nothing.
pub(crate) fn quiesce(bar: Bar0<'_>, chipset: Chipset, irq_type: pci::IrqType) {
let tree = Tree::new(bar, chipset, irq_type, GSP_SUBTREE.into());
tree.disable_all_leaves();
- // GSP boot consumes its notifications by polling the queue, which leaves SWGEN0 latched.
- // Clear it before the tree drain below, so the drain clears the tree state the clear sets.
- // Messages already posted raise no interrupt of their own, and the caller's queue drain
- // covers them.
- GspFalcon::clear_swgen0_intr(bar);
tree.drain();
+ // GSP boot consumes its notifications by polling the queue, which leaves SWGEN0 latched, and
+ // the GSP drives no new signal while it is set. Clear it after the tree drain, which erases
+ // every leaf bit and would erase the one a message posted since the clear had set.
+ GspFalcon::clear_swgen0_intr(bar);
// The `TOP_EN` cycle in `drain` is the rearm for the two enable-cycle methods, but pre-Hopper
// MSI rearms through a configuration-space write instead. An interrupt delivered before probe
// leaves delivery un-armed on that path, with no handler to have rearmed it.
@@ -80,6 +79,8 @@ pub(crate) struct GspInterrupt<'a> {
cmdq: Arc<Cmdq>,
/// The GIN interrupt tree for this chipset.
tree: Tree<'a>,
+ /// Chipset, for the falcon retrigger, which Turing does not implement.
+ chipset: Chipset,
/// Device, for logging from interrupt context without taking the command-queue lock.
dev: ARef<device::Device>,
}
@@ -98,15 +99,18 @@ pub(crate) fn new(
bar,
cmdq,
tree: Tree::new(bar, chipset, irq_type, GSP_SUBTREE.into()),
+ chipset,
dev,
}? Error)
}
}
impl irq::ThreadedHandler for GspInterrupt<'_> {
- /// Top half: clears the GIN leaf, takes the falcon SWGEN0 latch, and rearms PCI interrupt
- /// delivery.
+ /// Top half: clears the GIN leaf, takes every cause the falcon reports, 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.
@@ -119,27 +123,40 @@ fn handle(&self) -> irq::ThreadedIrqReturn {
}
leaf.clear_vectors(GSP_INTR_0_VECTOR.leaf_mask());
- // SWGEN0 is the message-queue notification, so wake the IRQ thread to drain it.
- let status = GspFalcon::take_swgen0_intr(self.bar);
- let ret = if status.swgen0() {
- irq::ThreadedIrqReturn::WakeThread
- } else {
- // The tree routes every falcon cause to this vector, so something other than a posted
- // message fired it, for example a HALT from a GSP crash. There is no recovery path for
- // those causes, so report the status rather than discarding it.
+ let status = GspFalcon::take_swgen0_intr(bar);
+
+ // Every cause the falcon reports leaves the falcon's enabled set on this invocation. A
+ // cause left latched holds that set non-empty, and the falcon signals the tree only on a
+ // transition of the set, so no later SWGEN0 would signal at all.
+ let unserviceable = status.with_swgen0(false);
+ if unserviceable.into_raw() != 0 {
+ // The tree routes every falcon cause to this vector, so a cause other than a posted
+ // message also arrives here, for example a HALT from a GSP crash. nova-core has no
+ // recovery path for those, so report the status rather than discarding it, then mask
+ // the cause.
dev_err!(
&self.dev,
- "GSP interrupt with no SWGEN0, falcon IRQSTAT {:#x}\n",
+ "unserviceable GSP falcon interrupt, IRQSTAT {:#x}\n",
status.into_raw()
);
- irq::ThreadedIrqReturn::Handled
- };
+ GspFalcon::mask_and_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 enabled 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);
- ret
+ // 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 and dispatches the GSP-to-CPU message queue.
diff --git a/drivers/gpu/nova-core/regs.rs b/drivers/gpu/nova-core/regs.rs
index e360a6d25c60..925600825434 100644
--- a/drivers/gpu/nova-core/regs.rs
+++ b/drivers/gpu/nova-core/regs.rs
@@ -124,6 +124,15 @@ pub(crate) fn usable_fb_size(self) -> u64 {
6:6 swgen0 => bool;
}
+ /// Masks interrupt causes at the falcon, one bit per cause, in the layout of
+ /// `NV_PFALCON_FALCON_IRQSTAT`.
+ ///
+ /// A masked cause is excluded from the enabled set the falcon signals on, so it cannot be
+ /// raised again by `NV_PFALCON_FALCON_INTR_RETRIGGER`.
+ pub(crate) NV_PFALCON_FALCON_IRQMCLR(u32) @ PFalconBase + 0x00000014 {
+ 31:0 value => u32;
+ }
+
pub(crate) NV_PFALCON_FALCON_MAILBOX0(u32) @ PFalconBase + 0x00000040 {
31:0 value => u32;
}
@@ -251,6 +260,17 @@ pub(crate) fn usable_fb_size(self) -> u64 {
0:0 reset => bool;
}
+ /// Re-emits the falcon's enabled interrupt causes into the interrupt tree.
+ ///
+ /// Write-only. A falcon signals the tree on a transition of its enabled causes, so a handler
+ /// that cleared the tree leaf while a cause was still latched has left no transition behind,
+ /// and this write supplies one. Turing falcons do not implement this register.
+ ///
+ /// OpenRM declares two elements and uses only the first.
+ pub(crate) NV_PFALCON_FALCON_INTR_RETRIGGER(u32)[2] @ PFalconBase + 0x000003e8 {
+ 0:0 trigger => bool;
+ }
+
pub(crate) NV_PFALCON_FBIF_TRANSCFG(u32)[8] @ PFalconBase + 0x00000600 {
2:2 mem_type => FalconFbifMemType;
1:0 target ?=> FalconFbifTarget;
--
2.55.0
^ permalink raw reply [flat|nested] 18+ messages in thread* [PATCH v2 14/15] gpu: nova-core: add KUnit tests for the interrupt tree and HALs
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (13 preceding siblings ...)
2026-08-29 1:33 ` [PATCH v2 13/15] gpu: nova-core: retrigger the GSP falcon and clear every latched cause John Hubbard
@ 2026-08-29 1:33 ` John Hubbard
2026-08-29 1:33 ` [PATCH v2 15/15] gpu: nova-core: document the GIN interrupt controller and GSP events John Hubbard
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:33 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 leaf index bounds, what a leaf count
derives, the subtree-to-leaf mapping and its out-of-range filtering,
where a vector lands in the tree, the bound that rejects a vector
outside it, the subtree set operations, and that every supported
chipset implements the subtree carrying the GSP notification.
* nova_core_gin_hal covers the tree size on each family, and the
rearm method for each combination of family and interrupt type.
* nova_core_falcon_hal covers the falcon retrigger gate. It is keyed
on the architecture rather than the HAL, because GA100 shares the
Turing HAL but does have the register.
Assisted-by: Cursor:claude-opus-5
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
drivers/gpu/nova-core/falcon/hal.rs | 24 +++++
drivers/gpu/nova-core/irq/hal.rs | 83 ++++++++++++++-
drivers/gpu/nova-core/irq/interrupt_tree.rs | 110 ++++++++++++++++++++
3 files changed, 216 insertions(+), 1 deletion(-)
diff --git a/drivers/gpu/nova-core/falcon/hal.rs b/drivers/gpu/nova-core/falcon/hal.rs
index f0828b32aebb..6bff9fea1a79 100644
--- a/drivers/gpu/nova-core/falcon/hal.rs
+++ b/drivers/gpu/nova-core/falcon/hal.rs
@@ -107,3 +107,27 @@ pub(super) fn falcon_hal<E: FalconEngine + 'static>(
Ok(hal)
}
+
+#[kunit_tests(nova_core_falcon_hal)]
+mod tests {
+ use super::*;
+
+ /// Only Turing falcons lack the interrupt retrigger register. GA100 has it even though
+ /// [`falcon_hal`] gives GA100 the Turing HAL, which is why the gate is keyed on the
+ /// architecture instead.
+ #[test]
+ fn intr_retrigger_gate_per_arch() {
+ assert!(!has_intr_retrigger(Chipset::TU102));
+
+ for chipset in [
+ Chipset::GA100,
+ Chipset::GA102,
+ Chipset::AD102,
+ Chipset::GH100,
+ Chipset::GB100,
+ Chipset::GB202,
+ ] {
+ assert!(has_intr_retrigger(chipset));
+ }
+ }
+}
diff --git a/drivers/gpu/nova-core/irq/hal.rs b/drivers/gpu/nova-core/irq/hal.rs
index ee354859b965..c7ecdc44144b 100644
--- a/drivers/gpu/nova-core/irq/hal.rs
+++ b/drivers/gpu/nova-core/irq/hal.rs
@@ -8,7 +8,8 @@
use kernel::{
io::Io,
- pci::IrqType, //
+ pci::IrqType,
+ prelude::*, //
};
use crate::{
@@ -109,3 +110,83 @@ 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(IrqType::Msi),
+ Some(PciIrqRearmMethod::ConfigMirrorEoi)
+ );
+ }
+
+ for chipset in [Chipset::GH100, Chipset::GB100, Chipset::GB202] {
+ let hal = cpu_interrupt_hal(chipset);
+ assert_eq!(
+ hal.pci_irq_rearm_method(IrqType::Msi),
+ Some(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(IrqType::MsiX),
+ Some(PciIrqRearmMethod::TopEnableCycleSubtree)
+ );
+ }
+ }
+
+ /// `INTx` is level-triggered and needs no rearm write on any architecture.
+ #[test]
+ fn intx_needs_no_rearm() {
+ 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(IrqType::Intx), None);
+ }
+ }
+}
diff --git a/drivers/gpu/nova-core/irq/interrupt_tree.rs b/drivers/gpu/nova-core/irq/interrupt_tree.rs
index 02077184fd17..7277ffcb33a1 100644
--- a/drivers/gpu/nova-core/irq/interrupt_tree.rs
+++ b/drivers/gpu/nova-core/irq/interrupt_tree.rs
@@ -503,3 +503,113 @@ 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!(LeafCount::Eight.subtree_set().into_raw(), 0x0f);
+ assert_eq!(LeafCount::Eight.vector_count(), 256);
+
+ assert_eq!(LeafCount::Sixteen.subtree_count(), 8);
+ assert_eq!(LeafCount::Sixteen.subtree_set().into_raw(), 0xff);
+ assert_eq!(LeafCount::Sixteen.vector_count(), 512);
+ }
+
+ /// Subtree `N` covers the two adjacent leaves `2N` and `2N + 1`, and an index past the leaf
+ /// register arrays yields nothing.
+ #[test]
+ fn subtree_covers_two_adjacent_leaves() {
+ for index in 0..8u32 {
+ let first = crate::num::u32_as_usize(index) * 2;
+ let mut leaves = subtree_leaves(index);
+
+ assert_eq!(leaves.next().map(LeafIndex::get), Some(first));
+ assert_eq!(leaves.next().map(LeafIndex::get), Some(first + 1));
+ assert!(leaves.next().is_none());
+ }
+
+ // Subtree 8 would cover leaves 16 and 17, both beyond the leaf index range.
+ assert!(subtree_leaves(8).next().is_none());
+ }
+
+ /// 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()
+ );
+ }
+
+ /// 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 [flat|nested] 18+ messages in thread* [PATCH v2 15/15] gpu: nova-core: document the GIN interrupt controller and GSP events
2026-08-29 1:22 [PATCH v2 00/15] nova-core: GPU interrupt support and GSP event delivery John Hubbard
` (14 preceding siblings ...)
2026-08-29 1:33 ` [PATCH v2 14/15] gpu: nova-core: add KUnit tests for the interrupt tree and HALs John Hubbard
@ 2026-08-29 1:33 ` John Hubbard
15 siblings, 0 replies; 18+ messages in thread
From: John Hubbard @ 2026-08-29 1:33 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 is invisible in the TOP
summary register. Three different numbers are also all called a vector,
in GIN, the MSI-X table, and the Linux IRQ API.
Add a design document covering the two-level register tree, how it
reaches the CPU under MSI and MSI-X, and the rules those behaviors
impose on a handler. It also covers the GSP event: the falcon retrigger,
the handoff from boot-time polling to interrupts, and how its messages
are classified. A glossary names each term after the register or the
specification that defines it.
Assisted-by: Cursor:claude-opus-5
Reviewed-by: Will Pierce <wpierce@nvidia.com>
Signed-off-by: John Hubbard <jhubbard@nvidia.com>
---
Documentation/gpu/nova/core/interrupts.rst | 686 +++++++++++++++++++++
Documentation/gpu/nova/index.rst | 1 +
2 files changed, 687 insertions(+)
create mode 100644 Documentation/gpu/nova/core/interrupts.rst
diff --git a/Documentation/gpu/nova/core/interrupts.rst b/Documentation/gpu/nova/core/interrupts.rst
new file mode 100644
index 000000000000..840012671511
--- /dev/null
+++ b/Documentation/gpu/nova/core/interrupts.rst
@@ -0,0 +1,686 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+=================================================
+GPU interrupt handling: GIN and the GSP event
+=================================================
+
+This document describes how nova-core receives interrupts from the GPU on Turing
+and later parts. It covers the GPU Interrupt and Notification unit (GIN), which
+is the GPU's interrupt controller, and the GSP event interrupt.
+
+Throughout, *CPU* means the CPU and the nova-core driver running on it. The GPU
+also has on-chip processors that run their own firmware and receive their own
+interrupts, and the GSP (GPU System Processor) is one of them.
+
+The register names in this document are the names from the GPU hardware
+reference headers. The CPU tree's registers live in the per-function
+``NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*`` aperture on every supported part, and
+the controller itself has a second name on pre-Hopper parts (see "Register
+naming").
+
+Terminology
+===========
+
+Three different numbers are all called a "vector" in the surrounding material.
+This document gives each one its own name and never uses "vector" on its own.
+
+GIN vector
+ The GPU-internal interrupt source number, 0 through 511 on Hopper. It is a
+ bit address within the tree: leaf ``vector / 32``, bit ``vector % 32``. The
+ CPU doorbell is GIN vector 129 and the GSP event is GIN vector 155.
+
+MSI-X entry
+ An index into the device's MSI-X table, 0 through 7 on Hopper. Linux's
+ ``struct msix_entry`` names its Linux IRQ number ``.vector``, which is a
+ third meaning.
+
+Linux IRQ number
+ What ``request_irq()`` takes, obtained from ``pci_irq_vector()``.
+
+The remaining terms, each named for the register or the specification that owns
+it:
+
+enable / disable a GIN vector
+ ``LEAF_EN_SET`` and ``LEAF_EN_CLEAR``.
+
+enable / disable a subtree
+ ``TOP_EN_SET`` and ``TOP_EN_CLEAR``.
+
+serviced subtree
+ A subtree nova-core enables and has a handler for.
+
+rearm
+ Restoring PCI interrupt delivery after servicing an interrupt. It is a
+ ``TOP_EN`` disable-then-enable cycle everywhere except under pre-Hopper
+ MSI, where it is a write to the end-of-interrupt (EOI) register in the BAR0
+ configuration-space mirror (see "Rearming PCI interrupt delivery").
+
+mask
+ Reserved for the two places hardware and the PCI specification use the
+ word: the MSI-X per-entry Vector Control mask bit, which Linux owns, and
+ the falcon cause masks. It never names a GIN enable.
+
+latched, pending
+ A ``LEAF`` bit records its source whether or not the GIN vector is enabled.
+ A disabled vector's pending bit never appears in ``TOP``.
+
+clear a leaf vector
+ Write a 1 to the vector's bit in ``LEAF``. Open RM spells the same
+ operation ``intrClearLeafVector_HAL``.
+
+pending bits
+ The plain bitmask value read from a ``LEAF`` register.
+
+unit
+ A generic interrupt-raising block. "Engine" is reserved for the blocks that
+ do usermode work: GR, CE, NVDEC, and the like.
+
+The GIN controller
+==================
+
+A GPU has many interrupt sources: the GSP, copy engines, the graphics engine,
+video decode and encode, the MMU fault path, timers, and others. Each one has a
+GIN vector number, which is internal to the controller and is not a PCI vector
+index.
+
+GIN records which vectors are pending in its own two-level register tree and
+raises the PCI interrupt when an enabled vector becomes pending. The CPU's
+handler reads that tree to tell the sources apart, clears the pending vectors,
+and runs the work for each.
+
+How the tree reaches the CPU over PCI
+-------------------------------------
+
+How many PCI interrupts the tree needs depends on the interrupt type Linux
+grants.
+
+MSI has a single message, and every subtree raises that one message. One
+allocated vector serves the whole tree.
+
+MSI-X raises a separate table entry per subtree, so a subtree's interrupts
+arrive on the table entry whose index is the subtree number. Linux masks each
+table entry a driver did not allocate, and a masked entry sends no message: the
+request sets a bit in the pending-bit array and waits for an unmask that never
+comes. A driver that leaves out the entry its subtree raises loses every
+interrupt on that subtree, and loses it silently, with the GIN leaf and TOP
+registers showing the vector pending and enabled while no handler runs.
+
+The serviced-subtree invariant
+------------------------------
+
+Every subtree enabled at TOP must have an allocated PCI vector with a registered
+handler.
+
+MSI satisfies this with one message that every subtree raises. MSI-X needs one
+allocated, unmasked entry per serviced subtree, and a PCI allocation cannot be
+sparse, so it runs from entry 0 through the highest serviced subtree::
+
+ MSI-X, with subtree 2 serviced:
+
+ subtree 0 -> entry 0 allocated, no handler, stays masked
+ subtree 1 -> entry 1 allocated, no handler, stays masked
+ subtree 2 -> entry 2 handler here, and its rearm covers subtree 2
+
+ MSI, with any serviced set:
+
+ every serviced subtree -> the one allocated vector, whose handler's
+ rearm covers the whole serviced set
+
+The entries allocated below a serviced subtree that the driver does not service
+cost nothing: Linux unmasks an entry only when its interrupt is requested, and a
+disabled subtree raises nothing.
+
+nova-core services exactly one subtree, subtree 2, because both the vectors it
+uses are in leaf 4: the GSP event (155) and the self-test doorbell (129). That
+is also the subtree the resource manager assigns to its ``UVM_SHARED`` interrupt
+category on every chipset nova-core supports.
+
+Interrupt trees
+===============
+
+GIN keeps a separate interrupt tree for each place an interrupt can be sent to:
+
+* One tree per PCIe function. The Physical Function (PF) has a tree, and each
+ Virtual Function (VF) has a tree.
+* One tree per on-chip microcontroller that receives interrupts, starting with
+ the GSP.
+
+Each destination reaches its own tree through its own BAR0 and cannot reach any
+other tree. GSP firmware selects the tree each unit's interrupt is sent to.
+
+nova-core services the CPU tree of one function. The VF trees and the
+microcontroller trees belong to firmware or to virtual functions.
+
+The two-level tree
+==================
+
+Each tree has two levels. The bottom level is the LEAF registers, which hold one
+pending bit per vector. The top level is the single TOP register, which
+summarizes the leaves.
+
+* Each ``LEAF(i)`` is a 32-bit register holding the pending bits for vectors
+ ``i * 32`` through ``i * 32 + 31``. A set bit means that vector is pending.
+* ``TOP`` is a single 32-bit read-only register. Each of its bits summarizes one
+ *subtree*, which is a pair of adjacent leaves. TOP bit ``N`` reflects
+ ``LEAF[2N]`` and ``LEAF[2N + 1]`` as filtered by their leaf enables, so a
+ vector that latched while disabled does not appear in TOP.
+
+A subtree is two leaves, so a part with L leaves has L / 2 subtrees and uses
+that many TOP bits. An 8-leaf part uses TOP bits 0 through 3, and the other 28
+bits always read 0. A 16-leaf part uses TOP bits 0 through 7::
+
+ TOP (one 32-bit register, and an 8-leaf part uses only bits 0..3)
+
+ bit 0 -> subtree 0 -> LEAF[0], LEAF[1] vectors 0..63
+ bit 1 -> subtree 1 -> LEAF[2], LEAF[3] vectors 64..127
+ bit 2 -> subtree 2 -> LEAF[4], LEAF[5] vectors 128..191
+ bit 3 -> subtree 3 -> LEAF[6], LEAF[7] vectors 192..255
+ bits 4..31: always 0 on an 8-leaf part (a 16-leaf part uses bits 0..7)
+
+ A LEAF is one 32-bit register, one bit per vector. For example, LEAF[4]
+ holds vectors 128..159:
+
+ bit 1 = vector 129 (CPU doorbell)
+ bit 27 = vector 155 (GSP event)
+
+Registers
+---------
+
+All the registers are 32 bits, defined in ``regs.rs`` under the
+``NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*`` names. The leaf registers are arrays
+indexed by leaf number:
+
+* ``LEAF(i)`` holds the pending bits for the vectors in leaf ``i``. Reading
+ returns the pending bits, and writing a 1 to a bit clears that vector
+ (write-1-to-clear).
+* ``LEAF_EN_SET(i)`` and ``LEAF_EN_CLEAR(i)`` enable and disable individual
+ vectors in leaf ``i``.
+* ``TOP`` is the read-only summary: bit N is set when an enabled vector is
+ pending in ``LEAF[2N]`` or ``LEAF[2N + 1]``. A vector that latched while its
+ leaf enable was clear does not appear.
+* ``TOP_EN_SET`` and ``TOP_EN_CLEAR`` enable and disable subtrees.
+* ``LEAF_TRIGGER`` makes a vector pending in software. The self-test uses it.
+
+Mapping a vector to the tree
+----------------------------
+
+Each vector occupies one bit of one leaf, and each leaf belongs to one
+subtree::
+
+ leaf = v / 32
+ bit = v % 32
+ subtree = leaf / 2
+
+Both of the vectors nova-core names by number fall in leaf 4: vector 129 at bit
+1 and vector 155 at bit 27, so both arrive under subtree 2.
+
+Enabling and clearing
+---------------------
+
+Each bit of a set or clear register acts on its own: writing a 1 performs the
+action for that bit, and writing a 0 leaves the bit's state alone. No caller
+ever needs a read-modify-write.
+
+* ``LEAF(i)`` is write-1-to-clear. Reading returns the pending bits. Each bit
+ must be cleared before its vector is serviced.
+* ``LEAF_EN_SET(i)`` and ``LEAF_EN_CLEAR(i)`` enable and disable individual
+ vectors in a leaf.
+* ``TOP_EN_SET`` and ``TOP_EN_CLEAR`` enable and disable whole subtrees.
+
+A vector reaches the CPU only when both its leaf enable bit and its subtree's
+TOP enable bit are set. The leaf enable governs delivery and the TOP summary,
+but not the latch: a disabled vector still latches its LEAF bit, and that bit is
+visible only by reading the leaf directly.
+
+How a unit interrupt reaches the CPU
+====================================
+
+A unit does not write a LEAF register itself. Each unit has an interrupt routing
+register, and GSP firmware programs it once at boot. Firmware writes three
+things into it: the unit's VECTOR (which leaf bit it uses), its GFID (which tree
+to post to: the PF or a specific VF), and its destination flags (which consumers
+get it: the CPU, the GSP, or another on-chip microcontroller).
+
+Later, when a unit has an event, three things happen in turn::
+
+ 1. The unit sends an interrupt message to GIN, carrying the VECTOR, GFID,
+ and destination flags from its routing register.
+ 2. GIN sets bit (VECTOR % 32) in LEAF[VECTOR / 32], in the tree that the
+ GFID and destination flags select.
+ 3. If that vector is enabled and its subtree is enabled, GIN raises the PCI
+ interrupt to the CPU.
+
+Because firmware assigns the vectors, nova-core does not hardcode which vector
+belongs to which unit. The one exception nova-core relies on is the GSP event
+vector, which firmware pins to a fixed number (see "The GSP event vector").
+
+Edge behavior and rearm
+=======================
+
+The pieces behave as follows:
+
+* A LEAF bit is a latch. It is set on the rising edge of its source and stays set
+ until the CPU writes a 1 to it. A source that stays high does not set the bit
+ again.
+* TOP is read-only and reports the subtree's *enabled* pending state. A vector
+ that latched while its leaf enable was clear does not appear in TOP.
+* LEAF_EN and TOP_EN are CPU-controlled enables that allow or block delivery.
+* GIN raises the PCI interrupt for subtree N when the subtree's enabled pending
+ state goes from low to high::
+
+ Per vector, in leaf i at bit b:
+ LEAF[i][b] AND LEAF_EN[i][b]
+
+ Per subtree N, across its leaves 2N and 2N + 1:
+ OR of every enabled pending bit -> TOP[N]
+
+ Delivery for subtree N:
+ TOP[N] AND TOP_EN[N] -> rising edge -> PCI interrupt
+
+ TOP_EN applies below TOP, so disabling a subtree halts delivery and leaves
+ what TOP reports unchanged.
+
+Because a disabled vector is invisible in TOP, code that must find every pending
+bit cannot descend from TOP. It has to read the leaves directly. Open RM does
+the same: its stalling-interrupt path never reads TOP, and instead walks every
+subtree it implements reading LEAF registers.
+
+Because delivery is edge-triggered, writing ``TOP_EN_SET`` while an enabled leaf
+bit is still set produces a new edge. A full tree walk uses this: after it
+clears the leaves, it writes ``TOP_EN_SET`` so an interrupt that arrived during
+servicing is still delivered.
+
+A unit that holds an internal level signal high does not produce a new leaf edge
+after the CPU clears the bit, so rearming alone does not re-deliver it. Such
+units have an ``INTR_RETRIGGER`` register that forces a new edge.
+
+Retriggering a falcon
+---------------------
+
+A falcon signals the tree on a transition of its enabled interrupt causes.
+Clearing the tree leaf while a cause is still latched leaves no transition, so
+the vector stays clear however many further causes arrive. Both clear orders
+have that window, so a handler on a falcon vector writes ``INTR_RETRIGGER`` on
+every path that services the vector.
+
+That re-emit must not be able to raise a cause that nothing clears. A cause the
+handler does not service is removed from the falcon's enabled set with
+``IRQMCLR`` and cleared with ``IRQSCLR`` before the re-emit.
+
+``INTR_RETRIGGER`` is absent on Turing falcons and present from GA100 onward, so
+the write is conditional on the architecture. A Turing handler cannot supply a
+transition that went missing, so it must leave no cause latched: it reads the
+status once and takes every cause that status reports, rather than stopping at
+the first one it recognizes. A cause left behind holds the falcon's enabled set
+non-empty, and no later cause from that falcon signals the tree at all.
+
+One window stays open on Turing. A cause that arrives between the status read
+and the clears is not in the status, so it stays latched after the tree leaf has
+been cleared. Open RM has the same window: ``kgspService_TU102`` ends with
+``kflcnIntrRetrigger``, which is implemented from GA100 onward and does nothing
+on Turing.
+
+Rearming PCI interrupt delivery
+-------------------------------
+
+Clearing the GIN state is not enough. A message-signaled interrupt is
+delivered once per edge, and the PCI side delivers no further interrupt until the
+CPU rearms it. Which operation does that depends on the GPU family and on the
+interrupt type Linux granted:
+
+================== ===== ===========================================
+Architecture Type Rearm operation
+================== ===== ===========================================
+Turing through Ada MSI write the configuration-mirror EOI register
+Hopper and later MSI clear then set the serviced TOP enables
+Any MSI-X clear then set the handler's own TOP enable
+================== ===== ===========================================
+
+The MSI forms cover every serviced subtree, because one message serves all of
+them. The MSI-X form covers one subtree, because each serviced subtree has its
+own table entry and its own handler.
+
+INTx is level-triggered and needs no rearm write. nova-core does not allocate it,
+so it never reaches a handler.
+
+A handler must rearm once per delivered interrupt, on every path that services
+one. A handler that skips the rearm receives no further interrupts at all.
+
+The rearm is separate from the TOP restore at the end of a full tree walk, even
+though two of the three forms write the same registers. The walk clears TOP_EN
+on entry so that it can read and clear without new interrupts arriving, and sets
+it again on exit. For the two enable-cycle forms that restore also rearms, but
+pre-Hopper MSI rearms through the configuration mirror, which the walk never
+writes, so the startup sequence rearms explicitly after the walk.
+
+Servicing an interrupt
+======================
+
+nova-core services the tree in one of two ways, depending on which code handles
+the interrupt.
+
+The GSP event handler services one vector, so it leaves its subtree enabled and
+reads and clears only its own leaf bit, touching a single leaf per interrupt.
+
+The startup drain walks the whole tree instead, because it must clear whatever is
+pending across every subtree rather than one known vector. It disables the
+subtrees, clears every pending leaf, then enables them again.
+
+The drain reads every implemented leaf rather than descending from TOP. Boot
+latches vectors while they are still disabled, and those bits do not appear in
+TOP, so a TOP-driven walk would skip exactly the state the drain has to clear.
+
+The two paths as register operations::
+
+ Full tree walk (the one-time startup drain):
+ write TOP_EN_CLEAR = serviced disable, to stop new interrupts
+ for each implemented subtree N, for i in {2N, 2N+1}:
+ pending = read LEAF[i] pending vectors in this leaf
+ write LEAF[i] = pending clear (write-1-to-clear)
+ write TOP_EN_SET = serviced restore TOP_EN
+
+ Notification, subtree stays enabled (the GSP event handler, and the
+ self-test, which deliberately mirrors it):
+ pending = read LEAF[gsp_leaf] is our vector's bit set?
+ write LEAF[gsp_leaf] = gsp_bit clear only our bit
+ rearm PCI interrupt delivery see "Rearming PCI interrupt
+ delivery"
+
+Two rules for the full walk:
+
+* Clear every pending leaf bit, including bits nova-core does not handle. An
+ uncleared bit holds its subtree in the pending state, and restoring TOP_EN
+ over it produces a delivery edge straight away. The walk writes back every bit
+ it read.
+* Restore TOP_EN only after clearing every pending leaf. Otherwise a still-set
+ bit raises the interrupt again while the walk is still running.
+
+The notification path clears one bit, so a vector pending alongside it in the
+same leaf keeps its bit and stays pending for whoever services it. Both paths
+must rearm PCI delivery for the interrupt they serviced.
+
+Interrupts and notifications
+============================
+
+Two kinds of source use the tree:
+
+* An interrupt means a unit needs servicing.
+* A notification means a unit is reporting that something happened, such as a log
+ record or completed work.
+
+The GSP event is a notification. Its handler leaves the subtree enabled and
+clears only the GSP leaf bit.
+
+The hardware manuals also split the vector space into "stall" and "nonstall"
+ranges. Those name address ranges rather than describing behavior. nova-core
+does not service the stall range.
+
+Per-architecture differences
+============================
+
+The tree is the same on every supported GPU except for its size, and there are
+only two sizes, split at Hopper:
+
+=================== ====== ======== ====================
+GPUs Leaves Subtrees Implemented subtrees
+=================== ====== ======== ====================
+Turing, Ampere, Ada 8 4 ``0x0f``
+Hopper and later 16 8 ``0xff``
+=================== ====== ======== ====================
+
+Only the lower eight leaves exist before Hopper, so TOP bits 4 through 31 read
+zero there. Hopper and later have 16 leaves, though sources do not populate all
+of them.
+
+The implemented subtrees bound which TOP bits mean anything. That set is wider
+than the set nova-core enables, which is the subtrees it services, per the
+serviced-subtree invariant. The startup drain still reads every implemented
+leaf, because a vector that latched while disabled is invisible in TOP and can
+be in any leaf.
+
+The HAL provides the leaf count, and the subtree count (leaves / 2) and the
+implemented-subtree set derive from it. The rearm method is the HAL's other
+per-architecture value.
+
+Multi-die parts
+===============
+
+On multi-die parts the controller is replicated per die, with an aggregation
+level above the per-die TOP registers. nova-core services the CPU tree of one
+function on a single-die part, so it does not drive the aggregation level.
+
+The GSP event
+=============
+
+When the GSP has output for the CPU (log records, error records, and other
+events), it writes the messages into the GSP-to-CPU queue in shared memory and
+raises SWGEN0, one of the software-generated interrupt outputs of the GSP
+microcontroller (a "falcon" in NVIDIA hardware). SWGEN0 is routed through a GIN
+vector, so it reaches the CPU as a PCI interrupt::
+
+ GSP writes messages into the GSP-to-CPU queue
+ GSP raises SWGEN0
+ GIN sets the GSP leaf bit, and the subtree becomes pending
+ PCI interrupt -> Linux IRQ -> nova-core top half, in IRQ context, which
+ must not sleep:
+ read the GSP leaf bit and clear it (subtree stays enabled)
+ read the GSP falcon IRQ status, clearing SWGEN0 if it was set
+ for every other cause that status reports: report it, then remove it
+ from the falcon's enabled set and clear it
+ retrigger the falcon
+ rearm PCI interrupt delivery
+ wake the IRQ thread if SWGEN0 was set
+ IRQ thread, which may sleep: take the command-queue lock and drain the
+ GSP-to-CPU queue, routing each message
+
+A halt and a posted message can be pending together, so the top half handles
+every cause the status reports rather than choosing between them (see
+"Retriggering a falcon").
+
+The interrupt is only the trigger to drain the queue. A thread polling for a
+command reply routes the messages it reads through the same classifier (see
+"Draining and classifying the GSP-to-CPU queue").
+
+If the drain fails, the queue cannot advance past the message it could not parse,
+so every later notification would repeat the same failure. The IRQ thread
+disables the GSP vector before reporting the failure, which leaves the queue
+unserviced until the device is reset.
+
+Enabling the GSP event
+----------------------
+
+SWGEN0 is a latch, and the GSP drives no new edge into the tree while it stays
+set. GSP boot consumes its notifications by polling the queue, which leaves the
+latch set and leaves stale state in the tree, so the handoff from polling to
+interrupts has a required order::
+
+ disable every implemented vector drop enables left by boot or by a
+ driver that ran before this one
+ drain the tree (full walk) clear stale GIN state from boot
+ clear the SWGEN0 latch so the next assertion makes an edge
+ rearm PCI interrupt delivery the walk does not do it under
+ pre-Hopper MSI
+ register the threaded IRQ handler nothing can reach it yet
+ enable the GSP vector at its leaf deliveries become possible here
+ drain the GSP-to-CPU queue messages posted before the clear
+
+Clearing the latch makes the first interrupt possible. Messages the GSP posted
+before that clear produce no interrupt, so the queue drain follows.
+
+The tree is quiesced before the handler is registered. Registering unmasks the
+PCI interrupt, and a leaf enable that boot left set would reach a handler that
+services one vector and has no way to service any other. Open RM clears all
+leaf enables at the same point for the same reason.
+
+The latch is cleared after the tree walk, not before. The walk erases every leaf
+bit, so a message posted between an earlier clear and the walk would leave the
+latch set with nothing in the tree to show for it, and on Turing no later
+message would signal the tree at all. Clearing last can instead leave the GSP
+vector pending with the latch already clear, so enabling the vector delivers one
+interrupt whose ``IRQSTAT`` reads zero. The queue drain that follows reads the
+message.
+
+The GSP event vector
+--------------------
+
+The GSP event uses a fixed vector, ``GSP_INTR_0_VECTOR`` (155), on Turing
+through Blackwell. Vector 155 is leaf 4, bit 27, subtree 2. nova-core enables
+that leaf bit and services it, with no runtime vector discovery.
+
+A full unit-to-vector table can be fetched from the GSP by RPC. nova-core does
+not fetch it, because a pinned vector needs no lookup.
+
+Draining and classifying the GSP-to-CPU queue
+=============================================
+
+The queue carries both command replies and unsolicited events. Each message is
+routed by its function code and its RPC sequence number, into one of three
+classes:
+
+* Function code and sequence both match the awaited reply. The message is
+ decoded and returned to the caller that sent the command.
+* The function code matches but the sequence does not. This is a reply to a
+ command that already timed out, so it is logged at warning level and dropped
+ rather than satisfying a later command that reused the same function code.
+* Anything else is an unsolicited event. OS-error and robust-channel records are
+ logged at error level. An unrecognized function code is logged at warning
+ level. Other known events (GSP logs, libos prints, assertion records,
+ lifecycle notices) need no action and are not logged again, because the RPC
+ receive trace already records their arrival.
+
+The read pointer advances past the message in all three cases, and also when a
+matched message fails to decode, so a message is never left at the queue head
+for the next receive to parse again.
+
+Corrupt framing is the exception. A message carries its length inside the
+region the checksum covers, so once the framing or the checksum fails there is
+no trustworthy length with which to skip the message. Such a failure poisons the
+queue and every later receive fails, which the IRQ thread reports before
+disabling the GSP vector.
+
+The classifier is a fixed set of function codes rather than a handler registry.
+The events that need action are handled directly in it.
+
+Both the polling path and the IRQ thread route messages through this classifier
+under the command-queue lock. Replies and events share one queue and one set of
+read pointers, so one lock covers the whole drain. A thread waiting for a reply
+dispatches any event it reads first and keeps waiting, under a single deadline
+for the whole wait rather than a fresh timeout after each message.
+
+One lock means a drain waits for an in-flight command's receive to finish or
+time out. For log and error records that delay does not matter.
+
+Design notes
+============
+
+Register naming
+---------------
+
+nova-core uses the ``NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_*`` names for the CPU
+tree on both pre-Hopper and Hopper-plus parts. Any function reaches its own tree
+through that aperture. The Hopper-plus central aperture (``NV_GIN_CPU_INTR_*``)
+configures other functions and is not used by the CPU path.
+
+The controller has two names in the hardware headers and in Open RM.
+``NV_CTRL`` names the tree on pre-Hopper parts, and ``NV_GIN`` names the
+Hopper+ unit that contains the tree along with arbiter logic. This document
+calls the controller GIN throughout, because the tree nova-core drives is the
+same on every supported part.
+
+Tree API
+--------
+
+Servicing a leaf has a required order: read its pending bits, then clear them.
+Reading a leaf is what produces the handle that clears it, so clearing a leaf
+before reading it does not compile. Enabling and disabling a vector or a subtree
+takes no such order, so those are operations on the tree itself.
+
+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 drain sleeps: it takes the command-queue mutex and walks shared memory, so it
+cannot run in hard-IRQ context. nova-core uses a threaded IRQ handler. The top
+half clears the GIN leaf, takes every cause the falcon reports, rearms delivery,
+and wakes the IRQ thread if SWGEN0 was among them. The thread takes the lock and
+drains the queue. The self-test does no sleeping work and uses a non-threaded
+handler with a completion.
+
+Shared BAR0 mapping
+-------------------
+
+The GPU, the self-test, and the GSP event handler read the same BAR0 registers.
+nova-core keeps one BAR0 mapping and lets each of them borrow it. An interrupt
+handler is torn down when the device unbinds, so it only runs while the mapping
+is alive.
+
+Self-test
+=========
+
+The self-test runs during driver probe. It registers a real interrupt handler
+and confirms that an interrupt injected at the GPU is delivered all the way to
+that handler, so it needs a working GPU and PCI interrupt path. It is gated by
+``CONFIG_NOVA_CORE_IRQ_SELFTEST`` and runs before GSP boot, so it never touches
+GSP interrupt state.
+
+The parts with no hardware dependency are covered by KUnit tests instead: the
+vector encoding, the subtree and leaf arithmetic, and the per-architecture rearm
+policy.
+
+The test drives ``LEAF_TRIGGER``, a hardware register that every supported part
+implements. Writing a vector number to it latches that vector exactly as its
+unit would, after which the vector takes the ordinary path to the CPU under the
+ordinary enables.
+
+The test drives vector 129, at leaf 4 bit 1. It registers a handler for that
+vector and triggers it twice, waiting for the first delivery before triggering
+the second. Its handler deliberately mirrors the notification path: it clears
+only its own leaf bit and rearms PCI interrupt delivery, rather than walking the
+tree.
+
+The two interrupts cannot coalesce into one, because the second is triggered
+only after the first handler has finished. A handler that fails to rearm times
+out on the second delivery instead of passing. A single delivery serviced by a
+full tree walk cannot detect that, because the walk's own TOP_EN restore
+produces an edge by itself.
+
+The test passes only if both deliveries arrive, each one finds the doorbell bit
+and nothing else pending in the leaf, and the leaf is clear once the source is
+stopped. Anything else fails probe. Requiring the exact mask on the second
+delivery shows that the first handler's clear reached the hardware. The test
+runs before GSP boot on a leaf the drain has just cleared, so no other vector in
+that leaf can be active and the exact mask costs nothing.
+
+The test borrows the allocation that probe made for the serviced subtrees rather
+than allocating its own, and looks up the vector for the doorbell's own subtree.
+A doorbell vector moved to a subtree nova-core does not service fails that
+lookup, and with it the self-test and probe, rather than being misrouted
+silently.
+
+The test exercises the interrupt path from the GPU to the handler without GSP
+firmware, which is useful when bringing up PCI, MSI, MSI-X, and passthrough
+setups. Under MSI-X a pass also shows that the per-subtree table entry routing
+works, since the delivery arrives on the entry belonging to the serviced
+subtree.
+
+Virtualization
+==============
+
+The per-function trees, the GFID routing, and the central ``NV_GIN`` aperture
+support virtualization: each VF gets its own tree, and the PF or firmware routes
+a unit's interrupt to the right function. MIG (multi-instance GPU) partitioning
+adds more structure. nova-core services the CPU tree of one function, and
+implements no VF tree management, GFID routing, or MIG support.
+
+References
+==========
+
+* nova-core source: the register definitions in ``regs.rs``, the interrupt HAL
+ and tree API in the ``irq`` module, and the GSP command queue in the ``gsp``
+ module.
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 [flat|nested] 18+ messages in thread