Skip to contentSkip to conversation

Transition Nova Core to TLV firmare images

PATCH Superseded Timur Tabi 4 participants 21 messages Jul 10 – Jul 29

Subsystems (11)

v5 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Timur Tabi

author
#0 lore raw

v5 cover Transition Nova Core to TLV firmare images

This patch set transitions nova-core to use the new "TLV" firmware image files, instead of the ones that Nouveau uses.

A prerequisite patch "rust: error: add remaining error codes" is required to compile. [1]

The current r570.144 images are a mix of binary headers and ELF files that are cumbersome to parse in Rust. There's a significant amount of code that just reads in a struct, extracts some offset, and uses it to find another struct, only to have nova-core use just a few fields.

The new format uses a sequence of tag/length/value fields that can be iterated over. The script that generates the TLV files, extract-firmware-nova.py, does the extra work to find the specific metadata needed by Nova and packages each one separately.

The TLV versions of r570.144 can be found here:

https://github.com/ttabi/linux-firmware-nova

along with instructions on how to install them. We are not planning on submitting these images to linux-firmware. Rather, if this patchset is accepted upstream, I expect the small handful of people who are actually working on Nova to grab and install these images, which needs to be done only once.

There are still opportunities for improvement. For example, I would like to get rid of more GPU-specific code, especially the GA100 quirks.

[1] https://lore.kernel.org/rust-for-linux/[email protected]/

v5:
1) Fixed imports in firmware.rs
2) Add VERS tag check to Tlv::new()
3) Added Vec::zeroed() method
4) Added BLID tag to gsp.tlv

Timur Tabi (8):
rust: alloc: add Vec::zeroed method
rust: firmware: add request_into_buf()
gpu: nova-core: add TLV parser for firmware files
gpu: nova-core: transition booter_load to TLV images
gpu: nova-core: transition gsp to TLV images
gpu: nova-core: transition gen_bootloader to TLV images
gpu: nova-core: transition fsp to TLV images
gpu: nova-core: update firmware module info for TLV images

 Documentation/gpu/nova/core/tlv.rst           | 187 ++++++++++
 drivers/gpu/nova-core/firmware.rs             | 302 +---------------
 drivers/gpu/nova-core/firmware/booter.rs      | 329 +++---------------
 drivers/gpu/nova-core/firmware/fsp.rs         |  88 +++--
 .../nova-core/firmware/fwsec/bootloader.rs    |  74 +---
 drivers/gpu/nova-core/firmware/gsp.rs         |  59 +---
 drivers/gpu/nova-core/firmware/riscv.rs       |  76 +---
 drivers/gpu/nova-core/firmware/tlv.rs         | 272 +++++++++++++++
 drivers/gpu/nova-core/fsp.rs                  |  11 +-
 drivers/gpu/nova-core/gsp/boot.rs             |   7 +-
 drivers/gpu/nova-core/gsp/hal/tu102.rs        |  13 +-
 rust/kernel/alloc/kvec.rs                     |  20 ++
 rust/kernel/firmware.rs                       |  49 ++-
 13 files changed, 699 insertions(+), 788 deletions(-)
 create mode 100644 Documentation/gpu/nova/core/tlv.rst
 create mode 100644 drivers/gpu/nova-core/firmware/tlv.rs

base-commit: d85845b64c0020b2812243a22fa79d57cc1c1e38
prerequisite-patch-id: 92c2d027299f0bc35d20918668f6874712d12f28

Signature · 1 line
2.54.0
author
#1 lore raw

PATCH v5 1/8 rust: alloc: add Vec::zeroed method

Add a constructor for kernel Vec that allocates a vector of a given length with all elements zero-initialized. Memory is allocated with the __GFP_ZERO flag, matching the existing KBox::zeroed() pattern.

---
 rust/kernel/alloc/kvec.rs | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
rust/kernel/alloc/kvec.rs +20 -0
index f7af62835aa8..4ca589919c1c 100644
@@ -9,6 +9,7 @@
         Vmalloc,
         VmallocPageIter, //
     },
+    flags::__GFP_ZERO,
     layout::ArrayLayout,
     AllocError,
     Allocator,
@@ -51,6 +52,8 @@
     }, //
 };
 
+use pin_init::Zeroable;
+
 mod errors;
 pub use self::errors::{InsertError, PushError, RemoveError};
 
@@ -532,6 +535,23 @@ pub fn with_capacity(capacity: usize, flags: Flags) -> Result<Self, AllocError>
         Ok(v)
     }
 
+    /// Creates a new [`Vec`] with `n` zero-initialized elements.
+    ///
+    /// New memory is allocated with `A` and the [`__GFP_ZERO`] flag.
+    pub fn zeroed(n: usize, flags: Flags) -> Result<Self, AllocError>
+    where
+        T: Zeroable,
+    {
+        let mut v = Self::with_capacity(n, flags | __GFP_ZERO)?;
+
+        // SAFETY:
+        // - `n <= capacity - len`: `with_capacity(n)` guarantees capacity >= n, len is 0.
+        // - All elements in `[0, n)` are initialized: `__GFP_ZERO` zeroes the allocation,
+        //   and `T: Zeroable` guarantees all-zeroes is a valid bit pattern.
+        unsafe { v.inc_len(n) };
+        Ok(v)
+    }
+
     /// Creates a `Vec<T, A>` from a pointer, a length and a capacity using the allocator `A`.
     ///
     /// # Examples
Signature · 1 line
2.54.0
#2 lore raw

Re: [PATCH v5 1/8] rust: alloc: add Vec::zeroed method

rust/kernel/alloc/kvec.rs pub fn with_capacity(capacity: usize, flags: Flags) -> Result<Self, AllocError> · line 540

Quoted 4 lines · Timur Tabi
rust/kernel/alloc/kvec.rs +3 -0
+    /// Creates a new [`Vec`] with `n` zero-initialized elements.
+    ///
+    /// New memory is allocated with `A` and the [`__GFP_ZERO`] flag.

This may be obvious since we pass flags and the function only does this, but the sentence (here and in the commit message) sounds a bit like only that flag is used.

Cheers,
Miguel

author
#3 lore raw

Re: [PATCH v5 1/8] rust: alloc: add Vec::zeroed method

Quoted 7 lines · Miguel Ojeda
Quoted 3 lines

+    /// Creates a new [Vec] with n zero-initialized elements. +    ///
+    /// New memory is allocated with A and the [__GFP_ZERO] flag.

This may be obvious since we pass flags and the function only does this, but the sentence (here and in the commit message) sounds a bit like only that flag is used.

Ok, I'll reword it in v6.

maintainer Reviewed-by on v5 1/8
#4 lore raw

Re: [PATCH v5 1/8] rust: alloc: add Vec::zeroed method

In reply to Timur Tabi
Quoted 31 lines · Timur Tabi

Add a constructor for kernel Vec that allocates a vector of a given length with all elements zero-initialized. Memory is allocated with the __GFP_ZERO flag, matching the existing KBox::zeroed() pattern.

---
 rust/kernel/alloc/kvec.rs | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
rust/kernel/alloc/kvec.rs +3 -0
index f7af62835aa8..4ca589919c1c 100644
@@ -9,6 +9,7 @@
         Vmalloc,
         VmallocPageIter, //
     },
+    flags::__GFP_ZERO,
     layout::ArrayLayout,
     AllocError,
     Allocator,
@@ -51,6 +52,8 @@
     }, //
 };
 
+use pin_init::Zeroable;
+
 mod errors;
 pub use self::errors::{InsertError, PushError, RemoveError};
 

rust/kernel/alloc/kvec.rs pub fn with_capacity(capacity: usize, flags: Flags) -> Result<Self, AllocError> · line 540

Quoted 6 lines
rust/kernel/alloc/kvec.rs +3 -0
@@ -532,6 +535,23 @@ pub fn with_capacity(capacity: usize, flags: Flags) -> Result<Self, AllocError>
         Ok(v)
     }
 
+    /// Creates a new [`Vec`] with `n` zero-initialized elements.
+    ///
+    /// New memory is allocated with `A` and the [`__GFP_ZERO`] flag.

Every other method I've looked at has an # Examples paragraph in its doccomment, can you add a short example to this one as well?

With this, and Miguel's comment taken into account:

author
#5 lore raw

PATCH v5 2/8 rust: firmware: add request_into_buf()

In reply to Timur Tabi

Add request_into_buf(), a Rust wrapper around the request_firmware_into_buf() function. This variant loads the firmware image directly into a caller-provided buffer rather than a kernel-allocated one.

---
 rust/kernel/firmware.rs | 49 +++++++++++++++++++++++++++++++++++++++--
 1 file changed, 47 insertions(+), 2 deletions(-)
rust/kernel/firmware.rs +47 -2
index 71168d8004e2..84b499ca822f 100644
@@ -7,13 +7,14 @@
 use crate::{
     bindings,
     device::Device,
-    error::Error,
-    error::Result,
+    error::to_result,
     ffi,
     str::{CStr, CStrExt as _},
 };
 use core::ptr::NonNull;
 
+use kernel::prelude::*;
+
 /// # Invariants
 ///
 /// One of the following: `bindings::request_firmware`, `bindings::firmware_request_nowarn`,
@@ -120,6 +121,50 @@ fn drop(&mut self) {
     }
 }
 
+/// Load firmware directly into the caller-provided `buf`.
+///
+/// On success the firmware image has been copied into `buf`; the caller accesses the data
+/// through `buf` itself.
+///
+/// This is intentionally a stand-alone function rather than a `Firmware` constructor. For
+/// the `into_buf` path, the firmware data lives in the caller's `buf`, not in a
+/// kernel-owned buffer, so returning a `Firmware` would expose `Firmware::data()` as a
+/// second handle aliasing `buf` (and `release_firmware()` does not free `buf` anyway).
+pub fn request_into_buf(name: &CStr, dev: &Device, buf: &mut [u8]) -> Result {
+    // `as_mut_ptr()` on an empty slice returns a non-NULL pointer to
+    // memory which the loader does not own. Passing that pointer with `size == 0`
+    // makes the loader believe that it is buffer it allocated itself, so when
+    // `release_firmware()` is called, it will vfree the pointer and trigger a
+    // bug. Reject empty slices to avoid this situation.
+    if buf.is_empty() {
+        return Err(EINVAL);
+    }
+
+    let mut fw: *mut bindings::firmware = core::ptr::null_mut();
+    let pfw: *mut *mut bindings::firmware = &mut fw;
+    let pfw: *mut *const bindings::firmware = pfw.cast();
+
+    // SAFETY: `pfw` is a valid pointer to a NULL initialized `bindings::firmware` pointer.
+    // `name` and `dev` are valid as by their type invariants. `buf` is a valid writable
+    // buffer of `buf.len()` bytes.\
+    to_result(unsafe {
+        bindings::request_firmware_into_buf(
+            pfw,
+            name.as_char_ptr(),
+            dev.as_raw(),
+            buf.as_mut_ptr().cast(),
+            buf.len(),
+        )
+    })?;
+
+    // The firmware bytes are now in `buf`, which the caller owns, so we don't need
+    // the kernel to hang on to it any more.
+    // SAFETY: `fw` is a valid pointer returned by `request_firmware_into_buf`.
+    unsafe { bindings::release_firmware(fw) };
+
+    Ok(())
+}
+
 // SAFETY: `Firmware` only holds a pointer to a C `struct firmware`, which is safe to be used from
 // any thread.
 unsafe impl Send for Firmware {}
Signature · 1 line
2.54.0
#6 lore raw

Re: [PATCH v5 2/8] rust: firmware: add request_into_buf()

On Sat Jul 11, 2026 at 8:04 AM JST, Timur Tabi wrote:
<snip>

Quoted 20 lines
rust/kernel/firmware.rs +16 -0
@@ -120,6 +121,50 @@ fn drop(&mut self) {
     }
 }
 
+/// Load firmware directly into the caller-provided `buf`.
+///
+/// On success the firmware image has been copied into `buf`; the caller accesses the data
+/// through `buf` itself.
+///
+/// This is intentionally a stand-alone function rather than a `Firmware` constructor. For
+/// the `into_buf` path, the firmware data lives in the caller's `buf`, not in a
+/// kernel-owned buffer, so returning a `Firmware` would expose `Firmware::data()` as a
+/// second handle aliasing `buf` (and `release_firmware()` does not free `buf` anyway).
+pub fn request_into_buf(name: &CStr, dev: &Device, buf: &mut [u8]) -> Result {
+    // `as_mut_ptr()` on an empty slice returns a non-NULL pointer to
+    // memory which the loader does not own. Passing that pointer with `size == 0`
+    // makes the loader believe that it is buffer it allocated itself, so when
+    // `release_firmware()` is called, it will vfree the pointer and trigger a
+    // bug. Reject empty slices to avoid this situation.
+    if buf.is_empty() {

rust/kernel/firmware.rs fn drop(&mut self) { · line 149

Quoted 10 lines
rust/kernel/firmware.rs +10 -0
+        return Err(EINVAL);
+    }
+
+    let mut fw: *mut bindings::firmware = core::ptr::null_mut();
+    let pfw: *mut *mut bindings::firmware = &mut fw;
+    let pfw: *mut *const bindings::firmware = pfw.cast();
+
+    // SAFETY: `pfw` is a valid pointer to a NULL initialized `bindings::firmware` pointer.
+    // `name` and `dev` are valid as by their type invariants. `buf` is a valid writable
+    // buffer of `buf.len()` bytes.\

Stray \ here on the last line.

#7 lore raw

Re: [PATCH v5 2/8] rust: firmware: add request_into_buf()

In reply to Timur Tabi
Quoted 18 lines · Timur Tabi

Add request_into_buf(), a Rust wrapper around the request_firmware_into_buf() function. This variant loads the firmware image directly into a caller-provided buffer rather than a kernel-allocated one.

---
 rust/kernel/firmware.rs | 49 +++++++++++++++++++++++++++++++++++++++--
 1 file changed, 47 insertions(+), 2 deletions(-)
rust/kernel/firmware.rs +0 -0
index 71168d8004e2..84b499ca822f 100644
@@ -7,13 +7,14 @@
 use crate::{
     bindings,

rust/kernel/firmware.rs line 16

Quoted 10 lines
rust/kernel/firmware.rs +2 -2
     device::Device,
-    error::Error,
-    error::Result,
+    error::to_result,
     ffi,
     str::{CStr, CStrExt as _},
 };
 use core::ptr::NonNull;
 
+use kernel::prelude::*;

Also this should be moved to the crate import block above.

author
#8 lore raw

PATCH v5 3/8 gpu: nova-core: add TLV parser for firmware files

In reply to Timur Tabi

TLV (type, length, value) files are the new image format used by Nova to encapsulate firmware images and their metadata. Unlike the firmware files for previous versions of the firmware, TLV filenames are not versioned, and they have a .tlv suffix.

Add function request_tlv() to load TLV firmware images.

Add the Tlv struct and supporting types for parsing TLV (type, length, value) firmware images. TLV files begin with a 4-byte magic header, which must be "NVFW" for Nvidia firmware files. This is followed by a sequence of blocks each containing a 4-byte ASCII tag, a 4-byte little-endian length, and a payload padded to a 4-byte boundary.

Tlv::new() validates the entire image up front, so that the iterator can subsequently yield blocks without fallible parsing.

Also add accessor methods for the various encoded types that will be used by the driver.

---
 Documentation/gpu/nova/core/tlv.rst   | 187 ++++++++++++++++++
 drivers/gpu/nova-core/firmware.rs     |   1 +
 drivers/gpu/nova-core/firmware/tlv.rs | 274 ++++++++++++++++++++++++++
 3 files changed, 462 insertions(+)
 create mode 100644 Documentation/gpu/nova/core/tlv.rst
 create mode 100644 drivers/gpu/nova-core/firmware/tlv.rs
Documentation/gpu/nova/core/tlv.rst new file +187 -0
new file mode 100644
index 000000000000..9e8c08727977
@@ -0,0 +1,187 @@
+.. SPDX-License-Identifier: (GPL-2.0+ OR MIT)
+
+==================================
+TLV Tags in Nova Firmware Images
+==================================
+
+Nova firmware images use a Type-Length-Value (TLV) format to encapsulate
+firmware components and metadata. The TLV file begins with a 4-byte "magic"
+header that contains the string "NVFW".  Following the header is a sequence of
+TLV blocks.
+
+Each block consists of a 4-byte tag of ASCII characters, a 4-byte length
+encoded as a little-endian unsigned integer, and a sequence of bytes, the size
+of which is equal to the length rounded up to the next multiple of 4.
+
+The driver code that reads the TLV and uses its contents is called the parser.
+It is the responsibility of the parser to handle missing or malformed tags,
+lengths, and values in the TLV.
+
+::
+
+    +------+------+------+------+
+    |  'N' |  'V' |  'F' |  'W' |  Magic header
+    +------+------+------+------+
+    |  Tag (4 bytes, ASCII)     |  TLV block 0
+    +---------------------------+
+    |  Length (4 bytes, LE)     |
+    +---------------------------+
+    |                           |
+    |  Value (length bytes,     |
+    |  padded to 4-byte align)  |
+    |                           |
+    +---------------------------+
+    |  Tag (4 bytes, ASCII)     |  TLV block 1
+    +---------------------------+
+    |  Length (4 bytes, LE)     |
+    +---------------------------+
+    |                           |
+    |  Value (length bytes,     |
+    |  padded to 4-byte align)  |
+    |                           |
+    +---------------------------+
+    |         ...               |  More TLV blocks
+    +---------------------------+
+
+Tags and Length
+===============
+TLV tags are always four-character words, with all letters being upper case.
+Duplicate tags are not allowed.
+
+Lengths of zero are allowed and indicate that the tag is a boolean.  That is,
+presence of the tag indicates ``True`` and absence indicates ``False``.
+
+A TLV file may contain additional tags not described in this document.
+
+Values
+======
+Values are one of three types.  The type is not encoded in the format; rather,
+the parser expects a given tag to have a value of a given type.
+
+1) Integers, encoded in 32-bit or 64-bit little-endian format.
+2) Strings, encoded as-is and required to be ASCII only and without a null terminator.
+3) An array of bytes, for binary data.
+
+Common Tags
+===========
+These tags are shared across firmware types and carry the same meaning
+wherever they appear.  Unlike the firmware-specific tags below, a common tag
+is reserved: its meaning is fixed and may never be redefined for a particular
+firmware type.
+
+``VERS`` (string)
+    Human-readable firmware version string, indicates the version of
+    the firmware.  Present in all TLV files.
+
+A TLV image must contain either a single ``BLOB`` tag (firmware embedded
+inline) or a ``SIZE``/``FILE`` pair (firmware stored in a separate file).
+
+``BLOB`` (bytes)
+    If the firmware microcode binary is stored in the TLV, this tag contains
+    the actual firmware image bytes.
+
+``FILE`` (string)
+    If the firmware binary is stored as a separate file, this tag contains the
+    name of that file, which is required to be in the same directory as the TLV,
+    so no paths are allowed in the filename.  This tag is always paired with
+    ``SIZE``, so as to allow the driver to pre-allocate the buffer before
+    loading the file.
+
+``SIZE`` (u32)
+    Total size in bytes of the firmware image to be loaded from the companion
+    file named by ``FILE``.  This tag is mandatory if ``FILE`` exists, so the
+    size of the firmware image must be known when the TLV is created.  If the
+    firmware image is updated and its size changes, then the TLV must be
+    updated with it.
+
+GSP Firmware Tags
+=================
+``SIGN`` (bytes)
+    Cryptographic signature for the GSP firmware.
+
+``BLID`` (bytes)
+    The build ID, extracted from the ".note.gnu.build-id" section.
+
+Booter Firmware Tags
+====================
+``DAOF`` (u32) - ``os_data_offset``
+    OS data section offset within the firmware image (absolute byte offset).
+    Maps to the DMEM load source.
+
+``DASZ`` (u32) - ``os_data_size``
+    OS data section size in bytes.
+
+``CDOF`` (u32) - ``os_code_offset``
+    OS code section offset within the firmware image (absolute byte offset).
+    Maps to the non-secure IMEM load source.
+
+``CDSZ`` (u32) - ``os_code_size``
+    OS code section size in bytes.
+
+``PLOC`` (u32) - ``patch_loc``
+    Signature patch location -- byte offset within the firmware image where the
+    selected signature should be written.
+
+``FUSE`` (u32) - ``fuse_version``
+    Fuse version of the firmware, used with the hardware fuse register to
+    select the correct signature index.
+
+``ENID`` (u32) - ``engine_id``
+    Engine ID mask identifying the falcon engine this firmware targets.
+
+``UCID`` (u32) - ``ucode_id``
+    Microcode ID used together with the engine ID to query hardware signature
+    fuse registers.
+
+``A0CO`` (u32) - ``app0_code_offset``
+    App0 code offset -- start of the secure code region within the firmware
+    image. Used as the IMEM secure section source.
+
+``A0CS`` (u32) - ``app0_code_size``
+    App0 code size in bytes.
+
+``NSIG`` (u32) - ``num_sigs``
+    Number of signatures included in the ``SIGN`` tag.  A value of 0 indicates
+    unsigned firmware and that there is no ``SIGN`` tag.
+
+``SIGN`` (bytes)
+    Concatenated array of firmware signatures. The size of each signature is
+    the total length of the ``SIGN`` value divided by ``NSIG``. The correct
+    signature is selected using the fuse-version-derived index.
+
+Generic Bootloader Tags
+=======================
+``CDSZ`` (u32) - ``code_size``
+    Size in bytes of the bootloader code to copy from the ``BLOB`` tag and
+    PIO-load into falcon IMEM.
+
+``STRT`` (u32) - ``start_tag``
+    Start tag identifying the IMEM block where execution begins.  The falcon
+    boot address is derived as ``start_tag << 8``.
+
+GSP Bootloader Tags
+===================
+``CDOF`` (u32) - ``code_offset``
+    Offset within the firmware image at which the code section starts.
+
+``DAOF`` (u32) - ``data_offset``
+    Offset within the firmware image at which the data section starts.
+
+``MFOF`` (u32) - ``manifest_offset``
+    Offset within the firmware image at which the manifest starts.
+
+``APPV`` (u32) - ``app_version``
+    Application version of the firmware.
+
+FMC Firmware Tags
+=================
+``HASH`` (bytes)
+    SHA-384 hash of the FMC firmware, exactly 48 bytes long.
+
+``PKEY`` (bytes)
+    Public key used to verify the FMC firmware. At most 384 bytes (RSA-3072),
+    but may be shorter.
+
+``SIGN`` (bytes)
+    Signature of the FMC firmware. At most 384 bytes (RSA-3072), but may
+    be shorter.
\ No newline at end of file
drivers/gpu/nova-core/firmware.rs +1 -0
index a94820a3b335..c0cd06579643 100644
@@ -32,6 +32,7 @@
 pub(crate) mod fwsec;
 pub(crate) mod gsp;
 pub(crate) mod riscv;
+pub(crate) mod tlv;
 
 pub(crate) const FIRMWARE_VERSION: &str = "570.144";
 
drivers/gpu/nova-core/firmware/tlv.rs new file +274 -0

274 lines not on this page · raw message

Signature · 1 line
2.54.0
#9 lore raw

Re: [PATCH v5 3/8] gpu: nova-core: add TLV parser for firmware files

Quoted 16 lines · Timur Tabi

TLV (type, length, value) files are the new image format used by Nova to encapsulate firmware images and their metadata. Unlike the firmware files for previous versions of the firmware, TLV filenames are not versioned, and they have a .tlv suffix.

Add function request_tlv() to load TLV firmware images.

Add the Tlv struct and supporting types for parsing TLV (type, length, value) firmware images. TLV files begin with a 4-byte magic header, which must be "NVFW" for Nvidia firmware files. This is followed by a sequence of blocks each containing a 4-byte ASCII tag, a 4-byte little-endian length, and a payload padded to a 4-byte boundary.

Tlv::new() validates the entire image up front, so that the iterator can subsequently yield blocks without fallible parsing.

Quoted 6 lines

Also add accessor methods for the various encoded types that will be used by the driver.

---
 Documentation/gpu/nova/core/tlv.rst   | 187 ++++++++++++++++++

We should add a link to this new document in
Documentation/gpu/nova/index.rst.

Quoted 53 lines
 drivers/gpu/nova-core/firmware.rs     |   1 +
 drivers/gpu/nova-core/firmware/tlv.rs | 274 ++++++++++++++++++++++++++
 3 files changed, 462 insertions(+)
 create mode 100644 Documentation/gpu/nova/core/tlv.rst
 create mode 100644 drivers/gpu/nova-core/firmware/tlv.rs
Documentation/gpu/nova/core/tlv.rst new file +41 -0
new file mode 100644
index 000000000000..9e8c08727977
@@ -0,0 +1,187 @@
+.. SPDX-License-Identifier: (GPL-2.0+ OR MIT)
+
+==================================
+TLV Tags in Nova Firmware Images
+==================================
+
+Nova firmware images use a Type-Length-Value (TLV) format to encapsulate
+firmware components and metadata. The TLV file begins with a 4-byte "magic"
+header that contains the string "NVFW".  Following the header is a sequence of
+TLV blocks.
+
+Each block consists of a 4-byte tag of ASCII characters, a 4-byte length
+encoded as a little-endian unsigned integer, and a sequence of bytes, the size
+of which is equal to the length rounded up to the next multiple of 4.
+
+The driver code that reads the TLV and uses its contents is called the parser.
+It is the responsibility of the parser to handle missing or malformed tags,
+lengths, and values in the TLV.
+
+::
+
+    +------+------+------+------+
+    |  'N' |  'V' |  'F' |  'W' |  Magic header
+    +------+------+------+------+
+    |  Tag (4 bytes, ASCII)     |  TLV block 0
+    +---------------------------+
+    |  Length (4 bytes, LE)     |
+    +---------------------------+
+    |                           |
+    |  Value (length bytes,     |
+    |  padded to 4-byte align)  |
+    |                           |
+    +---------------------------+
+    |  Tag (4 bytes, ASCII)     |  TLV block 1
+    +---------------------------+
+    |  Length (4 bytes, LE)     |
+    +---------------------------+
+    |                           |
+    |  Value (length bytes,     |
+    |  padded to 4-byte align)  |
+    |                           |

Documentation/gpu/nova/core/tlv.rst line 51

Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10 -0
+    +---------------------------+
+    |         ...               |  More TLV blocks
+    +---------------------------+
+
+Tags and Length
+===============
+TLV tags are always four-character words, with all letters being upper case.
+Duplicate tags are not allowed.
+
+Lengths of zero are allowed and indicate that the tag is a boolean.  That is,

Let's mention "Payloads of length zero" to be precise what length this is about.

Documentation/gpu/nova/core/tlv.rst line 63

Quoted 12 lines
Documentation/gpu/nova/core/tlv.rst new file +12 -0
+presence of the tag indicates ``True`` and absence indicates ``False``.
+
+A TLV file may contain additional tags not described in this document.
+
+Values
+======
+Values are one of three types.  The type is not encoded in the format; rather,
+the parser expects a given tag to have a value of a given type.
+
+1) Integers, encoded in 32-bit or 64-bit little-endian format.
+2) Strings, encoded as-is and required to be ASCII only and without a null terminator.
+3) An array of bytes, for binary data.

I guess booleans adds a fourth value type?

Quoted 30 lines
Documentation/gpu/nova/core/tlv.rst new file +30 -0
+
+Common Tags
+===========
+These tags are shared across firmware types and carry the same meaning
+wherever they appear.  Unlike the firmware-specific tags below, a common tag
+is reserved: its meaning is fixed and may never be redefined for a particular
+firmware type.
+
+``VERS`` (string)
+    Human-readable firmware version string, indicates the version of
+    the firmware.  Present in all TLV files.
+
+A TLV image must contain either a single ``BLOB`` tag (firmware embedded
+inline) or a ``SIZE``/``FILE`` pair (firmware stored in a separate file).
+
+``BLOB`` (bytes)
+    If the firmware microcode binary is stored in the TLV, this tag contains
+    the actual firmware image bytes.
+
+``FILE`` (string)
+    If the firmware binary is stored as a separate file, this tag contains the
+    name of that file, which is required to be in the same directory as the TLV,
+    so no paths are allowed in the filename.  This tag is always paired with
+    ``SIZE``, so as to allow the driver to pre-allocate the buffer before
+    loading the file.
+
+``SIZE`` (u32)
+    Total size in bytes of the firmware image to be loaded from the companion
+    file named by ``FILE``.  This tag is mandatory if ``FILE`` exists, so the
+    size of the firmware image must be known when the TLV is created.  If the

Documentation/gpu/nova/core/tlv.rst line 103

Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10 -0
+    firmware image is updated and its size changes, then the TLV must be
+    updated with it.
+
+GSP Firmware Tags
+=================
+``SIGN`` (bytes)
+    Cryptographic signature for the GSP firmware.
+
+``BLID`` (bytes)
+    The build ID, extracted from the ".note.gnu.build-id" section.

Should this be a string by any chance?

Quoted 32 lines
Documentation/gpu/nova/core/tlv.rst new file +32 -0
+
+Booter Firmware Tags
+====================
+``DAOF`` (u32) - ``os_data_offset``
+    OS data section offset within the firmware image (absolute byte offset).
+    Maps to the DMEM load source.
+
+``DASZ`` (u32) - ``os_data_size``
+    OS data section size in bytes.
+
+``CDOF`` (u32) - ``os_code_offset``
+    OS code section offset within the firmware image (absolute byte offset).
+    Maps to the non-secure IMEM load source.
+
+``CDSZ`` (u32) - ``os_code_size``
+    OS code section size in bytes.
+
+``PLOC`` (u32) - ``patch_loc``
+    Signature patch location -- byte offset within the firmware image where the
+    selected signature should be written.
+
+``FUSE`` (u32) - ``fuse_version``
+    Fuse version of the firmware, used with the hardware fuse register to
+    select the correct signature index.
+
+``ENID`` (u32) - ``engine_id``
+    Engine ID mask identifying the falcon engine this firmware targets.
+
+``UCID`` (u32) - ``ucode_id``
+    Microcode ID used together with the engine ID to query hardware signature
+    fuse registers.
+

Documentation/gpu/nova/core/tlv.rst line 145

Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10 -0
+``A0CO`` (u32) - ``app0_code_offset``
+    App0 code offset -- start of the secure code region within the firmware
+    image. Used as the IMEM secure section source.
+
+``A0CS`` (u32) - ``app0_code_size``
+    App0 code size in bytes.
+
+``NSIG`` (u32) - ``num_sigs``
+    Number of signatures included in the ``SIGN`` tag.  A value of 0 indicates
+    unsigned firmware and that there is no ``SIGN`` tag.

In patch 4 booter.rs says "Booter is always signed", which contradicts this definition. We had a non-signed path in the original code; why not preserve it? The current firmware files do not make use of it, but the point of specifying things here is to make the code future-proof in case we introduce or enable unsigned firmwares in the future; so let's make the code religiously follow the spec.

Quoted 78 lines
Documentation/gpu/nova/core/tlv.rst new file +42 -0
+
+``SIGN`` (bytes)
+    Concatenated array of firmware signatures. The size of each signature is
+    the total length of the ``SIGN`` value divided by ``NSIG``. The correct
+    signature is selected using the fuse-version-derived index.
+
+Generic Bootloader Tags
+=======================
+``CDSZ`` (u32) - ``code_size``
+    Size in bytes of the bootloader code to copy from the ``BLOB`` tag and
+    PIO-load into falcon IMEM.
+
+``STRT`` (u32) - ``start_tag``
+    Start tag identifying the IMEM block where execution begins.  The falcon
+    boot address is derived as ``start_tag << 8``.
+
+GSP Bootloader Tags
+===================
+``CDOF`` (u32) - ``code_offset``
+    Offset within the firmware image at which the code section starts.
+
+``DAOF`` (u32) - ``data_offset``
+    Offset within the firmware image at which the data section starts.
+
+``MFOF`` (u32) - ``manifest_offset``
+    Offset within the firmware image at which the manifest starts.
+
+``APPV`` (u32) - ``app_version``
+    Application version of the firmware.
+
+FMC Firmware Tags
+=================
+``HASH`` (bytes)
+    SHA-384 hash of the FMC firmware, exactly 48 bytes long.
+
+``PKEY`` (bytes)
+    Public key used to verify the FMC firmware. At most 384 bytes (RSA-3072),
+    but may be shorter.
+
+``SIGN`` (bytes)
+    Signature of the FMC firmware. At most 384 bytes (RSA-3072), but may
+    be shorter.
\ No newline at end of file
drivers/gpu/nova-core/firmware.rs +1 -0
index a94820a3b335..c0cd06579643 100644
@@ -32,6 +32,7 @@
 pub(crate) mod fwsec;
 pub(crate) mod gsp;
 pub(crate) mod riscv;
+pub(crate) mod tlv;
 
 pub(crate) const FIRMWARE_VERSION: &str = "570.144";
 
drivers/gpu/nova-core/firmware/tlv.rs new file +17 -0
new file mode 100644
index 000000000000..5dfd2dd814f8
@@ -0,0 +1,274 @@
+// 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`.
+#[expect(dead_code)]

drivers/gpu/nova-core/firmware/tlv.rs line 27

Quoted 10 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +10 -0
+pub(crate) fn request_tlv(
+    dev: &device::Device,
+    chipset: gpu::Chipset,
+    name: &str,
+) -> Result<firmware::Firmware> {
+    let chip_name = chipset.name();
+
+    dev_dbg!(
+        dev,
+        "loading firmware image {}/gsp/{}.tlv\n",

This is missing nvidia in the path. To avoid issue I would suggest building the CString earlier and using it both here and in the try_from_fmt statement below.

<...>

drivers/gpu/nova-core/firmware/tlv.rs line 224

Quoted 13 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +13 -0
+    /// Return a slice of bytes.  Returns ENODATA 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(ENODATA);
+        }
+
+        Ok(tlv.value)
+    }
+
+    // Return a little-endian u32.

Doccomment should use ///.

Quoted 10 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +10 -0
+    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)
+    }
+

drivers/gpu/nova-core/firmware/tlv.rs line 244

Quoted 10 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +10 -0
+    /// 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;
+
+        // To make sure the value actually is a string, ensure it's all ASCII.
+        if !bytes.is_ascii() {
+            return Err(EINVAL);
+        }

The spec also says that NULL characters are invalid; we should test for || bytes.contains(&0) as well here.

Quoted 16 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +16 -0
+
+        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 {

drivers/gpu/nova-core/firmware/tlv.rs line 270

Quoted 10 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +10 -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: usize = match index {
+            None => num_sigs - 1,
+            Some(index) => index,
+        };

This can be a one-liner:

  let index = index.unwrap_or(num_sigs - 1);
author
#10 lore raw

Re: [PATCH v5 3/8] gpu: nova-core: add TLV parser for firmware files

Quoted 10 lines · Alexandre Courbot

Documentation/gpu/nova/core/tlv.rst line 51

Quoted 7 lines
Documentation/gpu/nova/core/tlv.rst new file +6 -0
+Tags and Length
+===============
+TLV tags are always four-character words, with all letters being upper case.
+Duplicate tags are not allowed.
+
+Lengths of zero are allowed and indicate that the tag is a boolean.  That is,

Let's mention "Payloads of length zero" to be precise what length this is about.

I'm going to remove the stuff about booleans. We don't use them in Nova, and when I tried to add support for them it was just messy. Just because a tag is missing, that doesn't mean that it's false. It could be just missing, which would be something to check for.

The upcoming nvoc stuff does have a boolean tag, but it's not in the TLV yet. I don't have a real ETA for it, so there will be a time period where we support r615 but some tags will appear later. So we need to be able to check for a missing tag vs tag==false.

Quoted 10 lines

Documentation/gpu/nova/core/tlv.rst line 103

Quoted 8 lines
Documentation/gpu/nova/core/tlv.rst new file +8 -0
+
+GSP Firmware Tags
+=================
+``SIGN`` (bytes)
+    Cryptographic signature for the GSP firmware.
+
+``BLID`` (bytes)
+    The build ID, extracted from the ".note.gnu.build-id" section.

Should this be a string by any chance?

Yes, thanks.

Quoted 5 lines
Quoted 5 lines
Documentation/gpu/nova/core/tlv.rst new file +3 -0
+
+Booter Firmware Tags
+====================

...

Quoted 11 lines
Quoted 4 lines

+
+``NSIG`` (u32) - ``num_sigs``
+    Number of signatures included in the ``SIGN`` tag.  A value of 0 indicates +    unsigned firmware and that there is no ``SIGN`` tag.

In patch 4 booter.rs says "Booter is always signed", which contradicts this definition. We had a non-signed path in the original code; why not preserve it? The current firmware files do not make use of it, but the point of specifying things here is to make the code future-proof in case we introduce or enable unsigned firmwares in the future; so let's make the code religiously follow the spec.

Well, booter (both load and unload) always is signed. The script even enforces that.  The current unsigned code in booter.rs has never been exercised, so we can't really say it's correct.

I can change the documentation here to not mention NSIG==0 as a possibility. When I wrote this text, I hadn't noticed that NSIG is never 0.

We are never going to introduce unsigned booter firmware. For one thing, Hopper and later have already replaced booter with fmc, so this code is already legacy.

If it turns out that some future version of GSP-RM does add an unsigned booter, we would need to change the script and probably do more than just call no_patch_signature().

Quoted 5 lines
Quoted 5 lines

+    /// 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;

Quoted 8 lines
Quoted 5 lines

+
+        // To make sure the value actually is a string, ensure it's all ASCII. +        if !bytes.is_ascii() {
+            return Err(EINVAL);
+        }

The spec also says that NULL characters are invalid; we should test for || bytes.contains(&0) as well here.

Hmmm... I wonder if I should expand the definition to exclude all characters less than ASCII 32?

I was debating is_ascii_graphic() but that also excludes blank spaces. There is value in insisting that the tag is clearly printable.

Thoughts?

Quoted 1 line
#11 lore raw

Re: [PATCH v5 3/8] gpu: nova-core: add TLV parser for firmware files

Quoted 1 line · Timur Tabi

On Mon, 2026-07-27 at 20:31 +0900, Alexandre Courbot wrote:

...

Quoted 11 lines
Quoted 10 lines
Quoted 3 lines

+``NSIG`` (u32) - ``num_sigs``
+    Number of signatures included in the ``SIGN`` tag.  A value of 0 indicates +    unsigned firmware and that there is no ``SIGN`` tag.

In patch 4 booter.rs says "Booter is always signed", which contradicts this definition. We had a non-signed path in the original code; why not preserve it? The current firmware files do not make use of it, but the point of specifying things here is to make the code future-proof in case we introduce or enable unsigned firmwares in the future; so let's make the code religiously follow the spec.

Quoted 6 lines

Well, booter (both load and unload) always is signed. The script even enforces that.  The current unsigned code in booter.rs has never been exercised, so we can't really say it's correct.

I can change the documentation here to not mention NSIG==0 as a possibility. When I wrote this text, I hadn't noticed that NSIG is never 0.

Yes, that is what I'd recommend here, too.

Quoted 3 lines

We are never going to introduce unsigned booter firmware. For one thing, Hopper and later have already replaced booter with fmc, so this code is already legacy.

++1, this is not ever going to change.

Quoted 3 lines

If it turns out that some future version of GSP-RM does add an unsigned booter, we would need to change the script and probably do more than just call no_patch_signature().

Very true. And IMHO it is wildly unlikely that we would end up with any sort of unsigned booter thing. So it's best to just remove all mention of it.

...

Quoted 8 lines
Quoted 7 lines
Quoted 4 lines

+        // To make sure the value actually is a string, ensure it's all ASCII. +        if !bytes.is_ascii() {
+            return Err(EINVAL);
+        }

The spec also says that NULL characters are invalid; we should test for || bytes.contains(&0) as well here.

Quoted 6 lines

Hmmm... I wonder if I should expand the definition to exclude all characters less than ASCII 32?

I was debating is_ascii_graphic() but that also excludes blank spaces. There is value in insisting that the tag is clearly printable.

Thoughts?

Agree that there is value in enforcing printable tags. We could something like this if we want to allow spaces:

   bytes.iter().all(|b| b.is_ascii_graphic() || *b == b' ')

...but is there really-truly a need to support spaces? (I haven't checked on that, but it surprises me at first.)

thanks,

Signature · 1 line
John Hubbard
author
#12 lore raw

Re: [PATCH v5 3/8] gpu: nova-core: add TLV parser for firmware files

Quoted 7 lines · John Hubbard

Agree that there is value in enforcing printable tags. We could something like this if we want to allow spaces:

    bytes.iter().all(|b| b.is_ascii_graphic() || *b == b' ')

...but is there really-truly a need to support spaces? (I haven't checked on that, but it surprises me at first.)

For tags, no.

But this code is for the value in a string tag, so there could conceivably be spaces.

I posted a v6 which addresses this.

author
#13 lore raw

PATCH v5 4/8 gpu: nova-core: transition booter_load to TLV images

In reply to Timur Tabi

Switch the booter firmware loader from the legacy binary format to the TLV format. This change requires the new TLV versions of the r570.144 firmware images.

The new TLV format has all of the metadata needed by Nova encoded as separate tags, eliminating the need to parse legacy firmware headers such as HsHeaderV2 and HsSignatureParams. All of the structs and code for parsing those headers is therefore deleted.

---
 drivers/gpu/nova-core/firmware.rs        |  15 +-
 drivers/gpu/nova-core/firmware/booter.rs | 329 ++++-------------------
 drivers/gpu/nova-core/firmware/tlv.rs    |   2 -
 drivers/gpu/nova-core/gsp/hal/tu102.rs   |  13 +-
 4 files changed, 62 insertions(+), 297 deletions(-)
drivers/gpu/nova-core/firmware.rs +1 -14
index c0cd06579643..7634fe292446 100644
@@ -21,10 +21,7 @@
         FalconFirmware, //
     },
     gpu,
-    num::{
-        FromSafeCast,
-        IntoSafeCast, //
-    },
+    num::IntoSafeCast,
 };
 
 pub(crate) mod booter;
@@ -388,16 +385,6 @@ fn new(fw: &'a firmware::Firmware) -> Result<Self> {
             .map(|hdr| Self { hdr, fw })
             .ok_or(EINVAL)
     }
-
-    /// Returns the data payload of the firmware, or `None` if the data range is out of bounds of
-    /// the firmware image.
-    fn data(&self) -> Option<&[u8]> {
-        let fw_start = usize::from_safe_cast(self.hdr.data_offset);
-        let fw_size = usize::from_safe_cast(self.hdr.data_size);
-        let fw_end = fw_start.checked_add(fw_size)?;
-
-        self.fw.get(fw_start..fw_end)
-    }
 }
 
 pub(crate) struct ModInfoBuilder<const N: usize>(firmware::ModInfoBuilder<N>);
drivers/gpu/nova-core/firmware/booter.rs +57 -272

389 lines not on this page · raw message

drivers/gpu/nova-core/firmware/tlv.rs +0 -2
index 5dfd2dd814f8..357edd179c92 100644
@@ -14,7 +14,6 @@
 };
 
 /// Requests the GPU firmware TLV `name` suitable for `chipset`.
-#[expect(dead_code)]
 pub(crate) fn request_tlv(
     dev: &device::Device,
     chipset: gpu::Chipset,
@@ -135,7 +134,6 @@ pub(crate) struct Tlv<'a> {
     data: &'a [u8],
 }
 
-#[expect(dead_code)]
 impl<'a> Tlv<'a> {
     const MAGIC: &'static [u8; 4] = b"NVFW";
 
drivers/gpu/nova-core/gsp/hal/tu102.rs +4 -9
index ff71b45b5432..33dcf3eab162 100644
@@ -27,8 +27,7 @@
             FwsecCommand,
             FwsecFirmware, //
         },
-        gsp::GspFirmware,
-        FIRMWARE_VERSION, //
+        gsp::GspFirmware, //
     },
     gpu::Chipset,
     gsp::{
@@ -112,7 +111,6 @@ fn build(
                     dev,
                     BooterKind::Unloader,
                     chipset,
-                    FIRMWARE_VERSION,
                     sec2_falcon,
                 )?,
             },
@@ -313,14 +311,11 @@ fn boot<'a>(
             "Using SEC2 to load and run the booter_load firmware...\n"
         );
 
-        BooterFirmware::new(
+        BooterFirmware::new(dev, BooterKind::Loader, chipset, sec2_falcon)?.run(
             dev,
-            BooterKind::Loader,
-            chipset,
-            FIRMWARE_VERSION,
             sec2_falcon,
-        )?
-        .run(dev, sec2_falcon, wpr_meta)?;
+            wpr_meta,
+        )?;
 
         Ok(unload_guard)
     }
Signature · 1 line
2.54.0
author
#14 lore raw

PATCH v5 5/8 gpu: nova-core: transition gsp to TLV images

In reply to Timur Tabi

Switch the GSP firmware loader from the legacy binary format to the TLV format. This change requires the new TLV versions of the r570.144 firmware images.

Unlike the other TLV firmware images, gsp.tlv contains a pointer to the actual GSP firmware file instead of its contents. This allows each small gsp.tlv file to contain the distinct metadata for each GPU while still allowing the very large gsp.bin to be shared by all GPUs.

One key piece of metadata is the signature. The legacy GSP firmware image is an ELF file that contains multiple sections that needed to be parsed, and the driver needed to determine which section is relevant for the GPU. Instead, gsp.tlv contains the pre-processed metadata, so all the driver needs to do is to extract it.

---
 drivers/gpu/nova-core/firmware.rs       | 23 --------
 drivers/gpu/nova-core/firmware/gsp.rs   | 59 +++++++------------
 drivers/gpu/nova-core/firmware/riscv.rs | 76 ++++++-------------------
 drivers/gpu/nova-core/gsp/boot.rs       |  7 +--
 4 files changed, 38 insertions(+), 127 deletions(-)
drivers/gpu/nova-core/firmware.rs +0 -23
index 7634fe292446..06b74d82d698 100644
@@ -364,29 +364,6 @@ struct BinHdr {
 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
 unsafe impl FromBytes for BinHdr {}
 
-// A firmware blob starting with a `BinHdr`.
-struct BinFirmware<'a> {
-    hdr: BinHdr,
-    fw: &'a [u8],
-}
-
-impl<'a> BinFirmware<'a> {
-    /// Interpret `fw` as a firmware image starting with a [`BinHdr`], and returns the
-    /// corresponding [`BinFirmware`] that can be used to extract its payload.
-    fn new(fw: &'a firmware::Firmware) -> Result<Self> {
-        const BIN_MAGIC: u32 = 0x10de;
-        let fw = fw.data();
-
-        fw.get(0..size_of::<BinHdr>())
-            // Extract header.
-            .and_then(BinHdr::from_bytes_copy)
-            // Validate header.
-            .filter(|hdr| hdr.bin_magic == BIN_MAGIC)
-            .map(|hdr| Self { hdr, fw })
-            .ok_or(EINVAL)
-    }
-}
-
 pub(crate) struct ModInfoBuilder<const N: usize>(firmware::ModInfoBuilder<N>);
 
 impl<const N: usize> ModInfoBuilder<N> {
drivers/gpu/nova-core/firmware/gsp.rs +19 -40

96 lines not on this page · raw message

drivers/gpu/nova-core/firmware/riscv.rs +17 -59

96 lines not on this page · raw message

drivers/gpu/nova-core/gsp/boot.rs +2 -5
index 152093aafae6..56658faccdf7 100644
@@ -19,10 +19,7 @@
         Falcon, //
     },
     fb::FbLayout,
-    firmware::{
-        gsp::GspFirmware,
-        FIRMWARE_VERSION, //
-    },
+    firmware::gsp::GspFirmware,
     gsp::{
         cmdq::Cmdq,
         commands,
@@ -110,7 +107,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, FIRMWARE_VERSION), GFP_KERNEL)?;
+        let gsp_fw = KBox::pin_init(GspFirmware::new(dev, chipset), GFP_KERNEL)?;
 
         let fb_layout = FbLayout::new(chipset, bar, &gsp_fw)?;
         dev_dbg!(dev, "{:#x?}\n", fb_layout);
Signature · 1 line
2.54.0
#15 lore raw

Re: [PATCH v5 5/8] gpu: nova-core: transition gsp to TLV images

On Sat Jul 11, 2026 at 8:04 AM JST, Timur Tabi wrote:
<...>

Quoted 13 lines
drivers/gpu/nova-core/firmware/gsp.rs +1 -0
index 99a302bae567..185cae0689a3 100644
@@ -8,6 +8,7 @@
         DataDirection,
         DmaAddress, //
     },
+    firmware,
     prelude::*,
     scatterlist::{
         Owned,

drivers/gpu/nova-core/firmware/gsp.rs line 26

Quoted 10 lines
drivers/gpu/nova-core/firmware/gsp.rs +5 -1
@@ -17,13 +18,14 @@
 
 use crate::{
     firmware::{
-        elf,
         riscv::RiscvFirmware, //
+        tlv::{
+            request_tlv, //
+            Tlv,
+        },
+        CString,

CString should be imported from kernel, not crate. I guess this only works because crate::firmware also imports it and we are below it.

<...>

Quoted 20 lines
drivers/gpu/nova-core/firmware/gsp.rs +1 -15
-impl RmRiscvUCodeDesc {
-    /// Interprets the header of `bin_fw` as a [`RmRiscvUCodeDesc`] and returns it.
-    ///
-    /// Fails if the header pointed at by `bin_fw` is not within the bounds of the firmware image.
-    fn new(bin_fw: &BinFirmware<'_>) -> Result<Self> {
-        let offset = usize::from_safe_cast(bin_fw.hdr.header_offset);
-        let end = offset.checked_add(size_of::<Self>()).ok_or(EINVAL)?;
-
-        bin_fw
-            .fw
-            .get(offset..end)
-            .and_then(Self::from_bytes_copy)
-            .ok_or(EINVAL)
-    }
-}
+use crate::firmware::tlv::Tlv;
 
 /// A parsed firmware for a RISC-V core, ready to be loaded and run.
 pub(crate) struct RiscvFirmware {

drivers/gpu/nova-core/firmware/gsp.rs pub(crate) struct RiscvFirmware { · line 73

Quoted 4 lines
drivers/gpu/nova-core/firmware/gsp.rs +0 -1
@@ -70,26 +27,27 @@ pub(crate) struct RiscvFirmware {
 }
 
 impl RiscvFirmware {
-    /// Parses the RISC-V firmware image contained in `fw`.

Why remove this doccomment?

author
#16 lore raw

PATCH v5 6/8 gpu: nova-core: transition gen_bootloader to TLV images

In reply to Timur Tabi

Switch the generic bootloader firmware loader from the legacy binary format to the TLV format. This change requires the new TLV versions of the r570.144 firmware images.

---
 drivers/gpu/nova-core/firmware.rs             | 24 +-----
 .../nova-core/firmware/fwsec/bootloader.rs    | 74 +++++--------------
 2 files changed, 19 insertions(+), 79 deletions(-)
drivers/gpu/nova-core/firmware.rs +1 -23
index 06b74d82d698..4b41368a6b2f 100644
@@ -11,8 +11,7 @@
     device,
     firmware,
     prelude::*,
-    str::CString,
-    transmute::FromBytes, //
+    str::CString, //
 };
 
 use crate::{
@@ -343,27 +342,6 @@ fn no_patch_signature(self) -> FirmwareObject<F, Signed> {
     }
 }
 
-/// Header common to most firmware files.
-#[repr(C)]
-#[derive(Debug, Clone)]
-struct BinHdr {
-    /// Magic number, must be `0x10de`.
-    bin_magic: u32,
-    /// Version of the header.
-    bin_ver: u32,
-    /// Size in bytes of the binary (to be ignored).
-    bin_size: u32,
-    /// Offset of the start of the application-specific header.
-    header_offset: u32,
-    /// Offset of the start of the data payload.
-    data_offset: u32,
-    /// Size in bytes of the data payload.
-    data_size: u32,
-}
-
-// SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
-unsafe impl FromBytes for BinHdr {}
-
 pub(crate) struct ModInfoBuilder<const N: usize>(firmware::ModInfoBuilder<N>);
 
 impl<const N: usize> ModInfoBuilder<N> {
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +18 -56

117 lines not on this page · raw message

Signature · 1 line
2.54.0
author
#17 lore raw

PATCH v5 7/8 gpu: nova-core: transition fsp to TLV images

In reply to Timur Tabi

Switch the FSP firmware loaders from the legacy ELF32 format to the new TLV format. This change requires the new TLV versions of the r570.144 firmware images.

Because we are no longer loading ELF images, we can also delete the ELF parser.

Also remove function request_firmware() as this was the last user.

---
 drivers/gpu/nova-core/firmware.rs     | 219 --------------------------
 drivers/gpu/nova-core/firmware/fsp.rs |  88 +++++------
 drivers/gpu/nova-core/fsp.rs          |  11 +-
 3 files changed, 45 insertions(+), 273 deletions(-)
drivers/gpu/nova-core/firmware.rs +0 -219
index 4b41368a6b2f..4ea9eef46354 100644
@@ -8,7 +8,6 @@
 use core::ops::Deref;
 
 use kernel::{
-    device,
     firmware,
     prelude::*,
     str::CString, //
@@ -32,19 +31,6 @@
 
 pub(crate) const FIRMWARE_VERSION: &str = "570.144";
 
-/// Requests the GPU firmware `name` suitable for `chipset`, with version `ver`.
-fn request_firmware(
-    dev: &device::Device,
-    chipset: gpu::Chipset,
-    name: &str,
-    ver: &str,
-) -> Result<firmware::Firmware> {
-    let chip_name = chipset.name();
-
-    CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{name}-{ver}.bin"))
-        .and_then(|path| firmware::Firmware::request(&path, dev))
-}
-
 /// Structure used to describe some firmwares, notably FWSEC-FRTS.
 #[repr(C)]
 #[derive(Debug, Clone, FromBytes)]
@@ -396,208 +382,3 @@ pub(crate) const fn create(
         this.0
     }
 }
-
-/// Ad-hoc and temporary module to extract sections from ELF images.
-///
-/// Some firmware images are currently packaged as ELF files, where sections names are used as keys
-/// to specific and related bits of data. Future firmware versions are scheduled to move away from
-/// that scheme before nova-core becomes stable, which means this module will eventually be
-/// removed.
-mod elf {
-    use kernel::{
-        bindings,
-        prelude::*,
-        transmute::FromBytes, //
-    };
-
-    /// Trait to abstract over ELF header differences.
-    trait ElfHeader: FromBytes {
-        fn shnum(&self) -> u16;
-        fn shoff(&self) -> u64;
-        fn shstrndx(&self) -> u16;
-    }
-
-    /// Trait to abstract over ELF section-header differences.
-    trait ElfSectionHeader: FromBytes {
-        fn name(&self) -> u32;
-        fn offset(&self) -> u64;
-        fn size(&self) -> u64;
-    }
-
-    /// Trait describing a matching ELF header and section-header format.
-    trait ElfFormat {
-        type Header: ElfHeader;
-        type SectionHeader: ElfSectionHeader;
-    }
-
-    /// Newtype to provide a [`FromBytes`] implementation.
-    #[repr(transparent)]
-    struct Elf64Hdr(bindings::elf64_hdr);
-    // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
-    unsafe impl FromBytes for Elf64Hdr {}
-
-    impl ElfHeader for Elf64Hdr {
-        fn shnum(&self) -> u16 {
-            self.0.e_shnum
-        }
-
-        fn shoff(&self) -> u64 {
-            self.0.e_shoff
-        }
-
-        fn shstrndx(&self) -> u16 {
-            self.0.e_shstrndx
-        }
-    }
-
-    #[repr(transparent)]
-    struct Elf64SHdr(bindings::elf64_shdr);
-    // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
-    unsafe impl FromBytes for Elf64SHdr {}
-
-    impl ElfSectionHeader for Elf64SHdr {
-        fn name(&self) -> u32 {
-            self.0.sh_name
-        }
-
-        fn offset(&self) -> u64 {
-            self.0.sh_offset
-        }
-
-        fn size(&self) -> u64 {
-            self.0.sh_size
-        }
-    }
-
-    struct Elf64Format;
-
-    impl ElfFormat for Elf64Format {
-        type Header = Elf64Hdr;
-        type SectionHeader = Elf64SHdr;
-    }
-
-    /// Newtype to provide [`FromBytes`] and [`ElfHeader`] implementations for ELF32.
-    #[repr(transparent)]
-    struct Elf32Hdr(bindings::elf32_hdr);
-    // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
-    unsafe impl FromBytes for Elf32Hdr {}
-
-    impl ElfHeader for Elf32Hdr {
-        fn shnum(&self) -> u16 {
-            self.0.e_shnum
-        }
-
-        fn shoff(&self) -> u64 {
-            u64::from(self.0.e_shoff)
-        }
-
-        fn shstrndx(&self) -> u16 {
-            self.0.e_shstrndx
-        }
-    }
-
-    /// Newtype to provide [`FromBytes`] and [`ElfSectionHeader`] implementations for ELF32.
-    #[repr(transparent)]
-    struct Elf32SHdr(bindings::elf32_shdr);
-    // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
-    unsafe impl FromBytes for Elf32SHdr {}
-
-    impl ElfSectionHeader for Elf32SHdr {
-        fn name(&self) -> u32 {
-            self.0.sh_name
-        }
-
-        fn offset(&self) -> u64 {
-            u64::from(self.0.sh_offset)
-        }
-
-        fn size(&self) -> u64 {
-            u64::from(self.0.sh_size)
-        }
-    }
-
-    struct Elf32Format;
-
-    impl ElfFormat for Elf32Format {
-        type Header = Elf32Hdr;
-        type SectionHeader = Elf32SHdr;
-    }
-
-    /// Returns a NULL-terminated string from the ELF image at `offset`.
-    fn elf_str(elf: &[u8], offset: u64) -> Option<&str> {
-        let idx = usize::try_from(offset).ok()?;
-        let bytes = elf.get(idx..)?;
-        CStr::from_bytes_until_nul(bytes).ok()?.to_str().ok()
-    }
-
-    fn elf_section_generic<'a, F>(elf: &'a [u8], name: &str) -> Option<&'a [u8]>
-    where
-        F: ElfFormat,
-    {
-        let hdr = F::Header::from_bytes(elf.get(0..size_of::<F::Header>())?)?;
-
-        let shdr_num = usize::from(hdr.shnum());
-        let shdr_start = usize::try_from(hdr.shoff()).ok()?;
-        let shdr_end = shdr_num
-            .checked_mul(size_of::<F::SectionHeader>())
-            .and_then(|v| v.checked_add(shdr_start))?;
-
-        // Get all the section headers as an iterator over byte chunks.
-        let shdr_bytes = elf.get(shdr_start..shdr_end)?;
-        let mut shdr_iter = shdr_bytes.chunks_exact(size_of::<F::SectionHeader>());
-
-        // Get the strings table.
-        let strhdr = shdr_iter
-            .clone()
-            .nth(usize::from(hdr.shstrndx()))
-            .and_then(F::SectionHeader::from_bytes)?;
-
-        // Find the section which name matches `name` and return it.
-        shdr_iter.find_map(|sh_bytes| {
-            let sh = F::SectionHeader::from_bytes(sh_bytes)?;
-            let name_offset = strhdr.offset().checked_add(u64::from(sh.name()))?;
-            let section_name = elf_str(elf, name_offset)?;
-
-            if section_name != name {
-                return None;
-            }
-
-            let start = usize::try_from(sh.offset()).ok()?;
-            let end = usize::try_from(sh.size())
-                .ok()
-                .and_then(|sz| start.checked_add(sz))?;
-
-            elf.get(start..end)
-        })
-    }
-
-    /// Extract the section with name `name` from the ELF64 image `elf`.
-    fn elf64_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> {
-        elf_section_generic::<Elf64Format>(elf, name)
-    }
-
-    /// Extract the section with name `name` from the ELF32 image `elf`.
-    fn elf32_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> {
-        elf_section_generic::<Elf32Format>(elf, name)
-    }
-
-    /// Automatically detects ELF32 vs ELF64 based on the ELF header.
-    pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> {
-        // ELF identification: a 4-byte magic followed by a class byte (32- vs 64-bit).
-        const ELFMAG: &[u8] = b"\x7fELF";
-        const SELFMAG: usize = ELFMAG.len();
-        const EI_CLASS: usize = 4;
-        const ELFCLASS32: u8 = 1;
-        const ELFCLASS64: u8 = 2;
-
-        if elf.get(0..SELFMAG) != Some(ELFMAG) {
-            return None;
-        }
-
-        match *elf.get(EI_CLASS)? {
-            ELFCLASS32 => elf32_section(elf, name),
-            ELFCLASS64 => elf64_section(elf, name),
-            _ => None,
-        }
-    }
-}
drivers/gpu/nova-core/firmware/fsp.rs +41 -47

143 lines not on this page · raw message

drivers/gpu/nova-core/fsp.rs +4 -7
index 08f4acef09f6..654b5b4214a9 100644
@@ -32,12 +32,9 @@
         Falcon, //
     },
     fb::FbLayout,
-    firmware::{
-        fsp::{
-            FmcSignatures,
-            FspFirmware, //
-        },
-        FIRMWARE_VERSION, //
+    firmware::fsp::{
+        FmcSignatures,
+        FspFirmware, //
     },
     gpu::Chipset,
     gsp::GspFmcBootParams,
@@ -246,7 +243,7 @@ pub(crate) fn wait_secure_boot(
 
         let hal = hal::fsp_hal(chipset).ok_or(ENOTSUPP)?;
         let falcon = Falcon::<FspEngine>::new(dev, chipset, bar)?;
-        let fsp_fw = FspFirmware::new(dev, chipset, FIRMWARE_VERSION)?;
+        let fsp_fw = FspFirmware::new(dev, chipset)?;
 
         read_poll_timeout(
             || Ok(hal.fsp_boot_status(bar)),
Signature · 1 line
2.54.0
author
#18 lore raw

PATCH v5 8/8 gpu: nova-core: update firmware module info for TLV images

In reply to Timur Tabi

Now that nova-core loads the TLV firmware images, update the firmware module info to specify those files.

Also remove FIRMWARE_VERSION as it is no longer used.

---
 drivers/gpu/nova-core/firmware.rs | 20 ++++++++------------
 1 file changed, 8 insertions(+), 12 deletions(-)
drivers/gpu/nova-core/firmware.rs +8 -12
index 4ea9eef46354..2969f5a9f114 100644
@@ -29,8 +29,6 @@
 pub(crate) mod riscv;
 pub(crate) mod tlv;
 
-pub(crate) const FIRMWARE_VERSION: &str = "570.144";
-
 /// Structure used to describe some firmwares, notably FWSEC-FRTS.
 #[repr(C)]
 #[derive(Debug, Clone, FromBytes)]
@@ -338,10 +336,7 @@ const fn make_entry_file(self, chipset: &str, fw: &str) -> Self {
                 .push("nvidia/")
                 .push(chipset)
                 .push("/gsp/")
-                .push(fw)
-                .push("-")
-                .push(FIRMWARE_VERSION)
-                .push(".bin"),
+                .push(fw),
         )
     }
 
@@ -349,20 +344,21 @@ const fn make_entry_chipset(self, chipset: gpu::Chipset) -> Self {
         let name = chipset.name();
 
         let this = self
-            .make_entry_file(name, "bootloader")
-            .make_entry_file(name, "gsp");
+            .make_entry_file(name, "gsp_bootloader.tlv")
+            .make_entry_file(name, "gsp.tlv")
+            .make_entry_file(name, "gsp.bin");
 
         // FSP-based chipsets (Hopper, Blackwell and later) boot the GSP via the FMC image loaded by
         // FSP. Older chipsets use the SEC2 booter instead.
         let this = if chipset.uses_fsp() {
-            this.make_entry_file(name, "fmc")
+            this.make_entry_file(name, "fmc.tlv")
         } else {
-            this.make_entry_file(name, "booter_load")
-                .make_entry_file(name, "booter_unload")
+            this.make_entry_file(name, "booter_load.tlv")
+                .make_entry_file(name, "booter_unload.tlv")
         };
 
         if chipset.needs_fwsec_bootloader() {
-            this.make_entry_file(name, "gen_bootloader")
+            this.make_entry_file(name, "gen_bootloader.tlv")
         } else {
             this
         }
Signature · 1 line
2.54.0
#19 lore raw

Re: [PATCH v5 8/8] gpu: nova-core: update firmware module info for TLV images

Quoted 6 lines · Timur Tabi

Now that nova-core loads the TLV firmware images, update the firmware module info to specify those files.

Also remove FIRMWARE_VERSION as it is no longer used.

Doing this in one go creates a potential bisectability issue: there are points in the history where the firmware entries do not reflect the actual firmware files used.

Can you fold this patch gradually into the respective patches (4-7) to avoid this?

Also, preemptively: note that the latest drm-rust-next introduces a helper boot_firmware_files function to get a list of files relevant to a given chipset. This list will have to be updated to include the .tlv suffix.

author
#20 lore raw

Re: [PATCH v5 8/8] gpu: nova-core: update firmware module info for TLV images

Quoted 11 lines · Alexandre Courbot
Quoted 6 lines · Timur Tabi

Now that nova-core loads the TLV firmware images, update the firmware module info to specify those files.

Also remove FIRMWARE_VERSION as it is no longer used.

Doing this in one go creates a potential bisectability issue: there are points in the history where the firmware entries do not reflect the actual firmware files used.

True, but that only used for making initramfs. I have a hard time believing that this will actually matter.

Quoted 2 lines

Can you fold this patch gradually into the respective patches (4-7) to avoid this?

Sure, but that will create a lot of churn in make_entry_chipset() and boot_firmware_files().

Quoted 4 lines

Also, preemptively: note that the latest drm-rust-next introduces a helper boot_firmware_files function to get a list of files relevant to a given chipset. This list will have to be updated to include the .tlv suffix.

Already done for v6.