Skip to contentSkip to conversation

Transition Nova Core to TLV firmare images

PATCH Superseded Timur Tabi 5 participants 40 messages Jul 2 – Jul 9

Subsystems (10)

v3 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Timur Tabi

author
#0 lore raw

v3 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.

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.

v3:
1) Added test for empty slices in request_into_buf
2) Added [expect(dead_code)]
3) Documented handling of duplicate TLV tags

Timur Tabi (7):
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           | 182 +++++++++
 drivers/gpu/nova-core/firmware.rs             | 302 +--------------
 drivers/gpu/nova-core/firmware/booter.rs      | 344 ++++--------------
 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         | 227 ++++++++++++
 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/firmware.rs                       |  47 +++
 12 files changed, 644 insertions(+), 786 deletions(-)
 create mode 100644 Documentation/gpu/nova/core/tlv.rst
 create mode 100644 drivers/gpu/nova-core/firmware/tlv.rs

base-commit: 24d2581fd911d34f88153af59d3b0d6bc5f07adf

Signature · 1 line
2.54.0
author
#1 lore raw

PATCH v3 1/7 rust: firmware: add request_into_buf()

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 | 47 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 47 insertions(+)
rust/kernel/firmware.rs +47 -0
index 71168d8004e2..4460fb2cd5d8 100644
@@ -120,6 +120,53 @@ 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(crate::error::code::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.
+    let ret = unsafe {
+        bindings::request_firmware_into_buf(
+            pfw,
+            name.as_char_ptr(),
+            dev.as_raw(),
+            buf.as_mut_ptr().cast(),
+            buf.len(),
+        )
+    };
+    if ret != 0 {
+        return Err(Error::from_errno(ret));
+    }
+
+    // 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
#2 lore raw

Re: [PATCH v3 1/7] rust: firmware: add request_into_buf()

Quoted 25 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 | 47 +++++++++++++++++++++++++++++++++++++++++
  1 file changed, 47 insertions(+)
rust/kernel/firmware.rs +7 -0
index 71168d8004e2..4460fb2cd5d8 100644
@@ -120,6 +120,53 @@ 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

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

Quoted 10 lines
rust/kernel/firmware.rs +10 -0
+/// 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(crate::error::code::EINVAL);

EINVAL is already in prelude, you can use it directly.

Quoted 11 lines
rust/kernel/firmware.rs +11 -0
+    }
+
+    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.
+    let ret = unsafe {
+        bindings::request_firmware_into_buf(

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

Quoted 10 lines
rust/kernel/firmware.rs +10 -0
+            pfw,
+            name.as_char_ptr(),
+            dev.as_raw(),
+            buf.as_mut_ptr().cast(),
+            buf.len(),
+        )
+    };
+    if ret != 0 {
+        return Err(Error::from_errno(ret));
+    }

to_result can be used here to simplify.

Quoted 12 lines
rust/kernel/firmware.rs +9 -0
+
+    // 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 {}
author
#3 lore raw

Re: [PATCH v3 1/7] rust: firmware: add request_into_buf()

Quoted 10 lines · Alvin Sun
Quoted 8 lines

+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(crate::error::code::EINVAL);

EINVAL is already in prelude, you can use it directly.

I would have to add it to the list of imports.

Quoted 16 lines
Quoted 7 lines

+    // 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.
+    let ret = unsafe {
+        bindings::request_firmware_into_buf(
+            pfw,
+            name.as_char_ptr(),

Quoted 8 lines

+            dev.as_raw(),
+            buf.as_mut_ptr().cast(),
+            buf.len(),
+        )
+    };
+    if ret != 0 {
+        return Err(Error::from_errno(ret));
+    }

Quoted 1 line

to_result can be used here to simplify.

Will add in v4.

maintainer
#4 lore raw

Re: [PATCH v3 1/7] rust: firmware: add request_into_buf()

Quoted 1 line · Timur Tabi

I would have to add it to the list of imports.

That's fine, please do. While at it, you can also remove the explicit imports that are then covered by the prelude.

Thanks,
Danilo

#5 lore raw

Re: [PATCH v3 1/7] 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 | 47 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 47 insertions(+)
rust/kernel/firmware.rs +0 -0
index 71168d8004e2..4460fb2cd5d8 100644
@@ -120,6 +120,53 @@ fn drop(&mut self) {
     }
 }
 

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

Quoted 10 lines
rust/kernel/firmware.rs +10 -0
+/// 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 {

Sashiko is correct to point out that this doesn't return the number of bytes actually written into buf. We might not use that information in nova-core, but this is a kernel-wide API.

Returning a Result<&[u8]> would take care of this and cover the general use-case nicely.

maintainer
#6 lore raw

Re: [PATCH v3 1/7] rust: firmware: add request_into_buf()

Quoted 3 lines · Alexandre Courbot

Sashiko is correct to point out that this doesn't return the number of bytes actually written into buf. We might not use that information in nova-core, but this is a kernel-wide API.

Returning the size only doesn't carry a lot of value, please see [1].

Quoted 2 lines

Returning a Result<&[u8]> would take care of this and cover the general use-case nicely.

I'm fine with either this or just Result, as we don't have a user for the former.

[1] https://lore.kernel.org/nova-gpu/[email protected]/

author
#7 lore raw

Re: [PATCH v3 1/7] rust: firmware: add request_into_buf()

Quoted 7 lines · Danilo Krummrich
Quoted 3 lines · Alexandre Courbot

Sashiko is correct to point out that this doesn't return the number of bytes actually written into buf. We might not use that information in nova-core, but this is a kernel-wide API.

Returning the size only doesn't carry a lot of value, please see [1].

Quoted 7 lines
Quoted 2 lines

Returning a Result<&[u8]> would take care of this and cover the general use-case nicely.

I'm fine with either this or just Result, as we don't have a user for the former.

[1] https://lore.kernel.org/nova-gpu/[email protected]/

Guys, please come to a consensus. I had it return a size originally, but then Danilo said don't bother, and now Alex says I should return a size.

maintainer Reviewed-by
#8 lore raw

Re: [PATCH v3 1/7] rust: firmware: add request_into_buf()

Quoted 11 lines · Timur Tabi
Quoted 10 lines · Danilo Krummrich
Quoted 3 lines · Alexandre Courbot

Sashiko is correct to point out that this doesn't return the number of bytes actually written into buf. We might not use that information in nova-core, but this is a kernel-wide API.

Returning the size only doesn't carry a lot of value, please see [1].

Quoted 2 lines

Returning a Result<&[u8]> would take care of this and cover the general use-case nicely.

Quoted 7 lines
Quoted 4 lines

I'm fine with either this or just Result, as we don't have a user for the former.

[1] https://lore.kernel.org/nova-gpu/[email protected]/

Guys, please come to a consensus. I had it return a size originally, but then Danilo said don't bother, and now Alex says I should return a size.

Incorrect; I said you should return a slice. :)

What makes me a bit nervous with this API is that it is not sound against incorrect size information or race conditions (e.g. if the file on disk changes after we determined its size). But that's true of my proposal as well anyway.

Another inefficiency is that the buffer must be initialized when passed, only for its content to be immediately overwritten. I'd like to make this function accept a MaybeUninit, but that will require more generic code.

All that to say, I will likely think some more about it and revisit after it lands, but the current version does the job, so:

maintainer
#9 lore raw

Re: [PATCH v3 1/7] rust: firmware: add request_into_buf()

Quoted 12 lines · Alexandre Courbot
Quoted 11 lines · Timur Tabi
Quoted 10 lines · Danilo Krummrich
Quoted 3 lines · Alexandre Courbot

Sashiko is correct to point out that this doesn't return the number of bytes actually written into buf. We might not use that information in nova-core, but this is a kernel-wide API.

Returning the size only doesn't carry a lot of value, please see [1].

Quoted 2 lines

Returning a Result<&[u8]> would take care of this and cover the general use-case nicely.

Quoted 7 lines
Quoted 7 lines
Quoted 4 lines

I'm fine with either this or just Result, as we don't have a user for the former.

[1] https://lore.kernel.org/nova-gpu/[email protected]/

Guys, please come to a consensus. I had it return a size originally, but then Danilo said don't bother, and now Alex says I should return a size.

I said that both are fine for now, just Result or the slice, but only the size doesn't serve a purpose (see [1] above or the reasoning below).

Quoted 6 lines

Incorrect; I said you should return a slice. :)

What makes me a bit nervous with this API is that it is not sound against incorrect size information or race conditions (e.g. if the file on disk changes after we determined its size). But that's true of my proposal as well anyway.

There's nothing we can do about this, the file could also be corrupted, etc. In the end there are only two cases, the hardware can't deal with garbage, then the size-sanity check is not sufficient and we need proper validation (e.g. through the returned slice), or the hardware can deal with garbage, then the size-sanity check isn't necessary.

Quoted 4 lines

Another inefficiency is that the buffer must be initialized when passed, only for its content to be immediately overwritten. I'd like to make this function accept a MaybeUninit, but that will require more generic code.

This is true, with the current approach we need something like

	let buf = VBox::<[u8; SIZE]>::zeroed(GFP_KERNEL)?;

which isn't the end of the world, especially in the firmware loading path, but I agree it is a bit unfortunate.

We could indeed get rid of the initialization requirement entirely, but in this case just returning a slice isn't sufficient, as it leaves the caller with e.g. a VBox<MaybeUninit<[u8; SIZE]>> for storage, which is annoying if you want to access the buffer subsequently, e.g. to parse headers, etc.

So, for this to properly work, you'd need to take the container (Vec, Box, CoherentBox) by value and return the initialized one on success and the uninitialized one wrapped into a custom error type on failure. But this is probably a bit overengineered.

A simpler option would be to just use an initializer, such that request_into_buf() becomes something like this:

	pub fn request_firmware_init<'a>(
	    name: &'a CStr,
	    dev: &'a Device,
	) -> impl Init<[u8], Error> + 'a {
	    unsafe {
	        init_from_closure(move |slot: *mut [u8]| {
	            // call request_firmware_into_buf()
	            Ok(())
	        })
	    }
	}

And then allocate the buffer with

	let init = request_firmware_init(...);
	let fw = VVec::init_with(len, init, GFP_KERNEL)?;

In any case, the current approach is fine for this series, this can be a follow-up if needed.

The only thing that'd be nice to replace would be

	VVec::from_elem(0u8, size, GFP_KERNEL)

with

	VVec::<u8>::zeroed(size, GFP_KERNEL)

analogous to Box::zeroed().

author
#10 lore raw

PATCH v3 2/7 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   | 182 +++++++++++++++++++++
 drivers/gpu/nova-core/firmware.rs     |   1 +
 drivers/gpu/nova-core/firmware/tlv.rs | 225 ++++++++++++++++++++++++++
 3 files changed, 408 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 +182 -0
new file mode 100644
index 000000000000..e4eb6ab6d02f
@@ -0,0 +1,182 @@
+.. 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``.
+
+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 expected to be ASCII only, 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.
+
+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 +225 -0

225 lines not on this page · raw message

Signature · 1 line
2.54.0
author
#11 lore raw

Re: [PATCH v3 2/7] gpu: nova-core: add TLV parser for firmware files

Quoted 5 lines · Timur Tabi

+    pub(crate) fn get_bytes(&self, tag: &[u8; 4]) -> Result<&'a [u8]> { +        let tlv = self.find(tag)?;
+
+        Ok(tlv.value)
+    }

I forgot to update get_bytes() to return an error if the value is empty. That should address a lot of potential issues, including the ones that Sashiko raised.

#12 lore raw

Re: [PATCH v3 2/7] gpu: nova-core: add TLV parser for firmware files

Quoted 9 lines · Timur Tabi
Quoted 5 lines · Timur Tabi

+    pub(crate) fn get_bytes(&self, tag: &[u8; 4]) -> Result<&'a [u8]> { +        let tlv = self.find(tag)?;
+
+        Ok(tlv.value)
+    }

I forgot to update get_bytes() to return an error if the value is empty. That should address a lot of potential issues, including the ones that Sashiko raised.

The spec says that

Lengths of zero are allowed and indicate that the tag is a boolean.

though, so we probably don't want to return an error in that case.

author
#13 lore raw

Re: [PATCH v3 2/7] gpu: nova-core: add TLV parser for firmware files

Quoted 9 lines · Alexandre Courbot
Quoted 3 lines

I forgot to update get_bytes() to return an error if the value is empty.  That should address a lot
of potential issues, including the ones that Sashiko raised.

The spec says that

  Lengths of zero are allowed and indicate that the tag is a boolean.

though, so we probably don't want to return an error in that case.

Just don't call get_bytes() if you expect it to have no value. I can add a get_bool() or is_true() function to handle booleans, but there are no users.

Returning error on length==0 simplifies a lot of code on the caller side.

#14 lore raw

Re: [PATCH v3 2/7] gpu: nova-core: add TLV parser for firmware files

Quoted 7 lines · Timur Tabi
Quoted 6 lines · Alexandre Courbot
Quoted 3 lines

I forgot to update get_bytes() to return an error if the value is empty.  That should address a lot
of potential issues, including the ones that Sashiko raised.

The spec says that

Quoted 8 lines
Quoted 3 lines

  Lengths of zero are allowed and indicate that the tag is a boolean.

though, so we probably don't want to return an error in that case.

Just don't call get_bytes() if you expect it to have no value. I can add a get_bool() or is_true() function to handle booleans, but there are no users.

Returning error on length==0 simplifies a lot of code on the caller side.

Can you give an example of such a simplification? I'm fine if there is a benefit to doing so, but would like to understand what we gain.

author
#15 lore raw

Re: [PATCH v3 2/7] gpu: nova-core: add TLV parser for firmware files

Quoted 4 lines · Alexandre Courbot
Quoted 1 line

Returning error on length==0 simplifies a lot of code on the caller side.

Can you give an example of such a simplification? I'm fine if there is a benefit to doing so, but would like to understand what we gain.

Well, maybe not "a lot" of code, but in general, it eliminates the need to test for empty slices every time.  If get_bytes() returns success, you know that you actually do have some bytes.

For example:

        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;

sig_bytes.len() cannot be 0, so we know that sig_size cannot be 0, and therefore

sig_bytes.chunks_exact(sig_size).nth(index).ok_or(EINVAL)

chunks_exact() cannot fail.

#16 lore raw

Re: [PATCH v3 2/7] gpu: nova-core: add TLV parser for firmware files

Quoted 21 lines · Timur Tabi
Quoted 4 lines · Alexandre Courbot
Quoted 1 line

Returning error on length==0 simplifies a lot of code on the caller side.

Can you give an example of such a simplification? I'm fine if there is a benefit to doing so, but would like to understand what we gain.

Well, maybe not "a lot" of code, but in general, it eliminates the need to test for empty slices every time.  If get_bytes() returns success, you know that you actually do have some bytes.

For example:

        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;
Quoted 5 lines

sig_bytes.len() cannot be 0, so we know that sig_size cannot be 0, and therefore

sig_bytes.chunks_exact(sig_size).nth(index).ok_or(EINVAL)

chunks_exact() cannot fail.

Basically we want a guarantee that sig_size is not zero. I'd prefer if we could enforce that using the type system rather than relying on a guarantee that get_bytes doesn't return an empty slice, because even that guarantee alone is not enough - we also need num_sigs > 0 and sig_bytes.len() % num_sigs == 0 for that.

All these conditions are spread around in the code, so I think it is a good opportunity to gather them together, and use NonZero to hold the guarantee we want.

Something like this:

    let num_sigs = usize::from_safe_cast(tlv.get_u32(b"NSIG")?);

    // Size of one signature - Booter is always signed
    let sig_size = if (1..=15).contains(&num_sigs) && sig_bytes.len() % num_sigs == 0 {
        NonZero::new(sig_bytes.len() / num_sigs)
    } else {
        None
    }
    .ok_or_else(|| {
        dev_err!(dev, "invalid signature count {}\n", num_sigs);
        EINVAL
    })?;

    ...

    // PANIC: `sig_size` is `NonZero`, so `chunks_exact` cannot panic.
    let sig_chunk = sig_bytes.chunks_exact(sig_size.get()).nth(index).ok_or(EINVAL)?;

This is more sound as the guarantee we need is carried by the type of sig_size, and with that there is no need to make get_bytes return an error on empty slices.

author
#17 lore raw

Re: [PATCH v3 2/7] gpu: nova-core: add TLV parser for firmware files

Quoted 11 lines · Alexandre Courbot
Quoted 5 lines

sig_bytes.len() cannot be 0, so we know that sig_size cannot be 0, and therefore

        sig_bytes.chunks_exact(sig_size).nth(index).ok_or(EINVAL)

chunks_exact() cannot fail.

Basically we want a guarantee that sig_size is not zero. I'd prefer if we could enforce that using the type system rather than relying on a guarantee that get_bytes doesn't return an empty slice, because even that guarantee alone is not enough - we also need num_sigs > 0 and sig_bytes.len() % num_sigs == 0 for that.

I'm about to post a v4 that has a "get_signature()" method that encapsulates all this processing. I think it addresses most, if not all, of these issues. It does depend on get_bytes() not returning an empty slice, though.

#18 lore raw

Re: [PATCH v3 2/7] gpu: nova-core: add TLV parser for firmware files

In reply to Timur Tabi
Quoted 42 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.

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

---
 Documentation/gpu/nova/core/tlv.rst   | 182 +++++++++++++++++++++
 drivers/gpu/nova-core/firmware.rs     |   1 +
 drivers/gpu/nova-core/firmware/tlv.rs | 225 ++++++++++++++++++++++++++
 3 files changed, 408 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 +8 -0
new file mode 100644
index 000000000000..e4eb6ab6d02f
@@ -0,0 +1,182 @@
+.. 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"

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

Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10 -0
+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.

I guess that last paragraph is kind of expected - spelling it out loud without being specific as to how to handle missing or malformed tags is just confusing. I think it can just be dropped?

Quoted 32 lines
Documentation/gpu/nova/core/tlv.rst new file +32 -0
+
+::
+
+    +------+------+------+------+
+    |  '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.
+

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

Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10 -0
+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``.
+
+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 expected to be ASCII only, without a null terminator.

"expected" leaves a window of interpretation - let's say "required" or just "encoded in ASCII without a null terminator".

Quoted 70 lines
Documentation/gpu/nova/core/tlv.rst new file +70 -0
+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.
+
+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 140

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.

Shall we say "A value of 0 or absence of this tag" for coverage? ... Or not, see my review of patch 3.

Quoted 92 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 +31 -0
new file mode 100644
index 000000000000..56e0d5cab580
@@ -0,0 +1,225 @@
+// 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;
+
+/// Requests the GPU firmware TLV `name` suitable for `chipset`.
+#[expect(dead_code)]
+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",
+        chip_name,
+        name
+    );
+
+    CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{name}.tlv"))
+        .and_then(|path| firmware::Firmware::request(&path, dev))
+}

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

Quoted 10 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +10 -0
+
+struct TlvBlock<'a> {
+    tag: &'a [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<'a> {
+    tag: &'a [u8; 4],

This struct doesn't need a lifetime - it can store tag as [u8; 4]. Same for the tag member of TlvBlock. Everything above them (find, get_bytes, etc) can still take a reference to the array for convenience as we use the b"ABCD" syntax, but for these two the reference is just inefficient without reason.

Quoted 5 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +5 -0
+    length: usize,
+}
+
+impl<'a> TlvBlockHeader<'a> {
+    const SIZE: usize = size_of::<[u8; 4]>() + size_of::<u32>();

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

Quoted 10 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +10 -0
+
+    /// Parses the first [`Self::SIZE`] bytes of `hdr` (caller may pass a longer slice).
+    fn parse(hdr: &'a [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::from_le_bytes(len_arr) as usize;

Let's avoid using the potentially lossy as keyword:

    let length = num::u32_as_usize(u32::from_le_bytes(len_arr));

(after importing crate::num).

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

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

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

Maybe use checked_add here as well for consistency.

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

Quoted 9 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +9 -0
+
+        Some(TlvBlock {
+            tag: header.tag,
+            value,
+        })
+    }
+}
+
+/// The payload of a validated TLV (type, length, value) firmware image.

I think we can just say "A validated TLV", as payload makes it sound like this is the payload of a given key within the TLV firmware.

Quoted 62 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +62 -0
+///
+/// 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
+/// 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.
+///
+/// # 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],
+}
+
+#[expect(dead_code)]
+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)?;
+
+        if payload.is_empty() {
+            // Reject empty TLV files
+            return Err(EINVAL);
+        }
+
+        let mut rest = payload;
+        while !rest.is_empty() {
+            // Validate and extract the header (type, length).
+            let Some(header) = rest
+                .get(..TlvBlockHeader::SIZE)
+                .and_then(TlvBlockHeader::parse)
+            else {
+                return Err(EINVAL);
+            };
+            // 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)

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

Quoted 10 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +10 -0
+                .ok_or(EINVAL)?;
+
+            if length > rest.len() {
+                return Err(EINVAL);
+            }
+
+            // Advance to the next block. `length <= rest.len()` was just checked, so this
+            // slice is always in bounds and lands on the next block boundary (or empties
+            // `rest` after the final block).
+            rest = &rest[length..];

The check on length and slice split can be factored out into this one-liner:

    rest = rest.split_at_checked(length).ok_or(EINVAL)?.1;

It is preferable not only because it is shorter; the guarantee of correctness is carried by the split operation itself, and as a result you also don't need a comment justifying that you just performed the check.

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

Quoted 3 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +3 -0
+        }
+
+        Ok(Self { data: payload })

As mentioned by Sashiko, this needs an INVARIANT: comment.

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

Quoted 13 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +13 -0
+    }
+
+    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)
+    }
+
+    pub(crate) fn get_bytes(&self, tag: &[u8; 4]) -> Result<&'a [u8]> {

These methods are simple, but let's grant them a one-line doccomment for consistency.

One thing I'd like to eventually add (for the record; as a follow-up is ok) is an abstraction of the BLOB/FILE distinction: maybe a get_payload method that returns either a reference to the BLOB section, or creates a VVec to load the references firmware file. Its return type would be an enum with an AsRef<[u8]> implementation and a to_owned(self) -> VVec<u8> method so individual firmware implementations can get the representation they need without caring about the underlying storage type.

author
#19 lore raw

Re: [PATCH v3 2/7] gpu: nova-core: add TLV parser for firmware files

Quoted 12 lines · Alexandre Courbot
Quoted 12 lines

+==================================

Documentation/gpu/nova/core/tlv.rst new file +11 -0
+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.
Quoted 8 lines

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

Quoted 4 lines
Documentation/gpu/nova/core/tlv.rst new file +4 -0
+
+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.

I guess that last paragraph is kind of expected - spelling it out loud without being specific as to how to handle missing or malformed tags is just confusing. I think it can just be dropped?

I think the docs need a statement somewhere that "parsers" should handle missing or invalid tags, and that that there is no expectation that when a TLV is created, that all the tags are there or that they are even the correct format or anything like that.

Quoted 8 lines
Quoted 5 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.

Shall we say "A value of 0 or absence of this tag" for coverage? ... Or not, see my review of patch 3.

Hmmm... I'm not really crazy about that idea, because then there is incentive to make all u32 tags act that way. Sometimes 0 is just another number, and not a synonym for "None".

Quoted 17 lines

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

Quoted 11 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +10 -0
+
+struct TlvBlock<'a> {
+    tag: &'a [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<'a> {
+    tag: &'a [u8; 4],

This struct doesn't need a lifetime - it can store tag as [u8; 4]. Same for the tag member of TlvBlock. Everything above them (find, get_bytes, etc) can still take a reference to the array for convenience as we use the b"ABCD" syntax, but for these two the reference is just inefficient without reason.

Ok. This change resulted in a cascading effect and I had to change a lot of &[u8; 4] into [u8; 4], but I didn't want to change all of them. Which is better:

    pub(crate) fn get_bytes(&self, tag: &[u8; 4]) -> Result<&'a [u8]> {
...
    tlv.get_bytes(b"BLOB")?

or

    pub(crate) fn get_bytes(&self, tag: [u8; 4]) -> Result<&'a [u8]> {
...
    tlv.get_bytes(*b"BLOB")?
Quoted 5 lines

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

Quoted 2 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +2 -0
+
+/// The payload of a validated TLV (type, length, value) firmware image.

I think we can just say "A validated TLV", as payload makes it sound like this is the payload of a given key within the TLV firmware.

Well, it's the part after the "NVFW" header. The "payload" of an actual get is the "value".

I'll change it to:

/// The post-header part of a validated TLV (type, length, value) firmware image.

Quoted 10 lines

One thing I'd like to eventually add (for the record; as a follow-up is ok) is an abstraction of the BLOB/FILE distinction: maybe a get_payload method that returns either a reference to the BLOB section, or creates a VVec to load the references firmware file. Its return type would be an enum with an AsRef<[u8]> implementation and a to_owned(self) -> VVec<u8> method so individual firmware implementations can get the representation they need without caring about the underlying storage type.

Yes, I definitely want to do that in the future also.

#20 lore raw

Re: [PATCH v3 2/7] gpu: nova-core: add TLV parser for firmware files

Quoted 22 lines · Timur Tabi
Quoted 12 lines · Alexandre Courbot
Quoted 12 lines

+==================================

Documentation/gpu/nova/core/tlv.rst new file +11 -0
+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.
Quoted 8 lines

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

Quoted 4 lines
Documentation/gpu/nova/core/tlv.rst new file +4 -0
+
+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.

I guess that last paragraph is kind of expected - spelling it out loud without being specific as to how to handle missing or malformed tags is just confusing. I think it can just be dropped?

Quoted 3 lines

I think the docs need a statement somewhere that "parsers" should handle missing or invalid tags, and that that there is no expectation that when a TLV is created, that all the tags are there or that they are even the correct format or anything like that.

No issue with keeping that paragraph if you prefer.

Quoted 7 lines
Quoted 7 lines
Quoted 6 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.

Quoted 5 lines
Quoted 2 lines

Shall we say "A value of 0 or absence of this tag" for coverage? ... Or not, see my review of patch 3.

Hmmm... I'm not really crazy about that idea, because then there is incentive to make all u32 tags act that way. Sometimes 0 is just another number, and not a synonym for "None".

Yup, that would make the absence of NSIG an error, but that's not a problem.

Quoted 26 lines
Quoted 18 lines

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

Quoted 12 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +10 -0
+
+struct TlvBlock<'a> {
+    tag: &'a [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<'a> {
+    tag: &'a [u8; 4],

This struct doesn't need a lifetime - it can store tag as [u8; 4]. Same for the tag member of TlvBlock. Everything above them (find, get_bytes, etc) can still take a reference to the array for convenience as we use the b"ABCD" syntax, but for these two the reference is just inefficient without reason.

Ok. This change resulted in a cascading effect and I had to change a lot of &[u8; 4] into [u8; 4], but I didn't want to change all of them. Which is better:

    pub(crate) fn get_bytes(&self, tag: &[u8; 4]) -> Result<&'a [u8]> {
...
    tlv.get_bytes(b"BLOB")?
Quoted 5 lines

or

    pub(crate) fn get_bytes(&self, tag: [u8; 4]) -> Result<&'a [u8]> {
...
    tlv.get_bytes(*b"BLOB")?

The first one is fine - and better arguably, as the callers don't have to dereference the b"ABCD" tags. It should also limit the cascading effect.

Quoted 8 lines
Quoted 7 lines

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

Quoted 4 lines
drivers/gpu/nova-core/firmware/tlv.rs new file +2 -0
+
+/// The payload of a validated TLV (type, length, value) firmware image.

I think we can just say "A validated TLV", as payload makes it sound like this is the payload of a given key within the TLV firmware.

Quoted 5 lines

Well, it's the part after the "NVFW" header. The "payload" of an actual get is the "value".

I'll change it to:

/// The post-header part of a validated TLV (type, length, value) firmware image.

Sounds good!

author
#21 lore raw

PATCH v3 3/7 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 | 344 +++++------------------
 drivers/gpu/nova-core/firmware/tlv.rs    |   6 +-
 drivers/gpu/nova-core/gsp/hal/tu102.rs   |  13 +-
 4 files changed, 81 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 +72 -272

404 lines not on this page · raw message

drivers/gpu/nova-core/firmware/tlv.rs +4 -2
index 56e0d5cab580..68b12637ff2c 100644
@@ -11,7 +11,6 @@
 use crate::gpu;
 
 /// Requests the GPU firmware TLV `name` suitable for `chipset`.
-#[expect(dead_code)]
 pub(crate) fn request_tlv(
     dev: &device::Device,
     chipset: gpu::Chipset,
@@ -117,6 +116,9 @@ fn next(&mut self) -> Option<Self::Item> {
 /// 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
@@ -129,7 +131,6 @@ pub(crate) struct Tlv<'a> {
     data: &'a [u8],
 }
 
-#[expect(dead_code)]
 impl<'a> Tlv<'a> {
     const MAGIC: &'static [u8; 4] = b"NVFW";
 
@@ -161,6 +162,7 @@ pub(crate) fn new(data: &'a [u8]) -> Result<Self> {
             else {
                 return Err(EINVAL);
             };
+
             // 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 {
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
#22 lore raw

Re: [PATCH v3 3/7] gpu: nova-core: transition booter_load to TLV images

On Fri Jul 3, 2026 at 4:27 AM JST, Timur Tabi wrote:
<...>

Quoted 38 lines

/// 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]);

drivers/gpu/nova-core/firmware/booter.rs +13 -12
@@ -291,85 +85,91 @@ pub(crate) fn new(
         dev: &device::Device<device::Bound>,
         kind: BooterKind,
         chipset: Chipset,
-        ver: &str,
         falcon: &Falcon<'_, <Self as FalconFirmware>::Target>,
     ) -> Result<Self> {
         let fw_name = match kind {
             BooterKind::Loader => "booter_load",
             BooterKind::Unloader => "booter_unload",
         };
-        let fw = super::request_firmware(dev, chipset, fw_name, ver)?;
-        let bin_fw = BinFirmware::new(&fw)?;
-
-        // The binary firmware embeds a Heavy-Secured firmware.
-        let hs_fw = HsFirmwareV2::new(&bin_fw)?;
-
-        // The Heavy-Secured firmware embeds a firmware load descriptor.
-        let load_hdr = HsLoadHeaderV2::new(&hs_fw)?;
-
-        // Offset in `ucode` where to patch the signature.
-        let patch_loc = hs_fw.patch_location()?;
+        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")?;

drivers/gpu/nova-core/firmware/booter.rs pub(crate) fn new( · line 116

Quoted 10 lines
drivers/gpu/nova-core/firmware/booter.rs +10 -0
+        let patch_loc = tlv.get_u32(b"PLOC")?;
+        let fuse_version = tlv.get_u32(b"FUSE")?;
+        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 num_sigs = tlv.get_u32(b"NSIG")?;
+        let sig_bytes = tlv.get_bytes(b"SIGN")?;
+
+        // Booter is always signed

The .rst file mentions the non-signed case though - we should reconcile the spec and the code one way or the other.

drivers/gpu/nova-core/firmware/booter.rs pub(crate) fn new( · line 117

Quoted 1 line
drivers/gpu/nova-core/firmware/booter.rs +1 -0
+        if !(1..=15).contains(&num_sigs) || sig_bytes.len() % num_sigs as usize != 0 {

s/as usize/into_safe_cast.

Quoted 69 lines
drivers/gpu/nova-core/firmware/booter.rs +20 -41
+            dev_err!(dev, "invalid signature count {}\n", num_sigs);
+            return Err(EINVAL);
+        }
 
-        let sig_params = HsSignatureParams::new(&hs_fw)?;
         let brom_params = FalconBromParams {
-            // `load_hdr.os_data_offset` is an absolute index, but `pkc_data_offset` is from the
+            // `os_data_offset` is an absolute index, but `pkc_data_offset` is from the
             // signature patch location.
-            pkc_data_offset: patch_loc
-                .checked_sub(load_hdr.os_data_offset)
-                .ok_or(EINVAL)?,
-            engine_id_mask: u16::try_from(sig_params.engine_id_mask).map_err(|_| EINVAL)?,
-            ucode_id: u8::try_from(sig_params.ucode_id).map_err(|_| EINVAL)?,
+            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 app0 = HsLoadHeaderV2App::new(&hs_fw, 0)?;
 
-        // Object containing the firmware microcode to be signature-patched.
-        let ucode = bin_fw
-            .data()
-            .ok_or(EINVAL)
+        let ucode = tlv
+            .get_bytes(b"BLOB")
             .and_then(FirmwareObject::<Self, _>::new_booter)?;
 
-        let ucode_signed = {
-            let mut signatures = hs_fw.signatures_iter()?.peekable();
-
-            if signatures.peek().is_none() {
-                // If there are no signatures, then the firmware is unsigned.
-                ucode.no_patch_signature()
-            } else {
-                // Obtain the version from the fuse register, and extract the corresponding
-                // signature.
-                let reg_fuse_version = falcon
-                    .signature_reg_fuse_version(brom_params.engine_id_mask, brom_params.ucode_id)?;
-
-                // `0` means the last signature should be used.
-                const FUSE_VERSION_USE_LAST_SIG: u32 = 0;
-                let signature = match reg_fuse_version {
-                    FUSE_VERSION_USE_LAST_SIG => signatures.last(),
-                    // Otherwise hardware fuse version needs to be subtracted to obtain the index.
-                    reg_fuse_version => {
-                        let Some(idx) = sig_params.fuse_ver.checked_sub(reg_fuse_version) else {
-                            dev_err!(dev, "invalid fuse version for Booter firmware\n");
-                            return Err(EINVAL);
-                        };
-                        signatures.nth(idx.into_safe_cast())
-                    }
-                }
-                .ok_or(EINVAL)?;
-
-                ucode.patch_signature(&signature, patch_loc.into_safe_cast())?
-            }
+        // Obtain the version from the fuse register, and extract the corresponding
+        // signature.
+        let reg_fuse_version =
+            falcon.signature_reg_fuse_version(brom_params.engine_id_mask, brom_params.ucode_id)?;
+
+        const FUSE_VERSION_USE_LAST_SIG: u32 = 0;
+        let index = match reg_fuse_version {
+            // `0` means the last signature should be used.
+            FUSE_VERSION_USE_LAST_SIG => num_sigs - 1,
+            // Otherwise, hardware fuse version needs to be subtracted to obtain the index.
+            _ => fuse_version.checked_sub(reg_fuse_version).ok_or(EINVAL)?,
         };

drivers/gpu/nova-core/firmware/booter.rs pub(crate) fn new( · line 155

Quoted 10 lines
drivers/gpu/nova-core/firmware/booter.rs +9 -0
 
+        // The size of one signature
+        let sig_size = sig_bytes
+            .len()
+            .checked_div(num_sigs.into_safe_cast())
+            .ok_or(EINVAL)?;
+
+        // Extract the nth signature
+        let sig_chunk = sig_bytes
+            .chunks_exact(sig_size)

As Sashiko pointed out, this will panic if sig_size == 0, so we need to check that - and whether an unsigned Booter is valid at all.

drivers/gpu/nova-core/firmware/booter.rs pub(crate) fn new( · line 156

Quoted 1 line
drivers/gpu/nova-core/firmware/booter.rs +1 -0
+            .nth(index as usize)

s/as_usize/into_safe_cast.

Quoted 55 lines
drivers/gpu/nova-core/firmware/booter.rs +12 -7
+            .ok_or(EINVAL)?;
+
+        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.offset,
+                app0_code_offset,
                 Some(FalconDmaLoadTarget {
                     src_start: 0,
-                    dst_start: load_hdr.os_code_offset,
-                    len: load_hdr.os_code_size,
+                    dst_start: os_code_offset,
+                    len: os_code_size,
                 }),
             )
         } else {
@@ -378,15 +178,15 @@ pub(crate) fn new(
 
         Ok(Self {
             imem_sec_load_target: FalconDmaLoadTarget {
-                src_start: app0.offset,
+                src_start: app0_code_offset,
                 dst_start: imem_sec_dst_start,
-                len: app0.len,
+                len: app0_code_size,
             },
             imem_ns_load_target,
             dmem_load_target: FalconDmaLoadTarget {
-                src_start: load_hdr.os_data_offset,
+                src_start: os_data_offset,
                 dst_start: 0,
-                len: load_hdr.os_data_size,
+                len: os_data_size,
             },
             brom_params,
             ucode: ucode_signed,
drivers/gpu/nova-core/firmware/tlv.rs +0 -1
index 56e0d5cab580..68b12637ff2c 100644
@@ -11,7 +11,6 @@
 use crate::gpu;
 
 /// Requests the GPU firmware TLV `name` suitable for `chipset`.
-#[expect(dead_code)]
 pub(crate) fn request_tlv(
     dev: &device::Device,
     chipset: gpu::Chipset,

drivers/gpu/nova-core/firmware/tlv.rs fn next(&mut self) -> Option<Self::Item> { · line 121

Quoted 6 lines
drivers/gpu/nova-core/firmware/tlv.rs +3 -0
@@ -117,6 +116,9 @@ fn next(&mut self) -> Option<Self::Item> {
 /// 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.
+///

This chunk should probably be in patch 2.

Quoted 12 lines
drivers/gpu/nova-core/firmware/tlv.rs +0 -1
 /// # Invariants
 ///
 /// `data` is a validated TLV payload (the bytes *after* the `NVFW` magic): it is the exact
@@ -129,7 +131,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/firmware/tlv.rs pub(crate) fn new(data: &'a [u8]) -> Result<Self> { · line 165

Quoted 4 lines
drivers/gpu/nova-core/firmware/tlv.rs +1 -0
@@ -161,6 +162,7 @@ pub(crate) fn new(data: &'a [u8]) -> Result<Self> {
             else {
                 return Err(EINVAL);
             };
+

Same here.

author
#23 lore raw

Re: [PATCH v3 3/7] gpu: nova-core: transition booter_load to TLV images

Quoted 16 lines · Alexandre Courbot
Quoted 15 lines

+        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 = tlv.get_u32(b"FUSE")?; +        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 num_sigs = tlv.get_u32(b"NSIG")?; +        let sig_bytes = tlv.get_bytes(b"SIGN")?; +
+        // Booter is always signed

Quoted 2 lines

The .rst file mentions the non-signed case though - we should reconcile the spec and the code one way or the other.

The .rst does not mention that Booter is signed, only that if the firmware is unsigned, then NSIG is 0 and SIGN does not exist. And since get_bytes() now returns Error if SIGN doesn't exist, we enforce that here.

But you're right in that it does feel a little off. That's one of the reasons I had get_nth() in v1 -- to streamline getting the nth signature.

What do you think about adding a get_signature(index) method that combines parsing NSIG and SIGN, automatically calculating sig_size and returning Option<&[u8]> ?

Quoted 12 lines
Quoted 11 lines


+        // The size of one signature
+        let sig_size = sig_bytes
+            .len()
+            .checked_div(num_sigs.into_safe_cast()) +            .ok_or(EINVAL)?;
+
+        // Extract the nth signature
+        let sig_chunk = sig_bytes
+            .chunks_exact(sig_size)

Quoted 2 lines

As Sashiko pointed out, this will panic if sig_size == 0, so we need to check that - and whether an unsigned Booter is valid at all.

sig_size cannot be 0 because of this:

        if !(1..=15).contains(&num_sigs) || sig_bytes.len() % num_sigs != 0 {

Neither sig_bytes.len() nor num_sigs can be 0.

But IMHO, this just reinforces the idea that I should add get_signature().

#24 lore raw

Re: [PATCH v3 3/7] gpu: nova-core: transition booter_load to TLV images

Quoted 24 lines · Timur Tabi
Quoted 16 lines · Alexandre Courbot
Quoted 15 lines

+        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 = tlv.get_u32(b"FUSE")?; +        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 num_sigs = tlv.get_u32(b"NSIG")?; +        let sig_bytes = tlv.get_bytes(b"SIGN")?; +
+        // Booter is always signed

Quoted 2 lines

The .rst file mentions the non-signed case though - we should reconcile the spec and the code one way or the other.

The .rst does not mention that Booter is signed, only that if the firmware is unsigned, then NSIG is 0 and SIGN does not exist. And since get_bytes() now returns Error if SIGN doesn't exist, we enforce that here.

Quoted 5 lines

But you're right in that it does feel a little off. That's one of the reasons I had get_nth() in v1 -- to streamline getting the nth signature.

What do you think about adding a get_signature(index) method that combines parsing NSIG and SIGN, automatically calculating sig_size and returning Option<&[u8]> ?

That would make sense to me, yes. The current ad-hoc code is rather messy and having it in a separate method would definitely help with that.

Do you mean to make it a method of Tlv or BooterFirmware? The latter looks more adequate for the time being, as AFAIK Booter is the only user of this signature.

Quoted 16 lines
Quoted 13 lines
Quoted 12 lines


+        // The size of one signature
+        let sig_size = sig_bytes
+            .len()
+            .checked_div(num_sigs.into_safe_cast()) +            .ok_or(EINVAL)?;
+
+        // Extract the nth signature
+        let sig_chunk = sig_bytes
+            .chunks_exact(sig_size)

Quoted 2 lines

As Sashiko pointed out, this will panic if sig_size == 0, so we need to check that - and whether an unsigned Booter is valid at all.

Quoted 7 lines

sig_size cannot be 0 because of this:

        if !(1..=15).contains(&num_sigs) || sig_bytes.len() % num_sigs != 0 {

Neither sig_bytes.len() nor num_sigs can be 0.

But IMHO, this just reinforces the idea that I should add get_signature().

Yes, that would keep all the conditions we need to track local to a much smaller code block. Please also check my other reply [1] for further potential improvements.

[1] https://lore.kernel.org/all/[email protected]/

author
#25 lore raw

Re: [PATCH v3 3/7] gpu: nova-core: transition booter_load to TLV images

Quoted 14 lines · Alexandre Courbot
Quoted 6 lines

The .rst does not mention that Booter is signed, only that if the firmware is unsigned, then NSIG is
0 and SIGN does not exist.  And since get_bytes() now returns Error if SIGN doesn't exist, we
enforce that here.

Quoted 7 lines

But you're right in that it does feel a little off.  That's one of the reasons I had get_nth() in v1
-- to streamline getting the nth signature.

What do you think about adding a get_signature(index) method that combines parsing NSIG and SIGN,
automatically calculating sig_size and returning Option<&[u8]> ?

Quoted 6 lines

That would make sense to me, yes. The current ad-hoc code is rather messy and having it in a separate method would definitely help with that.

Do you mean to make it a method of Tlv or BooterFirmware? The latter looks more adequate for the time being, as AFAIK Booter is the only user of this signature.

It's a method of Tlv, since it's along the same lines as "get_u32", but still different. I added it in v4, please take a look.

author
#26 lore raw

PATCH v3 4/7 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 ab0491b57944..1acd169ddb6c 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
author
#27 lore raw

PATCH v3 5/7 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
#28 lore raw

Re: [PATCH v3 5/7] gpu: nova-core: transition gen_bootloader to TLV images

On Fri Jul 3, 2026 at 4:27 AM JST, Timur Tabi wrote:
<...>

Quoted 20 lines

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

drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +0 -13
@@ -146,38 +121,23 @@ pub(crate) fn new(
         dev: &Device<device::Bound>,
         chipset: Chipset,
     ) -> Result<Self> {
-        let fw = request_firmware(dev, chipset, "gen_bootloader", FIRMWARE_VERSION)?;
-        let hdr = fw
-            .data()
-            .get(0..size_of::<BinHdr>())
-            .and_then(BinHdr::from_bytes_copy)
-            .ok_or(EINVAL)?;
-
-        let desc = {
-            let desc_offset = usize::from_safe_cast(hdr.header_offset);
-
-            fw.data()
-                .get(desc_offset..)
-                .and_then(BootloaderDesc::from_bytes_copy_prefix)

drivers/gpu/nova-core/firmware/fwsec/bootloader.rs pub(crate) fn new( · line 130

Quoted 10 lines
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +7 -3
-                .ok_or(EINVAL)?
-                .0
-        };
+        let fw = request_tlv(dev, chipset, "gen_bootloader")?;
+        let tlv = Tlv::new(fw.data())?;
+        dev_info!(
+            dev,
+            "loaded generic bootloader firmware v{}\n",
+            tlv.get_string(b"VERS")?
+        );

s/dev_info/dev_dbg.

Also, since dev_dbg can be compiled out, the check performed on the VERS tag existing is not guaranteed to be performed. We should probably extract it out of the dev_dbg statement. This is true across the series; which makes me think it might also benefit from a helper to factor out the request_t.v/Tlv::new/dev_dbg common sequence.

author
#29 lore raw

Re: [PATCH v3 5/7] gpu: nova-core: transition gen_bootloader to TLV images

Quoted 6 lines · Alexandre Courbot
Quoted 5 lines

+        dev_info!(
+            dev,
+            "loaded generic bootloader firmware v{}\n", +            tlv.get_string(b"VERS")?
+        );

Quoted 7 lines

s/dev_info/dev_dbg.

Also, since dev_dbg can be compiled out, the check performed on the VERS tag existing is not guaranteed to be performed. We should probably extract it out of the dev_dbg statement. This is true across the series; which makes me think it might also benefit from a helper to factor out the request_t.v/Tlv::new/dev_dbg common sequence.

We don't care about the VERS tag if we're not going to print it out, so we probably should not extract it otherwise.

I know it's a common pattern, but I couldn't find a way to cleanly combine request_tlv() with Tlv::new().

#30 lore raw

Re: [PATCH v3 5/7] gpu: nova-core: transition gen_bootloader to TLV images

Quoted 9 lines · Timur Tabi
Quoted 8 lines · Alexandre Courbot
Quoted 5 lines

+        dev_info!(
+            dev,
+            "loaded generic bootloader firmware v{}\n", +            tlv.get_string(b"VERS")?
+        );

s/dev_info/dev_dbg.

Quoted 8 lines
Quoted 5 lines

Also, since dev_dbg can be compiled out, the check performed on the VERS tag existing is not guaranteed to be performed. We should probably extract it out of the dev_dbg statement. This is true across the series; which makes me think it might also benefit from a helper to factor out the request_t.v/Tlv::new/dev_dbg common sequence.

We don't care about the VERS tag if we're not going to print it out, so we probably should not extract it otherwise.

The spec mentions that this tag is present in all TLV files, so its absence means the file is invalid and should trigger an error.

Quoted 3 lines

I know it's a common pattern, but I couldn't find a way to cleanly combine request_tlv() with Tlv::new().

Ah right, Tlv keeps a reference to the Firmware instance, which would become a local variable if we used a helper. We could work around this by using more generics, but that cascades into other ownership issues and is more trouble than is worth for now.

author
#31 lore raw

Re: [PATCH v3 5/7] gpu: nova-core: transition gen_bootloader to TLV images

Quoted 7 lines · Alexandre Courbot
Quoted 7 lines
Quoted 6 lines

Also, since dev_dbg can be compiled out, the check performed on the VERS tag existing is not guaranteed to be performed. We should probably extract it out of the dev_dbg statement. This is true across the series; which makes me think it might also benefit from a helper to factor out the request_t.v/Tlv::new/dev_dbg common sequence.

Quoted 6 lines
Quoted 3 lines

We don't care about the VERS tag if we're not going to print it out, so we probably should not
extract it otherwise.

The spec mentions that this tag is present in all TLV files, so its absence means the file is invalid and should trigger an error.

If a tree falls in the woods and no one is around to hear it, does it make a sound?

I see your point, I'm just not sure I agree with it. By that logic, we should test for VERS in the constructor. My concern is that maybe one day we will have a TLV that doesn't have a VERS tag because it's not attached to a versioned firmware image, it's just some misc data.

I need to think about this a little more. What do you think about testing for VERS in the constructor? We could move the dev_dbg! into the constructor, but then we'd have to pass dev as a parameter.

I'm going to post a v4 today in the meantime.

#32 lore raw

Re: [PATCH v3 5/7] gpu: nova-core: transition gen_bootloader to TLV images

Quoted 21 lines · Timur Tabi
Quoted 7 lines · Alexandre Courbot
Quoted 7 lines
Quoted 6 lines

Also, since dev_dbg can be compiled out, the check performed on the VERS tag existing is not guaranteed to be performed. We should probably extract it out of the dev_dbg statement. This is true across the series; which makes me think it might also benefit from a helper to factor out the request_t.v/Tlv::new/dev_dbg common sequence.

Quoted 6 lines
Quoted 3 lines

We don't care about the VERS tag if we're not going to print it out, so we probably should not
extract it otherwise.

The spec mentions that this tag is present in all TLV files, so its absence means the file is invalid and should trigger an error.

If a tree falls in the woods and no one is around to hear it, does it make a sound?

I see your point, I'm just not sure I agree with it. By that logic, we should test for VERS in the constructor. My concern is that maybe one day we will have a TLV that doesn't have a VERS tag because it's not attached to a versioned firmware image, it's just some misc data.

Quoted 5 lines

I need to think about this a little more. What do you think about testing for VERS in the constructor? We could move the dev_dbg! into the constructor, but then we'd have to pass dev as a parameter.

I'm going to post a v4 today in the meantime.

If you have a spec, then it's either a spec or it's just a waste of time. Assuming that it's a spec, then if it says "shall have a VERS tag", then by gosh we should fail out if that tag is missing.

Otherwise, write the spec differently.

This is not a fuzzy sort of thing.

thanks,

Signature · 1 line
John Hubbard
author
#33 lore raw

Re: [PATCH v3 5/7] gpu: nova-core: transition gen_bootloader to TLV images

Quoted 3 lines · John Hubbard
Quoted 1 line

I'm going to post a v4 today in the meantime.

If you have a spec, then it's either a spec or it's just a waste of time.

That's a little harsh. I was thinking that maybe we should change the spec instead, to specify that if the TLV references a version firmware image, then it should have a VERS tag.

Quoted 6 lines

Assuming that it's a spec, then if it says "shall have a VERS tag", then by gosh we should fail out if that tag is missing.

Otherwise, write the spec differently.

This is not a fuzzy sort of thing.

I thought this was a forum for discussing things?

#34 lore raw

Re: [PATCH v3 5/7] gpu: nova-core: transition gen_bootloader to TLV images

Quoted 7 lines · Timur Tabi
Quoted 3 lines · John Hubbard
Quoted 1 line

I'm going to post a v4 today in the meantime.

If you have a spec, then it's either a spec or it's just a waste of time.

That's a little harsh. I was thinking that maybe we should change the spec instead, to specify that if the TLV references a version firmware image, then it should have a VERS tag.

oh sorry about sounding harsh. I'm trying to communicate that specs are harsh. Because they are.

Quoted 9 lines
Quoted 7 lines

Assuming that it's a spec, then if it says "shall have a VERS tag", then by gosh we should fail out if that tag is missing.

Otherwise, write the spec differently.

This is not a fuzzy sort of thing.

I thought this was a forum for discussing things?

Yes, sorry again, the idea here is that specs are not fuzzy. I'm not trying to quash discussion, just trying to say that if you have a spec, then you either have to change the spec, or *follow it*.

thanks,

Signature · 1 line
John Hubbard
author
#35 lore raw

Re: [PATCH v3 5/7] gpu: nova-core: transition gen_bootloader to TLV images

Quoted 5 lines · John Hubbard
Quoted 1 line

I thought this was a forum for discussing things?

Yes, sorry again, the idea here is that specs are not fuzzy. I'm not trying to quash discussion, just trying to say that if you have a spec, then you either have to change the spec, or *follow it*.

Yes, I would like some opinions on whether the spec should be changed or the driver should reject TLVs without VERS tags.

I'm fine with either. I'm just not 100% sure that we'll never have an unversioned TLV.

#36 lore raw

Re: [PATCH v3 5/7] gpu: nova-core: transition gen_bootloader to TLV images

Quoted 11 lines · Timur Tabi
Quoted 5 lines · John Hubbard
Quoted 1 line

I thought this was a forum for discussing things?

Yes, sorry again, the idea here is that specs are not fuzzy. I'm not trying to quash discussion, just trying to say that if you have a spec, then you either have to change the spec, or *follow it*.

Yes, I would like some opinions on whether the spec should be changed or the driver should reject TLVs without VERS tags.

I'm fine with either. I'm just not 100% sure that we'll never have an unversioned TLV.

I'd suggest keeping it simple and clear: the spec requires VERS tags, and the driver rejects TLVs that don't comply.

If someone creates TLVs without following the spec, then that's just...well, I don't know what it is, but it's wrong and we don't have to care about it.

thanks,

Signature · 1 line
John Hubbard
author
#37 lore raw

Re: [PATCH v3 5/7] gpu: nova-core: transition gen_bootloader to TLV images

Quoted 6 lines · John Hubbard

I'd suggest keeping it simple and clear: the spec requires VERS tags, and the driver rejects TLVs that don't comply.

If someone creates TLVs without following the spec, then that's just...well, I don't know what it is, but it's wrong and we don't have to care about it.

Ok, I'll add a VERS check in the constructor, and maybe a dev_dbg! as well.

author
#38 lore raw

PATCH v3 6/7 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 574e1627e63c..033848772d23 100644
@@ -31,12 +31,9 @@
         Falcon, //
     },
     fb::FbLayout,
-    firmware::{
-        fsp::{
-            FmcSignatures,
-            FspFirmware, //
-        },
-        FIRMWARE_VERSION, //
+    firmware::fsp::{
+        FmcSignatures,
+        FspFirmware, //
     },
     gpu::Chipset,
     gsp::GspFmcBootParams,
@@ -245,7 +242,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
#39 lore raw

PATCH v3 7/7 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