Transition Nova Core to TLV firmware images
Subsystems (9)
cover Transition Nova Core to TLV firmware 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.
Timur Tabi (8):
rust: firmware: add request_into_buf()
gpu: nova-core: add request_tlv to load TLV images
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 | 172 +++++++ drivers/gpu/nova-core/firmware.rs | 451 ++++++++---------- drivers/gpu/nova-core/firmware/booter.rs | 328 +++---------- drivers/gpu/nova-core/firmware/fsp.rs | 84 ++-- .../nova-core/firmware/fwsec/bootloader.rs | 72 +-- drivers/gpu/nova-core/firmware/gsp.rs | 56 +-- drivers/gpu/nova-core/firmware/riscv.rs | 71 +-- drivers/gpu/nova-core/gsp/boot.rs | 7 +- drivers/gpu/nova-core/gsp/hal/gh100.rs | 7 +- drivers/gpu/nova-core/gsp/hal/tu102.rs | 15 +- rust/kernel/firmware.rs | 45 ++ 11 files changed, 575 insertions(+), 733 deletions(-) create mode 100644 Documentation/gpu/nova/core/tlv.rst
base-commit: 9eaff547805f8556992a9474465001c3e128b7bd
prerequisite-patch-id: 0a9ea098bc3576171da9f6293065fdb4db552466
Signature · 1 line
2.54.0
PATCH 1/8 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 | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+)
rust/kernel/firmware.rs +45 -0
@@ -120,6 +120,51 @@ fn drop(&mut self) { } } +/// Load firmware directly into the caller-provided `buf`. +/// +/// On success the firmware image has been copied into `buf`; the number of bytes +/// written is returned. The caller accesses the data through `buf` itself. +/// See also `bindings::request_firmware_into_buf`. +/// +/// 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 an +/// alias of `buf`. Since `buf` is `&mut [u8]` and the returned handle does not borrow it, +/// the caller could mutate `buf` while reads via `data()` are outstanding (and +/// `release_firmware()` does not free `buf` anyway). Releasing the bookkeeping here and +/// returning only the size leaves `buf` as the single owner and accessor of the data. +pub fn request_into_buf (name: &CStr , dev: &Device , buf: &mut [u8 ]) ->Result <usize > { +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)); + } + +// SAFETY: `fw` is a valid pointer returned by `request_firmware_into_buf`. +let size =unsafe { (*fw).size }; + +// 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 (size) +} +// 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
PATCH 2/8 gpu: nova-core: add request_tlv to load TLV images
In reply to Timur TabiAdd function request_tlv() to load TLV firmware images.
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.
Also add some #[allow(unused)] statements to two identifiers that will soon be removed, to keep the patchset clean.
--- drivers/gpu/nova-core/firmware.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)
drivers/gpu/nova-core/firmware.rs +17 -0
@@ -33,9 +33,11 @@pub (crate )mod gsp;pub (crate )mod riscv; +#[allow(unused)] pub (crate )const FIRMWARE_VERSION : &str ="570.144" ;/// Requests the GPU firmware `name` suitable for `chipset`, with version `ver`. +#[allow(unused)] fn request_firmware ( dev: &device::Device , chipset: gpu::Chipset,
@@ -48,6 +50,21 @@ fn request_firmware( .and_then(|path| firmware::Firmware::request(&path, dev)) } +/// Requests the GPU firmware TLV `name` suitable for `chipset`. +#[allow(unused)] +fn request_tlv ( + dev: &device::Device , + chipset: gpu::Chipset , + name: &str , +) ->Result <firmware::Firmware > { +let chip_name = chipset.name (); + +dev_info! (dev,"loading firmware image {}.tlv\n" , name); + +CString ::try_from_fmt (fmt! ("nvidia/{chip_name}/gsp/{name}.tlv" )) + .and_then (|path| firmware::Firmware ::request (&path, dev)) +} +/// Structure used to describe some firmwares, notably FWSEC-FRTS. #[repr( C )] #[derive( Debug , Clone )]
Signature · 1 line
2.54.0
PATCH 3/8 gpu: nova-core: add TLV parser for firmware files
In reply to Timur TabiAdd 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 | 172 ++++++++++++++++++++ drivers/gpu/nova-core/firmware.rs | 239 +++++++++++++++++++++++++++- 2 files changed, 410 insertions(+), 1 deletion(-) create mode 100644 Documentation/gpu/nova/core/tlv.rst
Documentation/gpu/nova/core/tlv.rst new file +172 -0
@@ -0,0 +1,172 @@ +.. 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 encode as a little-endian non-negative integer, and a +sequence of bytes, the size of which is equal to the length rounded +up to the next multiple of 4. + +:: + + +------+------+------+------+ + | '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 + +---------------------------+ + +Values +====== +Values are one of three types: + +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. + + +Common Tags +=========== +These tags appear across multiple firmware types. + +``VERS`` (string) + Human-readable firmware version string, indicates the version of + the firmware. Present in all TLV files. + +A TLV image contains either a ``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, assumed to be in the same directory as the TLV. + 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``. + +GSP Firmware Tags +================= +Used when loading the GSP (GPU System Processor) firmware +(``gsp.bin``). + +``SIGN`` (bytes) + Cryptographic signatures for the GSP firmware, DMA-mapped + for the GSP bootloader to verify before execution. + +Booter Firmware Tags +==================== +Used by the Booter firmware (``booter_load.bin``, +``booter_unload.bin``). + +``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 ``SIGS`` tag. A value + of 0 indicates unsigned firmware. + +``SIGS`` (bytes) + Concatenated array of firmware signatures. The size of + each signature is the total length of the ``SIGS`` value + divided by ``NSIG``. The correct signature is selected + using the fuse-version-derived index. + +Generic Bootloader Tags (FWSEC) +=============================== +Used by the generic bootloader (``gen_bootloader.bin``) that +loads the FWSEC firmware via DMA on Turing GPUs. Also includes +the common ``VERS`` and ``BLOB`` 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``. + +RISC-V Firmware Tags (GSP Bootloader) +====================================== +Used by RISC-V-based firmwares such as the GSP bootloader +(``gsp_bootloader.bin``). Also includes the common ``VERS`` +and ``BLOB`` 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.
drivers/gpu/nova-core/firmware.rs +238 -1
248 lines not on this page · raw message
Signature · 1 line
2.54.0
PATCH 5/8 gpu: nova-core: transition gsp to TLV images
In reply to Timur TabiSwitch 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 | 22 -------- drivers/gpu/nova-core/firmware/gsp.rs | 56 ++++++------------- drivers/gpu/nova-core/firmware/riscv.rs | 71 +++++-------------------- drivers/gpu/nova-core/gsp/boot.rs | 7 +-- 4 files changed, 30 insertions(+), 126 deletions(-)
drivers/gpu/nova-core/firmware.rs +0 -22
@@ -387,28 +387,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 >);
drivers/gpu/nova-core/firmware/gsp.rs +16 -40
93 lines not on this page · raw message
drivers/gpu/nova-core/firmware/riscv.rs +12 -59
91 lines not on this page · raw message
drivers/gpu/nova-core/gsp/boot.rs +2 -5
@@ -20,10 +20,7 @@ Falcon, // }, fb::FbLayout, - firmware::{ - gsp::GspFirmware, - FIRMWARE_VERSION, // - }, + firmware::gsp::GspFirmware, gpu::Chipset, gsp::{ cmdq::Cmdq,
@@ -112,7 +109,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
PATCH 4/8 gpu: nova-core: transition booter_load to TLV images
In reply to Timur TabiSwitch 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 | 328 ++++------------------- drivers/gpu/nova-core/gsp/hal/tu102.rs | 15 +- 3 files changed, 63 insertions(+), 295 deletions(-)
drivers/gpu/nova-core/firmware.rs +1 -14
@@ -21,10 +21,7 @@ FalconFirmware, // }, gpu, - num::{ -FromSafeCast , -IntoSafeCast ,// - }, + num::IntoSafeCast, };pub (crate )mod booter;
@@ -411,16 +408,6 @@ fn new(fw: &'a firmware::Firmware) -> Result<Self> { .map(|hdr| Self { hdr, fw }) .ok_or (EINVAL ) } - -/// Returns the data payload of the firmware, or `None` if the data range is out of bounds of -/// the firmware image. -fn data (&self) ->Option <&[u8 ]> { -let fw_start = usize::from_safe_cast (self.hdr.data_offset); -let fw_size = usize::from_safe_cast (self.hdr.data_size); -let fw_end = fw_start.checked_add (fw_size)?; - - self.fw.get (fw_start..fw_end) - } }pub (crate )struct ModInfoBuilder <const N :usize >(firmware::ModInfoBuilder <N >);
drivers/gpu/nova-core/firmware/booter.rs +57 -271
390 lines not on this page · raw message
drivers/gpu/nova-core/gsp/hal/tu102.rs +5 -10
@@ -27,8 +27,7 @@ FwsecCommand, FwsecFirmware, // }, - gsp::GspFirmware, - FIRMWARE_VERSION, // + gsp::GspFirmware, // }, gpu::Chipset, gsp::{
@@ -113,7 +112,6 @@ fn build( dev, BooterKind::Unloader, chipset, - FIRMWARE_VERSION, sec2_falcon, bar, )?,
@@ -319,15 +317,12 @@ fn boot<'a>("Using SEC2 to load and run the booter_load firmware...\n" ); -BooterFirmware ::new ( +BooterFirmware ::new (dev,BooterKind ::Loader , chipset, sec2_falcon, bar)?.run ( dev, -BooterKind ::Loader , - chipset, -FIRMWARE_VERSION , - sec2_falcon, bar, - )? - .run (dev, bar, sec2_falcon, wpr_meta)?; + sec2_falcon, + wpr_meta, + )?;Ok (unload_guard) }
Signature · 1 line
2.54.0
PATCH 7/8 gpu: nova-core: transition fsp to TLV images
In reply to Timur TabiSwitch 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.
--- drivers/gpu/nova-core/firmware.rs | 207 ------------------------- drivers/gpu/nova-core/firmware/fsp.rs | 84 +++++----- drivers/gpu/nova-core/gsp/hal/gh100.rs | 7 +- 3 files changed, 39 insertions(+), 259 deletions(-)
drivers/gpu/nova-core/firmware.rs +0 -207
@@ -421,213 +421,6 @@ pub(crate) const fn create( } } -/// 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 core::mem::size_of; - -use kernel::{ - bindings, - str::CStr , - 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 , - } - } -} -pub (crate )struct TlvBlock <'a> {pub (crate ) tag: &'astr ,pub (crate ) value: &'a [u8 ],
drivers/gpu/nova-core/firmware/fsp.rs +37 -47
139 lines not on this page · raw message
drivers/gpu/nova-core/gsp/hal/gh100.rs +2 -5
@@ -18,10 +18,7 @@ Falcon, // }, fb::FbLayout, - firmware::{ - fsp::FspFirmware, - FIRMWARE_VERSION, // - }, + firmware::fsp::FspFirmware, fsp::{FmcBootArgs ,Fsp ,//
@@ -160,7 +157,7 @@ fn boot<'a>( gsp_falcon: &'a Falcon<GspEngine>, sec2_falcon: &'a Falcon<Sec2>, ) -> Result<BootUnloadGuard<'a>> { -let fsp_fw =FspFirmware ::new (dev, chipset,FIRMWARE_VERSION )?; +let fsp_fw =FspFirmware ::new (dev, chipset)?;let unload_bundle =crate ::gsp::UnloadBundle ( KBox::new(FspUnloadBundle, GFP_KERNEL)? as KBox<dyn UnloadBundle>
Signature · 1 line
2.54.0
PATCH 6/8 gpu: nova-core: transition gen_bootloader to TLV images
In reply to Timur TabiSwitch 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 | 22 ------ .../nova-core/firmware/fwsec/bootloader.rs | 72 +++++-------------- 2 files changed, 16 insertions(+), 78 deletions(-)
drivers/gpu/nova-core/firmware.rs +0 -22
@@ -366,28 +366,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 +16 -56
115 lines not on this page · raw message
Signature · 1 line
2.54.0
PATCH 8/8 gpu: nova-core: update firmware module info for TLV images
In reply to Timur TabiNow that nova-core loads the TLV firmware images, update the firmware module info to specify those files.
Also remove FIRMWARE_VERSION and request_firmware() as they are no longer used.
--- drivers/gpu/nova-core/firmware.rs | 35 +++++++------------------------ 1 file changed, 8 insertions(+), 27 deletions(-)
drivers/gpu/nova-core/firmware.rs +8 -27
@@ -30,23 +30,6 @@pub (crate )mod gsp;pub (crate )mod riscv; -#[allow(unused)] -pub (crate )const FIRMWARE_VERSION : &str ="570.144" ; - -/// Requests the GPU firmware `name` suitable for `chipset`, with version `ver`. -#[allow(unused)] -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)) -} -/// Requests the GPU firmware TLV `name` suitable for `chipset`. #[allow(unused)] fn request_tlv(
@@ -376,10 +359,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), ) }
@@ -387,20 +367,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,"booter_load.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
Gary Guo
reviewerRe: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Timur TabiQuoted 22 lines · Timur Tabi
Add
request_into_buf(), a Rust wrapper around therequest_firmware_into_buf()function. This variant loads the firmware image directly into a caller-provided buffer rather than a kernel-allocated one.Signed-off-by Timur Tabi <[email protected]>--- rust/kernel/firmware.rs | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+)rust/kernel/firmware.rs +4
-0@@ -120,6 +120,51 @@ fn drop(&mut self) { } } +/// Load firmware directly into the caller-provided `buf`. +/// +/// On success the firmware image has been copied into `buf`; the number of bytes +/// written is returned. The caller accesses the data through `buf` itself.
rust/kernel/firmware.rs fn drop(&mut self) { · line 136
Quoted 10 lines
rust/kernel/firmware.rs +10
-0+/// See also `bindings::request_firmware_into_buf`. +/// +/// 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 an +/// alias of `buf`. Since `buf` is `&mut [u8]` and the returned handle does not borrow it, +/// the caller could mutate `buf` while reads via `data()` are outstanding (and +/// `release_firmware()` does not free `buf` anyway). Releasing the bookkeeping here and +/// returning only the size leaves `buf` as the single owner and accessor of the data. +pub fn request_into_buf (name: &CStr , dev: &Device , buf: &mut [u8 ]) ->Result <usize > {
It looks like this API design is very prone to misuse. Patch 5 of this series for example does not check for the returned size.
Also, I think people might just write buf[..size] and then it'll panic because size can be larger.
Best,
Gary
Quoted 34 lines
rust/kernel/firmware.rs +31
-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 ( + pfw, + name.as_char_ptr (), + dev.as_raw (), + buf.as_mut_ptr ().cast (), + buf.len (), + ) + }; +if ret !=0 { +return Err (Error ::from_errno (ret)); + } + +// SAFETY: `fw` is a valid pointer returned by `request_firmware_into_buf`. +let size =unsafe { (*fw).size }; + +// 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 (size) +} +// 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 {}
Quoted 8 lines · Timur Tabi
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.
Quoted 8 lines
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:
Hi Timur,
A quick heads up on this, it works for Ampere and Blackwell, but it is failing on TU117:
<redforge> ktest $ ./tests/nova_basic_tests.py
PCIe Probe: PASS: Chipset info: all 3 GPUs OK
ok 0000:c1:00.0: NVIDIA (Chipset: TU117, Architecture: Turing, Revision: a.1) ok 0000:c2:00.0: NVIDIA (Chipset: GB202, Architecture: BlackwellGB20x, Revision: a.1) ok 0000:01:00.0: NVIDIA (Chipset: GA104, Architecture: Ampere, Revision: a.1)
Get GPU Name: FAIL: GPU name: 2 of 3 GPUs OK, 1 failed
FAIL 0000:c1:00.0: probe with driver nova-core failed with error -2
ok 0000:c2:00.0: NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition
ok 0000:01:00.0: NVIDIA RTX A4000
dmesg:
nova-core 0000:c1:00.0: Direct firmware load for nvidia/tu117/gsp/gsp_bootloader.tlv failed with error -2 nova-core 0000:c1:00.0: probe with driver nova-core failed with error -2
<redforge> firmware $ ll /lib/firmware/nvidia/tu117/gsp/gsp_bootloader.tlv/bin/ls: cannot access '/lib/firmware/nvidia/tu117/gsp/gsp_bootloader.tlv': No such file or directory
thanks,
Signature · 1 line
John Hubbard
Quoted 37 lines
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.
Timur Tabi (8):
rust: firmware: addrequest_into_buf()
gpu: nova-core: addrequest_tlvto load TLV images
gpu: nova-core: add TLV parser for firmware files
gpu: nova-core: transitionbooter_loadto TLV images
gpu: nova-core: transition gsp to TLV images
gpu: nova-core: transitiongen_bootloaderto TLV images
gpu: nova-core: transition fsp to TLV images
gpu: nova-core: update firmware module info for TLV imagesDocumentation/gpu/nova/core/tlv.rst | 172 +++++++ drivers/gpu/nova-core/firmware.rs | 451 ++++++++---------- drivers/gpu/nova-core/firmware/booter.rs | 328 +++---------- drivers/gpu/nova-core/firmware/fsp.rs | 84 ++-- .../nova-core/firmware/fwsec/bootloader.rs | 72 +-- drivers/gpu/nova-core/firmware/gsp.rs | 56 +-- drivers/gpu/nova-core/firmware/riscv.rs | 71 +-- drivers/gpu/nova-core/gsp/boot.rs | 7 +- drivers/gpu/nova-core/gsp/hal/gh100.rs | 7 +- drivers/gpu/nova-core/gsp/hal/tu102.rs | 15 +- rust/kernel/firmware.rs | 45 ++ 11 files changed, 575 insertions(+), 733 deletions(-) create mode 100644 Documentation/gpu/nova/core/tlv.rstbase-commit:
9eaff547805f8556992a9474465001c3e128b7bd
prerequisite-patch-id:0a9ea098bc3576171da9f6293065fdb4db552466
Quoted 5 lines · John Hubbard
Get GPU Name: FAIL: GPU name: 2 of 3 GPUs OK, 1 failed
FAIL 0000:c1:00.0: probe with driver nova-core failed with error -2 ok 0000:c2:00.0: NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition ok 0000:01:00.0: NVIDIA RTX A4000
Quoted 8 lines
dmesg:
nova-core 0000:c1:00.0: Direct firmware load for nvidia/tu117/gsp/gsp_bootloader.tlv failed with error -2
nova-core 0000:c1:00.0: probe with driver nova-core failed with error -2<redforge> firmware $ ll
/lib/firmware/nvidia/tu117/gsp/gsp_bootloader.tlv/bin/ls: cannot access '/lib/firmware/nvidia/tu117/gsp/gsp_bootloader.tlv': No such file or directory
Yeah, I just noticed yesterday that the symlinks() command in my script is broken. It needs a symlink for gsp_bootloader.tlv.
I'll fix it soon and force-push an update to the git repo.
Re: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Gary GuoQuoted 4 lines · Gary Guo
Quoted 1 line
+pub fn
request_into_buf(name: &CStr, dev: &Device, buf: &mut [u8])-> Result<usize> {It looks like this API design is very prone to misuse. Patch 5 of this series for example does not check for the returned size.
I was debating changing it to use request_partial_firmware_into_buf, which would "encourage" users to verify the return value.
Quoted 2 lines
Also, I think people might just write
buf[..size]and then it'll panic becausesizecan be larger.
Why would it panic if the buffer is larger than the size of the file? The kernel API requires you to know the size of the file before using request_firmware_into_buf(). If the file on disk is larger than the buffer, the kernel returns -EFBIG. If the file on this is smaller, then it is loader completely and the returned Result<usize> is the number of bytes actually loaded from disk.
This has always been a problem for Nouveau because the GSP binary is 90MB in size, and request_firmware() allocates a contiguous block of memory for it, only for us to memcpy it to a vmalloc'd buffer.
So now, thanks to TLVs, we can finally use request_firmware_into_buf() for gsp.bin.
Quoted 4 lines · Timur Tabi
Yeah, I just noticed yesterday that the
symlinks()command in my script is broken. It needs a symlink for gsp_bootloader.tlv.I'll fix it soon and force-push an update to the git repo.
Ok, it should be fixed now:
# ls -l /lib/firmware/nvidia/tu117/gsp/ total 108 -rw-rw-r-- 1 ttabi admin 59064 Jun 10 18:48 booter_load.tlv -rw-rw-r-- 1 ttabi admin 39096 Jun 10 18:48 booter_unload.tlv lrwxrwxrwx 1 ttabi admin 34 Jun 10 18:48 gen_bootloader.tlv -> ../../tu102/gsp/gen_bootloader.tlv lrwxrwxrwx 1 ttabi admin 23 Jun 10 18:48 gsp.bin -> ../../tu102/gsp/gsp.bin -rw-rw-r-- 1 ttabi admin 4152 Jun 10 18:48 gsp.tlv lrwxrwxrwx 1 ttabi admin 34 Jun 10 18:48 gsp_bootloader.tlv -> ../../tu102/gsp/gsp_bootloader.tlv
Since I did force-push, you will need to this to actually pull it:
git reset HEAD^
git pull
For some reason, git pull -f doesn't overwrite local history.
Alternatively, you can just do this:
cd /lib/firmware/nvidia/tu116/gsp/
ln -s ../../tu102/gsp/gsp_bootloader.tlv gsp_bootloader.tlv
This should fix it for tu116 and tu117.
Gary Guo
reviewerRe: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Timur TabiQuoted 9 lines · Timur Tabi
Quoted 4 lines · Gary Guo
Quoted 1 line
+pub fn
request_into_buf(name: &CStr, dev: &Device, buf: &mut [u8])-> Result<usize> {It looks like this API design is very prone to misuse. Patch 5 of this series for example does not check for the returned size.
I was debating changing it to use
request_partial_firmware_into_buf, which would "encourage" users to verify the return value.
Quoted 7 lines
Quoted 2 lines
Also, I think people might just write
buf[..size]and then it'll panic becausesizecan be larger.Why would it panic if the buffer is larger than the size of the file? The kernel API requires you to know the size of the file before using request_firmware_into_buf(). If the file on disk is larger than the buffer, the kernel returns
-EFBIG. If the file on this is smaller, then it is loader completely and the returned Result<usize> is the number of bytes actually loaded from disk.
Right, this is not the partial version of the API, so this would indeed not happen.
BTW, this thread should have been cc'ed to the RfL list, as the abstraction is changed.
Best,
Gary
Quoted 6 lines
This has always been a problem for Nouveau because the GSP binary is 90MB in size, and
request_firmware()allocates a contiguous block of memory for it, only for us to memcpy it to a vmalloc'd buffer.So now, thanks to TLVs, we can finally use
request_firmware_into_buf()for gsp.bin.
Re: [PATCH 1/8] rust: firmware: add request_into_buf()
Quoted 9 lines · Gary Guo
Quoted 1 line
Why would it panic if the buffer is larger than the size of the file? The kernel API requires
you
Quoted 1 line
to know the size of the file before using
request_firmware_into_buf(). If the file on disk islarger
Quoted 2 lines
than the buffer, the kernel returns
-EFBIG. If the file on this is smaller, then it is loader completely and the returned Result<usize> is the number of bytes actually loaded from disk.Right, this is not the partial version of the API, so this would indeed not happen.
So you don't want me to switch to request_partial_firmware_into_buf?
Quoted 2 lines
BTW, this thread should have been cc'ed to the RfL list, as the abstraction is changed.
Oops. I will do that with v2.
Quoted 7 lines · Timur Tabi
Quoted 4 lines · Timur Tabi
Yeah, I just noticed yesterday that the
symlinks()command in my script is broken. It needs a symlink for gsp_bootloader.tlv.I'll fix it soon and force-push an update to the git repo.
Ok, it should be fixed now:
Yes, all better now:
<redforge> ktest $ ./tests/nova_basic_tests.py
PCIe Probe: PASS: Chipset info: all 3 GPUs OK
ok 0000:c1:00.0: NVIDIA (Chipset: TU117, Architecture: Turing, Revision: a.1) ok 0000:c2:00.0: NVIDIA (Chipset: GB202, Architecture: BlackwellGB20x, Revision: a.1) ok 0000:01:00.0: NVIDIA (Chipset: GA104, Architecture: Ampere, Revision: a.1)
Get GPU Name: PASS: GPU name: all 3 GPUs OK
ok 0000:c1:00.0: NVIDIA T400 4GB ok 0000:c2:00.0: NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition ok 0000:01:00.0: NVIDIA RTX A4000
But a follow-up: do you have a quick "undo" command for this? If not, that's OK, because it's only needed between now and when this series gets merged, but at the moment I have to bounce back and forth between reviewing this, and other things that do *not* yet use TLV.
Just a minor convenience, nothing to waste any real time on of course.
Quoted 10 lines
# ls -l /lib/firmware/nvidia/tu117/gsp/ total 108(quoted diff) +0
-2-rw-rw-r-- 1 ttabi admin 59064 Jun 10 18:48 booter_load.tlv -rw-rw-r-- 1 ttabi admin 39096 Jun 10 18:48 booter_unload.tlvlrwxrwxrwx 1 ttabi admin 34 Jun 10 18:48 gen_bootloader.tlv -> ../../tu102/gsp/gen_bootloader.tlv
lrwxrwxrwx 1 ttabi admin 23 Jun 10 18:48 gsp.bin -> ../../tu102/gsp/gsp.bin
-rw-rw-r-- 1 ttabi admin 4152 Jun 10 18:48 gsp.tlv
lrwxrwxrwx 1 ttabi admin 34 Jun 10 18:48 gsp_bootloader.tlv -> ../../tu102/gsp/gsp_bootloader.tlv
Quoted 6 lines
Since I did force-push, you will need to this to actually pull it:
git reset HEAD^
git pullFor some reason,
git pull -fdoesn't overwrite local history.
Eh? "git pull -r" works here, even for force-pushed histories, as it usually does, no need to invent any new steps:
<blueforge> linux-firmware-nova (main)$ git pull -r
remote: Enumerating objects: 3, done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 3 (from 1) Unpacking objects: 100% (3/3), 66.03 MiB | 19.29 MiB/s, done. From https://github.com/ttabi/linux-firmware-nova
+ c2931d3...60f69ef main -> origin/main (forced update)
Successfully rebased and updated refs/heads/main.
<blueforge> linux-firmware-nova (main)$ g60f69eff16b7 nvidia: add v570.144 TLV tarball <Timur Tabi> (Wed, 10 Jun 2026) 1d3cbf7723eb Add README.md LICENCE.nvidia <Timur Tabi> (Fri, 15 May 2026)
And with that, it is all working.
thanks,
Signature · 1 line
John Hubbard
Quoted 23 lines · John Hubbard
Quoted 7 lines · Timur Tabi
Quoted 4 lines · Timur Tabi
Yeah, I just noticed yesterday that the
symlinks()command in my script is broken. It needs a symlink for gsp_bootloader.tlv.I'll fix it soon and force-push an update to the git repo.
Ok, it should be fixed now:
Yes, all better now:
<redforge> ktest $
./tests/nova_basic_tests.py
PCIe Probe: PASS: Chipset info: all 3 GPUs OK
ok 0000:c1:00.0: NVIDIA (Chipset: TU117, Architecture: Turing, Revision: a.1) ok 0000:c2:00.0: NVIDIA (Chipset: GB202, Architecture: BlackwellGB20x, Revision: a.1) ok 0000:01:00.0: NVIDIA (Chipset: GA104, Architecture: Ampere, Revision: a.1)Get GPU Name: PASS: GPU name: all 3 GPUs OK
ok 0000:c1:00.0: NVIDIA T400 4GB
ok 0000:c2:00.0: NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition ok 0000:01:00.0: NVIDIA RTX A4000
Quoted 5 lines
But a follow-up: do you have a quick "undo" command for this? If not, that's OK, because it's only needed between now and when this series gets merged, but at the moment I have to bounce back and forth between reviewing this, and other things that do *not* yet use TLV.
I'll see if I can add a clean.sh script, but in the meantime, Gemini has a few ideas:
https://gemini.google.com/share/a4b48287389d
Quoted 1 line
Just a minor convenience, nothing to waste any real time on of course.
It's bitten me also, so it's a good idea.
Quoted 10 lines
Quoted 7 lines
Since I did force-push, you will need to this to actually pull it:
git reset HEAD^
git pullFor some reason,
git pull -fdoesn't overwrite local history.Eh? "git pull -r" works here, even for force-pushed histories, as it usually does, no need to invent any new steps:
Learn something new every day, thanks.
Danilo Krummrich
maintainerRe: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Gary GuoQuoted 2 lines · Gary Guo
BTW, this thread should have been cc'ed to the RfL list, as the abstraction is changed.
FIRMWARE LOADER uses the driver-core list, so please Cc:
[email protected] and the other FW loader maintainers.
Danilo Krummrich
maintainerRe: [PATCH 2/8] gpu: nova-core: add request_tlv to load TLV images
In reply to Timur TabiQuoted 20 lines · Timur Tabi
Add function
request_tlv()to load TLV firmware images.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.
Also add some #[allow(unused)] statements to two identifiers that will soon be removed, to keep the patchset clean.
Signed-off-by Timur Tabi <[email protected]>--- drivers/gpu/nova-core/firmware.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+)drivers/gpu/nova-core/firmware.rs +0
-0
drivers/gpu/nova-core/firmware.rs line 36
Quoted 4 lines
drivers/gpu/nova-core/firmware.rs +1
-0@@ -33,9 +33,11 @@pub (crate )mod gsp;pub (crate )mod riscv; +#[allow(unused)]
This shouldn't be needed, it can just be removed when once it becomes unused, no?
drivers/gpu/nova-core/firmware.rs fn request_firmware( · line 54
Quoted 13 lines
drivers/gpu/nova-core/firmware.rs +3
-0pub (crate )const FIRMWARE_VERSION : &str ="570.144" ;/// Requests the GPU firmware `name` suitable for `chipset`, with version `ver`. +#[allow(unused)] fn request_firmware ( dev: &device::Device , chipset: gpu::Chipset,@@ -48,6 +50,21 @@ fn request_firmware( .and_then(|path| firmware::Firmware::request(&path, dev)) } +/// Requests the GPU firmware TLV `name` suitable for `chipset`. +#[allow(unused)]
Please use expect instead.
drivers/gpu/nova-core/firmware.rs fn request_firmware( · line 62
Quoted 8 lines
drivers/gpu/nova-core/firmware.rs +8
-0+fn request_tlv ( + dev: &device::Device , + chipset: gpu::Chipset , + name: &str , +) ->Result <firmware::Firmware > { +let chip_name = chipset.name (); + +dev_info! (dev,"loading firmware image {}.tlv\n" , name);
Please use dev_dbg!() instead, this should not be printed under normal operation.
Quoted 9 lines
drivers/gpu/nova-core/firmware.rs +4
-0+CString ::try_from_fmt (fmt! ("nvidia/{chip_name}/gsp/{name}.tlv" )) + .and_then (|path| firmware::Firmware ::request (&path, dev)) +} +/// Structure used to describe some firmwares, notably FWSEC-FRTS. #[repr( C )] #[derive( Debug , Clone )] Signature · 1 line
2.54.0
Danilo Krummrich
maintainerRe: [PATCH 3/8] gpu: nova-core: add TLV parser for firmware files
In reply to Timur TabiDocumentation/gpu/nova/core/tlv.rst line 5
Quoted 11 lines · Timur Tabi
Documentation/gpu/nova/core/tlv.rst new file +5
-0@@ -0,0 +1,172 @@ +.. SPDX-License-Identifier: (GPL-2.0+ OR MIT) + +================================== +TLV Tags in Nova Firmware Images +==================================
Thanks for adding this!
drivers/gpu/nova-core/firmware.rs line 14
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +1
-1@@ -11,7 +11,7 @@ device, firmware, prelude::*, - str::CString, + str::{CStr, CString},
NIT: format
Quoted 23 lines
drivers/gpu/nova-core/firmware.rs +16
-0transmute::FromBytes, // };@@ -684,3 +684,240 @@ pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { } } } + +pub (crate )struct TlvBlock <'a> { +pub (crate ) tag: &'astr , +pub (crate ) 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: &'astr , + length:usize , +} + +impl <'a>TlvBlockHeader <'a> { +const SIZE :usize =size_of ::<[u8 ;4 ]>() +size_of ::<u32 >(); +
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 712
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +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_bytes = hdr.get (..4 )?; +let tag = core::str::from_utf8 (tag_bytes).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 ;
Here and in a couple other cases, nova-core depends on !CPU_BIG_ENDIAN, so that shouldn't be necessary.
I'm not concerned to keep it for documentation purposes, but it may be a bit inconsistent with the rest of the driver.
Quoted 45 lines
drivers/gpu/nova-core/firmware.rs +45
-0+Some (Self { tag, length }) + } +} + +/// Sequential scan over [`Tlv`]. Unlike [`Tlv`], this type carries a cursor (`pos`) into +/// the parent blob. It is not interchangeable with a fresh [`Tlv`] view of the same +/// bytes. +/// +/// # 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: &'tlvTlv <'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. +/// +/// The body relies on a number of `unsafe` operations, because [`Iterator::next`] can +/// only return [`Option`], not [`Result`], so there is no way to report a parse error +/// from here. That is why the entire TLV stream is validated up front in the +/// constructor. By this type's invariants, `self.pos` is always on a block boundary +/// into already-validated data, so each block is known to be well-formed, and +/// therefore the unchecked operations cannot fail. +fn next (&mut self) ->Option <Self ::Item > { +if self.pos >= self.tlv.data.len () { +return None ; + } + +let tail = &self.tlv.data[self.pos..]; + +// SAFETY: `self.pos` is on a block boundary (`TlvIter` invariant) and the check +// above gives `self.pos < data.len()`, so by the `Tlv` invariant a complete +// well-formed block starts at `tail`. +let hdr =unsafe { tail.get_unchecked (..TlvBlockHeader ::SIZE ) }; + +// SAFETY: same header bytes as validated in `Tlv::new` for this offset. +let header =unsafe {TlvBlockHeader ::parse (hdr).unwrap_unchecked () }; +
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 767
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +10
-0+let stored_size = header.length.next_multiple_of (4 ); +let advance =TlvBlockHeader ::SIZE + stored_size; +let payload_end =TlvBlockHeader ::SIZE + header.length; + +// SAFETY: `advance` and `payload_end` are exactly the stored and logical payload extents +// `Tlv::new` accepted for this block. +let value =unsafe { +let block = tail.get_unchecked (..advance); + block.get_unchecked (TlvBlockHeader ::SIZE ..payload_end) + };
Given that this method returns an Option anyways, this could just use the corresponding safe accessors, e.g.
let hdr = tail.get(..TlvBlockHeader::SIZE)?;
Alternatively, we can just use panicking accessors with a '// PANIC' comment, but again, since the function already returns an Option, this isn't a hot path, and the panic comments aren't obviously trivial, it might not be worth it in this case.
That said, I'm fine with either safe or panicking, but I don't like the unsafe accessors.
Quoted 48 lines
drivers/gpu/nova-core/firmware.rs +48
-0+ +// 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; + +Some (TlvBlock { + tag: header.tag, + value, + }) + } +} + +/// The payload of a validated TLV (type, length, value) firmware image. +/// +/// TLV firmware images start with a 4-byte "NVFW" magic header, followed by a sequence of +/// blocks. Each block has a 4-byte type tag, a 4-byte length field, and a data payload +/// 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. +#[allow(dead_code)] +pub (crate )struct Tlv <'a> { + data: &'a [u8 ], +} + +#[allow(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 ) + {
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 825
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +10
-0+return Err (EINVAL ); + } + +// The payload is the contiguous sequence of TLV blocks after the magic. +let payload = data.get (magic_len..).ok_or (EINVAL )?; + +let mut pos =0usize ; +while pos < payload.len () { +// Get the next TLV block. +let Some (rest) = payload.get (pos..)else {
This check doesn't seem to be needed because the loop constraints it directly above, so I'd use let rest = &payload[pos..] instead in this case.
Quoted 65 lines
drivers/gpu/nova-core/firmware.rs +65
-0+return Err (EINVAL ); + }; +// 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 end = pos + .checked_add (TlvBlockHeader ::SIZE ) + .and_then (|p| p.checked_add (stored_size)) + .ok_or (EINVAL )?; +if end > payload.len () { +return Err (EINVAL ); + } + pos = end; + } + +// INVARIANT: the loop above walked `payload` from offset 0 and only stopped once `pos` +// reached `payload.len()` exactly, rejecting any block whose header failed to parse or +// whose stored extent overran. So `payload` is an exact concatenation of well-formed +// blocks with no partial header or trailing slack. +Ok (Self { data: payload }) + } + +fn iter (&self) ->TlvIter <'_, 'a> { +// INVARIANT: 0 is a block boundary, either the start of the first block, +// or `data.len()` when `data` is empty. +TlvIter { tlv: self, pos:0 } + } + +pub (crate )fn len (&self, tag: &str ) ->Result <usize > { +let tlv = self.iter ().find (|b| b.tag == tag).ok_or (EINVAL )?; + +Ok (tlv.value.len ()) + } + +pub (crate )fn get_bytes (&self, tag: &str ) ->Result <&'a [u8 ]> { +let tlv = self.iter ().find (|b| b.tag == tag).ok_or (EINVAL )?; + +Ok (tlv.value) + } + +pub (crate )fn get_u32 (&self, tag: &str ) ->Result <u32 > { +let tlv = self.iter ().find (|b| b.tag == tag).ok_or (EINVAL )?; + + tlv.value + .try_into () + .ok () + .map (u32::from_le_bytes) + .ok_or (EINVAL ) + } + +pub (crate )fn get_string (&self, tag: &str ) ->Result <&'astr > { +let tlv = self.iter ().find (|b| b.tag == tag).ok_or (EINVAL )?; + +// Handle the possibility that the value is null-terminated. +let bytes =match CStr ::from_bytes_until_nul (tlv.value) { +Ok (cstr) => cstr.to_bytes (),
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 900
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +10
-0+ Err(_) => tlv.value, + }; + +// But do require it to be all ASCII. +if !bytes.is_ascii () { +return Err (EINVAL ); + } + + core::str::from_utf8 (bytes).map_err (|_|EINVAL ) + }
Would it make sense to provide those accessors on TlvBlock, so we don't have to create a fresh TlvIter and scan from the start every time?
Quoted 25 lines
drivers/gpu/nova-core/firmware.rs +23
-0+ +/// Returns the `n`-th fixed-size chunk from the value of the TLV entry matching +/// `tag`. +/// +/// The value is treated as an array of contiguous, equally-sized chunks, each +/// `sig_size` bytes long. `sig_size` is the size of one signature. The returned +/// slice is the `n`-th chunk. +/// +/// Returns [`EINVAL`] if no entry matches `tag`, if computing the chunk's offset +/// overflows, or if the value is too short to contain the requested chunk. +pub (crate )fn get_nth_chunk (&self, tag: &str , sig_size:usize , n:usize ) ->Result <&'a [u8 ]> { +let sigs = self + .iter () + .find (|b| b.tag == tag) + .map (|b| b.value) + .ok_or (EINVAL )?; + +let start = sig_size.checked_mul (n).ok_or (EINVAL )?; +let end = start.checked_add (sig_size).ok_or (EINVAL )?; + + sigs.get (start..end).ok_or (EINVAL ) + } +}Signature · 1 line
2.54.0
Alexandre Courbot
maintainerRe: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Timur TabiQuoted 12 lines · Timur Tabi
Quoted 4 lines · Gary Guo
Quoted 1 line
+pub fn
request_into_buf(name: &CStr, dev: &Device, buf: &mut [u8])-> Result<usize> {It looks like this API design is very prone to misuse. Patch 5 of this series for example does not check for the returned size.
I was debating changing it to use
request_partial_firmware_into_buf, which would "encourage" users to verify the return value.Quoted 2 lines
Also, I think people might just write
buf[..size]and then it'll panic becausesizecan be larger.
Quoted 8 lines
Why would it panic if the buffer is larger than the size of the file? The kernel API requires you to know the size of the file before using request_firmware_into_buf(). If the file on disk is larger than the buffer, the kernel returns
-EFBIG. If the file on this is smaller, then it is loader completely and the returned Result<usize> is the number of bytes actually loaded from disk.This has always been a problem for Nouveau because the GSP binary is 90MB in size, and
request_firmware()allocates a contiguous block of memory for it, only for us to memcpy it to a vmalloc'd buffer.
IIUC request_firmware allocates its memory using vmalloc. Unless the firmware is built-in, in which case it returns a pointer to its location in .rodata. That last option is probably the reason for the unconditional copy in Nouveau.
Alexandre Courbot
maintainerRe: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Timur TabiQuoted 22 lines · Timur Tabi
Add
request_into_buf(), a Rust wrapper around therequest_firmware_into_buf()function. This variant loads the firmware image directly into a caller-provided buffer rather than a kernel-allocated one.Signed-off-by Timur Tabi <[email protected]>--- rust/kernel/firmware.rs | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+)rust/kernel/firmware.rs +4
-0@@ -120,6 +120,51 @@ fn drop(&mut self) { } } +/// Load firmware directly into the caller-provided `buf`. +/// +/// On success the firmware image has been copied into `buf`; the number of bytes +/// written is returned. The caller accesses the data through `buf` itself.
rust/kernel/firmware.rs fn drop(&mut self) { · line 136
Quoted 10 lines
rust/kernel/firmware.rs +10
-0+/// See also `bindings::request_firmware_into_buf`. +/// +/// 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 an +/// alias of `buf`. Since `buf` is `&mut [u8]` and the returned handle does not borrow it, +/// the caller could mutate `buf` while reads via `data()` are outstanding (and +/// `release_firmware()` does not free `buf` anyway). Releasing the bookkeeping here and +/// returning only the size leaves `buf` as the single owner and accessor of the data. +pub fn request_into_buf (name: &CStr , dev: &Device , buf: &mut [u8 ]) ->Result <usize > {
By adding a lifetime parameter you can return a Result<&'a mut [u8]>. This is more sound as the caller cannot use the unwritten part of buf. It is also more convenient as there is now no need to create a sub-slice manually.
Alexandre Courbot
maintainerRe: [PATCH 3/8] gpu: nova-core: add TLV parser for firmware files
In reply to Danilo KrummrichOn Thu Jun 11, 2026 at 7:37 AM JST, Danilo Krummrich wrote:
<...>
Quoted 29 lines
Quoted 15 lines
drivers/gpu/nova-core/firmware.rs +15
-0+pub (crate )struct TlvBlock <'a> { +pub (crate ) tag: &'astr , +pub (crate ) 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: &'astr , + length:usize , +} + +impl <'a>TlvBlockHeader <'a> { +const SIZE :usize =size_of ::<[u8 ;4 ]>() +size_of ::<u32 >(); +drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 712
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +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_bytes = hdr.get (..4 )?; +let tag = core::str::from_utf8 (tag_bytes).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 ;Here and in a couple other cases, nova-core depends on !CPU_BIG_ENDIAN, so that shouldn't be necessary.
Quoted 2 lines
I'm not concerned to keep it for documentation purposes, but it may be a bit inconsistent with the rest of the driver.
While relying in the little endianness is useful for things like using FromBytes on data structures, I think it still makes sense to handle it in cases like this one where it is easy to do so.
Code moves, and in the (remote :)) chance that TLV takes off and other drivers want to pick it up, this is one less fix to pick.
Re: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Alexandre CourbotQuoted 9 lines · Alexandre Courbot
Quoted 4 lines
This has always been a problem for Nouveau because the GSP binary is 90MB in size, and
request_firmware()allocates a contiguous block of memory for it, only for us to memcpy it to a
vmalloc'd buffer.IIUC
request_firmwareallocates its memory usingvmalloc. Unless the firmware is built-in, in which case it returns a pointer to its location in.rodata. That last option is probably the reason for the unconditional copy in Nouveau.
It seems you are correct and I'm mis-remembering how request_firmware works.
Still, avoiding the memcpy and a double vmalloc of 90MB seems like a good idea to me.
Re: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Alexandre CourbotQuoted 9 lines · Alexandre Courbot
rust/kernel/firmware.rs fn drop(&mut self) { · line 136
Quoted 4 lines
rust/kernel/firmware.rs +4
-0+/// the caller could mutate `buf` while reads via `data()` are outstanding (and +/// `release_firmware()` does not free `buf` anyway). Releasing the bookkeeping here and +/// returning only the size leaves `buf` as the single owner and accessor of the data. +pub fn request_into_buf (name: &CStr , dev: &Device , buf: &mut [u8 ]) ->Result <usize > {By adding a lifetime parameter you can return a
Result<&'a mut [u8]>. This is more sound as the caller cannot use the unwritten part ofbuf. It is also more convenient as there is now no need to create a sub-slice manually.
Sorry, I don't understand. The caller allocates the buffer any way it wants and passes the slice. This function is basically a gloried memcpy, it doesn't care about lifetimes. Why would I want to add one? It even releases the firmware object before it exits, so there's no kernel-allocated data to retain, which is why it's not part of the Firmware struct.
Quoted 1 line
"the caller cannot use the unwritten part of
buf"
Sure it can. It allocated the buffer, and passed a slice of the whole buffer or just a portion. After the function returns, the caller can do whatever it wants with the buffer, since it owns it outright.
Re: [PATCH 2/8] gpu: nova-core: add request_tlv to load TLV images
In reply to Danilo KrummrichQuoted 13 lines · Danilo Krummrich
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +0
-0@@ -33,9 +33,11 @@ pub(crate) mod gsp; pub(crate) mod riscv;
+#[allow(unused)]This shouldn't be needed, it can just be removed when once it becomes unused, no?
Technically, yes. As a convenience, I removed it here so that I wouldn't have to worry about it in a later patch. I find that the patches themselves are cleaner that way. I don't want to have a patch where the only change to firmware.rs is adding or removing the unused statement.
Quoted 16 lines
Quoted 12 lines
pub(crate) const
FIRMWARE_VERSION: &str = "570.144";
/// Requests the GPU firmwarenamesuitable forchipset, with versionver. +#[allow(unused)]
fn request_firmware(
dev:&device::Device,
chipset:gpu::Chipset,drivers/gpu/nova-core/firmware.rs +0
-0@@ -48,6 +50,21 @@ fn request_firmware( .and_then(|path| firmware::Firmware::request(&path, dev)) }drivers/gpu/nova-core/firmware.rs fn request_firmware( · line 54
Quoted 2 lines
drivers/gpu/nova-core/firmware.rs +2
-0+/// Requests the GPU firmware TLV `name` suitable for `chipset`. +#[allow(unused)] Please use expect instead.
Ok, but why should I use expect here but allowed is for FIRMWARE_VERSION? As soon as I use request_tlv() in patch #4, won't get I get a compiler warning and be forced to change it to allow?
Quoted 11 lines
drivers/gpu/nova-core/firmware.rs fn request_firmware( · line 62
Quoted 8 lines
drivers/gpu/nova-core/firmware.rs +8
-0+fn request_tlv ( + dev: &device::Device, + chipset: gpu::Chipset, + name: &str, +) ->Result <firmware::Firmware > { + let chip_name = chipset.name(); + + dev_info!(dev, "loading firmware image {}.tlv\n", name);Please use dev_dbg!() instead, this should not be printed under normal operation.
Ok.
Gary Guo
reviewerRe: [PATCH 2/8] gpu: nova-core: add request_tlv to load TLV images
Quoted 37 lines · Timur Tabi
Quoted 13 lines · Danilo Krummrich
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +0
-0@@ -33,9 +33,11 @@ pub(crate) mod gsp; pub(crate) mod riscv;
+#[allow(unused)]This shouldn't be needed, it can just be removed when once it becomes unused, no?
Technically, yes. As a convenience, I removed it here so that I wouldn't have to worry about it in a later patch. I find that the patches themselves are cleaner that way. I don't want to have a patch where the only change to
firmware.rsis adding or removing theunusedstatement.Quoted 16 lines
Quoted 12 lines
pub(crate) const
FIRMWARE_VERSION: &str = "570.144";
/// Requests the GPU firmwarenamesuitable forchipset, with versionver. +#[allow(unused)]
fn request_firmware(
dev:&device::Device,
chipset:gpu::Chipset,drivers/gpu/nova-core/firmware.rs +0
-0@@ -48,6 +50,21 @@ fn request_firmware( .and_then(|path| firmware::Firmware::request(&path, dev)) }drivers/gpu/nova-core/firmware.rs fn request_firmware( · line 54
Quoted 2 lines
drivers/gpu/nova-core/firmware.rs +2
-0+/// Requests the GPU firmware TLV `name` suitable for `chipset`. +#[allow(unused)] Please use expect instead.
Quoted 3 lines
Ok, but why should I use
expecthere butallowedis forFIRMWARE_VERSION? As soon as I userequest_tlv()in patch #4, won't get I get a compiler warning and be forced to change it toallow?
The goal is to be able to easily find unused code. If expect is used, then you know for sure the code is unused. If nothing is used then you know for sure the code is used. If allow is used you don't know either way.
#[allow(unused)] should only be used when it's used but gated behind some cfg only.
Best,
Gary
Re: [PATCH 2/8] gpu: nova-core: add request_tlv to load TLV images
Quoted 6 lines · Gary Guo
The goal is to be able to easily find unused code. If
expectis used, then you know for sure the code is unused. If nothing is used then you know for sure the code is used. Ifallowis used you don't know either way.
#[allow(unused)]should only be used when it's used but gated behind some cfg only.
This doesn't make any sense to me. Why would I keep code around if I expect it to be unused? May as well just delete the code.
Are are you saying that in patch #1, I add expect(unused), and then in patch #2 I remove the expect(unused) when I actually use it? Because that seems dumb to me.
To me, the whole point behind allow(unused) is so that I don't need to remove it right away when the last user is deleted. Or conversely, (which is what I'm doing in this case), allow me to add the function without any callers in one patch, and then add the callers in a subsequent patch. Then, after all the callers have been added, I can remove the allow(unused) cleanly.
This gives you a clean sequence of patches, without having to deal with pointless "unusued" warnings that would happen if you only applied a subset of the patches.
Re: [PATCH 3/8] gpu: nova-core: add TLV parser for firmware files
In reply to Alexandre CourbotQuoted 8 lines · Alexandre Courbot
On Thu Jun 11, 2026 at 7:37 AM JST, Danilo Krummrich wrote:
<...>Quoted 6 lines
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 712
Quoted 2 lines
drivers/gpu/nova-core/firmware.rs +2
-0+let len_arr = <[u8 ;4 ]>::try_from (hdr.get (4 ..Self ::SIZE )?).ok ()?; +let length = u32::from_le_bytes (len_arr)as usize ;Here and in a couple other cases, nova-core depends on !CPU_BIG_ENDIAN, so that shouldn't be necessary.
Quoted 7 lines
Quoted 2 lines
I'm not concerned to keep it for documentation purposes, but it may be a bit inconsistent with the rest of the driver.
While relying in the little endianness is useful for things like using
FromByteson data structures, I think it still makes sense to handle it in cases like this one where it is easy to do so.
Ah no, we don't want to add code that is not useful, even if it is easy. We should not have code in Nova that is "aspirational"!
Also, it's actually worse if we are inconsistent about LE/BE throughout the driver, because then no one knows why the code is (sometimes!) there.
Quoted 1 line
Code moves, and in the (remote :)) chance that TLV takes off and other
Not all by itself. Some thought is required.
Quoted 1 line
drivers want to pick it up, this is one less fix to pick.
This sort of reasoning leads to over-engineering, which is of course a sin. :)
Build things correctly for their intended use, and be clear, clean and concise. Then if and when it gets promoted to more general use, that's the time to make any changes.
thanks,
Signature · 1 line
John Hubbard
Gary Guo
reviewerRe: [PATCH 2/8] gpu: nova-core: add request_tlv to load TLV images
In reply to Timur TabiQuoted 10 lines · Timur Tabi
Quoted 6 lines · Gary Guo
The goal is to be able to easily find unused code. If
expectis used, then you know for sure the code is unused. If nothing is used then you know for sure the code is used. Ifallowis used you don't know either way.
#[allow(unused)]should only be used when it's used but gated behind some cfg only.This doesn't make any sense to me. Why would I keep code around if I expect it to be unused? May as well just delete the code.
Which is why #[allow(unused)] is discouraged, because it allows people to keep code around without deleting it.
Quoted 3 lines
Are are you saying that in patch #1, I add expect(unused), and then in patch #2 I remove the expect(unused) when I actually use it? Because that seems dumb to me.
Yes, this is what is expected. No, it's not dumb, because the fact a "unused, but expected to be used" function being actually used is a useful information.
Quoted 5 lines
To me, the whole point behind allow(unused) is so that I don't need to remove it right away when the last user is deleted. Or conversely, (which is what I'm doing in this case), allow me to add the function without any callers in one patch, and then add the callers in a subsequent patch. Then, after all the callers have been added, I can remove the allow(unused) cleanly.
What prevent you from forgetting to remove the allow(unused)?
Quoted 3 lines
This gives you a clean sequence of patches, without having to deal with pointless "unusued" warnings that would happen if you only applied a subset of the patches.
Same for #[expect]
Best,
Gary
Danilo Krummrich
maintainerRe: [PATCH 2/8] gpu: nova-core: add request_tlv to load TLV images
In reply to Timur TabiQuoted 16 lines · Timur Tabi
Quoted 13 lines · Danilo Krummrich
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +0
-0@@ -33,9 +33,11 @@ pub(crate) mod gsp; pub(crate) mod riscv;
+#[allow(unused)]This shouldn't be needed, it can just be removed when once it becomes unused, no?
Quoted 3 lines
Technically, yes. As a convenience, I removed it here so that I wouldn't have to worry about it in a later patch. I find that the patches themselves are cleaner that way. I don't want to have a patch where the only change to
firmware.rsis adding or removing theunusedstatement.
You remove FIRMWARE_VERSION in patch 8 together with its (last) user, so adding #[allow(unused)] here in unnecessary. Am I missing anything?
Quoted 17 lines
Quoted 16 lines
Quoted 12 lines
pub(crate) const
FIRMWARE_VERSION: &str = "570.144";
/// Requests the GPU firmwarenamesuitable forchipset, with versionver. +#[allow(unused)]
fn request_firmware(
dev:&device::Device,
chipset:gpu::Chipset,drivers/gpu/nova-core/firmware.rs +0
-0@@ -48,6 +50,21 @@ fn request_firmware( .and_then(|path| firmware::Firmware::request(&path, dev)) }drivers/gpu/nova-core/firmware.rs fn request_firmware( · line 54
Quoted 2 lines
drivers/gpu/nova-core/firmware.rs +2
-0+/// Requests the GPU firmware TLV `name` suitable for `chipset`. +#[allow(unused)] Please use expect instead.
Quoted 3 lines
Ok, but why should I use
expecthere butallowedis forFIRMWARE_VERSION? As soon as I userequest_tlv()in patch #4, won't get I get a compiler warning and be forced to change it toallow?
Gary already explained it very well.
Thanks,
Danilo
Re: [PATCH 2/8] gpu: nova-core: add request_tlv to load TLV images
In reply to Gary GuoQuoted 8 lines · Gary Guo
Quoted 6 lines
To me, the whole point behind allow(unused) is so that I don't need to remove it right away when
the last user is deleted. Or conversely, (which is what I'm doing in this case), allow me to
add the function without any callers in one patch, and then add the callers in a subsequent patch. Then, after all the callers have been added, I can remove the allow(unused) cleanly.What prevent you from forgetting to remove the
allow(unused)?
Common sense?
I can understand if I wrote a patch set that only added request_tlv() without any users, with the expectation that the users would come in some other patch set.
But this is all in the same patch set, and it's supposed to be applied together. The only reason I added allow(unused) at all is in case someone in the future wants to git-bisect and they land in the middle of my series by coincidence. It serves no purpose otherwise.
Re: [PATCH 2/8] gpu: nova-core: add request_tlv to load TLV images
In reply to Danilo KrummrichQuoted 10 lines · Danilo Krummrich
Quoted 7 lines
Technically, yes. As a convenience, I removed it here so that I wouldn't have to worry about it
in a later patch. I find that the patches themselves are cleaner that way. I don't want to have a patch where the only change tofirmware.rsis adding or removing theunusedstatement.You remove
FIRMWARE_VERSIONin patch 8 together with its (last) user, so adding #[allow(unused)] here in unnecessary. Am I missing anything?
Ah, you're right. At some point during development, I had some other patch be the last user.
Thanks for catching that. I will remove the allow(unused) from FIRMWARE_VERSION.
Re: [PATCH 2/8] gpu: nova-core: add request_tlv to load TLV images
In reply to Timur TabiQuoted 10 lines · Timur Tabi
Quoted 8 lines · Gary Guo
Quoted 6 lines
To me, the whole point behind allow(unused) is so that I don't need to remove it right away when
the last user is deleted. Or conversely, (which is what I'm doing in this case), allow me to
add the function without any callers in one patch, and then add the callers in a subsequent patch. Then, after all the callers have been added, I can remove the allow(unused) cleanly.What prevent you from forgetting to remove the
allow(unused)?
Quoted 9 lines
Common sense?
I can understand if I wrote a patch set that only added
request_tlv()without any users, with the expectation that the users would come in some other patch set.But this is all in the same patch set, and it's supposed to be applied together. The only reason I added allow(unused) at all is in case someone in the future wants to git-bisect and they land in the middle of my series by coincidence. It serves no purpose otherwise.
The series should be git-bisect-friendly, of course.
We've learned that expect(dead_code) is the way to go for this sort of thing. allow is much worse, because it is too easy for it to linger (just as here!) when it's not needed.
thanks,
Signature · 1 line
John Hubbard
Danilo Krummrich
maintainerRe: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Timur TabiQuoted 11 lines · Timur Tabi
Quoted 9 lines · Alexandre Courbot
rust/kernel/firmware.rs fn drop(&mut self) { · line 136
Quoted 4 lines
rust/kernel/firmware.rs +4
-0+/// the caller could mutate `buf` while reads via `data()` are outstanding (and +/// `release_firmware()` does not free `buf` anyway). Releasing the bookkeeping here and +/// returning only the size leaves `buf` as the single owner and accessor of the data. +pub fn request_into_buf (name: &CStr , dev: &Device , buf: &mut [u8 ]) ->Result <usize > {By adding a lifetime parameter you can return a
Result<&'a mut [u8]>. This is more sound as the caller cannot use the unwritten part ofbuf. It is also more convenient as there is now no need to create a sub-slice manually.
Quoted 4 lines
Sorry, I don't understand. The caller allocates the buffer any way it wants and passes the slice. This function is basically a gloried memcpy, it doesn't care about lifetimes. Why would I want to add one? It even releases the
firmwareobject before it exits, so there's no kernel-allocated data to retain, which is why it's not part of the Firmware struct.
It allows you to return a &'a mut [u8], where this is a sub-slice that is already "trimmed" to the length of the actual firmware image loaded. This way callers do not need to bother creating a sub-slice themselves.
The lifetime is required to tell the compiler which argument to infer the output lifetime from.
fn request_into_buf<'a>(name: &CStr, dev: &Device, buf: &'a mut [u8]) -> Result<&'a mut [u8]>
This tells the compiler that the returned sub-slice must not outlive buf. Note that the compiler does only look at the signature, not the function body.
Quoted 5 lines
Quoted 1 line
"the caller cannot use the unwritten part of
buf"Sure it can. It allocated the buffer, and passed a slice of the whole buffer or just a portion. After the function returns, the caller can do whatever it wants with the buffer, since it owns it outright.
True, but there is no reason for the caller to create the sub-slice on its own anymore, i.e. the correct usage becomes the "path of least resistance".
Re: [PATCH 1/8] rust: firmware: add request_into_buf()
Quoted 8 lines · Danilo Krummrich
Quoted 5 lines
Sure it can. It allocated the buffer, and passed a slice of the whole buffer or just a portion.
After the function returns, the caller can do whatever it wants with the buffer, since it owns
it outright.True, but there is no reason for the caller to create the sub-slice on its own anymore, i.e. the correct usage becomes the "path of least resistance".
Is having the caller create the subslice on its own such a big deal? Given the returned size, the caller already has all the info it needs. Most likely, the caller will want to verify size and still use the original buffer.
This just seems like another one of those things that Rust make unnecessarily complicated.
Re: [PATCH 1/8] rust: firmware: add request_into_buf()
Quoted 7 lines · Timur Tabi
Quoted 6 lines · Danilo Krummrich
Quoted 5 lines
Sure it can. It allocated the buffer, and passed a slice of the whole buffer or just a portion.
After the function returns, the caller can do whatever it wants with the buffer, since it owns
it outright.
Quoted 8 lines
Quoted 2 lines
True, but there is no reason for the caller to create the sub-slice on its own anymore, i.e. the correct usage becomes the "path of least resistance".
Is having the caller create the subslice on its own such a big deal? Given the returned
size, the caller already has all the info it needs. Most likely, the caller will want to verifysizeand still use the original buffer.This just seems like another one of those things that Rust make unnecessarily complicated.
Hmmm, interesting. I remain a student of Rust-based design, and am learning that Rust likes to constrain things early in the call stack (often at ctor time, even), so that soundness and correctness don't have to be set up or verified in functions further down.
This is one of those things.
Constraining things so that it is Hard To Do It Wrong is a core theme of Rust programming, and our experts here are helping guide us into it.
Hope that helps.
thanks,
Signature · 1 line
John Hubbard
Re: [PATCH 1/8] rust: firmware: add request_into_buf()
Quoted 6 lines · John Hubbard
Hmmm, interesting. I remain a student of Rust-based design, and am learning that Rust likes to constrain things early in the call stack (often at ctor time, even), so that soundness and correctness don't have to be set up or verified in functions further down.
This is one of those things.
Ok, I can understand that. There is just one problem, however. The code will ignore the returned slice:
let mut fw_vvec = VVec::from_elem(0u8, size, GFP_KERNEL).map_err(|_| ENOMEM)?;
...
let filename = CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{file}"))?;
firmware::request_into_buf(&filename, dev, fw_vvec.as_mut_slice())?;...
Ok(try_pin_init!(Self {
fw <- SGTable::new(dev, fw_vvec, DataDirection::ToDevice, GFP_KERNEL),
The returned slice is of no use in this case. The rest of the code works with the original Vec<u8, Vmalloc>. SGTable::new() can't work with a slice.
Danilo Krummrich
maintainerRe: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Timur TabiQuoted 4 lines · Timur Tabi
Is having the caller create the subslice on its own such a big deal? Given the returned
size, the caller already has all the info it needs. Most likely, the caller will want to verifysizeand still use the original buffer.
My answer was more about addressing your questions regarding why the approach would need a lifetime and why it is the better option if you want to do something with the data before passing it along, and less about expressing an opinion.
That said, the whole point of the API is that the caller already knows the size in advance, which is the premise of being able to provide the pre-allocated buffer in the first place.
For validation the size alone doesn't seem to be overly useful as it is just an indicator. Either the hardware can report a corrupted image, or you probably want to do an integrity check in the driver.
Hence, I think this should either return just Result (as nothing else is needed for now) or a sub-slice. Either is fine with me.
Re: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Timur TabiQuoted 15 lines · Timur Tabi
Quoted 6 lines · John Hubbard
Hmmm, interesting. I remain a student of Rust-based design, and am learning that Rust likes to constrain things early in the call stack (often at ctor time, even), so that soundness and correctness don't have to be set up or verified in functions further down.
This is one of those things.
Ok, I can understand that. There is just one problem, however. The code will ignore the returned slice:
let mut fw_vvec = VVec::from_elem(0u8, size, GFP_KERNEL).map_err(|_| ENOMEM)?; ... let filename = CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{file}"))?; firmware::request_into_buf(&filename, dev, fw_vvec.as_mut_slice())?;
Quoted 6 lines
...
Ok(try_pin_init!(Self {
fw <-SGTable::new(dev, fw_vvec, DataDirection::ToDevice, GFP_KERNEL),The returned slice is of no use in this case. The rest of the code works with the original Vec<u8, Vmalloc>.
SGTable::new()can't work with a slice.
I see that Danilo has addressed this point, in the nearby thread, so I think you're all set, and I don't have anything more to add.
thanks,
Signature · 1 line
John Hubbard
Danilo Krummrich
maintainerRe: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Timur TabiQuoted 1 line · Timur Tabi
The code will ignore the returned slice:
And currently it does ignore the returned usize. :) Please see [1].
Re: [PATCH 3/8] gpu: nova-core: add TLV parser for firmware files
In reply to Danilo KrummrichQuoted 9 lines · Danilo Krummrich
Quoted 3 lines
+ let
len_arr= <[u8; 4]>::try_from(hdr.get(4..Self::SIZE)?).ok()?; + let length =u32::from_le_bytes(len_arr)as usize;Here and in a couple other cases, nova-core depends on !CPU_BIG_ENDIAN, so that shouldn't be necessary.
I'm not concerned to keep it for documentation purposes, but it may be a bit inconsistent with the rest of the driver.
Don't we normally need to use endian-specific functions to convert an array of bytes into an integer?
The only alternative I came up with is this:
let length = u32::from_bytes_copy(hdr.get(4..Self::SIZE)?)? as usize;
I don't think this is an improvement.
Quoted 61 lines
Quoted 51 lines
+
Some(Self { tag, length })
+ }drivers/gpu/nova-core/firmware.rs +48
-0+} + +/// Sequential scan over [`Tlv`]. Unlike [`Tlv`], this type carries a cursor (`pos`) into +/// the parent blob. It is not interchangeable with a fresh [`Tlv`] view of the same +/// bytes. +/// +/// # 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. + /// + /// The body relies on a number of `unsafe` operations, because [`Iterator::next`] can + /// only return [`Option`], not [`Result`], so there is no way to report a parse error + /// from here. That is why the entire TLV stream is validated up front in the + /// constructor. By this type's invariants, `self.pos` is always on a block boundary + /// into already-validated data, so each block is known to be well-formed, and + /// therefore the unchecked operations cannot fail. + fn next(&mut self) -> Option<Self::Item> { + if self.pos >= self.tlv.data.len() { + return None; + } + + let tail = &self.tlv.data[self.pos..]; + + // SAFETY: `self.pos` is on a block boundary (`TlvIter` invariant) and the check + // above gives `self.pos < data.len()`, so by the `Tlv` invariant a complete + // well-formed block starts at `tail`. + let hdr = unsafe { tail.get_unchecked(..TlvBlockHeader::SIZE) }; + + // SAFETY: same header bytes as validated in `Tlv::new` for this offset. + let header = unsafe { TlvBlockHeader::parse(hdr).unwrap_unchecked() }; + + let stored_size = header.length.next_multiple_of(4); + let advance = TlvBlockHeader::SIZE + stored_size; + let payload_end = TlvBlockHeader::SIZE + header.length; + + // SAFETY: `advance` and `payload_end` are exactly the stored and logical payloadQuoted 6 lines
extents
+ //Tlv::newaccepted for this block.
+ let value = unsafe {
+ let block =tail.get_unchecked(..advance); +block.get_unchecked(TlvBlockHeader::SIZE..payload_end)+ };Given that this method returns an Option anyways, this could just use the corresponding safe accessors, e.g.
Quoted 1 line
let hdr = tail.get(..TlvBlockHeader::SIZE)?;
Well, I was under the impression that iterators cannot return errors, so I wanted to avoid ? everywhere. Wouldn't your code just return None in case of error, falsely indicating that the iteration was finished?
Quoted 4 lines
Alternatively, we can just use panicking accessors with a '// PANIC' comment, but again, since the function already returns an Option, this isn't a hot path, and the panic comments aren't obviously trivial, it might not be worth it in this case.
Well, the reason the constructor validates the entire TLV is so that the iterator cannot fail.
Quoted 2 lines
That said, I'm fine with either safe or panicking, but I don't like the unsafe accessors.
I don't like them either, but I don't know how else to handle this.
Quoted 54 lines
Quoted 54 lines
drivers/gpu/nova-core/firmware.rs +53
-0+ + // 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; + + Some(TlvBlock { + tag: header.tag, + value, + }) + } +} + +/// The payload of a validated TLV (type, length, value) firmware image. +/// +/// TLV firmware images start with a 4-byte "NVFW" magic header, followed by a sequence of +/// blocks. Each block has a 4-byte type tag, a 4-byte length field, and a data payload +/// 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. +#[allow(dead_code)] +pub (crate )struct Tlv <'a> { + data: &'a [u8], +} + +#[allow(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)?;
Quoted 8 lines
Quoted 5 lines
+
+ let mut pos = 0usize;
+ while pos <payload.len(){
+ // Get the next TLV block.
+ let Some(rest) =payload.get(pos..)else {This check doesn't seem to be needed because the loop constraints it directly above, so I'd use let rest = &payload[pos..] instead in this case.
Ok.
Quoted 11 lines
Quoted 11 lines
+ pub(crate) fn
get_string(&self, tag: &str)-> Result<&'a str> { + let tlv = self.iter().find(|b| b.tag == tag).ok_or(EINVAL)?;drivers/gpu/nova-core/firmware.rs +9
-0+ + // Handle the possibility that the value is null-terminated. + let bytes = match CStr::from_bytes_until_nul(tlv.value) { + Ok(cstr) => cstr.to_bytes(), + Err(_) => tlv.value, + }; + + // But do require it to be all ASCII. + if !bytes.is_ascii() {
Quoted 8 lines
Quoted 5 lines
+ return Err(EINVAL);
+ }
+
+ core::str::from_utf8(bytes).map_err(|_| EINVAL) + }Would it make sense to provide those accessors on TlvBlock, so we don't have to create a fresh TlvIter and scan from the start every time?
Sorry, I don't understand. We have to iterate from the start every time because we have no idea where in the TLV the requested tag is. There is no requirement to request tags in order.
Keep in mind that most TLVs only have a few tags in them, so all searches are very quick.
Quoted 1 line
Alexandre Courbot
maintainerRe: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Timur TabiQuoted 11 lines · Timur Tabi
Quoted 8 lines · Danilo Krummrich
Quoted 5 lines
Sure it can. It allocated the buffer, and passed a slice of the whole buffer or just a portion.
After the function returns, the caller can do whatever it wants with the buffer, since it owns
it outright.True, but there is no reason for the caller to create the sub-slice on its own anymore, i.e. the correct usage becomes the "path of least resistance".
Is having the caller create the subslice on its own such a big deal?
It is a potential footgun that we can remove through API design.
For the way we use it in Nova, it is not as useful since we work with the backing VVec to DMA-map the pages, and that VVec won't be automatically resized.
But general users are likely to keep working with the slice if they e.g. load the firmware using regular I/O. With a returned slice they cannot forget to check the size.
Alexandre Courbot
maintainerRe: [PATCH 3/8] gpu: nova-core: add TLV parser for firmware files
In reply to Timur TabiQuoted 11 lines · Timur Tabi
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.
Thanks for putting this together, this is quite an improvement.
Quoted 17 lines
Signed-off-by Timur Tabi <[email protected]>--- Documentation/gpu/nova/core/tlv.rst | 172 ++++++++++++++++++++ drivers/gpu/nova-core/firmware.rs | 239 +++++++++++++++++++++++++++- 2 files changed, 410 insertions(+), 1 deletion(-) create mode 100644 Documentation/gpu/nova/core/tlv.rstDocumentation/gpu/nova/core/tlv.rst new file +3
-0@@ -0,0 +1,172 @@ +.. SPDX-License-Identifier: (GPL-2.0+ OR MIT) + +==================================
Documentation/gpu/nova/core/tlv.rst line 13
Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10
-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 encode as a little-endian non-negative integer, and a
"little-endian unsigned" would be more precise (non-negative can also be understood as "signed, but >= 0").
Quoted 26 lines
Documentation/gpu/nova/core/tlv.rst new file +26
-0+sequence of bytes, the size of which is equal to the length rounded +up to the next multiple of 4. + +:: + + +------+------+------+------+ + | 'N' | 'V' | 'F' | 'W' | Magic header + +------+------+------+------+ + | Tag (4 bytes, ASCII) | TLV block 0 + +---------------------------+ + | Length (4 bytes, LE) | + +---------------------------+ + | | + | Value (length bytes, | + | padded to 4-byte align) | + | | + +---------------------------+ + | Tag (4 bytes, ASCII) | TLV block 1 + +---------------------------+ + | Length (4 bytes, LE) | + +---------------------------+ + | | + | Value (length bytes, | + | padded to 4-byte align) | + | | + +---------------------------+
Documentation/gpu/nova/core/tlv.rst line 49
Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10
-0+ | ... | More TLV blocks + +---------------------------+ + +Values +====== +Values are one of three types: + +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.
I think it's worth mentioning that the type is tied to the tag and not encoded in the format.
Documentation/gpu/nova/core/tlv.rst line 62
Quoted 13 lines
Documentation/gpu/nova/core/tlv.rst new file +13
-0+ + +Common Tags +=========== +These tags appear across multiple firmware types. + +``VERS`` (string) + Human-readable firmware version string, indicates the version of + the firmware. Present in all TLV files. + +A TLV image contains either a ``BLOB`` tag (firmware embedded +inline) or a ``SIZE``/``FILE`` pair (firmware stored in a +separate file).
We will also want to specify what happens when neither BLOB nor FILE exist, or when on the contrary both or them are present.
Documentation/gpu/nova/core/tlv.rst line 72
Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10
-0+ +``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, assumed to be in the same directory as the TLV. + This tag is always paired with ``SIZE``, so as to allow the driver to + pre-allocate the buffer before loading the file.
Note that request_firmware outrights reject paths that contain ... These should probably be excluded from the allowed paths here as well.
Documentation/gpu/nova/core/tlv.rst line 76
Quoted 4 lines
Documentation/gpu/nova/core/tlv.rst new file +4
-0+ +``SIZE`` (u32) + Total size in bytes of the firmware image to be loaded from + the companion file named by ``FILE``.
We also need to specify what happens if we have a FILE tag but no SIZE or vice-versa (presumably, this should be an error?).
Another thing I think we should also formally specify: how are duplicate tags handled?
Documentation/gpu/nova/core/tlv.rst line 81
Quoted 5 lines
Documentation/gpu/nova/core/tlv.rst new file +5
-0+ +GSP Firmware Tags +================= +Used when loading the GSP (GPU System Processor) firmware +(``gsp.bin``).
Do you mean gsp.tlv? (same for other files).
Documentation/gpu/nova/core/tlv.rst line 84
Quoted 3 lines
Documentation/gpu/nova/core/tlv.rst new file +3
-0+ +``SIGN`` (bytes) + Cryptographic signatures for the GSP firmware, DMA-mapped
That we DMA-map them is out of scope of the file format imho.
Quoted 49 lines
Documentation/gpu/nova/core/tlv.rst new file +49
-0+ for the GSP bootloader to verify before execution. + +Booter Firmware Tags +==================== +Used by the Booter firmware (``booter_load.bin``, +``booter_unload.bin``). + +``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 ``SIGS`` tag. A value + of 0 indicates unsigned firmware. + +``SIGS`` (bytes)
Documentation/gpu/nova/core/tlv.rst line 143
Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10
-0+ Concatenated array of firmware signatures. The size of + each signature is the total length of the ``SIGS`` value + divided by ``NSIG``. The correct signature is selected + using the fuse-version-derived index. + +Generic Bootloader Tags (FWSEC) +=============================== +Used by the generic bootloader (``gen_bootloader.bin``) that +loads the FWSEC firmware via DMA on Turing GPUs. Also includes +the common ``VERS`` and ``BLOB`` tags.
The common tags are not explicitly mentioned for GSP and Booter - I think we can remove that last sentence.
Quoted 4 lines
Documentation/gpu/nova/core/tlv.rst new file +4
-0+ +``CDSZ`` (u32) - ``code_size`` + Size in bytes of the bootloader code to copy from the + ``BLOB`` tag and PIO-load into falcon IMEM.
Documentation/gpu/nova/core/tlv.rst line 157
Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10
-0+ +``STRT`` (u32) - ``start_tag`` + Start tag identifying the IMEM block where execution begins. + The falcon boot address is derived as ``start_tag << 8``. + +RISC-V Firmware Tags (GSP Bootloader) +====================================== +Used by RISC-V-based firmwares such as the GSP bootloader +(``gsp_bootloader.bin``). Also includes the common ``VERS`` +and ``BLOB`` tags.
Same here.
drivers/gpu/nova-core/firmware.rs
Quoted 19 lines
Documentation/gpu/nova/core/tlv.rst new file +15
-0+ +``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.drivers/gpu/nova-core/firmware.rs +0
-0
Since the code for Tlv seems to be nicely self-contained, can you put it into a sub-module (firmware/tlv.rs)? This will reduce the amount of stuff in firmware.rs too.
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +1
-1@@ -11,7 +11,7 @@ device, firmware, prelude::*, - str::CString, + str::{CStr, CString}, transmute::FromBytes, // };
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 688
Quoted 5 lines
drivers/gpu/nova-core/firmware.rs +2
-0@@ -684,3 +684,240 @@ pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { } } } + +pub (crate )struct TlvBlock <'a> {
TlvBlock and its members can be private IIUC.
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 689
Quoted 1 line
drivers/gpu/nova-core/firmware.rs +1
-0+ pub(crate) tag: &'a str,
This should probably be a &'a [u8; 4]? str is variable length and technically UTF-8, using a 4-bytes array is the more accurate type. Doing this also simplifies parse a bit.
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 696
Quoted 7 lines
drivers/gpu/nova-core/firmware.rs +7
-0+ pub(crate) 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: &'astr ,
Same here.
Quoted 13 lines
drivers/gpu/nova-core/firmware.rs +13
-0+ length: usize, +} + +impl <'a>TlvBlockHeader <'a> { +const SIZE :usize =size_of ::<[u8 ;4 ]>() +size_of ::<u32 >(); + +/// Parses the first [`Self::SIZE`] bytes of `hdr` (caller may pass a longer slice). +fn parse (hdr: &'a [u8 ]) ->Option <Self > { +let hdr = hdr.get (..Self ::SIZE )?; +let tag_bytes = hdr.get (..4 )?; +let tag = core::str::from_utf8 (tag_bytes).ok ()?; +if !tag.is_ascii () { +return None ;
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 719
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +10
-0+ } +let len_arr = <[u8 ;4 ]>::try_from (hdr.get (4 ..Self ::SIZE )?).ok ()?; +let length = u32::from_le_bytes (len_arr)as usize ; +Some (Self { tag, length }) + } +} + +/// Sequential scan over [`Tlv`]. Unlike [`Tlv`], this type carries a cursor (`pos`) into +/// the parent blob. It is not interchangeable with a fresh [`Tlv`] view of the same +/// bytes.
The last two sentences are basically implementation details - are they needed in a public doc?
Quoted 13 lines
drivers/gpu/nova-core/firmware.rs +13
-0+/// +/// # 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: &'tlvTlv <'a>, + pos:usize , +} + +impl <'tlv, 'a>Iterator for TlvIter <'tlv, 'a> { +type Item =TlvBlock <'a>;
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 742
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +10
-0+ +/// Returns the block starting at `self.pos` and advances the cursor past it, or [`None`] +/// once the cursor reaches the end of the data. +/// +/// The body relies on a number of `unsafe` operations, because [`Iterator::next`] can +/// only return [`Option`], not [`Result`], so there is no way to report a parse error +/// from here. That is why the entire TLV stream is validated up front in the +/// constructor. By this type's invariants, `self.pos` is always on a block boundary +/// into already-validated data, so each block is known to be well-formed, and +/// therefore the unchecked operations cannot fail.
Second paragraph also leaks implementation details and is not relevant to users.
Quoted 15 lines
drivers/gpu/nova-core/firmware.rs +15
-0+fn next (&mut self) ->Option <Self ::Item > { +if self.pos >= self.tlv.data.len () { +return None ; + } + +let tail = &self.tlv.data[self.pos..]; + +// SAFETY: `self.pos` is on a block boundary (`TlvIter` invariant) and the check +// above gives `self.pos < data.len()`, so by the `Tlv` invariant a complete +// well-formed block starts at `tail`. +let hdr =unsafe { tail.get_unchecked (..TlvBlockHeader ::SIZE ) }; + +// SAFETY: same header bytes as validated in `Tlv::new` for this offset. +let header =unsafe {TlvBlockHeader ::parse (hdr).unwrap_unchecked () }; +
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 767
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +10
-0+let stored_size = header.length.next_multiple_of (4 ); +let advance =TlvBlockHeader ::SIZE + stored_size; +let payload_end =TlvBlockHeader ::SIZE + header.length; + +// SAFETY: `advance` and `payload_end` are exactly the stored and logical payload extents +// `Tlv::new` accepted for this block. +let value =unsafe { +let block = tail.get_unchecked (..advance); + block.get_unchecked (TlvBlockHeader ::SIZE ..payload_end) + };
As Danilo mentioned we should get rid of these unsafe blocks. I think returning None if an error is met is fine: an error is, technically, the end of the iteration; and we have validated the whole file in the constructor, so they won't happen anyway.
Quoted 45 lines
drivers/gpu/nova-core/firmware.rs +45
-0+ +// 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; + +Some (TlvBlock { + tag: header.tag, + value, + }) + } +} + +/// The payload of a validated TLV (type, length, value) firmware image. +/// +/// TLV firmware images start with a 4-byte "NVFW" magic header, followed by a sequence of +/// blocks. Each block has a 4-byte type tag, a 4-byte length field, and a data payload +/// 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. +#[allow(dead_code)] +pub (crate )struct Tlv <'a> { + data: &'a [u8 ], +} + +#[allow(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
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 822
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +10
-0+ .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 )?; + +let mut pos =0usize ;
You can work directly with payload and avoid storing the position in its own variable. Just make payload's declaration above mut, and then:
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 823
Quoted 1 line
drivers/gpu/nova-core/firmware.rs +1
-0+while pos < payload.len () {
while !payload.is_empty() {drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 827
Quoted 4 lines
drivers/gpu/nova-core/firmware.rs +4
-0+// Get the next TLV block. +let Some (rest) = payload.get (pos..)else { +return Err (EINVAL ); + };
This can disappear.
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 829
Quoted 2 lines
drivers/gpu/nova-core/firmware.rs +2
-0+// Validate and extract the header (type, length). +let Some (header) = rest
s/rest/payload
Quoted 4 lines
drivers/gpu/nova-core/firmware.rs +4
-0+ .get(..TlvBlockHeader::SIZE) + .and_then(TlvBlockHeader::parse) + else { +return Err (EINVAL );
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 843
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +10
-0+ }; +// 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 end = pos + .checked_add (TlvBlockHeader ::SIZE ) + .and_then (|p| p.checked_add (stored_size)) + .ok_or (EINVAL )?;
Here you don't need to add pos anymore.
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 847
Quoted 4 lines
drivers/gpu/nova-core/firmware.rs +4
-0+if end > payload.len () { +return Err (EINVAL ); + } + pos = end;
This becomes:
payload = payload.split_at_checked(end).ok_or(EINVAL)?.1;
Quoted 6 lines
drivers/gpu/nova-core/firmware.rs +6
-0+ } + +// INVARIANT: the loop above walked `payload` from offset 0 and only stopped once `pos` +// reached `payload.len()` exactly, rejecting any block whose header failed to parse or +// whose stored extent overran. So `payload` is an exact concatenation of well-formed +// blocks with no partial header or trailing slack.
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 863
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +10
-0+Ok (Self { data: payload }) + } + +fn iter (&self) ->TlvIter <'_, 'a> { +// INVARIANT: 0 is a block boundary, either the start of the first block, +// or `data.len()` when `data` is empty. +TlvIter { tlv: self, pos:0 } + } + +pub (crate )fn len (&self, tag: &str ) ->Result <usize > {
This method name usually means something different in Rust - it should be documented (all methods should be, ideally), or even better renamed to e.g. tag_len.
But maybe we can also just remove it, since it can be expressed as get_bytes(tag).len(), and is only ever used in one place...
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 869
Quoted 6 lines
drivers/gpu/nova-core/firmware.rs +6
-0+let tlv = self.iter ().find (|b| b.tag == tag).ok_or (EINVAL )?; + +Ok (tlv.value.len ()) + } + +pub (crate )fn get_bytes (&self, tag: &str ) ->Result <&'a [u8 ]> {
For these getter methods as well, tag can be &[u8; 4]. Callers can build a literal using the b prefix, e.g.
let fmc_image_data = tlv.get_bytes(b"BLOB")?;
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 872
Quoted 3 lines
drivers/gpu/nova-core/firmware.rs +3
-0+let tlv = self.iter ().find (|b| b.tag == tag).ok_or (EINVAL )?; + +Ok (tlv.value)
nit: can be collapsed into
self.iter().find(|b| b.tag == tag).map(|b| b.value).ok_or(EINVAL)
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 876
Quoted 4 lines
drivers/gpu/nova-core/firmware.rs +4
-0+ } + +pub (crate )fn get_u32 (&self, tag: &str ) ->Result <u32 > { +let tlv = self.iter ().find (|b| b.tag == tag).ok_or (EINVAL )?;
You can reuse get_bytes to avoid repeating this snippet (also applies to the other get_ methods).
Quoted 7 lines
drivers/gpu/nova-core/firmware.rs +6
-0+ + tlv.value + .try_into () + .ok () + .map (u32::from_le_bytes) + .ok_or (EINVAL )
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 892
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +10
-0+ } + +pub (crate )fn get_string (&self, tag: &str ) ->Result <&'astr > { +let tlv = self.iter ().find (|b| b.tag == tag).ok_or (EINVAL )?; + +// Handle the possibility that the value is null-terminated. +let bytes =match CStr ::from_bytes_until_nul (tlv.value) { +Ok (cstr) => cstr.to_bytes (), +Err (_) => tlv.value, + };
The spec says that strings are expected to be ASCII without a NULL terminator - and the NULL terminator does not carry any meaning in Rust. So I don't think we should be doing that check.
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 897
Quoted 5 lines
drivers/gpu/nova-core/firmware.rs +5
-0+ +// But do require it to be all ASCII. +if !bytes.is_ascii () { +return Err (EINVAL ); + }
Btw, is it bad if we allow strings to be UTF-8?
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 910
Quoted 13 lines
drivers/gpu/nova-core/firmware.rs +13
-0+ + core::str::from_utf8 (bytes).map_err (|_|EINVAL ) + } + +/// Returns the `n`-th fixed-size chunk from the value of the TLV entry matching +/// `tag`. +/// +/// The value is treated as an array of contiguous, equally-sized chunks, each +/// `sig_size` bytes long. `sig_size` is the size of one signature. The returned +/// slice is the `n`-th chunk. +/// +/// Returns [`EINVAL`] if no entry matches `tag`, if computing the chunk's offset +/// overflows, or if the value is too short to contain the requested chunk.
This documentation is confusing - it start by mentioning chunks, then suddenly signature vocabulary is introduced.
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 921
Quoted 11 lines
drivers/gpu/nova-core/firmware.rs +11
-0+pub (crate )fn get_nth_chunk (&self, tag: &str , sig_size:usize , n:usize ) ->Result <&'a [u8 ]> { +let sigs = self + .iter () + .find (|b| b.tag == tag) + .map (|b| b.value) + .ok_or (EINVAL )?; + +let start = sig_size.checked_mul (n).ok_or (EINVAL )?; +let end = start.checked_add (sig_size).ok_or (EINVAL )?; + + sigs.get (start..end).ok_or (EINVAL )
This method is single-use Booter-domain logic, and feels a bit too specialized for a Tlv API. The caller in booter.rs could do:
tlv.get_bytes(b"SIGS")?
.chunks_exact(sig_size)
.nth(index as usize)
.ok_or(EINVAL)?;Alexandre Courbot
maintainerRe: [PATCH 1/8] rust: firmware: add request_into_buf()
In reply to Timur TabiQuoted 21 lines · Timur Tabi
Add
request_into_buf(), a Rust wrapper around therequest_firmware_into_buf()function. This variant loads the firmware image directly into a caller-provided buffer rather than a kernel-allocated one.Signed-off-by Timur Tabi <[email protected]>--- rust/kernel/firmware.rs | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+)rust/kernel/firmware.rs +3
-0@@ -120,6 +120,51 @@ fn drop(&mut self) { } } +/// Load firmware directly into the caller-provided `buf`. +/// +/// On success the firmware image has been copied into `buf`; the number of bytes
rust/kernel/firmware.rs fn drop(&mut self) { · line 135
Quoted 10 lines
rust/kernel/firmware.rs +10
-0+/// written is returned. The caller accesses the data through `buf` itself. +/// See also `bindings::request_firmware_into_buf`. +/// +/// 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 an +/// alias of `buf`. Since `buf` is `&mut [u8]` and the returned handle does not borrow it, +/// the caller could mutate `buf` while reads via `data()` are outstanding (and +/// `release_firmware()` does not free `buf` anyway). Releasing the bookkeeping here and +/// returning only the size leaves `buf` as the single owner and accessor of the data.
I think this last paragraph can stop after the first sentence - the stand-alone approach is the correct one here, interested readers can dive into the code, but this function does not need to justify its existence to every user.
Alexandre Courbot
maintainerRe: [PATCH 8/8] gpu: nova-core: update firmware module info for TLV images
In reply to Timur TabiOn Thu Jun 11, 2026 at 2:49 AM JST, Timur Tabi wrote:
<...>
Quoted 9 lines
drivers/gpu/nova-core/firmware.rs +3
-2@@ -387,20 +367,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,"booter_load.tlv" ) + .make_entry_file (name,"gsp.tlv" ) + .make_entry_file (name,"gsp.bin" );
drivers/gpu/nova-core/firmware.rs const fn make_entry_chipset(self, chipset: gpu::Chipset) -> Self { · line 379
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +2
-3// 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" )
booter_load.tlv is already unconditionally added above, won't this add a duplicate entry?
Re: [PATCH 8/8] gpu: nova-core: update firmware module info for TLV images
Quoted 18 lines · Alexandre Courbot
Quoted 9 lines
let this = self
- .make_entry_file(name, "bootloader")
- .make_entry_file(name, "gsp");
+ .make_entry_file(name, "booter_load.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 byQuoted 8 lines
// 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")
Quoted 2 lines
booter_load.tlvis already unconditionally added above, won't this add a duplicate entry?
Yes, good catch. This was a bad merge on top of John's recent patch.
Re: [PATCH 3/8] gpu: nova-core: add TLV parser for firmware files
In reply to Alexandre CourbotQuoted 37 lines · Alexandre Courbot
Quoted 11 lines · Timur Tabi
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.
Thanks for putting this together, this is quite an improvement.
Quoted 22 lines
Signed-off-by Timur Tabi <[email protected]>---
Documentation/gpu/nova/core/tlv.rst | 172 ++++++++++++++++++++ drivers/gpu/nova-core/firmware.rs | 239 +++++++++++++++++++++++++++-2 files changed, 410 insertions(+), 1 deletion(-)create mode 100644
Documentation/gpu/nova/core/tlv.rstDocumentation/gpu/nova/core/tlv.rst new file +8
-0@@ -0,0 +1,172 @@ +.. 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
Quoted 8 lines
Documentation/gpu/nova/core/tlv.rst line 13
Quoted 5 lines
Documentation/gpu/nova/core/tlv.rst new file +5
-0+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 encode as a little-endian non-negative integer, and a"little-endian unsigned" would be more precise (non-negative can also be understood as "signed, but >= 0").
Ok
Quoted 32 lines
Quoted 32 lines
Documentation/gpu/nova/core/tlv.rst new file +31
-0+sequence of bytes, the size of which is equal to the length rounded +up to the next multiple of 4. + +:: + + +------+------+------+------+ + | '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 + +---------------------------+ + +Values +======
Quoted 8 lines
Documentation/gpu/nova/core/tlv.rst line 49
Quoted 5 lines
Documentation/gpu/nova/core/tlv.rst new file +5
-0+Values are one of three types: + +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.I think it's worth mentioning that the type is tied to the tag and not encoded in the format.
Ok
Quoted 17 lines
Quoted 4 lines
Documentation/gpu/nova/core/tlv.rst new file +3
-0+ + +Common TagsDocumentation/gpu/nova/core/tlv.rst line 62
Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10
-0+=========== +These tags appear across multiple firmware types. + +``VERS`` (string) + Human-readable firmware version string, indicates the version of + the firmware. Present in all TLV files. + +A TLV image contains either a ``BLOB`` tag (firmware embedded +inline) or a ``SIZE``/``FILE`` pair (firmware stored in a +separate file).We will also want to specify what happens when neither BLOB nor FILE exist, or when on the contrary both or them are present.
Ok
Quoted 14 lines
Documentation/gpu/nova/core/tlv.rst line 72
Quoted 11 lines
Documentation/gpu/nova/core/tlv.rst new file +10
-0+ +``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, assumed to be in the same directory as the TLV. + This tag is always paired with ``SIZE``, so as to allow the driver to + pre-allocate the buffer before loading the file.Note that
request_firmwareoutrights reject paths that contain... These should probably be excluded from the allowed paths here as well.
Ok.
I guess that kills the idea of avoiding symlinks.
Quoted 2 lines
We also need to specify what happens if we have a
FILEtag but noSIZEor vice-versa (presumably, this should be an error?).
Technically, it's the caller that decides what to do in each case. There is no central "tag checker" that verifies any of this. I felt that this document should be limited to describing how the tags work if you see one, rather than describing how to actually build a "proper" TLV file. No one is expected to build the TLVs outside of the extract_firmware_nova.py script.
So to answer your question, if there's no SIZE tag, then it will need to use request_firmware() instead of request_firmware_into_buf(). I can add language that says that the SIZE tag should be created if it's at all possible to know the size when the TLV is built.
I don't really have a strong opinion either way.
Quoted 2 lines
Another thing I think we should also formally specify: how are duplicate tags handled?
Well, currently the code will ignore the second copy of the tag, since the iterator always starts from the beginning. I'll add some text that says duplicates are not allowed, but if they exist, only the first tag (in offset order) is used, and the others are ignored.
Quoted 8 lines
Documentation/gpu/nova/core/tlv.rst line 81
Quoted 6 lines
Documentation/gpu/nova/core/tlv.rst new file +5
-0+ +GSP Firmware Tags +================= +Used when loading the GSP (GPU System Processor) firmware +(``gsp.bin``).Do you mean
gsp.tlv? (same for other files).
Hmmm.... I don't think so. But it's obviously so unclear I should remove it. I think the point I was trying to make is that this is the TLV that goes with gsp.bin.
Quoted 4 lines
Documentation/gpu/nova/core/tlv.rst line 84
Quoted 2 lines
Documentation/gpu/nova/core/tlv.rst new file +2
-0+``SIGN`` (bytes) + Cryptographic signatures for the GSP firmware, DMA-mappedThat we DMA-map them is out of scope of the file format imho.
Ok. Also, I need to double-check whether this is SIGN or SIGS still. I should probably document
SIGN = one signature
SIGS = an array of same-sized signatures paired with NSIG
Quoted 54 lines
Quoted 54 lines
Documentation/gpu/nova/core/tlv.rst new file +54
-0+ for the GSP bootloader to verify before execution. + +Booter Firmware Tags +==================== +Used by the Booter firmware (``booter_load.bin``, +``booter_unload.bin``). + +``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 ``SIGS`` tag. A value + of 0 indicates unsigned firmware. + +``SIGS`` (bytes) + Concatenated array of firmware signatures. The size of + each signature is the total length of the ``SIGS`` value + divided by ``NSIG``. The correct signature is selected + using the fuse-version-derived index. +
Quoted 8 lines
Documentation/gpu/nova/core/tlv.rst line 143
Quoted 5 lines
Documentation/gpu/nova/core/tlv.rst new file +5
-0+Generic Bootloader Tags (FWSEC) +=============================== +Used by the generic bootloader (``gen_bootloader.bin``) that +loads the FWSEC firmware via DMA on Turing GPUs. Also includes +the common ``VERS`` and ``BLOB`` tags.The common tags are not explicitly mentioned for GSP and Booter - I think we can remove that last sentence.
Ok
Quoted 33 lines
Quoted 5 lines
Documentation/gpu/nova/core/tlv.rst new file +4
-0+ +``CDSZ`` (u32) - ``code_size`` + Size in bytes of the bootloader code to copy from the + ``BLOB`` tag and PIO-load into falcon IMEM.Documentation/gpu/nova/core/tlv.rst line 157
Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst new file +10
-0+ +``STRT`` (u32) - ``start_tag`` + Start tag identifying the IMEM block where execution begins. + The falcon boot address is derived as ``start_tag << 8``. + +RISC-V Firmware Tags (GSP Bootloader) +====================================== +Used by RISC-V-based firmwares such as the GSP bootloader +(``gsp_bootloader.bin``). Also includes the common ``VERS`` +and ``BLOB`` tags.Same here.
Quoted 15 lines
Documentation/gpu/nova/core/tlv.rst new file +15
-0+ +``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.
Quoted 8 lines
drivers/gpu/nova-core/firmware.rs
Quoted 4 lines
drivers/gpu/nova-core/firmware.rs +0
-0Since the code for
Tlvseems to be nicely self-contained, can you put it into a sub-module (firmware/tlv.rs)? This will reduce the amount of stuff infirmware.rstoo.
Ok.
I was also thinking of merging request_tlv() into the Tlv::new() constructor. Do you think that's a good idea? We always precede Tlv::new() with request_tlv() anyway.
Quoted 10 lines
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs +1
-1@@ -11,7 +11,7 @@ device, firmware, prelude::*, - str::CString, + str::{CStr, CString},
transmute::FromBytes, //
};drivers/gpu/nova-core/firmware.rs +0
-0@@ -684,3 +684,240 @@ pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a
Quoted 8 lines
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 688
Quoted 6 lines
drivers/gpu/nova-core/firmware.rs +0
-0[u8]> { } }}
drivers/gpu/nova-core/firmware.rs +2
-0+ +pub (crate )struct TlvBlock <'a> {
TlvBlockand its members can be private IIUC.
Ok
Quoted 7 lines
Quoted 2 lines
+ pub(crate) tag: &'a str,
This should probably be a
&'a [u8; 4]?stris variable length and technically UTF-8, using a 4-bytes array is the more accurate type. Doing this also simplifiesparsea bit.
Quoted 10 lines
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 696
Quoted 8 lines
+ pub(crate) value: &'a [u8],
drivers/gpu/nova-core/firmware.rs +3
-0+} + +/// On-wire TLV block header: 4-byte ASCII tag + little-endian payload length (bytes, excluding
drivers/gpu/nova-core/firmware.rs +3
-0+/// padding to a 4-byte boundary). +struct TlvBlockHeader <'a> { + tag: &'a str,Same here.
I made these as strings to simplify the iterator so that it can just compare strings, but I will take another look at the code.
Quoted 18 lines
Quoted 18 lines
+ length: usize,
drivers/gpu/nova-core/firmware.rs +17
-0+} + +impl <'a>TlvBlockHeader <'a> { + const SIZE: usize = size_of::<[u8; 4]>() + size_of::<u32>(); + + /// Parses the first [`Self::SIZE`] bytes of `hdr` (caller may pass a longer slice). + fn parse(hdr: &'a [u8]) -> Option<Self> { + let hdr = hdr.get(..Self::SIZE)?; + let tag_bytes = hdr.get(..4)?; + let tag = core::str::from_utf8(tag_bytes).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; + Some(Self { tag, length }) + }
Quoted 8 lines
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 719
Quoted 5 lines
drivers/gpu/nova-core/firmware.rs +5
-0+} + +/// Sequential scan over [`Tlv`]. Unlike [`Tlv`], this type carries a cursor (`pos`) into +/// the parent blob. It is not interchangeable with a fresh [`Tlv`] view of the same +/// bytes. The last two sentences are basically implementation details - are they needed in a public doc?
Uh, I think I wrote that to help me keep track of the code, but now I'm not quite sure what it means. I'll take another look, and probably delete it.
Quoted 20 lines
Quoted 20 lines
drivers/gpu/nova-core/firmware.rs +4
-0+/// +/// # Invariants +/// +/// `pos` is a byte offset into `tlv.data` that always lies on a block boundary (in the sense
drivers/gpu/nova-core/firmware.rs +11
-0+/// 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.
+ ///
+ /// The body relies on a number ofunsafeoperations, because [Iterator::next] can
Quoted 8 lines
Quoted 5 lines
+ /// only return [
Option], not [Result], so there is no way to report a parse error + /// from here. That is why the entire TLV stream is validated up front in the + /// constructor. By this type's invariants,self.posis always on a block boundary + /// into already-validated data, so each block is known to be well-formed, and + /// therefore the unchecked operations cannot fail.Second paragraph also leaks implementation details and is not relevant to users.
Ok. I like to add these kinds of comments, because I figure that if it was hard for me to figure out, then others would probably appreciate it. I wish the Nouveau code had been documented like that.
Quoted 23 lines
Quoted 23 lines
+ fn
next(&mut self)-> Option<Self::Item> {
+ if self.pos >=self.tlv.data.len(){
+ return None;
+ }drivers/gpu/nova-core/firmware.rs +16
-0+ + let tail = &self.tlv.data[self.pos..]; + + // SAFETY: `self.pos` is on a block boundary (`TlvIter` invariant) and the check + // above gives `self.pos < data.len()`, so by the `Tlv` invariant a complete + // well-formed block starts at `tail`. + let hdr = unsafe { tail.get_unchecked(..TlvBlockHeader::SIZE) }; + + // SAFETY: same header bytes as validated in `Tlv::new` for this offset. + let header = unsafe { TlvBlockHeader::parse(hdr).unwrap_unchecked() }; + + let stored_size = header.length.next_multiple_of(4); + let advance = TlvBlockHeader::SIZE + stored_size; + let payload_end = TlvBlockHeader::SIZE + header.length; + + // SAFETY: `advance` and `payload_end` are exactly the stored and logical payloadextents
+ //Tlv::newaccepted for this block.
+ let value = unsafe {
Quoted 8 lines
Quoted 3 lines
+ let block =
tail.get_unchecked(..advance); +block.get_unchecked(TlvBlockHeader::SIZE..payload_end)+ };As Danilo mentioned we should get rid of these
unsafeblocks. I think returningNoneif an error is met is fine: an error is, technically, the end of the iteration; and we have validated the whole file in the constructor, so they won't happen anyway.
Ok. I really don't like conflating Option with Result, though. I figured in this case, it would be better to eliminate any validation code that will never execute, but no one seems to mind so I'll change it. I'll just add a comment that technically this iterator will return None on errors that won't never actually occur because the TLV is validated.
Quoted 62 lines
Quoted 52 lines
+ // INVARIANT: by the
Tlvinvariant the block atself.posoccupies exactlyadvance
+ // bytes, soself.pos + advanceis the next block boundary (ordata.len()). + self.pos += advance;drivers/gpu/nova-core/firmware.rs +23
-0+ + Some(TlvBlock { + tag: header.tag, + value, + }) + } +} + +/// The payload of a validated TLV (type, length, value) firmware image. +/// +/// TLV firmware images start with a 4-byte "NVFW" magic header, followed by a sequence of +/// blocks. Each block has a 4-byte type tag, a 4-byte length field, and a data payload +/// 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.
drivers/gpu/nova-core/firmware.rs +14
-0+/// 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. +#[allow(dead_code)] +pub (crate )struct Tlv <'a> { + data: &'a [u8], +} + +#[allow(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 ismalformed.
+ pub(crate) fnnew(data: &'a [u8])-> Result<Self> {
+ // Verify that the magic bytes exist and are the correct value + letmagic_len=Self::MAGIC.len();
+ if data
+ .get(..magic_len)
+ .is_none_or(|magic| magic !=Self::MAGIC)
+ {
+ return Err(EINVAL);
+ }drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 822
Quoted 5 lines
drivers/gpu/nova-core/firmware.rs +5
-0+ + // The payload is the contiguous sequence of TLV blocks after the magic. + let payload = data.get(magic_len..).ok_or(EINVAL)?; + + let mut pos = 0usize;You can work directly with
payloadand avoid storing the position in its own variable. Just makepayload's declaration abovemut, and then:
Quoted 4 lines
Quoted 1 line
+ while pos <
payload.len(){while !payload.is_empty() {
Ok. I thought it would be safer to make an integer mut instead of a slice.
Quoted 6 lines
Quoted 4 lines
+ // Get the next TLV block.
+ let Some(rest) =payload.get(pos..)else { + return Err(EINVAL);
+ };This can disappear.
Ok
Quoted 5 lines
Quoted 3 lines
+ // Validate and extract the header (type, length). + let Some(header) = rest
s/rest/payload
Only if I make payload mut as you suggest, right?
Quoted 18 lines
Quoted 15 lines
+ .get(..TlvBlockHeader::SIZE)
+ .and_then(TlvBlockHeader::parse)
+ else {
+ return Err(EINVAL);
+ };
+ // Thelengthfield of a TLV block contains the actual byte length of the + // value, but each TLV block is aligned to a 4-byte boundary. + letSome(stored_size)=header.length.checked_next_multiple_of(4)else { + return Err(EINVAL);
+ };
+ let end = pos
+ .checked_add(TlvBlockHeader::SIZE)
+ .and_then(|p|p.checked_add(stored_size))
+ .ok_or(EINVAL)?;Here you don't need to add
posanymore.
Quoted 8 lines
Quoted 4 lines
+ if end >
payload.len(){
+ return Err(EINVAL);
+ }
+ pos = end;This becomes:
payload = payload.split_at_checked(end).ok_or(EINVAL)?.1;
Ok
Quoted 25 lines
Quoted 12 lines
+ }
+
+ // INVARIANT: the loop above walkedpayloadfrom offset 0 and only stopped oncepos
+ // reachedpayload.len()exactly, rejecting any block whose header failed to parse or
+ // whose stored extent overran. Sopayloadis an exact concatenation of well- formed
+ // blocks with no partial header or trailing slack.
+ Ok(Self { data: payload })
+ }drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 863
Quoted 8 lines
drivers/gpu/nova-core/firmware.rs +8
-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 } + } + + pub(crate) fn len(&self, tag: &str) -> Result<usize> {This method name usually means something different in Rust - it should be documented (all methods should be, ideally), or even better renamed to e.g.
tag_len.
Quoted 2 lines
But maybe we can also just remove it, since it can be expressed as
get_bytes(tag).len(), and is only ever used in one place...
Ok
Quoted 11 lines
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 869
Quoted 7 lines
+ let tlv = self.iter().find(|b| b.tag == tag).ok_or(EINVAL)?;
drivers/gpu/nova-core/firmware.rs +5
-0+ + Ok(tlv.value.len()) + } + + pub(crate) fn get_bytes(&self, tag: &str) -> Result<&'a [u8]> {For these getter methods as well,
tagcan be&[u8; 4]. Callers can build a literal using thebprefix, e.g.
Quoted 1 line
let
fmc_image_data=tlv.get_bytes(b"BLOB")?;
Ah ok.
Quoted 8 lines
Quoted 4 lines
+ let tlv = self.iter().find(|b| b.tag == tag).ok_or(EINVAL)?; +
+ Ok(tlv.value)nit: can be collapsed into
self.iter().find(|b| b.tag == tag).map(|b| b.value).ok_or(EINVAL)
I mean, yes it can be, but I don't see how that's an improvement. That first line
let tlv = self.iter().find(|b| b.tag == tag).ok_or(EINVAL)?;
exists in each getter, for consistency. So I can only "collapse it" in get_bytes, not in any of the others.
Quoted 8 lines
Quoted 5 lines
+ }
+
+ pub(crate) fnget_u32(&self, tag: &str)-> Result<u32> { + let tlv = self.iter().find(|b| b.tag == tag).ok_or(EINVAL)?;You can reuse
get_bytesto avoid repeating this snippet (also applies to the otherget_methods).
I would rather have a private "find_tlv" method, so that all the getters are independent.
Quoted 12 lines
Quoted 12 lines
drivers/gpu/nova-core/firmware.rs +12
-0+ + tlv.value + .try_into() + .ok() + .map(u32::from_le_bytes) + .ok_or(EINVAL) + } + + pub(crate) fn get_string(&self, tag: &str) -> Result<&'a str> { + let tlv = self.iter().find(|b| b.tag == tag).ok_or(EINVAL)?; + + // Handle the possibility that the value is null-terminated.
Quoted 8 lines
Quoted 4 lines
+ let bytes = match
CStr::from_bytes_until_nul(tlv.value){ + Ok(cstr) =>cstr.to_bytes(),
+Err(_)=> tlv.value,
+ };The spec says that strings are expected to be ASCII without a NULL terminator - and the NULL terminator does not carry any meaning in Rust. So I don't think we should be doing that check.
Ok. I thought I was being crafty here.
Quoted 7 lines
Quoted 5 lines
+
+ // But do require it to be all ASCII.
+ if !bytes.is_ascii() {
+ return Err(EINVAL);
+ }Btw, is it bad if we allow strings to be UTF-8?
Depends on your definition of "bad" I guess. printk doesn't have any real UTF-8 support, it just kinda works if you're careful. I added this check because string tags are meant to be things like file names and version strings, and those things really should not be UTF-8. Multi- byte characters cause all sorts of problems. We're not using TLV to store people's names.
Quoted 8 lines
Quoted 8 lines
drivers/gpu/nova-core/firmware.rs +8
-0+ + core::str::from_utf8(bytes).map_err(|_| EINVAL) + } + + /// Returns the `n`-th fixed-size chunk from the value of the TLV entry matching + /// `tag`. + /// + /// The value is treated as an array of contiguous, equally-sized chunks, each
Quoted 8 lines
Quoted 5 lines
+ ///
sig_sizebytes long.sig_sizeis the size of one signature. The returned + /// slice is then-th chunk.
+ ///
+ /// Returns [EINVAL] if no entry matchestag, if computing the chunk's offset + /// overflows, or if the value is too short to contain the requested chunk.This documentation is confusing - it start by mentioning chunks, then suddenly signature vocabulary is introduced.
Hmmm I'm not sure what happened there, but I'll fix it.
Quoted 17 lines
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 921
Quoted 13 lines
+ pub(crate) fn
get_nth_chunk(&self, tag: &str, sig_size: usize, n: usize)-> Result<&'a [u8]> {
+ let sigs = self
+ .iter()
+ .find(|b| b.tag == tag)
+ .map(|b| b.value)
+ .ok_or(EINVAL)?;drivers/gpu/nova-core/firmware.rs +5
-0+ + let start = sig_size.checked_mul(n).ok_or(EINVAL)?; + let end = start.checked_add(sig_size).ok_or(EINVAL)?; + + sigs.get(start..end).ok_or(EINVAL)This method is single-use Booter-domain logic, and feels a bit too specialized for a
TlvAPI. The caller inbooter.rscould do:
Quoted 4 lines
tlv.get_bytes(b"SIGS")?
.chunks_exact(sig_size)
.nth(index as usize)
.ok_or(EINVAL)?;
Ok. When I wrote this, I didn't think there was only one user. Plus, this lets me get rid of the awkward documentation.
Alexandre Courbot
maintainerRe: [PATCH 3/8] gpu: nova-core: add TLV parser for firmware files
On Sat Jun 13, 2026 at 3:04 AM JST, Timur Tabi wrote:
<...>
Quoted 14 lines
Quoted 5 lines
Quoted 5 lines
Documentation/gpu/nova/core/tlv.rst new file +5
-0+ +``BLOB`` (bytes) + If the firmware microcode binary is stored in the TLV, this tag contains + the actual firmware image bytes. +Quoted 8 lines
Quoted 5 lines
+``FILE`` (string)
+ If the firmware binary is stored as a separate file, this tag contains the + name of that file, assumed to be in the same directory as the TLV. + This tag is always paired with ``SIZE``, so as to allow the driver to + pre-allocate the buffer before loading the file.Note that
request_firmwareoutrights reject paths that contain... These should probably be excluded from the allowed paths here as well.
Quoted 3 lines
Ok.
I guess that kills the idea of avoiding symlinks.
Pretty much. We could technically mangle the paths ourselves in the kernel, but that's likely to be frowned upon.
Quoted 8 lines
Quoted 3 lines
We also need to specify what happens if we have a
FILEtag but noSIZEor vice-versa (presumably, this should be an error?).Technically, it's the caller that decides what to do in each case. There is no central "tag checker" that verifies any of this. I felt that this document should be limited to describing how the tags work if you see one, rather than describing how to actually build a "proper" TLV file. No one is expected to build the TLVs outside of the
extract_firmware_nova.pyscript.
Since this is a file format specification, I'd argue it should on the contrary try to pin down what is a valid TLV file and what is not. Essentially so we can rely on it to make changes that have backward-compatibility implications in the future.
Quoted 4 lines
So to answer your question, if there's no SIZE tag, then it will need to use
request_firmware()instead ofrequest_firmware_into_buf(). I can add language that says that the SIZE tag should be created if it's at all possible to know the size when the TLV is built.
Yes, I think that would remove all ambiguity.
Quoted 9 lines
I don't really have a strong opinion either way.
Quoted 2 lines
Another thing I think we should also formally specify: how are duplicate tags handled?
Well, currently the code will ignore the second copy of the tag, since the iterator always starts from the beginning. I'll add some text that says duplicates are not allowed, but if they exist, only the first tag (in offset order) is used, and the others are ignored.
Sounds good to me.
Quoted 11 lines
Quoted 10 lines
Documentation/gpu/nova/core/tlv.rst line 81
Quoted 8 lines
Documentation/gpu/nova/core/tlv.rst new file +5
-0+ +GSP Firmware Tags +================= +Used when loading the GSP (GPU System Processor) firmware +(``gsp.bin``).Do you mean
gsp.tlv? (same for other files).
Quoted 2 lines
Hmmm.... I don't think so. But it's obviously so unclear I should remove it. I think the point I was trying to make is that this is the TLV that goes with gsp.bin.
I guess I was confused because gsp.tlv could technically point to a different file through its FILE tag. The real anchor for the driver is gsp.tlv.
<...>
Quoted 9 lines
Quoted 8 lines
drivers/gpu/nova-core/firmware.rs
Quoted 4 lines
drivers/gpu/nova-core/firmware.rs +0
-0Since the code for
Tlvseems to be nicely self-contained, can you put it into a sub-module (firmware/tlv.rs)? This will reduce the amount of stuff infirmware.rstoo.
Quoted 4 lines
Ok.
I was also thinking of merging
request_tlv()into theTlv::new()constructor. Do you think that's a good idea? We always precedeTlv::new()withrequest_tlv()anyway.
I like the request wording because it implies more strongly that we are loading something. Maybe a Tlv::request constructor?
Having Tlv::new take an array of bytes looks natural and separates parsing from loading. It also enables things like nested TLV files should we ever need that.
Quoted 40 lines
Quoted 11 lines
Quoted 11 lines
drivers/gpu/nova-core/firmware.rs +1
-1@@ -11,7 +11,7 @@ device, firmware, prelude::*, - str::CString, + str::{CStr, CString},
transmute::FromBytes, //
};drivers/gpu/nova-core/firmware.rs +0
-0@@ -684,3 +684,240 @@ pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'aQuoted 8 lines
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 688
Quoted 6 lines
drivers/gpu/nova-core/firmware.rs +0
-0[u8]> { } }}
drivers/gpu/nova-core/firmware.rs +2
-0+ +pub (crate )struct TlvBlock <'a> {
TlvBlockand its members can be private IIUC.Ok
Quoted 7 lines
Quoted 2 lines
+ pub(crate) tag: &'a str,
This should probably be a
&'a [u8; 4]?stris variable length and technically UTF-8, using a 4-bytes array is the more accurate type. Doing this also simplifiesparsea bit.Quoted 10 lines
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 696
Quoted 8 lines
+ pub(crate) value: &'a [u8],
drivers/gpu/nova-core/firmware.rs +3
-0+} + +/// On-wire TLV block header: 4-byte ASCII tag + little-endian payload length (bytes, excluding
drivers/gpu/nova-core/firmware.rs +3
-0+/// padding to a 4-byte boundary). +struct TlvBlockHeader <'a> { + tag: &'a str,Same here.
Quoted 2 lines
I made these as strings to simplify the iterator so that it can just compare strings, but I will take another look at the code.
Comparison of [u8; 4]s should be equally trivial to perform.
<...>
Quoted 29 lines
Quoted 20 lines
Quoted 20 lines
drivers/gpu/nova-core/firmware.rs +4
-0+/// +/// # Invariants +/// +/// `pos` is a byte offset into `tlv.data` that always lies on a block boundary (in the sense
drivers/gpu/nova-core/firmware.rs +11
-0+/// 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.
+ ///
+ /// The body relies on a number ofunsafeoperations, because [Iterator::next] canQuoted 8 lines
Quoted 5 lines
+ /// only return [
Option], not [Result], so there is no way to report a parse error + /// from here. That is why the entire TLV stream is validated up front in the + /// constructor. By this type's invariants,self.posis always on a block boundary + /// into already-validated data, so each block is known to be well-formed, and + /// therefore the unchecked operations cannot fail.Second paragraph also leaks implementation details and is not relevant to users.
Quoted 3 lines
Ok. I like to add these kinds of comments, because I figure that if it was hard for me to figure out, then others would probably appreciate it. I wish the Nouveau code had been documented like that.
It's fine to turn these into regular code comments if you think they are useful (although in this case it looks like we are heading towards removing the unsafe statements anyway). It's just that they don't bring information that users will find directly useful and would justify them being doccomments.
Quoted 33 lines
Quoted 24 lines
Quoted 24 lines
+ fn
next(&mut self)-> Option<Self::Item> {
+ if self.pos >=self.tlv.data.len(){
+ return None;
+ }drivers/gpu/nova-core/firmware.rs +16
-0+ + let tail = &self.tlv.data[self.pos..]; + + // SAFETY: `self.pos` is on a block boundary (`TlvIter` invariant) and the check + // above gives `self.pos < data.len()`, so by the `Tlv` invariant a complete + // well-formed block starts at `tail`. + let hdr = unsafe { tail.get_unchecked(..TlvBlockHeader::SIZE) }; + + // SAFETY: same header bytes as validated in `Tlv::new` for this offset. + let header = unsafe { TlvBlockHeader::parse(hdr).unwrap_unchecked() }; + + let stored_size = header.length.next_multiple_of(4); + let advance = TlvBlockHeader::SIZE + stored_size; + let payload_end = TlvBlockHeader::SIZE + header.length; + + // SAFETY: `advance` and `payload_end` are exactly the stored and logical payloadextents
+ //Tlv::newaccepted for this block.
+ let value = unsafe {Quoted 8 lines
Quoted 3 lines
+ let block =
tail.get_unchecked(..advance); +block.get_unchecked(TlvBlockHeader::SIZE..payload_end)+ };As Danilo mentioned we should get rid of these
unsafeblocks. I think returningNoneif an error is met is fine: an error is, technically, the end of the iteration; and we have validated the whole file in the constructor, so they won't happen anyway.
Quoted 4 lines
Ok. I really don't like conflating Option with Result, though. I figured in this case, it would be better to eliminate any validation code that will never execute, but no one seems to mind so I'll change it. I'll just add a comment that technically this iterator will return None on errors that won't never actually occur because the TLV is validated.
Yeah, it's a tradeoff really. Ideally we would be able to represent the validation done by the constructor using the type system and rely on that to make the iterator safe and infallible. Here it looks like we cannot, so the options are doing redundant error handling, panicking, or unsafe code.
Unsafe code looks out of place in a parser that is not in any critical path. I am not a fan of panicking either as it adds a landmine just because nobody is ever supposed to step there and makes it harder to prove that the code is indeed safe. This leaves error handling as the least bad of the 3 options.
But since meeting these errors would technically be a bug in the code, we can at least log them using pr_err! so they don't go unnoticed.
<...>
Quoted 25 lines
Quoted 25 lines
Quoted 15 lines
drivers/gpu/nova-core/firmware.rs +5
-0+#[allow(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 ismalformed.
+ pub(crate) fnnew(data: &'a [u8])-> Result<Self> {
+ // Verify that the magic bytes exist and are the correct value + letmagic_len=Self::MAGIC.len();
+ if data
+ .get(..magic_len)
+ .is_none_or(|magic| magic !=Self::MAGIC)
+ {
+ return Err(EINVAL);
+ }drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 822
Quoted 5 lines
drivers/gpu/nova-core/firmware.rs +5
-0+ + // The payload is the contiguous sequence of TLV blocks after the magic. + let payload = data.get(magic_len..).ok_or(EINVAL)?; + + let mut pos = 0usize;You can work directly with
payloadand avoid storing the position in its own variable. Just makepayload's declaration abovemut, and then:
Quoted 6 lines
Quoted 4 lines
Quoted 1 line
+ while pos <
payload.len(){while !payload.is_empty() {
Ok. I thought it would be safer to make an integer mut instead of a slice.
The slice should be the safer option as it has less state to keep track of.
Note that the mut keyword applies to the slice itself, not what it points to - you still cannot modify the content of payload, you can just assign a different slice to the payload variable.
Quoted 11 lines
Quoted 7 lines
Quoted 5 lines
+ // Get the next TLV block.
+ let Some(rest) =payload.get(pos..)else { + return Err(EINVAL);
+ };This can disappear.
Ok
Quoted 1 line
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines
+ // Validate and extract the header (type, length). + let Some(header) = rest
s/rest/payload
Only if I make payload mut as you suggest, right?
Oh yes these comments are still about dropping pos.
<...>
Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
+ let tlv = self.iter().find(|b| b.tag == tag).ok_or(EINVAL)?; +
+ Ok(tlv.value)nit: can be collapsed into
Quoted 8 lines
Quoted 1 line
self.iter().find(|b| b.tag == tag).map(|b| b.value).ok_or(EINVAL)
I mean, yes it can be, but I don't see how that's an improvement. That first line
let tlv = self.iter().find(|b| b.tag == tag).ok_or(EINVAL)?;exists in each getter, for consistency. So I can only "collapse it" in
get_bytes, not in any of the others.
You can also chain more map and other operators. This gives a functional vibe to the method which feels slightly more idiomatic in Rust, but it is not critical if you prefer to keep it procedural. Both read fine for something that short.
Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
+ }
+
+ pub(crate) fnget_u32(&self, tag: &str)-> Result<u32> { + let tlv = self.iter().find(|b| b.tag == tag).ok_or(EINVAL)?;
Quoted 4 lines
Quoted 2 lines
You can reuse
get_bytesto avoid repeating this snippet (also applies to the otherget_methods).I would rather have a private "
find_tlv" method, so that all the getters are independent.
That would work as well.
Quoted 31 lines
Quoted 13 lines
Quoted 13 lines
drivers/gpu/nova-core/firmware.rs +12
-0+ + tlv.value + .try_into() + .ok() + .map(u32::from_le_bytes) + .ok_or(EINVAL) + } + + pub(crate) fn get_string(&self, tag: &str) -> Result<&'a str> { + let tlv = self.iter().find(|b| b.tag == tag).ok_or(EINVAL)?; + + // Handle the possibility that the value is null-terminated.Quoted 8 lines
Quoted 4 lines
+ let bytes = match
CStr::from_bytes_until_nul(tlv.value){ + Ok(cstr) =>cstr.to_bytes(),
+Err(_)=> tlv.value,
+ };The spec says that strings are expected to be ASCII without a NULL terminator - and the NULL terminator does not carry any meaning in Rust. So I don't think we should be doing that check.
Ok. I thought I was being crafty here.
Quoted 6 lines
Quoted 5 lines
+
+ // But do require it to be all ASCII.
+ if !bytes.is_ascii() {
+ return Err(EINVAL);
+ }
Quoted 6 lines
Quoted 1 line
Btw, is it bad if we allow strings to be UTF-8?
Depends on your definition of "bad" I guess. printk doesn't have any real UTF-8 support, it just kinda works if you're careful. I added this check because string tags are meant to be things like file names and version strings, and those things really should not be UTF-8. Multi- byte characters cause all sorts of problems. We're not using TLV to store people's names.
Mmm indeed there is probably no real benefit here.
Re: [PATCH 3/8] gpu: nova-core: add TLV parser for firmware files
In reply to Alexandre CourbotQuoted 1 line · Alexandre Courbot
On Thu Jun 11, 2026 at 2:49 AM JST, Timur Tabi wrote:
...
Quoted 11 lines
The spec says that strings are expected to be ASCII without a NULL terminator - and the NULL terminator does not carry any meaning in Rust. So I don't think we should be doing that check.
drivers/gpu/nova-core/firmware.rs pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { · line 897
Quoted 5 lines
drivers/gpu/nova-core/firmware.rs +5
-0+ +// But do require it to be all ASCII. +if !bytes.is_ascii () { +return Err (EINVAL ); + }Btw, is it bad if we allow strings to be UTF-8?
Yes, it is bad. :) This is a tightly constrained file format, rather than a general purpose filesystem. As such, sharply constraining it makes the code simpler and easier to confirm correct, whether via reading the code on the screen, or setting up test coverage.
thanks,
Signature · 1 line
John Hubbard