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