1 // SPDX-License-Identifier: GPL-2.0 2 // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. 3 4 //! Contains structures and functions dedicated to the parsing, building and patching of firmwares 5 //! to be loaded into a given execution unit. 6 7 use core::marker::PhantomData; 8 use core::ops::Deref; 9 10 use kernel::{ 11 device, 12 firmware, 13 prelude::*, 14 str::CString, 15 transmute::FromBytes, // 16 }; 17 18 use crate::{ 19 falcon::{ 20 FalconDmaLoadTarget, 21 FalconFirmware, // 22 }, 23 gpu, 24 gsp::boot_firmware_files, 25 num::{ 26 FromSafeCast, 27 IntoSafeCast, // 28 }, 29 }; 30 31 pub(crate) mod booter; 32 pub(crate) mod fsp; 33 pub(crate) mod fwsec; 34 pub(crate) mod gsp; 35 pub(crate) mod riscv; 36 pub(crate) mod tlv; 37 38 pub(crate) const FIRMWARE_VERSION: &str = "570.144"; 39 40 /// Requests the GPU firmware `name` suitable for `chipset`, with version `ver`. 41 fn request_firmware( 42 dev: &device::Device, 43 chipset: gpu::Chipset, 44 name: &str, 45 ver: &str, 46 ) -> Result<firmware::Firmware> { 47 let chip_name = chipset.name(); 48 49 CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{name}-{ver}.bin")) 50 .and_then(|path| firmware::Firmware::request(&path, dev)) 51 } 52 53 /// Structure used to describe some firmwares, notably FWSEC-FRTS. 54 #[repr(C)] 55 #[derive(Debug, Clone, FromBytes)] 56 pub(crate) struct FalconUCodeDescV2 { 57 /// Header defined by 'NV_BIT_FALCON_UCODE_DESC_HEADER_VDESC*' in OpenRM. 58 hdr: u32, 59 /// Stored size of the ucode after the header, compressed or uncompressed 60 stored_size: u32, 61 /// Uncompressed size of the ucode. If store_size == uncompressed_size, then the ucode 62 /// is not compressed. 63 pub(crate) uncompressed_size: u32, 64 /// Code entry point 65 pub(crate) virtual_entry: u32, 66 /// Offset after the code segment at which the Application Interface Table headers are located. 67 pub(crate) interface_offset: u32, 68 /// Base address at which to load the code segment into 'IMEM'. 69 pub(crate) imem_phys_base: u32, 70 /// Size in bytes of the code to copy into 'IMEM' (includes both secure and non-secure 71 /// segments). 72 pub(crate) imem_load_size: u32, 73 /// Virtual 'IMEM' address (i.e. 'tag') at which the code should start. 74 pub(crate) imem_virt_base: u32, 75 /// Virtual address of secure IMEM segment. 76 pub(crate) imem_sec_base: u32, 77 /// Size of secure IMEM segment. 78 pub(crate) imem_sec_size: u32, 79 /// Offset into stored (uncompressed) image at which DMEM begins. 80 pub(crate) dmem_offset: u32, 81 /// Base address at which to load the data segment into 'DMEM'. 82 pub(crate) dmem_phys_base: u32, 83 /// Size in bytes of the data to copy into 'DMEM'. 84 pub(crate) dmem_load_size: u32, 85 /// "Alternate" Size of data to load into IMEM. 86 pub(crate) alt_imem_load_size: u32, 87 /// "Alternate" Size of data to load into DMEM. 88 pub(crate) alt_dmem_load_size: u32, 89 } 90 91 /// Structure used to describe some firmwares, notably FWSEC-FRTS. 92 #[repr(C)] 93 #[derive(Debug, Clone, FromBytes)] 94 pub(crate) struct FalconUCodeDescV3 { 95 /// Header defined by `NV_BIT_FALCON_UCODE_DESC_HEADER_VDESC*` in OpenRM. 96 hdr: u32, 97 /// Stored size of the ucode after the header. 98 stored_size: u32, 99 /// Offset in `DMEM` at which the signature is expected to be found. 100 pub(crate) pkc_data_offset: u32, 101 /// Offset after the code segment at which the app headers are located. 102 pub(crate) interface_offset: u32, 103 /// Base address at which to load the code segment into `IMEM`. 104 pub(crate) imem_phys_base: u32, 105 /// Size in bytes of the code to copy into `IMEM`. 106 pub(crate) imem_load_size: u32, 107 /// Virtual `IMEM` address (i.e. `tag`) at which the code should start. 108 pub(crate) imem_virt_base: u32, 109 /// Base address at which to load the data segment into `DMEM`. 110 pub(crate) dmem_phys_base: u32, 111 /// Size in bytes of the data to copy into `DMEM`. 112 pub(crate) dmem_load_size: u32, 113 /// Mask of the falcon engines on which this firmware can run. 114 pub(crate) engine_id_mask: u16, 115 /// ID of the ucode used to infer a fuse register to validate the signature. 116 pub(crate) ucode_id: u8, 117 /// Number of signatures in this firmware. 118 pub(crate) signature_count: u8, 119 /// Versions of the signatures, used to infer a valid signature to use. 120 pub(crate) signature_versions: u16, 121 _reserved: u16, 122 } 123 124 /// Enum wrapping the different versions of Falcon microcode descriptors. 125 /// 126 /// This allows handling both V2 and V3 descriptor formats through a 127 /// unified type, providing version-agnostic access to firmware metadata 128 /// via the [`FalconUCodeDescriptor`] trait. 129 #[derive(Debug, Clone)] 130 pub(crate) enum FalconUCodeDesc { 131 V2(FalconUCodeDescV2), 132 V3(FalconUCodeDescV3), 133 } 134 135 impl Deref for FalconUCodeDesc { 136 type Target = dyn FalconUCodeDescriptor; 137 138 fn deref(&self) -> &Self::Target { 139 match self { 140 FalconUCodeDesc::V2(v2) => v2, 141 FalconUCodeDesc::V3(v3) => v3, 142 } 143 } 144 } 145 146 /// Trait providing a common interface for accessing Falcon microcode descriptor fields. 147 /// 148 /// This trait abstracts over the different descriptor versions ([`FalconUCodeDescV2`] and 149 /// [`FalconUCodeDescV3`]), allowing code to work with firmware metadata without needing to 150 /// know the specific descriptor version. Fields not present return zero. 151 pub(crate) trait FalconUCodeDescriptor { 152 fn hdr(&self) -> u32; 153 fn imem_load_size(&self) -> u32; 154 fn interface_offset(&self) -> u32; 155 fn dmem_load_size(&self) -> u32; 156 fn pkc_data_offset(&self) -> u32; 157 fn engine_id_mask(&self) -> u16; 158 fn ucode_id(&self) -> u8; 159 fn signature_count(&self) -> u8; 160 fn signature_versions(&self) -> u16; 161 162 /// Returns the size in bytes of the header. 163 fn size(&self) -> usize { 164 let hdr = self.hdr(); 165 166 const HDR_SIZE_SHIFT: u32 = 16; 167 const HDR_SIZE_MASK: u32 = 0xffff0000; 168 ((hdr & HDR_SIZE_MASK) >> HDR_SIZE_SHIFT).into_safe_cast() 169 } 170 171 fn imem_sec_load_params(&self) -> FalconDmaLoadTarget; 172 fn imem_ns_load_params(&self) -> Option<FalconDmaLoadTarget>; 173 fn dmem_load_params(&self) -> FalconDmaLoadTarget; 174 } 175 176 impl FalconUCodeDescriptor for FalconUCodeDescV2 { 177 fn hdr(&self) -> u32 { 178 self.hdr 179 } 180 fn imem_load_size(&self) -> u32 { 181 self.imem_load_size 182 } 183 fn interface_offset(&self) -> u32 { 184 self.interface_offset 185 } 186 fn dmem_load_size(&self) -> u32 { 187 self.dmem_load_size 188 } 189 fn pkc_data_offset(&self) -> u32 { 190 0 191 } 192 fn engine_id_mask(&self) -> u16 { 193 0 194 } 195 fn ucode_id(&self) -> u8 { 196 0 197 } 198 fn signature_count(&self) -> u8 { 199 0 200 } 201 fn signature_versions(&self) -> u16 { 202 0 203 } 204 205 fn imem_sec_load_params(&self) -> FalconDmaLoadTarget { 206 // `imem_sec_base` is the *virtual* start address of the secure IMEM segment, so subtract 207 // `imem_virt_base` to get its physical offset. 208 let imem_sec_start = self.imem_sec_base.saturating_sub(self.imem_virt_base); 209 210 FalconDmaLoadTarget { 211 src_start: imem_sec_start, 212 dst_start: self.imem_phys_base.saturating_add(imem_sec_start), 213 len: self.imem_sec_size, 214 } 215 } 216 217 fn imem_ns_load_params(&self) -> Option<FalconDmaLoadTarget> { 218 Some(FalconDmaLoadTarget { 219 // Non-secure code always starts at offset 0. 220 src_start: 0, 221 dst_start: self.imem_phys_base, 222 // `imem_load_size` includes the size of the secure segment, so subtract it to 223 // get the correct amount of data to copy. 224 len: self.imem_load_size.saturating_sub(self.imem_sec_size), 225 }) 226 } 227 228 fn dmem_load_params(&self) -> FalconDmaLoadTarget { 229 FalconDmaLoadTarget { 230 src_start: self.dmem_offset, 231 dst_start: self.dmem_phys_base, 232 len: self.dmem_load_size, 233 } 234 } 235 } 236 237 impl FalconUCodeDescriptor for FalconUCodeDescV3 { 238 fn hdr(&self) -> u32 { 239 self.hdr 240 } 241 fn imem_load_size(&self) -> u32 { 242 self.imem_load_size 243 } 244 fn interface_offset(&self) -> u32 { 245 self.interface_offset 246 } 247 fn dmem_load_size(&self) -> u32 { 248 self.dmem_load_size 249 } 250 fn pkc_data_offset(&self) -> u32 { 251 self.pkc_data_offset 252 } 253 fn engine_id_mask(&self) -> u16 { 254 self.engine_id_mask 255 } 256 fn ucode_id(&self) -> u8 { 257 self.ucode_id 258 } 259 fn signature_count(&self) -> u8 { 260 self.signature_count 261 } 262 fn signature_versions(&self) -> u16 { 263 self.signature_versions 264 } 265 266 fn imem_sec_load_params(&self) -> FalconDmaLoadTarget { 267 FalconDmaLoadTarget { 268 // IMEM segment always starts at offset 0. 269 src_start: 0, 270 dst_start: self.imem_phys_base, 271 len: self.imem_load_size, 272 } 273 } 274 275 fn imem_ns_load_params(&self) -> Option<FalconDmaLoadTarget> { 276 // Not used on V3 platforms 277 None 278 } 279 280 fn dmem_load_params(&self) -> FalconDmaLoadTarget { 281 FalconDmaLoadTarget { 282 // DMEM segment starts right after the IMEM one. 283 src_start: self.imem_load_size, 284 dst_start: self.dmem_phys_base, 285 len: self.dmem_load_size, 286 } 287 } 288 } 289 290 /// Trait implemented by types defining the signed state of a firmware. 291 trait SignedState {} 292 293 /// Type indicating that the firmware must be signed before it can be used. 294 struct Unsigned; 295 impl SignedState for Unsigned {} 296 297 /// Type indicating that the firmware is signed and ready to be loaded. 298 struct Signed; 299 impl SignedState for Signed {} 300 301 /// Microcode to be loaded into a specific falcon. 302 /// 303 /// This is module-local and meant for sub-modules to use internally. 304 /// 305 /// After construction, a firmware is [`Unsigned`], and must generally be patched with a signature 306 /// before it can be loaded (with an exception for development hardware). The 307 /// [`Self::patch_signature`] and [`Self::no_patch_signature`] methods are used to transition the 308 /// firmware to its [`Signed`] state. 309 // TODO: Consider replacing this with a coherent memory object once `CoherentAllocation` supports 310 // temporary CPU-exclusive access to the object without unsafe methods. 311 struct FirmwareObject<F: FalconFirmware, S: SignedState>(KVVec<u8>, PhantomData<(F, S)>); 312 313 /// Trait for signatures to be patched directly into a given firmware. 314 /// 315 /// This is module-local and meant for sub-modules to use internally. 316 trait FirmwareSignature<F: FalconFirmware>: AsRef<[u8]> {} 317 318 impl<F: FalconFirmware> FirmwareObject<F, Unsigned> { 319 /// Patches the firmware at offset `signature_start` with `signature`. 320 fn patch_signature<S: FirmwareSignature<F>>( 321 mut self, 322 signature: &S, 323 signature_start: usize, 324 ) -> Result<FirmwareObject<F, Signed>> { 325 let signature_bytes = signature.as_ref(); 326 let signature_end = signature_start 327 .checked_add(signature_bytes.len()) 328 .ok_or(EOVERFLOW)?; 329 let dst = self 330 .0 331 .get_mut(signature_start..signature_end) 332 .ok_or(EINVAL)?; 333 334 // PANIC: `dst` and `signature_bytes` have the same length. 335 dst.copy_from_slice(signature_bytes); 336 337 Ok(FirmwareObject(self.0, PhantomData)) 338 } 339 340 /// Mark the firmware as signed without patching it. 341 /// 342 /// This method is used to explicitly confirm that we do not need to sign the firmware, while 343 /// allowing us to continue as if it was. This is typically only needed for development 344 /// hardware. 345 fn no_patch_signature(self) -> FirmwareObject<F, Signed> { 346 FirmwareObject(self.0, PhantomData) 347 } 348 } 349 350 /// Header common to most firmware files. 351 #[repr(C)] 352 #[derive(Debug, Clone)] 353 struct BinHdr { 354 /// Magic number, must be `0x10de`. 355 bin_magic: u32, 356 /// Version of the header. 357 bin_ver: u32, 358 /// Size in bytes of the binary (to be ignored). 359 bin_size: u32, 360 /// Offset of the start of the application-specific header. 361 header_offset: u32, 362 /// Offset of the start of the data payload. 363 data_offset: u32, 364 /// Size in bytes of the data payload. 365 data_size: u32, 366 } 367 368 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability. 369 unsafe impl FromBytes for BinHdr {} 370 371 // A firmware blob starting with a `BinHdr`. 372 struct BinFirmware<'a> { 373 hdr: BinHdr, 374 fw: &'a [u8], 375 } 376 377 impl<'a> BinFirmware<'a> { 378 /// Interpret `fw` as a firmware image starting with a [`BinHdr`], and returns the 379 /// corresponding [`BinFirmware`] that can be used to extract its payload. 380 fn new(fw: &'a firmware::Firmware) -> Result<Self> { 381 const BIN_MAGIC: u32 = 0x10de; 382 let fw = fw.data(); 383 384 fw.get(0..size_of::<BinHdr>()) 385 // Extract header. 386 .and_then(BinHdr::from_bytes_copy) 387 // Validate header. 388 .filter(|hdr| hdr.bin_magic == BIN_MAGIC) 389 .map(|hdr| Self { hdr, fw }) 390 .ok_or(EINVAL) 391 } 392 393 /// Returns the data payload of the firmware, or `None` if the data range is out of bounds of 394 /// the firmware image. 395 fn data(&self) -> Option<&[u8]> { 396 let fw_start = usize::from_safe_cast(self.hdr.data_offset); 397 let fw_size = usize::from_safe_cast(self.hdr.data_size); 398 let fw_end = fw_start.checked_add(fw_size)?; 399 400 self.fw.get(fw_start..fw_end) 401 } 402 } 403 404 pub(crate) struct ModInfoBuilder<const N: usize>(firmware::ModInfoBuilder<N>); 405 406 impl<const N: usize> ModInfoBuilder<N> { 407 const fn make_entry_file(self, chipset: &str, fw: &str) -> Self { 408 ModInfoBuilder( 409 self.0 410 .new_entry() 411 .push("nvidia/") 412 .push(chipset) 413 .push("/gsp/") 414 .push(fw) 415 .push("-") 416 .push(FIRMWARE_VERSION) 417 .push(".bin"), 418 ) 419 } 420 421 const fn make_entry_chipset(self, chipset: gpu::Chipset) -> Self { 422 let name = chipset.name(); 423 424 // GSP firmware files are always present. 425 let mut this = self 426 .make_entry_file(name, "bootloader") 427 .make_entry_file(name, "gsp"); 428 429 // Add the firmware files specific to the GSP boot method of `chipset`. 430 let boot_files = boot_firmware_files(chipset); 431 let mut i = 0; 432 while i < boot_files.len() { 433 this = this.make_entry_file(name, boot_files[i]); 434 i += 1; 435 } 436 437 this 438 } 439 440 pub(crate) const fn create( 441 module_name: &'static core::ffi::CStr, 442 ) -> firmware::ModInfoBuilder<N> { 443 let mut this = Self(firmware::ModInfoBuilder::new(module_name)); 444 let mut i = 0; 445 446 while i < gpu::Chipset::ALL.len() { 447 this = this.make_entry_chipset(gpu::Chipset::ALL[i]); 448 i += 1; 449 } 450 451 this.0 452 } 453 } 454 455 /// Ad-hoc and temporary module to extract sections from ELF images. 456 /// 457 /// Some firmware images are currently packaged as ELF files, where sections names are used as keys 458 /// to specific and related bits of data. Future firmware versions are scheduled to move away from 459 /// that scheme before nova-core becomes stable, which means this module will eventually be 460 /// removed. 461 mod elf { 462 use kernel::{ 463 bindings, 464 prelude::*, 465 transmute::FromBytes, // 466 }; 467 468 /// Trait to abstract over ELF header differences. 469 trait ElfHeader: FromBytes { 470 fn shnum(&self) -> u16; 471 fn shoff(&self) -> u64; 472 fn shstrndx(&self) -> u16; 473 } 474 475 /// Trait to abstract over ELF section-header differences. 476 trait ElfSectionHeader: FromBytes { 477 fn name(&self) -> u32; 478 fn offset(&self) -> u64; 479 fn size(&self) -> u64; 480 } 481 482 /// Trait describing a matching ELF header and section-header format. 483 trait ElfFormat { 484 type Header: ElfHeader; 485 type SectionHeader: ElfSectionHeader; 486 } 487 488 /// Newtype to provide a [`FromBytes`] implementation. 489 #[repr(transparent)] 490 struct Elf64Hdr(bindings::elf64_hdr); 491 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability. 492 unsafe impl FromBytes for Elf64Hdr {} 493 494 impl ElfHeader for Elf64Hdr { 495 fn shnum(&self) -> u16 { 496 self.0.e_shnum 497 } 498 499 fn shoff(&self) -> u64 { 500 self.0.e_shoff 501 } 502 503 fn shstrndx(&self) -> u16 { 504 self.0.e_shstrndx 505 } 506 } 507 508 #[repr(transparent)] 509 struct Elf64SHdr(bindings::elf64_shdr); 510 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability. 511 unsafe impl FromBytes for Elf64SHdr {} 512 513 impl ElfSectionHeader for Elf64SHdr { 514 fn name(&self) -> u32 { 515 self.0.sh_name 516 } 517 518 fn offset(&self) -> u64 { 519 self.0.sh_offset 520 } 521 522 fn size(&self) -> u64 { 523 self.0.sh_size 524 } 525 } 526 527 struct Elf64Format; 528 529 impl ElfFormat for Elf64Format { 530 type Header = Elf64Hdr; 531 type SectionHeader = Elf64SHdr; 532 } 533 534 /// Newtype to provide [`FromBytes`] and [`ElfHeader`] implementations for ELF32. 535 #[repr(transparent)] 536 struct Elf32Hdr(bindings::elf32_hdr); 537 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability. 538 unsafe impl FromBytes for Elf32Hdr {} 539 540 impl ElfHeader for Elf32Hdr { 541 fn shnum(&self) -> u16 { 542 self.0.e_shnum 543 } 544 545 fn shoff(&self) -> u64 { 546 u64::from(self.0.e_shoff) 547 } 548 549 fn shstrndx(&self) -> u16 { 550 self.0.e_shstrndx 551 } 552 } 553 554 /// Newtype to provide [`FromBytes`] and [`ElfSectionHeader`] implementations for ELF32. 555 #[repr(transparent)] 556 struct Elf32SHdr(bindings::elf32_shdr); 557 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability. 558 unsafe impl FromBytes for Elf32SHdr {} 559 560 impl ElfSectionHeader for Elf32SHdr { 561 fn name(&self) -> u32 { 562 self.0.sh_name 563 } 564 565 fn offset(&self) -> u64 { 566 u64::from(self.0.sh_offset) 567 } 568 569 fn size(&self) -> u64 { 570 u64::from(self.0.sh_size) 571 } 572 } 573 574 struct Elf32Format; 575 576 impl ElfFormat for Elf32Format { 577 type Header = Elf32Hdr; 578 type SectionHeader = Elf32SHdr; 579 } 580 581 /// Returns a NULL-terminated string from the ELF image at `offset`. 582 fn elf_str(elf: &[u8], offset: u64) -> Option<&str> { 583 let idx = usize::try_from(offset).ok()?; 584 let bytes = elf.get(idx..)?; 585 CStr::from_bytes_until_nul(bytes).ok()?.to_str().ok() 586 } 587 588 fn elf_section_generic<'a, F>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> 589 where 590 F: ElfFormat, 591 { 592 let hdr = F::Header::from_bytes(elf.get(0..size_of::<F::Header>())?)?; 593 594 let shdr_num = usize::from(hdr.shnum()); 595 let shdr_start = usize::try_from(hdr.shoff()).ok()?; 596 let shdr_end = shdr_num 597 .checked_mul(size_of::<F::SectionHeader>()) 598 .and_then(|v| v.checked_add(shdr_start))?; 599 600 // Get all the section headers as an iterator over byte chunks. 601 let shdr_bytes = elf.get(shdr_start..shdr_end)?; 602 let mut shdr_iter = shdr_bytes.chunks_exact(size_of::<F::SectionHeader>()); 603 604 // Get the strings table. 605 let strhdr = shdr_iter 606 .clone() 607 .nth(usize::from(hdr.shstrndx())) 608 .and_then(F::SectionHeader::from_bytes)?; 609 610 // Find the section which name matches `name` and return it. 611 shdr_iter.find_map(|sh_bytes| { 612 let sh = F::SectionHeader::from_bytes(sh_bytes)?; 613 let name_offset = strhdr.offset().checked_add(u64::from(sh.name()))?; 614 let section_name = elf_str(elf, name_offset)?; 615 616 if section_name != name { 617 return None; 618 } 619 620 let start = usize::try_from(sh.offset()).ok()?; 621 let end = usize::try_from(sh.size()) 622 .ok() 623 .and_then(|sz| start.checked_add(sz))?; 624 625 elf.get(start..end) 626 }) 627 } 628 629 /// Extract the section with name `name` from the ELF64 image `elf`. 630 fn elf64_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { 631 elf_section_generic::<Elf64Format>(elf, name) 632 } 633 634 /// Extract the section with name `name` from the ELF32 image `elf`. 635 fn elf32_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { 636 elf_section_generic::<Elf32Format>(elf, name) 637 } 638 639 /// Automatically detects ELF32 vs ELF64 based on the ELF header. 640 pub(super) fn elf_section<'a>(elf: &'a [u8], name: &str) -> Option<&'a [u8]> { 641 // ELF identification: a 4-byte magic followed by a class byte (32- vs 64-bit). 642 const ELFMAG: &[u8] = b"\x7fELF"; 643 const SELFMAG: usize = ELFMAG.len(); 644 const EI_CLASS: usize = 4; 645 const ELFCLASS32: u8 = 1; 646 const ELFCLASS64: u8 = 2; 647 648 if elf.get(0..SELFMAG) != Some(ELFMAG) { 649 return None; 650 } 651 652 match *elf.get(EI_CLASS)? { 653 ELFCLASS32 => elf32_section(elf, name), 654 ELFCLASS64 => elf64_section(elf, name), 655 _ => None, 656 } 657 } 658 } 659