nova-core: GPU interrupt support and GSP event delivery
Subsystems (9)
v2 cover nova-core: GPU interrupt support and GSP event delivery
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.
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/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
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
Signature · 1 line
2.55.0
PATCH v2 1/15 rust: pci: declare IrqType and IrqTypes with impl_flags
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.
--- rust/kernel/pci/irq.rs | 68 +++++++++++++----------------------------- 1 file changed, 21 insertions(+), 47 deletions(-)
rust/kernel/pci/irq.rs +21 -47
@@ -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)?;
Signature · 1 line
2.55.0
Re: [PATCH v2 01/15] rust: pci: declare IrqType and IrqTypes with impl_flags
Quoted 4 lines · 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.
Quoted 8 lines
IrqTypes open-coded that pattern with a
with()builder, so a caller naming two interrupt types chained two calls ontoIrqTypes::default().Declare both types through
impl_flags!, so the same set reads asIrqType::Msi|IrqType::MsiX.Suggested-by Gary Guo <[email protected]>Signed-off-by John Hubbard <[email protected]>
Much better indeed.
PATCH v2 2/15 rust: sync: completion: add wait_for_completion_timeout()
In reply to John HubbardFrom: Joel Fernandes <[email protected]>
A driver that runs an interrupt self-test during probe waits for the handler to fire. wait_for_completion() has no timeout, so a broken interrupt path stalls probe indefinitely. Add a timeout variant of wait_for_completion().
--- rust/kernel/sync/completion.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-)
rust/kernel/sync/completion.rs +22 -1
@@ -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), + } + } }
Signature · 1 line
2.55.0
Re: [PATCH v2 02/15] rust: sync: completion: add wait_for_completion_timeout()
Quoted 10 lines · John Hubbard
From: Joel Fernandes <[email protected]>
A driver that runs an interrupt self-test during probe waits for the handler to fire.
wait_for_completion()has no timeout, so a broken interrupt path stalls probe indefinitely. Add a timeout variant ofwait_for_completion().Signed-off-by Joel Fernandes <[email protected]>[jhubbard: return the remaining jiffies]Signed-off-by John Hubbard <[email protected]>
Wish I took a look earlier; this patch could have been merged through the rust tree before the merge window opened. Now I guess we will need to take it into drm-rust-next as part of this series. Not a big deal though, unless other potential users appear this cycle.
PATCH v2 3/15 gpu: nova-core: add the GIN CPU interrupt tree and MSI EOI registers
In reply to John HubbardGIN 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.
--- 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
drivers/gpu/nova-core/irq.rs new file +11 -0
@@ -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;
drivers/gpu/nova-core/irq/regs.rs new file +71 -0
71 lines not on this page · raw message
drivers/gpu/nova-core/nova_core.rs +1 -0
@@ -17,6 +17,7 @@mod fsp;mod gpu;mod gsp; +mod irq;mod mctp;#[macro_use] mod num;
Signature · 1 line
2.55.0
PATCH v2 4/15 gpu: nova-core: add the GIN vector and subtree newtypes
In reply to John HubbardA 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.
--- 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
drivers/gpu/nova-core/irq.rs +1 -0
@@ -8,4 +8,5 @@//! //! See `Documentation/gpu/nova/core/interrupts.rst`. +mod interrupt_tree;mod regs;
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +209 -0
209 lines not on this page · raw message
drivers/gpu/nova-core/nova_core.rs +1 -0
@@ -17,6 +17,7 @@mod fsp;mod gpu;mod gsp; +#[expect(dead_code)] mod irq;mod mctp;#[macro_use]
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 04/15] gpu: nova-core: add the GIN vector and subtree newtypes
Quoted 38 lines · 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 <[email protected]>Signed-off-by John Hubbard <[email protected]>--- 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.rsdrivers/gpu/nova-core/irq.rs +1
-0@@ -8,4 +8,5 @@//! //! See `Documentation/gpu/nova/core/interrupts.rst`. +mod interrupt_tree;mod regs;drivers/gpu/nova-core/irq/interrupt_tree.rs new file +0
-0
drivers/gpu/nova-core/irq/interrupt_tree.rs line 8
Quoted 8 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +8
-0@@ -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.
The dedicated types are really nice. Looking at the full series, I think we can even push them further and unleash more of the guarantees they give us. I'll comment on the relevant bits of code in the patches, but one obvious instance is that the registers defined in patch 3 could use these types for their fields, instead of having to convert them into raw values and back again (which partially defeats the purpose of using dedicated types as you can write e.g. a SubtreeSet into a register meant to represent a LeafMask). For instance:
pub(super) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF(u32)[16] @ 0x00b81000 {
31:0 vectors => LeafMask;
}
...
pub(super) NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_SET(u32) @ 0x00b81608 {
31:0 subtrees => SubtreeSet;
}This unleashes some code cleanups in the patches ahead - I'll comment on them as I come across them. But basically this means that I think patch 3 should come *after* this one, so the registers can be defined with their fields from the get-go.
This also means you will need simple implementations to convert LeafMask and SubtreeSet from and to Bounded<u32, 32>, but they're as trivial as they come, e.g.:
impl From<Bounded<u32, 32>> for LeafMask {
fn from(value: Bounded<u32, 32>) -> Self {
Self(value.into())
}
}
impl From<LeafMask> for Bounded<u32, 32> {
fn from(value: LeafMask) -> Self {
Bounded::from(value.0)
}
}Quoted 26 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +26
-0+ +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.
drivers/gpu/nova-core/irq/interrupt_tree.rs line 44
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +10
-0+ Eight = 8, + +/// Hopper and later. + Sixteen = 16, +} + +impl LeafCount { +/// Returns the number of leaves. +pub (super )const fn into_raw (self) ->usize { + selfas usize
// CAST: comment needed here - it just needs to state the obvious though. :)
drivers/gpu/nova-core/irq/interrupt_tree.rs line 49
Quoted 5 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +5
-0+ } + +/// Returns the number of subtrees, each of which covers two leaves. +pub (super )const fn subtree_count (self) ->u32 { + selfas u32 /LEAVES_PER_SUBTREE
Here as well.
drivers/gpu/nova-core/irq/interrupt_tree.rs line 59
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +10
-0+ } + +/// 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 { + selfas u32 *VECTORS_PER_LEAF
And here as well - maybe we can have a into_u32() helper that does the cast, and then into_raw can call u32_as_usize on it to avoid having a CAST comment itself?
Quoted 91 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +91
-0+ } +} + +/// 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 ())
drivers/gpu/nova-core/irq/interrupt_tree.rs line 160
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +10
-0+ } +} + +/// 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 );
Since the maximum number of vectors is 512, and as NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_TRIGGER is 12 bits, how about storing the inner value as a Bounded<u32, 9>? This enforces the < 512 invariant using the type system and saves us one try_with_vector down the road when we write NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_LEAF_TRIGGER.
drivers/gpu/nova-core/irq/interrupt_tree.rs line 168
Quoted 8 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +8
-0+ +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 ());
This can be a const_assert! as it works with a generic argument. Although I guess we won't need this anymore if we use Bounded<u32, 9>. The Invariants section of GinVector could also be dropped.
Quoted 5 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +5
-0+ +// INVARIANT: `VECTOR` is within the widest supported tree. +Self (VECTOR ) + } +
drivers/gpu/nova-core/irq/interrupt_tree.rs line 183
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +10
-0+/// 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 )
Let's use crate::num so these prefixes become just num:: as there are quite a few instances in later patches as well.
Alexandre Courbot
maintainerRe: [PATCH v2 04/15] gpu: nova-core: add the GIN vector and subtree newtypes
In reply to John HubbardOn Sat Aug 29, 2026 at 10:22 AM JST, John Hubbard wrote:
<...>
Quoted 12 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +12
-0+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 ) + } +
drivers/gpu/nova-core/irq/interrupt_tree.rs line 183
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs new file +10
-0+/// 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 )
Noticed this while reviewing patch 7.
Another nice side effect of making GinVector a Bounded<u32, 9> is that you can now get rid of this from_expr (which relies on the optimizer-dependent build_assert! under the hood) by doing self.0.shr::<5, 4>() (i.e. divide by 32, aka. VECTORS_PER_LEAF) and now you have... A Bounded<u32, 4> that fits perfectly into a LeafIndex!
This method then becomes:
pub(super) fn leaf_index(self) -> LeafIndex {
// CALC: `self.0 / VECTORS_PER_LEAF`.
self.0.shr::<{ VECTORS_PER_LEAF.ilog2() }, _>().cast()
}LEAF_INDEX_MASK is now unused and can be removed.
PATCH v2 5/15 gpu: nova-core: add the per-architecture GIN CPU interrupt HAL
In reply to John HubbardGIN, 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.
--- 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
drivers/gpu/nova-core/irq.rs +1 -0
@@ -8,5 +8,6 @@//! //! See `Documentation/gpu/nova/core/interrupts.rst`. +mod hal;mod interrupt_tree;mod regs;
drivers/gpu/nova-core/irq/hal.rs new file +111 -0
111 lines not on this page · raw message
drivers/gpu/nova-core/irq/hal/gh100.rs new file +31 -0
@@ -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 ;
drivers/gpu/nova-core/irq/hal/tu102.rs new file +30 -0
@@ -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 ;
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 05/15] gpu: nova-core: add the per-architecture GIN CPU interrupt HAL
Quoted 7 lines · John Hubbard
GIN, the GPU Interrupt and Notification unit, is the GPU's interrupt controller. Each PCIe function has its own tree, whose leaf count depends on the GPU family.
Message-signaled delivery stops after each edge until the CPU rearms it, and the rearm write differs by family and interrupt type:
Quoted 7 lines
* 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.
The indentation of this bullet list is a bit unconventional for a kernel git log (* typically starts at column 1).
<...>
Quoted 15 lines
drivers/gpu/nova-core/irq/hal.rs new file +15
-0+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),
drivers/gpu/nova-core/irq/hal.rs line 79
Quoted 10 lines
drivers/gpu/nova-core/irq/hal.rs new file +10
-0+ }; + + 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 (), + );
With the typed register fields in patch 3, these can become:
bar.write_reg(
regs::NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_CLEAR::zeroed().with_subtrees(subtrees),
);
bar.write_reg(
regs::NV_VIRTUAL_FUNCTION_PRIV_CPU_INTR_TOP_EN_SET::zeroed().with_subtrees(subtrees),
);drivers/gpu/nova-core/irq/hal.rs line 86
Quoted 7 lines
drivers/gpu/nova-core/irq/hal.rs new file +7
-0+ } +} + +/// 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.
The last sentence sounds a bit self-evident and unneeded.
Quoted 48 lines
drivers/gpu/nova-core/irq/hal.rs new file +25
-0+/// +/// 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 ) -> &'staticdyn CpuInterruptHal { +match chipset.arch () { +Architecture ::Turing |Architecture ::Ampere |Architecture ::Ada => tu102::TU102_HAL , +Architecture ::Hopper |Architecture ::BlackwellGB10x |Architecture ::BlackwellGB20x => { + gh100::GH100_HAL + } + } +}drivers/gpu/nova-core/irq/hal/gh100.rs new file +17
-0@@ -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 {
drivers/gpu/nova-core/irq/hal/gh100.rs line 27
Quoted 10 lines
drivers/gpu/nova-core/irq/hal/gh100.rs new file +10
-0+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 ), + } + }
AFAIU we do not support INTx at all, right? In this case it just shouldn't be handled here, and we could simplify this method to just return PciIrqRearmMethod.
I suspect we are considering INTx because we work with the kernel's IrqType, which includes it, and must make our match arms exhaustive. Let's just use our own IRQ type for Nova:
pub(crate) enum MsiType {
Msi,
MsiX,
}Then every instance of IrqType in the irq module can be replaced by this one, and we don't need to care about INTx anymore. This method can also just return a PciIrqRearmMethod.
You will probably need to include a MsiType into SubtreeVectors to make its irq_type method work, but that's still better than having code for managing an INTx variant that is dead code since it would have failed at probe time anyway.
Quoted 3 lines · John Hubbard
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,
Signature · 1 line
John Hubbard
Quoted 132 lines
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::IrqTypeand IrqTypes withimpl_flags, so a call site readsIrqType::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_LEAFandGSP_BITare 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_pendinghands 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_areastill reads the GSP producer pointer with no acquire barrier. Gary Guo's barrier series putsdma_mb(Read)at exactly that point [2], so let's just wait for his fix to land.[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/Joel Fernandes (2):
rust: sync: completion: addwait_for_completion_timeout()
gpu: nova-core: add the GIN interrupt tree and allocate its vectorsJohn Hubbard (13):
rust: pci: declare IrqType and IrqTypes withimpl_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 eventsDocumentation/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
Quoted 10 lines · John Hubbard
Quoted 3 lines · John Hubbard
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,
Signature · 1 line
John Hubbard
PATCH v2 6/15 gpu: nova-core: add the GIN interrupt tree and allocate its vectors
In reply to John HubbardFrom: Joel Fernandes <[email protected]>
Servicing a GIN leaf has a required order: read its pending bits, then clear them. Clearing a leaf before reading it discards every vector latched in it, and nothing reports the loss.
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.
[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]
--- drivers/gpu/nova-core/irq.rs | 89 ++++++ drivers/gpu/nova-core/irq/interrupt_tree.rs | 284 +++++++++++++++++++- 2 files changed, 369 insertions(+), 4 deletions(-)
drivers/gpu/nova-core/irq.rs +89 -0
@@ -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 }) +}
drivers/gpu/nova-core/irq/interrupt_tree.rs +280 -4
321 lines not on this page · raw message
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 06/15] gpu: nova-core: add the GIN interrupt tree and allocate its vectors
Quoted 58 lines · John Hubbard
From: Joel Fernandes <[email protected]>
Servicing a GIN leaf has a required order: read its pending bits, then clear them. Clearing a leaf before reading it discards every vector latched in it, and nothing reports the loss.
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 <[email protected]>Signed-off-by Joel Fernandes <[email protected]>[jhubbard: name the module
interrupt_treewith 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 indrain()rather than descending from the TOP registers, which cannot see a vector that latched while disabled]Signed-off-by John Hubbard <[email protected]>--- drivers/gpu/nova-core/irq.rs | 89 ++++++ drivers/gpu/nova-core/irq/interrupt_tree.rs | 284 +++++++++++++++++++- 2 files changed, 369 insertions(+), 4 deletions(-)drivers/gpu/nova-core/irq.rs +14
-0@@ -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 ,//
drivers/gpu/nova-core/irq.rs line 37
Quoted 10 lines
drivers/gpu/nova-core/irq.rs +10
-0+}; + +/// 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 ,
Here we would also store the MsiType I proposed on the previous patch and return it in irq_type.
Quoted 24 lines
drivers/gpu/nova-core/irq.rs +24
-0+} + +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) + } +} +
drivers/gpu/nova-core/irq.rs line 71
Quoted 10 lines
drivers/gpu/nova-core/irq.rs +10
-0+/// 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 , + } +}
This is only called by request_for, which is just above, so can we inline it there?
Quoted 18 lines
drivers/gpu/nova-core/irq.rs +18
-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 () {
drivers/gpu/nova-core/irq.rs line 99
Quoted 10 lines
drivers/gpu/nova-core/irq.rs +10
-0+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 ())?, + };
Optional style nit:
let vectors = pdev
.alloc_irq_vectors(entries, entries, IrqType::MsiX.into()) .or_else(|_| pdev.alloc_irq_vectors(1, 1, IrqType::Msi.into()))?;
Quoted 42 lines
drivers/gpu/nova-core/irq.rs +3
-0+ +Ok (SubtreeVectors { vectors, serviced }) +}drivers/gpu/nova-core/irq/interrupt_tree.rs +20
-1@@ -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::{
drivers/gpu/nova-core/irq/interrupt_tree.rs line 43
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +10
-0+ 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, //
I'm not a big fan of these long imports - can we just use regs::* and access the registers using their full name?
We used to just import regs and access registers using regs::NV_FOO back when they were all declared in a single big file, but now that registers are properly confined to their module, using a local regs::* is much more appropriate and should become the default IMHO.
Quoted 25 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +5
-2+ }, // +}; +/// 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.
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn subtree(self) -> Subtree { · line 234
Quoted 5 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +1
-1@@ -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 {
Why are we losing the const here?
Quoted 19 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +12
-0if 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.
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn validate(self, leaves: LeafCount) -> Result { · line 263
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +10
-0+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 >,
With the proposed changes in the previous patch, this can hopefully become a PciIrqRearmMethod.
Quoted 12 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +12
-0+} + +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,
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn validate(self, leaves: LeafCount) -> Result { · line 285
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +10
-0+ 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 ()),
Shouldn't we error if we cannot service some of the requested vectors?
Quoted 13 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +13
-0+ 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.
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn validate(self, leaves: LeafCount) -> Result { · line 308
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +10
-0+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 ());
With the changes in patch 3, this becomes
self.bar
.write_reg(CPU_INTR_TOP_EN_SET::zeroed().with_subtrees(self.serviced));(also applies to disable_top).
Quoted 13 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +13
-0+ } + +/// 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 }
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn validate(self, leaves: LeafCount) -> Result { · line 331
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +10
-0+ } + +/// 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 ()); + } + }
There are a couple optimizations you can do here.
LeafIndex is 4-bits bounded, so its value is guaranteed to be < 16. But Bounded::get does not express this guarantee because it has to be usable in const context.
Bounded's Deref implementation, otoh, *does* include some assertions that tell the optimizer that the returned value is < 16. So you can use that, and the build-time checked at method, to get rid of the unwrap_or.
And with the register field types set in patch 3, you can set the field direction without converting to the raw value. So the above if statement becomes just:
self.bar.write(
Array::at(*leaf),
CPU_INTR_LEAF_EN_SET::zeroed().with_vectors(vectors),
);(also applies to disable_leaf)
Quoted 18 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +18
-0+ +/// 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,
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn validate(self, leaves: LeafCount) -> Result { · line 359
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +10
-0+ 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 );
Similarly, here you can just do:
let pending = self.bar.read(CPU_INTR_LEAF::at(*leaf)).vectors();
And drop the unwrap_or(0) which looks a bit sus to me.
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn validate(self, leaves: LeafCount) -> Result { · line 364
Quoted 5 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +5
-0+ +LeafPending { + tree: self, + leaf, + pending:LeafMask ::from_raw (pending),
... and you can now assign pending as-is.
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn validate(self, leaves: LeafCount) -> Result { · line 373
Quoted 9 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +9
-0+ } + } + +/// 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.
Hopefully this error becomes unneeded if we convert GinVector to use Bounded.
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn validate(self, leaves: LeafCount) -> Result { · line 375
Quoted 2 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +2
-0+// Only the interrupt self-test injects a software interrupt. +#[cfg_attr(not( CONFIG_NOVA_CORE_IRQ_SELFTEST ), expect(dead_code))]
This Kconfig option does not exist yet as of this patch IIUC.
Quoted 28 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +28
-0+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 indexin 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
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn validate(self, leaves: LeafCount) -> Result { · line 413
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +10
-0+/// 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 indexin 0 ..self.leaves.subtree_count () { +for leafin subtree_leaves (index) {
I guess you don't need this double-loop and can replace it with what disable_all_leaves does?
This would let you drop subtree_leaves and its associated tests. Actually it could be replaced by an iterator function returning the leaves directly.
Quoted 33 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +33
-0+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: &'aTree <'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
drivers/gpu/nova-core/irq/interrupt_tree.rs pub(super) const fn validate(self, leaves: LeafCount) -> Result { · line 456
Quoted 10 lines
drivers/gpu/nova-core/irq/interrupt_tree.rs +10
-0+/// 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 ()); + } + }
Here this would become:
if !vectors.is_empty() {
bar.write(
Array::at(*self.leaf),
CPU_INTR_LEAF::zeroed().with_vectors(vectors),
);
}PATCH v2 7/15 gpu: nova-core: add an interrupt delivery self-test
In reply to John HubbardA GPU interrupt can be lost in the MSI or MSI-X allocation, in the GIN tree's enable bits, or in the rearm. Every one of those failures looks the same to the driver: no interrupt arrives, and nothing in the symptom says which one broke.
Add an optional probe-time self-test that injects the CPU doorbell through the GIN software trigger. One injection would pass even with a broken rearm, because the first message-signaled interrupt arrives whether the driver rearms or not. The test injects twice, and waits for the first handler to rearm before it injects again.
Run it before GSP boot on a quiesced tree, and fail probe unless exactly two deliveries arrive, each delivery finds only the doorbell pending, and the leaf ends clear. Under MSI-X the injected subtree has its own table entry, so the delivery exercises that entry too.
--- drivers/gpu/nova-core/Kconfig | 15 + drivers/gpu/nova-core/gpu.rs | 8 + drivers/gpu/nova-core/irq.rs | 2 + drivers/gpu/nova-core/irq/doorbell_test.rs | 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
drivers/gpu/nova-core/Kconfig +15 -0
@@ -15,3 +15,18 @@ config NOVA_CORE This driver is work in progress and may not be functional. If M is selected, the module will be called nova-core. + +config NOVA_CORE_IRQ_SELFTEST + bool "Nova Core interrupt delivery self-test" + depends on NOVA_CORE + help + Run an interrupt delivery self-test during nova-core probe. It + injects a known vector through the GPU interrupt controller's + software trigger and confirms the interrupt reaches the driver's + handler, validating the PCI interrupt path from the GPU to the CPU + with no dependency on GSP firmware. The result is printed to dmesg. + + If the test fails, the PCI probe fails and the driver does not load. + + This is intended for driver bring-up and for debugging PCI, MSI, or + passthrough setups. If unsure, say N.
drivers/gpu/nova-core/gpu.rs +8 -0
@@ -347,6 +347,14 @@ pub(crate) fn new( .inspect_err(|_| dev_err!(dev, "GFW boot did not complete\n"))?; }, + // Validate the MSI interrupt path before booting GSP, when the self-test is + // enabled. This runs on a quiesced interrupt tree with no GSP state present, so it + // never observes or clears GSP or PRIV_RING interrupts. + _: { +#[cfg( CONFIG_NOVA_CORE_IRQ_SELFTEST )] +crate ::irq::doorbell_test::run_selftest (pdev, bar, spec.chipset)?; + }, +// Initialize this early because `gsp_resources` depends on it. sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?,
drivers/gpu/nova-core/irq.rs +2 -0
@@ -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;
drivers/gpu/nova-core/irq/doorbell_test.rs new file +294 -0
294 lines not on this page · raw message
drivers/gpu/nova-core/irq/interrupt_tree.rs +47 -26
166 lines not on this page · raw message
drivers/gpu/nova-core/nova_core.rs +1 -1
@@ -17,7 +17,7 @@mod fsp;mod gpu;mod gsp; -#[expect(dead_code)] +#[cfg_attr(not( CONFIG_NOVA_CORE_IRQ_SELFTEST ), expect(dead_code))] mod irq;mod mctp;#[macro_use]
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 07/15] gpu: nova-core: add an interrupt delivery self-test
Quoted 21 lines · John Hubbard
A GPU interrupt can be lost in the MSI or MSI-X allocation, in the GIN tree's enable bits, or in the rearm. Every one of those failures looks the same to the driver: no interrupt arrives, and nothing in the symptom says which one broke.
Add an optional probe-time self-test that injects the CPU doorbell through the GIN software trigger. One injection would pass even with a broken rearm, because the first message-signaled interrupt arrives whether the driver rearms or not. The test injects twice, and waits for the first handler to rearm before it injects again.
Run it before GSP boot on a quiesced tree, and fail probe unless exactly two deliveries arrive, each delivery finds only the doorbell pending, and the leaf ends clear. Under MSI-X the injected subtree has its own table entry, so the delivery exercises that entry too.
Assisted-by Cursor:claude-opus-5Reviewed-by Will Pierce <[email protected]>Co-developed-by Joel Fernandes <[email protected]>Signed-off-by Joel Fernandes <[email protected]>Signed-off-by John Hubbard <[email protected]>
Quoted 6 lines
--- 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 +++--
The whole edit of interrupt_tree.rs changes or removes code that has been added in the previous patch, and looks like churn that can be squashed into patch 6, or am I missing something? I've tried squashing it and things build just fine, so unless there is a good reason not to, let's squash. It also makes this patch cleaner as it really only adds the test.
<...>
Quoted 47 lines
drivers/gpu/nova-core/irq.rs +2
-0@@ -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;drivers/gpu/nova-core/irq/doorbell_test.rs new file +28
-0@@ -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,//
drivers/gpu/nova-core/irq/doorbell_test.rs line 38
Quoted 10 lines
drivers/gpu/nova-core/irq/doorbell_test.rs new file +10
-0+}; + +use super ::interrupt_tree::{ +GinVector , +LeafEnableGuard , +LeafMask , +Subtree , +TopEnableGuard , +Tree ,// +};
supernit: missing empty line.
<...>
Quoted 32 lines
drivers/gpu/nova-core/irq/doorbell_test.rs new file +32
-0+/// 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" ,
drivers/gpu/nova-core/irq/doorbell_test.rs line 187
Quoted 10 lines
drivers/gpu/nova-core/irq/doorbell_test.rs new file +10
-0+ 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 ();
How about making drain *not* call reenable_top() in the end, and making it the responsibility of the caller to reenable the tree if they need so? This would remove this unneeded flip-flop which looks like a tiny race condition.
Also, shouldn't we call disable_all_leaves() to make sure no potentially spurious vector remains enabled? Otherwise the mask test would fail, IIUC.
(bonus point: disable_all_leaves gets a user and doesn't need to be marked dead_code anymore.)
<...>
drivers/gpu/nova-core/irq/doorbell_test.rs fn subtree_leaves(index: u32) -> impl Iterator<Item = LeafIndex> { · line 281
Quoted 8 lines
drivers/gpu/nova-core/irq/doorbell_test.rs new file +4
-0@@ -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 )]
Mmm I'm not very comfortable with having several copies of Tree concurrently accessing the registers. I've managed to remove that derive directive, and thankfully the solution is simple: after you pass the Tree to the DoorbellTestHandler, just access it through reg.handler().tree to build the SelfTestResources:
let resources = SelftestResources {
_leaf_guard: reg
.handler()
.tree
.enable_leaf_guarded(doorbell, doorbell_mask),
_top_guard: reg.handler().tree.enable_top_guarded(),
reg,
};(notice how reg is now initialized last)
Then right after you have handler and can access it through handler.tree.
That way there is only one copy of Tree and we avoid potential future footguns.
PATCH v2 8/15 gpu: nova-core: dispatch GSP events instead of discarding them
In reply to John HubbardThe 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.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 64 ++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 13 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +51 -13
@@ -547,11 +547,11 @@ fn notify_gsp(bar: Bar0<'_>) {/// Sends `command` to the GSP and waits for the reply. /// -/// Messages with non-matching function codes are silently consumed until the expected reply -/// arrives. +/// A message read while waiting that is not the reply goes to +/// [`CmdqInner::dispatch_event`]. /// -/// The queue is locked for the entire send+receive cycle to ensure that no other command can -/// be interleaved. +/// The queue is locked for the entire send+receive cycle, so no other command can be +/// interleaved. /// /// # Errors ///
@@ -805,8 +805,10 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {/// Receive a message from the GSP. /// -/// The expected message type is specified using the `M` generic parameter. If the pending -/// message has a different function code, `ERANGE` is returned and the message is consumed. +/// The expected message type is specified using the `M` generic parameter. A message whose +/// function code matches is decoded and returned. Any other message, whether its function code +/// is a different one or is unrecognized, goes to [`Self::dispatch_event`] and `ERANGE` is +/// returned. /// /// The read pointer is always advanced past the message, regardless of whether it matched. ///
@@ -815,8 +817,7 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {/// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. /// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the /// message queue. -/// - `EINVAL` if the function code of the message was not recognized. -/// - `ERANGE` if the message had a recognized but non-matching function code. +/// - `ERANGE` if the message was not the awaited reply. /// /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is. fn receive_msg <M :MessageFromGsp >(&mut self, timeout:Delta ) ->Result <M >
@@ -825,11 +826,13 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> Error: From<M::InitError>, {let message = self.wait_for_msg (timeout)?; -let function = message.header.function ().map_err (|_|EINVAL )?; +let function = message.header.function (); +let seq = message.header.sequence (); +let matched =matches! (function,Ok (f)if f ==M ::FUNCTION ); -// Extract the message. Store the result as we want to advance the read pointer even in -// case of failure. -let result =if function ==M ::FUNCTION { +// Bind the result rather than returning early. The read pointer must advance past this +// message on every path. +let result =if matched {let (cmd, contents_1) =M ::Message ::from_bytes_prefix (message.contents.0 ).ok_or (EIO )?;let mut sbuffer =SBufferIter ::new_reader ([contents_1, message.contents.1 ]);
@@ -840,7 +843,7 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>dev_warn! ( &self.dev,"GSP message {:?} has unprocessed data\n" , - function +M ::FUNCTION ); } })
@@ -853,6 +856,41 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> message.header.length().div_ceil(GSP_PAGE_SIZE), )?); +if !matched { + self.dispatch_event (function, seq); + } + result } + +/// Routes a GSP message that is not the reply a caller is waiting for. +/// +/// GSP-reported errors are logged at error level and unrecognized function codes at warning +/// level. Every other known function code is consumed without a log line, because the RPC +/// receive trace in [`Self::wait_for_msg`] already records its arrival. +fn dispatch_event (&self, function:Result <MsgFunction ,u32 >, seq:u32 ) { +match function { +Ok (MsgFunction ::OsErrorLog ) => { +dev_err! (&self.dev,"GSP reported an OS error (seq {})\n" , seq); + } +Ok (MsgFunction ::RcTriggered ) => { +dev_err! ( + &self.dev, +"GSP triggered robust-channel recovery (seq {})\n" , + seq + ); + } +// GSP logs, libos prints, NoCat assertion records, and the other known event codes. +// None of them requires action. +Ok (_) => {} +Err (raw) => { +dev_warn! ( + &self.dev, +"unknown GSP message function {:#x} (seq {})\n" , + raw, + seq + ); + } + } + } }
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 08/15] gpu: nova-core: dispatch GSP events instead of discarding them
Quoted 8 lines · 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.
Quoted 5 lines
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.
The naming looks a bit misleading to me - dispatch_event doesn't really dispatch anything, it logs or ignores what is passed to it. If we plan on implementing a real dispatch mechanism in the future I'm ok with keeping the name, but we should document that intent in its doccomment.
Quoted 12 lines
Assisted-by Cursor:claude-opus-5Signed-off-by John Hubbard <[email protected]>--- drivers/gpu/nova-core/gsp/cmdq.rs | 64 ++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 13 deletions(-)drivers/gpu/nova-core/gsp/cmdq.rs +0
-0
drivers/gpu/nova-core/gsp/cmdq.rs fn notify_gsp(bar: Bar0<'_>) { · line 551
Quoted 7 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2
-2@@ -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`].
CmdqInner is an internal private type and an implementation detail, we shouldn't reference it in public documentation. Let's say something like "A message read while waiting that is logged if it is an error record, and ignored otherwise".
drivers/gpu/nova-core/gsp/cmdq.rs fn notify_gsp(bar: Bar0<'_>) { · line 554
Quoted 5 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2
-2/// -/// 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.
nit: is this hunk necessary?
Quoted 30 lines
drivers/gpu/nova-core/gsp/cmdq.rs +5
-4/// /// # 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)?;
drivers/gpu/nova-core/gsp/cmdq.rs fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> · line 834
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +5
-4-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.
Oooh nice catch, the queue was irreversibly unusable after an unknown message is received on the previous code.
Quoted 14 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2
-1+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 ); } })
drivers/gpu/nova-core/gsp/cmdq.rs fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> · line 861
Quoted 6 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3
-0@@ -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); + }
We already have an else branch for the if matched statement above, you can move this block there and avoid testing again.
It's also arguably (slightly) better since the message is now logged before the fallible u32::try_from is called.
drivers/gpu/nova-core/gsp/cmdq.rs fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> · line 871
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +8
-0+ 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 ) {
That's where we could describe the intent to turn this into an actual dispatcher if we plan to do so in the future. Otherwise, something like classify_event is probably a more fit name.
PATCH v2 9/15 gpu: nova-core: match GSP RPC replies by sequence, not just function
In reply to John HubbardThe 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.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 89 ++++++++++++++++++++----------- drivers/gpu/nova-core/gsp/fw.rs | 13 +++-- 2 files changed, 67 insertions(+), 35 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +59 -30
@@ -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) -> Resultlet (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) -> Resultdev_dbg! ( &self.dev,"GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n" , - self.seq, + rpc_seq,M ::FUNCTION , dst.header.length (), );// All set - update the write pointer and inform the GSP of the new command. let elem_count = dst.header.element_count (); - self.seq +=1 ; + self.elem_seq = self.elem_seq.wrapping_add (1 ); self.gsp_mem.advance_cpu_write_ptr (elem_count);Cmdq ::notify_gsp (bar);Ok (()) } -/// Sends `command` to the GSP. +/// Sends `command` to the GSP and returns the RPC sequence number assigned to it. /// -/// The command may be split into multiple messages if it is large. +/// The command may be split into multiple messages if it is large. The GSP echoes the +/// sequence number in the reply, so a caller passes it to [`Self::receive_msg`] to match the +/// reply to this command. /// /// # Errors ///
@@ -703,24 +712,26 @@ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result/// written to by its [`CommandToGsp::init_variable_payload`] method. /// /// Error codes returned by the command initializers are propagated as-is. -fn send_command <M >(&mut self, bar:Bar0 <'_>, command:M ) ->Result +fn send_command <M >(&mut self, bar:Bar0 <'_>, command:M ) ->Result <u32 >where M :CommandToGsp ,Error :From <M ::InitError >, { +let rpc_seq = self.rpc_seq; + self.rpc_seq = self.rpc_seq.wrapping_add (1 ); +match SplitState ::new (command)? { -SplitState ::Single (command) => self.send_single_command (bar, command), +SplitState ::Single (command) => self.send_single_command (bar, command, rpc_seq)?,SplitState ::Split (command,mut continuations) => { - self.send_single_command (bar, command)?; + self.send_single_command (bar, command, rpc_seq)?;while let Some (continuation) = continuations.next () { -// Turbofish needed because the compiler cannot infer M here. - self.send_single_command ::<ContinuationRecord <'_>>(bar, continuation)?; + self.send_single_command ::<ContinuationRecord <'_>>(bar, continuation, rpc_seq)?; } - -Ok (()) } } + +Ok (rpc_seq) }/// Wait for a message to become available on the message queue.
@@ -805,10 +816,14 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {/// Receive a message from the GSP. /// -/// The expected message type is specified using the `M` generic parameter. A message whose -/// function code matches is decoded and returned. Any other message, whether its function code -/// is a different one or is unrecognized, goes to [`Self::dispatch_event`] and `ERANGE` is -/// returned. +/// The expected message type is given by the `M` generic parameter. With `expected_seq` set, +/// the message must also carry that RPC sequence number to count as the awaited reply. With +/// `None`, the function code alone decides the match. +/// +/// A matching message is decoded and returned. A message carrying the expected function code +/// with a different sequence is a stale reply to a command that already timed out, and is +/// logged and dropped. Any other message goes to [`Self::dispatch_event`]. Both non-matching +/// cases return `ERANGE`. /// /// The read pointer is always advanced past the message, regardless of whether it matched. ///
@@ -820,7 +835,11 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {/// - `ERANGE` if the message was not the awaited reply. /// /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is. -fn receive_msg <M :MessageFromGsp >(&mut self, timeout:Delta ) ->Result <M > +fn receive_msg <M :MessageFromGsp >( + &mut self, + timeout:Delta , + expected_seq:Option <u32 >, + ) ->Result <M >where // This allows all error types, including `Infallible`, to be used for `M::InitError`. Error :From <M ::InitError >,
@@ -828,10 +847,10 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>let message = self.wait_for_msg (timeout)?;let function = message.header.function ();let seq = message.header.sequence (); -let matched =matches! (function,Ok (f)if f ==M ::FUNCTION ); +let func_matches =matches! (function,Ok (f)if f ==M ::FUNCTION ); +let matched = func_matches && expected_seq.is_none_or (|expected| seq == expected); -// Bind the result rather than returning early. The read pointer must advance past this -// message on every path. +// Every path must advance the read pointer past this message. let result =if matched {let (cmd, contents_1) =M ::Message ::from_bytes_prefix (message.contents.0 ).ok_or (EIO )?;let mut sbuffer =SBufferIter ::new_reader ([contents_1, message.contents.1 ]);
@@ -857,7 +876,17 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> )?);if !matched { - self.dispatch_event (function, seq); +if func_matches { +dev_warn! ( + &self.dev, +"GSP RPC: dropping stale {:?} reply (seq {}, awaiting {:?})\n" , +M ::FUNCTION , + seq, + expected_seq, + ); + }else { + self.dispatch_event (function, seq); + } } result
drivers/gpu/nova-core/gsp/fw.rs +8 -5
@@ -782,13 +782,14 @@ fn new() -> Self { }impl bindings::rpc_message_header_v { -fn init (cmd_size:usize , function:MsgFunction ) ->impl Init <Self ,Error > { +fn init (sequence:u32 , cmd_size:usize , function:MsgFunction ) ->impl Init <Self ,Error > {type RpcMessageHeader = bindings::rpc_message_header_v ;try_init! (RpcMessageHeader { header_version:MsgHeaderVersion ::new ().into (), signature: bindings::NV_VGPU_MSG_SIGNATURE_VALID , function: function.into (), + sequence, length:size_of ::<Self >() .checked_add (cmd_size) .ok_or (EOVERFLOW )
@@ -813,25 +814,27 @@ impl GspMsgElement {/// /// # Arguments /// -/// * `sequence` - Sequence number of the message. +/// * `elem_seq` - Transport sequence number of the queue element (`seqNum`). +/// * `rpc_seq` - RPC sequence number, echoed by the GSP in the reply. /// * `cmd_size` - Size of the command (not including the message element), in bytes. /// * `function` - Function of the message. pub (crate )fn init ( - sequence:u32 , + elem_seq:u32 , + rpc_seq:u32 , cmd_size:usize , function:MsgFunction , ) ->impl Init <Self ,Error > {type RpcMessageHeader = bindings::rpc_message_header_v ;type InnerGspMsgElement = bindings::GSP_MSG_QUEUE_ELEMENT ;let init_inner =try_init! (InnerGspMsgElement { - seqNum: sequence, + seqNum: elem_seq, elemCount:size_of ::<Self >() .checked_add (cmd_size) .ok_or (EOVERFLOW )? .div_ceil (GSP_PAGE_SIZE ) .try_into () .map_err (|_|EOVERFLOW )?, - rpc <-RpcMessageHeader ::init (cmd_size, function), + rpc <-RpcMessageHeader ::init (rpc_seq, cmd_size, function), ..Zeroable ::init_zeroed () });
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 09/15] gpu: nova-core: match GSP RPC replies by sequence, not just function
Quoted 14 lines · 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.
Quoted 2 lines
Assisted-by Cursor:claude-opus-5Signed-off-by John Hubbard <[email protected]>
So I am particularly looking at patches 8-11 at first, because it looks like they can be merged ahead of the rest and are useful on their own, but I am hitting an error with this one when unloading the driver:
modprobe -r nova-core
[ 3333.123171] nova-core 0000:08:00.0: GSP RPC: send: seq# 3, function=UnloadingGuestDriver, length=0x58 [ 3333.148123] nova-core 0000:08:00.0: GSP RPC: receive: seq# 0, function=Ok(GspPostNoCat), length=0x50c [ 3333.169449] nova-core 0000:08:00.0: GSP RPC: receive: seq# 0, function=Ok(UcodeLibOsPrint), length=0x78 [ 3333.323550] nova-core 0000:08:00.0: GSP RPC: receive: seq# 0, function=Ok(UnloadingGuestDriver), length=0x50 [ 3333.323551] nova-core 0000:08:00.0: GSP RPC: dropping stale UnloadingGuestDriver reply (seq 0, awaiting Some(3)) [ 3338.124152] nova-core 0000:08:00.0: GSP shutdown failed: ETIMEDOUT [ 3338.161317] nova-core 0000:08:00.0: failed to unload GSP: ETIMEDOUT
It looks like the GSP sends the UnloadingGuestDriver response with a sequence of 0... From what I can gather from OpenRM, 570.144 doesn't match the sequence number, only the function. Maybe this needs to be part of the r000 series instead, if that behavior is only expected there?
Re: [PATCH v2 09/15] gpu: nova-core: match GSP RPC replies by sequence, not just function
Quoted 1 line · Alexandre Courbot
On Sat Aug 29, 2026 at 10:33 AM JST, John Hubbard wrote:
...
Quoted 13 lines
So I am particularly looking at patches 8-11 at first, because it looks like they can be merged ahead of the rest and are useful on their own, but I am hitting an error with this one when unloading the driver:
modprobe -r nova-core
[ 3333.123171] nova-core 0000:08:00.0: GSP RPC: send: seq# 3, function=UnloadingGuestDriver, length=0x58 [ 3333.148123] nova-core 0000:08:00.0: GSP RPC: receive: seq# 0, function=Ok(GspPostNoCat), length=0x50c [ 3333.169449] nova-core 0000:08:00.0: GSP RPC: receive: seq# 0, function=Ok(UcodeLibOsPrint), length=0x78 [ 3333.323550] nova-core 0000:08:00.0: GSP RPC: receive: seq# 0, function=Ok(UnloadingGuestDriver), length=0x50 [ 3333.323551] nova-core 0000:08:00.0: GSP RPC: dropping stale UnloadingGuestDriver reply (seq 0, awaiting Some(3)) [ 3338.124152] nova-core 0000:08:00.0: GSP shutdown failed: ETIMEDOUT [ 3338.161317] nova-core 0000:08:00.0: failed to unload GSP: ETIMEDOUT
Quoted 5 lines
It looks like the GSP sends the UnloadingGuestDriver response with a sequence of 0... From what I can gather from OpenRM, 570.144 doesn't match the sequence number, only the function. Maybe this needs to be part of the r000 series instead, if that behavior is only expected there?
That sounds likely correct. In order to test this, I thought I was being smart by using the r000 as a base, but of course that seems to have led to this test hole. Let me go fix it up.
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH v2 09/15] gpu: nova-core: match GSP RPC replies by sequence, not just function
Quoted 22 lines · John Hubbard
Quoted 1 line · Alexandre Courbot
On Sat Aug 29, 2026 at 10:33 AM JST, John Hubbard wrote:
...
Quoted 13 lines
So I am particularly looking at patches 8-11 at first, because it looks like they can be merged ahead of the rest and are useful on their own, but I am hitting an error with this one when unloading the driver:
modprobe -r nova-core
[ 3333.123171] nova-core 0000:08:00.0: GSP RPC: send: seq# 3, function=UnloadingGuestDriver, length=0x58 [ 3333.148123] nova-core 0000:08:00.0: GSP RPC: receive: seq# 0, function=Ok(GspPostNoCat), length=0x50c [ 3333.169449] nova-core 0000:08:00.0: GSP RPC: receive: seq# 0, function=Ok(UcodeLibOsPrint), length=0x78 [ 3333.323550] nova-core 0000:08:00.0: GSP RPC: receive: seq# 0, function=Ok(UnloadingGuestDriver), length=0x50 [ 3333.323551] nova-core 0000:08:00.0: GSP RPC: dropping stale UnloadingGuestDriver reply (seq 0, awaiting Some(3)) [ 3338.124152] nova-core 0000:08:00.0: GSP shutdown failed: ETIMEDOUT [ 3338.161317] nova-core 0000:08:00.0: failed to unload GSP: ETIMEDOUTQuoted 5 lines
It looks like the GSP sends the UnloadingGuestDriver response with a sequence of 0... From what I can gather from OpenRM, 570.144 doesn't match the sequence number, only the function. Maybe this needs to be part of the r000 series instead, if that behavior is only expected there?
Quoted 4 lines
That sounds likely correct. In order to test this, I thought I was being smart by using the r000 as a base, but of course that seems to have led to this test hole. Let me go fix it up.
Actually, my existing tests pass with both r570 and r000, but the real problem was that my test suite did not include unloading nova-core.ko.
With that test added, I can reproduce your reported failure locally. Debugging it now.
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH v2 09/15] gpu: nova-core: match GSP RPC replies by sequence, not just function
Quoted 11 lines · John Hubbard
Quoted 3 lines · John Hubbard
Quoted 1 line · Alexandre Courbot
On Sat Aug 29, 2026 at 10:33 AM JST, John Hubbard wrote:
...
Actually, my existing tests pass with both r570 and r000, but the real problem was that my test suite did not include unloading nova-core.ko.
With that test added, I can reproduce your reported failure locally. Debugging it now.
OK, yes the seq number matching, which GSP only does on r580+, was the problem. All fixed locally, and I've added a test to catch this in the future.
thanks,
Signature · 1 line
John Hubbard
PATCH v2 10/15 gpu: nova-core: recover the GSP receive path from corrupt framing
In reply to John HubbardA 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.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 63 ++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 22 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +41 -22
@@ -3,6 +3,7 @@mod continuation;use core::{ + cell::Cell , mem, sync::atomic::{ fence,
@@ -523,6 +524,7 @@ pub(crate) fn new(dev: &device::Device<device::Bound>) -> impl PinInit<Self, Err gsp_mem, elem_seq: 0, rpc_seq: 0, + poisoned: Cell::new(false), }), })) })
@@ -622,6 +624,12 @@ struct CmdqInner {/// [`CmdqInner::receive_msg`] match that reply to the awaiting command. Advances once per /// logical command. rpc_seq: u32, +/// Set once a message with corrupt framing or a bad checksum is seen. Such a message has an +/// untrusted length, so the queue cannot be advanced past it, and every later receive fails +/// until the queue is torn down and reset. +/// +/// A [`Cell`], so the shared-borrow read path [`Self::wait_for_msg`] can set it. + poisoned: Cell<bool>,/// Memory area shared with the GSP for communicating commands and messages. gsp_mem: DmaGspMem, }
@@ -748,11 +756,13 @@ fn send_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result<u32>/// # Errors /// /// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. -/// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the -/// message queue. -/// -/// Error codes returned by the message constructor are propagated as-is. +/// - `EIO` if the framing or the checksum is invalid, or the queue was already poisoned by an +/// earlier such failure. Either failure poisons the queue, so recovery requires a reset. fn wait_for_msg (&self, timeout:Delta ) ->Result <GspMessage <'_>> { +if self.poisoned.get () { +return Err (EIO ); + } +// Wait for a message to arrive from the GSP. let (slice_1, slice_2) =read_poll_timeout ( || Ok(self.gsp_mem.driver_read_area()),
@@ -763,7 +773,10 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { .map(|(slice_1, slice_2)| (slice_1.as_flattened(), slice_2.as_flattened()))?;// Extract the `GspMsgElement`. -let (header, slice_1) =GspMsgElement ::from_bytes_prefix (slice_1).ok_or (EIO )?; +let Some ((header, slice_1)) =GspMsgElement ::from_bytes_prefix (slice_1)else { + self.poisoned.set (true ); +return Err (EIO ); + };dev_dbg! ( &self.dev,
@@ -777,6 +790,7 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {// Check that the driver read area is large enough for the message. if slice_1.len () + slice_2.len () < payload_length { + self.poisoned.set (true );return Err (EIO ); }
@@ -805,6 +819,7 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { "GSP RPC: receive: Call {} - bad checksum\n", header.sequence () ); + self.poisoned.set (true );return Err (EIO ); }
@@ -830,8 +845,8 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {/// # Errors /// /// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. -/// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the -/// message queue. +/// - `EIO` if the queue is poisoned or the message fails framing or checksum validation (see +/// [`Self::wait_for_msg`]), or if the matched message is too short for `M::Message`. /// - `ERANGE` if the message was not the awaited reply. /// /// Error codes returned by [`MessageFromGsp::read`] are propagated as-is.
@@ -850,22 +865,26 @@ fn receive_msg<M: MessageFromGsp>(let func_matches =matches! (function,Ok (f)if f ==M ::FUNCTION );let matched = func_matches && expected_seq.is_none_or (|expected| seq == expected); -// Every path must advance the read pointer past this message. +// Every path must advance the read pointer past this message, including a failed decode. let result =if matched { -let (cmd, contents_1) =M ::Message ::from_bytes_prefix (message.contents.0 ).ok_or (EIO )?; -let mut sbuffer =SBufferIter ::new_reader ([contents_1, message.contents.1 ]); - -M ::read (cmd, &mut sbuffer) - .map_err (|e| e.into ()) - .inspect (|_| { -if !sbuffer.is_empty () { -dev_warn! ( - &self.dev, -"GSP message {:?} has unprocessed data\n" , -M ::FUNCTION - ); - } - }) +match M ::Message ::from_bytes_prefix (message.contents.0 ) { +Some ((cmd, contents_1)) => { +let mut sbuffer =SBufferIter ::new_reader ([contents_1, message.contents.1 ]); + +M ::read (cmd, &mut sbuffer) + .map_err (|e| e.into ()) + .inspect (|_| { +if !sbuffer.is_empty () { +dev_warn! ( + &self.dev, +"GSP message {:?} has unprocessed data\n" , +M ::FUNCTION + ); + } + }) + } +None =>Err (EIO ), + } }else {Err (ERANGE ) };
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 10/15] gpu: nova-core: recover the GSP receive path from corrupt framing
On Sat Aug 29, 2026 at 10:33 AM JST, John Hubbard wrote:
<...>
Quoted 19 lines
drivers/gpu/nova-core/gsp/cmdq.rs +6
-4@@ -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()),
drivers/gpu/nova-core/gsp/cmdq.rs fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { · line 777
Quoted 6 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2
-1@@ -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 );
We probably want to dev_err some error here, or the queue will just stop working without explanation.
drivers/gpu/nova-core/gsp/cmdq.rs fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { · line 793
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3
-0+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 );
Same here. Maybe we can have a `fn poison(&self, reason:
fmt::Arguments<'_>) -> Error that performs the log and returns EIO` for convenience?
PATCH v2 11/15 gpu: nova-core: bound a GSP wait by a single deadline
In reply to John HubbardThe 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.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 52 ++++++++++++++++++++++---- drivers/gpu/nova-core/gsp/commands.rs | 8 +--- drivers/gpu/nova-core/gsp/sequencer.rs | 8 +--- 3 files changed, 46 insertions(+), 22 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +44 -8
@@ -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::Replet mut inner = self.inner.lock ();let expected_seq = inner.send_command (bar, command)?; +let deadline =Instant ::<Monotonic >::now () +Self ::RECEIVE_TIMEOUT ;loop { -match inner.receive_msg ::<M ::Reply >(Self ::RECEIVE_TIMEOUT ,Some (expected_seq)) { +let remaining = deadline -Instant ::<Monotonic >::now (); +if remaining.is_negative () { +break Err (ETIMEDOUT ); + } +match inner.receive_msg ::<M ::Reply >(remaining,Some (expected_seq)) {Ok (reply) =>break Ok (reply),Err (ERANGE ) =>continue ,Err (e) =>break Err (e),
@@ -600,17 +610,43 @@ pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul self.inner.lock ().send_command (bar, command).map (|_| ()) } -/// Receive a message from the GSP. +/// Receive a message from the GSP, matching on the function code alone. /// -/// Matches on the function code alone, for a caller awaiting an unsolicited GSP event rather -/// than a reply to a command. See [`CmdqInner::receive_msg`]. -pub (crate )fn receive_msg <M :MessageFromGsp >(&self, timeout:Delta ) ->Result <M > +/// Returns `ERANGE` if the message that arrives is not of type `M`. See +/// [`CmdqInner::receive_msg`]. +fn receive_msg <M :MessageFromGsp >(&self, timeout:Delta ) ->Result <M >where // This allows all error types, including `Infallible`, to be used for `M::InitError`. Error :From <M ::InitError >, { self.inner.lock ().receive_msg (timeout,None ) } + +/// Waits for an unsolicited GSP event of type `M`, dispatching any other event that arrives +/// first. +/// +/// # Errors +/// +/// - `ETIMEDOUT` if the event does not arrive within [`Self::RECEIVE_TIMEOUT`] of the call, +/// however many other events are dispatched while waiting. +pub (crate )fn await_msg <M :MessageFromGsp >(&self) ->Result <M > +where +// This allows all error types, including `Infallible`, to be used for `M::InitError`. +Error :From <M ::InitError >, + { +let deadline =Instant ::<Monotonic >::now () +Self ::RECEIVE_TIMEOUT ; +loop { +let remaining = deadline -Instant ::<Monotonic >::now (); +if remaining.is_negative () { +break Err (ETIMEDOUT ); + } +match self.receive_msg ::<M >(remaining) { +Ok (msg) =>break Ok (msg), +Err (ERANGE ) =>continue , +Err (e) =>break Err (e), + } + } + } }/// Inner mutex protected state of [`Cmdq`].
drivers/gpu/nova-core/gsp/commands.rs +1 -7
@@ -188,13 +188,7 @@ fn read(/// Waits for GSP initialization to complete. pub (crate )fn wait_gsp_init_done (cmdq: &Cmdq ) ->Result { -loop { -match cmdq.receive_msg ::<GspInitDone >(Cmdq ::RECEIVE_TIMEOUT ) { -Ok (_) =>break Ok (()), -Err (ERANGE ) =>continue , -Err (e) =>break Err (e), - } - } + cmdq.await_msg ::<GspInitDone >().map (|_| ()) }/// The `GetGspStaticInfo` command.
drivers/gpu/nova-core/gsp/sequencer.rs +1 -7
@@ -343,13 +343,7 @@ pub(crate) fn run( libos: &'a Coherent<[LibosMemoryRegionInitArgument]>, bootloader_app_version: u32, ) -> Result { -let seq_info =loop { -match cmdq.receive_msg ::<GspSequence >(Cmdq ::RECEIVE_TIMEOUT ) { -Ok (seq_info) =>break seq_info, -Err (ERANGE ) =>continue , -Err (e) =>return Err (e), - } - }; +let seq_info = cmdq.await_msg ::<GspSequence >()?; let sequencer = GspSequencer { bar: ctx.bar,
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 11/15] gpu: nova-core: bound a GSP wait by a single deadline
On Sat Aug 29, 2026 at 10:33 AM JST, John Hubbard wrote:
<...>
Quoted 17 lines
drivers/gpu/nova-core/gsp/cmdq.rs +4
-4@@ -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 >, {
drivers/gpu/nova-core/gsp/cmdq.rs pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul · line 631
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +8
-0self.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.
We also return the errors from receive_msg, this should be documented.
Quoted 8 lines
drivers/gpu/nova-core/gsp/cmdq.rs +8
-0+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 ();
drivers/gpu/nova-core/gsp/cmdq.rs pub(crate) fn send_command_no_wait<M>(&self, bar: Bar0<'_>, command: M) -> Resul · line 649
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +10
-0+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), + } + } + }
Note that this will release the lock between calls to receive_msg. If a send_command comes in from another thread at the wrong time, that one *does* keep the lock until it has received the reply it expects - so our reply will be consumed silently and we will timeout.
I guess you can just remove Cmdq::receive_msg here: acquire the lock at the beginning of await_msg, and call inner.receive_msg from it directly. The GSP queue is synchronous by design anyway, so that's what we want even if it looks strange to hold a lock for potentially 5 seconds.
PATCH v2 12/15 gpu: nova-core: drive GSP events with the SWGEN0 interrupt
In reply to John HubbardThe 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.
--- 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
drivers/gpu/nova-core/driver.rs +51 -4
@@ -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: &'boundSubtreeVectors <'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",
drivers/gpu/nova-core/falcon/gsp.rs +31 -4
@@ -14,6 +14,7 @@ };use crate ::{ + driver::Bar0 , falcon::{Falcon ,FalconEngine ,
@@ -36,14 +37,40 @@ impl RegisterBase<PFalcon2Base> for Gsp {impl FalconEngine for Gsp {} +impl Gsp { +/// Clears the GSP falcon SWGEN0 interrupt latch. +/// +/// The latch holds until it is cleared, and the GSP drives no new edge into the interrupt +/// tree while it is set, so a caller that consumed a notification by any means other than the +/// interrupt handler must clear it or no further notification is delivered. +pub (crate )fn clear_swgen0_intr (bar:Bar0 <'_>) { + bar.write ( +WithBase ::of ::<Self >(), + regs::NV_PFALCON_FALCON_IRQSCLR ::zeroed ().with_swgen0 (true ), + ); + } + +/// Reads the GSP falcon interrupt status, clearing the SWGEN0 latch if it was set. +/// +/// Returns the status as it was read, before the clear. The GSP raises SWGEN0 when it has +/// posted messages in the GSP-to-CPU queue. The interrupt tree routes every falcon cause to +/// a single vector, so the rest of the status identifies a cause other than a posted message. +pub (crate )fn take_swgen0_intr (bar:Bar0 <'_>) -> regs::NV_PFALCON_FALCON_IRQSTAT { +let status = bar.read (regs::NV_PFALCON_FALCON_IRQSTAT ::of ::<Self >()); + +if status.swgen0 () { +Self ::clear_swgen0_intr (bar); + } + + status + } +} +impl <'a>Falcon <'a,Gsp > {/// Clears the SWGEN0 bit in the Falcon's IRQ status clear register to /// allow GSP to signal CPU for processing new messages in message queue. pub (crate )fn clear_swgen0_intr (&self) { - self.bar.write ( -WithBase ::of ::<Gsp >(), - regs::NV_PFALCON_FALCON_IRQSCLR ::zeroed ().with_swgen0 (true ), - ); +Gsp ::clear_swgen0_intr (self.bar); }/// Checks if GSP reload/resume has completed during the boot process.
drivers/gpu/nova-core/gpu.rs +20 -2
@@ -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.
drivers/gpu/nova-core/gsp.rs +11 -6
@@ -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, Errorpub (crate )fn get_static_info (&self, bar:Bar0 <'_>) ->Result <commands::GetGspStaticInfoReply > { self.cmdq.send_command (bar, commands::GetGspStaticInfo ) } + +/// Returns a shared handle to the GSP command queue. +pub (crate )fn cmdq (&self) ->Arc <Cmdq > { + self.cmdq.clone () + } }/// Opaque bundle required to unload the GSP. Created by [`Gsp::boot`], consumed by [`Gsp::unload`].
drivers/gpu/nova-core/gsp/cmdq.rs +42 -0
52 lines not on this page · raw message
drivers/gpu/nova-core/irq.rs +1 -0
@@ -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;
drivers/gpu/nova-core/irq/doorbell_test.rs +19 -15
@@ -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: &'aSubtreeVectors <'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 ());
drivers/gpu/nova-core/irq/gsp.rs new file +215 -0
215 lines not on this page · raw message
drivers/gpu/nova-core/irq/interrupt_tree.rs +0 -1
@@ -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 indexin 0 ..self.leaves.into_raw () {if let Some (leaf) =LeafIndex ::try_new (index) {
drivers/gpu/nova-core/nova_core.rs +0 -1
@@ -17,7 +17,6 @@mod fsp;mod gpu;mod gsp; -#[cfg_attr(not( CONFIG_NOVA_CORE_IRQ_SELFTEST ), expect(dead_code))] mod irq;mod mctp;#[macro_use]
drivers/gpu/nova-core/regs.rs +4 -0
@@ -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; }
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 12/15] gpu: nova-core: drive GSP events with the SWGEN0 interrupt
Hi John,
I am still looking at this one in depth, but wanted to post what I've found so far before going to sleep.
Quoted 19 lines · John Hubbard
The GSP posts events, logs and error records to the GSP-to-CPU queue and raises the falcon SWGEN0 output. GSP boot polls for its own notifications, which leaves the latch set and pending bits in the tree.
nova-core drained the queue only while polling for a command reply, so an event sat unread until the next command was sent.
Service the queue from a threaded handler on the GSP notification vector. The top half runs in hard interrupt context and touches only
registers: it clears the GIN leaf, takes the falcon's SWGEN0 latch and rearms PCI delivery. Draining the queue takes the command-queue mutex, which can sleep, so the top half wakes the IRQ thread to do it.Quiesce the tree, clear the latch and rearm PCI delivery before registering the handler, so none of that boot state reaches it. Pre-Hopper MSI rearms through a configuration-space write that the tree drain does not perform, and an interrupt delivered before probe leaves delivery un-armed.
Quoted 4 lines
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.
Could the vector allocation have been put at its final place since patch 7?
<...>
Quoted 30 lines
drivers/gpu/nova-core/gpu.rs +4
-1@@ -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>) { }
drivers/gpu/nova-core/gpu.rs fn drop(self: Pin<&mut Self>) { · line 337
Quoted 10 lines
drivers/gpu/nova-core/gpu.rs +9
-0impl <'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 () + }
I would expect that the interrupt rework series by Danilo would allow us to borrow a reference to the Cmdq for the interrupt handler. Is there a hard reason we cannot do it and need an Arc? GspInterrupt already borrows Bar0, so this should not be different.
If the Arc is really needed (which I doubt, but still going through the code), the Arc refactor should be in its own patch to make this one a bit lighter and easier to review.
<...>
drivers/gpu/nova-core/irq/doorbell_test.rs
Quoted 4 lines
drivers/gpu/nova-core/irq/doorbell_test.rs +0
-0
I would not expect doorbell_test.rs to be affected by this patch - please see if this can be squashed into patch 7.
<...>
Quoted 36 lines
drivers/gpu/nova-core/irq/gsp.rs new file +30
-0@@ -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 ,// +};
drivers/gpu/nova-core/irq/gsp.rs line 40
Quoted 10 lines
drivers/gpu/nova-core/irq/gsp.rs new file +10
-0+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,
nit: "GSP-RM pins the ..." for alignment with the rest of the docs.
Quoted 30 lines
drivers/gpu/nova-core/irq/gsp.rs new file +30
-0+/// 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 ); +} +
drivers/gpu/nova-core/irq/gsp.rs line 80
Quoted 10 lines
drivers/gpu/nova-core/irq/gsp.rs new file +10
-0+/// 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 >,
As mentioned above, I strongly suspect this can be a &'a Cmdq. Which would be great as it would make the whole Arc refactoring unnecessary.
drivers/gpu/nova-core/irq/gsp.rs line 84
Quoted 4 lines
drivers/gpu/nova-core/irq/gsp.rs new file +4
-0+/// 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>,
This can be a &'a device::Device (tested locally).
Will post some more tomorrow but this is what I have so far. :)
Danilo Krummrich
maintainerRe: [PATCH v2 12/15] gpu: nova-core: drive GSP events with the SWGEN0 interrupt
Quoted 5 lines · Alexandre Courbot
Quoted 5 lines
drivers/gpu/nova-core/irq/gsp.rs new file +5
-0+/// 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]
Quoted 8 lines
drivers/gpu/nova-core/irq/gsp.rs line 80
Quoted 5 lines
drivers/gpu/nova-core/irq/gsp.rs new file +5
-0+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 >,As mentioned above, I strongly suspect this can be a
&'a Cmdq. Which would be great as it would make the wholeArcrefactoring unnecessary.
Yeah, this does not need a reference count, let's not introduce them where we don't actually need them.
Thanks,
Danilo
Alexandre Courbot
maintainerRe: [PATCH v2 12/15] gpu: nova-core: drive GSP events with the SWGEN0 interrupt
In reply to John HubbardOn Sat Aug 29, 2026 at 10:33 AM JST, John Hubbard wrote:
<...>
Quoted 33 lines
drivers/gpu/nova-core/driver.rs +22
-3@@ -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,
drivers/gpu/nova-core/driver.rs fn probe<'bound>( · line 135
Quoted 10 lines
drivers/gpu/nova-core/driver.rs +10
-0+ 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 ()?; + },
Can't these last 3 blocks (quiesce, _gsp_irq, and cmdq drain) be moved inside Gpu? It seems to make sense in terms of ownership, as the Gpu would own its interrupt handler, and things would be much cleaner as
well: there would be no need for the unsafe bar lifetime conversion, vectors_ref, or the chipset and cmdq accessor methods.
Just gave it a quick try locally and it builds fine (with a net -20 LoCs), and AFAICT drop order is also preserved.
Pushing a bit further I could also put vectors into Gpu, which again makes sense to me ownership-wise (because the set of interrupts we want to serve might depend on e.g. the GPU architecture). The only drawback is that I had to reintroduce vectors_ref, but that's a small and temporary hack. I'd say this belongs in gpu.rs as well.
(after looking some more at the code) Ok, I'm now completely convinced this belongs here. We could put these blocks right after gsp_resources (which boots the GSP), with the benefit that the GSP interrupts will be working to build gsp_static_info, which is obtained by sending a regular GSP message! Right now we are still polling to build it, but with the IRQ handler ready we could just wait for the signal to read the reply. I am not saying this should be done for this series (let's do it as a follow-up), but this is to illustrate that this is where the IRQ setup should be done, not in driver.rs.
<...>
Quoted 9 lines
drivers/gpu/nova-core/irq/gsp.rs new file +9
-0+/// 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.
drivers/gpu/nova-core/irq/gsp.rs line 69
Quoted 10 lines
drivers/gpu/nova-core/irq/gsp.rs new file +10
-0+// 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 ); +}
The clear_swgen0_intr bit is interesting - note that we already do it in Gpu::new (I had no idea why, now I understand! :)), so that vestigial one can be removed (which should also simplify falcon/gsp.rs a bit).
It also looks like this function could become a method of SubtreeVectors that resets the tree covered by the allocation.
drivers/gpu/nova-core/irq/gsp.rs line 76
Quoted 7 lines
drivers/gpu/nova-core/irq/gsp.rs new file +7
-0+ +/// 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> {
This type doesn't need #[pin_data]. Its constructor can also return just Self - you will just need to wrap its call as a parameter of irq::ThreadedRegistration::new into an Ok(...) to make it happy, but it's simpler overall.
I'll stop here for this revision - I suppose there are more minor things, but it will be easier to discover them with the bigger cleanups applied.
Re: [PATCH v2 12/15] gpu: nova-core: drive GSP events with the SWGEN0 interrupt
Quoted 6 lines · Alexandre Courbot
On Sat Aug 29, 2026 at 10:33 AM JST, John Hubbard wrote:
<...>I'll stop here for this revision - I suppose there are more minor things, but it will be easier to discover them with the bigger cleanups applied.
I'm going to post a v3 with all of your and Danilo's feedback incorporated.
I've been fussing over the interrupts.rst document a bit more, btw, and maybe it helped a little with readability, we'll see.
thanks,
Signature · 1 line
John Hubbard
PATCH v2 13/15 gpu: nova-core: retrigger the GSP falcon and clear every latched cause
In reply to John HubbardA 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.
--- 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(-)
drivers/gpu/nova-core/falcon/gsp.rs +36 -0
@@ -16,11 +16,13 @@use crate ::{ driver::Bar0 , falcon::{ + hal,Falcon ,FalconEngine ,PFalcon2Base ,PFalconBase ,// }, + gpu::Chipset , regs, };
@@ -64,6 +66,40 @@ pub(crate) fn take_swgen0_intr(bar: Bar0<'_>) -> regs::NV_PFALCON_FALCON_IRQSTAT status } + +/// Masks and clears every interrupt cause set in `status`. +/// +/// A masked cause leaves the falcon's enabled set, so it neither raises the tree again nor +/// holds that set non-empty. +pub (crate )fn mask_and_clear_intr (bar:Bar0 <'_>, status: regs::NV_PFALCON_FALCON_IRQSTAT ) { +let causes = status.into_raw (); + + bar.write ( +WithBase ::of ::<Self >(), + regs::NV_PFALCON_FALCON_IRQMCLR ::zeroed ().with_value (causes), + ); + bar.write ( +WithBase ::of ::<Self >(), + regs::NV_PFALCON_FALCON_IRQSCLR ::from (causes), + ); + } + +/// Re-emits the falcon's enabled interrupt causes into the interrupt tree. +/// +/// The falcon signals the tree on a transition of its enabled causes, so clearing the tree +/// leaf while a cause is still latched leaves no transition and no further vector. +/// +/// Does nothing on Turing, whose falcons do not implement the register. +pub (crate )fn retrigger_intr (bar:Bar0 <'_>, chipset:Chipset ) { +if !hal::has_intr_retrigger (chipset) { +return ; + } + + bar.write ( +WithBase ::of ::<Self >().at (0 ), + regs::NV_PFALCON_FALCON_INTR_RETRIGGER ::zeroed ().with_trigger (true ), + ); + } }impl <'a>Falcon <'a,Gsp > {
drivers/gpu/nova-core/falcon/hal.rs +8 -0
@@ -72,6 +72,14 @@ fn signature_reg_fuse_version(fn load_method (&self) ->LoadMethod ; } +/// Returns whether `chipset`'s falcons implement `NV_PFALCON_FALCON_INTR_RETRIGGER`. +/// +/// Turing falcons do not. Ampere and later do, including GA100, whose falcon otherwise uses the +/// Turing HAL, so this is keyed on the architecture rather than provided through [`FalconHal`]. +pub (crate )fn has_intr_retrigger (chipset:Chipset ) ->bool { + !matches! (chipset.arch (),Architecture ::Turing ) +} +/// Returns a boxed falcon HAL adequate for `chipset`. /// /// We use a heap-allocated trait object instead of a statically defined one because the
drivers/gpu/nova-core/irq/gsp.rs +39 -22
105 lines not on this page · raw message
drivers/gpu/nova-core/regs.rs +20 -0
@@ -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;
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 13/15] gpu: nova-core: retrigger the GSP falcon and clear every latched cause
On Sat Aug 29, 2026 at 10:33 AM JST, John Hubbard wrote:
<...>
Quoted 17 lines
drivers/gpu/nova-core/irq/gsp.rs +3
-3@@ -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 ();
drivers/gpu/nova-core/irq/gsp.rs line 63
Quoted 10 lines
drivers/gpu/nova-core/irq/gsp.rs +4
-5-// 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);
This code was introduced in the previous patch and is now immediately moved around, and the comments for the two versions contradict each other. This patch's order seems to be the correct one, so let's use it from the get-go.
I guess this stems from the general ordering problem with this patch: if its new falcon registers were introduced before patch 12, then patch 12 could be written in its final form instead of having its code amended right away. It would be nice if you could reorder things this way for v3.
Quoted 55 lines
drivers/gpu/nova-core/irq/gsp.rs +17
-10// 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
drivers/gpu/nova-core/irq/gsp.rs fn handle(&self) -> irq::ThreadedIrqReturn { · line 142
Quoted 10 lines
drivers/gpu/nova-core/irq/gsp.rs +3
-3+// 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);
Is this correct? My Clanker told me (and looking closer it seems to be correct) that IRQSTAT also reports causes that are masked, or routed to the RISC-V core itself rather than to the host (i.e. GSP-RM's own interrupts), and that OpenRM filters these out: kgspService_TU102() gets its status from kflcnGetPendingHostInterrupts(), which for a RISC-V falcon is FALCON_IRQSTAT & PRISCV_RISCV_IRQMASK & PRISCV_RISCV_IRQDEST. Without that filter, any GSP-internal cause that happens to be latched when SWGEN0 fires gets reported here, then cleared and masked out from under the firmware.
Also in RISC-V mode the mask gating host routing appears to be PRISCV_RISCV_IRQMASK, not FALCON_IRQMASK - OpenRM never writes the latter for the GSP. So the comment about the tree routing every falcon cause here also seems inaccurate.
PATCH v2 14/15 gpu: nova-core: add KUnit tests for the interrupt tree and HALs
In reply to John HubbardNeither 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.
--- 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(-)
drivers/gpu/nova-core/falcon/hal.rs +24 -0
@@ -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 chipsetin [ +Chipset ::GA100 , +Chipset ::GA102 , +Chipset ::AD102 , +Chipset ::GH100 , +Chipset ::GB100 , +Chipset ::GB202 , + ] { +assert! (has_intr_retrigger (chipset)); + } + } +}
drivers/gpu/nova-core/irq/hal.rs +82 -1
92 lines not on this page · raw message
drivers/gpu/nova-core/irq/interrupt_tree.rs +110 -0
113 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 15/15 gpu: nova-core: document the GIN interrupt controller and GSP events
In reply to John HubbardThe 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.
--- Documentation/gpu/nova/core/interrupts.rst | 686 +++++++++++++++++++++ Documentation/gpu/nova/index.rst | 1 + 2 files changed, 687 insertions(+) create mode 100644 Documentation/gpu/nova/core/interrupts.rst
Documentation/gpu/nova/core/interrupts.rst new file +686 -0
@@ -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.
Documentation/gpu/nova/index.rst +1 -0
@@ -34,3 +34,4 @@ vGPU manager VFIO driver and the nova-drm driver. core/fwsec core/falcon core/tlv + core/interrupts
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 15/15] gpu: nova-core: document the GIN interrupt controller and GSP events
On Sat Aug 29, 2026 at 10:33 AM JST, John Hubbard wrote:
<...>
Quoted 11 lines
Documentation/gpu/nova/core/interrupts.rst new file +11
-0+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. +
Documentation/gpu/nova/core/interrupts.rst line 42
Quoted 10 lines
Documentation/gpu/nova/core/interrupts.rst new file +10
-0+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:
Coming to this patch series without any preliminary knowledge of interrupts handling on NVIDIA GPUs, I would have found it useful if leaf, subtree, and tree were also defined here.
Quoted 14 lines
Documentation/gpu/nova/core/interrupts.rst new file +14
-0+ +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
Documentation/gpu/nova/core/interrupts.rst line 66
Quoted 10 lines
Documentation/gpu/nova/core/interrupts.rst new file +10
-0+ 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``.
IIUC a disabled vector's pending bits doesn't contribute to its subtree's TOP bit. Something like "A disabled vector's pending bit doesn't signal its leaf in ``TOP``" sounds more accurate to me.