1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Contains structures and functions dedicated to the parsing, building and patching of firmwares 4 //! to be loaded into a given execution unit. 5 6 use core::marker::PhantomData; 7 use core::mem::size_of; 8 9 use kernel::device; 10 use kernel::firmware; 11 use kernel::prelude::*; 12 use kernel::str::CString; 13 use kernel::transmute::FromBytes; 14 15 use crate::dma::DmaObject; 16 use crate::falcon::FalconFirmware; 17 use crate::gpu; 18 use crate::gpu::Chipset; 19 20 pub(crate) mod booter; 21 pub(crate) mod fwsec; 22 pub(crate) mod gsp; 23 24 pub(crate) const FIRMWARE_VERSION: &str = "535.113.01"; 25 26 /// Requests the GPU firmware `name` suitable for `chipset`, with version `ver`. 27 fn request_firmware( 28 dev: &device::Device, 29 chipset: gpu::Chipset, 30 name: &str, 31 ver: &str, 32 ) -> Result<firmware::Firmware> { 33 let chip_name = chipset.name(); 34 35 CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{name}-{ver}.bin")) 36 .and_then(|path| firmware::Firmware::request(&path, dev)) 37 } 38 39 /// Structure encapsulating the firmware blobs required for the GPU to operate. 40 #[expect(dead_code)] 41 pub(crate) struct Firmware { 42 bootloader: firmware::Firmware, 43 } 44 45 impl Firmware { 46 pub(crate) fn new(dev: &device::Device, chipset: Chipset, ver: &str) -> Result<Firmware> { 47 let request = |name| request_firmware(dev, chipset, name, ver); 48 49 Ok(Firmware { 50 bootloader: request("bootloader")?, 51 }) 52 } 53 } 54 55 /// Structure used to describe some firmwares, notably FWSEC-FRTS. 56 #[repr(C)] 57 #[derive(Debug, Clone)] 58 pub(crate) struct FalconUCodeDescV3 { 59 /// Header defined by `NV_BIT_FALCON_UCODE_DESC_HEADER_VDESC*` in OpenRM. 60 hdr: u32, 61 /// Stored size of the ucode after the header. 62 stored_size: u32, 63 /// Offset in `DMEM` at which the signature is expected to be found. 64 pub(crate) pkc_data_offset: u32, 65 /// Offset after the code segment at which the app 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`. 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 /// Base address at which to load the data segment into `DMEM`. 74 pub(crate) dmem_phys_base: u32, 75 /// Size in bytes of the data to copy into `DMEM`. 76 pub(crate) dmem_load_size: u32, 77 /// Mask of the falcon engines on which this firmware can run. 78 pub(crate) engine_id_mask: u16, 79 /// ID of the ucode used to infer a fuse register to validate the signature. 80 pub(crate) ucode_id: u8, 81 /// Number of signatures in this firmware. 82 pub(crate) signature_count: u8, 83 /// Versions of the signatures, used to infer a valid signature to use. 84 pub(crate) signature_versions: u16, 85 _reserved: u16, 86 } 87 88 impl FalconUCodeDescV3 { 89 /// Returns the size in bytes of the header. 90 pub(crate) fn size(&self) -> usize { 91 const HDR_SIZE_SHIFT: u32 = 16; 92 const HDR_SIZE_MASK: u32 = 0xffff0000; 93 94 ((self.hdr & HDR_SIZE_MASK) >> HDR_SIZE_SHIFT) as usize 95 } 96 } 97 98 /// Trait implemented by types defining the signed state of a firmware. 99 trait SignedState {} 100 101 /// Type indicating that the firmware must be signed before it can be used. 102 struct Unsigned; 103 impl SignedState for Unsigned {} 104 105 /// Type indicating that the firmware is signed and ready to be loaded. 106 struct Signed; 107 impl SignedState for Signed {} 108 109 /// A [`DmaObject`] containing a specific microcode ready to be loaded into a falcon. 110 /// 111 /// This is module-local and meant for sub-modules to use internally. 112 /// 113 /// After construction, a firmware is [`Unsigned`], and must generally be patched with a signature 114 /// before it can be loaded (with an exception for development hardware). The 115 /// [`Self::patch_signature`] and [`Self::no_patch_signature`] methods are used to transition the 116 /// firmware to its [`Signed`] state. 117 struct FirmwareDmaObject<F: FalconFirmware, S: SignedState>(DmaObject, PhantomData<(F, S)>); 118 119 /// Trait for signatures to be patched directly into a given firmware. 120 /// 121 /// This is module-local and meant for sub-modules to use internally. 122 trait FirmwareSignature<F: FalconFirmware>: AsRef<[u8]> {} 123 124 impl<F: FalconFirmware> FirmwareDmaObject<F, Unsigned> { 125 /// Patches the firmware at offset `sig_base_img` with `signature`. 126 fn patch_signature<S: FirmwareSignature<F>>( 127 mut self, 128 signature: &S, 129 sig_base_img: usize, 130 ) -> Result<FirmwareDmaObject<F, Signed>> { 131 let signature_bytes = signature.as_ref(); 132 if sig_base_img + signature_bytes.len() > self.0.size() { 133 return Err(EINVAL); 134 } 135 136 // SAFETY: We are the only user of this object, so there cannot be any race. 137 let dst = unsafe { self.0.start_ptr_mut().add(sig_base_img) }; 138 139 // SAFETY: `signature` and `dst` are valid, properly aligned, and do not overlap. 140 unsafe { 141 core::ptr::copy_nonoverlapping(signature_bytes.as_ptr(), dst, signature_bytes.len()) 142 }; 143 144 Ok(FirmwareDmaObject(self.0, PhantomData)) 145 } 146 147 /// Mark the firmware as signed without patching it. 148 /// 149 /// This method is used to explicitly confirm that we do not need to sign the firmware, while 150 /// allowing us to continue as if it was. This is typically only needed for development 151 /// hardware. 152 fn no_patch_signature(self) -> FirmwareDmaObject<F, Signed> { 153 FirmwareDmaObject(self.0, PhantomData) 154 } 155 } 156 157 /// Header common to most firmware files. 158 #[repr(C)] 159 #[derive(Debug, Clone)] 160 struct BinHdr { 161 /// Magic number, must be `0x10de`. 162 bin_magic: u32, 163 /// Version of the header. 164 bin_ver: u32, 165 /// Size in bytes of the binary (to be ignored). 166 bin_size: u32, 167 /// Offset of the start of the application-specific header. 168 header_offset: u32, 169 /// Offset of the start of the data payload. 170 data_offset: u32, 171 /// Size in bytes of the data payload. 172 data_size: u32, 173 } 174 175 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability. 176 unsafe impl FromBytes for BinHdr {} 177 178 // A firmware blob starting with a `BinHdr`. 179 struct BinFirmware<'a> { 180 hdr: BinHdr, 181 fw: &'a [u8], 182 } 183 184 impl<'a> BinFirmware<'a> { 185 /// Interpret `fw` as a firmware image starting with a [`BinHdr`], and returns the 186 /// corresponding [`BinFirmware`] that can be used to extract its payload. 187 fn new(fw: &'a firmware::Firmware) -> Result<Self> { 188 const BIN_MAGIC: u32 = 0x10de; 189 let fw = fw.data(); 190 191 fw.get(0..size_of::<BinHdr>()) 192 // Extract header. 193 .and_then(BinHdr::from_bytes_copy) 194 // Validate header. 195 .and_then(|hdr| { 196 if hdr.bin_magic == BIN_MAGIC { 197 Some(hdr) 198 } else { 199 None 200 } 201 }) 202 .map(|hdr| Self { hdr, fw }) 203 .ok_or(EINVAL) 204 } 205 206 /// Returns the data payload of the firmware, or `None` if the data range is out of bounds of 207 /// the firmware image. 208 fn data(&self) -> Option<&[u8]> { 209 let fw_start = self.hdr.data_offset as usize; 210 let fw_size = self.hdr.data_size as usize; 211 212 self.fw.get(fw_start..fw_start + fw_size) 213 } 214 } 215 216 pub(crate) struct ModInfoBuilder<const N: usize>(firmware::ModInfoBuilder<N>); 217 218 impl<const N: usize> ModInfoBuilder<N> { 219 const fn make_entry_file(self, chipset: &str, fw: &str) -> Self { 220 ModInfoBuilder( 221 self.0 222 .new_entry() 223 .push("nvidia/") 224 .push(chipset) 225 .push("/gsp/") 226 .push(fw) 227 .push("-") 228 .push(FIRMWARE_VERSION) 229 .push(".bin"), 230 ) 231 } 232 233 const fn make_entry_chipset(self, chipset: &str) -> Self { 234 self.make_entry_file(chipset, "booter_load") 235 .make_entry_file(chipset, "booter_unload") 236 .make_entry_file(chipset, "bootloader") 237 .make_entry_file(chipset, "gsp") 238 } 239 240 pub(crate) const fn create( 241 module_name: &'static kernel::str::CStr, 242 ) -> firmware::ModInfoBuilder<N> { 243 let mut this = Self(firmware::ModInfoBuilder::new(module_name)); 244 let mut i = 0; 245 246 while i < gpu::Chipset::ALL.len() { 247 this = this.make_entry_chipset(gpu::Chipset::ALL[i].name()); 248 i += 1; 249 } 250 251 this.0 252 } 253 } 254