gpu: nova-core: boot on the r000 GSP firmware
Subsystems (8)
v2 cover gpu: nova-core: boot on the r000 GSP firmware
Hi,
I'm sending this just a few days after v1, which is soon, but Timur Tabi and Zhi Wang reviewed the whole series in that time, and that led to quite a lot of fixes and lines changed. So I think it is helpful to provide a v2 now, so that future reviewers can avoid rediscovering all those issues.
Changes in v2, from Timur Tabi's and Zhi Wang's reviews, plus a couple of small new ones at the end to do better printing of the new GMC API RPC messages, below.
(Every number below is a v2 patch number. Patches 1 and 27 shifted the numbering from v1. Patches 30 and 31 are new at the end).
* Patch 1 is new. The Rust PCI abstraction has no accessor for the PCI domain, which patch 23 needs.
* Patches 2 and 28 drop the generated bindings that nova-core never references, resulting in a net removal of 429 lines.
* Patch 4 documents the MCTP destination endpoint ID and version fields in fsp.rst.
* Patch 5 uses checked_add for the per-block DMA offsets.
* Patch 6 allocates each radix3 page table level zeroed at its page-rounded size, rather than appending entries and padding afterwards.
* Patch 7 wraps the two debug-log counters instead of trapping.
* Patch 8 drops the inline BLOB representation from the TLV payload loader, loses two FILE name checks that could not fire, returns ENODATA rather than EINVAL for a zero SIZE, and loads the GSP firmware image through the same loader instead of open-coding it.
* Patch 9 gives the log buffer a single const page-count parameter.
* Patch 11 corrects its commit message.
* Patch 15 asserts the GMC API header layout against GMCAPI_HEADER from the bindings, rather than against a hardcoded size.
* Patch 17 checks the MCTP version, the NVDM vendor ID and the declared element length, which is what Open RM checks on arriving elements. Patch 27 is new, and extends the same checks to the RPC receive path.
* Patch 18 requires the GMC header's payload size to match the length the transport header declares.
* Patches 20, 21 and 22 use expect rather than allow for clippy::too_many_arguments, or drop the attribute where the lint cannot fire.
* Patch 21 restores the FBIF aperture only once the loaded image halts, as Open RM does.
* Patch 23 sends the PCI location as domain, bus and device, which is what GSP-RM decodes, rather than the bus, device and function that PCI_DEVID packs.
* Patch 28 also removes the SetRegistry command, which the GSP_INIT payload replaced.
* Patch 30 is new. GMC debug lines printed a bare command id, so print the name next to it: GSP_INIT (0x10001).
* Patch 31 is new. GSP-initiated events number their sequence from 0x8000000000000000, which printed as seq# 9223372036854775808, and the GSP_INIT reply was labeled an event. Print the sequence with that bit cleared, and label a reply as a response.
Nova-core boots the 570.144 GSP firmware today. This series moves the driver to the r000 firmware ABI, which is stable across releases, so firmware file names no longer carry a version number.
The firmware is not yet publicly available, so this series is for early review, and should not be merged until the firmware ships.
Patch 26 makes the switch in one commit. Before that, everything works on r570. After patch 26, only r000 is supported.
Beyond drm-rust-next, the series sits on these patchsets:
* The GIN interrupt controller series, which needs Danilo Krummrich's PCI and irq rework and Joel Fernandes' wait_for_completion_timeout().
* Eliot Courtney's NVKV encoder and decoder, which GSP_INIT is built on, and his Vec::push_init.
* Timur Tabi's "gpu: nova-core: write initial RPCs before booting GSP-RM", which patch 26 builds on.
* Timur Tabi's "rust: error: add remaining error codes", which supplies ENODATA and arrived in the 7.3 Rust pull as b93fb6e76ec1.
A branch with everything applied:
https://github.com/johnhubbard/linux/tree/nova-core-run-on-r615-or-later-v2
Tested on TU117 (Turing, T400), GA104 (Ampere, RTX A4000), AD102 (Ada) and GB202 (Blackwell, RTX PRO 6000), covering PCIe probe, chipset and GPU name readback, the interrupt delivery self-test, and the KUnit suites.
The vGPU team tested an earlier version of this series, minus the final cleanups.
John Hubbard (31):
rust: pci: add domain_nr() accessor
gpu: nova-core: firmware: add r000 bindings
gpu: nova-core: extract radix3 page table into its own module
gpu: nova-core: set MCTP transport header version to 1
gpu: nova-core: add Falcon helpers for r000 LOAD_EXEC events
gpu: nova-core: zero-pad radix3 page table levels to page boundary
gpu: nova-core: distinguish async GSP RPC traffic in debug logs
gpu: nova-core: add optional ucodes firmware loading
gpu: nova-core: add LIBOS3 log buffers and state monitor buffer
gpu: nova-core: add build ID headers to debugfs log buffer dumps
gpu: nova-core: rename the FbRanges elf field to fw_image
gpu: nova-core: regs: add msgq v2 BAR0 register declarations
gpu: nova-core: gsp: add msgq v2 internals
gpu: nova-core: generalize allocate_command() for variable headers
gpu: nova-core: add GMC API message types
gpu: nova-core: add GMC send path
gpu: nova-core: add GMC transport receive path
gpu: nova-core: gsp: add GMC dispatch on receive
gpu: nova-core: separate the generic falcon bootloader from FWSEC
gpu: nova-core: handle the r000 load-and-execute HS binary event
gpu: nova-core: handle the r000 load-and-execute bootloader event
gpu: nova-core: gsp: add the GMC boot event dispatcher
gpu: nova-core: gsp: add the GSP_INIT request builder
gpu: nova-core: gsp: send GSP_INIT and decode its reply
gpu: nova-core: gsp: pass the remaining log buffers to GSP-RM
gpu: nova-core: switch to the r000 GSP firmware
gpu: nova-core: gsp: validate RPC element framing on receive
gpu: nova-core: gsp: remove the RPCs that GSP_INIT replaced
gpu: nova-core: firmware: delete the r570 bindings
gpu: nova-core: print GMC command names in debug logs
gpu: nova-core: distinguish GMC event and response debug logs
Documentation/gpu/nova/core/fsp.rst | 2 +
drivers/gpu/nova-core/driver.rs | 2 +-
drivers/gpu/nova-core/falcon.rs | 166 +++-
drivers/gpu/nova-core/fb.rs | 18 +-
drivers/gpu/nova-core/fb/hal/gb100.rs | 25 +-
drivers/gpu/nova-core/fb/hal/gb202.rs | 5 +-
drivers/gpu/nova-core/firmware.rs | 44 +-
drivers/gpu/nova-core/firmware/bindata.rs | 38 +
.../nova-core/firmware/fwsec/bootloader.rs | 112 +--
.../gpu/nova-core/firmware/gen_bootloader.rs | 215 +++++
drivers/gpu/nova-core/firmware/gsp.rs | 135 +--
drivers/gpu/nova-core/firmware/radix3.rs | 149 +++
drivers/gpu/nova-core/firmware/tlv.rs | 37 +
drivers/gpu/nova-core/fsp.rs | 3 +-
drivers/gpu/nova-core/gpu.rs | 23 +-
drivers/gpu/nova-core/gsp.rs | 279 +++++-
drivers/gpu/nova-core/gsp/boot.rs | 550 ++++++++++-
drivers/gpu/nova-core/gsp/cmdq.rs | 829 +++++++++++-----
.../gpu/nova-core/gsp/cmdq/continuation.rs | 1 +
drivers/gpu/nova-core/gsp/commands.rs | 386 ++++----
drivers/gpu/nova-core/gsp/fw.rs | 899 ++++++++++--------
drivers/gpu/nova-core/gsp/fw/commands.rs | 275 +++---
.../gsp/fw/{r570_144.rs => r000_00.rs} | 2 +-
.../gsp/fw/{r570_144 => r000_00}/bindings.rs | 683 +++++--------
drivers/gpu/nova-core/gsp/hal.rs | 22 +-
drivers/gpu/nova-core/gsp/hal/tu102.rs | 18 +-
drivers/gpu/nova-core/gsp/regs.rs | 30 +
drivers/gpu/nova-core/gsp/sequencer.rs | 379 --------
drivers/gpu/nova-core/irq/gsp.rs | 2 +-
drivers/gpu/nova-core/mctp.rs | 32 +-
drivers/gpu/nova-core/regs.rs | 9 +-
rust/helpers/pci.c | 5 +
rust/kernel/pci.rs | 12 +
33 files changed, 3217 insertions(+), 2170 deletions(-)
create mode 100644 drivers/gpu/nova-core/firmware/bindata.rs
create mode 100644 drivers/gpu/nova-core/firmware/gen_bootloader.rs
create mode 100644 drivers/gpu/nova-core/firmware/radix3.rs
rename drivers/gpu/nova-core/gsp/fw/{r570_144.rs => r000_00.rs} (95%)
rename drivers/gpu/nova-core/gsp/fw/{r570_144 => r000_00}/bindings.rs (71%)
delete mode 100644 drivers/gpu/nova-core/gsp/sequencer.rsSignature · 1 line
2.55.0
PATCH v2 1/31 rust: pci: add domain_nr() accessor
The Rust PCI abstraction exposes a device's bus and device numbers through dev_id(), which returns the packed PCI_DEVID value, but it does not provide an accessor for the PCI domain number.
Add domain_nr(). Because pci_domain_nr() is a static inline rather than an exported function, the accessor needs a helper as well.
The nova-core GPU driver needs the domain to build the domain/bus/device word that GSP-RM firmware requires.
--- rust/helpers/pci.c | 5 +++++ rust/kernel/pci.rs | 12 ++++++++++++ 2 files changed, 17 insertions(+)
rust/helpers/pci.c +5 -0
@@ -7,6 +7,11 @@ __rust_helper u16 rust_helper_pci_dev_id(struct pci_dev *dev)return PCI_DEVID (dev->bus->number, dev->devfn); } +__rust_helper int rust_helper_pci_domain_nr(struct pci_dev *dev) +{ +return pci_domain_nr (dev->bus); +} + __rust_helper resource_size_trust_helper_pci_resource_start (struct pci_dev *pdev,int bar) {
rust/kernel/pci.rs +12 -0
@@ -405,6 +405,18 @@ pub fn dev_id(&self) -> u16 {unsafe { bindings::pci_dev_id (self.as_raw ()) } } +/// Returns the PCI domain number of the bus this device is on. +#[inline] +pub fn domain_nr (&self) ->u32 { +// SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a +// `struct pci_dev`. +let domain_nr =unsafe { bindings::pci_domain_nr (self.as_raw ()) }; + +// CAST: The C function returns `int`, but a PCI domain number is always +// non-negative, so this cast will not lose any information. + domain_nras u32 + } +/// Returns the PCI subsystem vendor ID. #[inline] pub fn subsystem_vendor_id (&self) ->u16 {
Signature · 1 line
2.55.0
Re: [PATCH v2 01/31] rust: pci: add domain_nr() accessor
rust/kernel/pci.rs pub fn dev_id(&self) -> u16 { · line 417
Quoted 4 lines · John Hubbard
rust/kernel/pci.rs +3
-0+// CAST: The C function returns `int`, but a PCI domain number is always +// non-negative, so this cast will not lose any information. + domain_nras u32
What about
debug_assert!(domain_nr >= 0);
?
Cheers,
Miguel
Re: [PATCH v2 01/31] rust: pci: add domain_nr() accessor
Quoted 11 lines · Miguel Ojeda
rust/kernel/pci.rs pub fn dev_id(&self) -> u16 { · line 417
Quoted 4 lines · John Hubbard
rust/kernel/pci.rs +3
-0+// CAST: The C function returns `int`, but a PCI domain number is always +// non-negative, so this cast will not lose any information. + domain_nras u32 What about
debug_assert!(domain_nr >= 0);?
Yes, good idea. That's appropriate because the PCI core on the C side provides a positive domain number, and the Rust side can assert that that continues to be true.
I'll add it right after the "let domain_nr..." statement, when I send the next version.
(Although I would like to figure out some way to get this in ahead of things, one way or another.)
thanks,
Signature · 1 line
John Hubbard
Alexandre Courbot
maintainerRe: [PATCH v2 01/31] rust: pci: add domain_nr() accessor
Quoted 17 lines · John Hubbard
Quoted 11 lines · Miguel Ojeda
rust/kernel/pci.rs pub fn dev_id(&self) -> u16 { · line 417
Quoted 4 lines · John Hubbard
rust/kernel/pci.rs +3
-0+// CAST: The C function returns `int`, but a PCI domain number is always +// non-negative, so this cast will not lose any information. + domain_nras u32 What about
debug_assert!(domain_nr >= 0);?
Yes, good idea. That's appropriate because the PCI core on the C side provides a positive domain number, and the Rust side can assert that that continues to be true.
Quoted 5 lines
I'll add it right after the "let
domain_nr..." statement, when I send the next version.(Although I would like to figure out some way to get this in ahead of things, one way or another.)
Since this is a very similar case I thought that maybe we can fix the C API to return an unsigned like we did in [1], but things appear to be a bit more intricate here and a negative number is (temporarily) stored at least once (PCI_DOMAIN_NR_NOT_SET).
So indeed debug_assert sounds like the right call (and maybe we should have one in [2] as well)
[1] https://patch.msgid.link/[email protected]
[2] https://patch.msgid.link/[email protected]
PATCH v2 2/31 gpu: nova-core: firmware: add r000 bindings
In reply to John Hubbard"r000" means "latest firmware", without getting bogged down into naming actual versions, because those will vary. The story is: nova uses r570 at this point, but will transition soon to some later version, and that version will have a stable ABI, which in turn means that the firmware file names will stop including version numbers in the file name itself. Version information will still be recorded inside each firmware image, though.
Add generated firmware bindings from the r000 Open RM headers. The module is registered but not yet wired as the active binding set.
--- drivers/gpu/nova-core/gsp/fw.rs | 1 + drivers/gpu/nova-core/gsp/fw/r000_00.rs | 31 + .../gpu/nova-core/gsp/fw/r000_00/bindings.rs | 1210 +++++++++++++++++ 3 files changed, 1242 insertions(+) create mode 100644 drivers/gpu/nova-core/gsp/fw/r000_00.rs create mode 100644 drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs
drivers/gpu/nova-core/gsp/fw.rs +1 -0
@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. pub (crate )mod commands; +mod r000_00;mod r570_144;// Alias to avoid repeating the version number with every use.
drivers/gpu/nova-core/gsp/fw/r000_00.rs new file +31 -0
@@ -0,0 +1,31 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Firmware bindings. +//! +//! Imports the generated bindings by `bindgen`. +//! +//! This module may not be directly used. Please abstract or re-export the needed symbols in the +//! parent module instead. + +#![allow( +dead_code, +clippy::all, +clippy::undocumented_unsafe_blocks, +clippy::ptr_as_ptr, +clippy::ref_as_ptr, +missing_docs, +non_camel_case_types, +non_upper_case_globals, +non_snake_case, +improper_ctypes, +unreachable_pub, +unsafe_op_in_unsafe_fn +)] +use kernel::ffi; +use pin_init::MaybeZeroable ; + +include! ("r000_00/bindings.rs" ); + +// SAFETY: This type has a size of zero, so its inclusion into another type should not affect their +// ability to implement `Zeroable`. +unsafe impl <T > kernel::prelude::Zeroable for __IncompleteArrayField <T > {}
drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs new file +1210 -0
1,210 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 3/31 gpu: nova-core: extract radix3 page table into its own module
In reply to John HubbardMove the 3-level radix page table construction out of GspFirmware into a standalone Radix3 type in firmware/radix3.rs. The ucodes (bindata) firmware that GSP-RM loads at runtime also needs a radix3 page table, so the logic needs to be reusable.
Refactor GspFirmware to use the new Radix3 type and expose firmware size through a size() method instead of a public field.
--- drivers/gpu/nova-core/fb.rs | 2 +- drivers/gpu/nova-core/firmware.rs | 1 + drivers/gpu/nova-core/firmware/gsp.rs | 116 ++++---------------- drivers/gpu/nova-core/firmware/radix3.rs | 133 +++++++++++++++++++++++ drivers/gpu/nova-core/gsp/fw.rs | 4 +- 5 files changed, 159 insertions(+), 97 deletions(-) create mode 100644 drivers/gpu/nova-core/firmware/radix3.rs
drivers/gpu/nova-core/fb.rs +1 -1
@@ -236,7 +236,7 @@ pub(crate) fn new(let elf = {const ELF_DOWN_ALIGN :Alignment =Alignment ::new ::<SZ_64K >(); -let elf_size = u64::from_safe_cast (gsp_fw.size); +let elf_size = u64::from_safe_cast (gsp_fw.size ());let elf_addr = (boot.start - elf_size).align_down (ELF_DOWN_ALIGN );FbRange (elf_addr..elf_addr + elf_size)
drivers/gpu/nova-core/firmware.rs +1 -0
@@ -26,6 +26,7 @@pub (crate )mod fsp;pub (crate )mod fwsec;pub (crate )mod gsp; +pub (crate )mod radix3;pub (crate )mod riscv;pub (crate )mod tlv;
drivers/gpu/nova-core/firmware/gsp.rs +22 -94
165 lines not on this page · raw message
drivers/gpu/nova-core/firmware/radix3.rs new file +133 -0
133 lines not on this page · raw message
drivers/gpu/nova-core/gsp/fw.rs +2 -2
@@ -188,7 +188,7 @@ pub(crate) fn from_ranges<'a>( magic: bindings::GSP_FW_WPR_META_MAGIC as u64, revision: u64::from(bindings::GSP_FW_WPR_META_REVISION), sysmemAddrOfRadix3Elf: gsp_firmware.radix3_dma_address(), - sizeOfRadix3Elf: u64::from_safe_cast(gsp_firmware.size), + sizeOfRadix3Elf: u64::from_safe_cast(gsp_firmware.size()), sysmemAddrOfBootloader: gsp_firmware.bootloader.ucode.dma_address(), sizeOfBootloader: u64::from_safe_cast(gsp_firmware.bootloader.ucode.size()), bootloaderCodeOffset: u64::from(gsp_firmware.bootloader.code_offset),
@@ -243,7 +243,7 @@ pub(crate) fn from_sizes<'a>( magic: bindings::GSP_FW_WPR_META_MAGIC as u64, revision: u64::from(bindings::GSP_FW_WPR_META_REVISION), sysmemAddrOfRadix3Elf: gsp_firmware.radix3_dma_address(), - sizeOfRadix3Elf: u64::from_safe_cast(gsp_firmware.size), + sizeOfRadix3Elf: u64::from_safe_cast(gsp_firmware.size()), sysmemAddrOfBootloader: gsp_firmware.bootloader.ucode.dma_address(), sizeOfBootloader: u64::from_safe_cast(gsp_firmware.bootloader.ucode.size()), bootloaderCodeOffset: u64::from(gsp_firmware.bootloader.code_offset),
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 03/31] gpu: nova-core: extract radix3 page table into its own module
On Sat Aug 22, 2026 at 10:54 AM JST, John Hubbard wrote:
<...>
Quoted 32 lines
drivers/gpu/nova-core/firmware/gsp.rs +1
-18@@ -26,38 +21,21 @@ }, }, gpu::Chipset, - gsp::GSP_PAGE_SIZE, num::FromSafeCast, };/// GSP firmware with 3-level radix page tables for the GSP bootloader. /// -/// The bootloader expects firmware to be mapped starting at address 0 in GSP's virtual address -/// space: -/// -/// ```text -/// Level 0: 1 page, 1 entry -> points to first level 1 page -/// Level 1: Multiple pages/entries -> each entry points to a level 2 page -/// Level 2: Multiple pages/entries -> each entry points to a firmware page -/// ``` -/// -/// Each page is 4KB, each entry is 8 bytes (64-bit DMA address). /// Also known as "Radix3" firmware. #[pin_data] pub (crate )struct GspFirmware { -/// The GSP firmware inside a [`VVec`], device-mapped via a SG table. -#[pin] - fw:SGTable <Owned <VVec <u8 >>>, -/// Level 2 page table whose entries contain DMA addresses of firmware pages. -#[pin] - level2:SGTable <Owned <VVec <u8 >>>, -/// Level 1 page table whose entries contain DMA addresses of level 2 pages. +/// The GSP firmware image mapped via a 3-level radix page table. #[pin]
drivers/gpu/nova-core/firmware/gsp.rs line 38
Quoted 10 lines
drivers/gpu/nova-core/firmware/gsp.rs +5
-5- level1: SGTable<Owned<VVec<u8>>>, - /// Level 0 page table (single 4KB page) with one entry: DMA address of first level 1 page. - level0: Coherent<[u64]>, -/// Size in bytes of the firmware contained in [`Self::fw`]. - pub(crate) size: usize, + radix3: Radix3, +/// Firmware file path requested from userspace. + pub(crate) fw_path: CString, +/// Firmware version from the TLV metadata. + pub(crate) fw_version: CString,
I was contemplating merging this patch early as it is a reasonable change on its own, but unfortunately these two introduced (and unused for now) members prevent me from doing so. They are also not related to moving the Radix3 code around. Can you introduce them when they are actually used?
This would allow me to merge this one and patch 6 (which btw is strangely not placed right after this one, with unrelated changes in between) early and lighten the series a bit.
I think patch 11 can also go in early, but I refrained from picking it up now to spare you a conflict upon rebasing this series. Ideally this one would also have been at the beginning of the series.
Re: [PATCH v2 03/31] gpu: nova-core: extract radix3 page table into its own module
Quoted 7 lines · Alexandre Courbot
On Sat Aug 22, 2026 at 10:54 AM JST, John Hubbard wrote:
<...>
I was contemplating merging this patch early as it is a reasonable change on its own, but unfortunately these two introduced (and unused for now) members prevent me from doing so. They are also not related to moving the Radix3 code around. Can you introduce them when they are actually used?
Sure.
Quoted 8 lines
This would allow me to merge this one and patch 6 (which btw is strangely not placed right after this one, with unrelated changes in between) early and lighten the series a bit.
I think patch 11 can also go in early, but I refrained from picking it up now to spare you a conflict upon rebasing this series. Ideally this one would also have been at the beginning of the series.
Don't worry about conflicts, because lately I can resolve those pretty much automatically, with today's tools.
Should I sent a separate 2-patch series, with this patch merged in with patch 6, and patch 11, then? I also would like this series to be shorter, of course.
thanks,
Signature · 1 line
John Hubbard
Alexandre Courbot
maintainerRe: [PATCH v2 03/31] gpu: nova-core: extract radix3 page table into its own module
Quoted 16 lines · John Hubbard
Quoted 7 lines · Alexandre Courbot
On Sat Aug 22, 2026 at 10:54 AM JST, John Hubbard wrote:
<...>
I was contemplating merging this patch early as it is a reasonable change on its own, but unfortunately these two introduced (and unused for now) members prevent me from doing so. They are also not related to moving the Radix3 code around. Can you introduce them when they are actually used?Sure.
Quoted 5 lines
This would allow me to merge this one and patch 6 (which btw is strangely not placed right after this one, with unrelated changes in between) early and lighten the series a bit.
Quoted 6 lines
Quoted 3 lines
I think patch 11 can also go in early, but I refrained from picking it up now to spare you a conflict upon rebasing this series. Ideally this one would also have been at the beginning of the series.
Don't worry about conflicts, because lately I can resolve those pretty much automatically, with today's tools.
I do worry because today's tools tend to introduce churn when they meet a speedbump. :')
Quoted 4 lines
Should I sent a separate 2-patch series, with this patch merged in with patch 6, and patch 11, then? I also would like this series to be shorter, of course.
A separate series would be the shortest course, I think we could merge it quickly in this case.
Let's keep the move to a new module and zero-padding as separate patches though, it makes the history cleaner.
PATCH v2 4/31 gpu: nova-core: set MCTP transport header version to 1
In reply to John HubbardFSP requires MCTP transport header version 1. Nova-core leaves version bits 3:0 at zero, so every CoT and PRC request carries an invalid transport header.
Define the version and destination endpoint ID fields. Set the version to 1 for single-packet requests, and leave the unused destination endpoint ID at zero.
--- Documentation/gpu/nova/core/fsp.rst | 2 ++ drivers/gpu/nova-core/mctp.rs | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-)
Documentation/gpu/nova/core/fsp.rst +2 -0
@@ -106,6 +106,8 @@ All FSP messages share a common header format consisting of two 32-bit words: - Bit 30: EOM (End of Message) - Bits 29:28: Packet sequence number - Bits 23:16: Source Endpoint ID +- Bits 15:8: Destination Endpoint ID +- Bits 3:0: MCTP header version (1) **NVDM header** (NVIDIA Vendor Defined Message):
drivers/gpu/nova-core/mctp.rs +12 -2
@@ -42,13 +42,23 @@ pub(crate) struct MctpHeader(u32) { 29:28 seq;/// Source endpoint ID. 23:16 seid; +/// Destination endpoint ID. + 15:8 deid; +/// MCTP header version. + 3:0 version; } }impl MctpHeader { -/// Builds a single-packet MCTP header (`SOM=1`, `EOM=1`, `SEQ=0`, `SEID=0`). +/// MCTP specification version 1.0. +const VERSION :u32 =1 ; + +/// Builds a single-packet MCTP header (`SOM=1`, `EOM=1`, `SEQ=0`, `SEID=0`, `VERSION=1`). pub (crate )fn single_packet () ->Self { -Self ::zeroed ().with_som (true ).with_eom (true ) +Self ::zeroed () + .with_const_version ::<{Self ::VERSION }>() + .with_som (true ) + .with_eom (true ) }/// Returns whether this is a complete single-packet message (`SOM=1` and `EOM=1`).
Signature · 1 line
2.55.0
PATCH v2 5/31 gpu: nova-core: add Falcon helpers for r000 LOAD_EXEC events
In reply to John HubbardThe r000 LOAD_EXEC events provide addresses for images that the driver must copy into GSP Falcon IMEM and DMEM. The existing Falcon DMA path creates its source buffer from a FalconFirmware object, so it cannot use those addresses. The protocol also reports GSP RISC-V suspension through MAILBOX0 bit 31 rather than CPUCTL.halted.
Add Falcon operations for DMA from event-provided addresses and for the RISC-V suspend indication.
--- drivers/gpu/nova-core/falcon.rs | 139 +++++++++++++++++++++++++++++++- drivers/gpu/nova-core/regs.rs | 2 +- 2 files changed, 139 insertions(+), 2 deletions(-)
drivers/gpu/nova-core/falcon.rs +138 -1
@@ -133,12 +133,25 @@ pub(crate) enum FalconMem {/// Secure Instruction Memory. ImemSecure,/// Non-Secure Instruction Memory. -#[expect(unused)] +#[expect(dead_code)] ImemNonSecure,/// Data Memory. Dmem, } +/// Source offset of a raw falcon DMA transfer, added to the DMA base address. +#[expect(dead_code)] +#[derive( Copy , Clone )] +pub (crate )enum FalconDmaSrcOffset { +/// Byte offset from the DMA base address. +Offset (u32 ), +/// DMEM virtual address. The DMA engine also tags each loaded block with this value, so the +/// falcon reaches the data through its DMEM VA. The caller must bias the DMA base address so +/// that base plus this value addresses the first byte of the image. Only valid with +/// [`FalconMem::Dmem`]. +DmemVa (u32 ), +} +bounded_enum! {/// Defines the Framebuffer Interface (FBIF) aperture type. /// This determines the memory type for external memory access during a DMA transfer, which is
@@ -592,6 +605,112 @@ fn dma_wr(Ok (()) } +/// Perform a raw DMA transfer from a physical address to falcon IMEM or DMEM. +/// +/// Used by the GSP boot event handlers where the firmware provides the source +/// address directly (in GPU physical address space, routed through the FBIF +/// aperture). The caller must configure the FBIF TRANSCFG register +/// corresponding to `ctx_dma` before calling this method. +/// +/// A [`FalconDmaSrcOffset::DmemVa`] source offset also sets `DMATRFCMD.SET_DMTAG`, and +/// requires `target_mem` to be [`FalconMem::Dmem`]. +/// +/// # Errors +/// +/// - `EINVAL` if `ctx_dma` is not a valid context DMA slot, if `src_addr` is not aligned to +/// 256 bytes, or if a [`FalconDmaSrcOffset::DmemVa`] source offset is paired with an IMEM +/// target. +/// - `ERANGE` if `src_addr` does not fit the `DMATRFBASE` register pair. +/// - `EOVERFLOW` if a per-block source or destination offset exceeds `u32`. +#[expect(dead_code)] +pub (crate )fn raw_dma_transfer ( + &self, + ctx_dma:u8 , + src_addr:u64 , + target_mem:FalconMem , + src:FalconDmaSrcOffset , + dst_offset:u32 , + len:u32 , + ) ->Result { +const DMA_LEN :u32 = num::usize_into_u32 ::<{MEM_BLOCK_ALIGNMENT }>(); +const NUM_CTXDMA_SLOTS :u8 =8 ; + +if ctx_dma >=NUM_CTXDMA_SLOTS { +dev_err! (self.dev,"raw DMA: ctx_dma {} out of range\n" , ctx_dma); +return Err (EINVAL ); + } + +if src_addr % u64::from (DMA_LEN ) >0 { +dev_err! ( + self.dev, +"raw DMA: source address {:#x} not 256B-aligned\n" , + src_addr + ); +return Err (EINVAL ); + } + +if src_addr >>40 > u64::from (regs::NV_PFALCON_FALCON_DMATRFBASE1 ::BASE_MASK ) { +dev_err! ( + self.dev, +"raw DMA: source address {:#x} does not fit DMATRFBASE\n" , + src_addr + ); +return Err (ERANGE ); + } + +let (src_offset, set_dmtag) =match src { +FalconDmaSrcOffset ::Offset (offset) => (offset,false ), +// `SET_DMTAG` applies to DMEM only. +FalconDmaSrcOffset ::DmemVa (_)if target_mem !=FalconMem ::Dmem =>return Err (EINVAL ), +FalconDmaSrcOffset ::DmemVa (va) => (va,true ), + }; + +let num_transfers = len.div_ceil (DMA_LEN ); + + self.bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_DMATRFBASE ::zeroed ().with_base ( +// CAST: `as u32` is used on purpose since we do want to strip the upper bits, +// which will be written to `NV_PFALCON_FALCON_DMATRFBASE1`. + (src_addr >>8 )as u32 , + ), + ); + self.bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_DMATRFBASE1 ::zeroed ().try_with_base (src_addr >>40 )?, + ); + +let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD ::zeroed () + .with_size (DmaTrfCmdSize ::Size256B ) + .try_with_ctxdma (u32::from (ctx_dma))? + .with_falcon_mem (target_mem) + .with_set_dmtag (set_dmtag); + +for posin (0 ..num_transfers).map (|i| i *DMA_LEN ) { + self.bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_DMATRFMOFFS ::zeroed () + .try_with_offs (dst_offset.checked_add (pos).ok_or (EOVERFLOW )?)?, + ); + self.bar.write ( +WithBase ::of ::<E >(), + regs::NV_PFALCON_FALCON_DMATRFFBOFFS ::zeroed () + .with_offs (src_offset.checked_add (pos).ok_or (EOVERFLOW )?), + ); + + self.bar.write (WithBase ::of ::<E >(), cmd); + +read_poll_timeout ( + ||Ok (self.bar.read (regs::NV_PFALCON_FALCON_DMATRFCMD ::of ::<E >())), + |r| r.idle (), +Delta ::ZERO , +Delta ::from_secs (2 ), + )?; + } + +Ok (()) + } +/// Perform a DMA load into `IMEM` and `DMEM` of `fw`, and prepare the falcon to run it. fn dma_load <F :FalconFirmware <Target =E > +FalconDmaLoadable >(&self, fw: &F ) ->Result {// DMA object with firmware content as the source of the DMA engine.
@@ -647,6 +766,24 @@ pub(crate) fn wait_till_halted(&self) -> Result<()> {Ok (()) } +/// Wait until the GSP processor has suspended. +/// +/// The RISC-V GSP signals suspension by setting bit 31 (`0x8000_0000`) in `MAILBOX0`, rather +/// than through `CPUCTL.halted`. +#[expect(dead_code)] +pub (crate )fn wait_for_processor_suspend (&self) ->Result <()> { +const INTERRUPT_PROCESSOR_SUSPENDED :u32 =0x8000_0000 ; + +read_poll_timeout ( + ||Ok (self.read_mailbox0 ()), + |val| (*val &INTERRUPT_PROCESSOR_SUSPENDED ) !=0 , +Delta ::ZERO , +Delta ::from_secs (2 ), + )?; + +Ok (()) + } +/// Start the falcon CPU. pub (crate )fn start (&self) ->Result <()> { match self
drivers/gpu/nova-core/regs.rs +1 -1
@@ -264,7 +264,7 @@ pub(crate) fn usable_fb_size(self) -> u64 { } pub(crate) NV_PFALCON_FALCON_DMATRFCMD(u32) @ PFalconBase + 0x00000118 { - 16:16 set_dmtag; + 16:16 set_dmtag => bool; 14:12 ctxdma; 10:8 size ?=> DmaTrfCmdSize; 5:5 is_write => bool;
Signature · 1 line
2.55.0
PATCH v2 6/31 gpu: nova-core: zero-pad radix3 page table levels to page boundary
In reply to John HubbardGSP-RM allocates the whole radix3 page table region in one block and zeroes it before writing entries. The booter reads each level a full page at a time when it walks the table, so every byte of a level page is firmware-visible whether or not it holds a valid entry.
The driver allocates each level separately and writes only the valid entries, so the last page of each level is only partly written. The booter reads the whole page regardless, and a non-zero word in the unwritten remainder is indistinguishable from an entry.
Allocate each level zeroed, sized to a whole number of GSP pages, and write the entries into it.
--- drivers/gpu/nova-core/firmware/radix3.rs | 50 ++++++++++++++++-------- 1 file changed, 33 insertions(+), 17 deletions(-)
drivers/gpu/nova-core/firmware/radix3.rs +33 -17
@@ -67,22 +67,14 @@ pub(crate) fn new<'a>( Ok(try_pin_init!(Self { data <- SGTable::new(dev, data, DataDirection::ToDevice, GFP_KERNEL), level2 <- { - VVec::<u8>::with_capacity( - data.iter().count() * core::mem::size_of::<u64>(), - GFP_KERNEL, - ) - .map_err(|_| ENOMEM) - .and_then(|level2| map_into_lvl(&data, level2)) - .map(|level2| SGTable::new(dev, level2, DataDirection::ToDevice, GFP_KERNEL))? + let level2 = build_lvl(&data)?; + + SGTable::new(dev, level2, DataDirection::ToDevice, GFP_KERNEL) }, level1 <- { - VVec::<u8>::with_capacity( - level2.iter().count() * core::mem::size_of::<u64>(), - GFP_KERNEL, - ) - .map_err(|_| ENOMEM) - .and_then(|level1| map_into_lvl(&level2, level1)) - .map(|level1| SGTable::new(dev, level1, DataDirection::ToDevice, GFP_KERNEL))? + let level1 = build_lvl(&level2)?; + + SGTable::new(dev, level1, DataDirection::ToDevice, GFP_KERNEL) }, level0: { let level1_entry = level1.iter().next().ok_or(EINVAL)?;
@@ -113,19 +105,43 @@ pub(crate) fn size(&self) -> usize { } } -/// Build a page table from a scatter-gather list. +/// Returns the size, in bytes, of the page table level that maps `sg_table`: one `u64` entry per +/// 4KB page it spans, rounded up to a whole number of `GSP_PAGE_SIZE` pages. +fn lvl_size (sg_table: &SGTable <Owned <VVec <u8 >>>) ->usize { +let entries:usize = sg_table + .iter () + .map (|sg_entry| usize::from_safe_cast (sg_entry.dma_len ()).div_ceil (GSP_PAGE_SIZE )) + .sum (); + + (entries *size_of ::<u64 >()).next_multiple_of (GSP_PAGE_SIZE ) +} + +/// Builds a page table level from a scatter-gather list. /// /// Takes each DMA-mapped region from `sg_table` and writes page table entries /// for all 4KB pages within that region. For example, a 16KB SG entry becomes /// 4 consecutive page table entries. -fn map_into_lvl (sg_table: &SGTable <Owned <VVec <u8 >>>,mut dst:VVec <u8 >) ->Result <VVec <u8 >> { +/// +/// The returned buffer spans a whole number of `GSP_PAGE_SIZE` pages, and every byte past the +/// last entry is zero. The booter DMAs each level a whole page at a time. +/// +/// Returns `ENOMEM` if the level cannot be allocated, and `EINVAL` if `sg_table` spans more +/// pages than [`lvl_size`] accounted for. +fn build_lvl (sg_table: &SGTable <Owned <VVec <u8 >>>) ->Result <VVec <u8 >> { +let mut dst =VVec ::<u8 >::zeroed (lvl_size (sg_table),GFP_KERNEL ).map_err (|_|ENOMEM )?; +let mut entries = dst.chunks_exact_mut (size_of ::<u64 >()); +for sg_entryin sg_table.iter () {let num_pages = usize::from_safe_cast (sg_entry.dma_len ()).div_ceil (GSP_PAGE_SIZE );for iin 0 ..num_pages {let entry = sg_entry.dma_address () + (u64::from_safe_cast (i) * u64::from_safe_cast (GSP_PAGE_SIZE )); - dst.extend_from_slice (&entry.to_le_bytes (),GFP_KERNEL )?; + + entries + .next () + .ok_or (EINVAL )? + .copy_from_slice (&entry.to_le_bytes ()); } }
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 06/31] gpu: nova-core: zero-pad radix3 page table levels to page boundary
Quoted 28 lines · John Hubbard
GSP-RM allocates the whole radix3 page table region in one block and zeroes it before writing entries. The booter reads each level a full page at a time when it walks the table, so every byte of a level page is firmware-visible whether or not it holds a valid entry.
The driver allocates each level separately and writes only the valid entries, so the last page of each level is only partly written. The booter reads the whole page regardless, and a non-zero word in the unwritten remainder is indistinguishable from an entry.
Allocate each level zeroed, sized to a whole number of GSP pages, and write the entries into it.
Assisted-by Cursor:claude-opus-5Reviewed-by Timur Tabi <[email protected]>Signed-off-by John Hubbard <[email protected]>--- drivers/gpu/nova-core/firmware/radix3.rs | 50 ++++++++++++++++-------- 1 file changed, 33 insertions(+), 17 deletions(-)drivers/gpu/nova-core/firmware/radix3.rs +0
-0@@ -67,22 +67,14 @@ pub(crate) fn new<'a>( Ok(try_pin_init!(Self { data <- SGTable::new(dev, data, DataDirection::ToDevice, GFP_KERNEL), level2 <- {
drivers/gpu/nova-core/firmware/radix3.rs pub(crate) fn new<'a>( · line 72
Quoted 10 lines
drivers/gpu/nova-core/firmware/radix3.rs +3
-7-VVec ::<u8 >::with_capacity ( - data.iter ().count () * core::mem::size_of ::<u64 >(), -GFP_KERNEL , - ) - .map_err (|_|ENOMEM ) - .and_then (|level2|map_into_lvl (&data, level2)) - .map (|level2|SGTable ::new (dev, level2,DataDirection ::ToDevice ,GFP_KERNEL ))? +let level2 =build_lvl (&data)?; + +SGTable ::new (dev, level2,DataDirection ::ToDevice ,GFP_KERNEL )
Or alternatively:
level2 <- {
build_lvl(&data)
.map(|l2| SGTable::new(dev, l2, DataDirection::ToDevice, GFP_KERNEL))
},I don't feel strongly about this, I just think it describes the flow a bit better when there are no fleeting local variables. Feel free to keep your version if you prefer it.
(also applicable to level1 below)
PATCH v2 7/31 gpu: nova-core: distinguish async GSP RPC traffic in debug logs
In reply to John HubbardThe receive path logged every message at the transport layer and did not distinguish events from command replies. Async sends shared the RPC sequence with waited-for commands, and GSP-initiated events arrived with that field unset.
Print a distinct debug line for async send, sync send, event, and command reply. Number async sends and events with driver-local counters, which wrap rather than trap, since they only number log lines.
IS_ASYNC selects only the send log line. Every command still carries the next RPC sequence on the wire.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 111 ++++++++++++++---- .../gpu/nova-core/gsp/cmdq/continuation.rs | 1 + drivers/gpu/nova-core/gsp/commands.rs | 2 + drivers/gpu/nova-core/gsp/fw.rs | 19 +++ 4 files changed, 107 insertions(+), 26 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +85 -26
@@ -87,6 +87,12 @@ pub(crate) trait CommandToGsp {/// Function identifying this command to the GSP. const FUNCTION :MsgFunction ; +/// Classifies the send-side debug log as an async send. +/// +/// Default is `false`. Set this only on commands that are sent without waiting for a reply. A +/// [`NoReply`] continuation of a waited-for command stays `false`. +const IS_ASYNC :bool =false ; +/// Type generated by [`CommandToGsp::init`], to be written into the command queue buffer. type Command :FromBytes +AsBytes ;
@@ -528,6 +534,8 @@ pub(crate) fn new(dev: &device::Device<device::Bound>) -> impl PinInit<Self, Err gsp_mem, elem_seq: 0, rpc_seq: 0, + tx_async_seq: 0, + rx_event_seq: 0, poisoned: Cell::new(false), }), }))
@@ -672,6 +680,12 @@ struct CmdqInner {/// [`CmdqInner::receive_msg`] match that reply to the awaiting command. Advances once per /// logical command. rpc_seq: u32, +/// Debug-log sequence for async sends. Those commands do not wait for a reply, so this +/// counter is the number printed in the send log. + tx_async_seq: u32, +/// Debug-log sequence for GSP-initiated events. The GSP leaves the RPC sequence unset on +/// those messages, so the driver numbers them itself. + rx_event_seq: u32,/// Set once a message with corrupt framing or a bad checksum is seen. Such a message has an /// untrusted length, so the queue cannot be advanced past it, and every later receive fails /// until the queue is torn down and reset.
@@ -738,13 +752,24 @@ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M, rpc_seq: u32) -> dst.contents.1, ]))); -dev_dbg! ( - &self.dev, -"GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n" , - rpc_seq, -M ::FUNCTION , - dst.header.length (), - ); +if M ::IS_ASYNC { +dev_dbg! ( + &self.dev, +"GSP RPC: async send: seq# {}, function={:?}, length=0x{:x}\n" , + self.tx_async_seq, +M ::FUNCTION , + dst.header.length (), + ); + self.tx_async_seq = self.tx_async_seq.wrapping_add (1 ); + }else { +dev_dbg! ( + &self.dev, +"GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n" , + rpc_seq, +M ::FUNCTION , + dst.header.length (), + ); + }// All set - update the write pointer and inform the GSP of the new command. let elem_count = dst.header.element_count ();
@@ -826,14 +851,6 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {return Err (EIO ); }; -dev_dbg! ( - &self.dev, -"GSP RPC: receive: seq# {}, function={:?}, length=0x{:x}\n" , - header.sequence (), - header.function (), - header.length (), - ); -let payload_length = header.payload_length ();// Check that the driver read area is large enough for the message.
@@ -877,6 +894,41 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { }) } +/// Writes the classified receive debug line for a decoded GSP message. +/// +/// Events print [`Self::rx_event_seq`]. Command replies print `seq`. An unrecognized function +/// code prints nothing here. +fn log_received (&self, function:Result <MsgFunction ,u32 >, seq:u32 , length:usize ) { +match function { +Ok (f)if f.is_event () => { +dev_dbg! ( + &self.dev, +"GSP RPC: async received: seq# {}, function={:?}, length=0x{:x}\n" , + self.rx_event_seq, + f, + length, + ); + } +Ok (f) => { +dev_dbg! ( + &self.dev, +"GSP RPC: response received: seq# {}, function={:?}, length=0x{:x}\n" , + seq, + f, + length, + ); + } +Err (_) => {} + } + } + +/// Advances [`Self::rx_event_seq`] after a GSP-initiated event has been consumed. +fn advance_rx_event_seq (&mut self, function:Result <MsgFunction ,u32 >) { +if matches! (function,Ok (f)if f.is_event ()) { + self.rx_event_seq = self.rx_event_seq.wrapping_add (1 ); + } + } +/// Receive a message from the GSP. /// /// The expected message type is given by the `M` generic parameter. With `expected_seq` set,
@@ -910,9 +962,12 @@ fn receive_msg<M: MessageFromGsp>(let message = self.wait_for_msg (timeout)?;let function = message.header.function ();let seq = message.header.sequence (); +let length = message.header.length ();let func_matches =matches! (function,Ok (f)if f ==M ::FUNCTION );let matched = func_matches && expected_seq.is_none_or (|expected| seq == expected); + self.log_received (function, seq, length); +// Every path must advance the read pointer past this message, including a failed decode. let result =if matched {match M ::Message ::from_bytes_prefix (message.contents.0 ) {
@@ -938,9 +993,10 @@ fn receive_msg<M: MessageFromGsp>( };// Advance the read pointer past this message. - self.gsp_mem.advance_cpu_read_ptr (u32::try_from ( - message.header.length ().div_ceil (GSP_PAGE_SIZE ), - )?); + self.gsp_mem + .advance_cpu_read_ptr (u32::try_from (length.div_ceil (GSP_PAGE_SIZE ))?); + + self.advance_rx_event_seq (function);if !matched {if func_matches {
@@ -962,8 +1018,8 @@ fn receive_msg<M: MessageFromGsp>(/// Routes a GSP message that is not the reply a caller is waiting for. /// /// GSP-reported errors are logged at error level and unrecognized function codes at warning -/// level. Every other known function code is consumed without a log line, because the RPC -/// receive trace in [`Self::wait_for_msg`] already records its arrival. +/// level. Every other known function code is consumed without a log line, because +/// [`Self::log_received`] already records its arrival. fn dispatch_event (&self, function:Result <MsgFunction ,u32 >, seq:u32 ) {match function {Ok (MsgFunction ::OsErrorLog ) => {
@@ -1004,16 +1060,19 @@ fn drain(&mut self) -> Result {while !self.gsp_mem.driver_read_area ().0 .is_empty () {// A message is available, so this returns without waiting. let msg = self.wait_for_msg (Delta ::ZERO )?; - -let pages = - u32::try_from (msg.header.length ().div_ceil (GSP_PAGE_SIZE )).map_err (|_| { -dev_err! (&self.dev,"GSP drain: message length overflow\n" ); -EIO - })?;let function = msg.header.function ();let seq = msg.header.sequence (); +let length = msg.header.length (); + + self.log_received (function, seq, length); + +let pages = u32::try_from (length.div_ceil (GSP_PAGE_SIZE )).map_err (|_| { +dev_err! (&self.dev,"GSP drain: message length overflow\n" ); +EIO + })?; self.gsp_mem.advance_cpu_read_ptr (pages); + self.advance_rx_event_seq (function); self.dispatch_event (function, seq); }
drivers/gpu/nova-core/gsp/cmdq/continuation.rs +1 -0
@@ -147,6 +147,7 @@ fn new(command: C, payload: KVVec<u8>) -> Self {impl <C :CommandToGsp >CommandToGsp for SplitCommand <C > {const FUNCTION :MsgFunction =C ::FUNCTION ; +const IS_ASYNC :bool =C ::IS_ASYNC ;type Command =C ::Command ;type Reply =C ::Reply ;type InitError =C ::InitError ;
drivers/gpu/nova-core/gsp/commands.rs +2 -0
@@ -52,6 +52,7 @@ pub(crate) fn new(pdev: &'a pci::Device<device::Bound>, chipset: Chipset) -> Selimpl <'a>CommandToGsp for SetSystemInfo <'a> {const FUNCTION :MsgFunction =MsgFunction ::GspSetSystemInfo ; +const IS_ASYNC :bool =true ;type Command = fw::commands::GspSetSystemInfo ;type Reply =NoReply ;type InitError =Error ;
@@ -122,6 +123,7 @@ pub(crate) fn new(vgpu_state: VgpuState) -> Result<Self> {impl CommandToGsp for SetRegistry {const FUNCTION :MsgFunction =MsgFunction ::SetRegistry ; +const IS_ASYNC :bool =true ;type Command = fw::commands::PackedRegistryTable ;type Reply =NoReply ;type InitError =Infallible ;
drivers/gpu/nova-core/gsp/fw.rs +19 -0
@@ -359,6 +359,25 @@ fn try_from(value: u32) -> Result<MsgFunction> { } } +impl MsgFunction { +/// Returns true if this is a GSP-initiated async event (`NV_VGPU_MSG_EVENT_*`), as opposed to +/// a command response (`NV_VGPU_MSG_FUNCTION_*`). +pub (crate )fn is_event (&self) ->bool { +matches! ( + self, +Self ::GspInitDone + |Self ::GspRunCpuSequencer + |Self ::PostEvent + |Self ::RcTriggered + |Self ::MmuFaultQueued + |Self ::OsErrorLog + |Self ::GspPostNoCat + |Self ::GspLockdownNotice + |Self ::UcodeLibOsPrint // + ) + } +} +impl From <MsgFunction >for u32 {fn from (value:MsgFunction ) ->Self {// CAST: `MsgFunction` is `repr(u32)` and can thus be cast losslessly.
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerRe: [PATCH v2 07/31] gpu: nova-core: distinguish async GSP RPC traffic in debug logs
Quoted 50 lines · John Hubbard
The receive path logged every message at the transport layer and did not distinguish events from command replies. Async sends shared the RPC sequence with waited-for commands, and GSP-initiated events arrived with that field unset.
Print a distinct debug line for async send, sync send, event, and command reply. Number async sends and events with driver-local counters, which wrap rather than trap, since they only number log lines.
IS_ASYNCselects only the send log line. Every command still carries the next RPC sequence on the wire.Assisted-by Cursor:claude-opus-5Reviewed-by Timur Tabi <[email protected]>Reviewed-by Zhi Wang <[email protected]>Signed-off-by John Hubbard <[email protected]>--- drivers/gpu/nova-core/gsp/cmdq.rs | 111 ++++++++++++++---- .../gpu/nova-core/gsp/cmdq/continuation.rs | 1 + drivers/gpu/nova-core/gsp/commands.rs | 2 + drivers/gpu/nova-core/gsp/fw.rs | 19 +++ 4 files changed, 107 insertions(+), 26 deletions(-)drivers/gpu/nova-core/gsp/cmdq.rs +8
-0@@ -87,6 +87,12 @@ pub(crate) trait CommandToGsp {/// Function identifying this command to the GSP. const FUNCTION :MsgFunction ; +/// Classifies the send-side debug log as an async send. +/// +/// Default is `false`. Set this only on commands that are sent without waiting for a reply. A +/// [`NoReply`] continuation of a waited-for command stays `false`. +const IS_ASYNC :bool =false ; +/// Type generated by [`CommandToGsp::init`], to be written into the command queue buffer. type Command :FromBytes +AsBytes ;@@ -528,6 +534,8 @@ pub(crate) fn new(dev: &device::Device<device::Bound>) -> impl PinInit<Self, Err gsp_mem, elem_seq: 0, rpc_seq: 0, + tx_async_seq: 0, + rx_event_seq: 0, poisoned: Cell::new(false), }), }))
drivers/gpu/nova-core/gsp/cmdq.rs struct CmdqInner { · line 688
Quoted 9 lines
drivers/gpu/nova-core/gsp/cmdq.rs +6
-0@@ -672,6 +680,12 @@ struct CmdqInner {/// [`CmdqInner::receive_msg`] match that reply to the awaiting command. Advances once per /// logical command. rpc_seq: u32, +/// Debug-log sequence for async sends. Those commands do not wait for a reply, so this +/// counter is the number printed in the send log. + tx_async_seq: u32, +/// Debug-log sequence for GSP-initiated events. The GSP leaves the RPC sequence unset on +/// those messages, so the driver numbers them itself. + rx_event_seq: u32,
What do these counters give us concretely? I don't understand how they are useful for debugging since we already have sequence numbers for the commands.
Quoted 22 lines
drivers/gpu/nova-core/gsp/cmdq.rs +8
-7/// Set once a message with corrupt framing or a bad checksum is seen. Such a message has an /// untrusted length, so the queue cannot be advanced past it, and every later receive fails /// until the queue is torn down and reset. @@ -738,13 +752,24 @@ fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M, rpc_seq: u32) -> dst.contents.1, ]))); -dev_dbg! ( - &self.dev, -"GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n" , - rpc_seq, -M ::FUNCTION , - dst.header.length (), - ); +if M ::IS_ASYNC { +dev_dbg! ( + &self.dev, +"GSP RPC: async send: seq# {}, function={:?}, length=0x{:x}\n" , + self.tx_async_seq, +M ::FUNCTION , + dst.header.length (), + );
drivers/gpu/nova-core/gsp/cmdq.rs fn send_single_command<M>(&mut self, bar: Bar0<'_>, command: M, rpc_seq: u32) -> · line 772
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +10
-0+ self.tx_async_seq = self.tx_async_seq.wrapping_add (1 ); + }else { +dev_dbg! ( + &self.dev, +"GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n" , + rpc_seq, +M ::FUNCTION , + dst.header.length (), + ); + }
These two dev_dbg! statements are almost identical, can we differentiate the relevant part with a custom string and fmt!?
<...>
Quoted 13 lines
drivers/gpu/nova-core/gsp/commands.rs +1
-0@@ -52,6 +52,7 @@ pub(crate) fn new(pdev: &'a pci::Device<device::Bound>, chipset: Chipset) -> Selimpl <'a>CommandToGsp for SetSystemInfo <'a> {const FUNCTION :MsgFunction =MsgFunction ::GspSetSystemInfo ; +const IS_ASYNC :bool =true ;type Command = fw::commands::GspSetSystemInfo ;type Reply =NoReply ;type InitError =Error ;
drivers/gpu/nova-core/gsp/commands.rs pub(crate) fn new(vgpu_state: VgpuState) -> Result<Self> { · line 129
Quoted 7 lines
drivers/gpu/nova-core/gsp/commands.rs +1
-0@@ -122,6 +123,7 @@ pub(crate) fn new(vgpu_state: VgpuState) -> Result<Self> {impl CommandToGsp for SetRegistry {const FUNCTION :MsgFunction =MsgFunction ::SetRegistry ; +const IS_ASYNC :bool =true ;type Command = fw::commands::PackedRegistryTable ;type Reply =NoReply ;type InitError =Infallible ;
Async commands are effectively removed by the end of this series, so I'd question the need to add this distinction here. This looks to me like this patch should come *after* the switch to r000 to make sure that all of its premises still hold.
So unless there is a strong need for it I'd wager it is best to drop this patch for now as it looks more like a drive-by feature than a preliminary need for r000 support.
Quoted 16 lines
drivers/gpu/nova-core/gsp/fw.rs +8
-0@@ -359,6 +359,25 @@ fn try_from(value: u32) -> Result<MsgFunction> { } } +impl MsgFunction { +/// Returns true if this is a GSP-initiated async event (`NV_VGPU_MSG_EVENT_*`), as opposed to +/// a command response (`NV_VGPU_MSG_FUNCTION_*`). +pub (crate )fn is_event (&self) ->bool { +matches! ( + self, +Self ::GspInitDone + |Self ::GspRunCpuSequencer
drivers/gpu/nova-core/gsp/fw.rs fn try_from(value: u32) -> Result<MsgFunction> { · line 379
Quoted 10 lines
drivers/gpu/nova-core/gsp/fw.rs +10
-0+ |Self ::PostEvent + |Self ::RcTriggered + |Self ::MmuFaultQueued + |Self ::OsErrorLog + |Self ::GspPostNoCat + |Self ::GspLockdownNotice + |Self ::UcodeLibOsPrint // + ) + } +}
There is a NV_VGPU_MSG_EVENT_FIRST_EVENT value in the bindings that can be used to classify events without resorting to an exhaustive and error-prone list.
PATCH v2 8/31 gpu: nova-core: add optional ucodes firmware loading
In reply to John HubbardThe new GSP firmware takes an optional ucodes image, a bindata blob of microcode that GSP-RM loads at runtime. Open RM fetches it for every chip family except GB10Y and fails firmware load without it, so the driver will require it too once it boots the new firmware. The helper added here reports a missing metadata file rather than failing, and leaves that policy to its caller.
Load the ucodes metadata with the existing TLV request helper, and give the TLV parser a method for the payload convention it uses: a FILE basename together with its SIZE. A FILE tag may only name a basename in the metadata file's own directory, so one holding a path separator or naming a special directory is rejected. The GSP firmware image is named the same way, so both go through the same method. Nothing calls this until the driver switches to the new firmware.
--- drivers/gpu/nova-core/firmware.rs | 8 ++++- drivers/gpu/nova-core/firmware/bindata.rs | 39 +++++++++++++++++++++++ drivers/gpu/nova-core/firmware/gsp.rs | 14 ++------ drivers/gpu/nova-core/firmware/tlv.rs | 37 +++++++++++++++++++++ 4 files changed, 86 insertions(+), 12 deletions(-) create mode 100644 drivers/gpu/nova-core/firmware/bindata.rs
drivers/gpu/nova-core/firmware.rs +7 -1
@@ -22,6 +22,7 @@ num::IntoSafeCast, // }; +pub (crate )mod bindata;pub (crate )mod booter;pub (crate )mod fsp;pub (crate )mod fwsec;
@@ -348,7 +349,12 @@ const fn make_entry_chipset(self, chipset: gpu::Chipset) -> Self {let mut this = self .make_entry_file (name,"gsp_bootloader.tlv" ) .make_entry_file (name,"gsp.tlv" ) - .make_entry_file (name,"gsp.bin" ); + .make_entry_file (name,"gsp.bin" ) + .make_entry_file (name,"ucodes.tlv" ) +// `ucodes.tlv` may name another safe basename in its FILE tag, but module firmware +// metadata cannot describe a runtime-selected filename. Advertise the conventional +// filename used by the distributed metadata. + .make_entry_file (name,"ucodes.bin" );// Add the firmware files specific to the GSP boot method of `chipset`. let boot_files =boot_firmware_files (chipset);
drivers/gpu/nova-core/firmware/bindata.rs new file +39 -0
@@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +//! GSP bindata firmware loading. + +use kernel::{ + device, + prelude::*,// +}; + +use crate ::{ + firmware::tlv::{ + request_tlv, +Tlv ,// + }, + gpu::Chipset , +}; + +/// Requests the optional `ucodes` bindata metadata and loads its payload. +/// +/// A missing metadata file is reported as [`None`] so that the eventual caller can decide whether +/// ucodes are optional for its boot path. Once the metadata has been found, all parse and payload +/// loading errors, including a missing referenced file, are returned as errors. +#[expect(dead_code)] +pub (crate )fn request_ucodes_firmware ( + dev: &device::Device , + chipset:Chipset , +) ->Result <Option <VVec <u8 >>> { +let firmware =match request_tlv (dev, chipset,"ucodes" ) { +Ok (firmware) => firmware, +Err (e)if e ==ENOENT =>return Ok (None ), +Err (e) =>return Err (e), + }; + +let tlv =Tlv ::new (firmware.data ())?; +let (_, ucodes) = tlv.load_file (dev, chipset)?; + +Ok (Some (ucodes)) +}
drivers/gpu/nova-core/firmware/gsp.rs +3 -11
@@ -6,7 +6,6 @@ Coherent, DmaAddress, // }, - firmware, prelude::*, str::CString, };
@@ -20,8 +19,7 @@ Tlv, }, }, - gpu::Chipset, - num::FromSafeCast, + gpu::Chipset, // };/// GSP firmware with 3-level radix page tables for the GSP bootloader.
@@ -59,19 +57,13 @@ pub(crate) fn new<'a>( fw_version.to_str ().unwrap_or ("unknown" ) ); -let size = usize::from_safe_cast (tlv.get_u32 (b"SIZE" )?); -let mut fw_vvec =VVec ::zeroed (size,GFP_KERNEL ).map_err (|_|ENOMEM )?; - -let chip_name = chipset.name (); -let file = tlv.get_string (b"FILE" )?; -let filename =CString ::try_from_fmt (fmt! ("nvidia/{chip_name}/gsp/{file}" ))?; - firmware::request_into_buf (&filename, dev, fw_vvec.as_mut_slice ())?; +let (fw_path, fw_vvec) = tlv.load_file (dev, chipset)?;let signatures =Coherent ::from_slice (dev, tlv.get_bytes (b"SIGN" )?,GFP_KERNEL )?; Ok(try_pin_init!(Self { radix3 <- Radix3::new(dev, fw_vvec), - fw_path: filename, + fw_path, fw_version, signatures, bootloader: {
drivers/gpu/nova-core/firmware/tlv.rs +37 -0
@@ -198,6 +198,43 @@ fn iter(&self) -> TlvIter<'_, 'a> { self.iter ().find (|b| b.tag == *tag).ok_or (EINVAL ) } +/// Loads the file that this TLV references. +/// +/// A TLV that names its payload rather than carrying it inline holds a `FILE` basename and +/// the payload's `SIZE`. The basename is resolved against the metadata file's own directory, +/// so an empty name, `.`, `..`, or a name holding a `/` is rejected. +/// +/// On success, returns the firmware path that was requested and a [`VVec`] holding `SIZE` +/// bytes of file contents. +/// +/// Returns `EINVAL` if either tag is absent or the basename is rejected, and `ENODATA` if +/// `SIZE` is zero. +pub (crate )fn load_file ( + &self, + dev: &device::Device , + chipset: gpu::Chipset , + ) ->Result <(CString ,VVec <u8 >)> { +let file = self.get_string (b"FILE" )?; + +// FILE is a basename relative to the TLV's directory, not an arbitrary firmware path. +if file.is_empty () ||matches! (file,"." |".." ) || file.contains ('/' ) { +return Err (EINVAL ); + } + +let chip_name = chipset.name (); +let path =CString ::try_from_fmt (fmt! ("nvidia/{chip_name}/gsp/{file}" ))?; + +let size = usize::from_safe_cast (self.get_u32 (b"SIZE" )?); +if size ==0 { +return Err (ENODATA ); + } + +let mut data =VVec ::zeroed (size,GFP_KERNEL ).map_err (|_|ENOMEM )?; + firmware::request_into_buf (&path, dev, data.as_mut_slice ())?; + +Ok ((path, data)) + } +/// Return a slice of bytes. /// /// Returns `EINVAL` if the value is empty.
Signature · 1 line
2.55.0
Re: [PATCH v2 08/31] gpu: nova-core: add optional ucodes firmware loading
drivers/gpu/nova-core/firmware/tlv.rs fn iter(&self) -> TlvIter<'_, 'a> { · line 222
Quoted 4 lines · John Hubbard
drivers/gpu/nova-core/firmware/tlv.rs +4
-0+// FILE is a basename relative to the TLV's directory, not an arbitrary firmware path. +if file.is_empty () ||matches! (file,"." |".." ) || file.contains ('/' ) { +return Err (EINVAL ); + }
This isn't a sane way to check if a path includes a directory component or not. You really want to use path-handling apis, rather than open-coding this in a way that rejects a few special cases.
Re: [PATCH v2 08/31] gpu: nova-core: add optional ucodes firmware loading
Quoted 9 lines · M Henning
drivers/gpu/nova-core/firmware/tlv.rs fn iter(&self) -> TlvIter<'_, 'a> { · line 222
Quoted 4 lines · John Hubbard
drivers/gpu/nova-core/firmware/tlv.rs +4
-0+// FILE is a basename relative to the TLV's directory, not an arbitrary firmware path. +if file.is_empty () ||matches! (file,"." |".." ) || file.contains ('/' ) { +return Err (EINVAL ); + }This isn't a sane way to check if a path includes a directory component or not. You really want to use path-handling apis, rather than open-coding this in a way that rejects a few special cases.
I'll drop these checks entirely for v3. Timur wondered whether they were needed during the v1 review, for the same reason, and I think you're both right that the check that matters already happens lower down.
Although, load_file()'s doccomments do claim that an embedded '/' is rejected, so I'll need to either delete that, or add in a check for it.
Here's the calling stack:
Tlv::load_file()
firmware::request_into_buf()
request_firmware_into_buf()
_request_firmware()and _request_firmware() already does this:
if (!name || name[0] == '\0') {
ret = -EINVAL;
goto out;
}
/*
* Reject firmware file names with ".." path components.
* There are drivers that construct firmware file names from
* device-supplied strings, and we don't want some device to be
* able to tell us "I would like to be sent my firmware from
* ../../../etc/shadow, please".
*
* This intentionally only looks at the firmware name, not at
* the firmware base directory or at symlink contents.
*/
if (name_contains_dotdot(name)) {
dev_warn(device,
"Firmware load for '%s' refused, path contains '..' component\n",
name);
ret = -EINVAL;
goto out;
}On the path-handling API: there isn't one to reach for in Rust for Linux:
rust/kernel is #![no_std], so no Path or PathBuf, and the C side has kbasename() and the VFS lookup helpers, but nothing that validates an unresolved name string beyond the name_contains_dotdot() above.
thanks,
Signature · 1 line
John Hubbard
PATCH v2 9/31 gpu: nova-core: add LIBOS3 log buffers and state monitor buffer
In reply to John HubbardGSP-RM on the new firmware logs from six LIBOS3 tasks on GA102 and later, where r570 logs from three, and it maps a small buffer during init to report RM state for diagnostics. Turing and GA100 run LIBOS2, where only the init and RM task logs exist. Two of the six task logs are a single page, where the rest are 64KB.
Allocate the three missing log buffers and the state monitor buffer, give the log buffer type a const page count so the single-page buffers can exist, and expose the new log buffers through the debugfs directory that already carries the others.
Nothing passes these to GSP-RM yet. The libos init arguments gain them when the driver switches to the new firmware.
--- drivers/gpu/nova-core/gsp.rs | 66 ++++++++++++++++++++++++++---------- 1 file changed, 49 insertions(+), 17 deletions(-)
drivers/gpu/nova-core/gsp.rs +49 -17
@@ -82,7 +82,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 )]
@@ -118,9 +117,20 @@ fn init(view: CoherentView<'_, Self>, start: DmaAddress) -> Result<()> {/// 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 (Coherent <[u8 ;LOG_BUFFER_SIZE ]>); +struct LogBuffer <const NUM_PAGES :usize >(Coherent <[[u8 ;GSP_PAGE_SIZE ];NUM_PAGES ]>); -impl LogBuffer { +/// Log buffer for a task that GSP-RM logs to at its default size. +/// +/// Matches the registry defaults for the init, interrupt, RM, and MNOC tasks +/// (`NV_REG_STR_RM_GSP_LOG_BUFFER_SIZE_TASK_*_DEFAULT`). +type TaskLogBuffer =LogBuffer <RM_LOG_BUFFER_NUM_PAGES >; + +/// Log buffer for a task that GSP-RM gives a single page. +/// +/// Matches the size GSP-RM hardcodes for the root and RM state monitor tasks. +type SmallLogBuffer =LogBuffer <1 >; + +impl <const NUM_PAGES :usize >LogBuffer <NUM_PAGES > {/// Creates a new `LogBuffer` mapped on `dev`. fn new (dev: &device::Device <device::Bound >) ->Result <Self > {let obj =Self (Coherent ::zeroed (dev,GFP_KERNEL )?);
@@ -129,22 +139,35 @@ fn new(dev: &device::Device<device::Bound>) -> Result<Self> {let pte_view =io_project! ( obj.0 , - [build:size_of ::<u64 >()..][build: ..RM_LOG_BUFFER_NUM_PAGES *size_of ::<u64 >()] + [build:0 ][build:size_of ::<u64 >()..][build: ..NUM_PAGES *size_of ::<u64 >()] ) - .try_cast ::<PteArray <RM_LOG_BUFFER_NUM_PAGES >>()?; + .try_cast ::<PteArray <NUM_PAGES >>()?;PteArray ::init (pte_view, start_addr)?;Ok (obj) } } +/// Log buffers used by GSP-RM for debug logging. +/// +/// r000+ firmware expects log buffers for all LIBOS3 tasks. Each buffer is +/// registered as a libos memory region entry, identified by its id8 name. +/// +/// The Open RM equivalents are `_kgspInitLibosLoggingStructures`, which allocates the buffers, +/// and `kgspSetupLibosInitArgs_IMPL`, which builds the `pLibosInitArgs[]` array. struct LogBuffers { -/// Init log buffer. - loginit:LogBuffer , -/// Interrupts log buffer. - logintr:LogBuffer , -/// RM log buffer. - logrm:LogBuffer , +/// Init task log buffer (LOGINIT). + loginit:TaskLogBuffer , +/// Interrupt task log buffer (LOGINTR). + logintr:TaskLogBuffer , +/// RM task log buffer (LOGRM). + logrm:TaskLogBuffer , +/// MNOC task log buffer (LOGMNOC). + logmnoc:TaskLogBuffer , +/// Root task log buffer (LOGROOT). + logroot:SmallLogBuffer , +/// RM state monitor task log buffer (LOGRMON). + logrmon:SmallLogBuffer , }/// GSP runtime data.
@@ -159,6 +182,8 @@ pub(crate) struct Gsp { pub(crate) cmdq: Arc<Cmdq>,/// RM arguments. rmargs: Coherent<GspArgumentsPadded>, +/// RM state monitor buffer (required by r000+ GSP-RM for diagnostics). + rm_state_monitor: Coherent<[u8; GSP_PAGE_SIZE]>, }impl Gsp {
@@ -167,16 +192,17 @@ pub(crate) fn new(pdev: &pci::Device<device::Bound>) -> impl PinInit<Self, Error pin_init::pin_init_scope(move || { let dev = pdev.as_ref(); - let loginit = LogBuffer::new(dev)?; - let logintr = LogBuffer::new(dev)?; - let logrm = LogBuffer::new(dev)?; + let loginit = TaskLogBuffer::new(dev)?; + let logintr = TaskLogBuffer::new(dev)?; + let logrm = TaskLogBuffer::new(dev)?; + let logmnoc = TaskLogBuffer::new(dev)?; + let logroot = SmallLogBuffer::new(dev)?; + let logrmon = SmallLogBuffer::new(dev)?; - // 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: Arc::pin_init(Cmdq::new(dev), GFP_KERNEL)?, rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(cmdq.as_ref()))?, + rm_state_monitor: Coherent::zeroed(dev, GFP_KERNEL)?, libos: { let mut libos = CoherentBox::zeroed_slice( dev,
@@ -196,6 +222,9 @@ pub(crate) fn new(pdev: &pci::Device<device::Bound>) -> impl PinInit<Self, Error loginit, logintr, logrm, + logmnoc, + logroot, + logrmon, };#[allow(static_mut_refs)]
@@ -212,6 +241,9 @@ pub(crate) fn new(pdev: &pci::Device<device::Bound>) -> impl PinInit<Self, Error 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"logmnoc" , &logs.logmnoc.0 ); + dir.read_binary_file (c"logroot" , &logs.logroot.0 ); + dir.read_binary_file (c"logrmon" , &logs.logrmon.0 ); }) }, }))
Signature · 1 line
2.55.0
PATCH v2 10/31 gpu: nova-core: add build ID headers to debugfs log buffer dumps
In reply to John HubbardA raw log buffer dump cannot be decoded without knowing which firmware build produced it, and which GPU and metadata format it belongs to. GSP-RM's own decoder takes that from a header ahead of the data, in the LIBOS_LOG_NVLOG_BUFFER_V2 layout.
Prepend that header to each debugfs dump. The build ID comes from the BLID tag of gsp.tlv, so request the metadata once when the GSP manager is created and hand it to the firmware loader rather than requesting it again during boot. A buffer whose build ID is missing serves its contents with no header.
--- drivers/gpu/nova-core/firmware.rs | 34 +++++ drivers/gpu/nova-core/firmware/gsp.rs | 9 +- drivers/gpu/nova-core/gpu.rs | 2 +- drivers/gpu/nova-core/gsp.rs | 183 ++++++++++++++++++++++---- drivers/gpu/nova-core/gsp/boot.rs | 2 +- 5 files changed, 199 insertions(+), 31 deletions(-)
drivers/gpu/nova-core/firmware.rs +34 -0
@@ -31,6 +31,40 @@pub (crate )mod riscv;pub (crate )mod tlv; +/// Maximum length of a build ID, matching Open RM's `BUILD_ID_MAX_LENGTH`. +const BUILD_ID_MAX_LENGTH :usize =32 ; + +/// Build ID extracted from firmware, used to correlate debugfs log buffer dumps +/// with the correct firmware symbols. +pub (crate )struct BuildId { + bytes: [u8 ;BUILD_ID_MAX_LENGTH ], + len:u8 , +} + +impl BuildId { +/// Constructs a [`BuildId`] from raw descriptor bytes. +/// +/// Returns `None` if `data` is empty or exceeds [`BUILD_ID_MAX_LENGTH`]. +pub (crate )fn from_raw (data: &[u8 ]) ->Option <Self > { +if data.is_empty () || data.len () >BUILD_ID_MAX_LENGTH { +return None ; + } + +let mut bytes = [0u8 ;BUILD_ID_MAX_LENGTH ]; + bytes[..data.len ()].copy_from_slice (data); + +Some (Self { + bytes, + len: data.len ()as u8 , + }) + } + +/// Returns the build ID bytes. +pub (crate )fn as_bytes (&self) -> &[u8 ] { + &self.bytes[..usize::from (self.len)] + } +} +/// Structure used to describe some firmwares, notably FWSEC-FRTS. #[repr( C )] #[derive( Debug , Clone , FromBytes )]
drivers/gpu/nova-core/firmware/gsp.rs +5 -4
@@ -6,6 +6,7 @@ Coherent, DmaAddress, // }, + firmware, prelude::*, str::CString, };
@@ -15,8 +16,8 @@ radix3::Radix3, riscv::RiscvFirmware, // tlv::{ - request_tlv,// -Tlv , + request_tlv, +Tlv ,// }, }, gpu::Chipset, //
@@ -46,10 +47,10 @@ impl GspFirmware { pub(crate) fn new<'a>( dev: &'a device::Device<device::Bound>, chipset: Chipset, + gsp_tlv: &'a firmware::Firmware, ) -> impl PinInit<Self, Error> + 'a { pin_init::pin_init_scope(move || { - let firmware = request_tlv(dev, chipset, "gsp")?; - let tlv = Tlv::new(firmware.data())?; + let tlv = Tlv::new(gsp_tlv.data())?; let fw_version = CString::try_from_fmt(fmt!("{}", tlv.get_string(b"VERS")?))?; dev_dbg!( dev,
drivers/gpu/nova-core/gpu.rs +1 -1
@@ -396,7 +396,7 @@ pub(crate) fn new( vgpu: VgpuManager::new(pdev, spec.chipset, fsp.as_mut()), - gsp <- Gsp::new(pdev), + gsp <- Gsp::new(pdev, spec.chipset),// This member must be initialized last, so the `UnloadBundle` can never be dropped // from outside of the constructed `GspResources`, ensuring that the unload sequence
drivers/gpu/nova-core/gsp.rs +158 -25
257 lines not on this page · raw message
drivers/gpu/nova-core/gsp/boot.rs +1 -1
@@ -42,7 +42,7 @@ pub(crate) fn boot(let dev = pdev.as_ref ();let hal =super ::hal::gsp_hal (chipset); -let gsp_fw =KBox ::pin_init (GspFirmware ::new (dev, chipset),GFP_KERNEL )?; +let gsp_fw =KBox ::pin_init (GspFirmware ::new (dev, chipset, &self.gsp_tlv),GFP_KERNEL )?; self.cmdq .send_command_no_wait (bar, commands::SetSystemInfo ::new (pdev, chipset))?;
Signature · 1 line
2.55.0
PATCH v2 11/31 gpu: nova-core: rename the FbRanges elf field to fw_image
In reply to John HubbardThe framebuffer region this field describes holds the GSP firmware image. A TLV firmware image carries the section extracted from the original ELF, and that section is not itself an ELF, so the field name has been wrong since the driver moved to TLV images.
Name the field for what the region holds rather than for a format it no longer has.
No functional change.
--- drivers/gpu/nova-core/fb.rs | 18 +++++++++--------- drivers/gpu/nova-core/gsp/fw.rs | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-)
drivers/gpu/nova-core/fb.rs +9 -9
@@ -159,7 +159,7 @@ pub(crate) struct FbRanges {/// Memory area containing the GSP bootloader image. pub(crate) boot: FbRange,/// Memory area containing the GSP firmware image. - pub(crate) elf: FbRange, + pub(crate) fw_image: FbRange,/// WPR2 heap. pub(crate) wpr2_heap: FbRange,/// WPR2 region range, starting with an instance of `GspFwWprMeta`.
@@ -234,25 +234,25 @@ pub(crate) fn new(FbRange (bootloader_base..bootloader_base + bootloader_size) }; -let elf = { -const ELF_DOWN_ALIGN :Alignment =Alignment ::new ::<SZ_64K >(); -let elf_size = u64::from_safe_cast (gsp_fw.size ()); -let elf_addr = (boot.start - elf_size).align_down (ELF_DOWN_ALIGN ); +let fw_image = { +const FW_IMAGE_DOWN_ALIGN :Alignment =Alignment ::new ::<SZ_64K >(); +let fw_image_size = u64::from_safe_cast (gsp_fw.size ()); +let fw_image_addr = (boot.start - fw_image_size).align_down (FW_IMAGE_DOWN_ALIGN ); -FbRange (elf_addr..elf_addr + elf_size) +FbRange (fw_image_addr..fw_image_addr + fw_image_size) };let (vf_partition_count, wpr2_heap_size) =wpr2_heap_params (chipset, vgpu_state, fb.end)?;let wpr2_heap = {const WPR2_HEAP_DOWN_ALIGN :Alignment =Alignment ::new ::<SZ_1M >(); -let wpr2_heap_addr = elf +let wpr2_heap_addr = fw_image .start .checked_sub (wpr2_heap_size) .ok_or (EOVERFLOW )? .align_down (WPR2_HEAP_DOWN_ALIGN ); -FbRange (wpr2_heap_addr..(elf.start).align_down (WPR2_HEAP_DOWN_ALIGN )) +FbRange (wpr2_heap_addr..(fw_image.start).align_down (WPR2_HEAP_DOWN_ALIGN )) };let wpr2 = {
@@ -273,7 +273,7 @@ pub(crate) fn new( vga_workspace, frts, boot, - elf, + fw_image, wpr2_heap, wpr2, non_wpr_heap,
drivers/gpu/nova-core/gsp/fw.rs +1 -1
@@ -206,7 +206,7 @@ pub(crate) fn from_ranges<'a>( gspFwWprStart: ranges.wpr2.start, gspFwHeapOffset: ranges.wpr2_heap.start, gspFwHeapSize: ranges.wpr2_heap.len(), - gspFwOffset: ranges.elf.start, + gspFwOffset: ranges.fw_image.start, bootBinOffset: ranges.boot.start, frtsOffset: ranges.frts.start, frtsSize: ranges.frts.len(),
Signature · 1 line
2.55.0
PATCH v2 12/31 gpu: nova-core: regs: add msgq v2 BAR0 register declarations
In reply to John HubbardMsgq v2 moves the four ring pointers out of the in-memory headers and into BAR0. NV_PGSP_QUEUE_HEAD already exists as the v0 doorbell, so add NV_PGSP_QUEUE_TAIL, NV_PGSP_MSGQ_HEAD, and NV_PGSP_MSGQ_TAIL at the queue-0 offsets.
Nova only uses queue 0, so the registers are scalars rather than 8-element arrays. A comment records the full hardware layout for future multi-queue work.
--- drivers/gpu/nova-core/gsp/regs.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+)
drivers/gpu/nova-core/gsp/regs.rs +30 -0
@@ -5,6 +5,18 @@use crate ::regs::NV_PBUS_SW_SCRATCH ;// PGSP +// +// The msgq v2 wire protocol replaces the in-memory ring pointers with four +// BAR0 registers per queue: +// +// NV_PGSP_QUEUE_HEAD[i] @ 0x00110c00 + i*8 (CPU TX write, doorbell) +// NV_PGSP_QUEUE_TAIL[i] @ 0x00110c04 + i*8 (GSP TX read) +// NV_PGSP_MSGQ_HEAD[i] @ 0x00110c80 + i*8 (GSP RX write) +// NV_PGSP_MSGQ_TAIL[i] @ 0x00110c84 + i*8 (CPU RX read) +// +// Nova only uses queue 0, so the four registers are declared as single +// scalars at the i=0 offsets. NV_PGSP_QUEUE_HEAD is also used as the v0 +// doorbell, which is why it predates the others. register! {pub (super )NV_PGSP_QUEUE_HEAD (u32 ) @0x00110c00 {
@@ -12,6 +24,24 @@ } } +register! { +pub (super )NV_PGSP_QUEUE_TAIL (u32 ) @0x00110c04 { +31 :0 address; + } +} + +register! { +pub (super )NV_PGSP_MSGQ_HEAD (u32 ) @0x00110c80 { +31 :0 address; + } +} + +register! { +pub (super )NV_PGSP_MSGQ_TAIL (u32 ) @0x00110c84 { +31 :0 address; + } +} +// PBUS register! {
Signature · 1 line
2.55.0
PATCH v2 13/31 gpu: nova-core: gsp: add msgq v2 internals
In reply to John HubbardMsgq v2 moves the four ring pointers out of shared memory into BAR0 registers and treats them as monotonic counters, so head == tail distinguishes empty from full and the ring uses every slot. The pointers can also be out of step, because a GSP reset zeroes them while the ring keeps its contents.
Add the v2 TX header and the v2 ring helpers in parallel to the v0 ones, so the flip commit can swap call sites without writing new logic. Read the queue as empty while the read pointer is ahead of the write pointer, rather than taking the difference as a page count.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 140 ++++++++++++++++++++++++++++++ drivers/gpu/nova-core/gsp/fw.rs | 36 ++++++++ 2 files changed, 176 insertions(+)
drivers/gpu/nova-core/gsp/cmdq.rs +140 -0
@@ -467,6 +467,146 @@ fn advance_cpu_write_ptr(&mut self, elem_count: u32) { } } +// Msgq v2 internals. +// +// Msgq v2 keeps the four ring pointers in BAR0 registers as monotonic `u32` +// counters that wrap on overflow. The slot index is `ptr % MSGQ_NUM_PAGES` +// only at the point of use, and the ring uses every slot (no "leave one +// empty" rule, since `head == tail` distinguishes empty from full). +// +// Register-to-role mapping for queue 0: +// +// CPU TX write/doorbell: NV_PGSP_QUEUE_HEAD +// GSP TX read: NV_PGSP_QUEUE_TAIL +// GSP RX write: NV_PGSP_MSGQ_HEAD +// CPU RX read: NV_PGSP_MSGQ_TAIL +// +// A GSP reset zeroes all four counters while the in-memory ring keeps its +// contents, so the two ends can be out of step. Between the reset and +// GSP-RM writing its counter back the read pointer is ahead of the write +// pointer, which `driver_read_area_v2` reports as an empty ring. +// +// TODO: suspend/resume reset-recovery is not implemented. A power cycle +// loses the driver-side counters as well, so both ends have to be +// re-established. +#[expect(dead_code)] +impl DmaGspMem { +fn gsp_write_ptr_v2 (bar:Bar0 <'_>) ->u32 { + *bar.read (regs::NV_PGSP_MSGQ_HEAD ).address () + } + +fn gsp_read_ptr_v2 (bar:Bar0 <'_>) ->u32 { + *bar.read (regs::NV_PGSP_QUEUE_TAIL ).address () + } + +fn cpu_read_ptr_v2 (bar:Bar0 <'_>) ->u32 { + *bar.read (regs::NV_PGSP_MSGQ_TAIL ).address () + } + +fn cpu_write_ptr_v2 (bar:Bar0 <'_>) ->u32 { + *bar.read (regs::NV_PGSP_QUEUE_HEAD ).address () + } + +fn advance_cpu_read_ptr_v2 (bar:Bar0 <'_>, count:u32 ) { +let new_rptr =Self ::cpu_read_ptr_v2 (bar).wrapping_add (count); + +// Order all reads from the message data ahead of the read-pointer +// update so the GSP cannot recycle the slots while we are still +// looking at them. +fence (Ordering ::SeqCst ); + + bar.write_reg (regs::NV_PGSP_MSGQ_TAIL ::zeroed ().with_address (new_rptr)); + } + +fn advance_cpu_write_ptr_v2 (bar:Bar0 <'_>, count:u32 ) { +let new_wptr =Self ::cpu_write_ptr_v2 (bar).wrapping_add (count); + +// Order all writes to the message data ahead of the write-pointer +// update. Writing the head register doubles as the GSP doorbell. +fence (Ordering ::SeqCst ); + + bar.write_reg (regs::NV_PGSP_QUEUE_HEAD ::zeroed ().with_address (new_wptr)); + } + +/// Returns the region of the CPU message queue that the driver is currently allowed to write +/// to. +/// +/// As the message queue is a circular buffer, the region may be discontiguous in memory. In +/// that case the second slice will have a non-zero length. +fn driver_write_area_v2 ( + &mut self, + bar:Bar0 <'_>, + ) -> (&mut [[u8 ;GSP_PAGE_SIZE ]], &mut [[u8 ;GSP_PAGE_SIZE ]]) { +let raw_w =Self ::cpu_write_ptr_v2 (bar); +let raw_r =Self ::gsp_read_ptr_v2 (bar); + +let used = raw_w.wrapping_sub (raw_r); +let avail = num::u32_as_usize (MSGQ_NUM_PAGES .saturating_sub (used)); +let w_slot = num::u32_as_usize (raw_w %MSGQ_NUM_PAGES ); + +// Pointer to the first entry of the CPU message queue. +let data = ptr::project!(mut self.0 .as_mut_ptr (), .cpuq.msgq.data[build:0 ]); + +// SAFETY: +// - `data` points to `MSGQ_NUM_PAGES` valid message queue entries. +// - We will only access the driver-owned part of the shared memory. +// - Per the safety statement of the function, no concurrent access will be performed. +let data = +unsafe { core::slice::from_raw_parts_mut (data, num::u32_as_usize (MSGQ_NUM_PAGES )) }; +let (before_w, after_w) = data.split_at_mut (w_slot); + +let in_after = avail.min (after_w.len ()); +let in_before = avail - in_after; + (&mut after_w[..in_after], &mut before_w[..in_before]) + } + +/// Returns the size, in bytes, of the region of the CPU message queue that the driver is +/// currently allowed to write to. +fn driver_write_area_size_v2 (bar:Bar0 <'_>) ->usize { +let used =Self ::cpu_write_ptr_v2 (bar).wrapping_sub (Self ::gsp_read_ptr_v2 (bar)); +let slots =MSGQ_NUM_PAGES .saturating_sub (used); + num::u32_as_usize (slots) *GSP_PAGE_SIZE + } + +/// Returns the region of the GSP message queue that the driver is currently allowed to read +/// from. +/// +/// As the message queue is a circular buffer, the region may be discontiguous in memory. In +/// that case the second slice will have a non-zero length. +fn driver_read_area_v2 ( + &self, + bar:Bar0 <'_>, + ) -> (&[[u8 ;GSP_PAGE_SIZE ]], &[[u8 ;GSP_PAGE_SIZE ]]) { +let raw_w =Self ::gsp_write_ptr_v2 (bar); +let raw_r =Self ::cpu_read_ptr_v2 (bar); + +// A difference wider than the ring means the GSP has been reset and has not yet written +// its own counter back, so the read pointer is momentarily ahead of it. Report nothing +// readable, which holds the callers in their poll until GSP-RM restores the real value. +let pending = raw_w.wrapping_sub (raw_r); +let avail =if pending >MSGQ_NUM_PAGES { +0 + }else { + num::u32_as_usize (pending) + }; +let r_slot = num::u32_as_usize (raw_r %MSGQ_NUM_PAGES ); + +// Pointer to the first entry of the GSP message queue. +let data = ptr::project!(self.0 .as_ptr (), .gspq.msgq.data[build:0 ]); + +// SAFETY: +// - `data` points to `MSGQ_NUM_PAGES` valid message queue entries. +// - We will only access the driver-owned part of the shared memory. +// - Per the safety statement of the function, no concurrent access will be performed. +let data =unsafe { core::slice::from_raw_parts (data, num::u32_as_usize (MSGQ_NUM_PAGES )) }; +let (before_r, after_r) = data.split_at (r_slot); + +let in_after = avail.min (after_r.len ()); +let in_before = avail - in_after; + (&after_r[..in_after], &before_r[..in_before]) + } +} +/// A command ready to be sent on the command queue. /// /// This is the type returned by [`DmaGspMem::allocate_command`].
drivers/gpu/nova-core/gsp/fw.rs +36 -0
@@ -758,6 +758,42 @@ pub(crate) fn set_write_ptr(this: CoherentView<'_, Self>, val: u32) {// SAFETY: Padding is explicit and does not contain uninitialized data. unsafe impl AsBytes for MsgqTxHeader {} +/// TX header for setting up a message queue with the GSP, msgq v2 layout. +/// +/// Same wire size as [`MsgqTxHeader`] (32 bytes) with a different field +/// layout: the v0 `writePtr`, `flags`, and `rxHdrOff` fields are gone, the +/// `version` `u32` becomes split `versionMajor`/`versionMinor` `u16`s, and +/// the trailing space holds three reserved `u32`s. +#[repr(transparent)] +pub (crate )struct MsgqTxHeaderV2 (r000_00::msgqTxHeader ); + +#[expect(dead_code)] +impl MsgqTxHeaderV2 { +/// Creates a new v2 TX queue header. +/// +/// # Arguments +/// +/// * `msgq_size` - Total size of the message queue structure, in bytes. +/// * `msg_size` - Size of each message slot, in bytes. +/// * `msg_count` - Number of message slots in the ring. +/// * `entry_off` - Byte offset from the start of the queue at which the +/// message data array begins. +pub (crate )fn new (msgq_size:u32 , msg_size:u32 , msg_count:u32 , entry_off:u32 ) ->Self { +Self (r000_00::msgqTxHeader { + versionMajor:2 , + versionMinor:0 , + size: msgq_size, + msgSize: msg_size, + msgCount: msg_count, + entryOff: entry_off, + reserved: [0 ;3 ], + }) + } +} + +// SAFETY: Padding is explicit and does not contain uninitialized data. +unsafe impl AsBytes for MsgqTxHeaderV2 {} +/// RX header for setting up a message queue with the GSP. #[repr(transparent)] pub (crate )struct MsgqRxHeader (bindings::msgqRxHeader );
Signature · 1 line
2.55.0
Re: [PATCH v2 13/31] gpu: nova-core: gsp: add msgq v2 internals
Quoted 156 lines · John Hubbard
Msgq v2 moves the four ring pointers out of shared memory into BAR0 registers and treats them as monotonic counters, so head == tail distinguishes empty from full and the ring uses every slot. The pointers can also be out of step, because a GSP reset zeroes them while the ring keeps its contents.
Add the v2 TX header and the v2 ring helpers in parallel to the v0 ones, so the flip commit can swap call sites without writing new logic. Read the queue as empty while the read pointer is ahead of the write pointer, rather than taking the difference as a page count.
Assisted-by Cursor:claude-opus-5Reviewed-by Timur Tabi <[email protected]>Signed-off-by John Hubbard <[email protected]>--- drivers/gpu/nova-core/gsp/cmdq.rs | 140 ++++++++++++++++++++++++++++++ drivers/gpu/nova-core/gsp/fw.rs | 36 ++++++++ 2 files changed, 176 insertions(+)drivers/gpu/nova-core/gsp/cmdq.rs +129
-0@@ -467,6 +467,146 @@ fn advance_cpu_write_ptr(&mut self, elem_count: u32) { } } +// Msgq v2 internals. +// +// Msgq v2 keeps the four ring pointers in BAR0 registers as monotonic `u32` +// counters that wrap on overflow. The slot index is `ptr % MSGQ_NUM_PAGES` +// only at the point of use, and the ring uses every slot (no "leave one +// empty" rule, since `head == tail` distinguishes empty from full). +// +// Register-to-role mapping for queue 0: +// +// CPU TX write/doorbell: NV_PGSP_QUEUE_HEAD +// GSP TX read: NV_PGSP_QUEUE_TAIL +// GSP RX write: NV_PGSP_MSGQ_HEAD +// CPU RX read: NV_PGSP_MSGQ_TAIL +// +// A GSP reset zeroes all four counters while the in-memory ring keeps its +// contents, so the two ends can be out of step. Between the reset and +// GSP-RM writing its counter back the read pointer is ahead of the write +// pointer, which `driver_read_area_v2` reports as an empty ring. +// +// TODO: suspend/resume reset-recovery is not implemented. A power cycle +// loses the driver-side counters as well, so both ends have to be +// re-established. +#[expect(dead_code)] +impl DmaGspMem { +fn gsp_write_ptr_v2 (bar:Bar0 <'_>) ->u32 { + *bar.read (regs::NV_PGSP_MSGQ_HEAD ).address () + } + +fn gsp_read_ptr_v2 (bar:Bar0 <'_>) ->u32 { + *bar.read (regs::NV_PGSP_QUEUE_TAIL ).address () + } + +fn cpu_read_ptr_v2 (bar:Bar0 <'_>) ->u32 { + *bar.read (regs::NV_PGSP_MSGQ_TAIL ).address () + } + +fn cpu_write_ptr_v2 (bar:Bar0 <'_>) ->u32 { + *bar.read (regs::NV_PGSP_QUEUE_HEAD ).address () + } + +fn advance_cpu_read_ptr_v2 (bar:Bar0 <'_>, count:u32 ) { +let new_rptr =Self ::cpu_read_ptr_v2 (bar).wrapping_add (count); + +// Order all reads from the message data ahead of the read-pointer +// update so the GSP cannot recycle the slots while we are still +// looking at them. +fence (Ordering ::SeqCst ); + + bar.write_reg (regs::NV_PGSP_MSGQ_TAIL ::zeroed ().with_address (new_rptr)); + } + +fn advance_cpu_write_ptr_v2 (bar:Bar0 <'_>, count:u32 ) { +let new_wptr =Self ::cpu_write_ptr_v2 (bar).wrapping_add (count); + +// Order all writes to the message data ahead of the write-pointer +// update. Writing the head register doubles as the GSP doorbell. +fence (Ordering ::SeqCst ); + + bar.write_reg (regs::NV_PGSP_QUEUE_HEAD ::zeroed ().with_address (new_wptr)); + } + +/// Returns the region of the CPU message queue that the driver is currently allowed to write +/// to. +/// +/// As the message queue is a circular buffer, the region may be discontiguous in memory. In +/// that case the second slice will have a non-zero length. +fn driver_write_area_v2 ( + &mut self, + bar:Bar0 <'_>, + ) -> (&mut [[u8 ;GSP_PAGE_SIZE ]], &mut [[u8 ;GSP_PAGE_SIZE ]]) { +let raw_w =Self ::cpu_write_ptr_v2 (bar); +let raw_r =Self ::gsp_read_ptr_v2 (bar); + +let used = raw_w.wrapping_sub (raw_r); +let avail = num::u32_as_usize (MSGQ_NUM_PAGES .saturating_sub (used)); +let w_slot = num::u32_as_usize (raw_w %MSGQ_NUM_PAGES ); + +// Pointer to the first entry of the CPU message queue. +let data = ptr::project!(mut self.0 .as_mut_ptr (), .cpuq.msgq.data[build:0 ]); + +// SAFETY: +// - `data` points to `MSGQ_NUM_PAGES` valid message queue entries. +// - We will only access the driver-owned part of the shared memory. +// - Per the safety statement of the function, no concurrent access will be performed. +let data = +unsafe { core::slice::from_raw_parts_mut (data, num::u32_as_usize (MSGQ_NUM_PAGES )) }; +let (before_w, after_w) = data.split_at_mut (w_slot); + +let in_after = avail.min (after_w.len ()); +let in_before = avail - in_after; + (&mut after_w[..in_after], &mut before_w[..in_before]) + } + +/// Returns the size, in bytes, of the region of the CPU message queue that the driver is +/// currently allowed to write to. +fn driver_write_area_size_v2 (bar:Bar0 <'_>) ->usize { +let used =Self ::cpu_write_ptr_v2 (bar).wrapping_sub (Self ::gsp_read_ptr_v2 (bar)); +let slots =MSGQ_NUM_PAGES .saturating_sub (used); + num::u32_as_usize (slots) *GSP_PAGE_SIZE + } + +/// Returns the region of the GSP message queue that the driver is currently allowed to read +/// from. +/// +/// As the message queue is a circular buffer, the region may be discontiguous in memory. In +/// that case the second slice will have a non-zero length. +fn driver_read_area_v2 ( + &self, + bar:Bar0 <'_>, + ) -> (&[[u8 ;GSP_PAGE_SIZE ]], &[[u8 ;GSP_PAGE_SIZE ]]) { +let raw_w =Self ::gsp_write_ptr_v2 (bar); +let raw_r =Self ::cpu_read_ptr_v2 (bar); + +// A difference wider than the ring means the GSP has been reset and has not yet written +// its own counter back, so the read pointer is momentarily ahead of it. Report nothing +// readable, which holds the callers in their poll until GSP-RM restores the real value. +let pending = raw_w.wrapping_sub (raw_r); +let avail =if pending >MSGQ_NUM_PAGES { +0 + }else { + num::u32_as_usize (pending) + }; +let r_slot = num::u32_as_usize (raw_r %MSGQ_NUM_PAGES ); + +// Pointer to the first entry of the GSP message queue. +let data = ptr::project!(self.0 .as_ptr (), .gspq.msgq.data[build:0 ]); + +// SAFETY: +// - `data` points to `MSGQ_NUM_PAGES` valid message queue entries.
drivers/gpu/nova-core/gsp/cmdq.rs fn advance_cpu_write_ptr(&mut self, elem_count: u32) { · line 608
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +10
-0+// - We will only access the driver-owned part of the shared memory. +// - Per the safety statement of the function, no concurrent access will be performed. +let data =unsafe { core::slice::from_raw_parts (data, num::u32_as_usize (MSGQ_NUM_PAGES )) }; +let (before_r, after_r) = data.split_at (r_slot); + +let in_after = avail.min (after_r.len ()); +let in_before = avail - in_after; + (&after_r[..in_after], &before_r[..in_before]) + } +}
I think this is a good candidate for a trait, instead of using *_v2 named functions. Similarly, think we should also abstract out sending commands (later in this series) with a trait.
PATCH v2 14/31 gpu: nova-core: generalize allocate_command() for variable headers
In reply to John HubbardThe GMC command path uses a different message element header from the VGPU-style RPC path, but the two share the queue, the space accounting, and the wrapping rules. Make allocate_command() and GspCommand generic over the header type, defaulting to GspMsgElement so the existing RPC callers are unchanged.
No functional changes.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +15 -7
@@ -365,6 +365,8 @@ fn driver_write_area_size(&self) -> usize {/// Allocates a region on the command queue that is large enough to send a command of `size` /// bytes, waiting for space to become available based on the provided timeout. /// +/// The type parameter `H` selects the message element header, [`GspMsgElement`] for RM RPC. +/// /// This returns a [`GspCommand`] ready to be written to by the caller. /// /// # Errors
@@ -372,13 +374,17 @@ fn driver_write_area_size(&self) -> usize {/// - `EMSGSIZE` if the command is larger than [`GSP_MSG_QUEUE_ELEMENT_SIZE_MAX`]. /// - `ETIMEDOUT` if space does not become available within the timeout. /// - `EIO` if the command header is not properly aligned. -fn allocate_command (&mut self, size:usize , timeout:Delta ) ->Result <GspCommand <'_>> { -if size_of ::<GspMsgElement >() + size >GSP_MSG_QUEUE_ELEMENT_SIZE_MAX { +fn allocate_command <H :FromBytes +AsBytes >( + &mut self, + size:usize , + timeout:Delta , + ) ->Result <GspCommand <'_,H >> { +if size_of ::<H >() + size >GSP_MSG_QUEUE_ELEMENT_SIZE_MAX {return Err (EMSGSIZE ); }read_poll_timeout ( ||Ok (self.driver_write_area_size ()), - |available_bytes| *available_bytes >=size_of ::<GspMsgElement >() + size, + |available_bytes| *available_bytes >=size_of ::<H >() + size,Delta ::from_micros (1 ), timeout, )?;
@@ -390,8 +396,8 @@ fn allocate_command(&mut self, size: usize, timeout: Delta) -> Result<GspCommand (slice_1.as_flattened_mut (), slice_2.as_flattened_mut ()) }; -// Extract area for the `GspMsgElement`. -let (header, slice_1) =GspMsgElement ::from_bytes_mut_prefix (slice_1).ok_or (EIO )?; +// Extract area for the message element header. +let (header, slice_1) =H ::from_bytes_mut_prefix (slice_1).ok_or (EIO )?;// Create the contents area. let (slice_1, slice_2) =if slice_1.len () > size {
@@ -609,10 +615,12 @@ fn driver_read_area_v2(/// A command ready to be sent on the command queue. /// +/// The type parameter `H` is the message element header type, [`GspMsgElement`] for RM RPC. +/// /// This is the type returned by [`DmaGspMem::allocate_command`]. -struct GspCommand <'a> { +struct GspCommand <'a,H =GspMsgElement > {// Writable reference to the header of the command. - header: &'amut GspMsgElement , + header: &'amut H ,// Writable slices to the contents of the command. The second slice is zero unless the command // loops over the command queue. contents: (&'amut [u8 ], &'amut [u8 ]),
Signature · 1 line
2.55.0
PATCH v2 15/31 gpu: nova-core: add GMC API message types
In reply to John HubbardThe new firmware carries GMC commands over the same MCTP/NVDM transport as the RPC path, under NVDM type 0x26 and with its own fixed header in place of rpc_message_header_v. Add that header as GmcApiHeader, matching Open RM's GMCAPI_HEADER, and the queue element that wraps it.
--- drivers/gpu/nova-core/gsp/fw.rs | 147 ++++++++++++++++++++++++++++++++ drivers/gpu/nova-core/mctp.rs | 2 + 2 files changed, 149 insertions(+)
drivers/gpu/nova-core/gsp/fw.rs +147 -0
@@ -50,6 +50,11 @@ cmdq::Cmdq, // GSP_PAGE_SIZE, }, + mctp::{ + MctpHeader, + NvdmHeader, + NvdmType, // + }, num::{ self,FromSafeCast ,//
@@ -947,6 +952,148 @@ unsafe impl AsBytes for GspMsgElement {}// are valid. unsafe impl FromBytes for GspMsgElement {} +/// Magic value that opens every MCTP-framed queue element: `"MCTP"` in ASCII. +const MCTP_MAGIC :u32 =0x4D43_5450 ; + +/// GMC API message header. +/// +/// Matches the `GMCAPI_HEADER` struct from Open RM. The `command` field carries +/// flags in the high byte and a 24-bit command ID in the low bits. `size` is the +/// payload size for both requests and responses, while the union at offset 16 +/// carries the maximum response size for requests and the status for responses. +#[repr( C )] +#[derive( Zeroable )] +pub (crate )struct GmcApiHeader { +/// GMC command identifier with flags in the high byte. +pub (crate ) command:u32 , +/// Payload size in bytes. +pub (crate ) size:u32 , +/// Sequence number for matching requests to responses. +pub (crate ) sequence:u64 , +/// Request: maximum response size. Response: `NV_STATUS` code. +pub (crate ) max_resp_or_status:u32 , + reserved: [u32 ;5 ], +} + +static_assert! (size_of ::<GmcApiHeader >() ==size_of ::<r000_00::GMCAPI_HEADER >()); +static_assert! ( + core::mem::offset_of!(GmcApiHeader , command) + == core::mem::offset_of!(r000_00::GMCAPI_HEADER , command) +); +static_assert! ( + core::mem::offset_of!(GmcApiHeader , size) + == core::mem::offset_of!(r000_00::GMCAPI_HEADER , size) +); +static_assert! ( + core::mem::offset_of!(GmcApiHeader , sequence) + == core::mem::offset_of!(r000_00::GMCAPI_HEADER , sequence) +); +static_assert! ( + core::mem::offset_of!(GmcApiHeader , max_resp_or_status) + == core::mem::offset_of!(r000_00::GMCAPI_HEADER , __bindgen_anon_1) +); +static_assert! ( + core::mem::offset_of!(GmcApiHeader , reserved) + == core::mem::offset_of!(r000_00::GMCAPI_HEADER , reserved) +); + +// SAFETY: All fields are integer types with no uninitialized padding bytes. +unsafe impl AsBytes for GmcApiHeader {} + +// SAFETY: All fields are integer types for which all bit patterns are valid. +unsafe impl FromBytes for GmcApiHeader {} + +/// Header for an unencrypted GMC API message in the GSP command queue. +/// +/// The fields before `gmc` match `GSP_MSG_QUEUE_ELEMENT` through its +/// `noEncryption` union member. `gmc` occupies the start of that member's +/// flexible payload array, and the GMC command payload follows this structure. +#[repr( C )] +pub (crate )struct GspGmcMsgElement { + mctp_magic:u32 , + mctp_payload_size:u32 , + mctp_header:MctpHeader , + nvdm_header:NvdmHeader , + nvdm_payload_size:u32 , + reserved:u32 , +pub (crate ) gmc:GmcApiHeader , +} + +static_assert! ( + core::mem::offset_of!(GspGmcMsgElement , mctp_magic) + == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT , mctpMagic) +); +static_assert! ( + core::mem::offset_of!(GspGmcMsgElement , mctp_payload_size) + == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT , mctpPayloadSize) +); +static_assert! ( + core::mem::offset_of!(GspGmcMsgElement , mctp_header) + == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT , mctpHeader) +); +static_assert! ( + core::mem::offset_of!(GspGmcMsgElement , nvdm_header) + == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT , nvdmHeader) +); + +#[expect(dead_code)] +impl GspGmcMsgElement { +/// Creates a new GMC message element. +/// +/// `payload_size` is the size of the command payload following this header. +/// `command_id` is the GMC command identifier. +/// `sequence` is the sequence number for request/response matching. +/// `max_response_size` is the maximum expected response payload size. +pub (crate )fn init ( + command_id:u32 , + sequence:u64 , + payload_size:usize , + max_response_size:u32 , + ) ->impl Init <Self ,Error > { +try_init! (GspGmcMsgElement { + mctp_magic:MCTP_MAGIC , +// Despite the name, this counts the element header as well as the payload. + mctp_payload_size:size_of ::<Self >() + .checked_add (payload_size) + .ok_or (EOVERFLOW )? + .try_into () + .map_err (|_|EOVERFLOW )?, + mctp_header:MctpHeader ::single_packet (), + nvdm_header:NvdmHeader ::new (NvdmType ::GmcApi ), + nvdm_payload_size:size_of ::<GmcApiHeader >() + .checked_add (payload_size) + .ok_or (EOVERFLOW )? + .try_into () + .map_err (|_|EOVERFLOW )?, + reserved:0u32 , + gmc:GmcApiHeader { + command: command_id, + size: payload_size.try_into ().map_err (|_|EOVERFLOW )?, + sequence, + max_resp_or_status: max_response_size, + reserved: [0 ;5 ], + }, + }) + } + +/// Returns the total length of the message, transport and GMC headers included. +pub (crate )fn length (&self) ->usize { + num::u32_as_usize (self.mctp_payload_size) + } + +/// Returns the number of elements (i.e. memory pages) used by this message. +pub (crate )fn element_count (&self) ->u32 { + self.mctp_payload_size + .div_ceil (num::usize_into_u32 ::<GSP_PAGE_SIZE >()) + } +} + +// SAFETY: All fields are integer types with no uninitialized padding bytes. +unsafe impl AsBytes for GspGmcMsgElement {} + +// SAFETY: All fields are integer types for which all bit patterns are valid. +unsafe impl FromBytes for GspGmcMsgElement {} +/// Arguments for GSP startup. #[repr(transparent)] #[derive( Zeroable )]
drivers/gpu/nova-core/mctp.rs +2 -0
@@ -28,6 +28,8 @@ pub(crate) enum NvdmType with TryFrom<Bounded<u32, 8>> { Cot = 0x14,/// FSP command response. FspResponse = 0x15, +/// GMC API message (GSP command queue). + GmcApi = 0x26, } }
Signature · 1 line
2.55.0
PATCH v2 16/31 gpu: nova-core: add GMC send path
In reply to John HubbardThe r000 GSP-RM boot protocol requires the driver to send GSP_INIT as a GMC command. GMC and RPC commands share the command queue and sequence counter. GMC queue elements carry a GMC API header and no checksum.
Add the GMC send path needed for GSP_INIT.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 59 +++++++++++++++++++++++++++++++ drivers/gpu/nova-core/gsp/fw.rs | 1 - 2 files changed, 59 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/gsp/cmdq.rs +59 -0
@@ -52,6 +52,7 @@ driver::Bar0, gsp::{ fw::{ +GspGmcMsgElement ,GspMsgElement ,MsgFunction ,MsgqRxHeader ,
@@ -963,6 +964,64 @@ fn send_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result<u32>Ok (rpc_seq) } +/// Sends a GMC API command to the GSP. +/// +/// `command_id` is the GMC command identifier (from `GMCAPI_COMMANDS`). +/// `payload` is the command-specific data following the [`super::fw::GmcApiHeader`]. +/// `max_response_size` is the maximum expected response payload size. +/// +/// The command carries the next RPC sequence number, which the GSP echoes in its response. +/// The number is consumed whether or not the send succeeds. +/// +/// # Errors +/// +/// - `EMSGSIZE` if the command exceeds the maximum queue element size. +/// - `ETIMEDOUT` if space does not become available within the timeout. +/// - `EIO` if the command header is not properly aligned. +#[expect(dead_code)] +fn send_gmc ( + &mut self, + bar:Bar0 <'_>, + command_id:u32 , + payload: &[u8 ], + max_response_size:u32 , + ) ->Result { +let rpc_seq = self.rpc_seq; + self.rpc_seq = self.rpc_seq.wrapping_add (1 ); + +let dst = self + .gsp_mem + .allocate_command ::<GspGmcMsgElement >(payload.len (),Self ::ALLOCATE_TIMEOUT )?; + +let msg_element =GspGmcMsgElement ::init ( + command_id, + u64::from (rpc_seq), + payload.len (), + max_response_size, + ); +// SAFETY: `dst.header` points to a valid, writable `GspGmcMsgElement` region. +unsafe { + msg_element.__init (core::ptr::from_mut (dst.header))?; + } + +SBufferIter ::new_writer ([&mut dst.contents.0 [..], &mut dst.contents.1 [..]]) + .write_all (payload)?; + +dev_dbg! ( + &self.dev, +"GSP GMC: send: seq# {}, command_id=0x{:x}, length=0x{:x}\n" , + rpc_seq, + command_id, + dst.header.length (), + ); + +let elem_count = dst.header.element_count (); + self.gsp_mem.advance_cpu_write_ptr (elem_count); +Cmdq ::notify_gsp (bar); + +Ok (()) + } +/// Wait for a message to become available on the message queue. /// /// This works purely at the transport layer and does not interpret or validate the message
drivers/gpu/nova-core/gsp/fw.rs +0 -1
@@ -1036,7 +1036,6 @@ pub(crate) struct GspGmcMsgElement { == core::mem::offset_of!(r000_00::GSP_MSG_QUEUE_ELEMENT, nvdmHeader) ); -#[expect(dead_code)] impl GspGmcMsgElement {/// Creates a new GMC message element. ///
Signature · 1 line
2.55.0
PATCH v2 17/31 gpu: nova-core: add GMC transport receive path
In reply to John HubbardGSP-RM posts GMC and RPC messages on the same message queue. Both use the same MCTP and NVDM transport headers, but RPC messages continue with rpc_message_header_v and GMC messages continue with GmcApiHeader. Existing RPC receive code cannot parse the GMC layout.
Add a GMC receive path. It checks the MCTP magic, the MCTP header version and the NVIDIA vendor id, and requires the declared element length to lie between the element header size and the maximum queue element size, matching the checks Open RM makes on arriving elements.
Poison the queue on any of those failures. The read pointer advances by the declared length, so without a trusted length the driver cannot move past the element at all.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 87 ++++++++++++++++++++++++++++++- drivers/gpu/nova-core/gsp/fw.rs | 54 +++++++++++++++++++ drivers/gpu/nova-core/mctp.rs | 14 ++++- 3 files changed, 152 insertions(+), 3 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +86 -1
@@ -629,7 +629,7 @@ struct GspCommand<'a, H = GspMsgElement> {/// A message ready to be processed from the message queue. /// -/// This is the type returned by [`Cmdq::wait_for_msg`]. +/// This is the type returned by [`CmdqInner::wait_for_msg`]. struct GspMessage <'a> {// Reference to the header of the message. header: &'aGspMsgElement ,
@@ -638,6 +638,18 @@ struct GspMessage<'a> { contents: (&'a [u8], &'a [u8]), } +/// A GMC message ready to be processed from the message queue. +/// +/// This is the type returned by [`CmdqInner::wait_for_gmc_msg`]. +#[expect(dead_code)] +struct GmcMessage <'a> { +// Reference to the header of the message. + header: &'aGspGmcMsgElement , +// Slices of the payload following the `GmcApiHeader`. The second slice is empty unless the +// payload wraps around the end of the message queue. + contents: (&'a [u8 ], &'a [u8 ]), +} +/// GSP command queue. /// /// Provides the ability to send commands and receive messages from the GSP using a shared memory
@@ -1285,4 +1297,77 @@ fn drain(&mut self) -> Result {Ok (()) } + +/// Wait for a GMC message to become available on the message queue. +/// +/// This is the GMC counterpart to [`Self::wait_for_msg`] and reads the same queue. Like that +/// method it works purely at the transport layer, validating the MCTP framing and the +/// advertised length and nothing else. +/// +/// A [`GspGmcMsgElement`] and a [`GspMsgElement`] share every field through `nvdm_header`, +/// so a caller that may see either must check the NVDM type before reading `gmc`. Both +/// layouts put the element length in the same place, so the caller can advance the read +/// pointer past a returned message either way. +/// +/// # Errors +/// +/// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. +/// - `EIO` if the framing is invalid, or the queue was already poisoned by an earlier such +/// failure. Either failure poisons the queue, so recovery requires a reset. +#[expect(dead_code)] +fn wait_for_gmc_msg (&self, timeout:Delta ) ->Result <GmcMessage <'_>> { +if self.poisoned.get () { +return Err (EIO ); + } + +let (slice_1, slice_2) =read_poll_timeout ( + ||Ok (self.gsp_mem.driver_read_area ()), + |driver_area| !driver_area.0 .is_empty (), +Delta ::from_millis (1 ), + timeout, + ) + .map (|(slice_1, slice_2)| (slice_1.as_flattened (), slice_2.as_flattened ()))?; + +let Some ((header, slice_1)) =GspGmcMsgElement ::from_bytes_prefix (slice_1)else { + self.poisoned.set (true ); +return Err (EIO ); + }; + +// Checked before any length field is read, since bad framing leaves them untrusted. +if let Err (e) = header.validate_framing () { +dev_err! ( + &self.dev, +"GSP GMC: receive: bad MCTP framing, declared length {}\n" , + header.length (), + ); + self.poisoned.set (true ); +return Err (e); + } + +let payload_length = header.payload_length (); + +// Check that the driver read area is large enough for the message. +if slice_1.len () + slice_2.len () < payload_length { + self.poisoned.set (true ); +return Err (EIO ); + } + +// Cut the message slices down to the actual length of the message. +let (slice_1, slice_2) =if slice_1.len () > payload_length { +// PANIC: we checked above that `slice_1` is at least as long as `payload_length`. + (slice_1.split_at (payload_length).0 , &slice_2[0 ..0 ]) + }else { + ( + slice_1, +// PANIC: we checked above that `slice_1.len() + slice_2.len()` is at least as +// large as `payload_length`. + slice_2.split_at (payload_length - slice_1.len ()).0 , + ) + }; + +Ok (GmcMessage { + header, + contents: (slice_1, slice_2), + }) + } }
drivers/gpu/nova-core/gsp/fw.rs +54 -0
71 lines not on this page · raw message
drivers/gpu/nova-core/mctp.rs +12 -2
@@ -67,6 +67,11 @@ pub(crate) fn single_packet() -> Self {pub (crate )fn is_single_packet (self) ->bool { self.som ().into_bool () && self.eom ().into_bool () } + +/// Returns whether the header carries the MCTP version this driver speaks. +pub (crate )fn has_expected_version (self) ->bool { + u32::from (self.version ()) ==Self ::VERSION + } }/// MCTP message type for PCI vendor-defined messages.
@@ -93,10 +98,15 @@ pub(crate) fn new(nvdm_type: NvdmType) -> Self { .with_nvdm_type(nvdm_type) } -/// Validates this header against the expected NVIDIA NVDM format and type. -pub (crate )fn validate (self, expected_type:NvdmType ) ->bool { +/// Returns whether this is an NVIDIA vendor-defined MCTP message, whatever its NVDM type. +pub (crate )fn has_nvidia_vendor (self) ->bool { u8::from (self.msg_type ()) ==MSG_TYPE_VENDOR_PCI && u16::from (self.vendor_id ()) ==Vendor ::NVIDIA .as_raw () + } + +/// Validates this header against the expected NVIDIA NVDM format and type. +pub (crate )fn validate (self, expected_type:NvdmType ) ->bool { + self.has_nvidia_vendor () &&matches! (self.nvdm_type (),Ok (nvdm_type)if nvdm_type == expected_type) } }
Signature · 1 line
2.55.0
PATCH v2 18/31 gpu: nova-core: gsp: add GMC dispatch on receive
In reply to John HubbardThe r000 boot path delivers the load-and-execute steps as GMC events keyed by command id, where the RPC path keys on a function code, so the boot loop needs its own dispatch.
Add a GMC receive that dispatches on the command id. A GMC element and an RPC element share every field through the NVDM header, so this checks the NVDM type before reading the GMC header and drops an element of the other kind rather than handing the handler a command id decoded from an RPC header. It also drops an element whose GMC payload size disagrees with the length the transport header declares, since GSP-RM sends the two as one length and nothing says which to believe. An element nobody claims yields Ok(None), and the read pointer advances on every path.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 79 ++++++++++++++++++++++++++++++- drivers/gpu/nova-core/gsp/fw.rs | 20 ++++++++ 2 files changed, 97 insertions(+), 2 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +77 -2
@@ -641,7 +641,6 @@ struct GspMessage<'a> {/// A GMC message ready to be processed from the message queue. /// /// This is the type returned by [`CmdqInner::wait_for_gmc_msg`]. -#[expect(dead_code)] struct GmcMessage <'a> {// Reference to the header of the message. header: &'aGspGmcMsgElement ,
@@ -791,6 +790,22 @@ fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M> self.inner.lock ().receive_msg (timeout,None ) } +/// Receives one GMC event from the GSP and passes its command id and raw payload slices to +/// `handler`. +/// +/// This method may sleep while waiting. The [`CmdqInner`] mutex stays locked across the wait +/// and across the `handler` call, so `handler` must not call back into this [`Cmdq`]. +/// +/// See [`CmdqInner::receive_gmc_and_dispatch`] for return values, queue state, and errors. +#[expect(dead_code)] +pub (crate )fn receive_gmc_and_dispatch <R >( + &self, + timeout:Delta , + handler:impl FnOnce (u32 , &[u8 ], &[u8 ]) ->Option <R >, + ) ->Result <Option <R >> { + self.inner.lock ().receive_gmc_and_dispatch (timeout, handler) + } +/// Waits for an unsolicited GSP event of type `M`, dispatching any other event that arrives /// first. ///
@@ -1314,7 +1329,6 @@ fn drain(&mut self) -> Result {/// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. /// - `EIO` if the framing is invalid, or the queue was already poisoned by an earlier such /// failure. Either failure poisons the queue, so recovery requires a reset. -#[expect(dead_code)] fn wait_for_gmc_msg (&self, timeout:Delta ) ->Result <GmcMessage <'_>> {if self.poisoned.get () {return Err (EIO );
@@ -1370,4 +1384,65 @@ fn wait_for_gmc_msg(&self, timeout: Delta) -> Result<GmcMessage<'_>> { contents: (slice_1, slice_2), }) } + +/// Receive the next GMC event from the GSP and dispatch it through a handler. +/// +/// The handler receives the GMC command id and the raw payload slices that follow the +/// [`super::fw::GmcApiHeader`] (two slices because the circular buffer may wrap). It returns +/// `None` for an event it does not handle. +/// +/// Where [`Self::receive_msg`] keys on [`MsgFunction`], this keys on the GMC command id, +/// which is the form the r000 firmware uses for boot events. +/// +/// Returns `Ok(None)` when nothing claimed the element, either because it is not a GMC +/// element or because the handler declined it. The read pointer is advanced on every path. +/// +/// # Errors +/// +/// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. +/// - `EIO` if the queue is poisoned or the element fails framing validation (see +/// [`Self::wait_for_gmc_msg`]). +fn receive_gmc_and_dispatch <R >( + &mut self, + timeout:Delta , + handler:impl FnOnce (u32 , &[u8 ], &[u8 ]) ->Option <R >, + ) ->Result <Option <R >> { +let message = self.wait_for_gmc_msg (timeout)?; +let header = message.header; +let length = header.length (); + +// The RPC and GMC elements share every field through `nvdm_header`, so `gmc` holds an +// RPC header rather than a GMC one unless the NVDM type says otherwise. +let result =if !header.is_gmc_api () { +dev_warn! (&self.dev,"GSP GMC: dropping non-GMC queue element\n" ); +None + }else if num::u32_as_usize (header.gmc.size) != header.payload_length () { +// GSP-RM sends the element as the GMC header plus `size` bytes, so the two lengths +// describe the same payload and a handler cannot tell which one to believe. +dev_err! ( + &self.dev, +"GSP GMC: payload is {} bytes, transport declares {}\n" , + header.gmc.size, + header.payload_length (), + ); +None + }else { +let command_id = header.gmc.command_id (); + +dev_dbg! ( + &self.dev, +"GSP GMC: event: seq# {}, command_id=0x{:x}, length=0x{:x}\n" , + header.gmc.sequence, + command_id, + length, + ); + +handler (command_id, message.contents.0 , message.contents.1 ) + }; + + self.gsp_mem + .advance_cpu_read_ptr (u32::try_from (length.div_ceil (GSP_PAGE_SIZE ))?); + +Ok (result) + } }
drivers/gpu/nova-core/gsp/fw.rs +20 -0
@@ -1008,6 +1008,10 @@ pub(crate) struct GmcApiHeader { reserved: [u32; 5], } +/// Command identifier bits of [`GmcApiHeader::command`], matching Open RM's +/// `GMCAPI_HEADER_COMMAND_ID_MASK`. The remaining byte carries flags. +const GMCAPI_COMMAND_ID_MASK :u32 =0x00ff_ffff ; +static_assert! (size_of ::<GmcApiHeader >() ==size_of ::<r000_00::GMCAPI_HEADER >());static_assert! ( core::mem::offset_of!(GmcApiHeader , command)
@@ -1030,6 +1034,13 @@ pub(crate) struct GmcApiHeader { == core::mem::offset_of!(r000_00::GMCAPI_HEADER, reserved) ); +impl GmcApiHeader { +/// Returns the command identifier, without the flag byte. +pub (crate )fn command_id (&self) ->u32 { + self.command &GMCAPI_COMMAND_ID_MASK + } +} +// SAFETY: All fields are integer types with no uninitialized padding bytes. unsafe impl AsBytes for GmcApiHeader {}
@@ -1134,6 +1145,15 @@ pub(crate) fn validate_framing(&self) -> Result { ) } +/// Returns `true` if the NVDM header routes this element to the GSP's GMC dispatch. +/// +/// A [`GspMsgElement`] and a [`GspGmcMsgElement`] share every field through `nvdm_header`, +/// so the NVDM type is what distinguishes the two on the queue, and `gmc` holds an RPC +/// header rather than a GMC one when this returns `false`. +pub (crate )fn is_gmc_api (&self) ->bool { + self.nvdm_header.validate (NvdmType ::GmcApi ) + } +/// Returns the number of elements (i.e. memory pages) used by this message. pub (crate )fn element_count (&self) ->u32 { self.mctp_payload_size
Signature · 1 line
2.55.0
PATCH v2 19/31 gpu: nova-core: separate the generic falcon bootloader from FWSEC
In reply to John HubbardThe r000 GSP boot protocol sends a load-and-execute event for the generic falcon bootloader.
Nova-core stored the image and its load parameters in the FWSEC firmware wrapper, which kept the r000 boot path from loading it independently.
Separate the bootloader image and load parameters from the FWSEC wrapper. Place the bootloader at the end of the target falcon's HWCFG-reported IMEM rather than below a fixed 64 KiB ceiling, so its placement remains within bounds on falcons with less IMEM.
--- drivers/gpu/nova-core/falcon.rs | 15 +++ drivers/gpu/nova-core/firmware.rs | 1 + .../nova-core/firmware/fwsec/bootloader.rs | 64 ++--------- .../gpu/nova-core/firmware/gen_bootloader.rs | 102 ++++++++++++++++++ drivers/gpu/nova-core/gsp/hal/tu102.rs | 6 +- drivers/gpu/nova-core/regs.rs | 5 + 6 files changed, 135 insertions(+), 58 deletions(-) create mode 100644 drivers/gpu/nova-core/firmware/gen_bootloader.rs
drivers/gpu/nova-core/falcon.rs +15 -0
@@ -387,6 +387,21 @@ pub(crate) fn new( }) } +/// Returns the size of this falcon's IMEM, in bytes. +/// +/// `NV_PFALCON_FALCON_IMEMC` addresses IMEM with a 16-bit byte offset, so the result never +/// exceeds 64KiB. +pub (crate )fn imem_size (&self) ->usize { +let blocks = usize::from_safe_cast ( + *self + .bar + .read (regs::NV_PFALCON_FALCON_HWCFG ::of ::<E >()) + .imem_size (), + ); + + blocks *MEM_BLOCK_ALIGNMENT + } +/// Resets DMA-related registers. pub (crate )fn dma_reset (&self) { self.bar.update (regs::NV_PFALCON_FBIF_CTL ::of ::<E >(), |v| {
drivers/gpu/nova-core/firmware.rs +1 -0
@@ -26,6 +26,7 @@pub (crate )mod booter;pub (crate )mod fsp;pub (crate )mod fwsec; +pub (crate )mod gen_bootloader;pub (crate )mod gsp;pub (crate )mod radix3;pub (crate )mod riscv;
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +8 -56
121 lines not on this page · raw message
drivers/gpu/nova-core/firmware/gen_bootloader.rs new file +102 -0
102 lines not on this page · raw message
drivers/gpu/nova-core/gsp/hal/tu102.rs +4 -2
@@ -166,7 +166,7 @@ fn run_fwsec_frts( )?;if self.needs_fwsec_bootloader { -let fwsec_frts_bl =FwsecFirmwareWithBl ::new (fwsec_frts, dev, chipset)?; +let fwsec_frts_bl =FwsecFirmwareWithBl ::new (fwsec_frts, dev, chipset, falcon)?;// Load and run the bootloader, which will load FWSEC-FRTS and run it. fwsec_frts_bl.run (dev, falcon, bar)?; }else {
@@ -224,7 +224,9 @@ fn build_unload_bundle(// Load the FWSEC SB firmware, as well as its bootloader if required. let fwsec_sb =FwsecFirmware ::new (dev, gsp_falcon, bios,FwsecCommand ::Sb )?;let fwsec_sb =if self.needs_fwsec_bootloader { -FwsecUnloadFirmware ::WithBl (FwsecFirmwareWithBl ::new (fwsec_sb, dev, chipset)?) +FwsecUnloadFirmware ::WithBl (FwsecFirmwareWithBl ::new ( + fwsec_sb, dev, chipset, gsp_falcon, + )?) }else {FwsecUnloadFirmware ::WithoutBl (fwsec_sb) };
drivers/gpu/nova-core/regs.rs +5 -0
@@ -247,6 +247,11 @@ pub(crate) fn usable_fb_size(self) -> u64 { 31:0 value => u32; } + pub(crate) NV_PFALCON_FALCON_HWCFG(u32) @ PFalconBase + 0x00000108 { +/// Size of this falcon's IMEM, in blocks of [`crate::falcon::MEM_BLOCK_ALIGNMENT`] bytes. + 8:0 imem_size; + } + pub(crate) NV_PFALCON_FALCON_DMACTL(u32) @ PFalconBase + 0x0000010c { 7:7 secure_stat => bool; 6:3 dmaq_num;
Signature · 1 line
2.55.0
PATCH v2 20/31 gpu: nova-core: handle the r000 load-and-execute HS binary event
In reply to John HubbardThe r000 GSP boot protocol asks the driver to run a high-security binary on the GSP falcon, and sends the framebuffer addresses of its code and data in the event payload.
Nova-core has no handler for that event. It also has no way to restart GSP-RM afterwards, which every load-and-execute event needs.
Add the handler. It DMAs the image into falcon memory, programs the BROM registers that make the falcon verify the PKC signature, runs the binary, and resumes GSP-RM. The aperture it loads through is context DMA slot 0, set to local framebuffer, physical addressing and the BAR2 function 0 engine ID. Write FLCN_ERR_BINARY_NOT_STARTED to MAILBOX0 before starting, which Open RM does so a binary that never runs is distinguishable from one that succeeded, and which also clears the suspend bit the next event polls.
--- drivers/gpu/nova-core/falcon.rs | 18 ++- drivers/gpu/nova-core/gsp/boot.rs | 229 +++++++++++++++++++++++++++++- drivers/gpu/nova-core/regs.rs | 2 + 3 files changed, 244 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/falcon.rs +15 -3
@@ -140,7 +140,6 @@ pub(crate) enum FalconMem { }/// Source offset of a raw falcon DMA transfer, added to the DMA base address. -#[expect(dead_code)] #[derive( Copy , Clone )] pub (crate )enum FalconDmaSrcOffset {/// Byte offset from the DMA base address.
@@ -178,6 +177,17 @@ pub(crate) enum FalconFbifMemType with From<Bounded<u32, 1>> { } } +bounded_enum! { +/// Engine ID a falcon DMA transfer is tagged with on its way through the FBIF. +#[derive( Debug , Copy , Clone )] +pub (crate )enum FalconFbifEngineIdFlag withFrom <Bounded <u32 ,1 >> { +/// Function 0's BAR2 engine ID. +Bar2Fn0 =0 , +/// The falcon's own engine ID. +Own =1 , + } +} +/// Type used to represent the `PFALCON` registers address base for a given falcon engine. pub (crate )struct PFalconBase (());
@@ -637,7 +647,6 @@ fn dma_wr(/// target. /// - `ERANGE` if `src_addr` does not fit the `DMATRFBASE` register pair. /// - `EOVERFLOW` if a per-block source or destination offset exceeds `u32`. -#[expect(dead_code)] pub (crate )fn raw_dma_transfer ( &self, ctx_dma: u8,
@@ -785,7 +794,10 @@ pub(crate) fn wait_till_halted(&self) -> Result<()> {/// /// The RISC-V GSP signals suspension by setting bit 31 (`0x8000_0000`) in `MAILBOX0`, rather /// than through `CPUCTL.halted`. -#[expect(dead_code)] +/// +/// Nothing else clears that bit, so the caller must write `MAILBOX0` before starting the +/// falcon CPU. A caller that runs this twice without an intervening write sees the first +/// suspension both times. pub (crate )fn wait_for_processor_suspend (&self) ->Result <()> {const INTERRUPT_PROCESSOR_SUSPENDED :u32 =0x8000_0000 ;
drivers/gpu/nova-core/gsp/boot.rs +227 -2
258 lines not on this page · raw message
drivers/gpu/nova-core/regs.rs +2 -0
@@ -19,6 +19,7 @@ FalconCoreRev, FalconCoreRevSubversion, FalconEngine, + FalconFbifEngineIdFlag, FalconFbifMemType, FalconFbifTarget, FalconMem,
@@ -353,6 +354,7 @@ pub(crate) fn usable_fb_size(self) -> u64 { } pub(crate) NV_PFALCON_FBIF_TRANSCFG(u32)[8] @ PFalconBase + 0x00000600 { + 16:16 engine_id_flag => FalconFbifEngineIdFlag; 2:2 mem_type => FalconFbifMemType; 1:0 target ?=> FalconFbifTarget; }
Signature · 1 line
2.55.0
PATCH v2 21/31 gpu: nova-core: handle the r000 load-and-execute bootloader event
In reply to John HubbardThe r000 GSP boot protocol asks the driver to run an image on the GSP falcon, and passes a bootloader descriptor naming where the image lives. Open RM does not copy the image itself. It runs the generic falcon bootloader, which reads that descriptor from DMEM and does the copy.
Nova-core has no handler for that event, and keeps its copy of the descriptor in the FWSEC module that first needed one.
Move the descriptor next to the bootloader that reads it, and add the handler. It points the requested FBIF aperture at the image, loads the descriptor and the bootloader, runs it, and restores the aperture once the image halts, since a falcon that has not halted may still be reading through it.
--- .../nova-core/firmware/fwsec/bootloader.rs | 52 +----- .../gpu/nova-core/firmware/gen_bootloader.rs | 115 ++++++++++++- drivers/gpu/nova-core/gsp/boot.rs | 161 +++++++++++++++++- 3 files changed, 278 insertions(+), 50 deletions(-)
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +4 -48
@@ -33,60 +33,16 @@ }, firmware::{ fwsec::FwsecFirmware, - gen_bootloader::GenericBootloader, // + gen_bootloader::{ +BootloaderDmemDescV2 , +GenericBootloader ,// + }, }, gpu::Chipset, num::FromSafeCast, // regs, }; -/// Structure used by the boot-loader to load the rest of the code. -/// -/// This has to be filled by the GPU driver and copied into DMEM at offset -/// [`BootloaderDesc.dmem_load_off`]. -#[repr( C , packed)] -#[derive( Debug , Clone )] -struct BootloaderDmemDescV2 { -/// Reserved, should always be first element. - reserved: [u32 ;4 ], -/// 16B signature for secure code, 0s if no secure code. - signature: [u32 ;4 ], -/// DMA context used by the bootloader while loading code/data. - ctx_dma:u32 , -/// 256B-aligned physical FB address where code is located. - code_dma_base:u64 , -/// Offset from `code_dma_base` where the non-secure code is located. -/// -/// Also used as destination IMEM offset of non-secure code as the DMA firmware object is -/// expected to be a mirror image of its loaded state. -/// -/// Must be multiple of 256. - non_sec_code_off:u32 , -/// Size of the non-secure code part. - non_sec_code_size:u32 , -/// Offset from `code_dma_base` where the secure code is located (must be multiple of 256). -/// -/// Also used as destination IMEM offset of secure code as the DMA firmware object is expected -/// to be a mirror image of its loaded state. -/// -/// Must be multiple of 256. - sec_code_off:u32 , -/// Size of the secure code part. - sec_code_size:u32 , -/// Code entry point invoked by the bootloader after code is loaded. - code_entry_point:u32 , -/// 256B-aligned physical FB address where data is located. - data_dma_base:u64 , -/// Size of data block (should be multiple of 256B). - data_size:u32 , -/// Number of arguments to be passed to the target firmware being loaded. - argc:u32 , -/// Arguments to be passed to the target firmware being loaded. - argv:u32 , -} -// SAFETY: This struct doesn't contain uninitialized bytes and doesn't have interior mutability. -unsafe impl AsBytes for BootloaderDmemDescV2 {} -/// Wrapper for [`FwsecFirmware`] that includes the bootloader performing the actual load /// operation. pub (crate )struct FwsecFirmwareWithBl {
drivers/gpu/nova-core/firmware/gen_bootloader.rs +114 -1
138 lines not on this page · raw message
drivers/gpu/nova-core/gsp/boot.rs +160 -1
179 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 22/31 gpu: nova-core: gsp: add the GMC boot event dispatcher
In reply to John HubbardThe r000 GSP boot protocol sends its two load-and-execute events as GMC commands, each identified by a command id.
Nova-core has a handler for each of the two events, but nothing that reads a command id and selects between them.
Add the dispatcher, keyed on the two command ids from the r000 bindings.
--- drivers/gpu/nova-core/gsp/boot.rs | 62 +++++++++++++++++++++++++++++-- drivers/gpu/nova-core/gsp/fw.rs | 10 +++++ 2 files changed, 69 insertions(+), 3 deletions(-)
drivers/gpu/nova-core/gsp/boot.rs +59 -3
@@ -37,7 +37,11 @@ }, gsp::{ cmdq::Cmdq, - commands, // + commands, + fw::{ +GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER , +GMCAPI_CMD_EXEC_HS_BINARY ,// + }, // }, regs, // };
@@ -163,6 +167,60 @@ fn core_resume(Ok (()) } +/// Dispatch one GMC boot event to its load-and-execute handler. +/// +/// LIBOS2 chipsets send `GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER` and LIBOS3 chipsets send +/// `GMCAPI_CMD_EXEC_HS_BINARY`, so a given GPU only ever reaches one of the two handlers. +/// +/// # Errors +/// +/// - `EINVAL` if `command_id` is not a load-and-execute command. +/// +/// Errors from the handlers are propagated as-is. +#[expect(dead_code)] +#[expect(clippy::too_many_arguments)] +fn dispatch_gmc_boot_event ( + command_id:u32 , + payload: &[u8 ], + bootloader: &GenericBootloader , + gsp_falcon: &Falcon <'_,Gsp >, + sec2_falcon: &Falcon <'_,Sec2 >, + bar:Bar0 <'_>, + dev: &device::Device , + bootloader_app_version:u32 , + libos_dma_handle:u64 , + ) ->Result { +match command_id { +GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER =>Self ::handle_load_exec_bootloader ( + payload, + bootloader, + gsp_falcon, + sec2_falcon, + bar, + dev, + bootloader_app_version, + libos_dma_handle, + ), +GMCAPI_CMD_EXEC_HS_BINARY =>Self ::handle_load_exec_hs_binary ( + payload, + gsp_falcon, + sec2_falcon, + bar, + dev, + bootloader_app_version, + libos_dma_handle, + ), + _ => { +dev_err! ( + dev, +"Unexpected GMC boot event: command_id={:#010x}\n" , + command_id + ); +Err (EINVAL ) + } + } + } +/// Handle a `GSP_LOAD_EXEC_GENERIC_BOOTLOADER` event. /// /// The driver does not copy the image the GSP asks for. It writes the descriptor the event
@@ -177,7 +235,6 @@ fn core_resume(/// size this driver mirrors, or the event names a context DMA slot or an aperture that does /// not exist. /// - `ETIMEDOUT` if the GSP does not suspend, or the image does not halt, in time. -#[expect(dead_code)] #[expect(clippy::too_many_arguments)] fn handle_load_exec_bootloader ( payload: &[u8],
@@ -269,7 +326,6 @@ fn handle_load_exec_bootloader(/// - `EINVAL` if the payload is shorter than the parameter block, or the ucode id does not /// fit the BROM register field. /// - `ETIMEDOUT` if the GSP does not suspend, or the binary does not halt, in time. -#[expect(dead_code)] fn handle_load_exec_hs_binary ( payload: &[u8 ], gsp_falcon: &Falcon<'_, Gsp>,
drivers/gpu/nova-core/gsp/fw.rs +10 -0
@@ -1012,6 +1012,16 @@ pub(crate) struct GmcApiHeader {/// `GMCAPI_HEADER_COMMAND_ID_MASK`. The remaining byte carries flags. const GMCAPI_COMMAND_ID_MASK :u32 =0x00ff_ffff ; +/// GMC command asking the driver to run the generic falcon bootloader against a descriptor the +/// GSP supplies. +pub (crate )const GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER :u32 = + r000_00::GMCAPI_COMMANDS_GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER ; + +/// GMC command asking the driver to run a high-security binary the GSP has placed in the +/// framebuffer. +pub (crate )const GMCAPI_CMD_EXEC_HS_BINARY :u32 = + r000_00::GMCAPI_COMMANDS_GMCAPI_CMD_EXEC_HS_BINARY ; +static_assert! (size_of ::<GmcApiHeader >() ==size_of ::<r000_00::GMCAPI_HEADER >());static_assert! ( core::mem::offset_of!(GmcApiHeader , command)
Signature · 1 line
2.55.0
PATCH v2 23/31 gpu: nova-core: gsp: add the GSP_INIT request builder
In reply to John HubbardThe r000 GSP boot protocol replaces the separate system-info, registry and static-info commands with one GSP_INIT request, whose payload is an NVKV key-value blob rather than a packed struct.
Nova-core has the NVKV codec and the GSP_INIT schema, but nothing that fills the schema in from a PCI device.
Add the builder. It encodes the PCI identifiers and config mirror range the RPC path already sends, and the registry entries, whose names carry the NULL that GSP-RM counts in the encoded length. The PCI location goes out as domain, bus and device in bits 63:32, 15:8 and 7:0, which is what GSP-RM decodes, rather than the bus, device and function that PCI_DEVID packs.
--- drivers/gpu/nova-core/gsp/commands.rs | 52 +++++++++++++++ drivers/gpu/nova-core/gsp/fw/commands.rs | 84 +++++++++++++++++++++++- 2 files changed, 134 insertions(+), 2 deletions(-)
drivers/gpu/nova-core/gsp/commands.rs +52 -0
@@ -30,8 +30,16 @@ }, fw::{ self, + commands::{ + GspInitRequest, + RegKey, // + }, MsgFunction, // }, + nvkv::{ +Encodeable , +Encoder ,// + }, }, sbuffer::SBufferIter, vgpu::VgpuState, //
@@ -259,6 +267,50 @@ pub(crate) fn gpu_name(&self) -> core::result::Result<&str, GpuNameError> { } } +/// Registry entries the driver sends to GSP-RM on every boot, each with the NULL terminator that +/// Open RM counts in the encoded name length. +/// +/// `RMSecBusResetEnable` enables PCI secondary bus reset. `RMForcePcieConfigSave` makes GSP-RM +/// preserve PCI configuration registers across any PCI reset. `RMDevidCheckIgnore` lets GSP-RM +/// boot when the PCI device id is absent from its product name database. +/// +/// [`SetRegistry::new`] carries the same entries for the RPC path, where the names have no +/// terminator because that encoding appends one. +const REGISTRY_ENTRIES : &[(&[u8 ],u32 )] = &[ + (b"RMSecBusResetEnable\0" ,1 ), + (b"RMForcePcieConfigSave\0" ,1 ), + (b"RMDevidCheckIgnore\0" ,1 ), +]; + +/// Builds the NVKV-encoded payload of a `GSP_INIT` request. +/// +/// The payload carries the system information GSP-RM reads before it starts, and +/// [`REGISTRY_ENTRIES`] as `REGKEY_NAME` and `REGKEY_VALUE_U32` pairs. GSP-RM requires each name +/// to be followed by its value, which is the order [`RegKey`] declares them in. +/// +/// # Errors +/// +/// - `ENOMEM` if the registry list or the encoder buffer cannot be allocated. +#[expect(dead_code)] +pub (crate )fn build_gsp_init_payload ( + pdev: &pci::Device <device::Bound >, + chipset:Chipset , + vgpu_state:VgpuState , +) ->Result <KVVec <u64 >> { +let mut regkeys =KVVec ::new (); +for &(name, value)in REGISTRY_ENTRIES { + regkeys.push (RegKey ::new (name, value),GFP_KERNEL )?; + } +if matches! (vgpu_state,VgpuState ::Enabled { .. }) { + regkeys.push (RegKey ::new (b"RMSetSriovMode\0" ,1 ),GFP_KERNEL )?; + } + +let mut encoder =Encoder ::new (); +GspInitRequest ::new (pdev, chipset, regkeys).encode (&mut encoder)?; + +Ok (encoder.finish ()) +} +pub (crate )use fw::commands::PowerStateLevel ;/// The `UnloadingGuestDriver` command, used to shut down the GSP.
drivers/gpu/nova-core/gsp/fw/commands.rs +82 -2
120 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 24/31 gpu: nova-core: gsp: send GSP_INIT and decode its reply
In reply to John HubbardGSP-RM answers a GSP_INIT request with the static GPU configuration, and that reply is also what signals it has finished starting. It raises load-and-execute events in the meantime, so a caller must handle them rather than wait through them.
Nova-core can build the request but cannot send it: the GMC sender is private, and the receive path drops the field carrying the reply status.
Add the sender and the receive-side status field it needs, and decode the reply into the static-info type the RPC path already produces.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 49 ++++++-- drivers/gpu/nova-core/gsp/commands.rs | 140 ++++++++++++++++++++++- drivers/gpu/nova-core/gsp/fw.rs | 4 + drivers/gpu/nova-core/gsp/fw/commands.rs | 35 +++++- 4 files changed, 213 insertions(+), 15 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +39 -10
@@ -790,22 +790,43 @@ fn receive_msg<M: MessageFromGsp>(&self, timeout: Delta) -> Result<M> self.inner.lock ().receive_msg (timeout,None ) } -/// Receives one GMC event from the GSP and passes its command id and raw payload slices to -/// `handler`. +/// Receives one GMC element from the GSP and passes its command id, the `max_resp_or_status` +/// field, and the raw payload slices to `handler`. /// /// This method may sleep while waiting. The [`CmdqInner`] mutex stays locked across the wait /// and across the `handler` call, so `handler` must not call back into this [`Cmdq`]. /// /// See [`CmdqInner::receive_gmc_and_dispatch`] for return values, queue state, and errors. -#[expect(dead_code)] pub (crate )fn receive_gmc_and_dispatch <R >( &self, timeout:Delta , - handler:impl FnOnce (u32 , &[u8 ], &[u8 ]) ->Option <R >, + handler:impl FnOnce (u32 ,u32 , &[u8 ], &[u8 ]) ->Option <R >, ) ->Result <Option <R >> { self.inner.lock ().receive_gmc_and_dispatch (timeout, handler) } +/// Sends a GMC API command to the GSP without waiting for its response. +/// +/// A caller that expects a response reads it with [`Self::receive_gmc_and_dispatch`], which +/// lets it handle the events GSP-RM interleaves before the response arrives. +/// +/// # Errors +/// +/// - `EMSGSIZE` if the command exceeds the maximum queue element size. +/// - `ETIMEDOUT` if space does not become available within the timeout. +/// - `EIO` if the command header is not properly aligned. +pub (crate )fn send_gmc_no_wait ( + &self, + bar:Bar0 <'_>, + command_id:u32 , + payload: &[u8 ], + max_response_size:u32 , + ) ->Result { + self.inner + .lock () + .send_gmc (bar, command_id, payload, max_response_size) + } +/// Waits for an unsolicited GSP event of type `M`, dispatching any other event that arrives /// first. ///
@@ -1005,7 +1026,6 @@ fn send_command<M>(&mut self, bar: Bar0<'_>, command: M) -> Result<u32>/// - `EMSGSIZE` if the command exceeds the maximum queue element size. /// - `ETIMEDOUT` if space does not become available within the timeout. /// - `EIO` if the command header is not properly aligned. -#[expect(dead_code)] fn send_gmc ( &mut self, bar: Bar0<'_>,
@@ -1387,9 +1407,13 @@ fn wait_for_gmc_msg(&self, timeout: Delta) -> Result<GmcMessage<'_>> {/// Receive the next GMC event from the GSP and dispatch it through a handler. /// -/// The handler receives the GMC command id and the raw payload slices that follow the -/// [`super::fw::GmcApiHeader`] (two slices because the circular buffer may wrap). It returns -/// `None` for an event it does not handle. +/// The handler receives the GMC command id, the header's `max_resp_or_status` field, and the +/// raw payload slices that follow the [`super::fw::GmcApiHeader`] (two slices because the +/// circular buffer may wrap). It returns `None` for an element it does not handle. +/// +/// `max_resp_or_status` is a union: GSP-RM writes an `NV_STATUS` there when the element is a +/// response, and the maximum response size when it is a request. Only a handler that knows +/// which one it asked for can read it. /// /// Where [`Self::receive_msg`] keys on [`MsgFunction`], this keys on the GMC command id, /// which is the form the r000 firmware uses for boot events.
@@ -1405,7 +1429,7 @@ fn wait_for_gmc_msg(&self, timeout: Delta) -> Result<GmcMessage<'_>> {fn receive_gmc_and_dispatch <R >( &mut self, timeout:Delta , - handler:impl FnOnce (u32 , &[u8 ], &[u8 ]) ->Option <R >, + handler:impl FnOnce (u32 ,u32 , &[u8 ], &[u8 ]) ->Option <R >, ) ->Result <Option <R >> {let message = self.wait_for_gmc_msg (timeout)?;let header = message.header;
@@ -1437,7 +1461,12 @@ fn receive_gmc_and_dispatch<R>( length, ); -handler (command_id, message.contents.0 , message.contents.1 ) +handler ( + command_id, + header.gmc.max_resp_or_status, + message.contents.0 , + message.contents.1 , + ) }; self.gsp_mem
drivers/gpu/nova-core/gsp/commands.rs +138 -2
163 lines not on this page · raw message
drivers/gpu/nova-core/gsp/fw.rs +4 -0
@@ -1012,6 +1012,10 @@ pub(crate) struct GmcApiHeader {/// `GMCAPI_HEADER_COMMAND_ID_MASK`. The remaining byte carries flags. const GMCAPI_COMMAND_ID_MASK :u32 =0x00ff_ffff ; +/// GMC command that hands GSP-RM its system information and registry keys and returns the static +/// GPU configuration. Its reply is also what signals that GSP-RM has finished starting. +pub (crate )const GMCAPI_CMD_GSP_INIT :u32 = r000_00::GMCAPI_COMMANDS_GMCAPI_CMD_GSP_INIT ; +/// GMC command asking the driver to run the generic falcon bootloader against a descriptor the /// GSP supplies. pub(crate) const GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER: u32 =
drivers/gpu/nova-core/gsp/fw/commands.rs +32 -3
@@ -428,7 +428,7 @@ pub(crate) fn new(/// Schema for the `GSP_INIT` response. #[cfg_attr(not( CONFIG_KUNIT ), allow(dead_code))] #[derive( Default )] - struct GspInitResponseSchema => GspInitResponse { + pub(crate) struct GspInitResponseSchema => GspInitResponse { gpu_name:Array <u8 , {GspInitResponse ::MAX_GPU_NAME_LEN }, {Self ::GPU_NAME_STRING_KEY }>, fb_regions:Accumulated <FbRegionSchema >,
@@ -446,7 +446,7 @@ impl GspInitResponseSchema {/// Payload of the `GSP_INIT` response. #[cfg_attr(not( CONFIG_KUNIT ), allow(dead_code))] -struct GspInitResponse { +pub (crate )struct GspInitResponse { gpu_name:ArrayVec <u8 , {Self ::MAX_GPU_NAME_LEN }>, fb_regions:KVVec <FbRegion >, bar1_pde_base:u64 ,
@@ -454,7 +454,36 @@ struct GspInitResponse { }impl GspInitResponse { -const MAX_GPU_NAME_LEN :usize =64 ; +pub (crate )const MAX_GPU_NAME_LEN :usize =64 ; + +/// A region with no tag is general-purpose memory. A tagged region is reserved for a +/// firmware-internal use that the tag identifies. +const FB_REGION_TAG_NONE :u32 =0 ; + +/// Returns the GPU name, which GSP-RM sends with its NULL terminator. +pub (crate )fn gpu_name (&self) -> &[u8 ] { + self.gpu_name.as_slice () + } + +/// Iterates over the FB regions the driver may allocate from. +/// +/// A region qualifies when it is untagged, unprotected, and supports both compression and +/// isochronous access, which is the same set the RPC path selects from +/// [`GspStaticConfigInfo::usable_fb_regions`]. +pub (crate )fn usable_fb_regions (&self) ->impl Iterator <Item =Range <u64 >> + '_ { + self.fb_regions.iter ().filter_map (|region| { +if region.limit >= region.base + && region.tag ==Self ::FB_REGION_TAG_NONE + && !region.flags.protected () + && region.flags.support_compressed () + && region.flags.support_iso () + { + region.limit.checked_add (1 ).map (|end| region.base..end) + }else { +None + } + }) + } }nvkv_decode! {
Signature · 1 line
2.55.0
PATCH v2 25/31 gpu: nova-core: gsp: pass the remaining log buffers to GSP-RM
In reply to John HubbardThe libos loader finds each log buffer by looking up its eight-byte name in the init argument array, so a buffer the array does not name is never written to.
Nova-core allocates six log buffers and gives all six a debugfs file, but names only three, so the other three can never read back anything but zeros.
Name all six. RMARGS moves to the end of the array, which does not matter to a loader that searches by name.
--- drivers/gpu/nova-core/gsp.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/gpu/nova-core/gsp.rs +13 -1
@@ -346,7 +346,19 @@ pub(crate) fn new( 2, LibosMemoryRegionInitArgument::new("LOGRM", &logrm.buffer), )?; - libos.init_at (3 ,LibosMemoryRegionInitArgument ::new ("RMARGS" , rmargs))?; + libos.init_at ( +3 , +LibosMemoryRegionInitArgument ::new ("LOGMNOC" , &logmnoc.buffer), + )?; + libos.init_at ( +4 , +LibosMemoryRegionInitArgument ::new ("LOGROOT" , &logroot.buffer), + )?; + libos.init_at ( +5 , +LibosMemoryRegionInitArgument ::new ("LOGRMON" , &logrmon.buffer), + )?; + libos.init_at (6 ,LibosMemoryRegionInitArgument ::new ("RMARGS" , rmargs))?; libos.into () },
Signature · 1 line
2.55.0
PATCH v2 26/31 gpu: nova-core: switch to the r000 GSP firmware
In reply to John HubbardThe r000 firmware changes four things about how it talks to the driver. Queue elements carry MCTP and NVDM headers and no checksum. Msgq version 2 keeps all four ring pointers in BAR0, and its head-register write doubles as the doorbell. Load-and-execute steps arrive as GMC commands rather than as RPC events. And a single GSP_INIT request replaces the system-info, registry and static-info commands, with its reply standing in for the init-done event.
None of the four can change on its own, because only one firmware version is present at a time, so a commit that changed only some of them would not boot at all.
Switch all four together. The startup arguments gain the ucodes image and the state-monitor buffer, and the FMC boot parameters gain the magic and size header that r000 expects. A missing ucodes image is now fatal, which is what Open RM requires everywhere except GB10Y. Only Turing and GA100 raise the generic-bootloader event, so the bootloader image is requested only on those chipsets.
Each load-and-execute event ends in a GSP falcon reset, which zeroes all four msgq counters. GSP-RM writes back the two counters it owns and carries on counting from where it stopped. Write the driver's two counters back the same way, counting the element just handled as consumed.
Name the r000 module in the bindings alias, so that every constant comes from the r000 headers rather than the r570 ones. The r570 headers size the GSP heap at 14 MiB of RM boot working memory on Hopper and later, and the r000 headers size it at 18 MiB.
Msgq version 2 holds the read pointer in BAR0, so the r000 headers define no RX header. Remove the driver's copy and the space it occupied. No offset changes, because the message data is page-aligned and already sits at 4096.
The r000 firmware also sizes two framebuffer carveouts differently, and the driver reserves them. Its PMU region above FRTS covers the backing store, the communication surfaces and the misc memory, which come to 25 MiB + 384 KiB, and GB20x asks for a flat 3 MiB of non-WPR heap. Both are larger than the r570 amounts, so carrying those forward under-reserves memory the firmware expects to own.
The boot events and the GSP_INIT reply replace the CPU sequencer and the wait for init-done, so neither has a caller left. Remove both, and the run-CPU-sequencer entry in the message-function table with them, so that code arriving on the queue is reported as unknown rather than decoded into types nothing acts on.
--- drivers/gpu/nova-core/driver.rs | 2 +- drivers/gpu/nova-core/fb/hal/gb100.rs | 25 +- drivers/gpu/nova-core/fb/hal/gb202.rs | 5 +- drivers/gpu/nova-core/firmware/bindata.rs | 1 - drivers/gpu/nova-core/gpu.rs | 21 +- drivers/gpu/nova-core/gsp.rs | 34 +- drivers/gpu/nova-core/gsp/boot.rs | 137 +++-- drivers/gpu/nova-core/gsp/cmdq.rs | 367 +++++--------- drivers/gpu/nova-core/gsp/commands.rs | 68 +-- drivers/gpu/nova-core/gsp/fw.rs | 576 ++++++---------------- drivers/gpu/nova-core/gsp/hal.rs | 22 +- drivers/gpu/nova-core/gsp/hal/tu102.rs | 12 - drivers/gpu/nova-core/gsp/sequencer.rs | 379 -------------- drivers/gpu/nova-core/irq/gsp.rs | 2 +- drivers/gpu/nova-core/mctp.rs | 2 + 15 files changed, 462 insertions(+), 1191 deletions(-) delete mode 100644 drivers/gpu/nova-core/gsp/sequencer.rs
drivers/gpu/nova-core/driver.rs +1 -1
@@ -135,7 +135,7 @@ fn probe<'bound>(// SAFETY: as for the `bar` borrow above. let bar =unsafe { &*core::ptr::from_ref (bar) };crate ::irq::gsp::enable (bar, gpu.chipset (), vectors_ref.irq_type ()); - gpu.cmdq ().drain ()?; + gpu.cmdq ().drain (bar)?; }, _reg: auxiliary::Registration::new( pdev.as_ref(),
drivers/gpu/nova-core/fb/hal/gb100.rs +21 -4
@@ -80,10 +80,27 @@ fn write_sysmem_flush_page_gb100(bar: Bar0<'_>, addr: Bounded<u64, 52>) { ); } -// This PMU reservation size is r570-specific. +/// PMU backing store (see Open RM: `kpmuReservedMemoryBackingStoreSizeGet`). +const PMU_BACKING_STORE_SIZE :usize =9 *SZ_1M ; + +/// PMU communication surfaces (see Open RM: `gpuGetPmuReservedMemorySurfacesSize`). +const PMU_SURFACES_SIZE :usize =SZ_16M +SZ_256K ; + +/// Miscellaneous PMU memory (see Open RM: `kpmuReservedMemoryMiscSizeGet`). +const PMU_MISC_SIZE :usize =SZ_4K ; + +// Open RM reserves the backing store, the surfaces and the misc memory as one region above +// FRTS, aligned to KPMU_RESERVED_MEMORY_ALIGNMENT (see kpmuReservedMemorySizeGet). pub (super )const fn pmu_reserved_size_gb100 () ->u32 { -usize_into_u32 ::<{const_align_up (SZ_8M +SZ_16M +SZ_4K ,Alignment ::new ::<SZ_128K >()).unwrap () }>( - ) +usize_into_u32 ::< + { +const_align_up ( +PMU_BACKING_STORE_SIZE +PMU_SURFACES_SIZE +PMU_MISC_SIZE , +Alignment ::new ::<SZ_128K >(), + ) + .unwrap () + }, + >() }impl FbHal for Gb100 {
@@ -112,7 +129,7 @@ fn pmu_reserved_size(&self) -> u32 { }fn non_wpr_heap_size (&self) ->u64 { -// Non-WPR heap for GB10x (see Open RM: kgspGetNonWprHeapSize, GB100/GB102). +// Open RM's kgspGetNonWprHeapSize returns a flat 2 MiB for GB10x. u64::SZ_2M }
drivers/gpu/nova-core/fb/hal/gb202.rs +2 -3
@@ -72,9 +72,8 @@ fn pmu_reserved_size(&self) -> u32 { }fn non_wpr_heap_size (&self) ->u64 { -// Non-WPR heap for GB20x (see Open RM: kgspGetNonWprHeapSize, GB202+). -// This size is r570-specific. - u64::SZ_2M + u64::SZ_128K +// Open RM's kgspGetNonWprHeapSize returns a flat 3 MiB for GB20x. +3 * u64::SZ_1M }fn frts_size (&self) ->u64 {
drivers/gpu/nova-core/firmware/bindata.rs +0 -1
@@ -21,7 +21,6 @@/// A missing metadata file is reported as [`None`] so that the eventual caller can decide whether /// ucodes are optional for its boot path. Once the metadata has been found, all parse and payload /// loading errors, including a missing referenced file, are returned as errors. -#[expect(dead_code)] pub (crate )fn request_ucodes_firmware ( dev: &device::Device , chipset: Chipset,
drivers/gpu/nova-core/gpu.rs +8 -13
@@ -27,7 +27,6 @@ gsp::{ self, cmdq::Cmdq, - commands::GetGspStaticInfoReply,Gsp ,GspBootContext ,// },
@@ -276,16 +275,14 @@ struct GspResources<'gpu> {/// GSP runtime data. #[pin] gsp: Gsp, -/// GSP unload firmware bundle, if any. - unload_bundle: Option<gsp::UnloadBundle>, +/// What the GSP boot sequence produced, including the unload bundle. + boot_result: gsp::BootResult, }/// Structure holding the resources required to operate the GPU. #[pin_data] pub (crate )struct Gpu <'gpu> { spec:Spec , -/// Static GPU information as provided by the GSP. - gsp_static_info:GetGspStaticInfoReply ,/// GSP and its resources. #[pin] gsp_resources:GspResources <'gpu>,
@@ -303,7 +300,7 @@ fn drop(self: Pin<&mut Self>) {let this = self.project ();let device = *this.device;let bar = *this.bar; -let bundle = this.unload_bundle.take (); +let bundle = this.boot_result.take_unload_bundle ();let _ = this .gsp
@@ -398,10 +395,10 @@ pub(crate) fn new( gsp <- Gsp::new(pdev, spec.chipset), -// This member must be initialized last, so the `UnloadBundle` can never be dropped +// This member must be initialized last, so the unload bundle can never be dropped // from outside of the constructed `GspResources`, ensuring that the unload sequence // is properly run in case of failure. - unload_bundle: gsp.boot(GspBootContext { + boot_result: gsp.boot(GspBootContext { pdev, bar, chipset: spec.chipset,
@@ -412,9 +409,9 @@ pub(crate) fn new( })?, }), - gsp_static_info: { - // Obtain and display basic GPU information. - let info = gsp_resources.gsp.get_static_info(bar)?; + _: { +// The `GSP_INIT` reply already carried this. +let info = &gsp_resources.boot_result.static_info;match info.gpu_name () {Ok (name) =>dev_info! (dev,"GPU name: {}\n" , name),Err (e) =>dev_warn! (dev,"GPU name unavailable: {:?}\n" , e),
@@ -434,8 +431,6 @@ pub(crate) fn new( / u64::SZ_1M ); } - - info } }) }
drivers/gpu/nova-core/gsp.rs +32 -2
@@ -30,7 +30,6 @@#[cfg_attr(not( CONFIG_KUNIT ), allow(dead_code))] mod nvkv;mod regs; -mod sequencer;pub (crate )use fw::{GspFmcBootParams ,
@@ -325,8 +324,12 @@ pub(crate) fn new( Ok(try_pin_init!(Self { gsp_tlv, cmdq: Arc::pin_init(Cmdq::new(dev), GFP_KERNEL)?, - rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(cmdq.as_ref()))?, rm_state_monitor: Coherent::zeroed(dev, GFP_KERNEL)?, + rmargs: Coherent::init( + dev, + GFP_KERNEL, + GspArgumentsPadded::new(cmdq.as_ref(), None, rm_state_monitor), + )?, libos: { let mut libos = CoherentBox::zeroed_slice( dev,
@@ -396,6 +399,9 @@ pub(crate) fn new( }/// Query the GSP for the static GPU information. +/// +/// The r000 boot path gets the same information from the `GSP_INIT` reply instead. +#[expect(dead_code)] pub (crate )fn get_static_info (&self, bar:Bar0 <'_>) ->Result <commands::GetGspStaticInfoReply > { self.cmdq.send_command (bar, commands::GetGspStaticInfo ) }
@@ -408,3 +414,27 @@ pub(crate) fn cmdq(&self) -> Arc<Cmdq> {/// Opaque bundle required to unload the GSP. Created by [`Gsp::boot`], consumed by [`Gsp::unload`]. pub (crate )struct UnloadBundle (KBox <dyn hal::UnloadBundle >); + +/// What a successful [`Gsp::boot`] leaves the caller. +pub (crate )struct BootResult { + unload_bundle:Option <UnloadBundle >, +/// Static GPU configuration, as reported in the `GSP_INIT` reply. +pub (crate ) static_info: commands::GetGspStaticInfoReply , +} + +impl BootResult { +pub (super )fn new ( + unload_bundle:Option <UnloadBundle >, + static_info: commands::GetGspStaticInfoReply , + ) ->Self { +Self { + unload_bundle, + static_info, + } + } + +/// Takes the unload bundle out, leaving none behind, for the teardown path. +pub (crate )fn take_unload_bundle (&mut self) ->Option <UnloadBundle > { + self.unload_bundle.take () + } +}
drivers/gpu/nova-core/gsp/boot.rs +106 -31
241 lines not on this page · raw message
drivers/gpu/nova-core/gsp/cmdq.rs +110 -257
650 lines not on this page · raw message
drivers/gpu/nova-core/gsp/commands.rs +26 -42
141 lines not on this page · raw message
drivers/gpu/nova-core/gsp/fw.rs +144 -432
809 lines not on this page · raw message
drivers/gpu/nova-core/gsp/hal.rs +9 -13
@@ -41,19 +41,6 @@ fn boot( ctx: &mut GspBootContext<'_, '_>, gsp_fw: &GspFirmware, ) -> Result<Option<crate::gsp::UnloadBundle>>; - -/// Performs HAL-specific post-GSP boot tasks. -/// -/// This method is called by the GSP boot code after the GSP is confirmed to be running, and -/// after the initialization commands have been pushed onto its queue. -fn post_boot ( - &self, - _gsp: &Gsp , - _ctx: &mut GspBootContext <'_, '_>, - _gsp_fw: &GspFirmware , - ) ->Result { -Ok (()) - } }/// Returns the names of the firmware files required to boot the GSP of `chipset`, in addition to
@@ -75,6 +62,15 @@ pub(crate) const fn boot_firmware_files(chipset: Chipset) -> &'static [&'static } } +/// Returns `true` if GSP-RM on `chipset` loads its images through the generic falcon bootloader. +/// +/// Turing and GA100 raise `GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER` during boot and need the +/// `gen_bootloader.tlv` image to service it. GA102 and later raise `GMCAPI_CMD_EXEC_HS_BINARY` +/// instead, and [`boot_firmware_files`] ships them no such image. +pub (super )const fn uses_generic_bootloader (chipset:Chipset ) ->bool { +matches! (chipset.arch (),Architecture ::Turing ) ||matches! (chipset,Chipset ::GA100 ) +} +/// Returns the GSP HAL to be used for `chipset`. pub (super )fn gsp_hal (chipset:Chipset ) -> &'staticdyn GspHal {match chipset.arch () {
drivers/gpu/nova-core/gsp/hal/tu102.rs +0 -12
@@ -40,7 +40,6 @@ UnloadBundle, // }, regs, - sequencer::GspSequencer, Gsp, GspBootContext, GspFwWprMeta, //
@@ -316,17 +315,6 @@ fn boot(Ok (unload_guard.dismiss ()) } - -fn post_boot ( - &self, - gsp: &Gsp , - ctx: &mut GspBootContext <'_, '_>, - gsp_fw: &GspFirmware , - ) ->Result { -GspSequencer ::run (&gsp.cmdq, ctx, &gsp.libos, gsp_fw.bootloader.app_version)?; - -Ok (()) - } }/// The TU102 HAL requires the use of the FWSEC bootloader.
drivers/gpu/nova-core/gsp/sequencer.rs deleted +0 -379
379 lines not on this page · raw message
drivers/gpu/nova-core/irq/gsp.rs +1 -1
@@ -178,7 +178,7 @@ fn handle(&self) -> irq::ThreadedIrqReturn {/// IRQ thread: drains and dispatches the GSP-to-CPU message queue. fn handle_threaded (&self) -> irq::IrqReturn { -if let Err (e) = self.cmdq.drain () { +if let Err (e) = self.cmdq.drain (self.bar) {// A queue that fails to drain cannot advance past the message that failed, so every // later notification would repeat this failure. Disable the source instead. self.tree
drivers/gpu/nova-core/mctp.rs +2 -0
@@ -28,6 +28,8 @@ pub(crate) enum NvdmType with TryFrom<Bounded<u32, 8>> { Cot = 0x14,/// FSP command response. FspResponse = 0x15, +/// GSP-RM RPC message. + RmRpc = 0x25,/// GMC API message (GSP command queue). GmcApi = 0x26, }
Signature · 1 line
2.55.0
PATCH v2 27/31 gpu: nova-core: gsp: validate RPC element framing on receive
In reply to John HubbardThe r000 firmware gives RPC and GMC queue elements the same MCTP and NVDM transport headers, and the driver advances the read pointer by the element length those headers declare.
The RPC receive path checked only the MCTP magic, and only after it had already sliced the payload using a length from the same unchecked header. Nothing bounded the element length that advances the read pointer, so a corrupt one moved the pointer to an arbitrary slot.
Run the RPC path through the same framing validation the GMC path uses, before any length field is read.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 22 ++++++++++++---------- drivers/gpu/nova-core/gsp/fw.rs | 17 ++++++++++++++--- 2 files changed, 26 insertions(+), 13 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +12 -10
@@ -946,6 +946,18 @@ fn wait_for_msg(&self, bar: Bar0<'_>, timeout: Delta) -> Result<GspMessage<'_>>return Err (EIO ); }; +// Checked before any length field is read, since bad framing leaves them untrusted. +if let Err (e) = header.validate_framing () { +dev_err! ( + &self.dev, +"GSP RPC: receive: Call {} - bad MCTP framing, declared length {}\n" , + header.sequence (), + header.length (), + ); + self.poisoned.set (true ); +return Err (e); + } +let payload_length = header.payload_length ();// Check that the driver read area is large enough for the message.
@@ -967,16 +979,6 @@ fn wait_for_msg(&self, bar: Bar0<'_>, timeout: Delta) -> Result<GspMessage<'_>> ) }; -if !header.has_valid_magic () { -dev_err! ( - &self.dev, -"GSP RPC: receive: Call {} - bad MCTP magic\n" , - header.sequence () - ); - self.poisoned.set (true ); -return Err (EIO ); - } -Ok (GspMessage { header, contents: (slice_1, slice_2),
drivers/gpu/nova-core/gsp/fw.rs +14 -3
@@ -574,9 +574,20 @@ pub(crate) fn length(&self) -> usize { num::u32_as_usize (self.mctp_payload_size) } -/// Returns `true` if the MCTP magic field contains the expected value. -pub (crate )fn has_valid_magic (&self) ->bool { - self.mctp_magic ==MCTP_MAGIC +/// Validates the transport framing, before any length field in the element is trusted. +/// +/// # Errors +/// +/// - `EIO` if the MCTP magic, the MCTP version, the NVDM vendor id, or the declared element +/// length is not one this driver accepts. +pub (crate )fn validate_framing (&self) ->Result { +validate_mctp_framing ( + self.mctp_magic, + self.mctp_payload_size, + self.mctp_header, + self.nvdm_header, +size_of ::<Self >(), + ) }// Returns the sequence number of the message.
Signature · 1 line
2.55.0
PATCH v2 28/31 gpu: nova-core: gsp: remove the RPCs that GSP_INIT replaced
In reply to John HubbardThe r000 boot path folds the system information, the registry keys and the static GPU configuration into the GSP_INIT request, whose reply carries that configuration back to the driver.
The set-system-info, set-registry and get-static-info commands stayed behind after the switch, unreachable and marked dead, along with the payload structures that encoded them.
Remove the three commands and their payloads, and keep the decoded static configuration that the GSP_INIT reply fills in. Drop the generated bindings they were the only users of. The message-function entries stay, because that table catalogs the wire protocol rather than what the driver implements, and already names many functions nova-core never sends.
--- drivers/gpu/nova-core/gsp.rs | 8 - drivers/gpu/nova-core/gsp/commands.rs | 178 +-------- drivers/gpu/nova-core/gsp/fw/commands.rs | 164 +------- .../gpu/nova-core/gsp/fw/r000_00/bindings.rs | 351 ------------------ 4 files changed, 3 insertions(+), 698 deletions(-)
drivers/gpu/nova-core/gsp.rs +0 -8
@@ -398,14 +398,6 @@ pub(crate) fn new( }) } -/// Query the GSP for the static GPU information. -/// -/// The r000 boot path gets the same information from the `GSP_INIT` reply instead. -#[expect(dead_code)] -pub (crate )fn get_static_info (&self, bar:Bar0 <'_>) ->Result <commands::GetGspStaticInfoReply > { - self.cmdq.send_command (bar, commands::GetGspStaticInfo ) - } -/// Returns a shared handle to the GSP command queue. pub (crate )fn cmdq (&self) ->Arc <Cmdq > { self.cmdq.clone ()
drivers/gpu/nova-core/gsp/commands.rs +1 -177
202 lines not on this page · raw message
drivers/gpu/nova-core/gsp/fw/commands.rs +2 -162
188 lines not on this page · raw message
drivers/gpu/nova-core/gsp/fw/r000_00/bindings.rs +0 -351
369 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 29/31 gpu: nova-core: firmware: delete the r570 bindings
In reply to John HubbardNothing referenced the r570 firmware bindings once the driver started compiling against the r000 headers, but the module stayed declared and its generated definitions kept being built.
Delete the module and its bindings, along with the last two comments that named r570.
--- drivers/gpu/nova-core/fsp.rs | 3 +- drivers/gpu/nova-core/gsp/fw.rs | 4 +- drivers/gpu/nova-core/gsp/fw/r570_144.rs | 31 - .../gpu/nova-core/gsp/fw/r570_144/bindings.rs | 1060 ----------------- 4 files changed, 3 insertions(+), 1095 deletions(-) delete mode 100644 drivers/gpu/nova-core/gsp/fw/r570_144.rs delete mode 100644 drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs
drivers/gpu/nova-core/fsp.rs +2 -1
@@ -256,7 +256,8 @@ fn frts_vidmem_offset(hal: &dyn hal::FspHal, fb_info: &FbSizes) -> Result<u64> {// As per OpenRM's `kfspPrepareBootCommands_GH100`. if fb_info.pmu_reserved_size !=0 { offset = (offset + u64::from (fb_info.pmu_reserved_size)) -// The 2 MiB alignment is r570-specific. +// Open RM aligns this to WPR granularity, which is 128 KiB. 2 MiB is a +// multiple of that and reserves at least as much. .align_up (Alignment ::new ::<SZ_2M >()) .ok_or (EINVAL )?; }
drivers/gpu/nova-core/gsp/fw.rs +1 -3
@@ -3,7 +3,6 @@pub (crate )mod commands;mod r000_00; -mod r570_144;// Alias to avoid repeating the version number with every use. use r000_00as bindings;
@@ -512,10 +511,9 @@ fn init(sequence: u32, cmd_size: usize, function: MsgFunction) -> impl Init<Self } } -/// GSP Message Element (r000 MCTP/NVDM format). +/// GSP Message Element, in the MCTP/NVDM format. /// /// This is the transport-layer header for messages exchanged with GSP-RM. -/// r000 firmware uses MCTP/NVDM framing instead of the r570 `GSP_MSG_QUEUE_ELEMENT`. #[repr( C )] pub (crate )struct GspMsgElement { mctp_magic:u32 ,
drivers/gpu/nova-core/gsp/fw/r570_144.rs deleted +0 -31
@@ -1,31 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! Firmware bindings. -//! -//! Imports the generated bindings by `bindgen`. -//! -//! This module may not be directly used. Please abstract or re-export the needed symbols in the -//! parent module instead. - -#![allow( -dead_code, -clippy::all, -clippy::undocumented_unsafe_blocks, -clippy::ptr_as_ptr, -clippy::ref_as_ptr, -missing_docs, -non_camel_case_types, -non_upper_case_globals, -non_snake_case, -improper_ctypes, -unreachable_pub, -unsafe_op_in_unsafe_fn -)] -use kernel::ffi; -use pin_init::MaybeZeroable ; - -include! ("r570_144/bindings.rs" ); - -// SAFETY: This type has a size of zero, so its inclusion into another type should not affect their -// ability to implement `Zeroable`. -unsafe impl <T > kernel::prelude::Zeroable for __IncompleteArrayField <T > {}
drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs deleted +0 -1060
1,060 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 30/31 gpu: nova-core: print GMC command names in debug logs
In reply to John HubbardEach GMC command has a name and a numeric ID.
Nova-core has been printing a bare numeric ID for GMC send and receive debug lines. For example, 0x10001 instead of GSP_INIT.
Add Display formatting and decoding, so that we print the command name, in addition to the ID. Example output:
nova-core 0000:c2:00.0: GSP GMC: send: seq# 0, command=GSP_INIT (0x10001), length=0xf8 nova-core 0000:c2:00.0: GSP GMC: event: seq# 0, command=GSP_INIT (0x10001), length=0x550
--- drivers/gpu/nova-core/gsp/boot.rs | 5 ++- drivers/gpu/nova-core/gsp/cmdq.rs | 9 +++-- drivers/gpu/nova-core/gsp/fw.rs | 67 +++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 6 deletions(-)
drivers/gpu/nova-core/gsp/boot.rs +3 -2
@@ -45,6 +45,7 @@ commands, fw::{BindataArgs , +GmcCommand ,GspArgumentsPadded ,GMCAPI_CMD_EXEC_GENERIC_BOOTLOADER ,GMCAPI_CMD_EXEC_HS_BINARY ,//
@@ -278,8 +279,8 @@ fn dispatch_gmc_boot_event( _ => {dev_err! ( dev, -"Unexpected GMC boot event: command_id={:#010x}\n" , - command_id +"Unexpected GMC boot event: command={}\n" , +GmcCommand (command_id) );Err (EINVAL ) }
drivers/gpu/nova-core/gsp/cmdq.rs +5 -4
@@ -52,6 +52,7 @@ driver::Bar0, gsp::{ fw::{ +GmcCommand ,GspGmcMsgElement ,GspMsgElement ,MsgFunction ,
@@ -898,9 +899,9 @@ fn send_gmc(dev_dbg! ( &self.dev, -"GSP GMC: send: seq# {}, command_id=0x{:x}, length=0x{:x}\n" , +"GSP GMC: send: seq# {}, command={}, length=0x{:x}\n" , rpc_seq, - command_id, +GmcCommand (command_id), dst.header.length (), );
@@ -1301,9 +1302,9 @@ fn receive_gmc_and_dispatch<R>(dev_dbg! ( &self.dev, -"GSP GMC: event: seq# {}, command_id=0x{:x}, length=0x{:x}\n" , +"GSP GMC: event: seq# {}, command={}, length=0x{:x}\n" , header.gmc.sequence, - command_id, +GmcCommand (command_id), length, );
drivers/gpu/nova-core/gsp/fw.rs +67 -0
79 lines not on this page · raw message
Signature · 1 line
2.55.0
PATCH v2 31/31 gpu: nova-core: distinguish GMC event and response debug logs
In reply to John HubbardGSP-initiated GMC events assign sequence numbers starting at bit 63 so they cannot collide with driver request sequences, which start at zero.
The receive debug line printed the raw 64-bit value, so the first boot event showed seq# 9223372036854775808 (0x8000000000000000), and it labeled the GSP_INIT reply as an event.
Print the sequence with that bit cleared, and label a reply as a response. Sample output on a Turing GPU:
nova-core 0000:c1:00.0: GSP GMC: send: seq# 0, command=GSP_INIT (0x10001), length=0xf8 nova-core 0000:c1:00.0: GSP GMC: event: seq# 0, command=EXEC_GENERIC_BOOTLOADER (0x10002), length=0xb0 nova-core 0000:c1:00.0: GSP GMC: response: seq# 0, command=GSP_INIT (0x10001), length=0x450
--- drivers/gpu/nova-core/gsp/cmdq.rs | 10 ++++++++-- drivers/gpu/nova-core/gsp/fw.rs | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +8 -2
@@ -1299,11 +1299,17 @@ fn receive_gmc_and_dispatch<R>( (None ,QueuePointers ::Unchanged ) }else {let command_id = header.gmc.command_id (); +let kind =if header.gmc.is_response () { +"response" + }else { +"event" + };dev_dbg! ( &self.dev, -"GSP GMC: event: seq# {}, command={}, length=0x{:x}\n" , - header.gmc.sequence, +"GSP GMC: {}: seq# {}, command={}, length=0x{:x}\n" , + kind, + header.gmc.sequence_number (),GmcCommand (command_id), length, );
drivers/gpu/nova-core/gsp/fw.rs +17 -0
@@ -674,6 +674,13 @@ pub(crate) struct GmcApiHeader {/// `GMCAPI_HEADER_COMMAND_ID_MASK`. The remaining byte carries flags. const GMCAPI_COMMAND_ID_MASK :u32 =0x00ff_ffff ; +/// Response flag in the high byte of [`GmcApiHeader::command`]. +const GMCAPI_COMMAND_FLAGS_RESPONSE :u32 =0x0100_0000 ; + +/// GSP-initiated events set [`GmcApiHeader::sequence`] starting at this value so they +/// cannot collide with driver request sequences, which start at zero. +const GMC_EVENT_SEQUENCE_BASE :u64 =1 <<63 ; +/// GMC command that hands GSP-RM its system information and registry keys and returns the static /// GPU configuration. Its reply is also what signals that GSP-RM has finished starting. pub (crate )const GMCAPI_CMD_GSP_INIT :u32 = bindings::GMCAPI_COMMANDS_GMCAPI_CMD_GSP_INIT ;
@@ -715,6 +722,16 @@ impl GmcApiHeader {pub (crate )fn command_id (&self) ->u32 { self.command &GMCAPI_COMMAND_ID_MASK } + +/// Returns `true` if this header is a reply to a driver request. +pub (crate )fn is_response (&self) ->bool { + self.command &GMCAPI_COMMAND_FLAGS_RESPONSE !=0 + } + +/// Returns [`Self::sequence`] with the GSP-initiated-event bit cleared. +pub (crate )fn sequence_number (&self) ->u64 { + self.sequence & !GMC_EVENT_SEQUENCE_BASE + } }// SAFETY: All fields are integer types with no uninitialized padding bytes.
Signature · 1 line
2.55.0
Alexandre Courbot
maintainerQuoted 7 lines · John Hubbard
Hi,
I'm sending this just a few days after v1, which is soon, but Timur Tabi and Zhi Wang reviewed the whole series in that time, and that led to quite a lot of fixes and lines changed. So I think it is helpful to provide a v2 now, so that future reviewers can avoid rediscovering all those issues.
I only gave this a high-level look so far. This needs some reorganizing before it can be properly reviewed. I think the size of the series can be reduced by at least a third, maybe more.
First let's keep the series focused on r000: patches 7, 10, 30 and 31 are dealing with debug logs, not r000 proper. I'm sure they are useful but they are technically a different topic from adding support for r000.
Then there is a lot of churn. For instance patch 28 removes 351 LoCs of bindings introduced by patch 2. They are not required by the end of the series, but kept as dead code after patch 26 because (IIUC) their RPCs are removed later. This is one of the few cases where it is actually ok to do two things in the same patch: were they removed during the switch done by patch 26, their bindings wouldn't need to be introduced at all. Actually that's how the sequencer is treated; I have many issues with patch 26, but *that* one is ok - a bunch of deleted code is the simplest thing to review.
The msgq v2 part also looks more messy than it needs to be. It tries to keep both versions coexisting at the same time, even though only one of them is ever used at any given time. I suspect it would be simpler to implement the changes as part of the switch. Or at the very least, let's make the cmdq generic if we want it to handle both, and place the differences in sub-modules. This should also simplify the receive path considerably.
Patch 26 does 5 different things over hundreds and hundreds of lines, that's more contexts than a reviewer can hold in their head. This needs to be split. I strongly suspect (more an intuition than a realization) that a good part of it is actually intended to land in the already-existing preceding patches. Other things can be simplified: for instance Bar0 arguments are added to many cmdq methods, which was probably the only way of doing when the series was first developed, but now we can store a Bar0 in the relevant struct so let's do that. Actually the Cmdq is probably overdue holding one.
I'll give a deeper look at the next revision, which I expect to be well under the 3000 added LoCs (famous last words :)).
Quoted 45 lines · Alexandre Courbot
Quoted 7 lines · John Hubbard
Hi,
I'm sending this just a few days after v1, which is soon, but Timur Tabi and Zhi Wang reviewed the whole series in that time, and that led to quite a lot of fixes and lines changed. So I think it is helpful to provide a v2 now, so that future reviewers can avoid rediscovering all those issues.
I only gave this a high-level look so far. This needs some reorganizing before it can be properly reviewed. I think the size of the series can be reduced by at least a third, maybe more.
First let's keep the series focused on r000: patches 7, 10, 30 and 31 are dealing with debug logs, not r000 proper. I'm sure they are useful but they are technically a different topic from adding support for r000.
Then there is a lot of churn. For instance patch 28 removes 351 LoCs of bindings introduced by patch 2. They are not required by the end of the series, but kept as dead code after patch 26 because (IIUC) their RPCs are removed later. This is one of the few cases where it is actually ok to do two things in the same patch: were they removed during the switch done by patch 26, their bindings wouldn't need to be introduced at all. Actually that's how the sequencer is treated; I have many issues with patch 26, but *that* one is ok - a bunch of deleted code is the simplest thing to review.
The msgq v2 part also looks more messy than it needs to be. It tries to keep both versions coexisting at the same time, even though only one of them is ever used at any given time. I suspect it would be simpler to implement the changes as part of the switch. Or at the very least, let's make the cmdq generic if we want it to handle both, and place the differences in sub-modules. This should also simplify the receive path considerably.
Patch 26 does 5 different things over hundreds and hundreds of lines, that's more contexts than a reviewer can hold in their head. This needs to be split. I strongly suspect (more an intuition than a realization) that a good part of it is actually intended to land in the already-existing preceding patches. Other things can be simplified: for instance
Bar0arguments are added to many cmdq methods, which was probably the only way of doing when the series was first developed, but now we can store aBar0in the relevant struct so let's do that. Actually theCmdqis probably overdue holding one.
Quoted 2 lines
I'll give a deeper look at the next revision, which I expect to be well under the 3000 added LoCs (famous last words :)).
On a broader note, this series contains several chunks of functionality that could be separate patch series and reviewed separately. I think we'd be able to review this faster if it were explicitly split into several series, as Alex noted there is some churn / patches that could be put in a better order.
In particular, I see these sets of functionalities that could be done separately and in order:
1. MCTP transport + cmdq transport
2. GMCAPI cmdq infra
3. Boot events for r000
4. Boot using r000 - that's systeminfo+staticinfo stuff
5. Migration to r000 + removal of r570. Ideally, the migration to r000 can be the smallest commit to flip from (uses r570 for booth, doesn't use r000) => (doesn't use r570, uses r000).
6. Misc debug log stuff
Quoted 10 lines · Eliot Courtney
Quoted 9 lines · Alexandre Courbot
Quoted 7 lines · John Hubbard
Hi,
I'm sending this just a few days after v1, which is soon, but Timur Tabi and Zhi Wang reviewed the whole series in that time, and that led to quite a lot of fixes and lines changed. So I think it is helpful to provide a v2 now, so that future reviewers can avoid rediscovering all those issues.
Quoted 3 lines
Quoted 3 lines
I only gave this a high-level look so far. This needs some reorganizing before it can be properly reviewed. I think the size of the series can be reduced by at least a third, maybe more.
Not according to my latest math. But I'll do what I can. :)
Quoted 5 lines
Quoted 5 lines
First let's keep the series focused on r000: patches 7, 10, 30 and 31 are dealing with debug logs, not r000 proper. I'm sure they are useful but they are technically a different topic from adding support for r000.
Quoted 9 lines
Quoted 9 lines
Then there is a lot of churn. For instance patch 28 removes 351 LoCs of bindings introduced by patch 2. They are not required by the end of the series, but kept as dead code after patch 26 because (IIUC) their RPCs are removed later. This is one of the few cases where it is actually ok to do two things in the same patch: were they removed during the switch done by patch 26, their bindings wouldn't need to be introduced at all. Actually that's how the sequencer is treated; I have many issues with patch 26, but *that* one is ok - a bunch of deleted code is the simplest thing to review.
I was wondering about that approach to deleting the sequencer, so good to hear that it is readable.
Quoted 19 lines
Quoted 19 lines
The msgq v2 part also looks more messy than it needs to be. It tries to keep both versions coexisting at the same time, even though only one of them is ever used at any given time. I suspect it would be simpler to implement the changes as part of the switch. Or at the very least, let's make the cmdq generic if we want it to handle both, and place the differences in sub-modules. This should also simplify the receive path considerably.
Patch 26 does 5 different things over hundreds and hundreds of lines, that's more contexts than a reviewer can hold in their head. This needs to be split. I strongly suspect (more an intuition than a realization) that a good part of it is actually intended to land in the already-existing preceding patches. Other things can be simplified: for instance
Bar0arguments are added to many cmdq methods, which was probably the only way of doing when the series was first developed, but now we can store aBar0in the relevant struct so let's do that. Actually theCmdqis probably overdue holding one.
Quoted 8 lines
Quoted 2 lines
I'll give a deeper look at the next revision, which I expect to be well under the 3000 added LoCs (famous last words :)).
On a broader note, this series contains several chunks of functionality that could be separate patch series and reviewed separately. I think we'd be able to review this faster if it were explicitly split into several series, as Alex noted there is some churn / patches that could be put in a better order.
OK, I'll work on splitting up this huge series into digestible smaller patchsets.
Quoted 11 lines
In particular, I see these sets of functionalities that could be done separately and in order:
1. MCTP transport + cmdq transport
2. GMCAPI cmdq infra
3. Boot events for r000
4. Boot using r000 - that's systeminfo+staticinfo stuff
5. Migration to r000 + removal of r570. Ideally, the migration to r000 can be the smallest commit to flip from (uses r570 for booth, doesn't use r000) => (doesn't use r570, uses r000).
6. Misc debug log stuff
thanks,
Signature · 1 line
John Hubbard