summaryrefslogtreecommitdiff
path: root/drivers/gpu/nova-core/firmware
diff options
context:
space:
mode:
Diffstat (limited to 'drivers/gpu/nova-core/firmware')
-rw-r--r--drivers/gpu/nova-core/firmware/booter.rs241
-rw-r--r--drivers/gpu/nova-core/firmware/fwsec.rs408
-rw-r--r--drivers/gpu/nova-core/firmware/fwsec/bootloader.rs305
-rw-r--r--drivers/gpu/nova-core/firmware/gsp.rs82
-rw-r--r--drivers/gpu/nova-core/firmware/gsp_fmc.rs127
-rw-r--r--drivers/gpu/nova-core/firmware/radix3.rs144
-rw-r--r--drivers/gpu/nova-core/firmware/riscv.rs54
-rw-r--r--drivers/gpu/nova-core/firmware/tlv.rs262
8 files changed, 1623 insertions, 0 deletions
diff --git a/drivers/gpu/nova-core/firmware/booter.rs b/drivers/gpu/nova-core/firmware/booter.rs
new file mode 100644
index 000000000..aa4458bb3
--- /dev/null
+++ b/drivers/gpu/nova-core/firmware/booter.rs
@@ -0,0 +1,241 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! Support for loading and patching the `Booter` firmware. `Booter` is a Heavy Secured firmware
+//! running on [`Sec2`], that is used on Turing/Ampere to load the GSP firmware into the GSP falcon
+//! (and optionally unload it through a separate firmware image).
+
+use core::marker::PhantomData;
+
+use kernel::{
+ device,
+ dma::Coherent,
+ prelude::*, //
+};
+
+use crate::{
+ falcon::{
+ sec2::Sec2,
+ Falcon,
+ FalconBromParams,
+ FalconDmaLoadTarget,
+ FalconDmaLoadable,
+ FalconFirmware, //
+ },
+ firmware::{
+ tlv::{
+ request_tlv, //
+ Tlv,
+ },
+ FirmwareObject,
+ FirmwareSignature,
+ Signed,
+ Unsigned, //
+ },
+ gpu::Chipset,
+ num::IntoSafeCast,
+};
+
+/// Signature for Booter firmware. Their size is encoded into the header and not known a compile
+/// time, so we just wrap a byte slices on which we can implement [`FirmwareSignature`].
+struct BooterSignature<'a>(&'a [u8]);
+
+impl<'a> AsRef<[u8]> for BooterSignature<'a> {
+ fn as_ref(&self) -> &[u8] {
+ self.0
+ }
+}
+
+impl<'a> FirmwareSignature<BooterFirmware> for BooterSignature<'a> {}
+
+/// The `Booter` loader firmware, responsible for loading the GSP.
+pub(crate) struct BooterFirmware {
+ // Load parameters for Secure `IMEM` falcon memory.
+ imem_sec_load_target: FalconDmaLoadTarget,
+ // Load parameters for Non-Secure `IMEM` falcon memory,
+ // used only on Turing and GA100
+ imem_ns_load_target: Option<FalconDmaLoadTarget>,
+ // Load parameters for `DMEM` falcon memory.
+ dmem_load_target: FalconDmaLoadTarget,
+ // BROM falcon parameters.
+ brom_params: FalconBromParams,
+ // Device-mapped firmware image.
+ ucode: FirmwareObject<Self, Signed>,
+}
+
+impl FirmwareObject<BooterFirmware, Unsigned> {
+ fn new_booter(data: &[u8]) -> Result<Self> {
+ let mut ucode = KVVec::new();
+ ucode.extend_from_slice(data, GFP_KERNEL)?;
+
+ Ok(Self(ucode, PhantomData))
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum BooterKind {
+ Loader,
+ Unloader,
+}
+
+impl BooterFirmware {
+ /// Parses the Booter firmware contained in `fw`, and patches the correct signature so it is
+ /// ready to be loaded and run on `falcon`.
+ pub(crate) fn new(
+ dev: &device::Device<device::Bound>,
+ kind: BooterKind,
+ chipset: Chipset,
+ falcon: &Falcon<'_, <Self as FalconFirmware>::Target>,
+ ) -> Result<Self> {
+ let fw_name = match kind {
+ BooterKind::Loader => "booter_load",
+ BooterKind::Unloader => "booter_unload",
+ };
+ let fw = request_tlv(dev, chipset, fw_name)?;
+ let tlv = Tlv::new(fw.data())?;
+ dev_dbg!(
+ dev,
+ "loaded {} firmware v{}\n",
+ fw_name,
+ tlv.get_string(b"VERS")?
+ );
+
+ let os_data_offset = tlv.get_u32(b"DAOF")?;
+ let os_data_size = tlv.get_u32(b"DASZ")?;
+ let os_code_offset = tlv.get_u32(b"CDOF")?;
+ let os_code_size = tlv.get_u32(b"CDSZ")?;
+ let patch_loc = tlv.get_u32(b"PLOC")?;
+ let fuse_version: usize = tlv.get_u32(b"FUSE")?.into_safe_cast();
+ let engine_id = tlv.get_u32(b"ENID")?;
+ let ucode_id = tlv.get_u32(b"UCID")?;
+ let app0_code_offset = tlv.get_u32(b"A0CO")?;
+ let app0_code_size = tlv.get_u32(b"A0CS")?;
+
+ let brom_params = FalconBromParams {
+ // `os_data_offset` is an absolute index, but `pkc_data_offset` is from the
+ // signature patch location.
+ pkc_data_offset: patch_loc.checked_sub(os_data_offset).ok_or(EINVAL)?,
+ engine_id_mask: u16::try_from(engine_id).map_err(|_| EINVAL)?,
+ ucode_id: u8::try_from(ucode_id).map_err(|_| EINVAL)?,
+ };
+
+ let ucode = tlv
+ .get_bytes(b"BLOB")
+ .and_then(FirmwareObject::<Self, _>::new_booter)?;
+
+ // Obtain the version from the fuse register, and extract the corresponding
+ // signature.
+ let reg_fuse_version: usize = falcon
+ .signature_reg_fuse_version(brom_params.engine_id_mask, brom_params.ucode_id)?
+ .into_safe_cast();
+
+ const FUSE_VERSION_USE_LAST_SIG: usize = 0;
+
+ let index = match reg_fuse_version {
+ // `0` means the last signature should be used.
+ FUSE_VERSION_USE_LAST_SIG => None,
+ // Otherwise, hardware fuse version needs to be subtracted to obtain the index.
+ _ => Some(fuse_version.checked_sub(reg_fuse_version).ok_or(EINVAL)?),
+ };
+
+ // Extract the nth signature. Booter is always signed.
+ let sig_chunk = tlv.get_signature(index)?;
+
+ let signature = BooterSignature(sig_chunk);
+ let ucode_signed = ucode.patch_signature(&signature, patch_loc.into_safe_cast())?;
+
+ // There are two versions of Booter, one for Turing/GA100, and another for
+ // GA102+. The extraction of the IMEM sections differs between the two
+ // versions. Unfortunately, the file names are the same, and the headers
+ // don't indicate the versions. The only way to differentiate is by the Chipset.
+ let (imem_sec_dst_start, imem_ns_load_target) = if chipset <= Chipset::GA100 {
+ (
+ app0_code_offset,
+ Some(FalconDmaLoadTarget {
+ src_start: 0,
+ dst_start: os_code_offset,
+ len: os_code_size,
+ }),
+ )
+ } else {
+ (0, None)
+ };
+
+ Ok(Self {
+ imem_sec_load_target: FalconDmaLoadTarget {
+ src_start: app0_code_offset,
+ dst_start: imem_sec_dst_start,
+ len: app0_code_size,
+ },
+ imem_ns_load_target,
+ dmem_load_target: FalconDmaLoadTarget {
+ src_start: os_data_offset,
+ dst_start: 0,
+ len: os_data_size,
+ },
+ brom_params,
+ ucode: ucode_signed,
+ })
+ }
+
+ /// Load and run the booter firmware on SEC2.
+ ///
+ /// Resets SEC2, loads this firmware image, then boots with the WPR metadata
+ /// address passed via the SEC2 mailboxes.
+ pub(crate) fn run<T>(
+ &self,
+ dev: &device::Device<device::Bound>,
+ sec2_falcon: &Falcon<'_, Sec2>,
+ wpr_meta: &Coherent<'_, T>,
+ ) -> Result {
+ sec2_falcon.reset()?;
+ sec2_falcon.load(self)?;
+ let wpr_dma_address = wpr_meta.dma_address();
+ let (mbox0, mbox1) = sec2_falcon.boot(
+ Some(wpr_dma_address as u32),
+ Some((wpr_dma_address >> 32) as u32),
+ )?;
+ dev_dbg!(dev, "SEC2 MBOX0: {:#x}, MBOX1: {:#x}\n", mbox0, mbox1);
+
+ if mbox0 != 0 {
+ dev_err!(dev, "Booter-load failed with error {:#x}\n", mbox0);
+ return Err(ENODEV);
+ }
+
+ Ok(())
+ }
+}
+
+impl FalconDmaLoadable for BooterFirmware {
+ fn as_slice(&self) -> &[u8] {
+ self.ucode.0.as_slice()
+ }
+
+ fn imem_sec_load_params(&self) -> FalconDmaLoadTarget {
+ self.imem_sec_load_target.clone()
+ }
+
+ fn imem_ns_load_params(&self) -> Option<FalconDmaLoadTarget> {
+ self.imem_ns_load_target.clone()
+ }
+
+ fn dmem_load_params(&self) -> FalconDmaLoadTarget {
+ self.dmem_load_target.clone()
+ }
+}
+
+impl FalconFirmware for BooterFirmware {
+ type Target = Sec2;
+
+ fn brom_params(&self) -> FalconBromParams {
+ self.brom_params.clone()
+ }
+
+ fn boot_addr(&self) -> u32 {
+ if let Some(ns_target) = &self.imem_ns_load_target {
+ ns_target.dst_start
+ } else {
+ self.imem_sec_load_target.src_start
+ }
+ }
+}
diff --git a/drivers/gpu/nova-core/firmware/fwsec.rs b/drivers/gpu/nova-core/firmware/fwsec.rs
new file mode 100644
index 000000000..7a931f22f
--- /dev/null
+++ b/drivers/gpu/nova-core/firmware/fwsec.rs
@@ -0,0 +1,408 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! FWSEC is a High Secure firmware that is extracted from the BIOS and performs the first step of
+//! the GSP startup by creating the WPR2 memory region and copying critical areas of the VBIOS into
+//! it after authenticating them, ensuring they haven't been tampered with. It runs on the GSP
+//! falcon.
+//!
+//! Before being run, it needs to be patched in two areas:
+//!
+//! - The command to be run, as this firmware can perform several tasks ;
+//! - The ucode signature, so the GSP falcon can run FWSEC in HS mode.
+
+pub(crate) mod bootloader;
+
+use core::marker::PhantomData;
+
+use kernel::{
+ device::{
+ self,
+ Device, //
+ },
+ prelude::*,
+ transmute::{
+ AsBytes,
+ FromBytes, //
+ },
+};
+
+use crate::{
+ falcon::{
+ gsp::Gsp,
+ Falcon,
+ FalconBromParams,
+ FalconDmaLoadTarget,
+ FalconDmaLoadable,
+ FalconFirmware, //
+ },
+ firmware::{
+ FalconUCodeDesc,
+ FirmwareObject,
+ FirmwareSignature,
+ Signed,
+ Unsigned, //
+ },
+ num::FromSafeCast,
+ vbios::Vbios,
+};
+
+const NVFW_FALCON_APPIF_ID_DMEMMAPPER: u32 = 0x4;
+
+#[repr(C)]
+#[derive(Debug)]
+struct FalconAppifHdrV1 {
+ version: u8,
+ header_size: u8,
+ entry_size: u8,
+ entry_count: u8,
+}
+// SAFETY: Any byte sequence is valid for this struct.
+unsafe impl FromBytes for FalconAppifHdrV1 {}
+
+#[repr(C, packed)]
+#[derive(Debug)]
+struct FalconAppifV1 {
+ id: u32,
+ dmem_base: u32,
+}
+// SAFETY: Any byte sequence is valid for this struct.
+unsafe impl FromBytes for FalconAppifV1 {}
+
+#[derive(Debug)]
+#[repr(C, packed)]
+struct FalconAppifDmemmapperV3 {
+ signature: u32,
+ version: u16,
+ size: u16,
+ cmd_in_buffer_offset: u32,
+ cmd_in_buffer_size: u32,
+ cmd_out_buffer_offset: u32,
+ cmd_out_buffer_size: u32,
+ nvf_img_data_buffer_offset: u32,
+ nvf_img_data_buffer_size: u32,
+ printf_buffer_hdr: u32,
+ ucode_build_time_stamp: u32,
+ ucode_signature: u32,
+ init_cmd: u32,
+ ucode_feature: u32,
+ ucode_cmd_mask0: u32,
+ ucode_cmd_mask1: u32,
+ multi_tgt_tbl: u32,
+}
+// SAFETY: Any byte sequence is valid for this struct.
+unsafe impl FromBytes for FalconAppifDmemmapperV3 {}
+// SAFETY: This struct doesn't contain uninitialized bytes and doesn't have interior mutability.
+unsafe impl AsBytes for FalconAppifDmemmapperV3 {}
+
+#[derive(Debug)]
+#[repr(C, packed)]
+struct ReadVbios {
+ ver: u32,
+ hdr: u32,
+ addr: u64,
+ size: u32,
+ flags: u32,
+}
+// SAFETY: Any byte sequence is valid for this struct.
+unsafe impl FromBytes for ReadVbios {}
+// SAFETY: This struct doesn't contain uninitialized bytes and doesn't have interior mutability.
+unsafe impl AsBytes for ReadVbios {}
+
+#[derive(Debug)]
+#[repr(C, packed)]
+struct FrtsRegion {
+ ver: u32,
+ hdr: u32,
+ addr: u32,
+ size: u32,
+ ftype: u32,
+}
+// SAFETY: Any byte sequence is valid for this struct.
+unsafe impl FromBytes for FrtsRegion {}
+// SAFETY: This struct doesn't contain uninitialized bytes and doesn't have interior mutability.
+unsafe impl AsBytes for FrtsRegion {}
+
+const NVFW_FRTS_CMD_REGION_TYPE_FB: u32 = 2;
+
+#[repr(C, packed)]
+struct FrtsCmd {
+ read_vbios: ReadVbios,
+ frts_region: FrtsRegion,
+}
+// SAFETY: Any byte sequence is valid for this struct.
+unsafe impl FromBytes for FrtsCmd {}
+// SAFETY: This struct doesn't contain uninitialized bytes and doesn't have interior mutability.
+unsafe impl AsBytes for FrtsCmd {}
+
+const NVFW_FALCON_APPIF_DMEMMAPPER_CMD_FRTS: u32 = 0x15;
+const NVFW_FALCON_APPIF_DMEMMAPPER_CMD_SB: u32 = 0x19;
+
+/// Command for the [`FwsecFirmware`] to execute.
+pub(crate) enum FwsecCommand {
+ /// Asks [`FwsecFirmware`] to carve out the WPR2 area and place a verified copy of the VBIOS
+ /// image into it.
+ Frts { frts_addr: u64, frts_size: u64 },
+ /// Asks [`FwsecFirmware`] to load pre-OS apps on the PMU.
+ Sb,
+}
+
+/// Size of the signatures used in FWSEC.
+const BCRT30_RSA3K_SIG_SIZE: usize = 384;
+
+/// A single signature that can be patched into a FWSEC image.
+#[repr(transparent)]
+pub(crate) struct Bcrt30Rsa3kSignature([u8; BCRT30_RSA3K_SIG_SIZE]);
+
+/// SAFETY: A signature is just an array of bytes.
+unsafe impl FromBytes for Bcrt30Rsa3kSignature {}
+
+impl From<[u8; BCRT30_RSA3K_SIG_SIZE]> for Bcrt30Rsa3kSignature {
+ fn from(sig: [u8; BCRT30_RSA3K_SIG_SIZE]) -> Self {
+ Self(sig)
+ }
+}
+
+impl AsRef<[u8]> for Bcrt30Rsa3kSignature {
+ fn as_ref(&self) -> &[u8] {
+ &self.0
+ }
+}
+
+impl FirmwareSignature<FwsecFirmware> for Bcrt30Rsa3kSignature {}
+
+/// The FWSEC microcode, extracted from the BIOS and to be run on the GSP falcon.
+///
+/// It is responsible for e.g. carving out the WPR2 region as the first step of the GSP bootflow.
+pub(crate) struct FwsecFirmware {
+ /// Descriptor of the firmware.
+ desc: FalconUCodeDesc,
+ /// Object containing the firmware binary.
+ ucode: FirmwareObject<Self, Signed>,
+}
+
+impl FalconDmaLoadable for FwsecFirmware {
+ fn as_slice(&self) -> &[u8] {
+ self.ucode.0.as_slice()
+ }
+
+ fn imem_sec_load_params(&self) -> FalconDmaLoadTarget {
+ self.desc.imem_sec_load_params()
+ }
+
+ fn imem_ns_load_params(&self) -> Option<FalconDmaLoadTarget> {
+ self.desc.imem_ns_load_params()
+ }
+
+ fn dmem_load_params(&self) -> FalconDmaLoadTarget {
+ self.desc.dmem_load_params()
+ }
+}
+
+impl FalconFirmware for FwsecFirmware {
+ type Target = Gsp;
+
+ fn brom_params(&self) -> FalconBromParams {
+ FalconBromParams {
+ pkc_data_offset: self.desc.pkc_data_offset(),
+ engine_id_mask: self.desc.engine_id_mask(),
+ ucode_id: self.desc.ucode_id(),
+ }
+ }
+
+ fn boot_addr(&self) -> u32 {
+ 0
+ }
+}
+
+impl FirmwareObject<FwsecFirmware, Unsigned> {
+ fn new_fwsec(bios: &Vbios, cmd: FwsecCommand) -> Result<Self> {
+ let desc = bios.fwsec_image().header()?;
+ let mut ucode = KVVec::new();
+ ucode.extend_from_slice(bios.fwsec_image().ucode(&desc)?, GFP_KERNEL)?;
+
+ let hdr_offset = desc
+ .imem_load_size()
+ .checked_add(desc.interface_offset())
+ .map(usize::from_safe_cast)
+ .ok_or(EINVAL)?;
+
+ let hdr = ucode
+ .get(hdr_offset..)
+ .and_then(FalconAppifHdrV1::from_bytes_prefix)
+ .ok_or(EINVAL)?
+ .0;
+
+ if hdr.version != 1 {
+ return Err(EINVAL);
+ }
+
+ // Find the DMEM mapper section in the firmware.
+ for i in 0..usize::from(hdr.entry_count) {
+ // CALC: hdr_offset + header_size + i * entry_size.
+ let entry_offset = hdr_offset
+ .checked_add(usize::from(hdr.header_size))
+ .and_then(|o| o.checked_add(i.checked_mul(usize::from(hdr.entry_size))?))
+ .ok_or(EINVAL)?;
+
+ let app = ucode
+ .get(entry_offset..)
+ .and_then(FalconAppifV1::from_bytes_prefix)
+ .ok_or(EINVAL)?
+ .0;
+
+ if app.id != NVFW_FALCON_APPIF_ID_DMEMMAPPER {
+ continue;
+ }
+ let dmem_base = app.dmem_base;
+
+ let dmem_mapper_offset = desc
+ .imem_load_size()
+ .checked_add(dmem_base)
+ .map(usize::from_safe_cast)
+ .ok_or(EINVAL)?;
+
+ let dmem_mapper = ucode
+ .get_mut(dmem_mapper_offset..)
+ .and_then(FalconAppifDmemmapperV3::from_bytes_mut_prefix)
+ .ok_or(EINVAL)?
+ .0;
+
+ dmem_mapper.init_cmd = match cmd {
+ FwsecCommand::Frts { .. } => NVFW_FALCON_APPIF_DMEMMAPPER_CMD_FRTS,
+ FwsecCommand::Sb => NVFW_FALCON_APPIF_DMEMMAPPER_CMD_SB,
+ };
+ let cmd_in_buffer_offset = dmem_mapper.cmd_in_buffer_offset;
+
+ let frts_cmd_offset = desc
+ .imem_load_size()
+ .checked_add(cmd_in_buffer_offset)
+ .map(usize::from_safe_cast)
+ .ok_or(EINVAL)?;
+
+ let frts_cmd = ucode
+ .get_mut(frts_cmd_offset..)
+ .and_then(FrtsCmd::from_bytes_mut_prefix)
+ .ok_or(EINVAL)?
+ .0;
+
+ frts_cmd.read_vbios = ReadVbios {
+ ver: 1,
+ hdr: u32::try_from(size_of::<ReadVbios>())?,
+ addr: 0,
+ size: 0,
+ flags: 2,
+ };
+ if let FwsecCommand::Frts {
+ frts_addr,
+ frts_size,
+ } = cmd
+ {
+ frts_cmd.frts_region = FrtsRegion {
+ ver: 1,
+ hdr: u32::try_from(size_of::<FrtsRegion>())?,
+ addr: u32::try_from(frts_addr >> 12)?,
+ size: u32::try_from(frts_size >> 12)?,
+ ftype: NVFW_FRTS_CMD_REGION_TYPE_FB,
+ };
+ }
+
+ // Return early as we found and patched the DMEMMAPPER region.
+ return Ok(Self(ucode, PhantomData));
+ }
+
+ Err(ENOTSUPP)
+ }
+}
+
+impl FwsecFirmware {
+ /// Extract the Fwsec firmware from `bios` and patch it to run on `falcon` with the `cmd`
+ /// command.
+ pub(crate) fn new(
+ dev: &Device<device::Bound>,
+ falcon: &Falcon<'_, Gsp>,
+ bios: &Vbios,
+ cmd: FwsecCommand,
+ ) -> Result<Self> {
+ let ucode_dma = FirmwareObject::<Self, _>::new_fwsec(bios, cmd)?;
+
+ // Patch signature if needed.
+ let desc = bios.fwsec_image().header()?;
+ let ucode_signed = if desc.signature_count() != 0 {
+ let sig_base_img = desc
+ .imem_load_size()
+ .checked_add(desc.pkc_data_offset())
+ .map(usize::from_safe_cast)
+ .ok_or(EINVAL)?;
+ let desc_sig_versions = u32::from(desc.signature_versions());
+ let reg_fuse_version =
+ falcon.signature_reg_fuse_version(desc.engine_id_mask(), desc.ucode_id())?;
+ dev_dbg!(
+ dev,
+ "desc_sig_versions: {:#x}, reg_fuse_version: {}\n",
+ desc_sig_versions,
+ reg_fuse_version
+ );
+ let signature_idx = {
+ let reg_fuse_version_bit = 1 << reg_fuse_version;
+
+ // Check if the fuse version is supported by the firmware.
+ if desc_sig_versions & reg_fuse_version_bit == 0 {
+ dev_err!(
+ dev,
+ "no matching signature: {:#x} {:#x}\n",
+ reg_fuse_version_bit,
+ desc_sig_versions,
+ );
+ return Err(EINVAL);
+ }
+
+ // `desc_sig_versions` has one bit set per included signature. Thus, the index of
+ // the signature to patch is the number of bits in `desc_sig_versions` set to `1`
+ // before `reg_fuse_version_bit`.
+
+ // Mask of the bits of `desc_sig_versions` to preserve.
+ let reg_fuse_version_mask = reg_fuse_version_bit.wrapping_sub(1);
+
+ usize::from_safe_cast((desc_sig_versions & reg_fuse_version_mask).count_ones())
+ };
+
+ dev_dbg!(dev, "patching signature with index {}\n", signature_idx);
+ let signature = bios
+ .fwsec_image()
+ .sigs(&desc)
+ .and_then(|sigs| sigs.get(signature_idx).ok_or(EINVAL))?;
+
+ ucode_dma.patch_signature(signature, sig_base_img)?
+ } else {
+ ucode_dma.no_patch_signature()
+ };
+
+ Ok(FwsecFirmware {
+ desc,
+ ucode: ucode_signed,
+ })
+ }
+
+ /// Loads the FWSEC firmware into `falcon` and execute it.
+ ///
+ /// This must only be called on chipsets that do not need the FWSEC bootloader. On chipsets
+ /// where the bootloader is required, use [`bootloader::FwsecFirmwareWithBl`] instead.
+ pub(crate) fn run(&self, dev: &Device<device::Bound>, falcon: &Falcon<'_, Gsp>) -> Result<()> {
+ // Reset falcon, load the firmware, and run it.
+ falcon
+ .reset()
+ .inspect_err(|e| dev_err!(dev, "Failed to reset GSP falcon: {:?}\n", e))?;
+ falcon
+ .load(self)
+ .inspect_err(|e| dev_err!(dev, "Failed to load FWSEC firmware: {:?}\n", e))?;
+ let (mbox0, _) = falcon
+ .boot(Some(0), None)
+ .inspect_err(|e| dev_err!(dev, "Failed to boot FWSEC firmware: {:?}\n", e))?;
+ if mbox0 != 0 {
+ dev_err!(dev, "FWSEC firmware returned error {}\n", mbox0);
+ Err(EIO)
+ } else {
+ Ok(())
+ }
+ }
+}
diff --git a/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs b/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs
new file mode 100644
index 000000000..a87878fe2
--- /dev/null
+++ b/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs
@@ -0,0 +1,305 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Bootloader support for the FWSEC firmware.
+//!
+//! On Turing, the FWSEC firmware is not loaded directly, but is instead loaded through a small
+//! bootloader program that performs the required DMA operations. This bootloader itself needs to
+//! be loaded using PIO.
+
+use kernel::{
+ device::{
+ self,
+ Device, //
+ },
+ dma::Coherent,
+ io::{
+ register::Array,
+ Io, //
+ },
+ prelude::*,
+ ptr::{
+ Alignable,
+ Alignment, //
+ },
+ sizes,
+ transmute::AsBytes,
+};
+
+use crate::{
+ falcon::{
+ self,
+ gsp::Gsp,
+ Falcon,
+ FalconBromParams,
+ FalconDmaLoadable,
+ FalconFbifMemType,
+ FalconFbifTarget,
+ FalconFirmware,
+ FalconPioDmemLoadTarget,
+ FalconPioImemLoadTarget,
+ FalconPioLoadable, //
+ },
+ firmware::{
+ fwsec::FwsecFirmware,
+ tlv::{
+ request_tlv, //
+ Tlv,
+ },
+ },
+ 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<'a> {
+ /// DMA object the bootloader will copy the firmware from.
+ _firmware_dma: Coherent<'a, [u8]>,
+ /// Code of the bootloader to be loaded into non-secure IMEM.
+ ucode: KVec<u8>,
+ /// Descriptor to be loaded into DMEM for the bootloader to read.
+ dmem_desc: BootloaderDmemDescV2,
+ /// Range-validated start offset of the firmware code in IMEM.
+ imem_dst_start: u16,
+ /// BROM parameters of the loaded firmware.
+ brom_params: FalconBromParams,
+ /// Range-validated `desc.start_tag`.
+ start_tag: u16,
+}
+
+impl<'a> FwsecFirmwareWithBl<'a> {
+ /// Loads the bootloader firmware for `dev` and `chipset`, and wrap `firmware` so it can be
+ /// loaded using it.
+ pub(crate) fn new(
+ firmware: FwsecFirmware,
+ dev: &'a Device<device::Bound>,
+ chipset: Chipset,
+ ) -> Result<Self> {
+ let fw = request_tlv(dev, chipset, "gen_bootloader")?;
+ let tlv = Tlv::new(fw.data())?;
+ dev_dbg!(
+ dev,
+ "loaded generic bootloader firmware v{}\n",
+ tlv.get_string(b"VERS")?
+ );
+
+ let ucode = {
+ let blob = tlv.get_bytes(b"BLOB")?;
+ let code_size = usize::from_safe_cast(tlv.get_u32(b"CDSZ")?);
+ let code = blob.get(..code_size).ok_or(EINVAL)?;
+ let aligned_code_size = code_size
+ .align_up(Alignment::new::<{ falcon::MEM_BLOCK_ALIGNMENT }>())
+ .ok_or(EINVAL)?;
+
+ let mut ucode = KVec::with_capacity(aligned_code_size, GFP_KERNEL)?;
+ ucode.extend_from_slice(code, GFP_KERNEL)?;
+ ucode.resize(aligned_code_size, 0, GFP_KERNEL)?;
+
+ ucode
+ };
+
+ // `BootloaderDmemDescV2` expects the source to be a mirror image of the destination and
+ // uses the same offset parameter for both.
+ //
+ // Thus, the start of the source object needs to be padded with the difference between the
+ // destination and source offsets.
+ //
+ // In practice, this is expected to always be zero but is required for code correctness.
+ let (align_padding, firmware_dma) = {
+ let align_padding = {
+ let imem_sec = firmware.imem_sec_load_params();
+
+ imem_sec
+ .dst_start
+ .checked_sub(imem_sec.src_start)
+ .map(usize::from_safe_cast)
+ .ok_or(EOVERFLOW)?
+ };
+
+ let mut firmware_obj = KVVec::new();
+ firmware_obj.extend_with(align_padding, 0u8, GFP_KERNEL)?;
+ firmware_obj.extend_from_slice(firmware.ucode.0.as_slice(), GFP_KERNEL)?;
+
+ (
+ align_padding,
+ Coherent::from_slice(dev, firmware_obj.as_slice(), GFP_KERNEL)?,
+ )
+ };
+
+ let dmem_desc = {
+ // Bootloader payload is in non-coherent system memory.
+ const FALCON_DMAIDX_PHYS_SYS_NCOH: u32 = 4;
+
+ let imem_sec = firmware.imem_sec_load_params();
+ let imem_ns = firmware.imem_ns_load_params().ok_or(EINVAL)?;
+ let dmem = firmware.dmem_load_params();
+
+ // The bootloader does not have a data destination offset field and copies the data at
+ // the start of DMEM, so it can only be used if the destination offset of the firmware
+ // is 0.
+ if dmem.dst_start != 0 {
+ return Err(EINVAL);
+ }
+
+ BootloaderDmemDescV2 {
+ reserved: [0; 4],
+ signature: [0; 4],
+ ctx_dma: FALCON_DMAIDX_PHYS_SYS_NCOH,
+ code_dma_base: firmware_dma.dma_address(),
+ // `dst_start` is also valid as the source offset since the firmware DMA object is
+ // a mirror image of the target IMEM layout.
+ non_sec_code_off: imem_ns.dst_start,
+ non_sec_code_size: imem_ns.len,
+ // `dst_start` is also valid as the source offset since the firmware DMA object is
+ // a mirror image of the target IMEM layout.
+ sec_code_off: imem_sec.dst_start,
+ sec_code_size: imem_sec.len,
+ code_entry_point: 0,
+ // Start of data section is the added padding + the DMEM `src_start` field.
+ data_dma_base: firmware_dma
+ .dma_address()
+ .checked_add(u64::from_safe_cast(align_padding))
+ .and_then(|offset| offset.checked_add(dmem.src_start.into()))
+ .ok_or(EOVERFLOW)?,
+ data_size: dmem.len,
+ argc: 0,
+ argv: 0,
+ }
+ };
+
+ // The bootloader's code must be loaded in the area right below the first 64K of IMEM.
+ const BOOTLOADER_LOAD_CEILING: usize = sizes::SZ_64K;
+ let imem_dst_start = BOOTLOADER_LOAD_CEILING
+ .checked_sub(ucode.len())
+ .ok_or(EOVERFLOW)?;
+
+ let start_tag = u16::try_from(tlv.get_u32(b"STRT")?)?;
+
+ Ok(Self {
+ _firmware_dma: firmware_dma,
+ ucode,
+ dmem_desc,
+ brom_params: firmware.brom_params(),
+ imem_dst_start: u16::try_from(imem_dst_start)?,
+ start_tag,
+ })
+ }
+
+ /// Loads the bootloader into `falcon` and execute it.
+ ///
+ /// The bootloader will load the FWSEC firmware and then execute it. This function returns
+ /// after FWSEC has reached completion.
+ pub(crate) fn run(&self, dev: &Device<device::Bound>, falcon: &Falcon<'_, Gsp>) -> Result<()> {
+ // Reset falcon, load the firmware, and run it.
+ falcon
+ .reset()
+ .inspect_err(|e| dev_err!(dev, "Failed to reset GSP falcon: {:?}\n", e))?;
+ falcon
+ .pio_load(self)
+ .inspect_err(|e| dev_err!(dev, "Failed to load FWSEC firmware: {:?}\n", e))?;
+
+ // Configure DMA index for the bootloader to fetch the FWSEC firmware from system memory.
+ falcon.pfalcon.update(
+ regs::NV_PFALCON_FBIF_TRANSCFG::try_at(usize::from_safe_cast(self.dmem_desc.ctx_dma))
+ .ok_or(EINVAL)?,
+ |v| {
+ v.with_target(FalconFbifTarget::CoherentSysmem)
+ .with_mem_type(FalconFbifMemType::Physical)
+ },
+ );
+
+ let (mbox0, _) = falcon
+ .boot(Some(0), None)
+ .inspect_err(|e| dev_err!(dev, "Failed to boot FWSEC firmware: {:?}\n", e))?;
+ if mbox0 != 0 {
+ dev_err!(dev, "FWSEC firmware returned error {}\n", mbox0);
+ Err(EIO)
+ } else {
+ Ok(())
+ }
+ }
+}
+
+impl FalconFirmware for FwsecFirmwareWithBl<'_> {
+ type Target = Gsp;
+
+ fn brom_params(&self) -> FalconBromParams {
+ self.brom_params.clone()
+ }
+
+ fn boot_addr(&self) -> u32 {
+ // On V2 platforms, the boot address is extracted from the generic bootloader, because the
+ // gbl is what actually copies FWSEC into memory, so that is what needs to be booted.
+ u32::from(self.start_tag) << 8
+ }
+}
+
+impl FalconPioLoadable for FwsecFirmwareWithBl<'_> {
+ fn imem_sec_load_params(&self) -> Option<FalconPioImemLoadTarget<'_>> {
+ None
+ }
+
+ fn imem_ns_load_params(&self) -> Option<FalconPioImemLoadTarget<'_>> {
+ Some(FalconPioImemLoadTarget {
+ data: self.ucode.as_ref(),
+ dst_start: self.imem_dst_start,
+ secure: false,
+ start_tag: self.start_tag,
+ })
+ }
+
+ fn dmem_load_params(&self) -> FalconPioDmemLoadTarget<'_> {
+ FalconPioDmemLoadTarget {
+ data: self.dmem_desc.as_bytes(),
+ dst_start: 0,
+ }
+ }
+}
diff --git a/drivers/gpu/nova-core/firmware/gsp.rs b/drivers/gpu/nova-core/firmware/gsp.rs
new file mode 100644
index 000000000..341a8b19a
--- /dev/null
+++ b/drivers/gpu/nova-core/firmware/gsp.rs
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: GPL-2.0
+
+use kernel::{
+ device,
+ dma::{
+ Coherent,
+ DmaAddress, //
+ },
+ firmware,
+ prelude::*,
+ str::CString,
+};
+
+use crate::{
+ firmware::{
+ radix3::Radix3,
+ riscv::RiscvFirmware, //
+ tlv::{
+ request_tlv, //
+ Tlv,
+ },
+ },
+ gpu::Chipset,
+ num::FromSafeCast,
+};
+
+/// The GSP firmware image, its signatures, and the GSP bootloader.
+#[pin_data]
+pub(crate) struct GspFirmware<'a> {
+ /// The firmware image and the radix3 table that maps it.
+ #[pin]
+ radix3: Radix3<'a>,
+ /// Device-mapped GSP signatures matching the GPU's [`Chipset`].
+ pub(crate) signatures: Coherent<'a, [u8]>,
+ /// GSP bootloader, verifies the GSP firmware before loading and running it.
+ pub(crate) bootloader: RiscvFirmware<'a>,
+}
+
+impl<'a> GspFirmware<'a> {
+ /// Loads the GSP firmware binaries, map them into `dev`'s address-space, and creates the page
+ /// tables expected by the GSP bootloader to load it.
+ pub(crate) fn new(
+ dev: &'a device::Device<device::Bound>,
+ chipset: Chipset,
+ ) -> impl PinInit<Self, Error> + 'a {
+ pin_init::pin_init_scope(move || {
+ let firmware = request_tlv(dev, chipset, "gsp")?;
+ let tlv = Tlv::new(firmware.data())?;
+ dev_dbg!(dev, "loaded gsp firmware v{}\n", tlv.get_string(b"VERS")?);
+
+ 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 signatures = Coherent::from_slice(dev, tlv.get_bytes(b"SIGN")?, GFP_KERNEL)?;
+
+ Ok(try_pin_init!(Self {
+ radix3 <- Radix3::new(dev, fw_vvec),
+ signatures,
+ bootloader: {
+ let bl = request_tlv(dev, chipset, "gsp_bootloader")?;
+
+ RiscvFirmware::new(dev, &bl)?
+ },
+ }))
+ })
+ }
+
+ /// Returns the size of the firmware image, in bytes.
+ pub(crate) fn size(&self) -> usize {
+ self.radix3.size()
+ }
+
+ /// Returns the DMA address of the radix3 table that maps the firmware image.
+ pub(crate) fn radix3_dma_address(&self) -> DmaAddress {
+ self.radix3.dma_address()
+ }
+}
diff --git a/drivers/gpu/nova-core/firmware/gsp_fmc.rs b/drivers/gpu/nova-core/firmware/gsp_fmc.rs
new file mode 100644
index 000000000..94fcc86c7
--- /dev/null
+++ b/drivers/gpu/nova-core/firmware/gsp_fmc.rs
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! GSP-FMC (First Mutable Code) is loaded by FSP into GSP to serve as the loader and verifier of
+//! GSP-RM.
+
+use kernel::{
+ device,
+ dma::Coherent,
+ prelude::*, //
+};
+
+use crate::{
+ firmware::tlv::{
+ request_tlv, //
+ Tlv,
+ },
+ gpu::Chipset, //
+};
+
+/// Size of the GSP-FMC SHA-384 hash, in bytes.
+const FMC_HASH_SIZE: usize = 48;
+/// Maximum size of the GSP-FMC public key (RSA-3072), in bytes.
+///
+/// The `PKEY` tag may be shorter, so the remaining bytes are zero-padded.
+const FMC_PKEY_SIZE: usize = 384;
+/// Maximum size of the GSP-FMC signature (RSA-3072), in bytes.
+///
+/// The `SIGN` tag may be shorter, so the remaining bytes are zero-padded.
+const FMC_SIG_SIZE: usize = 384;
+
+/// Structure to hold FMC signatures.
+///
+/// C representation is used because this type is used for communication with the FSP.
+#[derive(Debug, Clone, Copy, Zeroable)]
+#[repr(C)]
+pub(crate) struct FmcSignatures {
+ pub(crate) hash384: [u8; FMC_HASH_SIZE],
+ pub(crate) public_key: [u8; FMC_PKEY_SIZE],
+ pub(crate) signature: [u8; FMC_SIG_SIZE],
+}
+
+pub(crate) struct GspFmcFirmware<'a> {
+ /// FMC firmware image data
+ pub(crate) fmc_image: Coherent<'a, [u8]>,
+ /// FMC firmware signatures.
+ pub(crate) fmc_sigs: KBox<FmcSignatures>,
+}
+
+impl<'a> GspFmcFirmware<'a> {
+ pub(crate) fn new(dev: &'a device::Device<device::Bound>, chipset: Chipset) -> Result<Self> {
+ let fw = request_tlv(dev, chipset, "fmc")?;
+ let tlv = Tlv::new(fw.data())?;
+ dev_dbg!(
+ dev,
+ "loaded GSP-FMC firmware v{}\n",
+ tlv.get_string(b"VERS")?
+ );
+
+ let fmc_image_data = tlv.get_bytes(b"BLOB")?;
+ let fmc_image = Coherent::from_slice(dev, fmc_image_data, GFP_KERNEL)?;
+
+ Ok(Self {
+ fmc_image,
+ fmc_sigs: Self::extract_fmc_signatures(&tlv, dev)?,
+ })
+ }
+
+ /// Extract FMC firmware signatures for Chain of Trust verification.
+ ///
+ /// Extracts real cryptographic signatures from FMC TLV firmware tags.
+ /// Returns signatures in a heap-allocated structure to prevent stack overflow.
+ fn extract_fmc_signatures(tlv: &Tlv<'_>, dev: &device::Device) -> Result<KBox<FmcSignatures>> {
+ let hash_section = tlv.get_bytes(b"HASH")?;
+ let pkey_section = tlv.get_bytes(b"PKEY")?;
+ let sig_section = tlv.get_bytes(b"SIGN")?;
+
+ // The hash section is a SHA-384 output: it must be exactly `FMC_HASH_SIZE` bytes.
+ if hash_section.len() != FMC_HASH_SIZE {
+ dev_err!(
+ dev,
+ "FMC hash section size {} != expected {}\n",
+ hash_section.len(),
+ FMC_HASH_SIZE
+ );
+ return Err(EINVAL);
+ }
+
+ // The key and signature sections are zero-padded to a fixed maximum, so they may be
+ // shorter, but must not exceed the destination buffers.
+ if pkey_section.len() > FMC_PKEY_SIZE {
+ dev_err!(
+ dev,
+ "FMC public key section size {} > maximum {}\n",
+ pkey_section.len(),
+ FMC_PKEY_SIZE
+ );
+ return Err(EINVAL);
+ }
+ if sig_section.len() > FMC_SIG_SIZE {
+ dev_err!(
+ dev,
+ "FMC signature section size {} > maximum {}\n",
+ sig_section.len(),
+ FMC_SIG_SIZE
+ );
+ return Err(EINVAL);
+ }
+
+ // Initialize the signatures in place to avoid building the large `FmcSignatures` on the
+ // stack, then fill each section from the firmware.
+ let signatures = KBox::init(
+ pin_init::init_zeroed::<FmcSignatures>().chain(|sigs| {
+ // PANIC: src and dst lengths are both `FMC_HASH_SIZE` (verified above).
+ sigs.hash384.copy_from_slice(hash_section);
+ // PANIC: dst is sliced to src.len(); src.len() <= `FMC_PKEY_SIZE` (verified above).
+ sigs.public_key[..pkey_section.len()].copy_from_slice(pkey_section);
+ // PANIC: dst is sliced to src.len(); src.len() <= `FMC_SIG_SIZE` (verified above).
+ sigs.signature[..sig_section.len()].copy_from_slice(sig_section);
+ Ok(())
+ }),
+ GFP_KERNEL,
+ )?;
+
+ Ok(signatures)
+ }
+}
diff --git a/drivers/gpu/nova-core/firmware/radix3.rs b/drivers/gpu/nova-core/firmware/radix3.rs
new file mode 100644
index 000000000..94235bd12
--- /dev/null
+++ b/drivers/gpu/nova-core/firmware/radix3.rs
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+//! The radix3 page table, through which firmware running on the GPU reads a buffer in system
+//! memory. LibOS, the operating system of the GSP, defines the format: three levels of
+//! [`GSP_PAGE_SIZE`] pages, each entry the little-endian DMA address of one page.
+//!
+//! ```text
+//! Level 0: one page, one entry -> the first level 1 page
+//! Level 1: pages of entries -> each entry a level 2 page
+//! Level 2: pages of entries -> each entry a page of the buffer
+//! ```
+
+use kernel::{
+ device,
+ dma::{
+ Coherent,
+ CoherentBox,
+ DataDirection,
+ DmaAddress, //
+ },
+ prelude::*,
+ scatterlist::{
+ Owned,
+ SGTable, //
+ },
+};
+
+use crate::{
+ gsp::GSP_PAGE_SIZE,
+ num::FromSafeCast, //
+};
+
+/// A radix3 page table and the data it maps.
+#[pin_data]
+pub(crate) struct Radix3<'a> {
+ /// The mapped data.
+ #[pin]
+ data: SGTable<Owned<VVec<u8>>>,
+ /// Level 2: one entry per page of `data`.
+ #[pin]
+ level2: SGTable<Owned<VVec<u8>>>,
+ /// Level 1: one entry per page of `level2`.
+ #[pin]
+ level1: SGTable<Owned<VVec<u8>>>,
+ /// Level 0: one page, whose single entry is the DMA address of the first `level1` page.
+ level0: Coherent<'a, [u64]>,
+ /// Length of `data`, in bytes.
+ size: usize,
+}
+
+impl<'a> Radix3<'a> {
+ /// Builds a radix3 page table over `data`, mapped for `dev` to read. May sleep.
+ pub(crate) fn new(
+ dev: &'a device::Device<device::Bound>,
+ data: VVec<u8>,
+ ) -> impl PinInit<Self, Error> + 'a {
+ let size = data.len();
+
+ pin_init::pin_init_scope(move || {
+ Ok(try_pin_init!(Self {
+ data <- SGTable::new(dev, data, DataDirection::ToDevice, GFP_KERNEL),
+ level2 <- {
+ build_lvl(&data)
+ .map(|l2| SGTable::new(dev, l2, DataDirection::ToDevice, GFP_KERNEL))?
+ },
+ level1 <- {
+ build_lvl(&level2)
+ .map(|l1| SGTable::new(dev, l1, DataDirection::ToDevice, GFP_KERNEL))?
+ },
+ level0: {
+ // Allocate the level 0 page table as a device-visible DMA object, and map the
+ // level 1 page table onto it.
+
+ // Fill level 1 page entry.
+ let level1_entry = level1.iter().next().ok_or(EINVAL)?;
+ let level1_entry_addr = level1_entry.dma_address();
+
+ // Create level 0 page table data and fill its first entry with the level 1
+ // table.
+ let mut level0 = CoherentBox::<'_, [u64]>::zeroed_slice(
+ dev,
+ GSP_PAGE_SIZE / size_of::<u64>(),
+ GFP_KERNEL
+ )?;
+ level0[0] = level1_entry_addr.to_le();
+
+ level0.into()
+ },
+ size,
+ }))
+ })
+ }
+
+ /// Returns the DMA address of the level 0 page, which is the address of the table.
+ pub(crate) fn dma_address(&self) -> DmaAddress {
+ self.level0.dma_address()
+ }
+
+ /// Returns the length of the mapped data, in bytes.
+ pub(crate) fn size(&self) -> usize {
+ self.size
+ }
+}
+
+/// Returns the size of the level that maps `sg_table`: one `u64` entry per [`GSP_PAGE_SIZE`]
+/// page of each DMA-mapped region, rounded up to whole 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 one level of the table over `sg_table`: one entry per [`GSP_PAGE_SIZE`] page of each
+/// DMA-mapped region, in region order. The level is a whole number of pages and every byte past
+/// the last entry is zero, because the booter reads a level a whole page at a time.
+///
+/// # Errors
+///
+/// - `ENOMEM` if the level cannot be allocated.
+/// - `EINVAL` if `sg_table` yields more entries than [`lvl_size`] sized the level 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_entry in sg_table.iter() {
+ let num_pages = usize::from_safe_cast(sg_entry.dma_len()).div_ceil(GSP_PAGE_SIZE);
+
+ for i in 0..num_pages {
+ let entry = sg_entry.dma_address()
+ + (u64::from_safe_cast(i) * u64::from_safe_cast(GSP_PAGE_SIZE));
+
+ entries
+ .next()
+ .ok_or(EINVAL)?
+ .copy_from_slice(&entry.to_le_bytes());
+ }
+ }
+
+ Ok(dst)
+}
diff --git a/drivers/gpu/nova-core/firmware/riscv.rs b/drivers/gpu/nova-core/firmware/riscv.rs
new file mode 100644
index 000000000..f05cfb1c6
--- /dev/null
+++ b/drivers/gpu/nova-core/firmware/riscv.rs
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Support for firmware binaries designed to run on a RISC-V core. Such firmwares files have a
+//! dedicated header.
+
+use kernel::{
+ device,
+ dma::Coherent,
+ firmware::Firmware,
+ prelude::*, //
+};
+
+use crate::firmware::tlv::Tlv;
+
+/// A parsed firmware for a RISC-V core, ready to be loaded and run.
+pub(crate) struct RiscvFirmware<'a> {
+ /// Offset at which the code starts in the firmware image.
+ pub(crate) code_offset: u32,
+ /// Offset at which the data starts in the firmware image.
+ pub(crate) data_offset: u32,
+ /// Offset at which the manifest starts in the firmware image.
+ pub(crate) manifest_offset: u32,
+ /// Application version.
+ pub(crate) app_version: u32,
+ /// Device-mapped firmware image.
+ pub(crate) ucode: Coherent<'a, [u8]>,
+}
+
+impl<'a> RiscvFirmware<'a> {
+ /// Parses the RISC-V firmware image contained in `fw`.
+ pub(crate) fn new(dev: &'a device::Device<device::Bound>, fw: &Firmware) -> Result<Self> {
+ let tlv = Tlv::new(fw.data())?;
+ dev_dbg!(
+ dev,
+ "loaded gsp bootloader firmware v{}\n",
+ tlv.get_string(b"VERS")?
+ );
+
+ let code_offset = tlv.get_u32(b"CDOF")?;
+ let data_offset = tlv.get_u32(b"DAOF")?;
+ let manifest_offset = tlv.get_u32(b"MFOF")?;
+ let app_version = tlv.get_u32(b"APPV")?;
+
+ let ucode = Coherent::from_slice(dev, tlv.get_bytes(b"BLOB")?, GFP_KERNEL)?;
+
+ Ok(Self {
+ ucode,
+ code_offset,
+ data_offset,
+ manifest_offset,
+ app_version,
+ })
+ }
+}
diff --git a/drivers/gpu/nova-core/firmware/tlv.rs b/drivers/gpu/nova-core/firmware/tlv.rs
new file mode 100644
index 000000000..7b879f13a
--- /dev/null
+++ b/drivers/gpu/nova-core/firmware/tlv.rs
@@ -0,0 +1,262 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
+use kernel::{
+ device,
+ firmware,
+ prelude::*,
+ str::CString, //
+};
+
+use crate::{
+ gpu,
+ num::*, //
+};
+
+/// Requests the GPU firmware TLV `name` suitable for `chipset`.
+pub(crate) fn request_tlv(
+ dev: &device::Device,
+ chipset: gpu::Chipset,
+ name: &str,
+) -> Result<firmware::Firmware> {
+ let chip_name = chipset.name();
+
+ let filename = CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{name}.tlv"))?;
+
+ dev_dbg!(dev, "loading firmware image {:?}\n", &filename);
+
+ firmware::Firmware::request(&filename, dev)
+}
+
+struct TlvBlock<'a> {
+ tag: [u8; 4],
+ value: &'a [u8],
+}
+
+/// On-wire TLV block header: 4-byte ASCII tag + little-endian payload length (bytes, excluding
+/// padding to a 4-byte boundary).
+struct TlvBlockHeader {
+ tag: [u8; 4],
+ length: usize,
+}
+
+impl TlvBlockHeader {
+ const SIZE: usize = size_of::<[u8; 4]>() + size_of::<u32>();
+
+ /// Parses the first [`Self::SIZE`] bytes of `hdr` (caller may pass a longer slice).
+ fn parse(hdr: &[u8]) -> Option<Self> {
+ let hdr = hdr.get(..Self::SIZE)?;
+ let tag = <[u8; 4]>::try_from(hdr.get(..4)?).ok()?;
+ if !tag.is_ascii() {
+ return None;
+ }
+ let len_arr = <[u8; 4]>::try_from(hdr.get(4..Self::SIZE)?).ok()?;
+ let length = u32_as_usize(u32::from_le_bytes(len_arr));
+ Some(Self { tag, length })
+ }
+}
+
+/// Iterator over the [`TlvBlock`]s of a [`Tlv`].
+///
+/// # Invariants
+///
+/// `pos` is a byte offset into `tlv.data` that always lies on a block boundary (in the sense
+/// of the [`Tlv`] invariant): it is either the start of a well-formed block, or equal to
+/// `tlv.data.len()` (end of iteration).
+struct TlvIter<'tlv, 'a> {
+ tlv: &'tlv Tlv<'a>,
+ pos: usize,
+}
+
+impl<'tlv, 'a> Iterator for TlvIter<'tlv, 'a> {
+ type Item = TlvBlock<'a>;
+
+ /// Returns the block starting at `self.pos` and advances the cursor past it, or [`None`]
+ /// once the cursor reaches the end of the data or encounters an error.
+ ///
+ /// Note that errors cannot actually occur because the data is validated in the constructor.
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.pos >= self.tlv.data.len() {
+ return None;
+ }
+
+ let tail = self.tlv.data.get(self.pos..)?;
+
+ let hdr = tail.get(..TlvBlockHeader::SIZE)?;
+ let header = TlvBlockHeader::parse(hdr)?;
+
+ let stored_size = header.length.checked_next_multiple_of(4)?;
+ let advance = TlvBlockHeader::SIZE.checked_add(stored_size)?;
+ let payload_end = TlvBlockHeader::SIZE.checked_add(header.length)?;
+
+ let value = tail
+ .get(..advance)?
+ .get(TlvBlockHeader::SIZE..payload_end)?;
+
+ // INVARIANT: by the `Tlv` invariant the block at `self.pos` occupies exactly `advance`
+ // bytes, so `self.pos + advance` is the next block boundary (or `data.len()`).
+ self.pos = self.pos.checked_add(advance)?;
+
+ Some(TlvBlock {
+ tag: header.tag,
+ value,
+ })
+ }
+}
+
+/// The post-header part of a validated TLV (type, length, value) firmware image.
+///
+/// TLV firmware images start with a 4-byte "NVFW" magic header, followed by a sequence of
+/// blocks. Each block has a 4-byte type tag, a 4-byte length field, and a data payload
+/// (value) whose stored size is the length rounded up to the nearest multiple of 4.
+///
+/// [`Self::new`] checks the magic header and walks every block: tags must be ASCII,
+/// lengths and padding must fit without overflow, and the byte stream after `NVFW` must
+/// be exactly partitionable into blocks (no trailing partial header or slack). After
+/// that, [`TlvIter`] only signals end-of-stream via [`None`], not parse failure.
+///
+/// Although the spec forbids duplicate tags, neither the constructor nor the iterator
+/// enforces this restriction. Instead, duplicate tags are simply ignored.
+///
+/// # Invariants
+///
+/// `data` is a validated TLV payload (the bytes *after* the `NVFW` magic): it is the exact
+/// concatenation of zero or more well-formed blocks, with no trailing partial header or slack.
+/// Consequently, any offset `o` into `data` that is a block boundary and satisfies
+/// `o < data.len()` is the start of a complete block whose header parses and whose stored
+/// extent (`TlvBlockHeader::SIZE + header.length.next_multiple_of(4)` bytes) lies within
+/// `data`. `data.len()` is itself a boundary.
+pub(crate) struct Tlv<'a> {
+ data: &'a [u8],
+}
+
+impl<'a> Tlv<'a> {
+ const MAGIC: &'static [u8; 4] = b"NVFW";
+
+ /// Parses `data` as a TLV firmware image, returning [`EINVAL`] if the image is malformed.
+ pub(crate) fn new(data: &'a [u8]) -> Result<Self> {
+ // Verify that the magic bytes exist and are the correct value
+ let magic_len = Self::MAGIC.len();
+ if data
+ .get(..magic_len)
+ .is_none_or(|magic| magic != Self::MAGIC)
+ {
+ return Err(EINVAL);
+ }
+
+ // The payload is the contiguous sequence of TLV blocks after the magic.
+ let payload = data.get(magic_len..).ok_or(EINVAL)?;
+
+ // The spec says every TLV must have a VERS tag.
+ let mut has_vers = false;
+
+ let mut rest = payload;
+ while !rest.is_empty() {
+ // Validate and extract the header (type, length).
+ let Some(header): Option<TlvBlockHeader> = rest
+ .get(..TlvBlockHeader::SIZE)
+ .and_then(TlvBlockHeader::parse)
+ else {
+ return Err(EINVAL);
+ };
+
+ has_vers |= header.tag == *b"VERS";
+
+ // The `length` field of a TLV block contains the actual byte length of the
+ // value, but each TLV block is aligned to a 4-byte boundary.
+ let Some(stored_size) = header.length.checked_next_multiple_of(4) else {
+ return Err(EINVAL);
+ };
+
+ let length = TlvBlockHeader::SIZE
+ .checked_add(stored_size)
+ .ok_or(EINVAL)?;
+
+ rest = rest.split_at_checked(length).ok_or(EINVAL)?.1;
+ }
+
+ if !has_vers {
+ return Err(EINVAL);
+ }
+
+ // INVARIANT: the loop above walked `payload` block-by-block. For each block, the
+ // header is parsed (`TlvBlockHeader::parse` rejects non-ASCII tags), and the
+ // stored extent (`SIZE + length.next_multiple_of(4)`) is computed without
+ // overflow and split off `rest` only when it fits. The loop ends only when `rest`
+ // is empty, so the byte stream is an exact concatenation of blocks with no
+ // trailing partial header or slack.
+ Ok(Self { data: payload })
+ }
+
+ fn iter(&self) -> TlvIter<'_, 'a> {
+ // INVARIANT: 0 is a block boundary, either the start of the first block,
+ // or `data.len()` when `data` is empty.
+ TlvIter { tlv: self, pos: 0 }
+ }
+
+ fn find(&self, tag: &[u8; 4]) -> Result<TlvBlock<'a>> {
+ self.iter().find(|b| b.tag == *tag).ok_or(EINVAL)
+ }
+
+ /// Return a slice of bytes.
+ ///
+ /// Returns `EINVAL` if the value is empty.
+ pub(crate) fn get_bytes(&self, tag: &[u8; 4]) -> Result<&'a [u8]> {
+ let tlv = self.find(tag)?;
+
+ // Treat empty value as an error, to avoid trying to parse nothing.
+ if tlv.value.is_empty() {
+ return Err(EINVAL); // TODO: Use ENODATA once available.
+ }
+
+ Ok(tlv.value)
+ }
+
+ /// Return a little-endian u32.
+ pub(crate) fn get_u32(&self, tag: &[u8; 4]) -> Result<u32> {
+ let tlv = self.find(tag)?;
+
+ tlv.value
+ .try_into()
+ .ok()
+ .map(u32::from_le_bytes)
+ .ok_or(EINVAL)
+ }
+
+ /// Return a string value.
+ pub(crate) fn get_string(&self, tag: &[u8; 4]) -> Result<&'a str> {
+ let tlv = self.find(tag)?;
+
+ let bytes = tlv.value;
+
+ // Strings can only contain printable ASCII characters.
+ if bytes.iter().any(|&b| !(32..127).contains(&b)) {
+ return Err(EINVAL);
+ }
+
+ core::str::from_utf8(bytes).map_err(|_| EINVAL)
+ }
+
+ /// Obtain the nth signature from a SIGN tag. If `index` is None,
+ /// then return the last signature.
+ pub(crate) fn get_signature(&self, index: Option<usize>) -> Result<&'a [u8]> {
+ let num_sigs: usize = match self.get_u32(b"NSIG")? {
+ 0 => return Err(EINVAL),
+ n => n.into_safe_cast(),
+ };
+
+ let sig_bytes = self.get_bytes(b"SIGN")?;
+
+ // Ensure that sig_bytes can be divided evenly into chunks.
+ if sig_bytes.len() % num_sigs != 0 {
+ return Err(EINVAL);
+ }
+
+ // num_sigs cannot be 0, and sig_bytes cannot be empty, so this cannot panic.
+ let sig_size = sig_bytes.len() / num_sigs;
+
+ let index = index.unwrap_or(num_sigs - 1);
+
+ sig_bytes.chunks_exact(sig_size).nth(index).ok_or(EINVAL)
+ }
+}