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