xref: /linux/drivers/gpu/nova-core/firmware/booter.rs (revision 457c70b7dde5c14f940664fdc7f0e1998aff56be)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Support for loading and patching the `Booter` firmware. `Booter` is a Heavy Secured firmware
4 //! running on [`Sec2`], that is used on Turing/Ampere to load the GSP firmware into the GSP falcon
5 //! (and optionally unload it through a separate firmware image).
6 
7 use core::{
8     marker::PhantomData,
9     ops::Deref, //
10 };
11 
12 use kernel::{
13     device,
14     prelude::*,
15     transmute::FromBytes, //
16 };
17 
18 use crate::{
19     dma::DmaObject,
20     driver::Bar0,
21     falcon::{
22         sec2::Sec2,
23         Falcon,
24         FalconBromParams,
25         FalconFirmware,
26         FalconLoadParams,
27         FalconLoadTarget, //
28     },
29     firmware::{
30         BinFirmware,
31         FirmwareDmaObject,
32         FirmwareSignature,
33         Signed,
34         Unsigned, //
35     },
36     gpu::Chipset,
37     num::{
38         FromSafeCast,
39         IntoSafeCast, //
40     },
41 };
42 
43 /// Local convenience function to return a copy of `S` by reinterpreting the bytes starting at
44 /// `offset` in `slice`.
45 fn frombytes_at<S: FromBytes + Sized>(slice: &[u8], offset: usize) -> Result<S> {
46     let end = offset.checked_add(size_of::<S>()).ok_or(EINVAL)?;
47     slice
48         .get(offset..end)
49         .and_then(S::from_bytes_copy)
50         .ok_or(EINVAL)
51 }
52 
53 /// Heavy-Secured firmware header.
54 ///
55 /// Such firmwares have an application-specific payload that needs to be patched with a given
56 /// signature.
57 #[repr(C)]
58 #[derive(Debug, Clone)]
59 struct HsHeaderV2 {
60     /// Offset to the start of the signatures.
61     sig_prod_offset: u32,
62     /// Size in bytes of the signatures.
63     sig_prod_size: u32,
64     /// Offset to a `u32` containing the location at which to patch the signature in the microcode
65     /// image.
66     patch_loc_offset: u32,
67     /// Offset to a `u32` containing the index of the signature to patch.
68     patch_sig_offset: u32,
69     /// Start offset to the signature metadata.
70     meta_data_offset: u32,
71     /// Size in bytes of the signature metadata.
72     meta_data_size: u32,
73     /// Offset to a `u32` containing the number of signatures in the signatures section.
74     num_sig_offset: u32,
75     /// Offset of the application-specific header.
76     header_offset: u32,
77     /// Size in bytes of the application-specific header.
78     header_size: u32,
79 }
80 
81 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
82 unsafe impl FromBytes for HsHeaderV2 {}
83 
84 /// Heavy-Secured Firmware image container.
85 ///
86 /// This provides convenient access to the fields of [`HsHeaderV2`] that are actually indices to
87 /// read from in the firmware data.
88 struct HsFirmwareV2<'a> {
89     hdr: HsHeaderV2,
90     fw: &'a [u8],
91 }
92 
93 impl<'a> HsFirmwareV2<'a> {
94     /// Interprets the header of `bin_fw` as a [`HsHeaderV2`] and returns an instance of
95     /// `HsFirmwareV2` for further parsing.
96     ///
97     /// Fails if the header pointed at by `bin_fw` is not within the bounds of the firmware image.
98     fn new(bin_fw: &BinFirmware<'a>) -> Result<Self> {
99         frombytes_at::<HsHeaderV2>(bin_fw.fw, bin_fw.hdr.header_offset.into_safe_cast())
100             .map(|hdr| Self { hdr, fw: bin_fw.fw })
101     }
102 
103     /// Returns the location at which the signatures should be patched in the microcode image.
104     ///
105     /// Fails if the offset of the patch location is outside the bounds of the firmware
106     /// image.
107     fn patch_location(&self) -> Result<u32> {
108         frombytes_at::<u32>(self.fw, self.hdr.patch_loc_offset.into_safe_cast())
109     }
110 
111     /// Returns an iterator to the signatures of the firmware. The iterator can be empty if the
112     /// firmware is unsigned.
113     ///
114     /// Fails if the pointed signatures are outside the bounds of the firmware image.
115     fn signatures_iter(&'a self) -> Result<impl Iterator<Item = BooterSignature<'a>>> {
116         let num_sig = frombytes_at::<u32>(self.fw, self.hdr.num_sig_offset.into_safe_cast())?;
117         let iter = match self.hdr.sig_prod_size.checked_div(num_sig) {
118             // If there are no signatures, return an iterator that will yield zero elements.
119             None => (&[] as &[u8]).chunks_exact(1),
120             Some(sig_size) => {
121                 let patch_sig =
122                     frombytes_at::<u32>(self.fw, self.hdr.patch_sig_offset.into_safe_cast())?;
123 
124                 let signatures_start = self
125                     .hdr
126                     .sig_prod_offset
127                     .checked_add(patch_sig)
128                     .map(usize::from_safe_cast)
129                     .ok_or(EINVAL)?;
130 
131                 let signatures_end = signatures_start
132                     .checked_add(usize::from_safe_cast(self.hdr.sig_prod_size))
133                     .ok_or(EINVAL)?;
134 
135                 self.fw
136                     // Get signatures range.
137                     .get(signatures_start..signatures_end)
138                     .ok_or(EINVAL)?
139                     .chunks_exact(sig_size.into_safe_cast())
140             }
141         };
142 
143         // Map the byte slices into signatures.
144         Ok(iter.map(BooterSignature))
145     }
146 }
147 
148 /// Signature parameters, as defined in the firmware.
149 #[repr(C)]
150 struct HsSignatureParams {
151     /// Fuse version to use.
152     fuse_ver: u32,
153     /// Mask of engine IDs this firmware applies to.
154     engine_id_mask: u32,
155     /// ID of the microcode.
156     ucode_id: u32,
157 }
158 
159 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
160 unsafe impl FromBytes for HsSignatureParams {}
161 
162 impl HsSignatureParams {
163     /// Returns the signature parameters contained in `hs_fw`.
164     ///
165     /// Fails if the meta data parameter of `hs_fw` is outside the bounds of the firmware image, or
166     /// if its size doesn't match that of [`HsSignatureParams`].
167     fn new(hs_fw: &HsFirmwareV2<'_>) -> Result<Self> {
168         let start = usize::from_safe_cast(hs_fw.hdr.meta_data_offset);
169         let end = start
170             .checked_add(hs_fw.hdr.meta_data_size.into_safe_cast())
171             .ok_or(EINVAL)?;
172 
173         hs_fw
174             .fw
175             .get(start..end)
176             .and_then(Self::from_bytes_copy)
177             .ok_or(EINVAL)
178     }
179 }
180 
181 /// Header for code and data load offsets.
182 #[repr(C)]
183 #[derive(Debug, Clone)]
184 struct HsLoadHeaderV2 {
185     // Offset at which the code starts.
186     os_code_offset: u32,
187     // Total size of the code, for all apps.
188     os_code_size: u32,
189     // Offset at which the data starts.
190     os_data_offset: u32,
191     // Size of the data.
192     os_data_size: u32,
193     // Number of apps following this header. Each app is described by a [`HsLoadHeaderV2App`].
194     num_apps: u32,
195 }
196 
197 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
198 unsafe impl FromBytes for HsLoadHeaderV2 {}
199 
200 impl HsLoadHeaderV2 {
201     /// Returns the load header contained in `hs_fw`.
202     ///
203     /// Fails if the header pointed at by `hs_fw` is not within the bounds of the firmware image.
204     fn new(hs_fw: &HsFirmwareV2<'_>) -> Result<Self> {
205         frombytes_at::<Self>(hs_fw.fw, hs_fw.hdr.header_offset.into_safe_cast())
206     }
207 }
208 
209 /// Header for app code loader.
210 #[repr(C)]
211 #[derive(Debug, Clone)]
212 struct HsLoadHeaderV2App {
213     /// Offset at which to load the app code.
214     offset: u32,
215     /// Length in bytes of the app code.
216     len: u32,
217 }
218 
219 // SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
220 unsafe impl FromBytes for HsLoadHeaderV2App {}
221 
222 impl HsLoadHeaderV2App {
223     /// Returns the [`HsLoadHeaderV2App`] for app `idx` of `hs_fw`.
224     ///
225     /// Fails if `idx` is larger than the number of apps declared in `hs_fw`, or if the header is
226     /// not within the bounds of the firmware image.
227     fn new(hs_fw: &HsFirmwareV2<'_>, idx: u32) -> Result<Self> {
228         let load_hdr = HsLoadHeaderV2::new(hs_fw)?;
229         if idx >= load_hdr.num_apps {
230             Err(EINVAL)
231         } else {
232             frombytes_at::<Self>(
233                 hs_fw.fw,
234                 usize::from_safe_cast(hs_fw.hdr.header_offset)
235                     // Skip the load header...
236                     .checked_add(size_of::<HsLoadHeaderV2>())
237                     // ... and jump to app header `idx`.
238                     .and_then(|offset| {
239                         offset
240                             .checked_add(usize::from_safe_cast(idx).checked_mul(size_of::<Self>())?)
241                     })
242                     .ok_or(EINVAL)?,
243             )
244         }
245     }
246 }
247 
248 /// Signature for Booter firmware. Their size is encoded into the header and not known a compile
249 /// time, so we just wrap a byte slices on which we can implement [`FirmwareSignature`].
250 struct BooterSignature<'a>(&'a [u8]);
251 
252 impl<'a> AsRef<[u8]> for BooterSignature<'a> {
253     fn as_ref(&self) -> &[u8] {
254         self.0
255     }
256 }
257 
258 impl<'a> FirmwareSignature<BooterFirmware> for BooterSignature<'a> {}
259 
260 /// The `Booter` loader firmware, responsible for loading the GSP.
261 pub(crate) struct BooterFirmware {
262     // Load parameters for Secure `IMEM` falcon memory.
263     imem_sec_load_target: FalconLoadTarget,
264     // Load parameters for Non-Secure `IMEM` falcon memory,
265     // used only on Turing and GA100
266     imem_ns_load_target: Option<FalconLoadTarget>,
267     // Load parameters for `DMEM` falcon memory.
268     dmem_load_target: FalconLoadTarget,
269     // BROM falcon parameters.
270     brom_params: FalconBromParams,
271     // Device-mapped firmware image.
272     ucode: FirmwareDmaObject<Self, Signed>,
273 }
274 
275 impl FirmwareDmaObject<BooterFirmware, Unsigned> {
276     fn new_booter(dev: &device::Device<device::Bound>, data: &[u8]) -> Result<Self> {
277         DmaObject::from_data(dev, data).map(|ucode| Self(ucode, PhantomData))
278     }
279 }
280 
281 #[derive(Copy, Clone, Debug, PartialEq)]
282 pub(crate) enum BooterKind {
283     Loader,
284     #[expect(unused)]
285     Unloader,
286 }
287 
288 impl BooterFirmware {
289     /// Parses the Booter firmware contained in `fw`, and patches the correct signature so it is
290     /// ready to be loaded and run on `falcon`.
291     pub(crate) fn new(
292         dev: &device::Device<device::Bound>,
293         kind: BooterKind,
294         chipset: Chipset,
295         ver: &str,
296         falcon: &Falcon<<Self as FalconFirmware>::Target>,
297         bar: &Bar0,
298     ) -> Result<Self> {
299         let fw_name = match kind {
300             BooterKind::Loader => "booter_load",
301             BooterKind::Unloader => "booter_unload",
302         };
303         let fw = super::request_firmware(dev, chipset, fw_name, ver)?;
304         let bin_fw = BinFirmware::new(&fw)?;
305 
306         // The binary firmware embeds a Heavy-Secured firmware.
307         let hs_fw = HsFirmwareV2::new(&bin_fw)?;
308 
309         // The Heavy-Secured firmware embeds a firmware load descriptor.
310         let load_hdr = HsLoadHeaderV2::new(&hs_fw)?;
311 
312         // Offset in `ucode` where to patch the signature.
313         let patch_loc = hs_fw.patch_location()?;
314 
315         let sig_params = HsSignatureParams::new(&hs_fw)?;
316         let brom_params = FalconBromParams {
317             // `load_hdr.os_data_offset` is an absolute index, but `pkc_data_offset` is from the
318             // signature patch location.
319             pkc_data_offset: patch_loc
320                 .checked_sub(load_hdr.os_data_offset)
321                 .ok_or(EINVAL)?,
322             engine_id_mask: u16::try_from(sig_params.engine_id_mask).map_err(|_| EINVAL)?,
323             ucode_id: u8::try_from(sig_params.ucode_id).map_err(|_| EINVAL)?,
324         };
325         let app0 = HsLoadHeaderV2App::new(&hs_fw, 0)?;
326 
327         // Object containing the firmware microcode to be signature-patched.
328         let ucode = bin_fw
329             .data()
330             .ok_or(EINVAL)
331             .and_then(|data| FirmwareDmaObject::<Self, _>::new_booter(dev, data))?;
332 
333         let ucode_signed = {
334             let mut signatures = hs_fw.signatures_iter()?.peekable();
335 
336             if signatures.peek().is_none() {
337                 // If there are no signatures, then the firmware is unsigned.
338                 ucode.no_patch_signature()
339             } else {
340                 // Obtain the version from the fuse register, and extract the corresponding
341                 // signature.
342                 let reg_fuse_version = falcon.signature_reg_fuse_version(
343                     bar,
344                     brom_params.engine_id_mask,
345                     brom_params.ucode_id,
346                 )?;
347 
348                 // `0` means the last signature should be used.
349                 const FUSE_VERSION_USE_LAST_SIG: u32 = 0;
350                 let signature = match reg_fuse_version {
351                     FUSE_VERSION_USE_LAST_SIG => signatures.last(),
352                     // Otherwise hardware fuse version needs to be subtracted to obtain the index.
353                     reg_fuse_version => {
354                         let Some(idx) = sig_params.fuse_ver.checked_sub(reg_fuse_version) else {
355                             dev_err!(dev, "invalid fuse version for Booter firmware\n");
356                             return Err(EINVAL);
357                         };
358                         signatures.nth(idx.into_safe_cast())
359                     }
360                 }
361                 .ok_or(EINVAL)?;
362 
363                 ucode.patch_signature(&signature, patch_loc.into_safe_cast())?
364             }
365         };
366 
367         // There are two versions of Booter, one for Turing/GA100, and another for
368         // GA102+.  The extraction of the IMEM sections differs between the two
369         // versions.  Unfortunately, the file names are the same, and the headers
370         // don't indicate the versions.  The only way to differentiate is by the Chipset.
371         let (imem_sec_dst_start, imem_ns_load_target) = if chipset <= Chipset::GA100 {
372             (
373                 app0.offset,
374                 Some(FalconLoadTarget {
375                     src_start: 0,
376                     dst_start: load_hdr.os_code_offset,
377                     len: load_hdr.os_code_size,
378                 }),
379             )
380         } else {
381             (0, None)
382         };
383 
384         Ok(Self {
385             imem_sec_load_target: FalconLoadTarget {
386                 src_start: app0.offset,
387                 dst_start: imem_sec_dst_start,
388                 len: app0.len,
389             },
390             imem_ns_load_target,
391             dmem_load_target: FalconLoadTarget {
392                 src_start: load_hdr.os_data_offset,
393                 dst_start: 0,
394                 len: load_hdr.os_data_size,
395             },
396             brom_params,
397             ucode: ucode_signed,
398         })
399     }
400 }
401 
402 impl FalconLoadParams for BooterFirmware {
403     fn imem_sec_load_params(&self) -> FalconLoadTarget {
404         self.imem_sec_load_target.clone()
405     }
406 
407     fn imem_ns_load_params(&self) -> Option<FalconLoadTarget> {
408         self.imem_ns_load_target.clone()
409     }
410 
411     fn dmem_load_params(&self) -> FalconLoadTarget {
412         self.dmem_load_target.clone()
413     }
414 
415     fn brom_params(&self) -> FalconBromParams {
416         self.brom_params.clone()
417     }
418 
419     fn boot_addr(&self) -> u32 {
420         if let Some(ns_target) = &self.imem_ns_load_target {
421             ns_target.dst_start
422         } else {
423             self.imem_sec_load_target.src_start
424         }
425     }
426 }
427 
428 impl Deref for BooterFirmware {
429     type Target = DmaObject;
430 
431     fn deref(&self) -> &Self::Target {
432         &self.ucode.0
433     }
434 }
435 
436 impl FalconFirmware for BooterFirmware {
437     type Target = Sec2;
438 }
439