* [RFC PATCH v2] gpu: nova-core: gsp: retain debugfs logs on teardown and capture logpmu
@ 2026-12-02 2:50 Agustín Pereira
2026-12-02 2:50 ` [RFC PATCH v2] gpu: nova-core: gsp: add RM alloc/control/free RPCs and client/device API Agustín Pereira
2026-12-02 3:37 ` [RFC PATCH v2] gpu: nova-core: gsp: retain debugfs logs on teardown and capture logpmu John Hubbard
0 siblings, 2 replies; 3+ messages in thread
From: Agustín Pereira @ 2026-12-02 2:50 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: David Airlie, Simona Vetter, Miguel Ojeda, nova-gpu, dri-devel,
rust-for-linux, linux-kernel, Agustín Pereira
Currently nova-core exposes the GSP-RM logging buffers (`loginit`,
`logintr`, and `logrm`) via a `debugfs::Scope` tied to `Gsp`. When
`Gsp::boot()` fails during `probe()` or when the device is unbound, the
scope is dropped immediately and its `debugfs` entries are removed,
making post-mortem inspection of firmware boot failures impossible. In
addition, `UCODE_LIBOS_PRINT` events from the PMU are silently discarded
by the command queue, so no `logpmu` buffer is captured or exposed.
Move the GSP logging infrastructure into a dedicated `gsp::logs` module
and address both gaps:
- Capture `MsgFunction::UcodeLibOsPrint` events in `handle_event()`
before advancing the queue read pointer, validating the
`rpc_ucode_libos_print_v1e_08` header (PMU engine class `0xf3d722` and
payload size `<= GSP_PAGE_SIZE`) and storing the latest dump in a
mutex-protected `PmuLogBuffer` exposed as `logpmu` in `debugfs`.
- Add a boolean `keep_gsp_logging` module parameter (default `false`) and
a module-scoped `RETAINED_LOGS` global mutex. Relying on `debugfs::Scope`
dropping its `debugfs` directory entry before its inner `LogBuffers`,
`LogBuffers::drop` validates each DMA buffer's put pointer
(`1 <= pp < LOG_BUFFER_SIZE / size_of::<u64>()`) and snapshots any
non-empty buffers (including `logpmu`) into regular kernel memory
(`KVVec<u8>`) before re-publishing them under
`/sys/kernel/debug/nova-core` until module unload or a subsequent
`probe()` of the same device.
- Add KUnit unit tests (`nova_core_gsp_logs`) covering put-pointer
validation, ring-wraparound PMU event capture, zero-padding on shorter
subsequent dumps, and rejection of malformed events without clobbering
existing data.
Testing:
- Compiled `drivers/gpu/nova-core.o` and `drivers/gpu/nova-drm.o` with
`LLVM=1 W=1 CLIPPY=1` (`CONFIG_RUST=y`, `CONFIG_NOVA_CORE=m`,
`CONFIG_DRM_NOVA=m`) under both (`CONFIG_DEBUG_FS=y`, `CONFIG_KUNIT=y`,
`CONFIG_NOVA_CORE_SELFTESTS=y`) and (`CONFIG_DEBUG_FS=n`,
`CONFIG_KUNIT=n`, `CONFIG_NOVA_CORE_SELFTESTS=n`) with zero warnings.
- Verified formatting with `rustfmt --check` and patch style with
`scripts/checkpatch.pl`.
- Tested on NVIDIA GeForce RTX 4070 Laptop GPU (AD106M, Ada, rev a.1)
with r570.144 TLV firmware on 7.4.0-rc5: verified non-empty `loginit`,
`logintr`, `logrm`, and `logpmu` capture, bit-for-bit identical SHA-256
checksums across PCI `unbind` with `keep_gsp_logging=1`, clean re-bind
without `EEXIST`, and clean module unload.
This change was drafted with the assistance of an AI coding assistant.
Signed-off-by: Agustín Pereira <agustin.pereira.ro@gmail.com>
---
Changes in v2:
- Use FromBytes::from_bytes_copy() in PmuLogBuffer::capture_event() to avoid
alignment failures on the stack buffer (reported by Sashiko AI review).
- Replace RETAINED_LOGS.lock().clear() with *RETAINED_LOGS.lock() = KVec::new()
in DebugfsRootGuard::drop() so the KVec backing buffer is freed on module
unload (reported by Sashiko AI review).
- Tested on real hardware: NVIDIA GeForce RTX 4070 Laptop GPU (AD106M, Ada,
rev a.1, r570.144 TLV firmware) on 7.4.0-rc5; verified non-empty loginit,
logintr, logrm, and logpmu capture, bit-for-bit identical SHA-256 across
PCI unbind, clean re-bind without EEXIST, and clean module unload.
drivers/gpu/nova-core/gsp.rs | 121 ++---
drivers/gpu/nova-core/gsp/cmdq.rs | 46 +-
drivers/gpu/nova-core/gsp/fw.rs | 36 ++
.../gpu/nova-core/gsp/fw/r570_144/bindings.rs | 7 +
drivers/gpu/nova-core/gsp/logs.rs | 450 ++++++++++++++++++
drivers/gpu/nova-core/nova_core.rs | 56 ++-
drivers/gpu/nova-core/sbuffer.rs | 1 -
7 files changed, 627 insertions(+), 90 deletions(-)
create mode 100644 drivers/gpu/nova-core/gsp/logs.rs
diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs
index dda58095f40b..69c332bba739 100644
--- a/drivers/gpu/nova-core/gsp.rs
+++ b/drivers/gpu/nova-core/gsp.rs
@@ -12,18 +12,16 @@
CoherentView,
DmaAddress, //
},
- io::{
- io_project,
- io_write,
- Io, //
- },
+ io::io_write,
pci,
- prelude::*, //
+ prelude::*,
+ sync::Arc, //
};
pub(crate) mod cmdq;
pub(crate) mod commands;
mod fw;
+pub(crate) mod logs;
mod regs;
mod sequencer;
@@ -46,7 +44,12 @@
gpu::Chipset,
gsp::{
cmdq::Cmdq,
- fw::GspArgumentsPadded, //
+ fw::GspArgumentsPadded,
+ logs::{
+ LogBuffer,
+ LogBuffers,
+ PmuLogBuffer, //
+ }, //
},
num,
vgpu::VgpuManager, //
@@ -77,10 +80,6 @@ pub(crate) fn dev(&self) -> &'gpu device::Device<device::Bound> {
}
}
-/// Number of GSP pages to use in a RM log buffer.
-const RM_LOG_BUFFER_NUM_PAGES: usize = 0x10;
-const LOG_BUFFER_SIZE: usize = RM_LOG_BUFFER_NUM_PAGES * GSP_PAGE_SIZE;
-
/// Array of page table entries, as understood by the GSP bootloader.
#[repr(C)]
#[derive(FromBytes, IntoBytes)]
@@ -101,66 +100,26 @@ fn init(view: CoherentView<'_, Self>, start: DmaAddress) -> Result<()> {
}
}
-/// The logging buffers are byte queues that contain encoded printf-like
-/// messages from GSP-RM. They need to be decoded by a special application
-/// that can parse the buffers.
-///
-/// The 'loginit' buffer contains logs from early GSP-RM init and
-/// exception dumps. The 'logrm' buffer contains the subsequent logs. Both are
-/// written to directly by GSP-RM and can be any multiple of GSP_PAGE_SIZE.
-///
-/// The physical address map for the log buffer is stored in the buffer
-/// itself, starting with offset 1. Offset 0 contains the "put" pointer (pp).
-/// Initially, pp is equal to 0. If the buffer has valid logging data in it,
-/// then pp points to index into the buffer where the next logging entry will
-/// be written. Therefore, the logging data is valid if:
-/// 1 <= pp < sizeof(buffer)/sizeof(u64)
-struct LogBuffer<'a>(Coherent<'a, [u8; LOG_BUFFER_SIZE]>);
-
-impl<'a> LogBuffer<'a> {
- /// Creates a new `LogBuffer` mapped on `dev`.
- fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
- let obj = Self(Coherent::zeroed(dev, GFP_KERNEL)?);
-
- let start_addr = obj.0.dma_address();
-
- let pte_view = io_project!(
- obj.0,
- [build: size_of::<u64>()..][build: ..RM_LOG_BUFFER_NUM_PAGES * size_of::<u64>()]
- )
- .try_cast::<PteArray<RM_LOG_BUFFER_NUM_PAGES>>()?;
- PteArray::init(pte_view, start_addr)?;
-
- Ok(obj)
- }
-}
-
-struct LogBuffers<'a> {
- /// Init log buffer.
- loginit: LogBuffer<'a>,
- /// Interrupts log buffer.
- logintr: LogBuffer<'a>,
- /// RM log buffer.
- logrm: LogBuffer<'a>,
-}
-
/// GSP runtime data.
#[pin_data]
pub(crate) struct Gsp<'gsp> {
/// Libos arguments.
pub(crate) libos: Coherent<'gsp, [LibosMemoryRegionInitArgument]>,
- /// Log buffers, optionally exposed via debugfs.
- #[pin]
- logs: debugfs::Scope<LogBuffers<'gsp>>,
/// Command queue.
+ ///
+ /// Declared before `logs` so the command queue drops its handle to the PMU
+ /// log buffer before `logs` snapshots and tears down its `debugfs` entries.
#[pin]
pub(crate) cmdq: Cmdq<'gsp>,
+ /// Log buffers, optionally exposed via `debugfs` and retained on teardown.
+ #[pin]
+ logs: debugfs::Scope<LogBuffers<'gsp>>,
/// RM arguments.
rmargs: Coherent<'gsp, GspArgumentsPadded>,
}
impl<'gsp> Gsp<'gsp> {
- // Creates an in-place initializer for a `Gsp` manager for `pdev`.
+ /// Creates an in-place initializer for a [`Gsp`] manager for `pdev`.
pub(crate) fn new(
pdev: &'gsp pci::Device<device::Bound>,
bar: Bar0<'gsp>,
@@ -171,12 +130,17 @@ pub(crate) fn new(
let loginit = LogBuffer::new(dev)?;
let logintr = LogBuffer::new(dev)?;
let logrm = LogBuffer::new(dev)?;
+ let logpmu = Arc::pin_init(PmuLogBuffer::new(), GFP_KERNEL)?;
+
+ // Remove any retained post-mortem log directory for this device
+ // before publishing the live `debugfs` entries.
+ crate::clear_retained_logs_for(dev.name());
// Initialise the logging structures. The OpenRM equivalents are in:
// _kgspInitLibosLoggingStructures (allocates memory for buffers)
// kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array)
Ok(try_pin_init!(Self {
- cmdq <- Cmdq::new(dev, bar),
+ cmdq <- Cmdq::new(dev, bar, logpmu.clone()),
rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
libos: {
let mut libos = CoherentBox::zeroed_slice(
@@ -185,34 +149,31 @@ pub(crate) fn new(
GFP_KERNEL,
)?;
- libos.init_at(0, LibosMemoryRegionInitArgument::new("LOGINIT", &loginit.0))?;
- libos.init_at(1, LibosMemoryRegionInitArgument::new("LOGINTR", &logintr.0))?;
- libos.init_at(2, LibosMemoryRegionInitArgument::new("LOGRM", &logrm.0))?;
+ libos.init_at(
+ 0,
+ LibosMemoryRegionInitArgument::new("LOGINIT", loginit.dma_coherent()),
+ )?;
+ libos.init_at(
+ 1,
+ LibosMemoryRegionInitArgument::new("LOGINTR", logintr.dma_coherent()),
+ )?;
+ libos.init_at(
+ 2,
+ LibosMemoryRegionInitArgument::new("LOGRM", logrm.dma_coherent()),
+ )?;
libos.init_at(3, LibosMemoryRegionInitArgument::new("RMARGS", rmargs))?;
libos.into()
},
logs <- {
- let log_buffers = LogBuffers {
- loginit,
- logintr,
- logrm,
- };
-
- #[allow(static_mut_refs)]
- // SAFETY: `DEBUGFS_ROOT` is created before driver registration and cleared
- // after driver unregistration, so no probe() can race with its modification.
- //
- // PANIC: `DEBUGFS_ROOT` cannot be `None` here. It is set before driver
- // registration and cleared after driver unregistration, so it is always
- // `Some` for the entire lifetime that probe() can be called.
- let log_parent: &debugfs::Dir = unsafe { crate::DEBUGFS_ROOT.as_ref() }
- .expect("DEBUGFS_ROOT not initialized");
+ let log_buffers = LogBuffers::new(dev, loginit, logintr, logrm, logpmu);
+ let log_parent = crate::debugfs_root();
log_parent.scope(log_buffers, dev.name(), |logs, dir| {
- dir.read_binary_file(c"loginit", &logs.loginit.0);
- dir.read_binary_file(c"logintr", &logs.logintr.0);
- dir.read_binary_file(c"logrm", &logs.logrm.0);
+ dir.read_binary_file(c"loginit", logs.loginit.dma_coherent());
+ dir.read_binary_file(c"logintr", logs.logintr.dma_coherent());
+ dir.read_binary_file(c"logrm", logs.logrm.dma_coherent());
+ dir.read_binary_file(c"logpmu", &logs.logpmu);
})
},
}))
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index 1b2f346a237f..f29625ee6910 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -26,6 +26,7 @@
Read,
Write, //
},
+ Arc,
Mutex, //
},
time::{
@@ -56,6 +57,7 @@
MsgqTxHeader,
GSP_MSG_QUEUE_ELEMENT_SIZE_MAX, //
},
+ logs::PmuLogBuffer,
PteArray,
GSP_PAGE_SHIFT,
GSP_PAGE_SIZE, //
@@ -529,6 +531,7 @@ impl<'cmdq> Cmdq<'cmdq> {
pub(crate) fn new(
dev: &'cmdq device::Device<device::Bound>,
bar: Bar0<'cmdq>,
+ pmu_log: Arc<PmuLogBuffer>,
) -> impl PinInit<Self, Error> + 'cmdq {
pin_init_scope(move || {
let gsp_mem = DmaGspMem::new(dev)?;
@@ -540,6 +543,7 @@ pub(crate) fn new(
bar,
gsp_mem,
seq: 0,
+ pmu_log,
}),
}))
})
@@ -655,6 +659,8 @@ struct CmdqInner<'a> {
seq: u32,
/// Memory area shared with the GSP for communicating commands and messages.
gsp_mem: DmaGspMem<'a>,
+ /// Buffer capturing PMU `UCODE_LIBOS_PRINT` events.
+ pmu_log: Arc<PmuLogBuffer>,
}
impl CmdqInner<'_> {
@@ -882,7 +888,7 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
}
})
} else {
- self.log_event(function, seq);
+ self.handle_event(function, seq, message.contents);
Err(ENOMSG)
};
@@ -926,12 +932,13 @@ fn await_msg<M: MessageFromGsp>(&mut self) -> Result<M>
}
}
- /// Logs an event, meaning a message that no caller was waiting for.
+ /// Handles an event, meaning a message that no caller was waiting for.
///
- /// An OS error or robust-channel record is logged at error level and an unknown function code
- /// at warning level. Every other event is recorded only by the receive trace in
- /// [`Self::wait_for_msg`].
- fn log_event(&self, function: Result<MsgFunction, u32>, seq: u32) {
+ /// An OS error or robust-channel record is logged at error level, a PMU
+ /// `UCODE_LIBOS_PRINT` dump is captured into `logpmu`, and an unknown
+ /// function code is logged at warning level. Every other event is recorded
+ /// only by the receive trace in [`Self::wait_for_msg`].
+ fn handle_event(&self, function: Result<MsgFunction, u32>, seq: u32, contents: (&[u8], &[u8])) {
match function {
Ok(MsgFunction::OsErrorLog) => {
dev_err!(&self.dev, "GSP reported an OS error (seq {})\n", seq);
@@ -943,6 +950,31 @@ fn log_event(&self, function: Result<MsgFunction, u32>, seq: u32) {
seq
);
}
+ Ok(MsgFunction::UcodeLibOsPrint) => match self.pmu_log.capture_event(contents) {
+ Ok(size) => {
+ dev_dbg!(
+ &self.dev,
+ "captured PMU libos print buffer ({} bytes, seq {})\n",
+ size,
+ seq
+ );
+ }
+ Err(ENOMSG) => {
+ dev_dbg!(
+ &self.dev,
+ "ignoring non-PMU libos print event (seq {})\n",
+ seq
+ );
+ }
+ Err(e) => {
+ dev_warn!(
+ &self.dev,
+ "failed to capture PMU libos print event (seq {}): {:?}\n",
+ seq,
+ e
+ );
+ }
+ },
// Nothing to do for the remaining known function codes.
Ok(_) => {}
Err(raw) => {
@@ -975,8 +1007,8 @@ fn drain(&mut self) -> Result {
let function = msg.header.function();
let seq = msg.header.sequence();
+ self.handle_event(function, seq, msg.contents);
self.gsp_mem.advance_cpu_read_ptr(pages);
- self.log_event(function, seq);
}
Ok(())
diff --git a/drivers/gpu/nova-core/gsp/fw.rs b/drivers/gpu/nova-core/gsp/fw.rs
index 918a7ae809eb..8ef96868ace0 100644
--- a/drivers/gpu/nova-core/gsp/fw.rs
+++ b/drivers/gpu/nova-core/gsp/fw.rs
@@ -636,6 +636,42 @@ unsafe impl FromBytes for RunCpuSequencer {}
// SAFETY: Padding is explicit and will not contain uninitialized data.
unsafe impl AsBytes for RunCpuSequencer {}
+/// Class ID identifying the PMU engine in [`UcodeLibOsPrintHeader`].
+const NV_GSP_MSG_EVENT_UCODE_LIBOS_CLASS_PMU: u32 = 0xf3d722;
+
+/// Header of a `UCODE_LIBOS_PRINT` GSP event payload.
+///
+/// The header is followed immediately by [`Self::buf_size`] bytes of raw LIBOS
+/// print buffer data.
+#[repr(transparent)]
+pub(crate) struct UcodeLibOsPrintHeader(bindings::rpc_ucode_libos_print_v1e_08);
+
+static_assert!(size_of::<UcodeLibOsPrintHeader>() == 8);
+
+impl UcodeLibOsPrintHeader {
+ /// Returns the engine class ID encoded in bits `[31:8]` of `ucode_eng_desc`.
+ pub(crate) const fn engine_class(&self) -> u32 {
+ self.0.ucode_eng_desc >> 8
+ }
+
+ /// Returns `true` if this print event originated from the PMU engine.
+ pub(crate) const fn is_pmu(&self) -> bool {
+ self.engine_class() == NV_GSP_MSG_EVENT_UCODE_LIBOS_CLASS_PMU
+ }
+
+ /// Returns the length in bytes of the print buffer following this header.
+ pub(crate) const fn buf_size(&self) -> usize {
+ num::u32_as_usize(self.0.libos_print_buf_size)
+ }
+}
+
+// SAFETY: This struct only contains integer fields and a zero-sized incomplete array marker,
+// so all bit patterns are valid.
+unsafe impl FromBytes for UcodeLibOsPrintHeader {}
+
+// SAFETY: All fields are packed without padding and do not contain uninitialized bytes.
+unsafe impl AsBytes for UcodeLibOsPrintHeader {}
+
/// Struct containing the arguments required to pass a memory buffer to the GSP
/// for use during initialisation.
///
diff --git a/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs b/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
index afe3e007f088..9a9631e9cb3d 100644
--- a/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
+++ b/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
@@ -982,6 +982,13 @@ pub struct rpc_run_cpu_sequencer_v17_00 {
pub regSaveArea: [u32_; 8usize],
pub commandBuffer: __IncompleteArrayField<u32_>,
}
+#[repr(C)]
+#[derive(Debug, Default, MaybeZeroable)]
+pub struct rpc_ucode_libos_print_v1e_08 {
+ pub ucode_eng_desc: u32_,
+ pub libos_print_buf_size: u32_,
+ pub libos_print_buf: __IncompleteArrayField<u8_>,
+}
pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_WRITE: GSP_SEQ_BUF_OPCODE = 0;
pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_MODIFY: GSP_SEQ_BUF_OPCODE = 1;
pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_POLL: GSP_SEQ_BUF_OPCODE = 2;
diff --git a/drivers/gpu/nova-core/gsp/logs.rs b/drivers/gpu/nova-core/gsp/logs.rs
new file mode 100644
index 000000000000..400508df2119
--- /dev/null
+++ b/drivers/gpu/nova-core/gsp/logs.rs
@@ -0,0 +1,450 @@
+// SPDX-License-Identifier: GPL-2.0-only
+
+//! GSP-RM LIBOS logging buffers and `debugfs` retention.
+//!
+//! GSP-RM emits encoded printf-like diagnostics into three DMA ring buffers
+//! (`loginit`, `logintr`, `logrm`) and sends PMU LIBOS print dumps over the
+//! message queue (`logpmu`). All four buffers are exposed through `debugfs`.
+//!
+//! When the `keep_gsp_logging` module parameter is enabled, any non-empty
+//! buffers are snapshotted into regular kernel memory when the [`Gsp`]
+//! instance is dropped (for example after a `probe()` failure or device
+//! unbind) and kept mounted in `debugfs` until the module unloads or the same
+//! device probes again.
+
+use kernel::{
+ debugfs::{
+ self,
+ BinaryWriter, //
+ },
+ device,
+ dma::Coherent,
+ fs::file,
+ io::{
+ io_project,
+ Io, //
+ },
+ new_mutex,
+ prelude::*,
+ str::CString,
+ sync::{
+ Arc,
+ Mutex, //
+ },
+ transmute::FromBytes,
+ uaccess::UserSliceWriter, //
+};
+
+use crate::{
+ gsp::{
+ fw::UcodeLibOsPrintHeader,
+ PteArray,
+ GSP_PAGE_SIZE, //
+ },
+ sbuffer::SBufferIter, //
+};
+
+/// Number of GSP pages to use in a RM log buffer.
+const RM_LOG_BUFFER_NUM_PAGES: usize = 0x10;
+
+/// Size in bytes of each DMA-backed GSP-RM log buffer.
+const LOG_BUFFER_SIZE: usize = RM_LOG_BUFFER_NUM_PAGES * GSP_PAGE_SIZE;
+
+/// Returns `true` if `put_ptr` indicates valid logged data in a buffer of `buffer_size` bytes.
+///
+/// Offset 0 of a LIBOS log buffer stores the `u64` put pointer (`pp`). Initially `pp == 0`.
+/// Once GSP-RM writes entries, `pp` points to the next `u64` slot in the buffer, so valid
+/// logging data satisfies `1 <= pp < buffer_size / size_of::<u64>()`.
+pub(crate) const fn log_put_pointer_is_valid(put_ptr: u64, buffer_size: usize) -> bool {
+ let max_entries = (buffer_size / size_of::<u64>()) as u64;
+ put_ptr >= 1 && put_ptr < max_entries
+}
+
+/// DMA-backed GSP-RM logging buffer.
+///
+/// The logging buffers are byte queues that contain encoded printf-like
+/// messages from GSP-RM. They need to be decoded by a special application
+/// that can parse the buffers.
+///
+/// The `loginit` buffer contains logs from early GSP-RM init and
+/// exception dumps. The `logrm` buffer contains the subsequent logs. Both are
+/// written to directly by GSP-RM and can be any multiple of [`GSP_PAGE_SIZE`].
+///
+/// The physical address map for the log buffer is stored in the buffer
+/// itself, starting with offset 1. Offset 0 contains the "put" pointer (`pp`).
+/// Initially, `pp` is equal to 0. If the buffer has valid logging data in it,
+/// then `pp` points to the index into the buffer where the next logging entry
+/// will be written. Therefore, the logging data is valid if:
+/// `1 <= pp < sizeof(buffer) / sizeof(u64)`.
+pub(super) struct LogBuffer<'a>(Coherent<'a, [u8; LOG_BUFFER_SIZE]>);
+
+impl<'a> LogBuffer<'a> {
+ /// Creates a new [`LogBuffer`] mapped on `dev`.
+ pub(super) fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
+ let obj = Self(Coherent::zeroed(dev, GFP_KERNEL)?);
+
+ let start_addr = obj.0.dma_address();
+
+ let pte_view = io_project!(
+ obj.0,
+ [build: size_of::<u64>()..][build: ..RM_LOG_BUFFER_NUM_PAGES * size_of::<u64>()]
+ )
+ .try_cast::<PteArray<RM_LOG_BUFFER_NUM_PAGES>>()?;
+ PteArray::init(pte_view, start_addr)?;
+
+ Ok(obj)
+ }
+
+ /// Returns the underlying coherent DMA allocation for LIBOS init arguments.
+ pub(super) fn dma_coherent(&self) -> &Coherent<'a, [u8; LOG_BUFFER_SIZE]> {
+ &self.0
+ }
+
+ /// Reads the put pointer stored at offset 0 of the buffer.
+ fn put_pointer(&self) -> u64 {
+ let mut bytes = [0u8; size_of::<u64>()];
+ io_project!(self.0, [build: ..size_of::<u64>()]).copy_to_slice(&mut bytes);
+ u64::from_le_bytes(bytes)
+ }
+
+ /// Copies the buffer into regular kernel memory if it contains valid logged data.
+ fn snapshot(&self) -> Result<Option<KVVec<u8>>> {
+ if !log_put_pointer_is_valid(self.put_pointer(), LOG_BUFFER_SIZE) {
+ return Ok(None);
+ }
+
+ let mut copy = KVVec::zeroed(LOG_BUFFER_SIZE, GFP_KERNEL)?;
+ io_project!(self.0, [build: ..]).copy_to_slice(copy.as_mut_slice());
+ Ok(Some(copy))
+ }
+}
+
+/// Inner state of [`PmuLogBuffer`], protected by a [`Mutex`].
+struct PmuLogBufferInner {
+ data: KVVec<u8>,
+ has_data: bool,
+}
+
+/// Kernel-memory buffer storing the latest PMU `UCODE_LIBOS_PRINT` dump.
+///
+/// Unlike `loginit`, `logintr`, and `logrm`, the PMU print buffer is delivered
+/// via an asynchronous `UCODE_LIBOS_PRINT` GSP RPC event rather than DMA and
+/// is always at most [`GSP_PAGE_SIZE`] bytes.
+#[pin_data]
+pub(crate) struct PmuLogBuffer {
+ #[pin]
+ inner: Mutex<PmuLogBufferInner>,
+}
+
+impl PmuLogBuffer {
+ /// Creates an in-place initializer for a zeroed [`PmuLogBuffer`].
+ pub(crate) fn new() -> impl PinInit<Self, Error> {
+ pin_init::pin_init_scope(|| {
+ let data = KVVec::zeroed(GSP_PAGE_SIZE, GFP_KERNEL)?;
+ Ok(try_pin_init!(Self {
+ inner <- new_mutex!(PmuLogBufferInner {
+ data,
+ has_data: false,
+ }),
+ }))
+ })
+ }
+
+ /// Parses a `UCODE_LIBOS_PRINT` event payload and stores it if it comes from the PMU.
+ ///
+ /// # Errors
+ ///
+ /// - `EINVAL` if the header or payload is truncated.
+ /// - `ENOMSG` if the event belongs to an engine class other than PMU.
+ /// - `E2BIG` if the advertised buffer exceeds [`GSP_PAGE_SIZE`].
+ pub(crate) fn capture_event(&self, contents: (&[u8], &[u8])) -> Result<usize> {
+ let total_len = contents.0.len().saturating_add(contents.1.len());
+ let header_len = size_of::<UcodeLibOsPrintHeader>();
+ if total_len < header_len {
+ return Err(EINVAL);
+ }
+
+ let mut sbuf = SBufferIter::new_reader([contents.0, contents.1]);
+ let mut hdr_bytes = [0u8; size_of::<UcodeLibOsPrintHeader>()];
+ sbuf.read_exact(&mut hdr_bytes)?;
+
+ let hdr = UcodeLibOsPrintHeader::from_bytes_copy(&hdr_bytes).ok_or(EIO)?;
+ if !hdr.is_pmu() {
+ return Err(ENOMSG);
+ }
+
+ let buf_size = hdr.buf_size();
+ if buf_size > GSP_PAGE_SIZE {
+ return Err(E2BIG);
+ }
+
+ if buf_size > total_len - header_len {
+ return Err(EINVAL);
+ }
+
+ let mut guard = self.inner.lock();
+ if buf_size > 0 {
+ sbuf.read_exact(&mut guard.data[..buf_size])?;
+ guard.data[buf_size..].fill(0);
+ guard.has_data = true;
+ } else {
+ guard.data.fill(0);
+ guard.has_data = false;
+ }
+
+ Ok(buf_size)
+ }
+
+ /// Copies the PMU log buffer if a non-empty dump has been captured.
+ fn snapshot(&self) -> Result<Option<KVVec<u8>>> {
+ let guard = self.inner.lock();
+ if !guard.has_data {
+ return Ok(None);
+ }
+
+ let mut copy = KVVec::with_capacity(guard.data.len(), GFP_KERNEL)?;
+ copy.extend_from_slice(guard.data.as_slice(), GFP_KERNEL)?;
+ Ok(Some(copy))
+ }
+}
+
+impl BinaryWriter for PmuLogBuffer {
+ fn write_to_slice(
+ &self,
+ writer: &mut UserSliceWriter,
+ offset: &mut file::Offset,
+ ) -> Result<usize> {
+ let guard = self.inner.lock();
+ guard.data.write_to_slice(writer, offset)
+ }
+}
+
+/// Snapshot of non-empty GSP-RM log buffers retained in `debugfs` after device teardown.
+pub(crate) struct RetainedLogs {
+ loginit: Option<KVVec<u8>>,
+ logintr: Option<KVVec<u8>>,
+ logrm: Option<KVVec<u8>>,
+ logpmu: Option<KVVec<u8>>,
+}
+
+impl RetainedLogs {
+ /// Returns `true` if none of the buffers contain logged data.
+ fn is_empty(&self) -> bool {
+ self.loginit.is_none()
+ && self.logintr.is_none()
+ && self.logrm.is_none()
+ && self.logpmu.is_none()
+ }
+
+ /// Populates `dir` with read-only binary files for each retained buffer.
+ fn populate_debugfs<'data>(&'data self, dir: &debugfs::ScopedDir<'data, '_>) {
+ if let Some(buf) = &self.loginit {
+ dir.read_binary_file(c"loginit", buf);
+ }
+ if let Some(buf) = &self.logintr {
+ dir.read_binary_file(c"logintr", buf);
+ }
+ if let Some(buf) = &self.logrm {
+ dir.read_binary_file(c"logrm", buf);
+ }
+ if let Some(buf) = &self.logpmu {
+ dir.read_binary_file(c"logpmu", buf);
+ }
+ }
+}
+
+/// Retained `debugfs` directory entry owned at module scope for a single PCI device.
+pub(crate) struct RetainedLogEntry {
+ dev_name: CString,
+ _scope: Pin<KBox<debugfs::Scope<RetainedLogs>>>,
+}
+
+impl RetainedLogEntry {
+ /// Creates a retained `debugfs` scope under `parent` named `dev_name`.
+ pub(crate) fn new(parent: &debugfs::Dir, dev_name: &CStr, logs: RetainedLogs) -> Result<Self> {
+ let owned_name = CString::try_from(dev_name)?;
+ let scope = KBox::pin_init(
+ parent.scope(logs, &owned_name, |retained, dir| {
+ retained.populate_debugfs(dir);
+ }),
+ GFP_KERNEL,
+ )?;
+
+ Ok(Self {
+ dev_name: owned_name,
+ _scope: scope,
+ })
+ }
+
+ /// Returns the device name identifying this retained `debugfs` directory.
+ pub(crate) fn dev_name(&self) -> &CStr {
+ &self.dev_name
+ }
+}
+
+/// Live GSP-RM log buffers exposed via `debugfs` while the device is bound.
+///
+/// Because [`debugfs::Scope`] drops its `debugfs` directory entry before dropping
+/// its inner data, [`Drop::drop`] on `LogBuffers` runs only after the live
+/// `debugfs` directory has been removed and no readers remain. When
+/// `keep_gsp_logging` is set, `drop` safely snapshots the buffers into regular
+/// kernel memory and re-exposes them under the module-level `debugfs` root.
+pub(super) struct LogBuffers<'a> {
+ dev: &'a device::Device<device::Bound>,
+ /// Init log buffer.
+ pub(super) loginit: LogBuffer<'a>,
+ /// Interrupts log buffer.
+ pub(super) logintr: LogBuffer<'a>,
+ /// RM log buffer.
+ pub(super) logrm: LogBuffer<'a>,
+ /// PMU log buffer populated from `UCODE_LIBOS_PRINT` events.
+ pub(super) logpmu: Arc<PmuLogBuffer>,
+}
+
+impl<'a> LogBuffers<'a> {
+ /// Creates a new [`LogBuffers`] collection for `dev`.
+ pub(super) fn new(
+ dev: &'a device::Device<device::Bound>,
+ loginit: LogBuffer<'a>,
+ logintr: LogBuffer<'a>,
+ logrm: LogBuffer<'a>,
+ logpmu: Arc<PmuLogBuffer>,
+ ) -> Self {
+ Self {
+ dev,
+ loginit,
+ logintr,
+ logrm,
+ logpmu,
+ }
+ }
+
+ /// Snapshots all non-empty log buffers into regular kernel memory.
+ fn snapshot(&self) -> Result<RetainedLogs> {
+ Ok(RetainedLogs {
+ loginit: self.loginit.snapshot()?,
+ logintr: self.logintr.snapshot()?,
+ logrm: self.logrm.snapshot()?,
+ logpmu: self.logpmu.snapshot()?,
+ })
+ }
+}
+
+impl Drop for LogBuffers<'_> {
+ fn drop(&mut self) {
+ if !cfg!(CONFIG_DEBUG_FS) || !crate::keep_gsp_logging() {
+ return;
+ }
+
+ let retained = match self.snapshot() {
+ Ok(retained) => retained,
+ Err(e) => {
+ dev_warn!(
+ self.dev,
+ "Failed to snapshot GSP logging buffers: {:?}\n",
+ e
+ );
+ return;
+ }
+ };
+
+ if retained.is_empty() {
+ dev_dbg!(
+ self.dev,
+ "GSP logging buffers are empty; nothing to retain\n"
+ );
+ return;
+ }
+
+ match crate::store_retained_logs(self.dev.name(), retained) {
+ Ok(()) => dev_info!(self.dev, "Retained GSP logging buffers in debugfs\n"),
+ Err(e) => dev_warn!(
+ self.dev,
+ "Failed to retain GSP logging buffers in debugfs: {:?}\n",
+ e
+ ),
+ }
+ }
+}
+
+#[kunit_tests(nova_core_gsp_logs)]
+mod tests {
+ use super::*;
+
+ const PMU_ENG_DESC: u32 = 0xf3d722 << 8;
+
+ fn make_event(eng_desc: u32, advertised_size: u32, payload: &[u8]) -> Result<KVec<u8>> {
+ let mut msg = KVec::with_capacity(8 + payload.len(), GFP_KERNEL)?;
+ msg.extend_from_slice(&eng_desc.to_le_bytes(), GFP_KERNEL)?;
+ msg.extend_from_slice(&advertised_size.to_le_bytes(), GFP_KERNEL)?;
+ msg.extend_from_slice(payload, GFP_KERNEL)?;
+ Ok(msg)
+ }
+
+ #[test]
+ fn put_pointer_bounds() {
+ let max_entries = (LOG_BUFFER_SIZE / size_of::<u64>()) as u64;
+ assert!(!log_put_pointer_is_valid(0, LOG_BUFFER_SIZE));
+ assert!(log_put_pointer_is_valid(1, LOG_BUFFER_SIZE));
+ assert!(log_put_pointer_is_valid(max_entries - 1, LOG_BUFFER_SIZE));
+ assert!(!log_put_pointer_is_valid(max_entries, LOG_BUFFER_SIZE));
+ assert!(!log_put_pointer_is_valid(u64::MAX, LOG_BUFFER_SIZE));
+ }
+
+ #[test]
+ fn pmu_log_capture_and_overwrite() -> Result {
+ let pmu = Arc::pin_init(PmuLogBuffer::new(), GFP_KERNEL)?;
+ assert!(pmu.snapshot()?.is_none());
+
+ // Split header and payload across two ring slices to simulate wraparound.
+ let payload = b"PMU LIBOS TEST LOG";
+ let raw = make_event(PMU_ENG_DESC, payload.len() as u32, payload)?;
+ let (part1, part2) = raw.as_slice().split_at(5);
+ assert_eq!(pmu.capture_event((part1, part2))?, payload.len());
+
+ let snap = pmu.snapshot()?.ok_or(EIO)?;
+ assert_eq!(snap.len(), GSP_PAGE_SIZE);
+ assert_eq!(&snap[..payload.len()], payload);
+ assert!(snap[payload.len()..].iter().all(|&b| b == 0));
+
+ // A shorter subsequent event must zero-pad the remainder.
+ let shorter = b"OK";
+ let raw2 = make_event(PMU_ENG_DESC, shorter.len() as u32, shorter)?;
+ assert_eq!(pmu.capture_event((raw2.as_slice(), &[]))?, shorter.len());
+
+ let snap2 = pmu.snapshot()?.ok_or(EIO)?;
+ assert_eq!(&snap2[..shorter.len()], shorter);
+ assert!(snap2[shorter.len()..].iter().all(|&b| b == 0));
+
+ Ok(())
+ }
+
+ #[test]
+ fn pmu_log_rejects_invalid_events_without_clobbering() -> Result {
+ let pmu = Arc::pin_init(PmuLogBuffer::new(), GFP_KERNEL)?;
+ let valid = b"KEEP";
+ let raw = make_event(PMU_ENG_DESC, valid.len() as u32, valid)?;
+ pmu.capture_event((raw.as_slice(), &[]))?;
+
+ // Truncated header.
+ assert_eq!(pmu.capture_event((&[0u8; 4], &[])), Err(EINVAL));
+
+ // Unknown engine class.
+ let bad_class = make_event(0x123456 << 8, 4, b"ABCD")?;
+ assert_eq!(pmu.capture_event((bad_class.as_slice(), &[])), Err(ENOMSG));
+
+ // Oversized buffer (> GSP_PAGE_SIZE).
+ let too_big = make_event(PMU_ENG_DESC, (GSP_PAGE_SIZE + 1) as u32, &[])?;
+ assert_eq!(pmu.capture_event((too_big.as_slice(), &[])), Err(E2BIG));
+
+ // Truncated payload (advertised 16 bytes, only 4 present).
+ let truncated = make_event(PMU_ENG_DESC, 16, b"ABCD")?;
+ assert_eq!(pmu.capture_event((truncated.as_slice(), &[])), Err(EINVAL));
+
+ // Existing valid contents must remain intact after rejected events.
+ let snap = pmu.snapshot()?.ok_or(EIO)?;
+ assert_eq!(&snap[..valid.len()], valid);
+
+ Ok(())
+ }
+}
diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
index a8f6dc22057b..f182ebb6b928 100644
--- a/drivers/gpu/nova-core/nova_core.rs
+++ b/drivers/gpu/nova-core/nova_core.rs
@@ -35,11 +35,53 @@
// TODO: Move this into per-module data once that exists.
static mut DEBUGFS_ROOT: Option<debugfs::Dir> = None;
-/// Guard that clears `DEBUGFS_ROOT` when dropped.
+kernel::sync::global_lock! {
+ // SAFETY: Initialized once in `NovaCoreModule::init` before driver registration
+ // and cleared in `DebugfsRootGuard::drop` after driver unregistration.
+ unsafe(uninit) static RETAINED_LOGS: Mutex<KVec<gsp::logs::RetainedLogEntry>> = KVec::new();
+}
+
+/// Returns whether GSP-RM `debugfs` log buffers should be retained after teardown.
+pub(crate) fn keep_gsp_logging() -> bool {
+ module_parameters::keep_gsp_logging.value()
+}
+
+/// Returns the module-wide `debugfs` root directory (`nova-core`).
+pub(crate) fn debugfs_root() -> &'static debugfs::Dir {
+ #[allow(static_mut_refs)]
+ // SAFETY: `DEBUGFS_ROOT` is initialized before driver registration and cleared
+ // only after driver unregistration, so no device code can race with its mutation.
+ //
+ // PANIC: `DEBUGFS_ROOT` is always `Some` while the PCI driver is registered.
+ unsafe { DEBUGFS_ROOT.as_ref() }.expect("DEBUGFS_ROOT not initialized")
+}
+
+/// Removes any retained `debugfs` log directory previously stored for `dev_name`.
+pub(crate) fn clear_retained_logs_for(dev_name: &CStr) {
+ let mut retained = RETAINED_LOGS.lock();
+ retained.retain(|entry| entry.dev_name() != dev_name);
+}
+
+/// Publishes a retained snapshot of GSP log buffers in `debugfs` until module unload.
+pub(crate) fn store_retained_logs(dev_name: &CStr, logs: gsp::logs::RetainedLogs) -> Result {
+ let mut retained = RETAINED_LOGS.lock();
+ retained.retain(|entry| entry.dev_name() != dev_name);
+
+ let entry = gsp::logs::RetainedLogEntry::new(debugfs_root(), dev_name, logs)?;
+ retained.push(entry, GFP_KERNEL)?;
+
+ Ok(())
+}
+
+/// Guard that clears retained logs and `DEBUGFS_ROOT` when dropped.
struct DebugfsRootGuard;
impl Drop for DebugfsRootGuard {
fn drop(&mut self) {
+ // Drop retained `debugfs` scopes and free the `KVec` backing allocation
+ // before removing `DEBUGFS_ROOT`.
+ *RETAINED_LOGS.lock() = KVec::new();
+
// SAFETY: This guard is dropped after `_driver` (due to field order),
// so the driver is unregistered and no probe() can be running.
unsafe { DEBUGFS_ROOT = None };
@@ -49,7 +91,7 @@ fn drop(&mut self) {
#[pin_data]
struct NovaCoreModule {
// Fields are dropped in declaration order, so `_driver` is dropped first,
- // then `_debugfs_guard` clears `DEBUGFS_ROOT`.
+ // then `_debugfs_guard` clears retained logs and `DEBUGFS_ROOT`.
#[pin]
_driver: Registration<pci::Adapter<driver::NovaCoreDriver>>,
_debugfs_guard: DebugfsRootGuard,
@@ -59,6 +101,10 @@ impl InPlaceModule for NovaCoreModule {
fn init(module: &'static kernel::ThisModule) -> impl PinInit<Self, Error> {
let dir = debugfs::Dir::new(c"nova-core");
+ // SAFETY: We are the only driver code running during init, so `RETAINED_LOGS`
+ // is initialized exactly once before any driver callback can access it.
+ unsafe { RETAINED_LOGS.init() };
+
// SAFETY: We are the only driver code running during init, so there
// cannot be any concurrent access to `DEBUGFS_ROOT`.
unsafe { DEBUGFS_ROOT = Some(dir) };
@@ -77,6 +123,12 @@ fn init(module: &'static kernel::ThisModule) -> impl PinInit<Self, Error> {
description: "Nova Core GPU driver",
license: "GPL v2",
firmware: [],
+ params: {
+ keep_gsp_logging: bool {
+ default: false,
+ description: "Retain GSP-RM debugfs log buffers after probe failure or unbind",
+ },
+ },
}
kernel::module_firmware!(firmware::ModInfoBuilder);
diff --git a/drivers/gpu/nova-core/sbuffer.rs b/drivers/gpu/nova-core/sbuffer.rs
index 3a41d224c77a..b8c01104c255 100644
--- a/drivers/gpu/nova-core/sbuffer.rs
+++ b/drivers/gpu/nova-core/sbuffer.rs
@@ -146,7 +146,6 @@ fn get_slice(&mut self, len: usize) -> Option<&'a [u8]> {
/// Ideally we would implement `Read`, but it is not available in `core`.
/// So mimic `std::io::Read::read_exact`.
- #[expect(unused)]
pub(crate) fn read_exact(&mut self, mut dst: &mut [u8]) -> Result {
while !dst.is_empty() {
match self.get_slice(dst.len()) {
base-commit: 693c2e04e3f1d4c59af236e1211b7b8cb165a790
--
2.56.1
^ permalink raw reply [flat|nested] 3+ messages in thread
* [RFC PATCH v2] gpu: nova-core: gsp: add RM alloc/control/free RPCs and client/device API
2026-12-02 2:50 [RFC PATCH v2] gpu: nova-core: gsp: retain debugfs logs on teardown and capture logpmu Agustín Pereira
@ 2026-12-02 2:50 ` Agustín Pereira
2026-12-02 3:37 ` [RFC PATCH v2] gpu: nova-core: gsp: retain debugfs logs on teardown and capture logpmu John Hubbard
1 sibling, 0 replies; 3+ messages in thread
From: Agustín Pereira @ 2026-12-02 2:50 UTC (permalink / raw)
To: Danilo Krummrich, Alexandre Courbot
Cc: David Airlie, Simona Vetter, Miguel Ojeda, nova-gpu, dri-devel,
rust-for-linux, linux-kernel, Agustín Pereira
Nova-core currently supports only fixed boot and teardown GSP RPCs
(`SetSystemInfo`, `SetRegistry`, `GetGspStaticInfo`, and
`UnloadingGuestDriver`). Higher-level GPU subsystems such as FIFO, GR,
and CE engines require allocating, controlling, and freeing GSP-RM
objects arranged in a client -> device -> subdevice hierarchy.
Implement the GSP-RM object RPC layer and RAII handle abstractions:
- Add the r570.144 firmware definitions (`rpc_gsp_rm_alloc_v03_00`,
`rpc_gsp_rm_control_v03_00`, `rpc_free_v03_00`,
`NV0000_ALLOC_PARAMETERS`, `NV0080_ALLOC_PARAMETERS`, and
`NV2080_ALLOC_PARAMETERS`) and wrap them in firmware-independent
types in `gsp::fw::commands` with compile-time layout assertions and
`RmStatus` (`NV_STATUS` to kernel `Error`) conversion.
- Validate the outer `rpc_result` field in `CmdqInner::receive_msg()`
and avoid returning early before advancing `cpu_read_ptr` on malformed
replies.
- Expose `MsgFunction::GspRmAlloc` and implement typed `CommandToGsp` /
`MessageFromGsp` commands (`RmAlloc`, `RmControl`, and `RmFree`) in
`gsp::commands`.
- Add `gsp::rm` providing `RmHandle`, an `IdPool`-backed
`RmClientIdAllocator` for handle allocation and recycling, and RAII
handles (`RmClient`, `RmDevice`, `RmSubdevice`, and `RmObject`) whose
Rust lifetime hierarchy enforces child-before-parent `FREE` teardown.
- Wire `Gsp::alloc_client()` into a `CONFIG_NOVA_CORE_SELFTESTS` probe
self-test and add KUnit unit tests (`nova_core_gsp_rm`) covering
handle encoding, allocator growth/recycling, `RmStatus` mapping, and
RPC wire serialization/reply decoding.
Testing:
- Compiled `drivers/gpu/nova-core.o` and `drivers/gpu/nova-drm.o` with
`LLVM=1 W=1 CLIPPY=1` (`CONFIG_RUST=y`, `CONFIG_NOVA_CORE=m`,
`CONFIG_DRM_NOVA=m`) under both (`CONFIG_NOVA_CORE_SELFTESTS=y`,
`CONFIG_KUNIT=y`) and (`CONFIG_NOVA_CORE_SELFTESTS=n`,
`CONFIG_KUNIT=n`) with zero warnings.
- Verified formatting with `rustfmt --check` and patch style with
`scripts/checkpatch.pl`.
- Tested on NVIDIA GeForce RTX 4070 Laptop GPU (AD106M, Ada, rev a.1)
with r570.144 TLV firmware on 7.4.0-rc5: `GSP RM` client/device/
subdevice alloc/control/free self-test passed on initial probe and
re-bind with zero warnings.
This change was drafted with the assistance of an AI coding assistant.
Signed-off-by: Agustín Pereira <agustin.pereira.ro@gmail.com>
---
Changes in v2:
- Validate the outer rpc_result field in CmdqInner::receive_msg() and avoid
returning early before advancing cpu_read_ptr on malformed replies
(reported by Sashiko AI review).
- Stop draining sbuffer after read_exact() in RmControlReply::read() so
unexpectedly large control payloads trigger the unprocessed-data warning
(reported by Sashiko AI review).
- Kept the 16-byte GspRmFree reply payload in RmFreeReply: testing on real
AD106M hardware (r570.144) confirmed GSP-RM echoes rpc_free_v03_00 in the
FREE reply (using Message = () produced "GSP message Free has unprocessed
data" warnings). Both outer rpc_result and params.status are now checked.
- Tested on real hardware: NVIDIA GeForce RTX 4070 Laptop GPU (AD106M, Ada,
rev a.1, r570.144 TLV firmware) on 7.4.0-rc5; GSP RM client/device/subdevice
alloc/control/free self-test passed on initial probe and re-bind with zero
warnings.
drivers/gpu/nova-core/gpu.rs | 4 +
drivers/gpu/nova-core/gsp.rs | 17 +-
drivers/gpu/nova-core/gsp/cmdq.rs | 42 +-
drivers/gpu/nova-core/gsp/commands.rs | 186 +++++
drivers/gpu/nova-core/gsp/fw.rs | 7 +
drivers/gpu/nova-core/gsp/fw/commands.rs | 229 +++++++
.../gpu/nova-core/gsp/fw/r570_144/bindings.rs | 73 ++
drivers/gpu/nova-core/gsp/rm.rs | 640 ++++++++++++++++++
drivers/gpu/nova-core/sbuffer.rs | 1 -
9 files changed, 1183 insertions(+), 16 deletions(-)
create mode 100644 drivers/gpu/nova-core/gsp/rm.rs
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 4e59072cab50..10a3d2ae4d6f 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -629,6 +629,10 @@ pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device<device::Bou
) {
dev_err!(dev, "self-tests failed: {:?}\n", err);
}
+
+ if let Err(err) = crate::gsp::rm::run_selftest(dev, &this.gsp_resources.gsp) {
+ dev_err!(dev, "GSP RM self-test failed: {:?}\n", err);
+ }
}
}
diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs
index dda58095f40b..8879c9ed99c3 100644
--- a/drivers/gpu/nova-core/gsp.rs
+++ b/drivers/gpu/nova-core/gsp.rs
@@ -25,6 +25,7 @@
pub(crate) mod commands;
mod fw;
mod regs;
+pub(crate) mod rm;
mod sequencer;
pub(crate) use fw::{
@@ -46,7 +47,11 @@
gpu::Chipset,
gsp::{
cmdq::Cmdq,
- fw::GspArgumentsPadded, //
+ fw::GspArgumentsPadded,
+ rm::{
+ RmClient,
+ RmClientIdAllocator, //
+ }, //
},
num,
vgpu::VgpuManager, //
@@ -155,6 +160,9 @@ pub(crate) struct Gsp<'gsp> {
/// Command queue.
#[pin]
pub(crate) cmdq: Cmdq<'gsp>,
+ /// RM client handle allocator.
+ #[pin]
+ rm_clients: RmClientIdAllocator,
/// RM arguments.
rmargs: Coherent<'gsp, GspArgumentsPadded>,
}
@@ -177,6 +185,7 @@ pub(crate) fn new(
// kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array)
Ok(try_pin_init!(Self {
cmdq <- Cmdq::new(dev, bar),
+ rm_clients <- RmClientIdAllocator::new(),
rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
libos: {
let mut libos = CoherentBox::zeroed_slice(
@@ -223,6 +232,12 @@ pub(crate) fn new(
pub(crate) fn get_static_info(&self) -> Result<commands::GetGspStaticInfoReply> {
self.cmdq.send_command(commands::GetGspStaticInfo)
}
+
+ /// Allocates a new GSP-RM root client (`NV01_ROOT`).
+ #[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))]
+ pub(crate) fn alloc_client(&self) -> Result<RmClient<'_, 'gsp>> {
+ RmClient::new(&self.cmdq, &self.rm_clients)
+ }
}
/// Opaque bundle required to unload the GSP. Created by [`Gsp::boot`], consumed by [`Gsp::unload`].
diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
index 1b2f346a237f..910a52dcd984 100644
--- a/drivers/gpu/nova-core/gsp/cmdq.rs
+++ b/drivers/gpu/nova-core/gsp/cmdq.rs
@@ -867,20 +867,34 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
// An early return here would leave the read pointer on this message.
let result = if matches!(function, Ok(f) if f == M::FUNCTION) {
- let (cmd, contents_1) = M::Message::from_bytes_prefix(message.contents.0).ok_or(EIO)?;
- let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]);
-
- M::read(cmd, &mut sbuffer)
- .map_err(|e| e.into())
- .inspect(|_| {
- if !sbuffer.is_empty() {
- dev_warn!(
- &self.dev,
- "GSP message {:?} has unprocessed data\n",
- M::FUNCTION
- );
- }
- })
+ let rpc_result = message.header.rpc_result();
+ if let Err(err) = rpc_result.into_result() {
+ dev_err!(
+ &self.dev,
+ "GSP RPC {:?} failed with rpc_result={:#x}\n",
+ M::FUNCTION,
+ rpc_result.raw(),
+ );
+ Err(err)
+ } else if let Some((cmd, contents_1)) =
+ M::Message::from_bytes_prefix(message.contents.0)
+ {
+ 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
+ );
+ }
+ })
+ } else {
+ Err(EIO)
+ }
} else {
self.log_event(function, seq);
diff --git a/drivers/gpu/nova-core/gsp/commands.rs b/drivers/gpu/nova-core/gsp/commands.rs
index cdbb13674f08..b52413735504 100644
--- a/drivers/gpu/nova-core/gsp/commands.rs
+++ b/drivers/gpu/nova-core/gsp/commands.rs
@@ -5,6 +5,7 @@
array,
convert::Infallible,
ffi::FromBytesUntilNulError,
+ marker::PhantomData,
ops::Range,
str::Utf8Error, //
};
@@ -329,3 +330,188 @@ fn read(
Ok(UnloadingGuestDriverReply)
}
}
+
+/// The `GSP_RM_ALLOC` command for allocating an RM object with typed parameters `P`.
+pub(super) struct RmAlloc<'a, P: AsBytes + FromBytes> {
+ client: u32,
+ parent: u32,
+ object: u32,
+ class: u32,
+ params: &'a P,
+}
+
+impl<'a, P: AsBytes + FromBytes> RmAlloc<'a, P> {
+ /// Creates a new `GSP_RM_ALLOC` command.
+ pub(super) fn new(client: u32, parent: u32, object: u32, class: u32, params: &'a P) -> Self {
+ Self {
+ client,
+ parent,
+ object,
+ class,
+ params,
+ }
+ }
+}
+
+impl<P: AsBytes + FromBytes> CommandToGsp for RmAlloc<'_, P> {
+ const FUNCTION: MsgFunction = MsgFunction::GspRmAlloc;
+ type Command = fw::commands::GspRmAllocHeader;
+ type Reply = RmAllocReply;
+ type InitError = Error;
+
+ fn init(&self) -> impl Init<Self::Command, Self::InitError> {
+ fw::commands::GspRmAllocHeader::init(
+ self.client,
+ self.parent,
+ self.object,
+ self.class,
+ size_of::<P>(),
+ )
+ }
+
+ fn variable_payload_len(&self) -> usize {
+ size_of::<P>()
+ }
+
+ fn init_variable_payload(
+ &self,
+ dst: &mut SBufferIter<core::array::IntoIter<&mut [u8], 2>>,
+ ) -> Result {
+ dst.write_all(self.params.as_bytes())
+ }
+}
+
+/// The reply from the GSP to [`RmAlloc`].
+pub(super) struct RmAllocReply;
+
+impl MessageFromGsp for RmAllocReply {
+ const FUNCTION: MsgFunction = MsgFunction::GspRmAlloc;
+ type InitError = Error;
+ type Message = fw::commands::GspRmAllocHeader;
+
+ fn read(
+ msg: &Self::Message,
+ sbuffer: &mut SBufferIter<array::IntoIter<&[u8], 2>>,
+ ) -> Result<Self, Self::InitError> {
+ msg.status().into_result()?;
+
+ // GSP echoes the allocation parameters in the reply; drain them so the
+ // command queue does not warn about unprocessed bytes.
+ while sbuffer.next().is_some() {}
+
+ Ok(RmAllocReply)
+ }
+}
+
+/// The `GSP_RM_CONTROL` command for invoking an RM control call with typed parameters `P`.
+pub(super) struct RmControl<'a, P: AsBytes + FromBytes + Zeroable> {
+ client: u32,
+ object: u32,
+ cmd: u32,
+ params: &'a P,
+ _reply: PhantomData<P>,
+}
+
+impl<'a, P: AsBytes + FromBytes + Zeroable> RmControl<'a, P> {
+ /// Creates a new `GSP_RM_CONTROL` command.
+ pub(super) fn new(client: u32, object: u32, cmd: u32, params: &'a P) -> Self {
+ Self {
+ client,
+ object,
+ cmd,
+ params,
+ _reply: PhantomData,
+ }
+ }
+}
+
+impl<P: AsBytes + FromBytes + Zeroable> CommandToGsp for RmControl<'_, P> {
+ const FUNCTION: MsgFunction = MsgFunction::GspRmControl;
+ type Command = fw::commands::GspRmControlHeader;
+ type Reply = RmControlReply<P>;
+ type InitError = Error;
+
+ fn init(&self) -> impl Init<Self::Command, Self::InitError> {
+ fw::commands::GspRmControlHeader::init(self.client, self.object, self.cmd, size_of::<P>())
+ }
+
+ fn variable_payload_len(&self) -> usize {
+ size_of::<P>()
+ }
+
+ fn init_variable_payload(
+ &self,
+ dst: &mut SBufferIter<core::array::IntoIter<&mut [u8], 2>>,
+ ) -> Result {
+ dst.write_all(self.params.as_bytes())
+ }
+}
+
+/// The reply from the GSP to [`RmControl`], carrying the updated parameter structure `P`.
+pub(super) struct RmControlReply<P: AsBytes + FromBytes + Zeroable> {
+ /// Output parameters returned by GSP-RM.
+ pub(super) params: P,
+}
+
+impl<P: AsBytes + FromBytes + Zeroable> MessageFromGsp for RmControlReply<P> {
+ const FUNCTION: MsgFunction = MsgFunction::GspRmControl;
+ type InitError = Error;
+ type Message = fw::commands::GspRmControlHeader;
+
+ fn read(
+ msg: &Self::Message,
+ sbuffer: &mut SBufferIter<array::IntoIter<&[u8], 2>>,
+ ) -> Result<Self, Self::InitError> {
+ msg.status().into_result()?;
+
+ let mut params = P::zeroed();
+ sbuffer.read_exact(params.as_bytes_mut())?;
+
+ Ok(Self { params })
+ }
+}
+
+/// The `FREE` command for releasing an RM object handle on the GSP.
+pub(super) struct RmFree {
+ root: u32,
+ object: u32,
+}
+
+impl RmFree {
+ /// Creates a new `FREE` command for `object` belonging to client `root`.
+ pub(super) fn new(root: u32, object: u32) -> Self {
+ Self { root, object }
+ }
+}
+
+impl CommandToGsp for RmFree {
+ const FUNCTION: MsgFunction = MsgFunction::Free;
+ type Command = fw::commands::GspRmFree;
+ type Reply = RmFreeReply;
+ type InitError = Infallible;
+
+ fn init(&self) -> impl Init<Self::Command, Self::InitError> {
+ fw::commands::GspRmFree::new(self.root, self.object)
+ }
+}
+
+/// The reply from the GSP to [`RmFree`].
+///
+/// The GSP reports RPC-level completion in the outer header's `rpc_result`
+/// (checked in `CmdqInner::receive_msg`) and echoes back the 16-byte
+/// `rpc_free_v03_00` payload with `params.status`.
+pub(super) struct RmFreeReply;
+
+impl MessageFromGsp for RmFreeReply {
+ const FUNCTION: MsgFunction = MsgFunction::Free;
+ type InitError = Error;
+ type Message = fw::commands::GspRmFree;
+
+ fn read(
+ msg: &Self::Message,
+ _sbuffer: &mut SBufferIter<array::IntoIter<&[u8], 2>>,
+ ) -> Result<Self, Self::InitError> {
+ msg.status().into_result()?;
+ Ok(RmFreeReply)
+ }
+}
diff --git a/drivers/gpu/nova-core/gsp/fw.rs b/drivers/gpu/nova-core/gsp/fw.rs
index 918a7ae809eb..c41e4a2c4c7f 100644
--- a/drivers/gpu/nova-core/gsp/fw.rs
+++ b/drivers/gpu/nova-core/gsp/fw.rs
@@ -285,6 +285,7 @@ pub(crate) enum MsgFunction {
GetGspStaticInfo = bindings::NV_VGPU_MSG_FUNCTION_GET_GSP_STATIC_INFO,
GetStaticInfo = bindings::NV_VGPU_MSG_FUNCTION_GET_STATIC_INFO,
GspInitPostObjGpu = bindings::NV_VGPU_MSG_FUNCTION_GSP_INIT_POST_OBJGPU,
+ GspRmAlloc = bindings::NV_VGPU_MSG_FUNCTION_GSP_RM_ALLOC,
GspRmControl = bindings::NV_VGPU_MSG_FUNCTION_GSP_RM_CONTROL,
GspSetSystemInfo = bindings::NV_VGPU_MSG_FUNCTION_GSP_SET_SYSTEM_INFO,
Log = bindings::NV_VGPU_MSG_FUNCTION_LOG,
@@ -328,6 +329,7 @@ fn try_from(value: u32) -> Result<MsgFunction> {
bindings::NV_VGPU_MSG_FUNCTION_GSP_INIT_POST_OBJGPU => {
Ok(MsgFunction::GspInitPostObjGpu)
}
+ bindings::NV_VGPU_MSG_FUNCTION_GSP_RM_ALLOC => Ok(MsgFunction::GspRmAlloc),
bindings::NV_VGPU_MSG_FUNCTION_GSP_RM_CONTROL => Ok(MsgFunction::GspRmControl),
bindings::NV_VGPU_MSG_FUNCTION_GSP_SET_SYSTEM_INFO => Ok(MsgFunction::GspSetSystemInfo),
bindings::NV_VGPU_MSG_FUNCTION_LOG => Ok(MsgFunction::Log),
@@ -879,6 +881,11 @@ pub(crate) fn function(&self) -> Result<MsgFunction, u32> {
pub(crate) fn element_count(&self) -> u32 {
self.inner.elemCount
}
+
+ /// Returns the `NV_STATUS` completion code from the outer RPC header.
+ pub(crate) fn rpc_result(&self) -> commands::RmStatus {
+ commands::RmStatus::from_raw(self.inner.rpc.rpc_result)
+ }
}
// SAFETY: Padding is explicit and does not contain uninitialized data.
diff --git a/drivers/gpu/nova-core/gsp/fw/commands.rs b/drivers/gpu/nova-core/gsp/fw/commands.rs
index 567c56fbbfe3..6ed091c3edc2 100644
--- a/drivers/gpu/nova-core/gsp/fw/commands.rs
+++ b/drivers/gpu/nova-core/gsp/fw/commands.rs
@@ -245,3 +245,232 @@ unsafe impl AsBytes for UnloadingGuestDriver {}
// SAFETY: This struct only contains integer types for which all bit patterns
// are valid.
unsafe impl FromBytes for UnloadingGuestDriver {}
+
+/// RM class identifier for allocating a root client (`NV01_ROOT`).
+pub(crate) const RM_CLASS_ROOT: u32 = bindings::NV01_ROOT;
+
+/// RM class identifier for allocating a device (`NV01_DEVICE_0`).
+pub(crate) const RM_CLASS_DEVICE: u32 = bindings::NV01_DEVICE_0;
+
+/// RM class identifier for allocating a subdevice (`NV20_SUBDEVICE_0`).
+pub(crate) const RM_CLASS_SUBDEVICE: u32 = bindings::NV20_SUBDEVICE_0;
+
+/// Status code returned by GSP-RM object RPCs (`NV_STATUS`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(transparent)]
+pub(crate) struct RmStatus(u32);
+
+impl RmStatus {
+ /// Creates an [`RmStatus`] from a raw firmware status code.
+ pub(crate) const fn from_raw(status: u32) -> Self {
+ Self(status)
+ }
+
+ /// Returns the raw `NV_STATUS` code.
+ pub(crate) const fn raw(self) -> u32 {
+ self.0
+ }
+
+ /// Converts this `NV_STATUS` into a kernel [`Result`].
+ pub(crate) fn into_result(self) -> Result {
+ match self.0 {
+ bindings::NV_OK => Ok(()),
+ bindings::NV_ERR_NOT_READY | bindings::NV_ERR_TIMEOUT_RETRY => Err(EBUSY),
+ bindings::NV_ERR_NO_MEMORY => Err(ENOMEM),
+ _ => Err(EINVAL),
+ }
+ }
+}
+
+/// Header of the `GSP_RM_ALLOC` RPC command and reply.
+#[repr(transparent)]
+pub(crate) struct GspRmAllocHeader {
+ inner: bindings::rpc_gsp_rm_alloc_v03_00,
+}
+
+static_assert!(size_of::<GspRmAllocHeader>() == 32);
+
+impl GspRmAllocHeader {
+ /// Returns an in-place initializer for a `GSP_RM_ALLOC` header.
+ pub(crate) fn init(
+ client: u32,
+ parent: u32,
+ object: u32,
+ class: u32,
+ params_size: usize,
+ ) -> impl Init<Self, Error> {
+ let init_inner = try_init!(bindings::rpc_gsp_rm_alloc_v03_00 {
+ hClient: client,
+ hParent: parent,
+ hObject: object,
+ hClass: class,
+ status: 0,
+ paramsSize: u32::try_from(params_size).map_err(|_| EOVERFLOW)?,
+ flags: 0,
+ reserved: [0; 4],
+ ..Zeroable::init_zeroed()
+ });
+
+ try_init!(Self {
+ inner <- init_inner,
+ })
+ }
+
+ /// Returns the `NV_STATUS` reported by the GSP in the reply header.
+ pub(crate) fn status(&self) -> RmStatus {
+ RmStatus::from_raw(self.inner.status)
+ }
+}
+
+// SAFETY: All fields are plain integers with no implicit padding.
+unsafe impl AsBytes for GspRmAllocHeader {}
+
+// SAFETY: All bit patterns are valid for the integer fields in this header.
+unsafe impl FromBytes for GspRmAllocHeader {}
+
+/// Header of the `GSP_RM_CONTROL` RPC command and reply.
+#[repr(transparent)]
+pub(crate) struct GspRmControlHeader {
+ inner: bindings::rpc_gsp_rm_control_v03_00,
+}
+
+static_assert!(size_of::<GspRmControlHeader>() == 24);
+
+impl GspRmControlHeader {
+ /// Returns an in-place initializer for a `GSP_RM_CONTROL` header.
+ pub(crate) fn init(
+ client: u32,
+ object: u32,
+ cmd: u32,
+ params_size: usize,
+ ) -> impl Init<Self, Error> {
+ let init_inner = try_init!(bindings::rpc_gsp_rm_control_v03_00 {
+ hClient: client,
+ hObject: object,
+ cmd,
+ status: 0,
+ paramsSize: u32::try_from(params_size).map_err(|_| EOVERFLOW)?,
+ flags: 0,
+ ..Zeroable::init_zeroed()
+ });
+
+ try_init!(Self {
+ inner <- init_inner,
+ })
+ }
+
+ /// Returns the `NV_STATUS` reported by the GSP in the reply header.
+ pub(crate) fn status(&self) -> RmStatus {
+ RmStatus::from_raw(self.inner.status)
+ }
+}
+
+// SAFETY: All fields are plain integers with no implicit padding.
+unsafe impl AsBytes for GspRmControlHeader {}
+
+// SAFETY: All bit patterns are valid for the integer fields in this header.
+unsafe impl FromBytes for GspRmControlHeader {}
+
+/// Payload of the `FREE` RM RPC command and reply.
+#[repr(transparent)]
+#[derive(Clone, Copy, Debug, Zeroable)]
+pub(crate) struct GspRmFree(bindings::rpc_free_v03_00);
+
+static_assert!(size_of::<GspRmFree>() == 16);
+
+impl GspRmFree {
+ /// Creates a new `FREE` payload for freeing `object` under `root`.
+ pub(crate) fn new(root: u32, object: u32) -> Self {
+ Self(bindings::rpc_free_v03_00 {
+ params: bindings::NVOS00_PARAMETERS_v03_00 {
+ hRoot: root,
+ hObjectParent: 0,
+ hObjectOld: object,
+ status: 0,
+ },
+ })
+ }
+
+ /// Returns the `NV_STATUS` reported by the GSP in the reply payload.
+ pub(crate) fn status(&self) -> RmStatus {
+ RmStatus::from_raw(self.0.params.status)
+ }
+}
+
+// SAFETY: All fields are plain integers with no padding.
+unsafe impl AsBytes for GspRmFree {}
+
+// SAFETY: All bit patterns are valid for the integer fields in this struct.
+unsafe impl FromBytes for GspRmFree {}
+
+/// Allocation parameters for an `NV01_ROOT` RM client (`NV0000_ALLOC_PARAMETERS`).
+#[repr(transparent)]
+#[derive(Clone, Copy, Debug, Zeroable)]
+pub(crate) struct RmClientAllocParams(bindings::NV0000_ALLOC_PARAMETERS);
+
+static_assert!(size_of::<RmClientAllocParams>() == 120);
+
+impl RmClientAllocParams {
+ /// Creates allocation parameters for a kernel RM client with `client_handle`.
+ pub(crate) fn new(client_handle: u32) -> Self {
+ Self(bindings::NV0000_ALLOC_PARAMETERS {
+ hClient: client_handle,
+ processID: u32::MAX,
+ processName: [0; 100],
+ __bindgen_padding_0: [0; 4],
+ pOsPidInfo: 0,
+ })
+ }
+}
+
+// SAFETY: Padding is explicit and initialized to zero.
+unsafe impl AsBytes for RmClientAllocParams {}
+
+// SAFETY: All bit patterns are valid for the integer and byte array fields.
+unsafe impl FromBytes for RmClientAllocParams {}
+
+/// Allocation parameters for an `NV01_DEVICE_0` RM device (`NV0080_ALLOC_PARAMETERS`).
+#[repr(transparent)]
+#[derive(Clone, Copy, Debug, Zeroable)]
+pub(crate) struct RmDeviceAllocParams(bindings::NV0080_ALLOC_PARAMETERS);
+
+static_assert!(size_of::<RmDeviceAllocParams>() == 56);
+
+impl RmDeviceAllocParams {
+ /// Creates allocation parameters for device `device_id` under `client_share`.
+ pub(crate) fn new(client_share: u32, device_id: u32) -> Self {
+ Self(bindings::NV0080_ALLOC_PARAMETERS {
+ deviceId: device_id,
+ hClientShare: client_share,
+ ..Zeroable::zeroed()
+ })
+ }
+}
+
+// SAFETY: Padding is explicit and initialized to zero.
+unsafe impl AsBytes for RmDeviceAllocParams {}
+
+// SAFETY: All bit patterns are valid for the integer fields.
+unsafe impl FromBytes for RmDeviceAllocParams {}
+
+/// Allocation parameters for an `NV20_SUBDEVICE_0` RM subdevice (`NV2080_ALLOC_PARAMETERS`).
+#[repr(transparent)]
+#[derive(Clone, Copy, Debug, Zeroable)]
+pub(crate) struct RmSubdeviceAllocParams(bindings::NV2080_ALLOC_PARAMETERS);
+
+static_assert!(size_of::<RmSubdeviceAllocParams>() == 4);
+
+impl RmSubdeviceAllocParams {
+ /// Creates allocation parameters for subdevice `subdevice_id`.
+ pub(crate) fn new(subdevice_id: u32) -> Self {
+ Self(bindings::NV2080_ALLOC_PARAMETERS {
+ subDeviceId: subdevice_id,
+ })
+ }
+}
+
+// SAFETY: This struct contains a single `u32` with no padding.
+unsafe impl AsBytes for RmSubdeviceAllocParams {}
+
+// SAFETY: All bit patterns are valid for `u32`.
+unsafe impl FromBytes for RmSubdeviceAllocParams {}
diff --git a/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs b/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
index afe3e007f088..0bf4e6a0a406 100644
--- a/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
+++ b/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
@@ -33,6 +33,13 @@ fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
pub const NV2080_CTRL_GPU_SET_POWER_STATE_GPU_LEVEL_0: u32 = 0;
pub const NV2080_CTRL_GPU_SET_POWER_STATE_GPU_LEVEL_3: u32 = 3;
pub const NV2080_CTRL_GPU_SET_POWER_STATE_GPU_LEVEL_7: u32 = 7;
+pub const NV01_ROOT: u32 = 0x0;
+pub const NV01_DEVICE_0: u32 = 0x80;
+pub const NV20_SUBDEVICE_0: u32 = 0x2080;
+pub const NV_OK: u32 = 0x0;
+pub const NV_ERR_NO_MEMORY: u32 = 0x51;
+pub const NV_ERR_NOT_READY: u32 = 0x55;
+pub const NV_ERR_TIMEOUT_RETRY: u32 = 0x66;
pub const NV_VGPU_MSG_SIGNATURE_VALID: u32 = 1129337430;
pub const GSP_FW_HEAP_PARAM_OS_SIZE_LIBOS2: u32 = 0;
pub const GSP_FW_HEAP_PARAM_OS_SIZE_LIBOS3_BAREMETAL: u32 = 23068672;
@@ -982,6 +989,72 @@ pub struct rpc_run_cpu_sequencer_v17_00 {
pub regSaveArea: [u32_; 8usize],
pub commandBuffer: __IncompleteArrayField<u32_>,
}
+#[repr(C)]
+#[derive(Debug, Default, MaybeZeroable)]
+pub struct rpc_gsp_rm_alloc_v03_00 {
+ pub hClient: u32_,
+ pub hParent: u32_,
+ pub hObject: u32_,
+ pub hClass: u32_,
+ pub status: u32_,
+ pub paramsSize: u32_,
+ pub flags: u32_,
+ pub reserved: [u8_; 4usize],
+ pub params: __IncompleteArrayField<u8_>,
+}
+#[repr(C)]
+#[derive(Debug, Default, MaybeZeroable)]
+pub struct rpc_gsp_rm_control_v03_00 {
+ pub hClient: u32_,
+ pub hObject: u32_,
+ pub cmd: u32_,
+ pub status: u32_,
+ pub paramsSize: u32_,
+ pub flags: u32_,
+ pub params: __IncompleteArrayField<u8_>,
+}
+#[repr(C)]
+#[derive(Debug, Default, Copy, Clone, MaybeZeroable)]
+pub struct NVOS00_PARAMETERS_v03_00 {
+ pub hRoot: u32_,
+ pub hObjectParent: u32_,
+ pub hObjectOld: u32_,
+ pub status: u32_,
+}
+#[repr(C)]
+#[derive(Debug, Default, Copy, Clone, MaybeZeroable)]
+pub struct rpc_free_v03_00 {
+ pub params: NVOS00_PARAMETERS_v03_00,
+}
+#[repr(C)]
+#[derive(Debug, Copy, Clone, MaybeZeroable)]
+pub struct NV0000_ALLOC_PARAMETERS {
+ pub hClient: u32_,
+ pub processID: u32_,
+ pub processName: [u8_; 100usize],
+ pub __bindgen_padding_0: [u8; 4usize],
+ pub pOsPidInfo: u64_,
+}
+#[repr(C)]
+#[derive(Debug, Default, Copy, Clone, MaybeZeroable)]
+pub struct NV0080_ALLOC_PARAMETERS {
+ pub deviceId: u32_,
+ pub hClientShare: u32_,
+ pub hTargetClient: u32_,
+ pub hTargetDevice: u32_,
+ pub flags: u32_,
+ pub __bindgen_padding_0: [u8; 4usize],
+ pub vaSpaceSize: u64_,
+ pub vaStartInternal: u64_,
+ pub vaLimitInternal: u64_,
+ pub vaMode: u32_,
+ pub __bindgen_padding_1: [u8; 4usize],
+}
+#[repr(C)]
+#[derive(Debug, Default, Copy, Clone, MaybeZeroable)]
+pub struct NV2080_ALLOC_PARAMETERS {
+ pub subDeviceId: u32_,
+}
pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_WRITE: GSP_SEQ_BUF_OPCODE = 0;
pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_MODIFY: GSP_SEQ_BUF_OPCODE = 1;
pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_POLL: GSP_SEQ_BUF_OPCODE = 2;
diff --git a/drivers/gpu/nova-core/gsp/rm.rs b/drivers/gpu/nova-core/gsp/rm.rs
new file mode 100644
index 000000000000..29bddfb699de
--- /dev/null
+++ b/drivers/gpu/nova-core/gsp/rm.rs
@@ -0,0 +1,640 @@
+// SPDX-License-Identifier: GPL-2.0-only
+
+//! GSP-RM object allocation, control, and client/device lifecycle management.
+//!
+//! GSP-RM organizes GPU resources in a handle hierarchy rooted at an RM client
+//! (`NV01_ROOT`), with child devices (`NV01_DEVICE_0`), subdevices
+//! (`NV20_SUBDEVICE_0`), and engine or memory objects underneath.
+//!
+//! This module models that hierarchy using Rust lifetimes and RAII:
+//! - [`RmClient`] borrows the [`Cmdq`] and [`RmClientIdAllocator`] from [`Gsp`].
+//! - [`RmDevice`] borrows its parent [`RmClient`].
+//! - [`RmSubdevice`] borrows its parent [`RmDevice`].
+//! - [`RmObject`] represents an arbitrary child object borrowing its [`RmClient`].
+//!
+//! Dropping any handle automatically issues a `FREE` RPC to GSP-RM, and the
+//! borrow hierarchy guarantees child objects are always freed before their
+//! parent device and client.
+
+use kernel::{
+ id_pool::IdPool,
+ new_mutex,
+ prelude::*,
+ sync::Mutex,
+ transmute::{
+ AsBytes,
+ FromBytes, //
+ }, //
+};
+
+use crate::gsp::{
+ cmdq::Cmdq,
+ commands::{
+ RmAlloc,
+ RmControl,
+ RmFree, //
+ },
+ fw::commands::{
+ RmClientAllocParams,
+ RmDeviceAllocParams,
+ RmSubdeviceAllocParams,
+ RM_CLASS_DEVICE,
+ RM_CLASS_ROOT,
+ RM_CLASS_SUBDEVICE, //
+ }, //
+};
+
+/// Base prefix for RM client handles allocated by nova-core.
+const RM_CLIENT_HANDLE_BASE: u32 = 0xc1d0_0000;
+
+/// Mask covering the 16-bit client ID encoded in an RM client handle.
+const RM_CLIENT_ID_MASK: u32 = 0x0000_ffff;
+
+/// Maximum number of concurrent RM client handles supported per GPU.
+const RM_CLIENT_MAX_IDS: usize = (RM_CLIENT_ID_MASK as usize) + 1;
+
+/// Fixed RM handle used for the primary device object under a client.
+const RM_DEVICE_HANDLE: RmHandle = RmHandle::new(0xde1d_0000);
+
+/// Fixed RM handle used for the primary subdevice object under a device.
+const RM_SUBDEVICE_HANDLE: RmHandle = RmHandle::new(0x5d1d_0000);
+
+/// Strongly typed GSP-RM object handle (`NvHandle`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+#[repr(transparent)]
+pub(crate) struct RmHandle(u32);
+
+impl RmHandle {
+ /// Creates an [`RmHandle`] from a raw 32-bit RM handle value.
+ pub(crate) const fn new(raw: u32) -> Self {
+ Self(raw)
+ }
+
+ /// Returns the raw 32-bit RM handle value.
+ pub(crate) const fn raw(self) -> u32 {
+ self.0
+ }
+
+ /// Encodes a client ID in `0..=0xffff` into a client [`RmHandle`].
+ ///
+ /// # Errors
+ ///
+ /// Returns `EINVAL` if `id` exceeds [`RM_CLIENT_ID_MASK`].
+ pub(crate) const fn client_from_id(id: u32) -> Result<Self> {
+ if id > RM_CLIENT_ID_MASK {
+ return Err(EINVAL);
+ }
+
+ Ok(Self(RM_CLIENT_HANDLE_BASE | id))
+ }
+
+ /// Extracts the client ID from a client [`RmHandle`], or [`None`] if the
+ /// handle does not carry the client prefix.
+ pub(crate) const fn client_id(self) -> Option<usize> {
+ if (self.0 & !RM_CLIENT_ID_MASK) == RM_CLIENT_HANDLE_BASE {
+ Some((self.0 & RM_CLIENT_ID_MASK) as usize)
+ } else {
+ None
+ }
+ }
+}
+
+/// Thread-safe allocator and recycler for RM client IDs backed by [`IdPool`].
+#[pin_data]
+pub(crate) struct RmClientIdAllocator {
+ #[pin]
+ pool: Mutex<IdPool>,
+}
+
+impl RmClientIdAllocator {
+ /// Creates an in-place initializer for an [`RmClientIdAllocator`].
+ pub(crate) fn new() -> impl PinInit<Self> {
+ pin_init!(Self {
+ pool <- new_mutex!(IdPool::new(), "nova_rm_client_ids"),
+ })
+ }
+
+ /// Allocates an unused client ID and returns its encoded [`RmHandle`].
+ ///
+ /// Grows the underlying [`IdPool`] outside the mutex if all currently
+ /// tracked slots are occupied.
+ ///
+ /// # Errors
+ ///
+ /// - `ENOSPC` if all [`RM_CLIENT_MAX_IDS`] client handles are in use.
+ /// - `ENOMEM` if growing the backing bitmap fails.
+ pub(crate) fn alloc(&self) -> Result<RmHandle> {
+ loop {
+ let mut pool = self.pool.lock();
+ if let Some(unused) = pool.find_unused_id(0) {
+ if unused.as_usize() >= RM_CLIENT_MAX_IDS {
+ return Err(ENOSPC);
+ }
+ let id = unused.as_u32();
+ let _ = unused.acquire();
+ return RmHandle::client_from_id(id);
+ }
+
+ if pool.capacity() >= RM_CLIENT_MAX_IDS {
+ return Err(ENOSPC);
+ }
+
+ let grow_req = pool.grow_request().ok_or(ENOSPC)?;
+ drop(pool);
+
+ let resizer = grow_req.realloc(GFP_KERNEL)?;
+ self.pool.lock().grow(resizer);
+ }
+ }
+
+ /// Releases a previously allocated client [`RmHandle`] back to the pool.
+ pub(crate) fn free(&self, handle: RmHandle) {
+ if let Some(id) = handle.client_id() {
+ self.pool.lock().release_id(id);
+ }
+ }
+}
+
+/// RAII handle to a GSP-RM root client (`NV01_ROOT`).
+///
+/// Dropping this handle sends a `FREE` RPC to GSP-RM and recycles its client ID.
+pub(crate) struct RmClient<'a, 'gsp> {
+ cmdq: &'a Cmdq<'gsp>,
+ allocator: &'a RmClientIdAllocator,
+ handle: RmHandle,
+}
+
+impl<'a, 'gsp> RmClient<'a, 'gsp> {
+ /// Allocates a new GSP-RM root client (`NV01_ROOT`).
+ pub(super) fn new(cmdq: &'a Cmdq<'gsp>, allocator: &'a RmClientIdAllocator) -> Result<Self> {
+ let handle = allocator.alloc()?;
+ let params = RmClientAllocParams::new(handle.raw());
+
+ if let Err(e) = cmdq.send_command(RmAlloc::new(
+ handle.raw(),
+ handle.raw(),
+ handle.raw(),
+ RM_CLASS_ROOT,
+ ¶ms,
+ )) {
+ allocator.free(handle);
+ return Err(e);
+ }
+
+ Ok(Self {
+ cmdq,
+ allocator,
+ handle,
+ })
+ }
+
+ /// Returns this client's [`RmHandle`].
+ pub(crate) const fn handle(&self) -> RmHandle {
+ self.handle
+ }
+
+ /// Allocates an RM device (`NV01_DEVICE_0`) belonging to this client.
+ #[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))]
+ pub(crate) fn alloc_device(&self, device_id: u32) -> Result<RmDevice<'_, 'gsp>> {
+ RmDevice::new(self, device_id)
+ }
+
+ /// Allocates an arbitrary RM child object under `parent` using typed parameters `P`.
+ #[expect(dead_code)]
+ pub(crate) fn alloc_object<P: AsBytes + FromBytes>(
+ &self,
+ parent: RmHandle,
+ object: RmHandle,
+ class: u32,
+ params: &P,
+ ) -> Result<RmObject<'_, 'gsp>> {
+ self.cmdq.send_command(RmAlloc::new(
+ self.handle.raw(),
+ parent.raw(),
+ object.raw(),
+ class,
+ params,
+ ))?;
+
+ Ok(RmObject {
+ cmdq: self.cmdq,
+ client_handle: self.handle,
+ handle: object,
+ })
+ }
+
+ /// Invokes a `GSP_RM_CONTROL` call targeting `object` under this client.
+ #[expect(dead_code)]
+ pub(crate) fn control<P: AsBytes + FromBytes + Zeroable>(
+ &self,
+ object: RmHandle,
+ cmd: u32,
+ params: &P,
+ ) -> Result<P> {
+ let reply =
+ self.cmdq
+ .send_command(RmControl::new(self.handle.raw(), object.raw(), cmd, params))?;
+
+ Ok(reply.params)
+ }
+}
+
+impl Drop for RmClient<'_, '_> {
+ fn drop(&mut self) {
+ let _ = self
+ .cmdq
+ .send_command(RmFree::new(self.handle.raw(), self.handle.raw()));
+ self.allocator.free(self.handle);
+ }
+}
+
+/// RAII handle to a GSP-RM device (`NV01_DEVICE_0`).
+///
+/// Borrows its parent [`RmClient`] so the device is always freed before its client.
+#[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))]
+pub(crate) struct RmDevice<'a, 'gsp> {
+ cmdq: &'a Cmdq<'gsp>,
+ client_handle: RmHandle,
+ handle: RmHandle,
+}
+
+#[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))]
+impl<'a, 'gsp> RmDevice<'a, 'gsp> {
+ /// Allocates an `NV01_DEVICE_0` object under `client`.
+ fn new(client: &'a RmClient<'_, 'gsp>, device_id: u32) -> Result<Self> {
+ let handle = RM_DEVICE_HANDLE;
+ let client_handle = client.handle();
+ let params = RmDeviceAllocParams::new(client_handle.raw(), device_id);
+
+ client.cmdq.send_command(RmAlloc::new(
+ client_handle.raw(),
+ client_handle.raw(),
+ handle.raw(),
+ RM_CLASS_DEVICE,
+ ¶ms,
+ ))?;
+
+ Ok(Self {
+ cmdq: client.cmdq,
+ client_handle,
+ handle,
+ })
+ }
+
+ /// Returns this device's [`RmHandle`].
+ pub(crate) const fn handle(&self) -> RmHandle {
+ self.handle
+ }
+
+ /// Allocates an RM subdevice (`NV20_SUBDEVICE_0`) belonging to this device.
+ pub(crate) fn alloc_subdevice(&self, subdevice_id: u32) -> Result<RmSubdevice<'_, 'gsp>> {
+ RmSubdevice::new(self, subdevice_id)
+ }
+
+ /// Invokes a `GSP_RM_CONTROL` call targeting this device.
+ #[expect(dead_code)]
+ pub(crate) fn control<P: AsBytes + FromBytes + Zeroable>(
+ &self,
+ cmd: u32,
+ params: &P,
+ ) -> Result<P> {
+ let reply = self.cmdq.send_command(RmControl::new(
+ self.client_handle.raw(),
+ self.handle.raw(),
+ cmd,
+ params,
+ ))?;
+
+ Ok(reply.params)
+ }
+}
+
+impl Drop for RmDevice<'_, '_> {
+ fn drop(&mut self) {
+ let _ = self
+ .cmdq
+ .send_command(RmFree::new(self.client_handle.raw(), self.handle.raw()));
+ }
+}
+
+/// RAII handle to a GSP-RM subdevice (`NV20_SUBDEVICE_0`).
+///
+/// Borrows its parent [`RmDevice`] so the subdevice is always freed before its device.
+#[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))]
+pub(crate) struct RmSubdevice<'a, 'gsp> {
+ cmdq: &'a Cmdq<'gsp>,
+ client_handle: RmHandle,
+ handle: RmHandle,
+}
+
+#[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))]
+impl<'a, 'gsp> RmSubdevice<'a, 'gsp> {
+ /// Allocates an `NV20_SUBDEVICE_0` object under `device`.
+ fn new(device: &'a RmDevice<'_, 'gsp>, subdevice_id: u32) -> Result<Self> {
+ let handle = RM_SUBDEVICE_HANDLE;
+ let params = RmSubdeviceAllocParams::new(subdevice_id);
+ let client_handle = device.client_handle;
+
+ device.cmdq.send_command(RmAlloc::new(
+ client_handle.raw(),
+ device.handle().raw(),
+ handle.raw(),
+ RM_CLASS_SUBDEVICE,
+ ¶ms,
+ ))?;
+
+ Ok(Self {
+ cmdq: device.cmdq,
+ client_handle,
+ handle,
+ })
+ }
+
+ /// Returns this subdevice's [`RmHandle`].
+ pub(crate) const fn handle(&self) -> RmHandle {
+ self.handle
+ }
+
+ /// Invokes a `GSP_RM_CONTROL` call targeting this subdevice.
+ #[expect(dead_code)]
+ pub(crate) fn control<P: AsBytes + FromBytes + Zeroable>(
+ &self,
+ cmd: u32,
+ params: &P,
+ ) -> Result<P> {
+ let reply = self.cmdq.send_command(RmControl::new(
+ self.client_handle.raw(),
+ self.handle.raw(),
+ cmd,
+ params,
+ ))?;
+
+ Ok(reply.params)
+ }
+}
+
+impl Drop for RmSubdevice<'_, '_> {
+ fn drop(&mut self) {
+ let _ = self
+ .cmdq
+ .send_command(RmFree::new(self.client_handle.raw(), self.handle.raw()));
+ }
+}
+
+/// RAII handle to an arbitrary child RM object allocated under an [`RmClient`].
+#[expect(dead_code)]
+pub(crate) struct RmObject<'a, 'gsp> {
+ cmdq: &'a Cmdq<'gsp>,
+ client_handle: RmHandle,
+ handle: RmHandle,
+}
+
+#[expect(dead_code)]
+impl RmObject<'_, '_> {
+ /// Returns this object's [`RmHandle`].
+ pub(crate) const fn handle(&self) -> RmHandle {
+ self.handle
+ }
+
+ /// Invokes a `GSP_RM_CONTROL` call targeting this object.
+ pub(crate) fn control<P: AsBytes + FromBytes + Zeroable>(
+ &self,
+ cmd: u32,
+ params: &P,
+ ) -> Result<P> {
+ let reply = self.cmdq.send_command(RmControl::new(
+ self.client_handle.raw(),
+ self.handle.raw(),
+ cmd,
+ params,
+ ))?;
+
+ Ok(reply.params)
+ }
+}
+
+impl Drop for RmObject<'_, '_> {
+ fn drop(&mut self) {
+ let _ = self
+ .cmdq
+ .send_command(RmFree::new(self.client_handle.raw(), self.handle.raw()));
+ }
+}
+
+/// Probe-time self-test verifying RM client, device, and subdevice allocation
+/// and teardown against the booted GSP.
+#[cfg(CONFIG_NOVA_CORE_SELFTESTS)]
+pub(crate) fn run_selftest(
+ dev: &kernel::device::Device<kernel::device::Bound>,
+ gsp: &crate::gsp::Gsp<'_>,
+) -> Result {
+ dev_info!(dev, "GSP RM: Starting client/device self-test...\n");
+
+ let client = gsp.alloc_client()?;
+ let device = client.alloc_device(0)?;
+ let subdevice = device.alloc_subdevice(0)?;
+
+ dev_info!(
+ dev,
+ "GSP RM: Allocated client={:#x}, device={:#x}, subdevice={:#x}\n",
+ client.handle().raw(),
+ device.handle().raw(),
+ subdevice.handle().raw()
+ );
+
+ drop(subdevice);
+ drop(device);
+ drop(client);
+
+ dev_info!(dev, "GSP RM: Self-test PASSED\n");
+ Ok(())
+}
+
+#[kunit_tests(nova_core_gsp_rm)]
+mod tests {
+ use super::*;
+
+ use crate::{
+ gsp::{
+ cmdq::{
+ CommandToGsp,
+ MessageFromGsp, //
+ },
+ commands::{
+ RmAllocReply,
+ RmControlReply,
+ RmFreeReply, //
+ },
+ fw::commands::{
+ GspRmAllocHeader,
+ GspRmControlHeader,
+ GspRmFree,
+ RmStatus, //
+ }, //
+ },
+ sbuffer::SBufferIter, //
+ };
+
+ #[repr(C)]
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Zeroable)]
+ struct TestCtrlParams {
+ arg: u32,
+ out: u32,
+ }
+
+ // SAFETY: `TestCtrlParams` consists only of two `u32` fields with no padding.
+ unsafe impl AsBytes for TestCtrlParams {}
+
+ // SAFETY: All bit patterns are valid for `u32` fields.
+ unsafe impl FromBytes for TestCtrlParams {}
+
+ #[test]
+ fn handle_client_encoding_and_bounds() -> Result {
+ let h0 = RmHandle::client_from_id(0)?;
+ assert_eq!(h0.raw(), 0xc1d0_0000);
+ assert_eq!(h0.client_id(), Some(0));
+
+ let hmax = RmHandle::client_from_id(0xffff)?;
+ assert_eq!(hmax.raw(), 0xc1d0_ffff);
+ assert_eq!(hmax.client_id(), Some(0xffff));
+
+ assert_eq!(RmHandle::client_from_id(0x1_0000), Err(EINVAL));
+ assert_eq!(RM_DEVICE_HANDLE.client_id(), None);
+ assert_eq!(RM_SUBDEVICE_HANDLE.client_id(), None);
+
+ Ok(())
+ }
+
+ #[test]
+ fn client_id_allocator_recycles_and_grows() -> Result {
+ let alloc = KBox::pin_init(RmClientIdAllocator::new(), GFP_KERNEL)?;
+
+ // Allocate beyond the initial inline IdPool capacity (64) to exercise growth.
+ let mut handles = KVec::with_capacity(80, GFP_KERNEL)?;
+ for expected in 0..80u32 {
+ let h = alloc.alloc()?;
+ assert_eq!(h, RmHandle::client_from_id(expected)?);
+ handles.push(h, GFP_KERNEL)?;
+ }
+
+ // Release an ID in the middle and verify it is recycled first.
+ alloc.free(handles[17]);
+ let reused = alloc.alloc()?;
+ assert_eq!(reused, RmHandle::client_from_id(17)?);
+
+ // Clean up all allocated handles.
+ for h in handles {
+ alloc.free(h);
+ }
+
+ // Slot 0 should now be available again.
+ assert_eq!(alloc.alloc()?, RmHandle::client_from_id(0)?);
+
+ Ok(())
+ }
+
+ #[test]
+ fn rm_status_mapping() {
+ assert_eq!(RmStatus::from_raw(0x0).into_result(), Ok(()));
+ assert_eq!(RmStatus::from_raw(0x51).into_result(), Err(ENOMEM));
+ assert_eq!(RmStatus::from_raw(0x55).into_result(), Err(EBUSY));
+ assert_eq!(RmStatus::from_raw(0x66).into_result(), Err(EBUSY));
+ assert_eq!(RmStatus::from_raw(0xdead_beef).into_result(), Err(EINVAL));
+ assert_eq!(RmStatus::from_raw(0x55).raw(), 0x55);
+ }
+
+ #[test]
+ fn rm_alloc_and_free_serialization() -> Result {
+ let client = RmHandle::client_from_id(3)?;
+ let params = RmClientAllocParams::new(client.raw());
+ let cmd = RmAlloc::new(
+ client.raw(),
+ client.raw(),
+ client.raw(),
+ RM_CLASS_ROOT,
+ ¶ms,
+ );
+
+ assert_eq!(cmd.variable_payload_len(), size_of::<RmClientAllocParams>());
+ let mut payload = KVec::zeroed(cmd.variable_payload_len(), GFP_KERNEL)?;
+ let mut sbuf = SBufferIter::new_writer([payload.as_mut_slice(), &mut []]);
+ cmd.init_variable_payload(&mut sbuf)?;
+ assert!(sbuf.is_empty());
+ drop(sbuf);
+ assert_eq!(payload.as_slice(), params.as_bytes());
+
+ // Verify reply decoding drains trailing echoed parameter bytes.
+ let ok_hdr = KBox::init(
+ GspRmAllocHeader::init(
+ client.raw(),
+ client.raw(),
+ client.raw(),
+ RM_CLASS_ROOT,
+ size_of::<RmClientAllocParams>(),
+ ),
+ GFP_KERNEL,
+ )?;
+ let mut reply_sbuf = SBufferIter::new_reader([payload.as_slice(), &[]]);
+ let _ = RmAllocReply::read(&ok_hdr, &mut reply_sbuf)?;
+ assert!(reply_sbuf.is_empty());
+
+ // Verify RmFree command size and reply payload handling.
+ let free_ok = GspRmFree::new(client.raw(), RM_DEVICE_HANDLE.raw());
+ assert_eq!(free_ok.as_bytes().len(), 16);
+ let mut empty = SBufferIter::new_reader([&[][..], &[][..]]);
+ let _ = RmFreeReply::read(&free_ok, &mut empty)?;
+
+ Ok(())
+ }
+
+ #[test]
+ fn rm_control_roundtrip_and_error() -> Result {
+ let client = RmHandle::client_from_id(1)?;
+ let req = TestCtrlParams {
+ arg: 0x1234_5678,
+ out: 0,
+ };
+ let cmd = RmControl::new(client.raw(), RM_SUBDEVICE_HANDLE.raw(), 0x2080_0101, &req);
+
+ assert_eq!(cmd.variable_payload_len(), size_of::<TestCtrlParams>());
+ let mut req_buf = [0u8; size_of::<TestCtrlParams>()];
+ let mut wbuf = SBufferIter::new_writer([&mut req_buf[..], &mut []]);
+ cmd.init_variable_payload(&mut wbuf)?;
+ drop(wbuf);
+ assert_eq!(&req_buf, req.as_bytes());
+
+ // Simulate a reply carrying updated output parameters split across slices.
+ let expected = TestCtrlParams {
+ arg: 0x1234_5678,
+ out: 0xcafe_babe,
+ };
+ let hdr = KBox::init(
+ GspRmControlHeader::init(
+ client.raw(),
+ RM_SUBDEVICE_HANDLE.raw(),
+ 0x2080_0101,
+ size_of::<TestCtrlParams>(),
+ ),
+ GFP_KERNEL,
+ )?;
+ let (p1, p2) = expected.as_bytes().split_at(3);
+ let mut rbuf = SBufferIter::new_reader([p1, p2]);
+ let reply = RmControlReply::<TestCtrlParams>::read(&hdr, &mut rbuf)?;
+ assert_eq!(reply.params, expected);
+ assert!(rbuf.is_empty());
+
+ // Simulate a non-zero NV_STATUS error in reply header (`NV_ERR_NO_MEMORY`).
+ let mut err_hdr_bytes = [0u8; size_of::<GspRmControlHeader>()];
+ err_hdr_bytes.copy_from_slice(hdr.as_bytes());
+ // `status` is the 4th `u32` field (byte offset 12) in `rpc_gsp_rm_control_v03_00`.
+ err_hdr_bytes[12..16].copy_from_slice(&0x51u32.to_le_bytes());
+ let err_hdr = GspRmControlHeader::from_bytes(&err_hdr_bytes).ok_or(EIO)?;
+ let mut rbuf2 = SBufferIter::new_reader([p1, p2]);
+ assert!(matches!(
+ RmControlReply::<TestCtrlParams>::read(err_hdr, &mut rbuf2),
+ Err(ENOMEM)
+ ));
+
+ Ok(())
+ }
+}
diff --git a/drivers/gpu/nova-core/sbuffer.rs b/drivers/gpu/nova-core/sbuffer.rs
index 3a41d224c77a..b8c01104c255 100644
--- a/drivers/gpu/nova-core/sbuffer.rs
+++ b/drivers/gpu/nova-core/sbuffer.rs
@@ -146,7 +146,6 @@ fn get_slice(&mut self, len: usize) -> Option<&'a [u8]> {
/// Ideally we would implement `Read`, but it is not available in `core`.
/// So mimic `std::io::Read::read_exact`.
- #[expect(unused)]
pub(crate) fn read_exact(&mut self, mut dst: &mut [u8]) -> Result {
while !dst.is_empty() {
match self.get_slice(dst.len()) {
base-commit: 693c2e04e3f1d4c59af236e1211b7b8cb165a790
--
2.56.1
^ permalink raw reply [flat|nested] 3+ messages in thread
* Re: [RFC PATCH v2] gpu: nova-core: gsp: retain debugfs logs on teardown and capture logpmu
2026-12-02 2:50 [RFC PATCH v2] gpu: nova-core: gsp: retain debugfs logs on teardown and capture logpmu Agustín Pereira
2026-12-02 2:50 ` [RFC PATCH v2] gpu: nova-core: gsp: add RM alloc/control/free RPCs and client/device API Agustín Pereira
@ 2026-12-02 3:37 ` John Hubbard
1 sibling, 0 replies; 3+ messages in thread
From: John Hubbard @ 2026-12-02 3:37 UTC (permalink / raw)
To: Agustín Pereira, Danilo Krummrich, Alexandre Courbot
Cc: David Airlie, Simona Vetter, Miguel Ojeda, nova-gpu, dri-devel,
rust-for-linux, linux-kernel
On 12/1/26 6:50 PM, Agustín Pereira wrote:
> Currently nova-core exposes the GSP-RM logging buffers (`loginit`,
> `logintr`, and `logrm`) via a `debugfs::Scope` tied to `Gsp`. When
> `Gsp::boot()` fails during `probe()` or when the device is unbound, the
> scope is dropped immediately and its `debugfs` entries are removed,
> making post-mortem inspection of firmware boot failures impossible. In
Please go read the nova-gpu mailing list, and look at the code in
drm-rust-next, and you will find that this has already been done.
Sending a large, AI-generated garbage patch with line noise in the
commit message, to a group whose code you haven't even bothered to
read (it's in drm-rust-next) is not helpful.
thanks,
--
John Hubbard
> addition, `UCODE_LIBOS_PRINT` events from the PMU are silently discarded
> by the command queue, so no `logpmu` buffer is captured or exposed.
>
> Move the GSP logging infrastructure into a dedicated `gsp::logs` module
> and address both gaps:
>
> - Capture `MsgFunction::UcodeLibOsPrint` events in `handle_event()`
> before advancing the queue read pointer, validating the
> `rpc_ucode_libos_print_v1e_08` header (PMU engine class `0xf3d722` and
> payload size `<= GSP_PAGE_SIZE`) and storing the latest dump in a
> mutex-protected `PmuLogBuffer` exposed as `logpmu` in `debugfs`.
> - Add a boolean `keep_gsp_logging` module parameter (default `false`) and
> a module-scoped `RETAINED_LOGS` global mutex. Relying on `debugfs::Scope`
> dropping its `debugfs` directory entry before its inner `LogBuffers`,
> `LogBuffers::drop` validates each DMA buffer's put pointer
> (`1 <= pp < LOG_BUFFER_SIZE / size_of::<u64>()`) and snapshots any
> non-empty buffers (including `logpmu`) into regular kernel memory
> (`KVVec<u8>`) before re-publishing them under
> `/sys/kernel/debug/nova-core` until module unload or a subsequent
> `probe()` of the same device.
> - Add KUnit unit tests (`nova_core_gsp_logs`) covering put-pointer
> validation, ring-wraparound PMU event capture, zero-padding on shorter
> subsequent dumps, and rejection of malformed events without clobbering
> existing data.
>
> Testing:
> - Compiled `drivers/gpu/nova-core.o` and `drivers/gpu/nova-drm.o` with
> `LLVM=1 W=1 CLIPPY=1` (`CONFIG_RUST=y`, `CONFIG_NOVA_CORE=m`,
> `CONFIG_DRM_NOVA=m`) under both (`CONFIG_DEBUG_FS=y`, `CONFIG_KUNIT=y`,
> `CONFIG_NOVA_CORE_SELFTESTS=y`) and (`CONFIG_DEBUG_FS=n`,
> `CONFIG_KUNIT=n`, `CONFIG_NOVA_CORE_SELFTESTS=n`) with zero warnings.
> - Verified formatting with `rustfmt --check` and patch style with
> `scripts/checkpatch.pl`.
> - Tested on NVIDIA GeForce RTX 4070 Laptop GPU (AD106M, Ada, rev a.1)
> with r570.144 TLV firmware on 7.4.0-rc5: verified non-empty `loginit`,
> `logintr`, `logrm`, and `logpmu` capture, bit-for-bit identical SHA-256
> checksums across PCI `unbind` with `keep_gsp_logging=1`, clean re-bind
> without `EEXIST`, and clean module unload.
>
> This change was drafted with the assistance of an AI coding assistant.
>
> Signed-off-by: Agustín Pereira <agustin.pereira.ro@gmail.com>
> ---
> Changes in v2:
> - Use FromBytes::from_bytes_copy() in PmuLogBuffer::capture_event() to avoid
> alignment failures on the stack buffer (reported by Sashiko AI review).
> - Replace RETAINED_LOGS.lock().clear() with *RETAINED_LOGS.lock() = KVec::new()
> in DebugfsRootGuard::drop() so the KVec backing buffer is freed on module
> unload (reported by Sashiko AI review).
> - Tested on real hardware: NVIDIA GeForce RTX 4070 Laptop GPU (AD106M, Ada,
> rev a.1, r570.144 TLV firmware) on 7.4.0-rc5; verified non-empty loginit,
> logintr, logrm, and logpmu capture, bit-for-bit identical SHA-256 across
> PCI unbind, clean re-bind without EEXIST, and clean module unload.
>
> drivers/gpu/nova-core/gsp.rs | 121 ++---
> drivers/gpu/nova-core/gsp/cmdq.rs | 46 +-
> drivers/gpu/nova-core/gsp/fw.rs | 36 ++
> .../gpu/nova-core/gsp/fw/r570_144/bindings.rs | 7 +
> drivers/gpu/nova-core/gsp/logs.rs | 450 ++++++++++++++++++
> drivers/gpu/nova-core/nova_core.rs | 56 ++-
> drivers/gpu/nova-core/sbuffer.rs | 1 -
> 7 files changed, 627 insertions(+), 90 deletions(-)
> create mode 100644 drivers/gpu/nova-core/gsp/logs.rs
>
> diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs
> index dda58095f40b..69c332bba739 100644
> --- a/drivers/gpu/nova-core/gsp.rs
> +++ b/drivers/gpu/nova-core/gsp.rs
> @@ -12,18 +12,16 @@
> CoherentView,
> DmaAddress, //
> },
> - io::{
> - io_project,
> - io_write,
> - Io, //
> - },
> + io::io_write,
> pci,
> - prelude::*, //
> + prelude::*,
> + sync::Arc, //
> };
>
> pub(crate) mod cmdq;
> pub(crate) mod commands;
> mod fw;
> +pub(crate) mod logs;
> mod regs;
> mod sequencer;
>
> @@ -46,7 +44,12 @@
> gpu::Chipset,
> gsp::{
> cmdq::Cmdq,
> - fw::GspArgumentsPadded, //
> + fw::GspArgumentsPadded,
> + logs::{
> + LogBuffer,
> + LogBuffers,
> + PmuLogBuffer, //
> + }, //
> },
> num,
> vgpu::VgpuManager, //
> @@ -77,10 +80,6 @@ pub(crate) fn dev(&self) -> &'gpu device::Device<device::Bound> {
> }
> }
>
> -/// Number of GSP pages to use in a RM log buffer.
> -const RM_LOG_BUFFER_NUM_PAGES: usize = 0x10;
> -const LOG_BUFFER_SIZE: usize = RM_LOG_BUFFER_NUM_PAGES * GSP_PAGE_SIZE;
> -
> /// Array of page table entries, as understood by the GSP bootloader.
> #[repr(C)]
> #[derive(FromBytes, IntoBytes)]
> @@ -101,66 +100,26 @@ fn init(view: CoherentView<'_, Self>, start: DmaAddress) -> Result<()> {
> }
> }
>
> -/// The logging buffers are byte queues that contain encoded printf-like
> -/// messages from GSP-RM. They need to be decoded by a special application
> -/// that can parse the buffers.
> -///
> -/// The 'loginit' buffer contains logs from early GSP-RM init and
> -/// exception dumps. The 'logrm' buffer contains the subsequent logs. Both are
> -/// written to directly by GSP-RM and can be any multiple of GSP_PAGE_SIZE.
> -///
> -/// The physical address map for the log buffer is stored in the buffer
> -/// itself, starting with offset 1. Offset 0 contains the "put" pointer (pp).
> -/// Initially, pp is equal to 0. If the buffer has valid logging data in it,
> -/// then pp points to index into the buffer where the next logging entry will
> -/// be written. Therefore, the logging data is valid if:
> -/// 1 <= pp < sizeof(buffer)/sizeof(u64)
> -struct LogBuffer<'a>(Coherent<'a, [u8; LOG_BUFFER_SIZE]>);
> -
> -impl<'a> LogBuffer<'a> {
> - /// Creates a new `LogBuffer` mapped on `dev`.
> - fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
> - let obj = Self(Coherent::zeroed(dev, GFP_KERNEL)?);
> -
> - let start_addr = obj.0.dma_address();
> -
> - let pte_view = io_project!(
> - obj.0,
> - [build: size_of::<u64>()..][build: ..RM_LOG_BUFFER_NUM_PAGES * size_of::<u64>()]
> - )
> - .try_cast::<PteArray<RM_LOG_BUFFER_NUM_PAGES>>()?;
> - PteArray::init(pte_view, start_addr)?;
> -
> - Ok(obj)
> - }
> -}
> -
> -struct LogBuffers<'a> {
> - /// Init log buffer.
> - loginit: LogBuffer<'a>,
> - /// Interrupts log buffer.
> - logintr: LogBuffer<'a>,
> - /// RM log buffer.
> - logrm: LogBuffer<'a>,
> -}
> -
> /// GSP runtime data.
> #[pin_data]
> pub(crate) struct Gsp<'gsp> {
> /// Libos arguments.
> pub(crate) libos: Coherent<'gsp, [LibosMemoryRegionInitArgument]>,
> - /// Log buffers, optionally exposed via debugfs.
> - #[pin]
> - logs: debugfs::Scope<LogBuffers<'gsp>>,
> /// Command queue.
> + ///
> + /// Declared before `logs` so the command queue drops its handle to the PMU
> + /// log buffer before `logs` snapshots and tears down its `debugfs` entries.
> #[pin]
> pub(crate) cmdq: Cmdq<'gsp>,
> + /// Log buffers, optionally exposed via `debugfs` and retained on teardown.
> + #[pin]
> + logs: debugfs::Scope<LogBuffers<'gsp>>,
> /// RM arguments.
> rmargs: Coherent<'gsp, GspArgumentsPadded>,
> }
>
> impl<'gsp> Gsp<'gsp> {
> - // Creates an in-place initializer for a `Gsp` manager for `pdev`.
> + /// Creates an in-place initializer for a [`Gsp`] manager for `pdev`.
> pub(crate) fn new(
> pdev: &'gsp pci::Device<device::Bound>,
> bar: Bar0<'gsp>,
> @@ -171,12 +130,17 @@ pub(crate) fn new(
> let loginit = LogBuffer::new(dev)?;
> let logintr = LogBuffer::new(dev)?;
> let logrm = LogBuffer::new(dev)?;
> + let logpmu = Arc::pin_init(PmuLogBuffer::new(), GFP_KERNEL)?;
> +
> + // Remove any retained post-mortem log directory for this device
> + // before publishing the live `debugfs` entries.
> + crate::clear_retained_logs_for(dev.name());
>
> // Initialise the logging structures. The OpenRM equivalents are in:
> // _kgspInitLibosLoggingStructures (allocates memory for buffers)
> // kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array)
> Ok(try_pin_init!(Self {
> - cmdq <- Cmdq::new(dev, bar),
> + cmdq <- Cmdq::new(dev, bar, logpmu.clone()),
> rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?,
> libos: {
> let mut libos = CoherentBox::zeroed_slice(
> @@ -185,34 +149,31 @@ pub(crate) fn new(
> GFP_KERNEL,
> )?;
>
> - libos.init_at(0, LibosMemoryRegionInitArgument::new("LOGINIT", &loginit.0))?;
> - libos.init_at(1, LibosMemoryRegionInitArgument::new("LOGINTR", &logintr.0))?;
> - libos.init_at(2, LibosMemoryRegionInitArgument::new("LOGRM", &logrm.0))?;
> + libos.init_at(
> + 0,
> + LibosMemoryRegionInitArgument::new("LOGINIT", loginit.dma_coherent()),
> + )?;
> + libos.init_at(
> + 1,
> + LibosMemoryRegionInitArgument::new("LOGINTR", logintr.dma_coherent()),
> + )?;
> + libos.init_at(
> + 2,
> + LibosMemoryRegionInitArgument::new("LOGRM", logrm.dma_coherent()),
> + )?;
> libos.init_at(3, LibosMemoryRegionInitArgument::new("RMARGS", rmargs))?;
>
> libos.into()
> },
> logs <- {
> - let log_buffers = LogBuffers {
> - loginit,
> - logintr,
> - logrm,
> - };
> -
> - #[allow(static_mut_refs)]
> - // SAFETY: `DEBUGFS_ROOT` is created before driver registration and cleared
> - // after driver unregistration, so no probe() can race with its modification.
> - //
> - // PANIC: `DEBUGFS_ROOT` cannot be `None` here. It is set before driver
> - // registration and cleared after driver unregistration, so it is always
> - // `Some` for the entire lifetime that probe() can be called.
> - let log_parent: &debugfs::Dir = unsafe { crate::DEBUGFS_ROOT.as_ref() }
> - .expect("DEBUGFS_ROOT not initialized");
> + let log_buffers = LogBuffers::new(dev, loginit, logintr, logrm, logpmu);
> + let log_parent = crate::debugfs_root();
>
> log_parent.scope(log_buffers, dev.name(), |logs, dir| {
> - dir.read_binary_file(c"loginit", &logs.loginit.0);
> - dir.read_binary_file(c"logintr", &logs.logintr.0);
> - dir.read_binary_file(c"logrm", &logs.logrm.0);
> + dir.read_binary_file(c"loginit", logs.loginit.dma_coherent());
> + dir.read_binary_file(c"logintr", logs.logintr.dma_coherent());
> + dir.read_binary_file(c"logrm", logs.logrm.dma_coherent());
> + dir.read_binary_file(c"logpmu", &logs.logpmu);
> })
> },
> }))
> diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs
> index 1b2f346a237f..f29625ee6910 100644
> --- a/drivers/gpu/nova-core/gsp/cmdq.rs
> +++ b/drivers/gpu/nova-core/gsp/cmdq.rs
> @@ -26,6 +26,7 @@
> Read,
> Write, //
> },
> + Arc,
> Mutex, //
> },
> time::{
> @@ -56,6 +57,7 @@
> MsgqTxHeader,
> GSP_MSG_QUEUE_ELEMENT_SIZE_MAX, //
> },
> + logs::PmuLogBuffer,
> PteArray,
> GSP_PAGE_SHIFT,
> GSP_PAGE_SIZE, //
> @@ -529,6 +531,7 @@ impl<'cmdq> Cmdq<'cmdq> {
> pub(crate) fn new(
> dev: &'cmdq device::Device<device::Bound>,
> bar: Bar0<'cmdq>,
> + pmu_log: Arc<PmuLogBuffer>,
> ) -> impl PinInit<Self, Error> + 'cmdq {
> pin_init_scope(move || {
> let gsp_mem = DmaGspMem::new(dev)?;
> @@ -540,6 +543,7 @@ pub(crate) fn new(
> bar,
> gsp_mem,
> seq: 0,
> + pmu_log,
> }),
> }))
> })
> @@ -655,6 +659,8 @@ struct CmdqInner<'a> {
> seq: u32,
> /// Memory area shared with the GSP for communicating commands and messages.
> gsp_mem: DmaGspMem<'a>,
> + /// Buffer capturing PMU `UCODE_LIBOS_PRINT` events.
> + pmu_log: Arc<PmuLogBuffer>,
> }
>
> impl CmdqInner<'_> {
> @@ -882,7 +888,7 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>
> }
> })
> } else {
> - self.log_event(function, seq);
> + self.handle_event(function, seq, message.contents);
>
> Err(ENOMSG)
> };
> @@ -926,12 +932,13 @@ fn await_msg<M: MessageFromGsp>(&mut self) -> Result<M>
> }
> }
>
> - /// Logs an event, meaning a message that no caller was waiting for.
> + /// Handles an event, meaning a message that no caller was waiting for.
> ///
> - /// An OS error or robust-channel record is logged at error level and an unknown function code
> - /// at warning level. Every other event is recorded only by the receive trace in
> - /// [`Self::wait_for_msg`].
> - fn log_event(&self, function: Result<MsgFunction, u32>, seq: u32) {
> + /// An OS error or robust-channel record is logged at error level, a PMU
> + /// `UCODE_LIBOS_PRINT` dump is captured into `logpmu`, and an unknown
> + /// function code is logged at warning level. Every other event is recorded
> + /// only by the receive trace in [`Self::wait_for_msg`].
> + fn handle_event(&self, function: Result<MsgFunction, u32>, seq: u32, contents: (&[u8], &[u8])) {
> match function {
> Ok(MsgFunction::OsErrorLog) => {
> dev_err!(&self.dev, "GSP reported an OS error (seq {})\n", seq);
> @@ -943,6 +950,31 @@ fn log_event(&self, function: Result<MsgFunction, u32>, seq: u32) {
> seq
> );
> }
> + Ok(MsgFunction::UcodeLibOsPrint) => match self.pmu_log.capture_event(contents) {
> + Ok(size) => {
> + dev_dbg!(
> + &self.dev,
> + "captured PMU libos print buffer ({} bytes, seq {})\n",
> + size,
> + seq
> + );
> + }
> + Err(ENOMSG) => {
> + dev_dbg!(
> + &self.dev,
> + "ignoring non-PMU libos print event (seq {})\n",
> + seq
> + );
> + }
> + Err(e) => {
> + dev_warn!(
> + &self.dev,
> + "failed to capture PMU libos print event (seq {}): {:?}\n",
> + seq,
> + e
> + );
> + }
> + },
> // Nothing to do for the remaining known function codes.
> Ok(_) => {}
> Err(raw) => {
> @@ -975,8 +1007,8 @@ fn drain(&mut self) -> Result {
> let function = msg.header.function();
> let seq = msg.header.sequence();
>
> + self.handle_event(function, seq, msg.contents);
> self.gsp_mem.advance_cpu_read_ptr(pages);
> - self.log_event(function, seq);
> }
>
> Ok(())
> diff --git a/drivers/gpu/nova-core/gsp/fw.rs b/drivers/gpu/nova-core/gsp/fw.rs
> index 918a7ae809eb..8ef96868ace0 100644
> --- a/drivers/gpu/nova-core/gsp/fw.rs
> +++ b/drivers/gpu/nova-core/gsp/fw.rs
> @@ -636,6 +636,42 @@ unsafe impl FromBytes for RunCpuSequencer {}
> // SAFETY: Padding is explicit and will not contain uninitialized data.
> unsafe impl AsBytes for RunCpuSequencer {}
>
> +/// Class ID identifying the PMU engine in [`UcodeLibOsPrintHeader`].
> +const NV_GSP_MSG_EVENT_UCODE_LIBOS_CLASS_PMU: u32 = 0xf3d722;
> +
> +/// Header of a `UCODE_LIBOS_PRINT` GSP event payload.
> +///
> +/// The header is followed immediately by [`Self::buf_size`] bytes of raw LIBOS
> +/// print buffer data.
> +#[repr(transparent)]
> +pub(crate) struct UcodeLibOsPrintHeader(bindings::rpc_ucode_libos_print_v1e_08);
> +
> +static_assert!(size_of::<UcodeLibOsPrintHeader>() == 8);
> +
> +impl UcodeLibOsPrintHeader {
> + /// Returns the engine class ID encoded in bits `[31:8]` of `ucode_eng_desc`.
> + pub(crate) const fn engine_class(&self) -> u32 {
> + self.0.ucode_eng_desc >> 8
> + }
> +
> + /// Returns `true` if this print event originated from the PMU engine.
> + pub(crate) const fn is_pmu(&self) -> bool {
> + self.engine_class() == NV_GSP_MSG_EVENT_UCODE_LIBOS_CLASS_PMU
> + }
> +
> + /// Returns the length in bytes of the print buffer following this header.
> + pub(crate) const fn buf_size(&self) -> usize {
> + num::u32_as_usize(self.0.libos_print_buf_size)
> + }
> +}
> +
> +// SAFETY: This struct only contains integer fields and a zero-sized incomplete array marker,
> +// so all bit patterns are valid.
> +unsafe impl FromBytes for UcodeLibOsPrintHeader {}
> +
> +// SAFETY: All fields are packed without padding and do not contain uninitialized bytes.
> +unsafe impl AsBytes for UcodeLibOsPrintHeader {}
> +
> /// Struct containing the arguments required to pass a memory buffer to the GSP
> /// for use during initialisation.
> ///
> diff --git a/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs b/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
> index afe3e007f088..9a9631e9cb3d 100644
> --- a/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
> +++ b/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
> @@ -982,6 +982,13 @@ pub struct rpc_run_cpu_sequencer_v17_00 {
> pub regSaveArea: [u32_; 8usize],
> pub commandBuffer: __IncompleteArrayField<u32_>,
> }
> +#[repr(C)]
> +#[derive(Debug, Default, MaybeZeroable)]
> +pub struct rpc_ucode_libos_print_v1e_08 {
> + pub ucode_eng_desc: u32_,
> + pub libos_print_buf_size: u32_,
> + pub libos_print_buf: __IncompleteArrayField<u8_>,
> +}
> pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_WRITE: GSP_SEQ_BUF_OPCODE = 0;
> pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_MODIFY: GSP_SEQ_BUF_OPCODE = 1;
> pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_POLL: GSP_SEQ_BUF_OPCODE = 2;
> diff --git a/drivers/gpu/nova-core/gsp/logs.rs b/drivers/gpu/nova-core/gsp/logs.rs
> new file mode 100644
> index 000000000000..400508df2119
> --- /dev/null
> +++ b/drivers/gpu/nova-core/gsp/logs.rs
> @@ -0,0 +1,450 @@
> +// SPDX-License-Identifier: GPL-2.0-only
> +
> +//! GSP-RM LIBOS logging buffers and `debugfs` retention.
> +//!
> +//! GSP-RM emits encoded printf-like diagnostics into three DMA ring buffers
> +//! (`loginit`, `logintr`, `logrm`) and sends PMU LIBOS print dumps over the
> +//! message queue (`logpmu`). All four buffers are exposed through `debugfs`.
> +//!
> +//! When the `keep_gsp_logging` module parameter is enabled, any non-empty
> +//! buffers are snapshotted into regular kernel memory when the [`Gsp`]
> +//! instance is dropped (for example after a `probe()` failure or device
> +//! unbind) and kept mounted in `debugfs` until the module unloads or the same
> +//! device probes again.
> +
> +use kernel::{
> + debugfs::{
> + self,
> + BinaryWriter, //
> + },
> + device,
> + dma::Coherent,
> + fs::file,
> + io::{
> + io_project,
> + Io, //
> + },
> + new_mutex,
> + prelude::*,
> + str::CString,
> + sync::{
> + Arc,
> + Mutex, //
> + },
> + transmute::FromBytes,
> + uaccess::UserSliceWriter, //
> +};
> +
> +use crate::{
> + gsp::{
> + fw::UcodeLibOsPrintHeader,
> + PteArray,
> + GSP_PAGE_SIZE, //
> + },
> + sbuffer::SBufferIter, //
> +};
> +
> +/// Number of GSP pages to use in a RM log buffer.
> +const RM_LOG_BUFFER_NUM_PAGES: usize = 0x10;
> +
> +/// Size in bytes of each DMA-backed GSP-RM log buffer.
> +const LOG_BUFFER_SIZE: usize = RM_LOG_BUFFER_NUM_PAGES * GSP_PAGE_SIZE;
> +
> +/// Returns `true` if `put_ptr` indicates valid logged data in a buffer of `buffer_size` bytes.
> +///
> +/// Offset 0 of a LIBOS log buffer stores the `u64` put pointer (`pp`). Initially `pp == 0`.
> +/// Once GSP-RM writes entries, `pp` points to the next `u64` slot in the buffer, so valid
> +/// logging data satisfies `1 <= pp < buffer_size / size_of::<u64>()`.
> +pub(crate) const fn log_put_pointer_is_valid(put_ptr: u64, buffer_size: usize) -> bool {
> + let max_entries = (buffer_size / size_of::<u64>()) as u64;
> + put_ptr >= 1 && put_ptr < max_entries
> +}
> +
> +/// DMA-backed GSP-RM logging buffer.
> +///
> +/// The logging buffers are byte queues that contain encoded printf-like
> +/// messages from GSP-RM. They need to be decoded by a special application
> +/// that can parse the buffers.
> +///
> +/// The `loginit` buffer contains logs from early GSP-RM init and
> +/// exception dumps. The `logrm` buffer contains the subsequent logs. Both are
> +/// written to directly by GSP-RM and can be any multiple of [`GSP_PAGE_SIZE`].
> +///
> +/// The physical address map for the log buffer is stored in the buffer
> +/// itself, starting with offset 1. Offset 0 contains the "put" pointer (`pp`).
> +/// Initially, `pp` is equal to 0. If the buffer has valid logging data in it,
> +/// then `pp` points to the index into the buffer where the next logging entry
> +/// will be written. Therefore, the logging data is valid if:
> +/// `1 <= pp < sizeof(buffer) / sizeof(u64)`.
> +pub(super) struct LogBuffer<'a>(Coherent<'a, [u8; LOG_BUFFER_SIZE]>);
> +
> +impl<'a> LogBuffer<'a> {
> + /// Creates a new [`LogBuffer`] mapped on `dev`.
> + pub(super) fn new(dev: &'a device::Device<device::Bound>) -> Result<Self> {
> + let obj = Self(Coherent::zeroed(dev, GFP_KERNEL)?);
> +
> + let start_addr = obj.0.dma_address();
> +
> + let pte_view = io_project!(
> + obj.0,
> + [build: size_of::<u64>()..][build: ..RM_LOG_BUFFER_NUM_PAGES * size_of::<u64>()]
> + )
> + .try_cast::<PteArray<RM_LOG_BUFFER_NUM_PAGES>>()?;
> + PteArray::init(pte_view, start_addr)?;
> +
> + Ok(obj)
> + }
> +
> + /// Returns the underlying coherent DMA allocation for LIBOS init arguments.
> + pub(super) fn dma_coherent(&self) -> &Coherent<'a, [u8; LOG_BUFFER_SIZE]> {
> + &self.0
> + }
> +
> + /// Reads the put pointer stored at offset 0 of the buffer.
> + fn put_pointer(&self) -> u64 {
> + let mut bytes = [0u8; size_of::<u64>()];
> + io_project!(self.0, [build: ..size_of::<u64>()]).copy_to_slice(&mut bytes);
> + u64::from_le_bytes(bytes)
> + }
> +
> + /// Copies the buffer into regular kernel memory if it contains valid logged data.
> + fn snapshot(&self) -> Result<Option<KVVec<u8>>> {
> + if !log_put_pointer_is_valid(self.put_pointer(), LOG_BUFFER_SIZE) {
> + return Ok(None);
> + }
> +
> + let mut copy = KVVec::zeroed(LOG_BUFFER_SIZE, GFP_KERNEL)?;
> + io_project!(self.0, [build: ..]).copy_to_slice(copy.as_mut_slice());
> + Ok(Some(copy))
> + }
> +}
> +
> +/// Inner state of [`PmuLogBuffer`], protected by a [`Mutex`].
> +struct PmuLogBufferInner {
> + data: KVVec<u8>,
> + has_data: bool,
> +}
> +
> +/// Kernel-memory buffer storing the latest PMU `UCODE_LIBOS_PRINT` dump.
> +///
> +/// Unlike `loginit`, `logintr`, and `logrm`, the PMU print buffer is delivered
> +/// via an asynchronous `UCODE_LIBOS_PRINT` GSP RPC event rather than DMA and
> +/// is always at most [`GSP_PAGE_SIZE`] bytes.
> +#[pin_data]
> +pub(crate) struct PmuLogBuffer {
> + #[pin]
> + inner: Mutex<PmuLogBufferInner>,
> +}
> +
> +impl PmuLogBuffer {
> + /// Creates an in-place initializer for a zeroed [`PmuLogBuffer`].
> + pub(crate) fn new() -> impl PinInit<Self, Error> {
> + pin_init::pin_init_scope(|| {
> + let data = KVVec::zeroed(GSP_PAGE_SIZE, GFP_KERNEL)?;
> + Ok(try_pin_init!(Self {
> + inner <- new_mutex!(PmuLogBufferInner {
> + data,
> + has_data: false,
> + }),
> + }))
> + })
> + }
> +
> + /// Parses a `UCODE_LIBOS_PRINT` event payload and stores it if it comes from the PMU.
> + ///
> + /// # Errors
> + ///
> + /// - `EINVAL` if the header or payload is truncated.
> + /// - `ENOMSG` if the event belongs to an engine class other than PMU.
> + /// - `E2BIG` if the advertised buffer exceeds [`GSP_PAGE_SIZE`].
> + pub(crate) fn capture_event(&self, contents: (&[u8], &[u8])) -> Result<usize> {
> + let total_len = contents.0.len().saturating_add(contents.1.len());
> + let header_len = size_of::<UcodeLibOsPrintHeader>();
> + if total_len < header_len {
> + return Err(EINVAL);
> + }
> +
> + let mut sbuf = SBufferIter::new_reader([contents.0, contents.1]);
> + let mut hdr_bytes = [0u8; size_of::<UcodeLibOsPrintHeader>()];
> + sbuf.read_exact(&mut hdr_bytes)?;
> +
> + let hdr = UcodeLibOsPrintHeader::from_bytes_copy(&hdr_bytes).ok_or(EIO)?;
> + if !hdr.is_pmu() {
> + return Err(ENOMSG);
> + }
> +
> + let buf_size = hdr.buf_size();
> + if buf_size > GSP_PAGE_SIZE {
> + return Err(E2BIG);
> + }
> +
> + if buf_size > total_len - header_len {
> + return Err(EINVAL);
> + }
> +
> + let mut guard = self.inner.lock();
> + if buf_size > 0 {
> + sbuf.read_exact(&mut guard.data[..buf_size])?;
> + guard.data[buf_size..].fill(0);
> + guard.has_data = true;
> + } else {
> + guard.data.fill(0);
> + guard.has_data = false;
> + }
> +
> + Ok(buf_size)
> + }
> +
> + /// Copies the PMU log buffer if a non-empty dump has been captured.
> + fn snapshot(&self) -> Result<Option<KVVec<u8>>> {
> + let guard = self.inner.lock();
> + if !guard.has_data {
> + return Ok(None);
> + }
> +
> + let mut copy = KVVec::with_capacity(guard.data.len(), GFP_KERNEL)?;
> + copy.extend_from_slice(guard.data.as_slice(), GFP_KERNEL)?;
> + Ok(Some(copy))
> + }
> +}
> +
> +impl BinaryWriter for PmuLogBuffer {
> + fn write_to_slice(
> + &self,
> + writer: &mut UserSliceWriter,
> + offset: &mut file::Offset,
> + ) -> Result<usize> {
> + let guard = self.inner.lock();
> + guard.data.write_to_slice(writer, offset)
> + }
> +}
> +
> +/// Snapshot of non-empty GSP-RM log buffers retained in `debugfs` after device teardown.
> +pub(crate) struct RetainedLogs {
> + loginit: Option<KVVec<u8>>,
> + logintr: Option<KVVec<u8>>,
> + logrm: Option<KVVec<u8>>,
> + logpmu: Option<KVVec<u8>>,
> +}
> +
> +impl RetainedLogs {
> + /// Returns `true` if none of the buffers contain logged data.
> + fn is_empty(&self) -> bool {
> + self.loginit.is_none()
> + && self.logintr.is_none()
> + && self.logrm.is_none()
> + && self.logpmu.is_none()
> + }
> +
> + /// Populates `dir` with read-only binary files for each retained buffer.
> + fn populate_debugfs<'data>(&'data self, dir: &debugfs::ScopedDir<'data, '_>) {
> + if let Some(buf) = &self.loginit {
> + dir.read_binary_file(c"loginit", buf);
> + }
> + if let Some(buf) = &self.logintr {
> + dir.read_binary_file(c"logintr", buf);
> + }
> + if let Some(buf) = &self.logrm {
> + dir.read_binary_file(c"logrm", buf);
> + }
> + if let Some(buf) = &self.logpmu {
> + dir.read_binary_file(c"logpmu", buf);
> + }
> + }
> +}
> +
> +/// Retained `debugfs` directory entry owned at module scope for a single PCI device.
> +pub(crate) struct RetainedLogEntry {
> + dev_name: CString,
> + _scope: Pin<KBox<debugfs::Scope<RetainedLogs>>>,
> +}
> +
> +impl RetainedLogEntry {
> + /// Creates a retained `debugfs` scope under `parent` named `dev_name`.
> + pub(crate) fn new(parent: &debugfs::Dir, dev_name: &CStr, logs: RetainedLogs) -> Result<Self> {
> + let owned_name = CString::try_from(dev_name)?;
> + let scope = KBox::pin_init(
> + parent.scope(logs, &owned_name, |retained, dir| {
> + retained.populate_debugfs(dir);
> + }),
> + GFP_KERNEL,
> + )?;
> +
> + Ok(Self {
> + dev_name: owned_name,
> + _scope: scope,
> + })
> + }
> +
> + /// Returns the device name identifying this retained `debugfs` directory.
> + pub(crate) fn dev_name(&self) -> &CStr {
> + &self.dev_name
> + }
> +}
> +
> +/// Live GSP-RM log buffers exposed via `debugfs` while the device is bound.
> +///
> +/// Because [`debugfs::Scope`] drops its `debugfs` directory entry before dropping
> +/// its inner data, [`Drop::drop`] on `LogBuffers` runs only after the live
> +/// `debugfs` directory has been removed and no readers remain. When
> +/// `keep_gsp_logging` is set, `drop` safely snapshots the buffers into regular
> +/// kernel memory and re-exposes them under the module-level `debugfs` root.
> +pub(super) struct LogBuffers<'a> {
> + dev: &'a device::Device<device::Bound>,
> + /// Init log buffer.
> + pub(super) loginit: LogBuffer<'a>,
> + /// Interrupts log buffer.
> + pub(super) logintr: LogBuffer<'a>,
> + /// RM log buffer.
> + pub(super) logrm: LogBuffer<'a>,
> + /// PMU log buffer populated from `UCODE_LIBOS_PRINT` events.
> + pub(super) logpmu: Arc<PmuLogBuffer>,
> +}
> +
> +impl<'a> LogBuffers<'a> {
> + /// Creates a new [`LogBuffers`] collection for `dev`.
> + pub(super) fn new(
> + dev: &'a device::Device<device::Bound>,
> + loginit: LogBuffer<'a>,
> + logintr: LogBuffer<'a>,
> + logrm: LogBuffer<'a>,
> + logpmu: Arc<PmuLogBuffer>,
> + ) -> Self {
> + Self {
> + dev,
> + loginit,
> + logintr,
> + logrm,
> + logpmu,
> + }
> + }
> +
> + /// Snapshots all non-empty log buffers into regular kernel memory.
> + fn snapshot(&self) -> Result<RetainedLogs> {
> + Ok(RetainedLogs {
> + loginit: self.loginit.snapshot()?,
> + logintr: self.logintr.snapshot()?,
> + logrm: self.logrm.snapshot()?,
> + logpmu: self.logpmu.snapshot()?,
> + })
> + }
> +}
> +
> +impl Drop for LogBuffers<'_> {
> + fn drop(&mut self) {
> + if !cfg!(CONFIG_DEBUG_FS) || !crate::keep_gsp_logging() {
> + return;
> + }
> +
> + let retained = match self.snapshot() {
> + Ok(retained) => retained,
> + Err(e) => {
> + dev_warn!(
> + self.dev,
> + "Failed to snapshot GSP logging buffers: {:?}\n",
> + e
> + );
> + return;
> + }
> + };
> +
> + if retained.is_empty() {
> + dev_dbg!(
> + self.dev,
> + "GSP logging buffers are empty; nothing to retain\n"
> + );
> + return;
> + }
> +
> + match crate::store_retained_logs(self.dev.name(), retained) {
> + Ok(()) => dev_info!(self.dev, "Retained GSP logging buffers in debugfs\n"),
> + Err(e) => dev_warn!(
> + self.dev,
> + "Failed to retain GSP logging buffers in debugfs: {:?}\n",
> + e
> + ),
> + }
> + }
> +}
> +
> +#[kunit_tests(nova_core_gsp_logs)]
> +mod tests {
> + use super::*;
> +
> + const PMU_ENG_DESC: u32 = 0xf3d722 << 8;
> +
> + fn make_event(eng_desc: u32, advertised_size: u32, payload: &[u8]) -> Result<KVec<u8>> {
> + let mut msg = KVec::with_capacity(8 + payload.len(), GFP_KERNEL)?;
> + msg.extend_from_slice(&eng_desc.to_le_bytes(), GFP_KERNEL)?;
> + msg.extend_from_slice(&advertised_size.to_le_bytes(), GFP_KERNEL)?;
> + msg.extend_from_slice(payload, GFP_KERNEL)?;
> + Ok(msg)
> + }
> +
> + #[test]
> + fn put_pointer_bounds() {
> + let max_entries = (LOG_BUFFER_SIZE / size_of::<u64>()) as u64;
> + assert!(!log_put_pointer_is_valid(0, LOG_BUFFER_SIZE));
> + assert!(log_put_pointer_is_valid(1, LOG_BUFFER_SIZE));
> + assert!(log_put_pointer_is_valid(max_entries - 1, LOG_BUFFER_SIZE));
> + assert!(!log_put_pointer_is_valid(max_entries, LOG_BUFFER_SIZE));
> + assert!(!log_put_pointer_is_valid(u64::MAX, LOG_BUFFER_SIZE));
> + }
> +
> + #[test]
> + fn pmu_log_capture_and_overwrite() -> Result {
> + let pmu = Arc::pin_init(PmuLogBuffer::new(), GFP_KERNEL)?;
> + assert!(pmu.snapshot()?.is_none());
> +
> + // Split header and payload across two ring slices to simulate wraparound.
> + let payload = b"PMU LIBOS TEST LOG";
> + let raw = make_event(PMU_ENG_DESC, payload.len() as u32, payload)?;
> + let (part1, part2) = raw.as_slice().split_at(5);
> + assert_eq!(pmu.capture_event((part1, part2))?, payload.len());
> +
> + let snap = pmu.snapshot()?.ok_or(EIO)?;
> + assert_eq!(snap.len(), GSP_PAGE_SIZE);
> + assert_eq!(&snap[..payload.len()], payload);
> + assert!(snap[payload.len()..].iter().all(|&b| b == 0));
> +
> + // A shorter subsequent event must zero-pad the remainder.
> + let shorter = b"OK";
> + let raw2 = make_event(PMU_ENG_DESC, shorter.len() as u32, shorter)?;
> + assert_eq!(pmu.capture_event((raw2.as_slice(), &[]))?, shorter.len());
> +
> + let snap2 = pmu.snapshot()?.ok_or(EIO)?;
> + assert_eq!(&snap2[..shorter.len()], shorter);
> + assert!(snap2[shorter.len()..].iter().all(|&b| b == 0));
> +
> + Ok(())
> + }
> +
> + #[test]
> + fn pmu_log_rejects_invalid_events_without_clobbering() -> Result {
> + let pmu = Arc::pin_init(PmuLogBuffer::new(), GFP_KERNEL)?;
> + let valid = b"KEEP";
> + let raw = make_event(PMU_ENG_DESC, valid.len() as u32, valid)?;
> + pmu.capture_event((raw.as_slice(), &[]))?;
> +
> + // Truncated header.
> + assert_eq!(pmu.capture_event((&[0u8; 4], &[])), Err(EINVAL));
> +
> + // Unknown engine class.
> + let bad_class = make_event(0x123456 << 8, 4, b"ABCD")?;
> + assert_eq!(pmu.capture_event((bad_class.as_slice(), &[])), Err(ENOMSG));
> +
> + // Oversized buffer (> GSP_PAGE_SIZE).
> + let too_big = make_event(PMU_ENG_DESC, (GSP_PAGE_SIZE + 1) as u32, &[])?;
> + assert_eq!(pmu.capture_event((too_big.as_slice(), &[])), Err(E2BIG));
> +
> + // Truncated payload (advertised 16 bytes, only 4 present).
> + let truncated = make_event(PMU_ENG_DESC, 16, b"ABCD")?;
> + assert_eq!(pmu.capture_event((truncated.as_slice(), &[])), Err(EINVAL));
> +
> + // Existing valid contents must remain intact after rejected events.
> + let snap = pmu.snapshot()?.ok_or(EIO)?;
> + assert_eq!(&snap[..valid.len()], valid);
> +
> + Ok(())
> + }
> +}
> diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
> index a8f6dc22057b..f182ebb6b928 100644
> --- a/drivers/gpu/nova-core/nova_core.rs
> +++ b/drivers/gpu/nova-core/nova_core.rs
> @@ -35,11 +35,53 @@
> // TODO: Move this into per-module data once that exists.
> static mut DEBUGFS_ROOT: Option<debugfs::Dir> = None;
>
> -/// Guard that clears `DEBUGFS_ROOT` when dropped.
> +kernel::sync::global_lock! {
> + // SAFETY: Initialized once in `NovaCoreModule::init` before driver registration
> + // and cleared in `DebugfsRootGuard::drop` after driver unregistration.
> + unsafe(uninit) static RETAINED_LOGS: Mutex<KVec<gsp::logs::RetainedLogEntry>> = KVec::new();
> +}
> +
> +/// Returns whether GSP-RM `debugfs` log buffers should be retained after teardown.
> +pub(crate) fn keep_gsp_logging() -> bool {
> + module_parameters::keep_gsp_logging.value()
> +}
> +
> +/// Returns the module-wide `debugfs` root directory (`nova-core`).
> +pub(crate) fn debugfs_root() -> &'static debugfs::Dir {
> + #[allow(static_mut_refs)]
> + // SAFETY: `DEBUGFS_ROOT` is initialized before driver registration and cleared
> + // only after driver unregistration, so no device code can race with its mutation.
> + //
> + // PANIC: `DEBUGFS_ROOT` is always `Some` while the PCI driver is registered.
> + unsafe { DEBUGFS_ROOT.as_ref() }.expect("DEBUGFS_ROOT not initialized")
> +}
> +
> +/// Removes any retained `debugfs` log directory previously stored for `dev_name`.
> +pub(crate) fn clear_retained_logs_for(dev_name: &CStr) {
> + let mut retained = RETAINED_LOGS.lock();
> + retained.retain(|entry| entry.dev_name() != dev_name);
> +}
> +
> +/// Publishes a retained snapshot of GSP log buffers in `debugfs` until module unload.
> +pub(crate) fn store_retained_logs(dev_name: &CStr, logs: gsp::logs::RetainedLogs) -> Result {
> + let mut retained = RETAINED_LOGS.lock();
> + retained.retain(|entry| entry.dev_name() != dev_name);
> +
> + let entry = gsp::logs::RetainedLogEntry::new(debugfs_root(), dev_name, logs)?;
> + retained.push(entry, GFP_KERNEL)?;
> +
> + Ok(())
> +}
> +
> +/// Guard that clears retained logs and `DEBUGFS_ROOT` when dropped.
> struct DebugfsRootGuard;
>
> impl Drop for DebugfsRootGuard {
> fn drop(&mut self) {
> + // Drop retained `debugfs` scopes and free the `KVec` backing allocation
> + // before removing `DEBUGFS_ROOT`.
> + *RETAINED_LOGS.lock() = KVec::new();
> +
> // SAFETY: This guard is dropped after `_driver` (due to field order),
> // so the driver is unregistered and no probe() can be running.
> unsafe { DEBUGFS_ROOT = None };
> @@ -49,7 +91,7 @@ fn drop(&mut self) {
> #[pin_data]
> struct NovaCoreModule {
> // Fields are dropped in declaration order, so `_driver` is dropped first,
> - // then `_debugfs_guard` clears `DEBUGFS_ROOT`.
> + // then `_debugfs_guard` clears retained logs and `DEBUGFS_ROOT`.
> #[pin]
> _driver: Registration<pci::Adapter<driver::NovaCoreDriver>>,
> _debugfs_guard: DebugfsRootGuard,
> @@ -59,6 +101,10 @@ impl InPlaceModule for NovaCoreModule {
> fn init(module: &'static kernel::ThisModule) -> impl PinInit<Self, Error> {
> let dir = debugfs::Dir::new(c"nova-core");
>
> + // SAFETY: We are the only driver code running during init, so `RETAINED_LOGS`
> + // is initialized exactly once before any driver callback can access it.
> + unsafe { RETAINED_LOGS.init() };
> +
> // SAFETY: We are the only driver code running during init, so there
> // cannot be any concurrent access to `DEBUGFS_ROOT`.
> unsafe { DEBUGFS_ROOT = Some(dir) };
> @@ -77,6 +123,12 @@ fn init(module: &'static kernel::ThisModule) -> impl PinInit<Self, Error> {
> description: "Nova Core GPU driver",
> license: "GPL v2",
> firmware: [],
> + params: {
> + keep_gsp_logging: bool {
> + default: false,
> + description: "Retain GSP-RM debugfs log buffers after probe failure or unbind",
> + },
> + },
> }
>
> kernel::module_firmware!(firmware::ModInfoBuilder);
> diff --git a/drivers/gpu/nova-core/sbuffer.rs b/drivers/gpu/nova-core/sbuffer.rs
> index 3a41d224c77a..b8c01104c255 100644
> --- a/drivers/gpu/nova-core/sbuffer.rs
> +++ b/drivers/gpu/nova-core/sbuffer.rs
> @@ -146,7 +146,6 @@ fn get_slice(&mut self, len: usize) -> Option<&'a [u8]> {
>
> /// Ideally we would implement `Read`, but it is not available in `core`.
> /// So mimic `std::io::Read::read_exact`.
> - #[expect(unused)]
> pub(crate) fn read_exact(&mut self, mut dst: &mut [u8]) -> Result {
> while !dst.is_empty() {
> match self.get_slice(dst.len()) {
>
> base-commit: 693c2e04e3f1d4c59af236e1211b7b8cb165a790
^ permalink raw reply [flat|nested] 3+ messages in thread
end of thread, other threads:[~2026-12-02 3:37 UTC | newest]
Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-12-02 2:50 [RFC PATCH v2] gpu: nova-core: gsp: retain debugfs logs on teardown and capture logpmu Agustín Pereira
2026-12-02 2:50 ` [RFC PATCH v2] gpu: nova-core: gsp: add RM alloc/control/free RPCs and client/device API Agustín Pereira
2026-12-02 3:37 ` [RFC PATCH v2] gpu: nova-core: gsp: retain debugfs logs on teardown and capture logpmu John Hubbard
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®