Skip to contentSkip to conversation

gpu: nova-core: process and prepare more firmwares to boot GSP

PATCH Superseded Alexandre Courbot 3 participants 31 messages Sep 2, 2025 – Sep 10, 2025

Subsystems (8)

v3 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

v3 cover gpu: nova-core: process and prepare more firmwares to boot GSP

This series makes more progress on the GSP boot process for Ampere GPUs.

At the end of the previous series [1], we were left with a WPR memory region created by the FRTS firmware, but still far from the GSP running. This series brings us closer to that goal by preparing 2 new firmware packages:

* The Booter firmware, which the driver loads and runs on the SEC2 falcon;
* The GSP bootloader, which is loaded by Booter onto the GSP RISC-V core;
* The GSP firmware itself, which is verified and loaded by the GSP bootloader.

There 3 firmwares are involved in a rather complex dance that is made necessary by limitations related to the level of privilege required to load code onto the GSP (doing so requires a Heavy Secured signed firmware, which is the role fulfilled by Booter).

The first 5 patches do some cleanup and preparatory work for the remainder of the series. Notably, the GSP boot is moved to a new method of Gpu that is called after the Gpu object is created. We also simplify chipset name generation a bit and move the code requesting a firmware file into a dedicated function in prevision of the removal of the Firmware structure.

Patch 6 parses the Booter firmware file, queries the hardware for the right signature to use, and patch it into the firmware blob. This makes Booter ready to load and run.

Patches 7 and 8 prepare the GSP firmware and its bootloader, and keep them into a single structure as they are closely related.

Patches 9 and 10 switch to the 570.144 firmware and introduce the layout for its bindings. The raw bindings are stored in a private module, and abstracted by the parent module as needed. This allows consumer modules to access a safer/nicer form of the bindings than the raw one, and also makes it easier to switch to a different (and potentially incompatible) firmware version in the future.

570.144 has been picked because it is the latest firmware currently in linux-firmware, but as development progresses the plan is to switch to a newer one that is designed with the constraint of upstream in mind. So support for 570.144 will be dropped in the future. Support for multiple firmware versions is not considered at the moment: there is no immediate need for it as the driver is still unstable, and we can think about this point once we approach stability (and have better visibility about the shape of the firmware at that point).

The last patch introduces the first bindings and uses them to compute more framebuffer layout information needed for booting the GSP. A separate patch series will pick up from there to use this information and finally run these firmware blobs.

The base of this series is today's nova-next, but there a few more unmerged dependencies required:

- BorrowedPage, AsPageIter and VmallocPageIter [2]
- Rust infrastructure for sg_table and scatterlist [3]
- The Alignment series [4]

A tree with all these dependencies and the patches of this series is available at [5].

[1] https://lore.kernel.org/rust-for-linux/[email protected]/
[2] https://lore.kernel.org/rust-for-linux/[email protected]/
[3] https://lore.kernel.org/rust-for-linux/[email protected]/
[4] https://lore.kernel.org/rust-for-linux/[email protected]/
[5] https://github.com/Gnurou/linux/tree/b4/nova_firmware

---
Changes in v3:
- Move the GSP boot process out of the Gpu constructor.
- Get rid of the Firmware struct and discard loaded firmware blobs
after the GSP is booted.
- Consolidate the GSP firmware, bootloader and signatures into a single type.
- Make firmware bindings completely opaque to the driver.
- Improve firmware abstractions related to framebuffer carveout.
- Improve comments and naming throughout the series. (thanks John!)
- Use alias for bindings module in nvfw to avoid repeated version
numbers everywhere. (thanks John!)
- Fix inconsistency in naming of members of Booter header. (thanks
Timur!)
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Add some GSP bindings and use them to compute more FB layout info
needed to boot GSP,
- Use PinInit in GspFirmware to avoid several heap allocations,
- Rename bootloader to gsp_bootloader in Firmware to avoid
confusion with the future Turing falcon bootloader,
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Alexandre Courbot (10):
gpu: nova-core: require Send on FalconEngine and FalconHal
gpu: nova-core: move GSP boot code out of Gpu constructor
gpu: nova-core: add Chipset::name() method
gpu: nova-core: firmware: move firmware request code into a function
gpu: nova-core: firmware: add support for common firmware header
gpu: nova-core: firmware: process Booter and patch its signature
gpu: nova-core: firmware: process and prepare the GSP firmware
gpu: nova-core: firmware: process the GSP bootloader
gpu: nova-core: firmware: use 570.144 firmware
gpu: nova-core: compute layout of more framebuffer regions required for GSP

Alistair Popple (1):
gpu: nova-core: Add base files for r570.144 firmware bindings

 Documentation/gpu/nova/core/todo.rst            |  17 --
 drivers/gpu/nova-core/driver.rs                 |  10 +-
 drivers/gpu/nova-core/falcon.rs                 |   6 +-
 drivers/gpu/nova-core/falcon/hal.rs             |   2 +-
 drivers/gpu/nova-core/fb.rs                     |  64 +++-
 drivers/gpu/nova-core/fb/hal.rs                 |   4 +
 drivers/gpu/nova-core/fb/hal/ga100.rs           |   5 +
 drivers/gpu/nova-core/fb/hal/ga102.rs           |  10 +
 drivers/gpu/nova-core/fb/hal/tu102.rs           |  11 +
 drivers/gpu/nova-core/firmware.rs               | 107 +++++--
 drivers/gpu/nova-core/firmware/booter.rs        | 375 ++++++++++++++++++++++++
 drivers/gpu/nova-core/firmware/gsp.rs           | 244 +++++++++++++++
 drivers/gpu/nova-core/firmware/riscv.rs         |  89 ++++++
 drivers/gpu/nova-core/gpu.rs                    |  87 ++++--
 drivers/gpu/nova-core/gsp.rs                    |   7 +
 drivers/gpu/nova-core/nova_core.rs              |   2 +
 drivers/gpu/nova-core/nvfw.rs                   |  92 ++++++
 drivers/gpu/nova-core/nvfw/r570_144.rs          |  28 ++
 drivers/gpu/nova-core/nvfw/r570_144_bindings.rs | 126 ++++++++
 drivers/gpu/nova-core/util.rs                   |  20 --
 20 files changed, 1209 insertions(+), 97 deletions(-)

---
base-commit: 331c24e6ce814af2af74bac648d1ac1708873e9c
change-id: 20250822-nova_firmware-e0ffb492ba35
prerequisite-message-id: <[email protected]>
prerequisite-patch-id: 0e1b1f9a665317ff569a37df6ff49cd1880b04f8
prerequisite-patch-id: 178b864e6d1b88ee299dcc05d1a7a4c89ec7ed51
prerequisite-patch-id: 7f72c4bfd0e5f50b6d2f8ce96751782894a3ba81
prerequisite-patch-id: 62fa6de7d3ae99dc54c092087bd716e6749545fd
prerequisite-patch-id: 3d14d56ca93b0831837aa26b802100a250adeac6
prerequisite-patch-id: 7a12f4b0e7588874ce589b41b70671dc261b9468
prerequisite-patch-id: c44763ec35c4e4431e769df088b98424cbddf7df
prerequisite-message-id: <[email protected]>
prerequisite-patch-id: a9e008c179b1c2fbe76654a191e5018880383d49
prerequisite-patch-id: 363279599349e5efc7069a63b3f0574639e25418
prerequisite-patch-id: 4dd34d858514b7b982f4ebc85103a756205c3219
prerequisite-patch-id: a747e05834cdb8b8f727e1f7c8b110c636cadab8
prerequisite-patch-id: 24833689bdecd3fc7a604e13bfe203ccd2fca6f0
prerequisite-message-id: <[email protected]>
prerequisite-patch-id: 3ddaa5300963f6c069411c6431965a7a48107a8b
prerequisite-change-id: 20250620-num-9420281c02c7:v4
prerequisite-patch-id: 50077433250cad1cf60eb8f85c78e532ac91852e
prerequisite-patch-id: 021a41cd35f09790ec383521ecc9b4c167868732
prerequisite-patch-id: a1ec5698a198d4aad45432b50d42f401e3db6452
prerequisite-patch-id: 8565b054c432bcc9a3a0d0121a934c74ef36d535
prerequisite-patch-id: 19d008deabb88beb441d2398f120ecb426fbdb43
prerequisite-patch-id: 3bc0d2be065a900d224ff8c1bc4450abfe9eb2cc
prerequisite-patch-id: 5b4eb0f71fa2ccf662594819fa79fd932f4f164f
prerequisite-patch-id: 9058ca08cd149444b5f910e4bb4494a890d1a733
prerequisite-patch-id: 8804806f7cc605feddded0804eec8b8362d7b965
prerequisite-patch-id: f999cabde51824432a1bf60817518d1ce189eb76
prerequisite-patch-id: 49e15538e142f2e7dd4f1ba0cf2fd891bd265d36
prerequisite-patch-id: 2ecf9b1e26b5203065bfac4ccf74301b3bb4fbe6
prerequisite-patch-id: 1af6ec7c2ce8503fe476985f59949dcd150ee6bf
prerequisite-patch-id: ac72e72b3affece504bff76b60b88769ff200a2f
prerequisite-patch-id: 7dc0a6da8c9727d27250cf730f8aaf6dd8b3d8c7
prerequisite-patch-id: 31a0a2469de9ac965186098072753dcc749b40fe
prerequisite-patch-id: 7e6d1fc7cf910decf481d135a19b0add38da2b2a
prerequisite-patch-id: c72ab11e9346de71eabfe0e6466636d5ab15a5ba
prerequisite-patch-id: 3f236fdea8c4b33620d0f863fea573b46ab0ded6
prerequisite-patch-id: a8ab42d0c9c3c837bb4cacb02cef585ef163a27e
prerequisite-patch-id: 930a1f26364ed67e0d6b85c96251028fda43c80a
prerequisite-patch-id: f1bc1fd46145a66235ab7475463584e1803882a3
prerequisite-patch-id: 4a2fd7bd8d13dc2feaf68e0dc681546ce2ab3e40
prerequisite-patch-id: dd0df8d299dc0615a88cc0019f38bc09cee31ed7
prerequisite-patch-id: 56a45978f7b956c94ec66eecd4b438706d5174ce
prerequisite-patch-id: e9bceff31bbf653d2641194b97eb1c4e5d8b93ee

Best regards,

Signature · 1 line
Alexandre Courbot <[email protected]>
author maintainer
#1 lore raw

PATCH v3 1/11 gpu: nova-core: require `Send` on `FalconEngine` and `FalconHal`

We want to store the GSP and SEC2 falcon instances inside the Gpu structure, but doing so require these types to implement Send for pci::Driver to remain implementable on NovaCore, which embeds Gpu.

All implementors of FalconEngine and FalconHal satisfy the requirements of Send, and this traits also already required Sync, so this a minor tweak.

---
 drivers/gpu/nova-core/falcon.rs     | 2 +-
 drivers/gpu/nova-core/falcon/hal.rs | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
drivers/gpu/nova-core/falcon.rs +1 -1
index 2dbcdf26697beb7e52083675fc9ea62a6167fef8..b16207e7242fe1ac26b8552575b8b4e52f34cf6a 100644
@@ -286,7 +286,7 @@ fn from(value: bool) -> Self {
 /// Each engine provides one base for `PFALCON` and `PFALCON2` registers. The `ID` constant is used
 /// to identify a given Falcon instance with register I/O methods.
 pub(crate) trait FalconEngine:
-    Sync + RegisterBase<PFalconBase> + RegisterBase<PFalcon2Base> + Sized
+    Send + Sync + RegisterBase<PFalconBase> + RegisterBase<PFalcon2Base> + Sized
 {
     /// Singleton of the engine, used to identify it with register I/O methods.
     const ID: Self;
drivers/gpu/nova-core/falcon/hal.rs +1 -1
index b233bc365882f9add9b6eab33b8d462d7913df37..bba28845561795914e9a4dba277d72bbac0b37dd 100644
@@ -13,7 +13,7 @@
 /// Implements chipset-specific low-level operations. The trait is generic against [`FalconEngine`]
 /// so its `BASE` parameter can be used in order to avoid runtime bound checks when accessing
 /// registers.
-pub(crate) trait FalconHal<E: FalconEngine>: Sync {
+pub(crate) trait FalconHal<E: FalconEngine>: Send + Sync {
     /// Activates the Falcon core if the engine is a risvc/falcon dual engine.
     fn select_core(&self, _falcon: &Falcon<E>, _bar: &Bar0) -> Result {
         Ok(())
Signature · 1 line
2.51.0
author maintainer
#2 lore raw

PATCH v3 2/11 gpu: nova-core: move GSP boot code out of `Gpu` constructor

In reply to Alexandre Courbot

Right now the GSP boot code is very incomplete and limited to running FRTS, so having it in Gpu::new is not a big constraint.

However, this will change as we add more steps of the GSP boot process, some of which are rather cumbersome to perform on a partially-constructed GPU instance.

Relatedly, booting the GSP typically happens only once in the GPU reset cycle. Most of the data created to complete this step (notably firmware loaded from user-space) is needed only temporary and can be discarded once the GSP is booted; it then makes all the more sense to store these as local variables of a dedicated method, instead of inside the Gpu structure where they as kept as long as the GPU is bound, using dozens of megabytes of host memory.

Thus, introduce a start_gsp method on the Gpu struct, which is called by probe after the GPU is instantiated and will return the running GSP instance, once the code completing its boot is integrated.

---
 drivers/gpu/nova-core/driver.rs | 10 +++++++++-
 drivers/gpu/nova-core/gpu.rs    | 41 ++++++++++++++++++++++++++++++-----------
 2 files changed, 39 insertions(+), 12 deletions(-)
drivers/gpu/nova-core/driver.rs +9 -1
index 274989ea1fb4a5e3e6678a08920ddc76d2809ab2..1062014c0a488e959379f009c2e8029ffaa1e2f8 100644
@@ -6,6 +6,8 @@
 
 #[pin_data]
 pub(crate) struct NovaCore {
+    // Placeholder for the real `Gsp` object once it is built.
+    pub(crate) gsp: (),
     #[pin]
     pub(crate) gpu: Gpu,
     _reg: auxiliary::Registration,
@@ -40,8 +42,14 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
         )?;
 
         let this = KBox::pin_init(
-            try_pin_init!(Self {
+            try_pin_init!(&this in Self {
                 gpu <- Gpu::new(pdev, bar)?,
+                gsp <- {
+                    // SAFETY: `this.gpu` is initialized to a valid value.
+                    let gpu = unsafe { &(*this.as_ptr()).gpu };
+
+                    gpu.start_gsp(pdev)?
+                },
                 _reg: auxiliary::Registration::new(
                     pdev.as_ref(),
                     c_str!("nova-drm"),
drivers/gpu/nova-core/gpu.rs +30 -11

84 lines not on this page · raw message

Signature · 1 line
2.51.0
maintainer
#3 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 16 lines · Alexandre Courbot
drivers/gpu/nova-core/driver.rs +2 -0
index 274989ea1fb4a5e3e6678a08920ddc76d2809ab2..1062014c0a488e959379f009c2e8029ffaa1e2f8 100644
@@ -6,6 +6,8 @@
 
 #[pin_data]
 pub(crate) struct NovaCore {
+    // Placeholder for the real `Gsp` object once it is built.
+    pub(crate) gsp: (),
     #[pin]
     pub(crate) gpu: Gpu,
     _reg: auxiliary::Registration,
@@ -40,8 +42,14 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
         )?;
 

drivers/gpu/nova-core/driver.rs fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self · line 52

Quoted 10 lines
drivers/gpu/nova-core/driver.rs +7 -1
         let this = KBox::pin_init(
-            try_pin_init!(Self {
+            try_pin_init!(&this in Self {
                 gpu <- Gpu::new(pdev, bar)?,
+                gsp <- {
+                    // SAFETY: `this.gpu` is initialized to a valid value.
+                    let gpu = unsafe { &(*this.as_ptr()).gpu };
+
+                    gpu.start_gsp(pdev)?
+                },

Please use pin_chain() [1] for this.

More in general, unsafe code should be the absolute last resort. If we add new unsafe code I'd love to see a comment justifying why there's no other way than using unsafe code for this, as we agreed in [2].

I did a quick grep on this series and I see 21 occurrences of "unsafe", if I substract the ones for annotations and for FromBytes impls, it's still 9 new ones. :(

Do we really need all of them?

Otherwise, I really like this, it's a great improvement over initializing everything into the Gpu struct -- thanks for the refactoring!

[1] https://rust.docs.kernel.org/kernel/prelude/trait.PinInit.html#method.pin_chain
[2] https://docs.kernel.org/gpu/nova/guidelines.html#language

author maintainer
#4 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 17 lines · Danilo Krummrich
Quoted 16 lines · Alexandre Courbot
drivers/gpu/nova-core/driver.rs +2 -0
index 274989ea1fb4a5e3e6678a08920ddc76d2809ab2..1062014c0a488e959379f009c2e8029ffaa1e2f8 100644
@@ -6,6 +6,8 @@
 
 #[pin_data]
 pub(crate) struct NovaCore {
+    // Placeholder for the real `Gsp` object once it is built.
+    pub(crate) gsp: (),
     #[pin]
     pub(crate) gpu: Gpu,
     _reg: auxiliary::Registration,
@@ -40,8 +42,14 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
         )?;
 
Quoted 12 lines

drivers/gpu/nova-core/driver.rs fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self · line 52

Quoted 10 lines
drivers/gpu/nova-core/driver.rs +7 -1
         let this = KBox::pin_init(
-            try_pin_init!(Self {
+            try_pin_init!(&this in Self {
                 gpu <- Gpu::new(pdev, bar)?,
+                gsp <- {
+                    // SAFETY: `this.gpu` is initialized to a valid value.
+                    let gpu = unsafe { &(*this.as_ptr()).gpu };
+
+                    gpu.start_gsp(pdev)?
+                },

Please use pin_chain() [1] for this.

Sorry, but I couldn't figure out how I can use pin_chain here (and couldn't find any relevant example in the kernel code either). Can you elaborate a bit?

Quoted 10 lines

More in general, unsafe code should be the absolute last resort. If we add new unsafe code I'd love to see a comment justifying why there's no other way than using unsafe code for this, as we agreed in [2].

I did a quick grep on this series and I see 21 occurrences of "unsafe", if I substract the ones for annotations and for FromBytes impls, it's still 9 new ones. :(

Do we really need all of them?

I've counted 16 uses of unsafe. :)

- 3 in the bindgen-generated code (these can't be avoided),
- 7 to implement FromBytes,
- 1 to work around the fact that FromBytes doesn't work on slices yet (maybe that one can be removed)
- 5 as a result of intra-dependencies in PinInit initializers (which we might be able to remove if I figure out how to use pin_chain).

So best-case scenario would be that we will be down to 10 that are truly unavoidable.

author maintainer
#5 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 31 lines · Alexandre Courbot
Quoted 17 lines · Danilo Krummrich
Quoted 16 lines · Alexandre Courbot
drivers/gpu/nova-core/driver.rs +2 -0
index 274989ea1fb4a5e3e6678a08920ddc76d2809ab2..1062014c0a488e959379f009c2e8029ffaa1e2f8 100644
@@ -6,6 +6,8 @@
 
 #[pin_data]
 pub(crate) struct NovaCore {
+    // Placeholder for the real `Gsp` object once it is built.
+    pub(crate) gsp: (),
     #[pin]
     pub(crate) gpu: Gpu,
     _reg: auxiliary::Registration,
@@ -40,8 +42,14 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
         )?;
 
Quoted 12 lines

drivers/gpu/nova-core/driver.rs fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self · line 52

Quoted 10 lines
drivers/gpu/nova-core/driver.rs +7 -1
         let this = KBox::pin_init(
-            try_pin_init!(Self {
+            try_pin_init!(&this in Self {
                 gpu <- Gpu::new(pdev, bar)?,
+                gsp <- {
+                    // SAFETY: `this.gpu` is initialized to a valid value.
+                    let gpu = unsafe { &(*this.as_ptr()).gpu };
+
+                    gpu.start_gsp(pdev)?
+                },

Please use pin_chain() [1] for this.

Quoted 3 lines

Sorry, but I couldn't figure out how I can use pin_chain here (and couldn't find any relevant example in the kernel code either). Can you elaborate a bit?

To be more specific on what I don't get: I see how pin_chain could be used to initialize a structure which dependent member can take a temporary value (like a pointer set to null), but in this case gsp must be initialized with the result of start_gsp, and there is no "default" valid value for it meanwhile (I use () as its type, but it is a temporary placeholder). But maybe I am just misunderstanding something about how pin_chain can be used.

maintainer
#6 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

In reply to Alexandre Courbot
Quoted 31 lines · Alexandre Courbot
Quoted 17 lines · Danilo Krummrich
Quoted 16 lines · Alexandre Courbot
drivers/gpu/nova-core/driver.rs +2 -0
index 274989ea1fb4a5e3e6678a08920ddc76d2809ab2..1062014c0a488e959379f009c2e8029ffaa1e2f8 100644
@@ -6,6 +6,8 @@
 
 #[pin_data]
 pub(crate) struct NovaCore {
+    // Placeholder for the real `Gsp` object once it is built.
+    pub(crate) gsp: (),
     #[pin]
     pub(crate) gpu: Gpu,
     _reg: auxiliary::Registration,
@@ -40,8 +42,14 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
         )?;
 
Quoted 12 lines

drivers/gpu/nova-core/driver.rs fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self · line 52

Quoted 10 lines
drivers/gpu/nova-core/driver.rs +7 -1
         let this = KBox::pin_init(
-            try_pin_init!(Self {
+            try_pin_init!(&this in Self {
                 gpu <- Gpu::new(pdev, bar)?,
+                gsp <- {
+                    // SAFETY: `this.gpu` is initialized to a valid value.
+                    let gpu = unsafe { &(*this.as_ptr()).gpu };
+
+                    gpu.start_gsp(pdev)?
+                },

Please use pin_chain() [1] for this.

Quoted 3 lines

Sorry, but I couldn't figure out how I can use pin_chain here (and couldn't find any relevant example in the kernel code either). Can you elaborate a bit?

I thought of just doing the following, which I think should be equivalent (diff against current nova-next).

drivers/gpu/nova-core/driver.rs +3 -1
index 274989ea1fb4..6d62867f7503 100644
@@ -41,7 +41,9 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
 
         let this = KBox::pin_init(
             try_pin_init!(Self {
-                gpu <- Gpu::new(pdev, bar)?,
+                gpu <- Gpu::new(pdev, bar)?.pin_chain(|gpu| {
+                    gpu.start_gsp(pdev)
+                }),
                 _reg: auxiliary::Registration::new(
                     pdev.as_ref(),
                     c_str!("nova-drm"),
drivers/gpu/nova-core/gpu.rs +7 -2
index 8caecaf7dfb4..211bc1a5a5b3 100644
@@ -266,7 +266,7 @@ fn run_fwsec_frts(
     pub(crate) fn new(
         pdev: &pci::Device<device::Bound>,
         devres_bar: Arc<Devres<Bar0>>,
-    ) -> Result<impl PinInit<Self>> {
+    ) -> Result<impl PinInit<Self, Error>> {
         let bar = devres_bar.access(pdev.as_ref())?;
         let spec = Spec::new(bar)?;
         let fw = Firmware::new(pdev.as_ref(), spec.chipset, FIRMWARE_VERSION)?;
@@ -302,11 +302,16 @@ pub(crate) fn new(
 
         Self::run_fwsec_frts(pdev.as_ref(), &gsp_falcon, bar, &bios, &fb_layout)?;
 
-        Ok(pin_init!(Self {
+        Ok(try_pin_init!(Self {
             spec,
             bar: devres_bar,
             fw,
             sysmem_flush,
         }))
     }
+
+    pub(crate) fn start_gsp(&self, _pdev: &pci::Device<device::Core>) -> Result {
+        // noop
+        Ok(())
+    }
 }

But maybe it doesn't capture your intend?

Quoted 5 lines
Quoted 5 lines

More in general, unsafe code should be the absolute last resort. If we add new unsafe code I'd love to see a comment justifying why there's no other way than using unsafe code for this, as we agreed in [2].

Quoted 7 lines
Quoted 5 lines

I did a quick grep on this series and I see 21 occurrences of "unsafe", if I substract the ones for annotations and for FromBytes impls, it's still 9 new ones. :(

Do we really need all of them?

I've counted 16 uses of unsafe. :)

I did a grep | wc on the mbox file, so it includes the 5 additional occurrences from the annotations. :)

Otherwise the 9 "real" ones I counted seem to match the 3 bindgen ones (fine of course) plus the 5 ones from the pin initializers (we should avoid them).

Quoted 10 lines

- 3 in the bindgen-generated code (these can't be avoided),
- 7 to implement FromBytes,
- 1 to work around the fact that FromBytes doesn't work on slices yet (maybe that one can be removed)
- 5 as a result of intra-dependencies in PinInit initializers (which we might be able to remove if I figure out how to use pin_chain).

So best-case scenario would be that we will be down to 10 that are truly unavoidable.

author maintainer
#7 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 86 lines · Danilo Krummrich
Quoted 31 lines · Alexandre Courbot
Quoted 17 lines · Danilo Krummrich
Quoted 16 lines · Alexandre Courbot
drivers/gpu/nova-core/driver.rs +2 -0
index 274989ea1fb4a5e3e6678a08920ddc76d2809ab2..1062014c0a488e959379f009c2e8029ffaa1e2f8 100644
@@ -6,6 +6,8 @@
 
 #[pin_data]
 pub(crate) struct NovaCore {
+    // Placeholder for the real `Gsp` object once it is built.
+    pub(crate) gsp: (),
     #[pin]
     pub(crate) gpu: Gpu,
     _reg: auxiliary::Registration,
@@ -40,8 +42,14 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
         )?;
 
Quoted 12 lines

drivers/gpu/nova-core/driver.rs fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self · line 52

Quoted 10 lines
drivers/gpu/nova-core/driver.rs +7 -1
         let this = KBox::pin_init(
-            try_pin_init!(Self {
+            try_pin_init!(&this in Self {
                 gpu <- Gpu::new(pdev, bar)?,
+                gsp <- {
+                    // SAFETY: `this.gpu` is initialized to a valid value.
+                    let gpu = unsafe { &(*this.as_ptr()).gpu };
+
+                    gpu.start_gsp(pdev)?
+                },

Please use pin_chain() [1] for this.

Quoted 3 lines

Sorry, but I couldn't figure out how I can use pin_chain here (and couldn't find any relevant example in the kernel code either). Can you elaborate a bit?

I thought of just doing the following, which I think should be equivalent (diff against current nova-next).

drivers/gpu/nova-core/driver.rs +3 -1
index 274989ea1fb4..6d62867f7503 100644
@@ -41,7 +41,9 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
 
         let this = KBox::pin_init(
             try_pin_init!(Self {
-                gpu <- Gpu::new(pdev, bar)?,
+                gpu <- Gpu::new(pdev, bar)?.pin_chain(|gpu| {
+                    gpu.start_gsp(pdev)
+                }),
                 _reg: auxiliary::Registration::new(
                     pdev.as_ref(),
                     c_str!("nova-drm"),
drivers/gpu/nova-core/gpu.rs +7 -2
index 8caecaf7dfb4..211bc1a5a5b3 100644
@@ -266,7 +266,7 @@ fn run_fwsec_frts(
     pub(crate) fn new(
         pdev: &pci::Device<device::Bound>,
         devres_bar: Arc<Devres<Bar0>>,
-    ) -> Result<impl PinInit<Self>> {
+    ) -> Result<impl PinInit<Self, Error>> {
         let bar = devres_bar.access(pdev.as_ref())?;
         let spec = Spec::new(bar)?;
         let fw = Firmware::new(pdev.as_ref(), spec.chipset, FIRMWARE_VERSION)?;
@@ -302,11 +302,16 @@ pub(crate) fn new(
 
         Self::run_fwsec_frts(pdev.as_ref(), &gsp_falcon, bar, &bios, &fb_layout)?;
 
-        Ok(pin_init!(Self {
+        Ok(try_pin_init!(Self {
             spec,
             bar: devres_bar,
             fw,
             sysmem_flush,
         }))
     }
+
+    pub(crate) fn start_gsp(&self, _pdev: &pci::Device<device::Core>) -> Result {
+        // noop
+        Ok(())
+    }
 }
Quoted 1 line

But maybe it doesn't capture your intend?

The issue is that start_gsp returns a value (currently a placeholder (), but it will change into a real type) that needs to be stored into the newly-introduced gsp member of NovaCore. I could not figure how how pin_chain could help with this (and this is the same problem for the other unsafe statements in firmware/gsp.rs).

It is a common pattern when initializing a pinned object, so I agree it would be nice support this without unsafe code.

maintainer
#8 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 87 lines · Alexandre Courbot
Quoted 86 lines · Danilo Krummrich
Quoted 31 lines · Alexandre Courbot
Quoted 17 lines · Danilo Krummrich
Quoted 16 lines · Alexandre Courbot
drivers/gpu/nova-core/driver.rs +2 -0
index 274989ea1fb4a5e3e6678a08920ddc76d2809ab2..1062014c0a488e959379f009c2e8029ffaa1e2f8 100644
@@ -6,6 +6,8 @@
 
 #[pin_data]
 pub(crate) struct NovaCore {
+    // Placeholder for the real `Gsp` object once it is built.
+    pub(crate) gsp: (),
     #[pin]
     pub(crate) gpu: Gpu,
     _reg: auxiliary::Registration,
@@ -40,8 +42,14 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
         )?;
 
Quoted 12 lines

drivers/gpu/nova-core/driver.rs fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self · line 52

Quoted 10 lines
drivers/gpu/nova-core/driver.rs +7 -1
         let this = KBox::pin_init(
-            try_pin_init!(Self {
+            try_pin_init!(&this in Self {
                 gpu <- Gpu::new(pdev, bar)?,
+                gsp <- {
+                    // SAFETY: `this.gpu` is initialized to a valid value.
+                    let gpu = unsafe { &(*this.as_ptr()).gpu };
+
+                    gpu.start_gsp(pdev)?
+                },

Please use pin_chain() [1] for this.

Quoted 3 lines

Sorry, but I couldn't figure out how I can use pin_chain here (and couldn't find any relevant example in the kernel code either). Can you elaborate a bit?

I thought of just doing the following, which I think should be equivalent (diff against current nova-next).

drivers/gpu/nova-core/driver.rs +3 -1
index 274989ea1fb4..6d62867f7503 100644
@@ -41,7 +41,9 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
 
         let this = KBox::pin_init(
             try_pin_init!(Self {
-                gpu <- Gpu::new(pdev, bar)?,
+                gpu <- Gpu::new(pdev, bar)?.pin_chain(|gpu| {
+                    gpu.start_gsp(pdev)
+                }),
                 _reg: auxiliary::Registration::new(
                     pdev.as_ref(),
                     c_str!("nova-drm"),
drivers/gpu/nova-core/gpu.rs +7 -2
index 8caecaf7dfb4..211bc1a5a5b3 100644
@@ -266,7 +266,7 @@ fn run_fwsec_frts(
     pub(crate) fn new(
         pdev: &pci::Device<device::Bound>,
         devres_bar: Arc<Devres<Bar0>>,
-    ) -> Result<impl PinInit<Self>> {
+    ) -> Result<impl PinInit<Self, Error>> {
         let bar = devres_bar.access(pdev.as_ref())?;
         let spec = Spec::new(bar)?;
         let fw = Firmware::new(pdev.as_ref(), spec.chipset, FIRMWARE_VERSION)?;
@@ -302,11 +302,16 @@ pub(crate) fn new(
 
         Self::run_fwsec_frts(pdev.as_ref(), &gsp_falcon, bar, &bios, &fb_layout)?;
 
-        Ok(pin_init!(Self {
+        Ok(try_pin_init!(Self {
             spec,
             bar: devres_bar,
             fw,
             sysmem_flush,
         }))
     }
+
+    pub(crate) fn start_gsp(&self, _pdev: &pci::Device<device::Core>) -> Result {
+        // noop
+        Ok(())
+    }
 }
Quoted 7 lines
Quoted 1 line

But maybe it doesn't capture your intend?

The issue is that start_gsp returns a value (currently a placeholder (), but it will change into a real type) that needs to be stored into the newly-introduced gsp member of NovaCore. I could not figure how how pin_chain could help with this (and this is the same problem for the other unsafe statements in firmware/gsp.rs).

Ok, I see, I think Benno is already working on a solution to access previously initialized fields from subsequent initializers.

@Benno: What's the status of this? I haven't seen an issue for that in the pin-init GitHub repo, should we create one?

However, in this case I'm a bit confused why we want Gsp next to Gpu? Why not just make Gsp a member of Gpu then?

I thought the intent was to keep temporary values local to start_gsp() and not store them next to Gpu in the same allocation?

Quoted 2 lines

It is a common pattern when initializing a pinned object, so I agree it would be nice support this without unsafe code.

author maintainer
#9 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 96 lines · Danilo Krummrich
Quoted 87 lines · Alexandre Courbot
Quoted 86 lines · Danilo Krummrich
Quoted 31 lines · Alexandre Courbot
Quoted 17 lines · Danilo Krummrich
Quoted 16 lines · Alexandre Courbot
drivers/gpu/nova-core/driver.rs +2 -0
index 274989ea1fb4a5e3e6678a08920ddc76d2809ab2..1062014c0a488e959379f009c2e8029ffaa1e2f8 100644
@@ -6,6 +6,8 @@
 
 #[pin_data]
 pub(crate) struct NovaCore {
+    // Placeholder for the real `Gsp` object once it is built.
+    pub(crate) gsp: (),
     #[pin]
     pub(crate) gpu: Gpu,
     _reg: auxiliary::Registration,
@@ -40,8 +42,14 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
         )?;
 
Quoted 12 lines

drivers/gpu/nova-core/driver.rs fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self · line 52

Quoted 10 lines
drivers/gpu/nova-core/driver.rs +7 -1
         let this = KBox::pin_init(
-            try_pin_init!(Self {
+            try_pin_init!(&this in Self {
                 gpu <- Gpu::new(pdev, bar)?,
+                gsp <- {
+                    // SAFETY: `this.gpu` is initialized to a valid value.
+                    let gpu = unsafe { &(*this.as_ptr()).gpu };
+
+                    gpu.start_gsp(pdev)?
+                },

Please use pin_chain() [1] for this.

Quoted 3 lines

Sorry, but I couldn't figure out how I can use pin_chain here (and couldn't find any relevant example in the kernel code either). Can you elaborate a bit?

I thought of just doing the following, which I think should be equivalent (diff against current nova-next).

drivers/gpu/nova-core/driver.rs +3 -1
index 274989ea1fb4..6d62867f7503 100644
@@ -41,7 +41,9 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self
 
         let this = KBox::pin_init(
             try_pin_init!(Self {
-                gpu <- Gpu::new(pdev, bar)?,
+                gpu <- Gpu::new(pdev, bar)?.pin_chain(|gpu| {
+                    gpu.start_gsp(pdev)
+                }),
                 _reg: auxiliary::Registration::new(
                     pdev.as_ref(),
                     c_str!("nova-drm"),
drivers/gpu/nova-core/gpu.rs +7 -2
index 8caecaf7dfb4..211bc1a5a5b3 100644
@@ -266,7 +266,7 @@ fn run_fwsec_frts(
     pub(crate) fn new(
         pdev: &pci::Device<device::Bound>,
         devres_bar: Arc<Devres<Bar0>>,
-    ) -> Result<impl PinInit<Self>> {
+    ) -> Result<impl PinInit<Self, Error>> {
         let bar = devres_bar.access(pdev.as_ref())?;
         let spec = Spec::new(bar)?;
         let fw = Firmware::new(pdev.as_ref(), spec.chipset, FIRMWARE_VERSION)?;
@@ -302,11 +302,16 @@ pub(crate) fn new(
 
         Self::run_fwsec_frts(pdev.as_ref(), &gsp_falcon, bar, &bios, &fb_layout)?;
 
-        Ok(pin_init!(Self {
+        Ok(try_pin_init!(Self {
             spec,
             bar: devres_bar,
             fw,
             sysmem_flush,
         }))
     }
+
+    pub(crate) fn start_gsp(&self, _pdev: &pci::Device<device::Core>) -> Result {
+        // noop
+        Ok(())
+    }
 }
Quoted 7 lines
Quoted 1 line

But maybe it doesn't capture your intend?

The issue is that start_gsp returns a value (currently a placeholder (), but it will change into a real type) that needs to be stored into the newly-introduced gsp member of NovaCore. I could not figure how how pin_chain could help with this (and this is the same problem for the other unsafe statements in firmware/gsp.rs).

Quoted 8 lines

Ok, I see, I think Benno is already working on a solution to access previously initialized fields from subsequent initializers.

@Benno: What's the status of this? I haven't seen an issue for that in the pin-init GitHub repo, should we create one?

However, in this case I'm a bit confused why we want Gsp next to Gpu? Why not just make Gsp a member of Gpu then?

To be honest I am not completely sure about the best layout yet and will need more visibility to understand whether this is optimal. But considering that we want to run the GSP boot process over a built Gpu instance, we cannot store the result of said process inside Gpu unless we put it inside e.g. an Option. But then the variant will always be Some after probe returns, and yet we will have to perform a match every time we want to access it.

The current separation sounds reasonable to me for the time being, with Gpu containing purely hardware resources obtained without help from user-space, while Gsp is the result of running a bunch of firmwares. An alternative design would be to store Gpu inside Gsp, but Gsp inside Gpu is trickier due to the build order. No matter what we do, switching the layout later should be trivial if we don't choose the best one now.

There is also an easy workaround to the sibling initialization issue, which is to store Gpu and Gsp behind Pin<KBox> - that way we can initialize both outside try_pin_init!, at the cost of two more heap allocations over the whole lifetime of the device. If we don't have a proper solution to the problem now, this might be better than using unsafe as a temporary solution.

The same workaround could also be used for to GspFirmware and its page tables - since GspFirmware is temporary and can apparently be discarded after the GSP is booted, this shouldn't be a big issue. This will allow the driver to probe, and we can add TODO items to fix that later if a solution is in sight.

Quoted 3 lines

I thought the intent was to keep temporary values local to start_gsp() and not store them next to Gpu in the same allocation?

It is not visible in the current patchset, but start_gsp will eventually return the runtime data of the GSP - notably its log buffers and command queue, which are needed to operate it. All the rest (notably the loaded firmwares) will be local to start_gsp and discarded upon its return.

maintainer
#10 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 8 lines · Alexandre Courbot

To be honest I am not completely sure about the best layout yet and will need more visibility to understand whether this is optimal. But considering that we want to run the GSP boot process over a built Gpu instance, we cannot store the result of said process inside Gpu unless we put it inside e.g. an Option. But then the variant will always be Some after probe returns, and yet we will have to perform a match every time we want to access it.

Quoted 7 lines

The current separation sounds reasonable to me for the time being, with Gpu containing purely hardware resources obtained without help from user-space, while Gsp is the result of running a bunch of firmwares. An alternative design would be to store Gpu inside Gsp, but Gsp inside Gpu is trickier due to the build order. No matter what we do, switching the layout later should be trivial if we don't choose the best one now.

Gsp should be part of the Gpu object. The Gpu object represents the entire instance of the Gpu, including hardware ressources, firmware runtime state, etc.

The initialization of the Gsp structure doesn't really need a Gpu structure to be constructed, it needs certain members of the Gpu structure, i.e. order of initialization of the members does matter.

If it makes things more obvious we can always create new types and increase the hierarchy within the Gpu struct itself.

The technical limitation you're facing is always the same, no matter the layout we choose: we need pin-init to provide us references to already initialized members.

I will check with Benno in today's Rust call what's the best way to address this.

Quoted 6 lines

There is also an easy workaround to the sibling initialization issue, which is to store Gpu and Gsp behind Pin<KBox> - that way we can initialize both outside try_pin_init!, at the cost of two more heap allocations over the whole lifetime of the device. If we don't have a proper solution to the problem now, this might be better than using unsafe as a temporary solution.

Yeah, this workaround is much easier to implement when they're siblings (less allocations temporarily), but let's not design things this way because of that.

As mentioned above, I will check with Benno today.

Quoted 7 lines

The same workaround could also be used for to GspFirmware and its page tables - since GspFirmware is temporary and can apparently be discarded after the GSP is booted, this shouldn't be a big issue. This will allow the driver to probe, and we can add TODO items to fix that later if a solution is in sight.

Quoted 1 line
Quoted 8 lines
Quoted 2 lines

I thought the intent was to keep temporary values local to start_gsp() and not store them next to Gpu in the same allocation?

It is not visible in the current patchset, but start_gsp will eventually return the runtime data of the GSP - notably its log buffers and command queue, which are needed to operate it. All the rest (notably the loaded firmwares) will be local to start_gsp and discarded upon its return.

Ok, that makes sense, but it should really be part of the Gpu structure.

#11 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Hi Danilo,

Quoted 17 lines · Danilo Krummrich
Quoted 8 lines · Alexandre Courbot

To be honest I am not completely sure about the best layout yet and will need more visibility to understand whether this is optimal. But considering that we want to run the GSP boot process over a built Gpu instance, we cannot store the result of said process inside Gpu unless we put it inside e.g. an Option. But then the variant will always be Some after probe returns, and yet we will have to perform a match every time we want to access it.

Quoted 7 lines

The current separation sounds reasonable to me for the time being, with Gpu containing purely hardware resources obtained without help from user-space, while Gsp is the result of running a bunch of firmwares. An alternative design would be to store Gpu inside Gsp, but Gsp inside Gpu is trickier due to the build order. No matter what we do, switching the layout later should be trivial if we don't choose the best one now.

Quoted 1 line

Gsp should be part of the Gpu object.

Just checking, if Gsp is a part of Gpu as you mentioned, and start_gsp() is called from within Gpu::new(), does that not avoid the problem of referring to fields of pin-initialized structs entirely, at least for this usecase for nova? Or is there any nova-related usecase where this is problematic?

thanks,

- Joel

[...]

Quoted 46 lines

The Gpu object represents the entire
instance of the Gpu, including hardware ressources, firmware runtime state, etc.

The initialization of the Gsp structure doesn't really need a Gpu structure to be constructed, it needs certain members of the Gpu structure, i.e. order of initialization of the members does matter.

If it makes things more obvious we can always create new types and increase the hierarchy within the Gpu struct itself.

The technical limitation you're facing is always the same, no matter the layout we choose: we need pin-init to provide us references to already initialized members.

I will check with Benno in today's Rust call what's the best way to address this.

Quoted 6 lines

There is also an easy workaround to the sibling initialization issue, which is to store Gpu and Gsp behind Pin<KBox> - that way we can initialize both outside try_pin_init!, at the cost of two more heap allocations over the whole lifetime of the device. If we don't have a proper solution to the problem now, this might be better than using unsafe as a temporary solution.

Yeah, this workaround is much easier to implement when they're siblings (less allocations temporarily), but let's not design things this way because of that.

As mentioned above, I will check with Benno today.

Quoted 7 lines

The same workaround could also be used for to GspFirmware and its page tables - since GspFirmware is temporary and can apparently be discarded after the GSP is booted, this shouldn't be a big issue. This will allow the driver to probe, and we can add TODO items to fix that later if a solution is in sight.

Quoted 1 line
Quoted 8 lines
Quoted 2 lines

I thought the intent was to keep temporary values local to start_gsp() and not store them next to Gpu in the same allocation?

It is not visible in the current patchset, but start_gsp will eventually return the runtime data of the GSP - notably its log buffers and command queue, which are needed to operate it. All the rest (notably the loaded firmwares) will be local to start_gsp and discarded upon its return.

Ok, that makes sense, but it should really be part of the Gpu structure.

maintainer
#12 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

In reply to Alexandre Courbot
Quoted 3 lines · Alexandre Courbot
      pub(crate) fn new(
          pdev: &pci::Device<device::Bound>,
          devres_bar: Arc<Devres<Bar0>>,

The diff is hiding it, but with this patch we should also make sure that this returns impl PinInit<Self, Error> rather than Result<impl PinInit<Self>.

I think this should be possible now.

Quoted 25 lines
drivers/gpu/nova-core/gpu.rs +3 -8
@@ -293,20 +317,15 @@ pub(crate) fn new(
          )?;
          gsp_falcon.clear_swgen0_intr(bar);
 
-        let _sec2_falcon = Falcon::<Sec2>::new(pdev.as_ref(), spec.chipset, bar, true)?;
-
-        let fb_layout = FbLayout::new(spec.chipset, bar)?;
-        dev_dbg!(pdev.as_ref(), "{:#x?}\n", fb_layout);
-
-        let bios = Vbios::new(pdev.as_ref(), bar)?;
-
-        Self::run_fwsec_frts(pdev.as_ref(), &gsp_falcon, bar, &bios, &fb_layout)?;
+        let sec2_falcon = Falcon::<Sec2>::new(pdev.as_ref(), spec.chipset, bar, true)?;
 
          Ok(pin_init!(Self {
              spec,
              bar: devres_bar,
              fw,
              sysmem_flush,
+            gsp_falcon,
+            sec2_falcon,
          }))
      }
  }
author maintainer
#13 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 9 lines · Danilo Krummrich
Quoted 3 lines · Alexandre Courbot
      pub(crate) fn new(
          pdev: &pci::Device<device::Bound>,
          devres_bar: Arc<Devres<Bar0>>,

The diff is hiding it, but with this patch we should also make sure that this returns impl PinInit<Self, Error> rather than Result<impl PinInit<Self>.

I think this should be possible now.

There is still code that can return errors (falcon creation, etc) - do you mean that we should move it into the pin initializer and turn it into a try_pin_init?

maintainer
#14 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 6 lines · Alexandre Courbot
Quoted 5 lines · Danilo Krummrich
Quoted 3 lines · Alexandre Courbot
      pub(crate) fn new(
          pdev: &pci::Device<device::Bound>,
          devres_bar: Arc<Devres<Bar0>>,
Quoted 8 lines
Quoted 4 lines

The diff is hiding it, but with this patch we should also make sure that this returns impl PinInit<Self, Error> rather than Result<impl PinInit<Self>.

I think this should be possible now.

There is still code that can return errors (falcon creation, etc) - do you mean that we should move it into the pin initializer and turn it into a try_pin_init?

Yeah, that would be better practice, if it doesn't work out for a good reason we can also fall back to Result<impl PinInit<Self, Error>, but we should at least try to avoid it.

author maintainer
#15 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 12 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
Quoted 9 lines · Danilo Krummrich
Quoted 3 lines · Alexandre Courbot
      pub(crate) fn new(
          pdev: &pci::Device<device::Bound>,
          devres_bar: Arc<Devres<Bar0>>,

The diff is hiding it, but with this patch we should also make sure that this returns impl PinInit<Self, Error> rather than Result<impl PinInit<Self>.

I think this should be possible now.

Quoted 7 lines
Quoted 3 lines

There is still code that can return errors (falcon creation, etc) - do you mean that we should move it into the pin initializer and turn it into a try_pin_init?

Yeah, that would be better practice, if it doesn't work out for a good reason we can also fall back to Result<impl PinInit<Self, Error>, but we should at least try to avoid it.

I tried but could not do it in a way that is satisfying. The problem is that Gpu::new receives a Arc<Devres<Bar0>>, which we need to access in order to do anything useful with it. If we first store it into the Gpu structure, then every subsequent member needs to access it in its own code block in order to perform their own initialization. This is quite cumbersome.

If there is a way to obtain the Bar0 once after the bar member of Gpu is initialized, and then use that instance with each remaining member, then that problem would go away but I am not aware of such a thing.

maintainer
#16 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 28 lines · Alexandre Courbot
Quoted 12 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
Quoted 9 lines · Danilo Krummrich
Quoted 3 lines · Alexandre Courbot
      pub(crate) fn new(
          pdev: &pci::Device<device::Bound>,
          devres_bar: Arc<Devres<Bar0>>,

The diff is hiding it, but with this patch we should also make sure that this returns impl PinInit<Self, Error> rather than Result<impl PinInit<Self>.

I think this should be possible now.

Quoted 7 lines
Quoted 3 lines

There is still code that can return errors (falcon creation, etc) - do you mean that we should move it into the pin initializer and turn it into a try_pin_init?

Yeah, that would be better practice, if it doesn't work out for a good reason we can also fall back to Result<impl PinInit<Self, Error>, but we should at least try to avoid it.

I tried but could not do it in a way that is satisfying. The problem is that Gpu::new receives a Arc<Devres<Bar0>>, which we need to access in order to do anything useful with it. If we first store it into the Gpu structure, then every subsequent member needs to access it in its own code block in order to perform their own initialization. This is quite cumbersome.

Quoted 4 lines

If there is a way to obtain the Bar0 once after the bar member of Gpu is initialized, and then use that instance with each remaining member, then that problem would go away but I am not aware of such a thing.

What about this?

	impl Gpu {
	    pub(crate) fn new<'a>(
	        dev: &'a Device<Bound>,
	        bar: &'a Bar0
	        devres_bar: Arc<Devres<Bar0>>,
	    ) -> impl PinInit<Self, Error> + 'a {
	        try_pin_init(Self {
	            bar: devres_bar,
	            spec: Spec::new(bar)?,
	            gsp_falcon: Falcon::<Gsp>::new(dev, spec.chipset)?,
	            sec2_falcon: Falcon::<Sec2>::new(dev, spec.chipset)?,
	            sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?
	            gsp <- Gsp::new(gsp_falcon, sec2_falcon, sysmem_flush)?,
	        })
	    }
	}
author maintainer
#17 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 36 lines · Danilo Krummrich
Quoted 28 lines · Alexandre Courbot
Quoted 12 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
Quoted 9 lines · Danilo Krummrich
Quoted 3 lines · Alexandre Courbot
      pub(crate) fn new(
          pdev: &pci::Device<device::Bound>,
          devres_bar: Arc<Devres<Bar0>>,

The diff is hiding it, but with this patch we should also make sure that this returns impl PinInit<Self, Error> rather than Result<impl PinInit<Self>.

I think this should be possible now.

Quoted 7 lines
Quoted 3 lines

There is still code that can return errors (falcon creation, etc) - do you mean that we should move it into the pin initializer and turn it into a try_pin_init?

Yeah, that would be better practice, if it doesn't work out for a good reason we can also fall back to Result<impl PinInit<Self, Error>, but we should at least try to avoid it.

I tried but could not do it in a way that is satisfying. The problem is that Gpu::new receives a Arc<Devres<Bar0>>, which we need to access in order to do anything useful with it. If we first store it into the Gpu structure, then every subsequent member needs to access it in its own code block in order to perform their own initialization. This is quite cumbersome.

Quoted 4 lines

If there is a way to obtain the Bar0 once after the bar member of Gpu is initialized, and then use that instance with each remaining member, then that problem would go away but I am not aware of such a thing.

What about this?

Quoted 16 lines
	impl Gpu {
	    pub(crate) fn new<'a>(
	        dev: &'a Device<Bound>,
	        bar: &'a Bar0
	        devres_bar: Arc<Devres<Bar0>>,
	    ) -> impl PinInit<Self, Error> + 'a {
	        try_pin_init(Self {
	            bar: devres_bar,
	            spec: Spec::new(bar)?,
	            gsp_falcon: Falcon::<Gsp>::new(dev, spec.chipset)?,
	            sec2_falcon: Falcon::<Sec2>::new(dev, spec.chipset)?,
	            sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?
	            gsp <- Gsp::new(gsp_falcon, sec2_falcon, sysmem_flush)?,
	        })
	    }
	}

It does work. The bizareness of passing the bar twice aside, here is what it looks like when I got it to compile:

    pub(crate) fn new<'a>(
        pdev: &'a pci::Device<device::Bound>,
        devres_bar: Arc<Devres<Bar0>>,
        bar: &'a Bar0,
    ) -> impl PinInit<Self, Error> + 'a {
        try_pin_init!(Self {
            spec: Spec::new(bar).inspect(|spec| {
                dev_info!(
                    pdev.as_ref(),
                    "NVIDIA (Chipset: {}, Architecture: {:?}, Revision: {})\n",
                    spec.chipset,
                    spec.chipset.arch(),
                    spec.revision
                );
            })?,

            sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.chipset)?,

            gsp_falcon: Falcon::<Gsp>::new(
                pdev.as_ref(),
                spec.chipset,
                bar,
                spec.chipset > Chipset::GA100,
            )
            .inspect(|falcon| falcon.clear_swgen0_intr(bar))?,

            sec2_falcon: Falcon::<Sec2>::new(pdev.as_ref(), spec.chipset, bar, true)?,

            gsp: Self::start_gsp(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon)?,

            bar: devres_bar,
        })
    }

The wait for GFW initialization had to be moved to probe, but that's fine IMO. I do however find the code less readable in this form, less editable as well. And LSP seems lost, so I don't get any syntax highlighting in the try_pin_init block.

Fundamentally, this changes the method from a fallible method returning a non-fallible initializer into a non-fallible method returning a fallible initializer. I'm ok with that, and maybe this new form will encourage us to keep this method short, which is what we want, but other than that what benefit are we getting from this change?

maintainer
#18 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 18 lines · Alexandre Courbot
Quoted 8 lines · Danilo Krummrich
	impl Gpu {
	    pub(crate) fn new<'a>(
	        dev: &'a Device<Bound>,
	        bar: &'a Bar0
	        devres_bar: Arc<Devres<Bar0>>,
	    ) -> impl PinInit<Self, Error> + 'a {
	        try_pin_init(Self {
	            bar: devres_bar,
Quoted 8 lines
	            spec: Spec::new(bar)?,
	            gsp_falcon: Falcon::<Gsp>::new(dev, spec.chipset)?,
	            sec2_falcon: Falcon::<Sec2>::new(dev, spec.chipset)?,
	            sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?
	            gsp <- Gsp::new(gsp_falcon, sec2_falcon, sysmem_flush)?,
	        })
	    }
	}
Quoted 1 line

It does work. The bizareness of passing the bar twice aside,

Yeah, but it really seems like a minor inconvinience. (Especially, since this will be the only occurance of this we'll ever have.)

Quoted 1 line

here is what it looks like when I got it to compile:

This looks great!

Quoted 7 lines
    pub(crate) fn new<'a>(
        pdev: &'a pci::Device<device::Bound>,
        devres_bar: Arc<Devres<Bar0>>,
        bar: &'a Bar0,
    ) -> impl PinInit<Self, Error> + 'a {
        try_pin_init!(Self {
            spec: Spec::new(bar).inspect(|spec| {
Quoted 8 lines
                dev_info!(
                    pdev.as_ref(),
                    "NVIDIA (Chipset: {}, Architecture: {:?}, Revision: {})\n",
                    spec.chipset,
                    spec.chipset.arch(),
                    spec.revision
                );
            })?,

+ _: {
+ gfw::wait_gfw_boot_completion(bar)
+ .inspect_err(|_| dev_err!(pdev.as_ref(), "GFW boot did not complete"))?;
+ },

Quoted 13 lines
            sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.chipset)?,

            gsp_falcon: Falcon::<Gsp>::new(
                pdev.as_ref(),
                spec.chipset,
                bar,
                spec.chipset > Chipset::GA100,
            )
            .inspect(|falcon| falcon.clear_swgen0_intr(bar))?,

            sec2_falcon: Falcon::<Sec2>::new(pdev.as_ref(), spec.chipset, bar, true)?,

- gsp: Self::start_gsp(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon)?,
+ gsp <- Self::start_gsp(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon),

Quoted 7 lines
            bar: devres_bar,
        })
    }

The wait for GFW initialization had to be moved to probe, but that's fine IMO.

That's not necessary, you can keep it in Gpu::new() -- I don't see what's preventing us from that. I inserted it in the code above.

Quoted 3 lines

I do however find the code less readable in this form, less editable as well. And LSP seems lost, so I don't get any syntax highlighting in the try_pin_init block.

Benno is working on a syntax update, so automatic formatting etc. will properly work.

Otherwise, I can't see how this is a downgrade. It represents the initialization process in a much clearer way that the current implementation of Gsp::new(), which is rather messy.

Quoted 3 lines

Fundamentally, this changes the method from a fallible method returning a non-fallible initializer into a non-fallible method returning a fallible initializer.

Yeah, that's the best case when working with pin-init.

Quoted 3 lines

I'm ok with that, and maybe this new form will
encourage us to keep this method short, which is what we want, but other than that what benefit are we getting from this change?

The immediate benefit is that we don't need an extra allocation for the Gsp structure.

The general benefit is that once we need to add more fields to structures that require pinning (such as locks -- and we will need a lot of them) we're prepared for it.

If we're not prepared for it, I'm pretty sure that everytime someone needs to add e.g. a new lock for something, it will just result in a new Pin<KBox<T>>, because the initial pin-init hierarchy just isn't there, and creating a new allocation is more convinient than fixing the existing code.

This is exactly what pin-init was introduced for in the kernel, such that we're not doing worse than equivalent C code.

	struct Foo {
	   struct Bar bar;
	   void *data;
	   struct mutex data_lock;
	}

	struct Bar {
	   void *data;
	   struct mutex data_lock;
	}

In C you can just kmalloc(sizeof(Foo), GFP_KERNEL) and subsequently initialize all fields.

In Rust I don't want to fall back having to allocate for Bar *and* for Foo separately.

If there are things to improve with pin-init, let's improve them, but let's not do worse than C code in this aspect.

author maintainer
#19 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 19 lines · Danilo Krummrich
Quoted 18 lines · Alexandre Courbot
Quoted 16 lines · Danilo Krummrich
	impl Gpu {
	    pub(crate) fn new<'a>(
	        dev: &'a Device<Bound>,
	        bar: &'a Bar0
	        devres_bar: Arc<Devres<Bar0>>,
	    ) -> impl PinInit<Self, Error> + 'a {
	        try_pin_init(Self {
	            bar: devres_bar,
	            spec: Spec::new(bar)?,
	            gsp_falcon: Falcon::<Gsp>::new(dev, spec.chipset)?,
	            sec2_falcon: Falcon::<Sec2>::new(dev, spec.chipset)?,
	            sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?
	            gsp <- Gsp::new(gsp_falcon, sec2_falcon, sysmem_flush)?,
	        })
	    }
	}
Quoted 4 lines
Quoted 1 line

It does work. The bizareness of passing the bar twice aside,

Yeah, but it really seems like a minor inconvinience. (Especially, since this will be the only occurance of this we'll ever have.)

It's definitely not a big deal.

Quoted 45 lines
Quoted 2 lines

here is what it looks like when I got it to compile:

This looks great!

Quoted 15 lines
    pub(crate) fn new<'a>(
        pdev: &'a pci::Device<device::Bound>,
        devres_bar: Arc<Devres<Bar0>>,
        bar: &'a Bar0,
    ) -> impl PinInit<Self, Error> + 'a {
        try_pin_init!(Self {
            spec: Spec::new(bar).inspect(|spec| {
                dev_info!(
                    pdev.as_ref(),
                    "NVIDIA (Chipset: {}, Architecture: {:?}, Revision: {})\n",
                    spec.chipset,
                    spec.chipset.arch(),
                    spec.revision
                );
            })?,
(quoted diff) +4 -0
+             _: {
+                 gfw::wait_gfw_boot_completion(bar)
+                     .inspect_err(|_| dev_err!(pdev.as_ref(), "GFW boot did not complete"))?;
+             },
Quoted 13 lines
            sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.chipset)?,

            gsp_falcon: Falcon::<Gsp>::new(
                pdev.as_ref(),
                spec.chipset,
                bar,
                spec.chipset > Chipset::GA100,
            )
            .inspect(|falcon| falcon.clear_swgen0_intr(bar))?,

            sec2_falcon: Falcon::<Sec2>::new(pdev.as_ref(), spec.chipset, bar, true)?,
(quoted diff) +1 -1
-             gsp: Self::start_gsp(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon)?,
+             gsp <- Self::start_gsp(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon),
Quoted 5 lines
            bar: devres_bar,
        })
    }
Quoted 5 lines
Quoted 2 lines

The wait for GFW initialization had to be moved to probe, but that's fine IMO.

That's not necessary, you can keep it in Gpu::new() -- I don't see what's preventing us from that. I inserted it in the code above.

This one didn't work for me, but maybe you have a newer version of the internal references patch:

error: no rules expected reserved identifier _

    --> drivers/gpu/nova-core/gpu.rs:323:13
     |
323  |             _: {
     |             ^ no rules expected this token in macro call
     |

note: while trying to match )

Quoted 48 lines
Quoted 4 lines

I do however find the code less readable in this form, less editable as well. And LSP seems lost, so I don't get any syntax highlighting in the try_pin_init block.

Benno is working on a syntax update, so automatic formatting etc. will properly work.

Otherwise, I can't see how this is a downgrade. It represents the initialization process in a much clearer way that the current implementation of Gsp::new(), which is rather messy.

Quoted 3 lines

Fundamentally, this changes the method from a fallible method returning a non-fallible initializer into a non-fallible method returning a fallible initializer.

Yeah, that's the best case when working with pin-init.

Quoted 3 lines

I'm ok with that, and maybe this new form will
encourage us to keep this method short, which is what we want, but other than that what benefit are we getting from this change?

The immediate benefit is that we don't need an extra allocation for the Gsp structure.

The general benefit is that once we need to add more fields to structures that require pinning (such as locks -- and we will need a lot of them) we're prepared for it.

If we're not prepared for it, I'm pretty sure that everytime someone needs to add e.g. a new lock for something, it will just result in a new Pin<KBox<T>>, because the initial pin-init hierarchy just isn't there, and creating a new allocation is more convinient than fixing the existing code.

This is exactly what pin-init was introduced for in the kernel, such that we're not doing worse than equivalent C code.

	struct Foo {
	   struct Bar bar;
	   void *data;
	   struct mutex data_lock;
	}

	struct Bar {
	   void *data;
	   struct mutex data_lock;
	}
Quoted 8 lines

In C you can just kmalloc(sizeof(Foo), GFP_KERNEL) and subsequently initialize all fields.

In Rust I don't want to fall back having to allocate for Bar *and* for Foo separately.

If there are things to improve with pin-init, let's improve them, but let's not do worse than C code in this aspect.

Maybe I need to get used to this way of initializing, but in any case I can definitely live with it. And it we split initialization into proper functions the code should remain readable.

I'll try and slip this into the next revision of this patchset, or as a follow-up if there isn't one.

author maintainer
#20 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

Quoted 53 lines · Alexandre Courbot
Quoted 44 lines
Quoted 1 line

here is what it looks like when I got it to compile:

This looks great!

Quoted 15 lines
    pub(crate) fn new<'a>(
        pdev: &'a pci::Device<device::Bound>,
        devres_bar: Arc<Devres<Bar0>>,
        bar: &'a Bar0,
    ) -> impl PinInit<Self, Error> + 'a {
        try_pin_init!(Self {
            spec: Spec::new(bar).inspect(|spec| {
                dev_info!(
                    pdev.as_ref(),
                    "NVIDIA (Chipset: {}, Architecture: {:?}, Revision: {})\n",
                    spec.chipset,
                    spec.chipset.arch(),
                    spec.revision
                );
            })?,
(quoted diff) +4 -0
+             _: {
+                 gfw::wait_gfw_boot_completion(bar)
+                     .inspect_err(|_| dev_err!(pdev.as_ref(), "GFW boot did not complete"))?;
+             },
Quoted 13 lines
            sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.chipset)?,

            gsp_falcon: Falcon::<Gsp>::new(
                pdev.as_ref(),
                spec.chipset,
                bar,
                spec.chipset > Chipset::GA100,
            )
            .inspect(|falcon| falcon.clear_swgen0_intr(bar))?,

            sec2_falcon: Falcon::<Sec2>::new(pdev.as_ref(), spec.chipset, bar, true)?,
(quoted diff) +1 -1
-             gsp: Self::start_gsp(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon)?,
+             gsp <- Self::start_gsp(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon),
Quoted 5 lines
            bar: devres_bar,
        })
    }
Quoted 5 lines
Quoted 2 lines

The wait for GFW initialization had to be moved to probe, but that's fine IMO.

That's not necessary, you can keep it in Gpu::new() -- I don't see what's preventing us from that. I inserted it in the code above.

This one didn't work for me, but maybe you have a newer version of the internal references patch:

Quoted 7 lines

error: no rules expected reserved identifier _

    --> drivers/gpu/nova-core/gpu.rs:323:13
     |
323  |             _: {
     |             ^ no rules expected this token in macro call
     |

note: while trying to match )

Ah, just found out about this, neat!

https://lore.kernel.org/rust-for-linux/[email protected]/

maintainer
#21 lore raw

Re: [PATCH v3 02/11] gpu: nova-core: move GSP boot code out of `Gpu` constructor

In reply to Alexandre Courbot
Quoted 81 lines · Alexandre Courbot
Quoted 19 lines · Danilo Krummrich
Quoted 18 lines · Alexandre Courbot
Quoted 16 lines · Danilo Krummrich
	impl Gpu {
	    pub(crate) fn new<'a>(
	        dev: &'a Device<Bound>,
	        bar: &'a Bar0
	        devres_bar: Arc<Devres<Bar0>>,
	    ) -> impl PinInit<Self, Error> + 'a {
	        try_pin_init(Self {
	            bar: devres_bar,
	            spec: Spec::new(bar)?,
	            gsp_falcon: Falcon::<Gsp>::new(dev, spec.chipset)?,
	            sec2_falcon: Falcon::<Sec2>::new(dev, spec.chipset)?,
	            sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?
	            gsp <- Gsp::new(gsp_falcon, sec2_falcon, sysmem_flush)?,
	        })
	    }
	}
Quoted 4 lines
Quoted 1 line

It does work. The bizareness of passing the bar twice aside,

Yeah, but it really seems like a minor inconvinience. (Especially, since this will be the only occurance of this we'll ever have.)

It's definitely not a big deal.

Quoted 45 lines
Quoted 2 lines

here is what it looks like when I got it to compile:

This looks great!

Quoted 15 lines
    pub(crate) fn new<'a>(
        pdev: &'a pci::Device<device::Bound>,
        devres_bar: Arc<Devres<Bar0>>,
        bar: &'a Bar0,
    ) -> impl PinInit<Self, Error> + 'a {
        try_pin_init!(Self {
            spec: Spec::new(bar).inspect(|spec| {
                dev_info!(
                    pdev.as_ref(),
                    "NVIDIA (Chipset: {}, Architecture: {:?}, Revision: {})\n",
                    spec.chipset,
                    spec.chipset.arch(),
                    spec.revision
                );
            })?,
(quoted diff) +4 -0
+             _: {
+                 gfw::wait_gfw_boot_completion(bar)
+                     .inspect_err(|_| dev_err!(pdev.as_ref(), "GFW boot did not complete"))?;
+             },
Quoted 13 lines
            sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.chipset)?,

            gsp_falcon: Falcon::<Gsp>::new(
                pdev.as_ref(),
                spec.chipset,
                bar,
                spec.chipset > Chipset::GA100,
            )
            .inspect(|falcon| falcon.clear_swgen0_intr(bar))?,

            sec2_falcon: Falcon::<Sec2>::new(pdev.as_ref(), spec.chipset, bar, true)?,
(quoted diff) +1 -1
-             gsp: Self::start_gsp(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon)?,
+             gsp <- Self::start_gsp(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon),
Quoted 5 lines
            bar: devres_bar,
        })
    }
Quoted 5 lines
Quoted 2 lines

The wait for GFW initialization had to be moved to probe, but that's fine IMO.

That's not necessary, you can keep it in Gpu::new() -- I don't see what's preventing us from that. I inserted it in the code above.

This one didn't work for me, but maybe you have a newer version of the internal references patch:

Quoted 7 lines

error: no rules expected reserved identifier _

    --> drivers/gpu/nova-core/gpu.rs:323:13
     |
323  |             _: {
     |             ^ no rules expected this token in macro call
     |

note: while trying to match )

Yeah, you also need this patch [1].

[1] https://lore.kernel.org/all/[email protected]/

author maintainer
#22 lore raw

PATCH v3 3/11 gpu: nova-core: add Chipset::name() method

In reply to Alexandre Courbot

There are a few cases where we need the lowercase name of a given chipset, notably to resolve firmware files paths for dynamic loading or to build the module information.

So far, we relied on a static NAMES array for the latter, and some CString hackery for the former.

Replace both with a new name const method that returns the lowercase name of a chipset instance. We can generate it using the paste! macro.

Using this method removes the need to create a CString when loading firmware, and lets us remove a couple of utility functions that now have no user.

---
 drivers/gpu/nova-core/firmware.rs |  8 +++-----
 drivers/gpu/nova-core/gpu.rs      | 25 +++++++++++++++++--------
 drivers/gpu/nova-core/util.rs     | 20 --------------------
 3 files changed, 20 insertions(+), 33 deletions(-)
drivers/gpu/nova-core/firmware.rs +3 -5
index 2931912ddba0ea1fe6d027ccec70b39cdb40344a..213d4506a53f83e7474861f6f81f033a9760fb61 100644
@@ -30,9 +30,7 @@ pub(crate) struct Firmware {
 
 impl Firmware {
     pub(crate) fn new(dev: &device::Device, chipset: Chipset, ver: &str) -> Result<Firmware> {
-        let mut chip_name = CString::try_from_fmt(fmt!("{chipset}"))?;
-        chip_name.make_ascii_lowercase();
-        let chip_name = &*chip_name;
+        let chip_name = chipset.name();
 
         let request = |name_| {
             CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{name_}-{ver}.bin"))
@@ -180,8 +178,8 @@ pub(crate) const fn create(
         let mut this = Self(firmware::ModInfoBuilder::new(module_name));
         let mut i = 0;
 
-        while i < gpu::Chipset::NAMES.len() {
-            this = this.make_entry_chipset(gpu::Chipset::NAMES[i]);
+        while i < gpu::Chipset::ALL.len() {
+            this = this.make_entry_chipset(gpu::Chipset::ALL[i].name());
             i += 1;
         }
 
drivers/gpu/nova-core/gpu.rs +17 -8
index 8343276e52e6a87a8ff1aff9fc484e00d4b57417..709afbe56c7f3b713bb249a022d68d81783d36f5 100644
@@ -10,7 +10,6 @@
 use crate::firmware::{Firmware, FIRMWARE_VERSION};
 use crate::gfw;
 use crate::regs;
-use crate::util;
 use crate::vbios::Vbios;
 use core::fmt;
 
@@ -28,13 +27,23 @@ impl Chipset {
                 $( Chipset::$variant, )*
             ];
 
-            pub(crate) const NAMES: [&'static str; Self::ALL.len()] = [
-                $( util::const_bytes_to_str(
-                        util::to_lowercase_bytes::<{ stringify!($variant).len() }>(
-                            stringify!($variant)
-                        ).as_slice()
-                ), )*
-            ];
+            ::kernel::macros::paste!(
+            /// Returns the name of this chipset, in lowercase.
+            ///
+            /// # Examples
+            ///
+            /// ```
+            /// let chipset = Chipset::GA102;
+            /// assert_eq!(chipset.name(), "ga102");
+            /// ```
+            pub(crate) const fn name(&self) -> &'static str {
+                match *self {
+                $(
+                    Chipset::$variant => stringify!([<$variant:lower>]),
+                )*
+                }
+            }
+            );
         }
 
         // TODO[FPRI]: replace with something like derive(FromPrimitive)
drivers/gpu/nova-core/util.rs +0 -20
index 76cedf3710d7bb248f62ed50381a70f8ffb3f19a..bf35f00cb732ee4fa6644854718a0ad99051666a 100644
@@ -3,26 +3,6 @@
 use kernel::prelude::*;
 use kernel::time::{Delta, Instant, Monotonic};
 
-pub(crate) const fn to_lowercase_bytes<const N: usize>(s: &str) -> [u8; N] {
-    let src = s.as_bytes();
-    let mut dst = [0; N];
-    let mut i = 0;
-
-    while i < src.len() && i < N {
-        dst[i] = (src[i] as char).to_ascii_lowercase() as u8;
-        i += 1;
-    }
-
-    dst
-}
-
-pub(crate) const fn const_bytes_to_str(bytes: &[u8]) -> &str {
-    match core::str::from_utf8(bytes) {
-        Ok(string) => string,
-        Err(_) => kernel::build_error!("Bytes are not valid UTF-8."),
-    }
-}
-
 /// Wait until `cond` is true or `timeout` elapsed.
 ///
 /// When `cond` evaluates to `Some`, its return value is returned.
Signature · 1 line
2.51.0
author maintainer
#23 lore raw

PATCH v3 4/11 gpu: nova-core: firmware: move firmware request code into a function

In reply to Alexandre Courbot

When all the firmware files are loaded from Firmware::new, it makes sense to have the firmware request code into a closure. However, as we eventually want each individual firmware constructor to request its own file (and get rid of Firmware altogether), move this code into a dedicated function that can be called by individual firmware types.

---
 drivers/gpu/nova-core/firmware.rs | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)
drivers/gpu/nova-core/firmware.rs +14 -6
index 213d4506a53f83e7474861f6f81f033a9760fb61..4e8654d294a2205ac6f0b05b6da8d959a415ced1 100644
@@ -19,6 +19,19 @@
 
 pub(crate) const FIRMWARE_VERSION: &str = "535.113.01";
 
+/// Requests the GPU firmware `name` suitable for `chipset`, with version `ver`.
+fn request_nv_firmware(
+    dev: &device::Device,
+    chipset: gpu::Chipset,
+    name: &str,
+    ver: &str,
+) -> Result<firmware::Firmware> {
+    let chip_name = chipset.name();
+
+    CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{name}-{ver}.bin"))
+        .and_then(|path| firmware::Firmware::request(&path, dev))
+}
+
 /// Structure encapsulating the firmware blobs required for the GPU to operate.
 #[expect(dead_code)]
 pub(crate) struct Firmware {
@@ -30,12 +43,7 @@ pub(crate) struct Firmware {
 
 impl Firmware {
     pub(crate) fn new(dev: &device::Device, chipset: Chipset, ver: &str) -> Result<Firmware> {
-        let chip_name = chipset.name();
-
-        let request = |name_| {
-            CString::try_from_fmt(fmt!("nvidia/{chip_name}/gsp/{name_}-{ver}.bin"))
-                .and_then(|path| firmware::Firmware::request(&path, dev))
-        };
+        let request = |name| request_nv_firmware(dev, chipset, name, ver);
 
         Ok(Firmware {
             booter_load: request("booter_load")?,
Signature · 1 line
2.51.0
author maintainer
#24 lore raw

PATCH v3 5/11 gpu: nova-core: firmware: add support for common firmware header

In reply to Alexandre Courbot

Several firmware files loaded from userspace feature a common header that describes their payload. Add basic support for it so subsequent patches can leverage it.

---
 drivers/gpu/nova-core/firmware.rs | 62 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 62 insertions(+)
drivers/gpu/nova-core/firmware.rs +62 -0
index 4e8654d294a2205ac6f0b05b6da8d959a415ced1..32b685c8757b1106084577c2cc7d5ef6056c1c64 100644
@@ -4,11 +4,13 @@
 //! to be loaded into a given execution unit.
 
 use core::marker::PhantomData;
+use core::mem::size_of;
 
 use kernel::device;
 use kernel::firmware;
 use kernel::prelude::*;
 use kernel::str::CString;
+use kernel::transmute::FromBytes;
 
 use crate::dma::DmaObject;
 use crate::falcon::FalconFirmware;
@@ -156,6 +158,66 @@ fn no_patch_signature(self) -> FirmwareDmaObject<F, Signed> {
     }
 }
 
+/// Header common to most firmware files.
+#[repr(C)]
+#[derive(Debug, Clone)]
+struct BinHdr {
+    /// Magic number, must be `0x10de`.
+    bin_magic: u32,
+    /// Version of the header.
+    bin_ver: u32,
+    /// Size in bytes of the binary (to be ignored).
+    bin_size: u32,
+    /// Offset of the start of the application-specific header.
+    header_offset: u32,
+    /// Offset of the start of the data payload.
+    data_offset: u32,
+    /// Size in bytes of the data payload.
+    data_size: u32,
+}
+
+// SAFETY: all bit patterns are valid for this type, and it doesn't use interior mutability.
+unsafe impl FromBytes for BinHdr {}
+
+// A firmware blob starting with a `BinHdr`.
+struct BinFirmware<'a> {
+    hdr: BinHdr,
+    fw: &'a [u8],
+}
+
+#[expect(dead_code)]
+impl<'a> BinFirmware<'a> {
+    /// Interpret `fw` as a firmware image starting with a [`BinHdr`], and returns the
+    /// corresponding [`BinFirmware`] that can be used to extract its payload.
+    fn new(fw: &'a firmware::Firmware) -> Result<Self> {
+        const BIN_MAGIC: u32 = 0x10de;
+        let fw = fw.data();
+
+        fw.get(0..size_of::<BinHdr>())
+            // Extract header.
+            .and_then(BinHdr::from_bytes_copy)
+            // Validate header.
+            .and_then(|hdr| {
+                if hdr.bin_magic == BIN_MAGIC {
+                    Some(hdr)
+                } else {
+                    None
+                }
+            })
+            .map(|hdr| Self { hdr, fw })
+            .ok_or(EINVAL)
+    }
+
+    /// Returns the data payload of the firmware, or `None` if the data range is out of bounds of
+    /// the firmware image.
+    fn data(&self) -> Option<&[u8]> {
+        let fw_start = self.hdr.data_offset as usize;
+        let fw_size = self.hdr.data_size as usize;
+
+        self.fw.get(fw_start..fw_start + fw_size)
+    }
+}
+
 pub(crate) struct ModInfoBuilder<const N: usize>(firmware::ModInfoBuilder<N>);
 
 impl<const N: usize> ModInfoBuilder<N> {
Signature · 1 line
2.51.0
author maintainer
#25 lore raw

PATCH v3 6/11 gpu: nova-core: firmware: process Booter and patch its signature

In reply to Alexandre Courbot

The Booter signed firmware is an essential part of bringing up the GSP on Turing and Ampere. It is loaded on the sec2 falcon core and is responsible for loading and running the RISC-V GSP bootloader into the GSP core.

Add support for parsing the Booter firmware loaded from userspace, patch its signatures, and store it into a form that is ready to be loaded and executed on the sec2 falcon.

Then, move the Booter instance from the Firmware struct to the start_gsp method since it doesn't need to be kept after the GSP is booted.

We do not run Booter yet, as its own payload (the GSP bootloader and firmware image) still need to be prepared.

---
 drivers/gpu/nova-core/falcon.rs          |   4 +-
 drivers/gpu/nova-core/firmware.rs        |   6 +-
 drivers/gpu/nova-core/firmware/booter.rs | 375 +++++++++++++++++++++++++++++++
 drivers/gpu/nova-core/gpu.rs             |  10 +
 4 files changed, 388 insertions(+), 7 deletions(-)
drivers/gpu/nova-core/falcon.rs +2 -2
index b16207e7242fe1ac26b8552575b8b4e52f34cf6a..37e6298195e49a9a29e81226abe16cd410c9adbc 100644
@@ -293,7 +293,7 @@ pub(crate) trait FalconEngine:
 }
 
 /// Represents a portion of the firmware to be loaded into a particular memory (e.g. IMEM or DMEM).
-#[derive(Debug)]
+#[derive(Debug, Clone)]
 pub(crate) struct FalconLoadTarget {
     /// Offset from the start of the source object to copy from.
     pub(crate) src_start: u32,
@@ -304,7 +304,7 @@ pub(crate) struct FalconLoadTarget {
 }
 
 /// Parameters for the falcon boot ROM.
-#[derive(Debug)]
+#[derive(Debug, Clone)]
 pub(crate) struct FalconBromParams {
     /// Offset in `DMEM`` of the firmware's signature.
     pub(crate) pkc_data_offset: u32,
drivers/gpu/nova-core/firmware.rs +1 -5
index 32b685c8757b1106084577c2cc7d5ef6056c1c64..d954b1e98fda82c44f87d2103e31fa717c392d79 100644
@@ -17,6 +17,7 @@
 use crate::gpu;
 use crate::gpu::Chipset;
 
+pub(crate) mod booter;
 pub(crate) mod fwsec;
 
 pub(crate) const FIRMWARE_VERSION: &str = "535.113.01";
@@ -37,8 +38,6 @@ fn request_nv_firmware(
 /// Structure encapsulating the firmware blobs required for the GPU to operate.
 #[expect(dead_code)]
 pub(crate) struct Firmware {
-    booter_load: firmware::Firmware,
-    booter_unload: firmware::Firmware,
     bootloader: firmware::Firmware,
     gsp: firmware::Firmware,
 }
@@ -48,8 +47,6 @@ pub(crate) fn new(dev: &device::Device, chipset: Chipset, ver: &str) -> Result<F
         let request = |name| request_nv_firmware(dev, chipset, name, ver);
 
         Ok(Firmware {
-            booter_load: request("booter_load")?,
-            booter_unload: request("booter_unload")?,
             bootloader: request("bootloader")?,
             gsp: request("gsp")?,
         })
@@ -185,7 +182,6 @@ struct BinFirmware<'a> {
     fw: &'a [u8],
 }
 
-#[expect(dead_code)]
 impl<'a> BinFirmware<'a> {
     /// Interpret `fw` as a firmware image starting with a [`BinHdr`], and returns the
     /// corresponding [`BinFirmware`] that can be used to extract its payload.
drivers/gpu/nova-core/firmware/booter.rs new file +375 -0

375 lines not on this page · raw message

drivers/gpu/nova-core/gpu.rs +10 -0
index 709afbe56c7f3b713bb249a022d68d81783d36f5..2f5ae89ab80b237eba5d55351229be78cd471a72 100644
@@ -6,6 +6,7 @@
 use crate::falcon::{gsp::Gsp, sec2::Sec2, Falcon};
 use crate::fb::FbLayout;
 use crate::fb::SysmemFlush;
+use crate::firmware::booter::{BooterFirmware, BooterKind};
 use crate::firmware::fwsec::{FwsecCommand, FwsecFirmware};
 use crate::firmware::{Firmware, FIRMWARE_VERSION};
 use crate::gfw;
@@ -293,6 +294,15 @@ pub(crate) fn start_gsp(&self, pdev: &pci::Device<device::Bound>) -> Result<()>
 
         self.run_fwsec_frts(dev, bar, &bios, &fb_layout)?;
 
+        let _booter_loader = BooterFirmware::new(
+            dev,
+            BooterKind::Loader,
+            self.spec.chipset,
+            FIRMWARE_VERSION,
+            &self.sec2_falcon,
+            bar,
+        )?;
+
         Ok(())
     }
 
Signature · 1 line
2.51.0
author maintainer
#26 lore raw

PATCH v3 7/11 gpu: nova-core: firmware: process and prepare the GSP firmware

In reply to Alexandre Courbot

The GSP firmware is a binary blob that is verified, loaded, and run by the GSP bootloader. Its presentation is a bit peculiar as the GSP bootloader expects to be given a DMA address to a 3-levels page table mapping the GSP firmware at address 0 of its own address space.

Prepare such a structure containing the DMA-mapped firmware as well as the DMA-mapped page tables, and a way to obtain the DMA handle of the level 0 page table.

Then, move the GSP firmware instance from the Firmware struct to the start_gsp method since it doesn't need to be kept after the GSP is booted.

As we are performing the required ELF section parsing and radix3 page table building, remove these items from the TODO file.

---
 Documentation/gpu/nova/core/todo.rst  |  17 ---
 drivers/gpu/nova-core/firmware.rs     |   3 +-
 drivers/gpu/nova-core/firmware/gsp.rs | 237 ++++++++++++++++++++++++++++++++++
 drivers/gpu/nova-core/gpu.rs          |   6 +
 drivers/gpu/nova-core/gsp.rs          |   4 +
 drivers/gpu/nova-core/nova_core.rs    |   1 +
 6 files changed, 249 insertions(+), 19 deletions(-)
Documentation/gpu/nova/core/todo.rst +0 -17
index 89431fec9041b1f35cc55799c91f48dc6bc918eb..0972cb905f7ae64dfbaef4808276757319009e9c 100644
@@ -229,23 +229,6 @@ Rust abstraction for debugfs APIs.
 GPU (general)
 =============
 
-Parse firmware headers
-----------------------
-
-Parse ELF headers from the firmware files loaded from the filesystem.
-
-| Reference: ELF utils
-| Complexity: Beginner
-| Contact: Abdiel Janulgue
-
-Build radix3 page table
------------------------
-
-Build the radix3 page table to map the firmware.
-
-| Complexity: Intermediate
-| Contact: Abdiel Janulgue
-
 Initial Devinit support
 -----------------------
 
drivers/gpu/nova-core/firmware.rs +1 -2
index d954b1e98fda82c44f87d2103e31fa717c392d79..cef910a7c2dc360139fafc2a01a050a9df40e45f 100644
@@ -19,6 +19,7 @@
 
 pub(crate) mod booter;
 pub(crate) mod fwsec;
+pub(crate) mod gsp;
 
 pub(crate) const FIRMWARE_VERSION: &str = "535.113.01";
 
@@ -39,7 +40,6 @@ fn request_nv_firmware(
 #[expect(dead_code)]
 pub(crate) struct Firmware {
     bootloader: firmware::Firmware,
-    gsp: firmware::Firmware,
 }
 
 impl Firmware {
@@ -48,7 +48,6 @@ pub(crate) fn new(dev: &device::Device, chipset: Chipset, ver: &str) -> Result<F
 
         Ok(Firmware {
             bootloader: request("bootloader")?,
-            gsp: request("gsp")?,
         })
     }
 }
drivers/gpu/nova-core/firmware/gsp.rs new file +237 -0

237 lines not on this page · raw message

drivers/gpu/nova-core/gpu.rs +6 -0
index 2f5ae89ab80b237eba5d55351229be78cd471a72..547e5dd31aeb9650b226c267de5f0412173b3fe0 100644
@@ -8,6 +8,7 @@
 use crate::fb::SysmemFlush;
 use crate::firmware::booter::{BooterFirmware, BooterKind};
 use crate::firmware::fwsec::{FwsecCommand, FwsecFirmware};
+use crate::firmware::gsp::GspFirmware;
 use crate::firmware::{Firmware, FIRMWARE_VERSION};
 use crate::gfw;
 use crate::regs;
@@ -289,6 +290,11 @@ pub(crate) fn start_gsp(&self, pdev: &pci::Device<device::Bound>) -> Result<()>
 
         let bios = Vbios::new(dev, bar)?;
 
+        let _gsp_fw = KBox::pin_init(
+            GspFirmware::new(dev, self.spec.chipset, FIRMWARE_VERSION)?,
+            GFP_KERNEL,
+        )?;
+
         let fb_layout = FbLayout::new(self.spec.chipset, bar)?;
         dev_dbg!(dev, "{:#x?}\n", fb_layout);
 
drivers/gpu/nova-core/gsp.rs new file +4 -0
new file mode 100644
index 0000000000000000000000000000000000000000..a0e7ec5f6c9c959d57540b3ebf4b782f2e002b08
@@ -0,0 +1,4 @@
+// SPDX-License-Identifier: GPL-2.0
+
+pub(crate) const GSP_PAGE_SHIFT: usize = 12;
+pub(crate) const GSP_PAGE_SIZE: usize = 1 << GSP_PAGE_SHIFT;
drivers/gpu/nova-core/nova_core.rs +1 -0
index cb2bbb30cba142265b354c9acf70349a6e40759e..fffcaee2249fe6cd7f55a7291c1e44be42e791d9 100644
@@ -9,6 +9,7 @@
 mod firmware;
 mod gfw;
 mod gpu;
+mod gsp;
 mod regs;
 mod util;
 mod vbios;
Signature · 1 line
2.51.0
author maintainer
#27 lore raw

PATCH v3 8/11 gpu: nova-core: firmware: process the GSP bootloader

In reply to Alexandre Courbot

The GSP bootloader is a small RISC-V firmware that is loaded by Booter onto the GSP core and is in charge of loading, validating, and starting the actual GSP firmware.

It is a regular binary firmware file containing a specific header. Create a type holding the DMA-mapped firmware as well as useful information extracted from the header, and hook it into our firmware structure for later use.

The GSP bootloader is stored into the GspFirmware structure, since it is part of the GSP firmware package. This makes the Firmware structure empty, so remove it.

---
 drivers/gpu/nova-core/firmware.rs       | 18 +------
 drivers/gpu/nova-core/firmware/gsp.rs   |  7 +++
 drivers/gpu/nova-core/firmware/riscv.rs | 89 +++++++++++++++++++++++++++++++++
 drivers/gpu/nova-core/gpu.rs            |  5 +-
 4 files changed, 98 insertions(+), 21 deletions(-)
drivers/gpu/nova-core/firmware.rs +1 -17
index cef910a7c2dc360139fafc2a01a050a9df40e45f..af7356a14def2ee92c3285878ea4de64eb48d344 100644
@@ -15,11 +15,11 @@
 use crate::dma::DmaObject;
 use crate::falcon::FalconFirmware;
 use crate::gpu;
-use crate::gpu::Chipset;
 
 pub(crate) mod booter;
 pub(crate) mod fwsec;
 pub(crate) mod gsp;
+pub(crate) mod riscv;
 
 pub(crate) const FIRMWARE_VERSION: &str = "535.113.01";
 
@@ -36,22 +36,6 @@ fn request_nv_firmware(
         .and_then(|path| firmware::Firmware::request(&path, dev))
 }
 
-/// Structure encapsulating the firmware blobs required for the GPU to operate.
-#[expect(dead_code)]
-pub(crate) struct Firmware {
-    bootloader: firmware::Firmware,
-}
-
-impl Firmware {
-    pub(crate) fn new(dev: &device::Device, chipset: Chipset, ver: &str) -> Result<Firmware> {
-        let request = |name| request_nv_firmware(dev, chipset, name, ver);
-
-        Ok(Firmware {
-            bootloader: request("bootloader")?,
-        })
-    }
-}
-
 /// Structure used to describe some firmwares, notably FWSEC-FRTS.
 #[repr(C)]
 #[derive(Debug, Clone)]
drivers/gpu/nova-core/firmware/gsp.rs +7 -0
index ddbf3f27dd795b9b2480f0392160a3bfb68c6ab7..a377c5138294c9cc70714cd18eed54d679aba835 100644
@@ -8,6 +8,7 @@
 use kernel::scatterlist::SGTable;
 
 use crate::dma::DmaObject;
+use crate::firmware::riscv::RiscvFirmware;
 use crate::gpu::Architecture;
 use crate::gpu::Chipset;
 use crate::gsp::GSP_PAGE_SIZE;
@@ -127,6 +128,8 @@ pub(crate) struct GspFirmware {
     pub size: usize,
     /// Device-mapped GSP signatures matching the GPU's [`Chipset`].
     signatures: DmaObject,
+    /// GSP bootloader, verifies the GSP firmware before loading and running it.
+    bootloader: RiscvFirmware,
 }
 
 impl GspFirmware {
@@ -160,6 +163,9 @@ pub(crate) fn new<'a, 'b>(
             })
             .map_err(|_| ENOMEM)?;
 
+        let bl = super::request_nv_firmware(dev, chipset, "bootloader", ver)?;
+        let bootloader = RiscvFirmware::new(dev, &bl)?;
+
         Ok(try_pin_init!(&this in Self {
             fw <- SGTable::new(dev, fw_vvec, DataDirection::ToDevice, GFP_KERNEL),
             level2 <- {
@@ -207,6 +213,7 @@ pub(crate) fn new<'a, 'b>(
             },
             size,
             signatures,
+            bootloader,
         }))
     }
 
drivers/gpu/nova-core/firmware/riscv.rs new file +89 -0

89 lines not on this page · raw message

drivers/gpu/nova-core/gpu.rs +1 -4
index 547e5dd31aeb9650b226c267de5f0412173b3fe0..b7798257e463a2a0e29e33a1e1076380de077bee 100644
@@ -9,7 +9,7 @@
 use crate::firmware::booter::{BooterFirmware, BooterKind};
 use crate::firmware::fwsec::{FwsecCommand, FwsecFirmware};
 use crate::firmware::gsp::GspFirmware;
-use crate::firmware::{Firmware, FIRMWARE_VERSION};
+use crate::firmware::FIRMWARE_VERSION;
 use crate::gfw;
 use crate::regs;
 use crate::vbios::Vbios;
@@ -179,7 +179,6 @@ pub(crate) struct Gpu {
     spec: Spec,
     /// MMIO mapping of PCI BAR 0
     bar: Arc<Devres<Bar0>>,
-    fw: Firmware,
     /// System memory page required for flushing all pending GPU-side memory writes done through
     /// PCIE into system memory, via sysmembar (A GPU-initiated HW memory-barrier operation).
     sysmem_flush: SysmemFlush,
@@ -318,7 +317,6 @@ pub(crate) fn new(
     ) -> Result<impl PinInit<Self>> {
         let bar = devres_bar.access(pdev.as_ref())?;
         let spec = Spec::new(bar)?;
-        let fw = Firmware::new(pdev.as_ref(), spec.chipset, FIRMWARE_VERSION)?;
 
         dev_info!(
             pdev.as_ref(),
@@ -347,7 +345,6 @@ pub(crate) fn new(
         Ok(pin_init!(Self {
             spec,
             bar: devres_bar,
-            fw,
             sysmem_flush,
             gsp_falcon,
             sec2_falcon,
Signature · 1 line
2.51.0
author maintainer
#28 lore raw

PATCH v3 9/11 gpu: nova-core: firmware: use 570.144 firmware

In reply to Alexandre Courbot

570.144 is the latest available into linux-firmware as of this commit, and the one we will use to start development of nova-core. It should eventually be dropped for a newer version before the driver becomes able to do anything useful. The newer firmware is expected to iron out some of the inelegances of 570.144, notably related to packaging.

---
 drivers/gpu/nova-core/firmware.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/nova-core/firmware.rs +1 -1
index af7356a14def2ee92c3285878ea4de64eb48d344..9a97e97a3c7b4ac65b66e4e5f092839720ded82d 100644
@@ -21,7 +21,7 @@
 pub(crate) mod gsp;
 pub(crate) mod riscv;
 
-pub(crate) const FIRMWARE_VERSION: &str = "535.113.01";
+pub(crate) const FIRMWARE_VERSION: &str = "570.144";
 
 /// Requests the GPU firmware `name` suitable for `chipset`, with version `ver`.
 fn request_nv_firmware(
Signature · 1 line
2.51.0
author maintainer
#29 lore raw

PATCH v3 10/11 gpu: nova-core: Add base files for r570.144 firmware bindings

In reply to Alexandre Courbot

From: Alistair Popple <[email protected]>

Interacting with the GSP currently requires using definitions from C header files. Rust definitions for the types needed for Nova core will be generated using the Rust bindgen tool. This patch adds the base module to allow inclusion of the generated bindings. The generated bindings themselves are added by subsequent patches when they are first used.

Currently we only intend to support a single firmware version, 570.144, with these bindings. Longer term we intend to move to a more stable GSP interface that isn't tied to specific firmware versions.

---
 drivers/gpu/nova-core/nova_core.rs              |  1 +
 drivers/gpu/nova-core/nvfw.rs                   |  6 +++++
 drivers/gpu/nova-core/nvfw/r570_144.rs          | 29 +++++++++++++++++++++++++
 drivers/gpu/nova-core/nvfw/r570_144_bindings.rs |  1 +
 4 files changed, 37 insertions(+)
drivers/gpu/nova-core/nova_core.rs +1 -0
index fffcaee2249fe6cd7f55a7291c1e44be42e791d9..db197498b0b7b1ff9234ef6645a4ea5ff44bd285 100644
@@ -10,6 +10,7 @@
 mod gfw;
 mod gpu;
 mod gsp;
+mod nvfw;
 mod regs;
 mod util;
 mod vbios;
drivers/gpu/nova-core/nvfw.rs new file +6 -0
new file mode 100644
index 0000000000000000000000000000000000000000..779db25095892d6d88652fb7da243a8d2f7db047
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: GPL-2.0
+
+mod r570_144;
+
+// Alias to avoid repeating the version number with every use.
+use r570_144 as bindings;
drivers/gpu/nova-core/nvfw/r570_144.rs new file +29 -0
new file mode 100644
index 0000000000000000000000000000000000000000..2e7bba80fa8b9c5fcb4e26887825d2cca3f7b6b7
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Firmware bindings.
+//!
+//! Imports the generated bindings by `bindgen`.
+//!
+//! This module may not be directly used. Please abstract or re-export the needed symbols in the
+//! parent module instead.
+
+#![cfg_attr(test, allow(deref_nullptr))]
+#![cfg_attr(test, allow(unaligned_references))]
+#![cfg_attr(test, allow(unsafe_op_in_unsafe_fn))]
+#![allow(
+    dead_code,
+    unused_imports,
+    clippy::all,
+    clippy::undocumented_unsafe_blocks,
+    clippy::ptr_as_ptr,
+    clippy::ref_as_ptr,
+    missing_docs,
+    non_camel_case_types,
+    non_upper_case_globals,
+    non_snake_case,
+    improper_ctypes,
+    unreachable_pub,
+    unsafe_op_in_unsafe_fn
+)]
+use kernel::ffi;
+include!("r570_144_bindings.rs");
drivers/gpu/nova-core/nvfw/r570_144_bindings.rs new file +1 -0
new file mode 100644
index 0000000000000000000000000000000000000000..cec5940325151e407aa90128a35cb683afd436d7
@@ -0,0 +1 @@
+// SPDX-License-Identifier: GPL-2.0
Signature · 1 line
2.51.0
author maintainer
#30 lore raw

PATCH v3 11/11 gpu: nova-core: compute layout of more framebuffer regions required for GSP

In reply to Alexandre Courbot

Compute more of the required FB layout information to boot the GSP firmware.

This information is dependent on the firmware itself, so first we need to import and abstract the required firmware bindings in the nvfw module.

Then, a new FB HAL method is introduced in fb::hal that uses these bindings and hardware information to compute the correct layout information.

This information is then used in fb and the result made visible in FbLayout.

These 3 things are grouped into the same patch to avoid lots of unused warnings that would be tedious to work around. As they happen in different files, they should not be too difficult to track separately.

---
 drivers/gpu/nova-core/fb.rs                     |  64 +++++++++++-
 drivers/gpu/nova-core/fb/hal.rs                 |   4 +
 drivers/gpu/nova-core/fb/hal/ga100.rs           |   5 +
 drivers/gpu/nova-core/fb/hal/ga102.rs           |  10 ++
 drivers/gpu/nova-core/fb/hal/tu102.rs           |  11 +++
 drivers/gpu/nova-core/firmware/gsp.rs           |   2 +-
 drivers/gpu/nova-core/firmware/riscv.rs         |   2 +-
 drivers/gpu/nova-core/gpu.rs                    |   4 +-
 drivers/gpu/nova-core/gsp.rs                    |   3 +
 drivers/gpu/nova-core/nvfw.rs                   |  86 ++++++++++++++++
 drivers/gpu/nova-core/nvfw/r570_144.rs          |   1 -
 drivers/gpu/nova-core/nvfw/r570_144_bindings.rs | 125 ++++++++++++++++++++++++
 12 files changed, 310 insertions(+), 7 deletions(-)
drivers/gpu/nova-core/fb.rs +62 -2
index b0e860498b883815b3861b8717f8ee1832d25440..8f75d7fff99f845cd6ba0d9c2734fc556c0097bb 100644
@@ -10,7 +10,9 @@
 
 use crate::dma::DmaObject;
 use crate::driver::Bar0;
+use crate::firmware::gsp::GspFirmware;
 use crate::gpu::Chipset;
+use crate::nvfw;
 use crate::regs;
 
 mod hal;
@@ -87,14 +89,28 @@ pub(crate) fn unregister(&self, bar: &Bar0) {
 #[derive(Debug)]
 #[expect(dead_code)]
 pub(crate) struct FbLayout {
+    /// Range of the framebuffer. Starts at `0`.
     pub(crate) fb: Range<u64>,
+    /// VGA workspace, small area of reserved memory at the end of the framebuffer.
     pub(crate) vga_workspace: Range<u64>,
+    /// FRTS range.
     pub(crate) frts: Range<u64>,
+    /// Memory area containing the GSP bootloader image.
+    pub(crate) boot: Range<u64>,
+    /// Memory area containing the GSP firmware image.
+    pub(crate) elf: Range<u64>,
+    /// WPR2 heap.
+    pub(crate) wpr2_heap: Range<u64>,
+    // WPR2 region range, starting with an instance of `GspFwWprMeta`.
+    pub(crate) wpr2: Range<u64>,
+    pub(crate) heap: Range<u64>,
+    pub(crate) vf_partition_count: u8,
 }
 
 impl FbLayout {
-    /// Computes the FB layout.
-    pub(crate) fn new(chipset: Chipset, bar: &Bar0) -> Result<Self> {
+    /// Computes the FB layout for `chipset`, for running the `bl` GSP bootloader and `gsp` GSP
+    /// firmware.
+    pub(crate) fn new(chipset: Chipset, bar: &Bar0, gsp_fw: &GspFirmware) -> Result<Self> {
         let hal = hal::fb_hal(chipset);
 
         let fb = {
@@ -138,10 +154,54 @@ pub(crate) fn new(chipset: Chipset, bar: &Bar0) -> Result<Self> {
             frts_base..frts_base + FRTS_SIZE
         };
 
+        let boot = {
+            const BOOTLOADER_DOWN_ALIGN: Alignment = Alignment::new(SZ_4K);
+            let bootloader_size = gsp_fw.bootloader.ucode.size() as u64;
+            let bootloader_base = (frts.start - bootloader_size).align_down(BOOTLOADER_DOWN_ALIGN);
+
+            bootloader_base..bootloader_base + bootloader_size
+        };
+
+        let elf = {
+            const ELF_DOWN_ALIGN: Alignment = Alignment::new(SZ_64K);
+            let elf_size = gsp_fw.size as u64;
+            let elf_addr = (boot.start - elf_size).align_down(ELF_DOWN_ALIGN);
+
+            elf_addr..elf_addr + elf_size
+        };
+
+        let wpr2_heap = {
+            const WPR2_HEAP_DOWN_ALIGN: Alignment = Alignment::new(SZ_1M);
+            let wpr2_heap_size = hal.libos_params().wpr_heap_size(chipset, fb.end);
+            let wpr2_heap_addr = (elf.start - wpr2_heap_size).align_down(WPR2_HEAP_DOWN_ALIGN);
+
+            wpr2_heap_addr..(elf.start).align_down(WPR2_HEAP_DOWN_ALIGN)
+        };
+
+        let wpr2 = {
+            const WPR2_DOWN_ALIGN: Alignment = Alignment::new(SZ_1M);
+            let wpr2_addr = (wpr2_heap.start - size_of::<nvfw::GspFwWprMeta>() as u64)
+                .align_down(WPR2_DOWN_ALIGN);
+
+            wpr2_addr..frts.end
+        };
+
+        let heap = {
+            const HEAP_SIZE: u64 = SZ_1M as u64;
+
+            wpr2.start - HEAP_SIZE..wpr2.start
+        };
+
         Ok(Self {
             fb,
             vga_workspace,
             frts,
+            boot,
+            elf,
+            wpr2_heap,
+            wpr2,
+            heap,
+            vf_partition_count: 0,
         })
     }
 }
drivers/gpu/nova-core/fb/hal.rs +4 -0
index 2f914948bb9a9842fd00a4c6381420b74de81c3f..d87d285d75841134e58375772543344131d804b3 100644
@@ -4,6 +4,7 @@
 
 use crate::driver::Bar0;
 use crate::gpu::Chipset;
+use crate::nvfw::LibosParams;
 
 mod ga100;
 mod ga102;
@@ -23,6 +24,9 @@ pub(crate) trait FbHal {
 
     /// Returns the VRAM size, in bytes.
     fn vidmem_size(&self, bar: &Bar0) -> u64;
+
+    /// Returns the libos requirements to start the GSP firmware.
+    fn libos_params(&self) -> &'static LibosParams;
 }
 
 /// Returns the HAL corresponding to `chipset`.
drivers/gpu/nova-core/fb/hal/ga100.rs +5 -0
index 871c42bf033acd0b9c5735c43d408503075099af..3ca46861ab4ffd267a50ffe04baad7e861fae04a 100644
@@ -6,6 +6,7 @@
 
 use crate::driver::Bar0;
 use crate::fb::hal::FbHal;
+use crate::nvfw::LibosParams;
 use crate::regs;
 
 use super::tu102::FLUSH_SYSMEM_ADDR_SHIFT;
@@ -51,6 +52,10 @@ fn supports_display(&self, bar: &Bar0) -> bool {
     fn vidmem_size(&self, bar: &Bar0) -> u64 {
         super::tu102::vidmem_size_gp102(bar)
     }
+
+    fn libos_params(&self) -> &'static LibosParams {
+        super::tu102::libos_params_tu102()
+    }
 }
 
 const GA100: Ga100 = Ga100;
drivers/gpu/nova-core/fb/hal/ga102.rs +10 -0
index a73b77e3971513d088211a97ad8e50b00a9131f7..8f54aff4418316f7bdf873a64e695df97d0eda28 100644
@@ -4,12 +4,18 @@
 
 use crate::driver::Bar0;
 use crate::fb::hal::FbHal;
+use crate::nvfw;
+use crate::nvfw::LibosParams;
 use crate::regs;
 
 fn vidmem_size_ga102(bar: &Bar0) -> u64 {
     regs::NV_USABLE_FB_SIZE_IN_MB::read(bar).usable_fb_size()
 }
 
+fn libos_params_ga102() -> &'static LibosParams {
+    &nvfw::LIBOS3_PARAMS
+}
+
 struct Ga102;
 
 impl FbHal for Ga102 {
@@ -30,6 +36,10 @@ fn supports_display(&self, bar: &Bar0) -> bool {
     fn vidmem_size(&self, bar: &Bar0) -> u64 {
         vidmem_size_ga102(bar)
     }
+
+    fn libos_params(&self) -> &'static LibosParams {
+        libos_params_ga102()
+    }
 }
 
 const GA102: Ga102 = Ga102;
drivers/gpu/nova-core/fb/hal/tu102.rs +11 -0
index b022c781caf4514b4060fa2083cdc0ca12573c5b..220e865242dcc11271d28860b2ea5834fbe00399 100644
@@ -2,7 +2,10 @@
 
 use crate::driver::Bar0;
 use crate::fb::hal::FbHal;
+use crate::nvfw;
+use crate::nvfw::LibosParams;
 use crate::regs;
+
 use kernel::prelude::*;
 
 /// Shift applied to the sysmem address before it is written into `NV_PFB_NISO_FLUSH_SYSMEM_ADDR`,
@@ -34,6 +37,10 @@ pub(super) fn vidmem_size_gp102(bar: &Bar0) -> u64 {
     regs::NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE::read(bar).usable_fb_size()
 }
 
+pub(super) fn libos_params_tu102() -> &'static LibosParams {
+    &nvfw::LIBOS2_PARAMS
+}
+
 struct Tu102;
 
 impl FbHal for Tu102 {
@@ -52,6 +59,10 @@ fn supports_display(&self, bar: &Bar0) -> bool {
     fn vidmem_size(&self, bar: &Bar0) -> u64 {
         vidmem_size_gp102(bar)
     }
+
+    fn libos_params(&self) -> &'static LibosParams {
+        libos_params_tu102()
+    }
 }
 
 const TU102: Tu102 = Tu102;
drivers/gpu/nova-core/firmware/gsp.rs +1 -1
index a377c5138294c9cc70714cd18eed54d679aba835..61e664db38ad4f73d4a344ea3eeb944c486e24f4 100644
@@ -129,7 +129,7 @@ pub(crate) struct GspFirmware {
     /// Device-mapped GSP signatures matching the GPU's [`Chipset`].
     signatures: DmaObject,
     /// GSP bootloader, verifies the GSP firmware before loading and running it.
-    bootloader: RiscvFirmware,
+    pub bootloader: RiscvFirmware,
 }
 
 impl GspFirmware {
drivers/gpu/nova-core/firmware/riscv.rs +1 -1
index b7eef29956995c49ab1466bb6a71a756731bf78a..b90acfc81e7898ed1726430001d31ebbc976f9f1 100644
@@ -61,7 +61,7 @@ pub(crate) struct RiscvFirmware {
     /// Application version.
     app_version: u32,
     /// Device-mapped firmware image.
-    ucode: DmaObject,
+    pub ucode: DmaObject,
 }
 
 impl RiscvFirmware {
drivers/gpu/nova-core/gpu.rs +2 -2
index b7798257e463a2a0e29e33a1e1076380de077bee..7bb0dc80d6e08c3c1b95ea13c5fbbee63153252e 100644
@@ -289,12 +289,12 @@ pub(crate) fn start_gsp(&self, pdev: &pci::Device<device::Bound>) -> Result<()>
 
         let bios = Vbios::new(dev, bar)?;
 
-        let _gsp_fw = KBox::pin_init(
+        let gsp_fw = KBox::pin_init(
             GspFirmware::new(dev, self.spec.chipset, FIRMWARE_VERSION)?,
             GFP_KERNEL,
         )?;
 
-        let fb_layout = FbLayout::new(self.spec.chipset, bar)?;
+        let fb_layout = FbLayout::new(self.spec.chipset, bar, &gsp_fw)?;
         dev_dbg!(dev, "{:#x?}\n", fb_layout);
 
         self.run_fwsec_frts(dev, bar, &bios, &fb_layout)?;
drivers/gpu/nova-core/gsp.rs +3 -0
index a0e7ec5f6c9c959d57540b3ebf4b782f2e002b08..ead471746ccad02f1e0d6ec114ab2aa67b1ed733 100644
@@ -1,4 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0
 
+use kernel::ptr::Alignment;
+
 pub(crate) const GSP_PAGE_SHIFT: usize = 12;
 pub(crate) const GSP_PAGE_SIZE: usize = 1 << GSP_PAGE_SHIFT;
+pub(crate) const GSP_HEAP_ALIGNMENT: Alignment = Alignment::new(1 << 20);
drivers/gpu/nova-core/nvfw.rs +86 -0

89 lines not on this page · raw message

drivers/gpu/nova-core/nvfw/r570_144.rs +0 -1
index 2e7bba80fa8b9c5fcb4e26887825d2cca3f7b6b7..bb8074797b550c7976a7432b41841c6bf61bf5f8 100644
@@ -12,7 +12,6 @@
 #![cfg_attr(test, allow(unsafe_op_in_unsafe_fn))]
 #![allow(
     dead_code,
-    unused_imports,
     clippy::all,
     clippy::undocumented_unsafe_blocks,
     clippy::ptr_as_ptr,
drivers/gpu/nova-core/nvfw/r570_144_bindings.rs +125 -0

126 lines not on this page · raw message

Signature · 1 line
2.51.0