Skip to contentSkip to conversation

gpu: nova-core: add NVKV codec

PATCH Applied Eliot Courtney 2 participants 10 messages Oct 28 – Nov 3

Subsystems (6)
lore
Share & tools
lore
#0 lore raw

v5 cover gpu: nova-core: add NVKV codec

This series adds support for the NVKV wire format for communicating with GSP.

Essentially, the format encodes a sequence of calls to some function f(key, index, value), where value is a [u8], u32, u64, [u32], or a [u64]. The key is a u16 and the index is a 12 bit integer. The interpretation of these function calls is per GMCAPI (RPC interface used in firmwares later than r570). Generally speaking, the function calls will map to some struct - for example, f(GPU_NAME_STRING_KEY, 0, b"some gpu") naturally maps to storing a &str with the GPU name.

This series adds a general encoder and decoder that works with the base formats used ([u8], u32, u64, [u32], or a [u64]) for encode and a general Schema trait for decode. This could be used directly, but since most messages are struct-like, it's more ergonomic to use some typed helpers for this declarative use case. So this series adds two simple macros for encode and decode of structs, plus some general types and implementations that help with using these.

Future patches will wire this up through the command queue.

This is based on drm-rust-next.

---
Changes in v5:
- Drop the Zeroable derive from ArrayVec (Alex)
- Add ArrayVec::init_empty and use it in Array (Alex)
- Implement ArrayVec::push with push_init (Alex)
- Make each Encoder method leave the stream unchanged on failure (Alex)
- Replace EncodedStream with a KVVec<u64> which simplifies the encoder a bit. It adds a memset to 0 - now that we have zerocopy in the future we could add a extend_from_bytes method to KVVec if we want to get rid of this.
- Use constants in the Key and Optional stack asserts (Alex)
- Make TruncatingArray wrap Array and share the visit code (Alex)
- Link to v4: https://patch.msgid.link/[email protected]

Changes in v4:
- Rebase onto drm-rust-next.
- Fold Vec::push_init into the Vec::try_push_init patch (Alex)
- Rename PushInitError to TryPushInitError and replace FullError with kvec::PushError (Alex)
- Add #[inline] to small Vec and ArrayVec methods (Sashiko)
- Drop #[inline] and #[repr(transparent)] (Alex)
- Move IndexedKey to nvkv.rs and make it crate-visible (Alex)
- Make Required work on schemas and add Optional (Alex)
- Add stack asserts for decoded Key and Optional values (Alex)
- Drop the GSP_INIT tests, use literal key ids (Alex)
- Doc, test and type cleanups (Alex)
- Fix expect dead_code for CONFIG_KUNIT=m build
- Drop the clippy exception from the ArrayVec::new() stack assert
It turns out this isn't just clippy, but also -Os.
- Implement ArrayVec::init_with with Init::chain (simpler)
- Allow a lifetime on nvkv_encode! structs, like on nvkv_decode! structs
- Add a stack assert for encoded Key values
- Support the As type of Key in decoding and use it for FbRegionFlags
- Add TruncatingArray and truncate a long GPU name as OpenRM does, instead of failing to decode
- Drop unneeded bounds on Array and Schema::init, make HostArch private
- Link to v3: https://patch.msgid.link/[email protected]

Changes in v3:
- Rebase + drop zerocopy prereqs which are in now.
- Define Opcode with bounded_enum! (Alex)
- Use #[inline] instead of #[inline(always)] (Alex)
- Add Co-developed-by for Danilo on the encoder patch (EncodedStream)
- Split Schema into Schema (init/finish) and Visit<'data> (visit) to let schemas borrow from the encoded stream
- Support schemas that borrow from the stream in nvkv_decode!, e.g. struct NameSchema<'d> => Name<'d>
- Construct schemas only in place with a required Schema::init() and drop the Default impls + stack size asserts (Alex)
- Doc improvements (Alex)
- Add a TODO for the O(#fields) visit dispatch in nvkv_decode! (Alex)
- Replace the Key<Option<T>> special case with TryFrom<DecoderValue> for Option<T>
- Make Key's field and IndexedKey::new private (Alex)
- Move the nvkv_*! re-exports to GSP_INIT patch (Alex)
- Add decoder tests (Alex)
- Add error path tests (Alex)
- Add IndexedKey tests (Alex)
- Add RegKey tests (Alex)
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- Tweak Schema trait to avoid materializing copies on the stack
- Move ArrayVec to alloc module (+add potentially useful methods) (Danilo)
- Add Vec::try_push_init (Danilo)
- Add sum error type for try_push_init, PushInitError
- Use Danilo's EncodedStream abstraction
- Add some stack space asserts (Danilo) - needs to skip on clippy tho
- Using zerocopy e.g. ref_from_prefix_with_elems requires updated zerocopy to avoid linking error, so added those as prereqs.
- Link to v1: https://patch.msgid.link/[email protected]

---
Eliot Courtney (7):
rust: alloc: add Vec::try_push_init and Vec::push_init
rust: alloc: add ArrayVec
gpu: nova-core: add NVKV encoder
gpu: nova-core: add NVKV decoder
gpu: nova-core: add NVKV typed encoding
gpu: nova-core: add NVKV typed decoding
gpu: nova-core: add NVKV GSP_INIT schemas

 drivers/gpu/nova-core/gsp.rs             |    1 +
 drivers/gpu/nova-core/gsp/fw/commands.rs |  157 +++-
 drivers/gpu/nova-core/gsp/nvkv.rs        |  133 ++++
 drivers/gpu/nova-core/gsp/nvkv/decode.rs | 1206 ++++++++++++++++++++++++++++++
 drivers/gpu/nova-core/gsp/nvkv/encode.rs |  465 ++++++++++++
 rust/kernel/alloc.rs                     |    3 +
 rust/kernel/alloc/arrayvec.rs            |  351 +++++++++
 rust/kernel/alloc/kvec.rs                |   86 ++-
 rust/kernel/alloc/kvec/errors.rs         |   32 +-
 9 files changed, 2430 insertions(+), 4 deletions(-)

---
base-commit: 3497a403264b094ebd61b8b755165d56e7d9dc37
change-id: 20260812-b4-nvkv-131af5c2661c

Best regards,

Signature · 1 line
Eliot Courtney <[email protected]>
#1 lore raw

PATCH v5 1/7 rust: alloc: add Vec::try_push_init and Vec::push_init

Add Vec::try_push_init for fallible initializers (impl Init<T, E>) and a new sum error type TryPushInitError<I, E> that it returns. If allocation fails, it hands back the original initializer. A From impl for Error lets callers decay the TryPushInitError<I, E> to a regular Error if they want.

Add Vec::push_init which is the init-infallible version of try_push_init.

---
 rust/kernel/alloc/kvec.rs        | 85 +++++++++++++++++++++++++++++++++++++++-
 rust/kernel/alloc/kvec/errors.rs | 30 ++++++++++++++
 2 files changed, 113 insertions(+), 2 deletions(-)
rust/kernel/alloc/kvec.rs +83 -2
index c7546b9da4fa..c8b312f64657 100644
@@ -52,10 +52,18 @@
     }, //
 };
 
-use pin_init::Zeroable;
+use pin_init::{
+    Init,
+    Zeroable, //
+};
 
 mod errors;
-pub use self::errors::{InsertError, PushError, RemoveError};
+pub use self::errors::{
+    InsertError,
+    PushError,
+    RemoveError,
+    TryPushInitError, //
+};
 
 /// Create a [`KVec`] containing the arguments.
 ///
@@ -359,6 +367,79 @@ pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> {
         Ok(())
     }
 
+    /// Appends an element to the back of the [`Vec`] instance by initializing it in place.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use pin_init::init_zeroed;
+    ///
+    /// let mut v = KVec::<[u8; 200]>::new();
+    /// v.push_init(init_zeroed(), GFP_KERNEL)?;
+    /// assert_eq!(v[0], [0; 200]);
+    /// # Ok::<(), Error>(())
+    /// ```
+    #[inline]
+    pub fn push_init(&mut self, init: impl Init<T>, flags: Flags) -> Result<(), AllocError> {
+        self.try_push_init(init, flags)
+            .map_err(|TryPushInitError::AllocError(_)| AllocError)
+    }
+
+    /// Appends an element to the back of the [`Vec`] instance by initializing it in place.
+    ///
+    /// Unlike [`Vec::push_init`], the initializer may be fallible. If the allocation fails, the
+    /// original initializer `init` is handed back in [`TryPushInitError::AllocError`]. If the
+    /// initializer itself fails, its error is returned in [`TryPushInitError::InitError`].
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// struct Element {
+    ///     value: u8,
+    /// }
+    ///
+    /// impl Element {
+    ///     fn new(value: u32) -> impl Init<Self, Error> {
+    ///         try_init!(Element {
+    ///             value: u8::try_from(value)?,
+    ///         }? Error)
+    ///     }
+    /// }
+    ///
+    /// let mut v: KVec<Element> = KVec::new();
+    /// v.try_push_init(Element::new(16), GFP_KERNEL)?;
+    /// assert_eq!(v[0].value, 16);
+    ///
+    /// // The initializer fails because 256 does not fit in a `u8`.
+    /// assert!(v.try_push_init(Element::new(256), GFP_KERNEL).is_err());
+    /// assert_eq!(v.len(), 1);
+    /// # Ok::<(), Error>(())
+    /// ```
+    pub fn try_push_init<I, E>(
+        &mut self,
+        init: I,
+        flags: Flags,
+    ) -> Result<(), TryPushInitError<I, E>>
+    where
+        I: Init<T, E>,
+    {
+        if self.reserve(1, flags).is_err() {
+            return Err(TryPushInitError::AllocError(init));
+        }
+        // SAFETY: The call to `reserve` was successful, so there is at least one spare slot.
+        let slot = unsafe { self.spare_capacity_mut().get_unchecked_mut(0) }.as_mut_ptr();
+        // SAFETY:
+        // - `slot` points to a spare slot, which is valid, uninitialized memory.
+        // - If `raw_try_init` fails, this returns without increasing the length or touching `slot`.
+        // - `init` implements `Init<T, E>`, which removes the pinning requirement.
+        unsafe { pin_init::raw_try_init(slot, init) }.map_err(TryPushInitError::InitError)?;
+        // SAFETY: The call to `raw_try_init` returned `Ok`, so the first spare slot now holds an
+        // initialized `T`. The new length does not exceed the capacity because `reserve` ensured
+        // the capacity is greater than the length by at least one.
+        unsafe { self.inc_len(1) };
+        Ok(())
+    }
+
     /// Appends an element to the back of the [`Vec`] instance without reallocating.
     ///
     /// Fails if the vector does not have capacity for the new element.
rust/kernel/alloc/kvec/errors.rs +30 -0
index aaca6446516a..d24dfe22834a 100644
@@ -25,6 +25,36 @@ fn from(_: PushError<T>) -> Error {
     }
 }
 
+/// Error type for [`Vec::try_push_init`].
+pub enum TryPushInitError<I, E> {
+    /// The allocation failed. Hand the initializer back.
+    AllocError(I),
+    /// The initializer failed.
+    InitError(E),
+}
+
+impl<I, E> fmt::Debug for TryPushInitError<I, E> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            TryPushInitError::AllocError(_) => write!(f, "Failed to allocate"),
+            TryPushInitError::InitError(_) => write!(f, "Initializer failed"),
+        }
+    }
+}
+
+impl<I, E> From<TryPushInitError<I, E>> for Error
+where
+    Error: From<E>,
+{
+    #[inline]
+    fn from(e: TryPushInitError<I, E>) -> Error {
+        match e {
+            TryPushInitError::AllocError(_) => ENOMEM,
+            TryPushInitError::InitError(e) => Error::from(e),
+        }
+    }
+}
+
 /// Error type for [`Vec::remove`].
 pub struct RemoveError;
 
Signature · 1 line
2.56.0
#2 lore raw

PATCH v5 2/7 rust: alloc: add ArrayVec

In reply to Eliot Courtney

Add a fixed capacity vector backed by [MaybeUninit<T>; N]. The ArrayVec is also initializable with a closure, returning an Init instance, to avoid constructing it on the stack. ArrayVec is useful for small but varying size arrays stored on the stack, to avoid a heap allocation, or, for larger varying size arrays initialized into caller provided memory but not wanting to provide an allocator.

---
 rust/kernel/alloc.rs             |   3 +
 rust/kernel/alloc/arrayvec.rs    | 351 +++++++++++++++++++++++++++++++++++++++
 rust/kernel/alloc/kvec.rs        |   1 +
 rust/kernel/alloc/kvec/errors.rs |   2 +-
 4 files changed, 356 insertions(+), 1 deletion(-)
rust/kernel/alloc.rs +3 -0
index 21067bde6860..510e2c7f9f72 100644
@@ -3,10 +3,13 @@
 //! Implementation of the kernel's memory allocation infrastructure.
 
 pub mod allocator;
+pub mod arrayvec;
 pub mod kbox;
 pub mod kvec;
 pub mod layout;
 
+pub use self::arrayvec::ArrayVec;
+
 pub use self::kbox::Box;
 pub use self::kbox::KBox;
 pub use self::kbox::KVBox;
rust/kernel/alloc/arrayvec.rs new file +351 -0

351 lines not on this page · raw message

rust/kernel/alloc/kvec.rs +1 -0
index c8b312f64657..cd0c57a9ad90 100644
@@ -1255,6 +1255,7 @@ fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
         )*
     }
 }
+pub(super) use impl_slice_eq;
 
 impl_slice_eq! {
     [A1: Allocator, A2: Allocator] Vec<T, A1>, Vec<U, A2>,
rust/kernel/alloc/kvec/errors.rs +1 -1
index d24dfe22834a..f5c44fdc7016 100644
@@ -7,7 +7,7 @@
     prelude::*, //
 };
 
-/// Error type for [`Vec::push_within_capacity`].
+/// Error type for a push that fails because there is no spare capacity.
 pub struct PushError<T>(pub T);
 
 impl<T> fmt::Debug for PushError<T> {
Signature · 1 line
2.56.0
#3 lore raw

PATCH v5 3/7 gpu: nova-core: add NVKV encoder

In reply to Eliot Courtney

Add an encoder for NVKV, which is the wire format for GMCAPI. The encoded stream is a sequence of 64-bit values. The first 64-bit value encodes an op word which describes the function of the next N values.

Essentially, the format encodes a sequence of calls to some function f(key, index, value), where value is a [u8], u32, u64, [u32], or a [u64]. The key is a u16 and the index is a 12 bit integer. The interpretation of these function calls is per GMCAPI.

Add tests for the wire encoding for each primitive.

---
 drivers/gpu/nova-core/gsp.rs             |   1 +
 drivers/gpu/nova-core/gsp/nvkv.rs        |  58 ++++++++++
 drivers/gpu/nova-core/gsp/nvkv/encode.rs | 192 +++++++++++++++++++++++++++++++
 3 files changed, 251 insertions(+)
drivers/gpu/nova-core/gsp.rs +1 -0
index dda58095f40b..a4a6bf7e2df7 100644
@@ -24,6 +24,7 @@
 pub(crate) mod cmdq;
 pub(crate) mod commands;
 mod fw;
+mod nvkv;
 mod regs;
 mod sequencer;
 
drivers/gpu/nova-core/gsp/nvkv.rs new file +58 -0

58 lines not on this page · raw message

drivers/gpu/nova-core/gsp/nvkv/encode.rs new file +192 -0

192 lines not on this page · raw message

Signature · 1 line
2.56.0
#4 lore raw

PATCH v5 4/7 gpu: nova-core: add NVKV decoder

In reply to Eliot Courtney

Add a decoder for NVKV. This is for receiving messages from GSP for GMCAPI calls. The NVKV format essentially encodes a sequence of function calls f(key, index, value). This decoder reads an encoded stream and invokes a type implementing the new Schema and Visit trait. The Visit trait can either consume the value or not, which is useful for composing schemas. If a (key, index, value) is not consumed, error out depending on UnknownKeyPolicy. Whether ignoring unknown keys is ok or not is per each GMCAPI call.

Add kunit tests for the decoder.

---
 drivers/gpu/nova-core/gsp/nvkv.rs        |   3 +
 drivers/gpu/nova-core/gsp/nvkv/decode.rs | 503 +++++++++++++++++++++++++++++++
 2 files changed, 506 insertions(+)
drivers/gpu/nova-core/gsp/nvkv.rs +3 -0
index f1e63e6c4927..98c5c31c3717 100644
@@ -21,6 +21,9 @@
 mod encode;
 pub(crate) use encode::*;
 
+mod decode;
+pub(crate) use decode::*;
+
 /// The identifier of an NVKV key.
 pub(crate) type KeyId = u16;
 
drivers/gpu/nova-core/gsp/nvkv/decode.rs new file +503 -0

503 lines not on this page · raw message

Signature · 1 line
2.56.0
#5 lore raw

PATCH v5 5/7 gpu: nova-core: add NVKV typed encoding

In reply to Eliot Courtney

For struct-like GMCAPI messages encoding field by field manually is noisy. Add some type machinery and a macro to automate encoding of struct-like messages. The Encodable trait can be implemented by any type to say that it can be encoded into an NVKV Encoder. Add a simple nvkv_encode! macro that works on structs and encodes each field in order. Provide some base types, such as Key which statically associates an NVKV key with some value, to avoid having to make a lot of newtypes and implement Encodable on them.

---
 drivers/gpu/nova-core/gsp/nvkv.rs        |  68 ++++++++
 drivers/gpu/nova-core/gsp/nvkv/encode.rs | 273 +++++++++++++++++++++++++++++++
 2 files changed, 341 insertions(+)
drivers/gpu/nova-core/gsp/nvkv.rs +68 -0
index 98c5c31c3717..9d89e09e02f5 100644
@@ -11,6 +11,14 @@
 
 #![expect(unused_imports)]
 
+use core::{
+    marker::PhantomData,
+    ops::{
+        Deref,
+        DerefMut, //
+    }, //
+};
+
 use kernel::{
     bitfield,
     num::Bounded, //
@@ -30,6 +38,66 @@
 /// The index of an NVKV value.
 pub(crate) type Index = Bounded<u64, 12>;
 
+/// A static association between an NVKV key `KEY_ID` and the storage of its value.
+///
+/// Use with the encoder or decoder macros `nvkv_encode!` and `nvkv_decode!` to let them know how to
+/// map the value `Key<T, KEY_ID, As>` to/from encoded data. For brevity, `As` inserts an additional
+/// conversion ([`From`]) to avoid having to implement [`Encodable`] for many types. For example,
+/// enums that are easily convertible to a u32 can have `As = u32` and rely on the existing encoding
+/// for u32.
+pub(crate) struct Key<T, const KEY_ID: KeyId, As = T>(T, PhantomData<As>);
+
+impl<T, const KEY_ID: KeyId, As> Key<T, KEY_ID, As> {
+    /// The maximum size in bytes we allow to materialize on the stack while
+    /// encoding or decoding a [`Key`]. This is checked at compile time.
+    const MAX_STACK_SIZE: usize = 32;
+}
+
+impl<T, const KEY_ID: KeyId, As> From<T> for Key<T, KEY_ID, As> {
+    fn from(value: T) -> Self {
+        Self(value, PhantomData)
+    }
+}
+
+impl<'a, T, const KEY_ID: KeyId, As, const N: usize> From<&'a [T; N]> for Key<&'a [T], KEY_ID, As> {
+    fn from(value: &'a [T; N]) -> Self {
+        Self(&value[..], PhantomData)
+    }
+}
+
+impl<T, const KEY_ID: KeyId, As> Deref for Key<T, KEY_ID, As> {
+    type Target = T;
+
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
+
+impl<T, const KEY_ID: KeyId, As> DerefMut for Key<T, KEY_ID, As> {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.0
+    }
+}
+
+impl<T: Default, const KEY_ID: KeyId, As> Default for Key<T, KEY_ID, As> {
+    fn default() -> Self {
+        Self(T::default(), PhantomData)
+    }
+}
+
+/// A value with a specific index that encodes under the NVKV key `KEY_ID`.
+pub(crate) struct IndexedKey<T, const KEY_ID: KeyId> {
+    index: Index,
+    value: T,
+}
+
+impl<T, const KEY_ID: KeyId> IndexedKey<T, KEY_ID> {
+    /// Creates a key with the given index and value.
+    pub(crate) fn new(index: Index, value: T) -> Self {
+        Self { index, value }
+    }
+}
+
 bitfield! {
     /// The op word that starts each NVKV operation.
     struct Op(u64) {
drivers/gpu/nova-core/gsp/nvkv/encode.rs +273 -0

288 lines not on this page · raw message

Signature · 1 line
2.56.0
#6 lore raw

PATCH v5 6/7 gpu: nova-core: add NVKV typed decoding

In reply to Eliot Courtney

Similar to the typed encoding layer, add some decoding type machinery. Add a simple macro nvkv_decode! which implements Schema for a struct by composing visit calls to each member. Add some common Schema kinds, such as Array which collects an array value into a fixed maximum size array, and Required which fails a decode if the value is not sent.

---
 drivers/gpu/nova-core/gsp/nvkv.rs        |   8 +-
 drivers/gpu/nova-core/gsp/nvkv/decode.rs | 706 ++++++++++++++++++++++++++++++-
 2 files changed, 712 insertions(+), 2 deletions(-)
drivers/gpu/nova-core/gsp/nvkv.rs +7 -1
index 9d89e09e02f5..143746daf782 100644
@@ -9,7 +9,7 @@
 //! speaking, the function calls will map to some struct - for example, f(GPU_NAME_STRING_KEY, 0,
 //! b"some gpu") naturally maps to storing a &str with the GPU name.
 
-#![expect(unused_imports)]
+#![cfg_attr(not(CONFIG_KUNIT = "y"), expect(unused_imports))]
 
 use core::{
     marker::PhantomData,
@@ -20,6 +20,7 @@
 };
 
 use kernel::{
+    alloc::ArrayVec,
     bitfield,
     num::Bounded, //
 };
@@ -98,6 +99,11 @@ pub(crate) fn new(index: Index, value: T) -> Self {
     }
 }
 
+/// A schema field for an array value under the NVKV key `KEY_ID`.
+pub(crate) struct Array<T, const N: usize, const KEY_ID: KeyId> {
+    vec: ArrayVec<T, N>,
+}
+
 bitfield! {
     /// The op word that starts each NVKV operation.
     struct Op(u64) {
drivers/gpu/nova-core/gsp/nvkv/decode.rs +705 -1

732 lines not on this page · raw message

Signature · 1 line
2.56.0
#7 lore raw

PATCH v5 7/7 gpu: nova-core: add NVKV GSP_INIT schemas

In reply to Eliot Courtney

Add the first user of NVKV encode/decode which is the request and response for GSP init. Later patches will support GMCAPI in Cmdq and use these messages.

---
 drivers/gpu/nova-core/gsp/fw/commands.rs | 157 ++++++++++++++++++++++++++++++-
 drivers/gpu/nova-core/gsp/nvkv.rs        |   2 -
 drivers/gpu/nova-core/gsp/nvkv/decode.rs |   1 -
 drivers/gpu/nova-core/gsp/nvkv/encode.rs |   2 +-
 4 files changed, 157 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/gsp/fw/commands.rs +156 -1
index 567c56fbbfe3..88111aec3ddb 100644
@@ -4,6 +4,8 @@
 use core::ops::Range;
 
 use kernel::{
+    alloc::ArrayVec,
+    bitfield,
     device,
     pci,
     prelude::*,
@@ -15,7 +17,19 @@
 
 use crate::{
     gpu::Chipset,
-    gsp::GSP_PAGE_SIZE,
+    gsp::{
+        nvkv::{
+            nvkv_decode,
+            nvkv_encode,
+            Accumulated,
+            Encodable,
+            Encoder,
+            Key,
+            Required,
+            TruncatingArray, //
+        },
+        GSP_PAGE_SIZE, //
+    },
     num::IntoSafeCast, //
 };
 
@@ -245,3 +259,144 @@ unsafe impl AsBytes for UnloadingGuestDriver {}
 // SAFETY: This struct only contains integer types for which all bit patterns
 // are valid.
 unsafe impl FromBytes for UnloadingGuestDriver {}
+
+/// The host CPU architecture.
+#[derive(Clone, Copy)]
+enum HostArch {
+    None = 0,
+    X86_64 = 1,
+    Ppc64le = 2,
+    Arm = 3,
+    Aarch64 = 4,
+    Riscv64 = 5,
+}
+
+// TODO[FPRI]: This is a temporary solution to be replaced with the corresponding derive macros once
+// they land.
+impl TryFrom<u32> for HostArch {
+    type Error = Error;
+
+    fn try_from(value: u32) -> Result<Self> {
+        match value {
+            0 => Ok(Self::None),
+            1 => Ok(Self::X86_64),
+            2 => Ok(Self::Ppc64le),
+            3 => Ok(Self::Arm),
+            4 => Ok(Self::Aarch64),
+            5 => Ok(Self::Riscv64),
+            _ => Err(EINVAL),
+        }
+    }
+}
+
+impl From<HostArch> for u32 {
+    fn from(value: HostArch) -> Self {
+        value as u32
+    }
+}
+
+nvkv_encode! {
+    /// A GSP registry entry.
+    struct RegKey {
+        key_name: Key<&'static [u8], 0x3070>,
+        key_value: Key<u32, 0x3071>,
+    }
+}
+
+impl Encodable for KVVec<RegKey> {
+    fn encode(&self, encoder: &mut Encoder) -> Result {
+        for regkey in self {
+            regkey.encode(encoder)?;
+        }
+        Ok(())
+    }
+}
+
+nvkv_encode! {
+    /// SR-IOV virtual function information.
+    struct VfInfo {
+        total_vfs: Key<u32, 0x0080>,
+        first_vf_offset: Key<u32, 0x0081>,
+        flags: Key<u64, 0x1003>,
+        first_bar0_address: Key<u64, 0x1050>,
+        first_bar1_address: Key<u64, 0x1051>,
+        first_bar2_address: Key<u64, 0x1052>,
+    }
+}
+
+nvkv_encode! {
+    /// Payload of the `GSP_INIT` command.
+    // TODO: expect() doesn't work here before rustc 1.97.0
+    // https://github.com/rust-lang/rust/pull/154377
+    #[allow(dead_code)]
+    struct GspInitRequest {
+        pci_device_id: Key<u32, 0x0001>,
+        pci_sub_device_id: Key<u32, 0x0002>,
+        pci_revision_id: Key<u32, 0x0003>,
+        pci_config_mirror_base: Key<u32, 0x0010>,
+        pci_config_mirror_size: Key<u32, 0x0011>,
+        host_arch: Key<HostArch, 0x0070, u32>,
+        bus_device_func: Key<u64, 0x1020>,
+        regkeys: KVVec<RegKey>,
+        vf_info: Option<VfInfo>,
+    }
+}
+
+// Decode:
+
+// Should decode with UnknownKeyPolicy::Ignore.
+nvkv_decode! {
+    /// Schema for the `GSP_INIT` response.
+    // TODO: expect() doesn't work here before rustc 1.97.0
+    // https://github.com/rust-lang/rust/pull/154377
+    #[allow(dead_code)]
+    struct GspInitResponseSchema => GspInitResponse {
+        gpu_name: TruncatingArray<u8, { GspInitResponse::MAX_GPU_NAME_LEN }, 0x2000>,
+        fb_regions: Accumulated<FbRegionSchema>,
+        bar1_pde_base: Required<Key<u64, 0x1020>>,
+        vmmu_segment_size: Key<u64, 0x1050>,
+    }
+}
+
+/// Payload of the `GSP_INIT` response.
+// TODO: expect() doesn't work here before rustc 1.97.0
+// https://github.com/rust-lang/rust/pull/154377
+#[allow(dead_code)]
+struct GspInitResponse {
+    gpu_name: ArrayVec<u8, { Self::MAX_GPU_NAME_LEN }>,
+    fb_regions: KVVec<FbRegion>,
+    bar1_pde_base: u64,
+    vmmu_segment_size: u64,
+}
+
+impl GspInitResponse {
+    const MAX_GPU_NAME_LEN: usize = 64;
+}
+
+nvkv_decode! {
+    /// Schema for one FB region of the `GSP_INIT` response.
+    struct FbRegionSchema => FbRegion {
+        base: Required<Key<u64, 0x1011>>,
+        limit: Required<Key<u64, 0x1012>>,
+        flags: Required<Key<FbRegionFlags, 0x0012, u32>>,
+        tag: Required<Key<u32, 0x0013>>,
+    }
+}
+
+bitfield! {
+    /// FB region attribute flags.
+    #[derive(Default)]
+    struct FbRegionFlags(u32) {
+        0:0 support_compressed => bool;
+        1:1 support_iso => bool;
+        2:2 protected => bool;
+    }
+}
+
+/// One FB memory region.
+struct FbRegion {
+    base: u64,
+    limit: u64,
+    flags: FbRegionFlags,
+    tag: u32,
+}
drivers/gpu/nova-core/gsp/nvkv.rs +0 -2
index 143746daf782..f81a9e60d89c 100644
@@ -9,8 +9,6 @@
 //! speaking, the function calls will map to some struct - for example, f(GPU_NAME_STRING_KEY, 0,
 //! b"some gpu") naturally maps to storing a &str with the GPU name.
 
-#![cfg_attr(not(CONFIG_KUNIT = "y"), expect(unused_imports))]
-
 use core::{
     marker::PhantomData,
     ops::{
drivers/gpu/nova-core/gsp/nvkv/decode.rs +0 -1
index 534056b97708..84c0c998b2c9 100644
@@ -57,7 +57,6 @@
 ///     }
 /// }
 /// ```
-#[cfg_attr(not(CONFIG_KUNIT = "y"), expect(unused_macros))]
 macro_rules! nvkv_decode {
     // A schema which doesn't borrow from the stream. The macro uses a generic lifetime for the
     // [`Visit`] implementation but not for the struct itself. This allows omitting the unused
drivers/gpu/nova-core/gsp/nvkv/encode.rs +1 -1
index a9d0420d0936..c6891c0441ff 100644
@@ -38,7 +38,6 @@ pub(crate) trait Encodable {
 ///     }
 /// }
 /// ```
-#[cfg_attr(not(CONFIG_KUNIT = "y"), expect(unused_macros))]
 macro_rules! nvkv_encode {
     (
         $(#[$attr:meta])*
@@ -65,6 +64,7 @@ fn encode(&self, encoder: &mut $crate::gsp::nvkv::Encoder) -> ::kernel::error::R
         }
     };
 }
+pub(crate) use nvkv_encode;
 
 impl<const KEY_ID: KeyId> Encodable for IndexedKey<u32, KEY_ID> {
     fn encode(&self, encoder: &mut Encoder) -> Result {
Signature · 1 line
2.56.0
maintainer Applied
#8 lore raw

Re: (subset) [PATCH v5 0/7] gpu: nova-core: add NVKV codec

In reply to Eliot Courtney
Quoted 1 line · Eliot Courtney

[PATCH v5 0/7] gpu: nova-core: add NVKV codec

Applied, thanks!

Branch: alloc-next
Tree: [email protected]:Rust-for-Linux/linux.git

[1/7] rust: alloc: add Vec::try_push_init and Vec::push_init

      commit: 55f9b4727cbb
[2/7] rust: alloc: add ArrayVec
      commit: a2a82cbb7334

The patches will appear in the next linux-next integration (typically within 24 hours on weekdays).

The patches are queued up for the upcoming merge window for the next major kernel release.

maintainer Applied
#9 lore raw

Re: (subset) [PATCH v5 0/7] gpu: nova-core: add NVKV codec

In reply to Eliot Courtney
Quoted 1 line · Eliot Courtney

[PATCH v5 0/7] gpu: nova-core: add NVKV codec

Applied, thanks!

Branch: drm-rust-next
Tree: https://gitlab.freedesktop.org/drm/rust/kernel.git

[3/7] gpu: nova-core: add NVKV encoder

      commit: 440b82a79574
[4/7] gpu: nova-core: add NVKV decoder
      commit: 9898bacda71c
[5/7] gpu: nova-core: add NVKV typed encoding
      commit: 75e32e6e3573
[6/7] gpu: nova-core: add NVKV typed decoding
      commit: 434b46a415fc

[7/7] gpu: nova-core: add NVKV GSP_INIT schemas
commit: 41871f4ddf71

[ Fix minor merge conflict. - Danilo ]

The patches will appear in the next linux-next integration (typically within 24 hours on weekdays).

The patches are queued up for the upcoming merge window for the next major kernel release.