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