Skip to contentSkip to conversation

gpu: nova-core: complete conversion to kernel `num` module

PATCH In review Alexandre Courbot 5 participants 13 messages Aug 28 – Aug 31

Subsystems (5)
lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

cover gpu: nova-core: complete conversion to kernel `num` module

This is extracted from the now-defunct const_as series [1] and does the groundwork required to eventually convert nova-core to use the cv! macro [2].

Patch 1 does the minimum necessary to convert nova-core to the kernel's num module and removes its local copy. Patch 2 broadens the use of FromSafeCast to avoid having to refer the casts module at every conversion. After it, the only references left to casts are the conversions done in const context, that will eventually be replaced by the cv! macro.

This series is based on master and should be mergeable after -rc1 has been tagged.

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

---
Alexandre Courbot (2):
gpu: nova-core: use kernel lossless integer conversion module
gpu: nova-core: use FromSafeCast wherever possible

 drivers/gpu/nova-core/falcon.rs                    |  12 +-
 drivers/gpu/nova-core/falcon/fsp.rs                |   4 +-
 drivers/gpu/nova-core/fb.rs                        |   2 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   6 +-
 drivers/gpu/nova-core/firmware.rs                  |   4 +-
 drivers/gpu/nova-core/firmware/booter.rs           |   4 +-
 drivers/gpu/nova-core/firmware/fwsec.rs            |   2 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   4 +-
 drivers/gpu/nova-core/firmware/gsp.rs              |   9 +-
 drivers/gpu/nova-core/firmware/tlv.rs              |  11 +-
 drivers/gpu/nova-core/fsp.rs                       |   8 +-
 drivers/gpu/nova-core/gsp.rs                       |   4 +-
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  25 +--
 drivers/gpu/nova-core/gsp/fw.rs                    |  42 ++--
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   4 +-
 drivers/gpu/nova-core/gsp/sequencer.rs             |   2 +-
 drivers/gpu/nova-core/mctp.rs                      |   8 +-
 drivers/gpu/nova-core/num.rs                       | 211 ---------------------
 drivers/gpu/nova-core/vbios.rs                     |   2 +-
 19 files changed, 81 insertions(+), 283 deletions(-)

---
base-commit: 1b78070aaef63512688aebfbc82365ef9d6660f1
change-id: 20260828-nova_num-64e1b2e84f77

Best regards,

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

PATCH 1/2 gpu: nova-core: use kernel lossless integer conversion module

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

---
 drivers/gpu/nova-core/falcon.rs                    |  12 +-
 drivers/gpu/nova-core/falcon/fsp.rs                |   4 +-
 drivers/gpu/nova-core/fb.rs                        |   2 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   6 +-
 drivers/gpu/nova-core/firmware.rs                  |   4 +-
 drivers/gpu/nova-core/firmware/booter.rs           |   4 +-
 drivers/gpu/nova-core/firmware/fwsec.rs            |   2 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   4 +-
 drivers/gpu/nova-core/firmware/gsp.rs              |   9 +-
 drivers/gpu/nova-core/firmware/tlv.rs              |  11 +-
 drivers/gpu/nova-core/fsp.rs                       |   8 +-
 drivers/gpu/nova-core/gsp.rs                       |   4 +-
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  22 +--
 drivers/gpu/nova-core/gsp/fw.rs                    |  42 ++--
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   4 +-
 drivers/gpu/nova-core/gsp/sequencer.rs             |   2 +-
 drivers/gpu/nova-core/mctp.rs                      |   8 +-
 drivers/gpu/nova-core/num.rs                       | 211 ---------------------
 drivers/gpu/nova-core/vbios.rs                     |   2 +-
 19 files changed, 78 insertions(+), 283 deletions(-)
drivers/gpu/nova-core/falcon.rs +6 -6
index 65cb12d26e2b..dfe4d2e6f82e 100644
@@ -20,6 +20,10 @@
         },
         Io,
     },
+    num::casts::{
+        self,
+        FromSafeCast, //
+    },
     prelude::*,
     time::Delta,
 };
@@ -29,11 +33,7 @@
     driver::Bar0,
     falcon::hal::LoadMethod,
     gpu::Chipset,
-    num::{
-        self,
-        FromSafeCast, //
-    },
-    regs,
+    regs, //
 };
 
 pub(crate) mod fsp;
@@ -510,7 +510,7 @@ fn dma_wr(
         target_mem: FalconMem,
         load_offsets: FalconDmaLoadTarget,
     ) -> Result {
-        const DMA_LEN: u32 = num::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();
+        const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();
 
         // DMA transfers can only be done in units of 256 bytes. Compute how many such transfers we
         // need to perform.
drivers/gpu/nova-core/falcon/fsp.rs +2 -2
index 0437180b8829..2470ac511c98 100644
@@ -16,6 +16,7 @@
         },
         Io, //
     },
+    num::casts,
     prelude::*,
     sizes::SZ_1K,
     time::Delta,
@@ -28,7 +29,6 @@
         PFalcon2Base,
         PFalconBase, //
     },
-    num,
     regs, //
 };
 
@@ -165,7 +165,7 @@ pub(crate) fn recv_msg(&mut self) -> Result<KVec<u8>> {
             Delta::from_millis(10),
             Delta::from_millis(FSP_MSG_TIMEOUT_MS),
         )
-        .map(num::u32_as_usize)?;
+        .map(casts::u32_as_usize)?;
 
         // Don't blindly allocate more than the maximum we expect from FSP.
         if msg_size > FSP_EMEM_CHANNEL_0_SIZE {
drivers/gpu/nova-core/fb.rs +1 -1
index 1576399389b1..8d5d9480378f 100644
@@ -10,6 +10,7 @@
     dma::CoherentHandle,
     fmt,
     io::Io,
+    num::casts::FromSafeCast,
     prelude::*,
     ptr::{
         Alignable,
@@ -23,7 +24,6 @@
     firmware::gsp::GspFirmware,
     gpu::Chipset,
     gsp,
-    num::FromSafeCast,
     vgpu::VgpuState, //
 };
 
drivers/gpu/nova-core/fb/hal/gb100.rs +4 -2
index d9e4d62ae632..a53d8b435dc2 100644
@@ -11,7 +11,10 @@
         },
         Io, //
     },
-    num::Bounded,
+    num::{
+        casts::usize_into_u32,
+        Bounded, //
+    },
     prelude::*,
     ptr::{
         const_align_up,
@@ -26,7 +29,6 @@
         hal::FbHal,
         regs, //
     },
-    num::usize_into_u32,
 };
 
 struct Gb100;
drivers/gpu/nova-core/firmware.rs +2 -2
index b49613a90bf0..19f13779bb30 100644
@@ -9,6 +9,7 @@
 
 use kernel::{
     firmware,
+    num::casts::IntoSafeCast,
     prelude::*, //
 };
 
@@ -18,8 +19,7 @@
         FalconFirmware, //
     },
     gpu,
-    gsp::boot_firmware_files,
-    num::IntoSafeCast, //
+    gsp::boot_firmware_files, //
 };
 
 pub(crate) mod booter;
drivers/gpu/nova-core/firmware/booter.rs +2 -2
index dc071edba331..aa830455b7e7 100644
@@ -10,6 +10,7 @@
 use kernel::{
     device,
     dma::Coherent,
+    num::casts::IntoSafeCast,
     prelude::*, //
 };
 
@@ -32,8 +33,7 @@
         Signed,
         Unsigned, //
     },
-    gpu::Chipset,
-    num::IntoSafeCast,
+    gpu::Chipset, //
 };
 
 /// Signature for Booter firmware. Their size is encoded into the header and not known a compile
drivers/gpu/nova-core/firmware/fwsec.rs +1 -1
index 7a931f22f629..7f7ca3ba2298 100644
@@ -19,6 +19,7 @@
         self,
         Device, //
     },
+    num::casts::FromSafeCast,
     prelude::*,
     transmute::{
         AsBytes,
@@ -42,7 +43,6 @@
         Signed,
         Unsigned, //
     },
-    num::FromSafeCast,
     vbios::Vbios,
 };
 
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +2 -2
index ec4d92317a93..d1fb7d2d7480 100644
@@ -13,6 +13,7 @@
     },
     dma::Coherent,
     io::{register::WithBase, Io},
+    num::casts::FromSafeCast,
     prelude::*,
     ptr::{
         Alignable,
@@ -45,8 +46,7 @@
         },
     },
     gpu::Chipset,
-    num::FromSafeCast, //
-    regs,
+    regs, //
 };
 
 /// Structure used by the boot-loader to load the rest of the code.
drivers/gpu/nova-core/firmware/gsp.rs +6 -3
index e8f9491e84cc..e75ce6fe47d8 100644
@@ -9,6 +9,10 @@
         DmaAddress, //
     },
     firmware,
+    num::casts::{
+        arch::FromSafeCastArch,
+        FromSafeCast, //
+    },
     prelude::*,
     scatterlist::{
         Owned,
@@ -26,8 +30,7 @@
         },
     },
     gpu::Chipset,
-    gsp::GSP_PAGE_SIZE,
-    num::FromSafeCast,
+    gsp::GSP_PAGE_SIZE, //
 };
 
 /// GSP firmware with 3-level radix page tables for the GSP bootloader.
@@ -154,7 +157,7 @@ pub(crate) fn radix3_dma_address(&self) -> DmaAddress {
 fn map_into_lvl(sg_table: &SGTable<Owned<VVec<u8>>>, mut dst: VVec<u8>) -> Result<VVec<u8>> {
     for sg_entry in sg_table.iter() {
         // Number of pages we need to map.
-        let num_pages = usize::from_safe_cast(sg_entry.dma_len()).div_ceil(GSP_PAGE_SIZE);
+        let num_pages = usize::from_safe_cast_arch(sg_entry.dma_len()).div_ceil(GSP_PAGE_SIZE);
 
         for i in 0..num_pages {
             let entry = sg_entry.dma_address()
drivers/gpu/nova-core/firmware/tlv.rs +6 -5
index 7b879f13a61e..6653c10e3e0a 100644
@@ -4,14 +4,15 @@
 use kernel::{
     device,
     firmware,
+    num::casts::{
+        self,
+        IntoSafeCast, //
+    },
     prelude::*,
     str::CString, //
 };
 
-use crate::{
-    gpu,
-    num::*, //
-};
+use crate::gpu;
 
 /// Requests the GPU firmware TLV `name` suitable for `chipset`.
 pub(crate) fn request_tlv(
@@ -51,7 +52,7 @@ fn parse(hdr: &[u8]) -> Option<Self> {
             return None;
         }
         let len_arr = <[u8; 4]>::try_from(hdr.get(4..Self::SIZE)?).ok()?;
-        let length = u32_as_usize(u32::from_le_bytes(len_arr));
+        let length = casts::u32_as_usize(u32::from_le_bytes(len_arr));
         Some(Self { tag, length })
     }
 }
drivers/gpu/nova-core/fsp.rs +5 -3
index ab685fb4168f..b9ca298dc97f 100644
@@ -11,7 +11,10 @@
     device,
     dma::Coherent,
     io::poll::read_poll_timeout,
-    num::TryIntoBounded,
+    num::{
+        casts,
+        TryIntoBounded, //
+    },
     prelude::*,
     ptr::{
         Alignable,
@@ -47,7 +50,6 @@
         NvdmHeader,
         NvdmType, //
     },
-    num,
     regs, //
 };
 
@@ -285,7 +287,7 @@ fn new<'a>(
         };
 
         let version = hal.cot_version();
-        let size = num::usize_into_u16::<{ core::mem::size_of::<NvdmPayloadCot>() }>();
+        let size = casts::usize_into_u16::<{ core::mem::size_of::<NvdmPayloadCot>() }>();
 
         Ok(init!(Self {
             header: FspMessageHeader::new(NvdmType::Cot),
drivers/gpu/nova-core/gsp.rs +2 -2
index 13f361406a6c..fc8648de84c2 100644
@@ -17,6 +17,7 @@
         io_write,
         Io, //
     },
+    num::casts,
     pci,
     prelude::*, //
 };
@@ -48,7 +49,6 @@
         cmdq::Cmdq,
         fw::GspArgumentsPadded, //
     },
-    num,
     vgpu::VgpuManager, //
 };
 
@@ -92,7 +92,7 @@ fn init(view: CoherentView<'_, Self>, start: DmaAddress) -> Result<()> {
         for i in 0..NUM_PAGES {
             io_write!(view, .0[build: i],
                 start
-                    .checked_add(num::usize_as_u64(i) << GSP_PAGE_SHIFT)
+                    .checked_add(casts::usize_as_u64(i) << GSP_PAGE_SHIFT)
                     .ok_or(EOVERFLOW)?
             );
         }
drivers/gpu/nova-core/gsp/cmdq.rs +11 -11
index 6da728201281..f85fde09aa6e 100644
@@ -23,6 +23,7 @@
         Io, //
     },
     new_mutex,
+    num::casts,
     prelude::*,
     ptr,
     sync::{
@@ -57,7 +58,6 @@
         GSP_PAGE_SHIFT,
         GSP_PAGE_SIZE, //
     },
-    num,
     sbuffer::SBufferIter, //
 };
 
@@ -162,7 +162,7 @@ fn read(
 #[repr(C, align(0x1000))]
 #[derive(Debug)]
 struct MsgqData {
-    data: [[u8; GSP_PAGE_SIZE]; num::u32_as_usize(MSGQ_NUM_PAGES)],
+    data: [[u8; GSP_PAGE_SIZE]; casts::u32_as_usize(MSGQ_NUM_PAGES)],
 }
 
 // Annoyingly we are forced to use a literal to specify the alignment of
@@ -235,8 +235,8 @@ unsafe impl FromBytes for GspMem {}
 impl DmaGspMem {
     /// Allocate a new instance and map it for `dev`.
     fn new(dev: &device::Device<device::Bound>) -> Result<Self> {
-        const MSGQ_SIZE: u32 = num::usize_into_u32::<{ size_of::<Msgq>() }>();
-        const RX_HDR_OFF: u32 = num::usize_into_u32::<{ mem::offset_of!(Msgq, rx) }>();
+        const MSGQ_SIZE: u32 = casts::usize_into_u32::<{ size_of::<Msgq>() }>();
+        const RX_HDR_OFF: u32 = casts::usize_into_u32::<{ mem::offset_of!(Msgq, rx) }>();
 
         let mut gsp_mem = CoherentBox::<GspMem>::zeroed(dev, GFP_KERNEL)?;
         gsp_mem.cpuq.tx = MsgqTxHeader::new(MSGQ_SIZE, RX_HDR_OFF, MSGQ_NUM_PAGES);
@@ -289,10 +289,10 @@ fn new(dev: &device::Device<device::Bound>) -> Result<Self> {
         unsafe {
             (
                 core::slice::from_raw_parts_mut(
-                    data.add(num::u32_as_usize(tx)),
-                    num::u32_as_usize(tail_end - tx),
+                    data.add(casts::u32_as_usize(tx)),
+                    casts::u32_as_usize(tail_end - tx),
                 ),
-                core::slice::from_raw_parts_mut(data, num::u32_as_usize(wrap_end)),
+                core::slice::from_raw_parts_mut(data, casts::u32_as_usize(wrap_end)),
             )
         }
     }
@@ -307,7 +307,7 @@ fn driver_write_area_size(&self) -> usize {
         // `cpu_write_ptr`. The minimum value case is where `rx == 0` and `tx == MSGQ_NUM_PAGES -
         // 1`, which gives `0 + MSGQ_NUM_PAGES - (MSGQ_NUM_PAGES - 1) - 1 == 0`.
         let slots = (rx + MSGQ_NUM_PAGES - tx - 1) % MSGQ_NUM_PAGES;
-        num::u32_as_usize(slots) * GSP_PAGE_SIZE
+        casts::u32_as_usize(slots) * GSP_PAGE_SIZE
     }
 
     /// Returns the region of the GSP message queue that the driver is currently allowed to read
@@ -343,10 +343,10 @@ fn driver_write_area_size(&self) -> usize {
         unsafe {
             (
                 core::slice::from_raw_parts(
-                    data.add(num::u32_as_usize(rx)),
-                    num::u32_as_usize(tail_end - rx),
+                    data.add(casts::u32_as_usize(rx)),
+                    casts::u32_as_usize(tail_end - rx),
                 ),
-                core::slice::from_raw_parts(data, num::u32_as_usize(wrap_end)),
+                core::slice::from_raw_parts(data, casts::u32_as_usize(wrap_end)),
             )
         }
     }
drivers/gpu/nova-core/gsp/fw.rs +21 -21

107 lines not on this page · raw message

drivers/gpu/nova-core/gsp/fw/commands.rs +2 -2
index 6dc31d1bf5ae..201594fa437b 100644
@@ -5,6 +5,7 @@
 
 use kernel::{
     device,
+    num::casts::IntoSafeCast,
     pci,
     prelude::*,
     transmute::{
@@ -15,8 +16,7 @@
 
 use crate::{
     gpu::Chipset,
-    gsp::GSP_PAGE_SIZE,
-    num::IntoSafeCast, //
+    gsp::GSP_PAGE_SIZE, //
 };
 
 use super::bindings;
drivers/gpu/nova-core/gsp/sequencer.rs +1 -1
index bcad1421953a..fed881ba80b0 100644
@@ -11,6 +11,7 @@
         poll::read_poll_timeout,
         Io, //
     },
+    num::casts::FromSafeCast,
     prelude::*,
     time::{
         delay::fsleep,
@@ -35,7 +36,6 @@
         GspBootContext,
         LibosMemoryRegionInitArgument, //
     },
-    num::FromSafeCast,
     sbuffer::SBufferIter,
 };
 
drivers/gpu/nova-core/mctp.rs +3 -5
index 90c642c91a72..67f64ac2b8d1 100644
@@ -9,14 +9,12 @@
 
 use kernel::{
     bitfield,
+    num::casts,
     pci::Vendor,
     prelude::*, //
 };
 
-use crate::{
-    bounded_enum,
-    num, //
-};
+use crate::bounded_enum;
 
 bounded_enum! {
     /// NVDM message type identifiers carried over MCTP.
@@ -76,7 +74,7 @@ impl NvdmHeader {
     /// Builds an NVDM header for the given message type.
     pub(crate) fn new(nvdm_type: NvdmType) -> Self {
         Self::zeroed()
-            .with_const_msg_type::<{ num::u8_as_u32(MSG_TYPE_VENDOR_PCI) }>()
+            .with_const_msg_type::<{ casts::u8_as_u32(MSG_TYPE_VENDOR_PCI) }>()
             .with_vendor_id(Vendor::NVIDIA.as_raw())
             .with_nvdm_type(nvdm_type)
     }
drivers/gpu/nova-core/num.rs +0 -211

217 lines not on this page · raw message

drivers/gpu/nova-core/vbios.rs +1 -1
index c03650ee5226..7a2ee29cbb91 100644
@@ -5,6 +5,7 @@
 use kernel::{
     device,
     io::Io,
+    num::casts::FromSafeCast,
     prelude::*,
     ptr::{
         Alignable,
@@ -23,7 +24,6 @@
         FalconUCodeDescV2,
         FalconUCodeDescV3, //
     },
-    num::FromSafeCast,
 };
 
 /// BIOS Image Type from PCI Data Structure code_type field.
Signature · 1 line
2.55.0
#2 lore raw

Re: [PATCH 1/2] gpu: nova-core: use kernel lossless integer conversion module

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] A TOCTOU double-fetch vulnerability in GSP message parsing allows compromised or malicious GSP firmware to corrupt the CPU's message queue read pointer, causing desynchronization and potential denial of service. --

commit eaaa0723c196a2c00643733ca548b4c1354725ff
Author: Alexandre Courbot <[email protected]>

gpu: nova-core: use kernel lossless integer conversion module

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

Quoted 4 lines
drivers/gpu/nova-core/gsp/cmdq.rs +0 -0
index 6da728201281b..f85fde09aa6e3 100644

[ ... ]

drivers/gpu/nova-core/gsp/cmdq.rs fn read( · line 166

Quoted 7 lines
drivers/gpu/nova-core/gsp/cmdq.rs +1 -1
@@ -162,7 +162,7 @@ fn read(
 #[repr(C, align(0x1000))]
 #[derive(Debug)]
 struct MsgqData {
-    data: [[u8; GSP_PAGE_SIZE]; num::u32_as_usize(MSGQ_NUM_PAGES)],
+    data: [[u8; GSP_PAGE_SIZE]; casts::u32_as_usize(MSGQ_NUM_PAGES)],
 }

[Severity: High]
This isn't a bug introduced by this patch, but while reviewing cmdq.rs, I noticed a pre-existing double-fetch issue that could allow a compromised GSP firmware to desynchronize the message queue.

Could the GSP modify the message length in DMA memory after it has been validated, causing the host to corrupt its CPU read pointer?

In CmdqInner::wait_for_msg(), the message length is fetched from DMA memory and validated against the available buffer size to ensure it is safe:

CmdqInner::wait_for_msg() {
    ...
    let payload_length = header.payload_length();

    // Check that the driver read area is large enough for the message.
    if slice_1.len() + slice_2.len() < payload_length {
        return Err(EIO);
    }
    ...
}

However, upon returning to CmdqInner::receive_msg(), the length is fetched a second time directly from the shared memory when advancing the queue read pointer:

CmdqInner::receive_msg() {
    ...
    let message = self.wait_for_msg(timeout)?;
    ...
    // Advance the read pointer past this message.
    self.gsp_mem.advance_cpu_read_ptr(u32::try_from(
        message.header.length().div_ceil(GSP_PAGE_SIZE),
    )?);
    ...
}

Because message.header is a reference into DMA memory, this second fetch uses an unvalidated value. If the GSP modifies the length field in DMA memory between these two reads, the kernel will advance its read pointer by an unvalidated amount. This could cause the kernel to misinterpret queue memory, fail subsequent validations, and lose communication with the GSP.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
maintainer
#3 lore raw

Re: [PATCH 1/2] gpu: nova-core: use kernel lossless integer conversion module

In reply to Alexandre Courbot

(Cc: Miguel)

Quoted 19 lines · Alexandre Courbot

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

---
 drivers/gpu/nova-core/falcon.rs                    |  12 +-
 drivers/gpu/nova-core/falcon/fsp.rs                |   4 +-
 drivers/gpu/nova-core/fb.rs                        |   2 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   6 +-
 drivers/gpu/nova-core/firmware.rs                  |   4 +-
 drivers/gpu/nova-core/firmware/booter.rs           |   4 +-
 drivers/gpu/nova-core/firmware/fwsec.rs            |   2 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   4 +-
 drivers/gpu/nova-core/firmware/gsp.rs              |   9 +-
 drivers/gpu/nova-core/firmware/tlv.rs              |  11 +-
 drivers/gpu/nova-core/fsp.rs                       |   8 +-
 drivers/gpu/nova-core/gsp.rs                       |   4 +-
Quoted 8 lines
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  22 +--
 drivers/gpu/nova-core/gsp/fw.rs                    |  42 ++--
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   4 +-
 drivers/gpu/nova-core/gsp/sequencer.rs             |   2 +-
 drivers/gpu/nova-core/mctp.rs                      |   8 +-
 drivers/gpu/nova-core/num.rs                       | 211 ---------------------
 drivers/gpu/nova-core/vbios.rs                     |   2 +-
 19 files changed, 78 insertions(+), 283 deletions(-)

Please see the discussion in [1].

If we make this change, then the subsequent conversion to const_as!() would need to go through the Rust tree next cycle, which could be a bit of a mess, as I'd expect a bunch of conflicts.

Alternatively, we could the the full three cycle dance, or have a signed tag for const_as!() and use it right away.

But honestly, the former would just be unnecessary noise. If we don't do the latter, let's just keep the nova-core num module until the dust has been settled.

[1] https://lore.kernel.org/all/CANiq72k+-fNWZCwGuQ=FTchxgm-X-f6WR=tG=Ercn19ic1edQg@mail.gmail.com/

#4 lore raw

Re: [PATCH 1/2] gpu: nova-core: use kernel lossless integer conversion module

Quoted 4 lines · Danilo Krummrich

But honestly, the former would just be unnecessary noise. If we don't do the latter, let's just keep the nova-core num module until the dust has been settled.

Yeah, keeping the nova num for a bit sounds fine.

Cheers,
Miguel

author maintainer
#5 lore raw

Re: [PATCH 1/2] gpu: nova-core: use kernel lossless integer conversion module

In reply to Danilo Krummrich
Quoted 37 lines · Danilo Krummrich

(Cc: Miguel)

Quoted 19 lines · Alexandre Courbot

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

---
 drivers/gpu/nova-core/falcon.rs                    |  12 +-
 drivers/gpu/nova-core/falcon/fsp.rs                |   4 +-
 drivers/gpu/nova-core/fb.rs                        |   2 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   6 +-
 drivers/gpu/nova-core/firmware.rs                  |   4 +-
 drivers/gpu/nova-core/firmware/booter.rs           |   4 +-
 drivers/gpu/nova-core/firmware/fwsec.rs            |   2 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   4 +-
 drivers/gpu/nova-core/firmware/gsp.rs              |   9 +-
 drivers/gpu/nova-core/firmware/tlv.rs              |  11 +-
 drivers/gpu/nova-core/fsp.rs                       |   8 +-
 drivers/gpu/nova-core/gsp.rs                       |   4 +-
Quoted 8 lines
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  22 +--
 drivers/gpu/nova-core/gsp/fw.rs                    |  42 ++--
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   4 +-
 drivers/gpu/nova-core/gsp/sequencer.rs             |   2 +-
 drivers/gpu/nova-core/mctp.rs                      |   8 +-
 drivers/gpu/nova-core/num.rs                       | 211 ---------------------
 drivers/gpu/nova-core/vbios.rs                     |   2 +-
 19 files changed, 78 insertions(+), 283 deletions(-)

Please see the discussion in [1].

If we make this change, then the subsequent conversion to const_as!() would need to go through the Rust tree next cycle, which could be a bit of a mess, as I'd expect a bunch of conflicts.

Quoted 8 lines

Alternatively, we could the the full three cycle dance, or have a signed tag for const_as!() and use it right away.

But honestly, the former would just be unnecessary noise. If we don't do the latter, let's just keep the nova-core num module until the dust has been settled.

[1] https://lore.kernel.org/all/CANiq72k+-fNWZCwGuQ=FTchxgm-X-f6WR=tG=Ercn19ic1edQg@mail.gmail.com/

Maybe I am missing something, but wouldn't the following work?

- rc1 gets tagged, drm-rust-next gets the num::casts module,
- This series gets applied to drm-rust-next, then cv! (without the nova-core conversion patch) in rust-next,
- We wait one cycle for cv! to trickle down to drm-rust-next before converting nova-core to use cv!.

Would that work? This series doesn't overlap with the const conversions that cv! covers on purpose, and it would have the benefit of getting rid of the local num module in nova-core quickly.

maintainer
#6 lore raw

Re: [PATCH 1/2] gpu: nova-core: use kernel lossless integer conversion module

Quoted 55 lines · Alexandre Courbot
Quoted 37 lines · Danilo Krummrich

(Cc: Miguel)

Quoted 19 lines · Alexandre Courbot

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

---
 drivers/gpu/nova-core/falcon.rs                    |  12 +-
 drivers/gpu/nova-core/falcon/fsp.rs                |   4 +-
 drivers/gpu/nova-core/fb.rs                        |   2 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   6 +-
 drivers/gpu/nova-core/firmware.rs                  |   4 +-
 drivers/gpu/nova-core/firmware/booter.rs           |   4 +-
 drivers/gpu/nova-core/firmware/fwsec.rs            |   2 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   4 +-
 drivers/gpu/nova-core/firmware/gsp.rs              |   9 +-
 drivers/gpu/nova-core/firmware/tlv.rs              |  11 +-
 drivers/gpu/nova-core/fsp.rs                       |   8 +-
 drivers/gpu/nova-core/gsp.rs                       |   4 +-
Quoted 8 lines
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  22 +--
 drivers/gpu/nova-core/gsp/fw.rs                    |  42 ++--
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   4 +-
 drivers/gpu/nova-core/gsp/sequencer.rs             |   2 +-
 drivers/gpu/nova-core/mctp.rs                      |   8 +-
 drivers/gpu/nova-core/num.rs                       | 211 ---------------------
 drivers/gpu/nova-core/vbios.rs                     |   2 +-
 19 files changed, 78 insertions(+), 283 deletions(-)

Please see the discussion in [1].

If we make this change, then the subsequent conversion to const_as!() would need to go through the Rust tree next cycle, which could be a bit of a mess, as I'd expect a bunch of conflicts.

Quoted 8 lines

Alternatively, we could the the full three cycle dance, or have a signed tag for const_as!() and use it right away.

But honestly, the former would just be unnecessary noise. If we don't do the latter, let's just keep the nova-core num module until the dust has been settled.

[1] https://lore.kernel.org/all/CANiq72k+-fNWZCwGuQ=FTchxgm-X-f6WR=tG=Ercn19ic1edQg@mail.gmail.com/

Maybe I am missing something, but wouldn't the following work?

- rc1 gets tagged, drm-rust-next gets the num::casts module,
- This series gets applied to drm-rust-next, then cv! (without the nova-core conversion patch) in rust-next,
- We wait one cycle for cv! to trickle down to drm-rust-next before converting nova-core to use cv!.

Quoted 3 lines

Would that work? This series doesn't overlap with the const conversions that cv! covers on purpose, and it would have the benefit of getting rid of the local num module in nova-core quickly.

Take casts::usize_into_u32() for instance, drm-rust-next replaces the usage of it next cycle, but rust-next wants to remove the API from rust/kernel/num/casts.rs.

In this case rust-next would need to get rid of the users (including nova-core), but drm-rust-next will likely do different changes, so we'd get unnecessary merge conflicts.

You can resolve this either by keeping casts::usize_into_u32 and friends around for one additional cycle, so that all users we introduce now are gone. Or, since there's no rush anyways, we just wait one cycle and use the real thing right away.

author maintainer
#7 lore raw

Re: [PATCH 1/2] gpu: nova-core: use kernel lossless integer conversion module

Quoted 64 lines · Danilo Krummrich
Quoted 55 lines · Alexandre Courbot
Quoted 37 lines · Danilo Krummrich

(Cc: Miguel)

Quoted 19 lines · Alexandre Courbot

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

---
 drivers/gpu/nova-core/falcon.rs                    |  12 +-
 drivers/gpu/nova-core/falcon/fsp.rs                |   4 +-
 drivers/gpu/nova-core/fb.rs                        |   2 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   6 +-
 drivers/gpu/nova-core/firmware.rs                  |   4 +-
 drivers/gpu/nova-core/firmware/booter.rs           |   4 +-
 drivers/gpu/nova-core/firmware/fwsec.rs            |   2 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   4 +-
 drivers/gpu/nova-core/firmware/gsp.rs              |   9 +-
 drivers/gpu/nova-core/firmware/tlv.rs              |  11 +-
 drivers/gpu/nova-core/fsp.rs                       |   8 +-
 drivers/gpu/nova-core/gsp.rs                       |   4 +-
Quoted 8 lines
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  22 +--
 drivers/gpu/nova-core/gsp/fw.rs                    |  42 ++--
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   4 +-
 drivers/gpu/nova-core/gsp/sequencer.rs             |   2 +-
 drivers/gpu/nova-core/mctp.rs                      |   8 +-
 drivers/gpu/nova-core/num.rs                       | 211 ---------------------
 drivers/gpu/nova-core/vbios.rs                     |   2 +-
 19 files changed, 78 insertions(+), 283 deletions(-)

Please see the discussion in [1].

If we make this change, then the subsequent conversion to const_as!() would need to go through the Rust tree next cycle, which could be a bit of a mess, as I'd expect a bunch of conflicts.

Quoted 8 lines

Alternatively, we could the the full three cycle dance, or have a signed tag for const_as!() and use it right away.

But honestly, the former would just be unnecessary noise. If we don't do the latter, let's just keep the nova-core num module until the dust has been settled.

[1] https://lore.kernel.org/all/CANiq72k+-fNWZCwGuQ=FTchxgm-X-f6WR=tG=Ercn19ic1edQg@mail.gmail.com/

Maybe I am missing something, but wouldn't the following work?

- rc1 gets tagged, drm-rust-next gets the num::casts module,
- This series gets applied to drm-rust-next, then cv! (without the nova-core conversion patch) in rust-next,
- We wait one cycle for cv! to trickle down to drm-rust-next before converting nova-core to use cv!.

Quoted 3 lines

Would that work? This series doesn't overlap with the const conversions that cv! covers on purpose, and it would have the benefit of getting rid of the local num module in nova-core quickly.

Take casts::usize_into_u32() for instance, drm-rust-next replaces the usage of it next cycle, but rust-next wants to remove the API from rust/kernel/num/casts.rs.

Quoted 8 lines

In this case rust-next would need to get rid of the users (including nova-core), but drm-rust-next will likely do different changes, so we'd get unnecessary merge conflicts.

You can resolve this either by keeping casts::usize_into_u32 and friends around for one additional cycle, so that all users we introduce now are gone. Or, since there's no rush anyways, we just wait one cycle and use the real thing right away.

Sorry, I should have explicitly mentioned that *_into_* would remain alongside cv! for the next cycle.

The reason why I think it's preferable to use casts in nova-core sooner is that some of the series currently under review (and that will likely be merged next cycle) add more uses of the local num methods, making the eentual conversion more painful. If we move to use casts early we can at least avoid the churn on those cases that do not use cv!.

maintainer
#8 lore raw

Re: [PATCH 1/2] gpu: nova-core: use kernel lossless integer conversion module

Quoted 69 lines · Alexandre Courbot
Quoted 68 lines · Danilo Krummrich
Quoted 55 lines · Alexandre Courbot
Quoted 37 lines · Danilo Krummrich

(Cc: Miguel)

Quoted 19 lines · Alexandre Courbot

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

---
 drivers/gpu/nova-core/falcon.rs                    |  12 +-
 drivers/gpu/nova-core/falcon/fsp.rs                |   4 +-
 drivers/gpu/nova-core/fb.rs                        |   2 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   6 +-
 drivers/gpu/nova-core/firmware.rs                  |   4 +-
 drivers/gpu/nova-core/firmware/booter.rs           |   4 +-
 drivers/gpu/nova-core/firmware/fwsec.rs            |   2 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   4 +-
 drivers/gpu/nova-core/firmware/gsp.rs              |   9 +-
 drivers/gpu/nova-core/firmware/tlv.rs              |  11 +-
 drivers/gpu/nova-core/fsp.rs                       |   8 +-
 drivers/gpu/nova-core/gsp.rs                       |   4 +-
Quoted 8 lines
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  22 +--
 drivers/gpu/nova-core/gsp/fw.rs                    |  42 ++--
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   4 +-
 drivers/gpu/nova-core/gsp/sequencer.rs             |   2 +-
 drivers/gpu/nova-core/mctp.rs                      |   8 +-
 drivers/gpu/nova-core/num.rs                       | 211 ---------------------
 drivers/gpu/nova-core/vbios.rs                     |   2 +-
 19 files changed, 78 insertions(+), 283 deletions(-)

Please see the discussion in [1].

If we make this change, then the subsequent conversion to const_as!() would need to go through the Rust tree next cycle, which could be a bit of a mess, as I'd expect a bunch of conflicts.

Quoted 8 lines

Alternatively, we could the the full three cycle dance, or have a signed tag for const_as!() and use it right away.

But honestly, the former would just be unnecessary noise. If we don't do the latter, let's just keep the nova-core num module until the dust has been settled.

[1] https://lore.kernel.org/all/CANiq72k+-fNWZCwGuQ=FTchxgm-X-f6WR=tG=Ercn19ic1edQg@mail.gmail.com/

Maybe I am missing something, but wouldn't the following work?

- rc1 gets tagged, drm-rust-next gets the num::casts module,
- This series gets applied to drm-rust-next, then cv! (without the nova-core conversion patch) in rust-next,
- We wait one cycle for cv! to trickle down to drm-rust-next before converting nova-core to use cv!.

Quoted 3 lines

Would that work? This series doesn't overlap with the const conversions that cv! covers on purpose, and it would have the benefit of getting rid of the local num module in nova-core quickly.

Take casts::usize_into_u32() for instance, drm-rust-next replaces the usage of it next cycle, but rust-next wants to remove the API from rust/kernel/num/casts.rs.

In this case rust-next would need to get rid of the users (including nova-core), but drm-rust-next will likely do different changes, so we'd get unnecessary merge conflicts.

Quoted 7 lines
Quoted 4 lines

You can resolve this either by keeping casts::usize_into_u32 and friends around for one additional cycle, so that all users we introduce now are gone. Or, since there's no rush anyways, we just wait one cycle and use the real thing right away.

Sorry, I should have explicitly mentioned that *_into_* would remain alongside cv! for the next cycle.

Maybe we have a different understanding of what "next cycle" means. As of today we are in the v7.4 cycle, so I call this the current cycle.

In the next cycle, as discussed in [1], rust-next will drop casts::*_into_*(), and so would drm-rust-next, if we start using casts::*_into_*() in nova-core this cycle.

I don't want this situation, so we can either keep casts::*_into_*() around for even longer, or just never start using it.

Quoted 6 lines

The reason why I think it's preferable to use casts in nova-core sooner is that some of the series currently under review (and that will likely be merged next cycle) add more uses of the local num methods, making the eentual conversion more painful. If we move to use casts early we can at least avoid the churn on those cases that do not use cv!.

It would come at the price of adding cross tree dependencies and converting the cv! parts twice, which is much worse than one clean and independent conversion.

author maintainer
#9 lore raw

Re: [PATCH 1/2] gpu: nova-core: use kernel lossless integer conversion module

Quoted 95 lines · Danilo Krummrich
Quoted 69 lines · Alexandre Courbot
Quoted 68 lines · Danilo Krummrich
Quoted 55 lines · Alexandre Courbot
Quoted 37 lines · Danilo Krummrich

(Cc: Miguel)

Quoted 19 lines · Alexandre Courbot

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

---
 drivers/gpu/nova-core/falcon.rs                    |  12 +-
 drivers/gpu/nova-core/falcon/fsp.rs                |   4 +-
 drivers/gpu/nova-core/fb.rs                        |   2 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   6 +-
 drivers/gpu/nova-core/firmware.rs                  |   4 +-
 drivers/gpu/nova-core/firmware/booter.rs           |   4 +-
 drivers/gpu/nova-core/firmware/fwsec.rs            |   2 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   4 +-
 drivers/gpu/nova-core/firmware/gsp.rs              |   9 +-
 drivers/gpu/nova-core/firmware/tlv.rs              |  11 +-
 drivers/gpu/nova-core/fsp.rs                       |   8 +-
 drivers/gpu/nova-core/gsp.rs                       |   4 +-
Quoted 8 lines
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  22 +--
 drivers/gpu/nova-core/gsp/fw.rs                    |  42 ++--
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   4 +-
 drivers/gpu/nova-core/gsp/sequencer.rs             |   2 +-
 drivers/gpu/nova-core/mctp.rs                      |   8 +-
 drivers/gpu/nova-core/num.rs                       | 211 ---------------------
 drivers/gpu/nova-core/vbios.rs                     |   2 +-
 19 files changed, 78 insertions(+), 283 deletions(-)

Please see the discussion in [1].

If we make this change, then the subsequent conversion to const_as!() would need to go through the Rust tree next cycle, which could be a bit of a mess, as I'd expect a bunch of conflicts.

Quoted 8 lines

Alternatively, we could the the full three cycle dance, or have a signed tag for const_as!() and use it right away.

But honestly, the former would just be unnecessary noise. If we don't do the latter, let's just keep the nova-core num module until the dust has been settled.

[1] https://lore.kernel.org/all/CANiq72k+-fNWZCwGuQ=FTchxgm-X-f6WR=tG=Ercn19ic1edQg@mail.gmail.com/

Maybe I am missing something, but wouldn't the following work?

- rc1 gets tagged, drm-rust-next gets the num::casts module,
- This series gets applied to drm-rust-next, then cv! (without the nova-core conversion patch) in rust-next,
- We wait one cycle for cv! to trickle down to drm-rust-next before converting nova-core to use cv!.

Quoted 3 lines

Would that work? This series doesn't overlap with the const conversions that cv! covers on purpose, and it would have the benefit of getting rid of the local num module in nova-core quickly.

Take casts::usize_into_u32() for instance, drm-rust-next replaces the usage of it next cycle, but rust-next wants to remove the API from rust/kernel/num/casts.rs.

In this case rust-next would need to get rid of the users (including nova-core), but drm-rust-next will likely do different changes, so we'd get unnecessary merge conflicts.

Quoted 7 lines
Quoted 4 lines

You can resolve this either by keeping casts::usize_into_u32 and friends around for one additional cycle, so that all users we introduce now are gone. Or, since there's no rush anyways, we just wait one cycle and use the real thing right away.

Sorry, I should have explicitly mentioned that *_into_* would remain alongside cv! for the next cycle.

Maybe we have a different understanding of what "next cycle" means. As of today we are in the v7.4 cycle, so I call this the current cycle.

In the next cycle, as discussed in [1], rust-next will drop casts::*_into_*(), and so would drm-rust-next, if we start using casts::*_into_*() in nova-core this cycle.

I don't want this situation, so we can either keep casts::*_into_*() around for even longer, or just never start using it.

Quoted 6 lines

The reason why I think it's preferable to use casts in nova-core sooner is that some of the series currently under review (and that will likely be merged next cycle) add more uses of the local num methods, making the eentual conversion more painful. If we move to use casts early we can at least avoid the churn on those cases that do not use cv!.

Quoted 2 lines

It would come at the price of adding cross tree dependencies and converting the cv! parts twice, which is much worse than one clean and independent conversion.

Got it - let's keep nova-core's num for one more cycle then. This will make for a larger conversion, but the silver lining is that this means less rebasing for the patches currently in-flight.

I'll revisit this series for 7.5 (?), although I guess patch 2 is still relevant as long as it keeps using nova-core's num crate.

author maintainer
#10 lore raw

PATCH 2/2 gpu: nova-core: use FromSafeCast wherever possible

In reply to Alexandre Courbot

FromSafeCast should be preferred to the *_as_* family of functions when it can be used (i.e. in non-const contexts), as it requires a single import to perform all valid conversions.

After this patch, the only remaining references to the casts module are those done in const context, which means the casts import can be removed once these are converted to use the cv! macro.

---
 drivers/gpu/nova-core/falcon/fsp.rs   |  4 ++--
 drivers/gpu/nova-core/firmware/tlv.rs |  4 ++--
 drivers/gpu/nova-core/gsp.rs          |  4 ++--
 drivers/gpu/nova-core/gsp/cmdq.rs     | 19 +++++++++++--------
 drivers/gpu/nova-core/gsp/fw.rs       |  8 ++++----
 5 files changed, 21 insertions(+), 18 deletions(-)
drivers/gpu/nova-core/falcon/fsp.rs +2 -2
index 2470ac511c98..ece95b1ea8cb 100644
@@ -16,7 +16,7 @@
         },
         Io, //
     },
-    num::casts,
+    num::casts::FromSafeCast,
     prelude::*,
     sizes::SZ_1K,
     time::Delta,
@@ -165,7 +165,7 @@ pub(crate) fn recv_msg(&mut self) -> Result<KVec<u8>> {
             Delta::from_millis(10),
             Delta::from_millis(FSP_MSG_TIMEOUT_MS),
         )
-        .map(casts::u32_as_usize)?;
+        .map(usize::from_safe_cast)?;
 
         // Don't blindly allocate more than the maximum we expect from FSP.
         if msg_size > FSP_EMEM_CHANNEL_0_SIZE {
drivers/gpu/nova-core/firmware/tlv.rs +2 -2
index 6653c10e3e0a..7dff8871e338 100644
@@ -5,7 +5,7 @@
     device,
     firmware,
     num::casts::{
-        self,
+        FromSafeCast,
         IntoSafeCast, //
     },
     prelude::*,
@@ -52,7 +52,7 @@ fn parse(hdr: &[u8]) -> Option<Self> {
             return None;
         }
         let len_arr = <[u8; 4]>::try_from(hdr.get(4..Self::SIZE)?).ok()?;
-        let length = casts::u32_as_usize(u32::from_le_bytes(len_arr));
+        let length = usize::from_safe_cast(u32::from_le_bytes(len_arr));
         Some(Self { tag, length })
     }
 }
drivers/gpu/nova-core/gsp.rs +2 -2
index fc8648de84c2..0f5275dcb41c 100644
@@ -17,7 +17,7 @@
         io_write,
         Io, //
     },
-    num::casts,
+    num::casts::FromSafeCast,
     pci,
     prelude::*, //
 };
@@ -92,7 +92,7 @@ fn init(view: CoherentView<'_, Self>, start: DmaAddress) -> Result<()> {
         for i in 0..NUM_PAGES {
             io_write!(view, .0[build: i],
                 start
-                    .checked_add(casts::usize_as_u64(i) << GSP_PAGE_SHIFT)
+                    .checked_add(u64::from_safe_cast(i) << GSP_PAGE_SHIFT)
                     .ok_or(EOVERFLOW)?
             );
         }
drivers/gpu/nova-core/gsp/cmdq.rs +11 -8
index f85fde09aa6e..658d0a9b2cfb 100644
@@ -23,7 +23,10 @@
         Io, //
     },
     new_mutex,
-    num::casts,
+    num::casts::{
+        self,
+        FromSafeCast, //
+    },
     prelude::*,
     ptr,
     sync::{
@@ -289,10 +292,10 @@ fn new(dev: &device::Device<device::Bound>) -> Result<Self> {
         unsafe {
             (
                 core::slice::from_raw_parts_mut(
-                    data.add(casts::u32_as_usize(tx)),
-                    casts::u32_as_usize(tail_end - tx),
+                    data.add(usize::from_safe_cast(tx)),
+                    usize::from_safe_cast(tail_end - tx),
                 ),
-                core::slice::from_raw_parts_mut(data, casts::u32_as_usize(wrap_end)),
+                core::slice::from_raw_parts_mut(data, usize::from_safe_cast(wrap_end)),
             )
         }
     }
@@ -307,7 +310,7 @@ fn driver_write_area_size(&self) -> usize {
         // `cpu_write_ptr`. The minimum value case is where `rx == 0` and `tx == MSGQ_NUM_PAGES -
         // 1`, which gives `0 + MSGQ_NUM_PAGES - (MSGQ_NUM_PAGES - 1) - 1 == 0`.
         let slots = (rx + MSGQ_NUM_PAGES - tx - 1) % MSGQ_NUM_PAGES;
-        casts::u32_as_usize(slots) * GSP_PAGE_SIZE
+        usize::from_safe_cast(slots) * GSP_PAGE_SIZE
     }
 
     /// Returns the region of the GSP message queue that the driver is currently allowed to read
@@ -343,10 +346,10 @@ fn driver_write_area_size(&self) -> usize {
         unsafe {
             (
                 core::slice::from_raw_parts(
-                    data.add(casts::u32_as_usize(rx)),
-                    casts::u32_as_usize(tail_end - rx),
+                    data.add(usize::from_safe_cast(rx)),
+                    usize::from_safe_cast(tail_end - rx),
                 ),
-                core::slice::from_raw_parts(data, casts::u32_as_usize(wrap_end)),
+                core::slice::from_raw_parts(data, usize::from_safe_cast(wrap_end)),
             )
         }
     }
drivers/gpu/nova-core/gsp/fw.rs +4 -4
index 88f083ff1f13..61064b6a251b 100644
@@ -681,7 +681,7 @@ fn id8(name: &str) -> u64 {
         let init_inner = init!(bindings::LibosMemoryRegionInitArgument {
             id8: id8(name),
             pa: obj.dma_address(),
-            size: casts::usize_as_u64(obj.size()),
+            size: u64::from_safe_cast(obj.size()),
             kind: casts::u32_into_u8::<
                 { bindings::LibosMemoryRegionKind_LIBOS_MEMORY_REGION_CONTIGUOUS },
             >(),
@@ -851,7 +851,7 @@ pub(crate) fn set_checksum(&mut self, checksum: u32) {
     /// Returns the length of the message's payload.
     pub(crate) fn payload_length(&self) -> usize {
         // `rpc.length` includes the length of the RPC message header.
-        casts::u32_as_usize(self.inner.rpc.length)
+        usize::from_safe_cast(self.inner.rpc.length)
             .saturating_sub(size_of::<bindings::rpc_message_header_v>())
     }
 
@@ -948,8 +948,8 @@ fn new(cmdq: &Cmdq) -> impl Init<Self> + '_ {
         init!(MessageQueueInitArguments {
             sharedMemPhysAddr: cmdq.dma_addr,
             pageTableEntryCount: casts::usize_into_u32::<{ Cmdq::NUM_PTES }>(),
-            cmdQueueOffset: casts::usize_as_u64(Cmdq::CMDQ_OFFSET),
-            statQueueOffset: casts::usize_as_u64(Cmdq::STATQ_OFFSET),
+            cmdQueueOffset: u64::from_safe_cast(Cmdq::CMDQ_OFFSET),
+            statQueueOffset: u64::from_safe_cast(Cmdq::STATQ_OFFSET),
             ..Zeroable::init_zeroed()
         })
     }
Signature · 1 line
2.55.0
Reviewed-by on v1 2/2
#11 lore raw

Re: [PATCH 2/2] gpu: nova-core: use FromSafeCast wherever possible

Quoted 10 lines · Alexandre Courbot

FromSafeCast should be preferred to the *_as_* family of functions when it can be used (i.e. in non-const contexts), as it requires a single import to perform all valid conversions.

After this patch, the only remaining references to the casts module are those done in const context, which means the casts import can be removed once these are converted to use the cv! macro.

---

#12 lore raw

Re: [PATCH 2/2] gpu: nova-core: use FromSafeCast wherever possible

In reply to Alexandre Courbot
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Pre-existing issues:
- [High] Missing DMA write memory barrier before updating the GSP command queue write pointer.
- [High] Missing DMA read memory barrier after reading the GSP message queue write pointer. --

commit 899e3ba6af7f4cc7e2c28b0f4f3f73db18de1f16
Author: Alexandre Courbot <[email protected]>

gpu: nova-core: use FromSafeCast wherever possible

Replaces various *_as_* casting functions with FromSafeCast in non-const contexts to simplify conversions.

Quoted 4 lines
drivers/gpu/nova-core/gsp/cmdq.rs +0 -0
index f85fde09aa6e3..658d0a9b2cfb2 100644

[ ... ]

Quoted 4 lines
drivers/gpu/nova-core/gsp/cmdq.rs +0 -0
@@ -343,10 +346,10 @@ fn driver_write_area_size(&self) -> usize {
         unsafe {
             (
                 core::slice::from_raw_parts(

drivers/gpu/nova-core/gsp/cmdq.rs fn driver_write_area_size(&self) -> usize { · line 355

Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3 -3
-                    data.add(casts::u32_as_usize(rx)),
-                    casts::u32_as_usize(tail_end - rx),
+                    data.add(usize::from_safe_cast(rx)),
+                    usize::from_safe_cast(tail_end - rx),
                 ),
-                core::slice::from_raw_parts(data, casts::u32_as_usize(wrap_end)),
+                core::slice::from_raw_parts(data, usize::from_safe_cast(wrap_end)),
             )
         }
     }

[Severity: High]
This isn't a bug introduced by this patch, but while reviewing this file I noticed a potential memory barrier issue in advance_cpu_write_ptr():

Quoted 8 lines
    fn advance_cpu_write_ptr(&mut self, elem_count: u32) {
        let tx = io_project!(self.0, .cpuq.tx);
        let wptr = MsgqTxHeader::write_ptr(tx).wrapping_add(elem_count) % MSGQ_NUM_PAGES;
        MsgqTxHeader::set_write_ptr(tx, wptr);

        // Ensure all command data is visible before triggering the GSP read.
        fence(Ordering::SeqCst);
    }

Because there is no memory barrier between the payload writes (done prior to calling this function) and the write pointer volatile write in MsgqTxHeader::set_write_ptr(), the CPU can reorder them.

If the GSP observes the updated write pointer before the payload writes are globally visible, could it read stale command data?

[Severity: High]
This is also a pre-existing issue, but is there a missing read memory barrier after reading the message queue write pointer in wait_for_msg()?

Quoted 4 lines
    fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
        // Wait for a message to arrive from the GSP.
        let (slice_1, slice_2) = read_poll_timeout(
            || Ok(self.gsp_mem.driver_read_area()),
Quoted 8 lines
            |driver_area| !driver_area.0.is_empty(),
            Delta::from_millis(1),
            timeout,
        )
        .map(|(slice_1, slice_2)| (slice_1.as_flattened(), slice_2.as_flattened()))?;

        // Extract the `GspMsgElement`.
        let (header, slice_1) = GspMsgElement::from_bytes_prefix(slice_1).ok_or(EIO)?;

When polling for a new message, read_poll_timeout repeatedly evaluates driver_read_area(), which performs a volatile read of the GSP write pointer.

Once a new message is indicated, the payload memory slices are immediately accessed.

Since there is no read memory barrier between the volatile read of the write pointer and the payload access, could modern CPUs speculatively execute the data loads before the write pointer read completes, causing the driver to read stale payload data?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2