lists.openwall.net   lists  /  announce  owl-users  owl-dev  john-users  john-dev  passwdqc-users  yescrypt  popa3d-users  /  oss-security  kernel-hardening  musl  sabotage  tlsify  passwords  /  crypt-dev  xvendor  /  Bugtraq  Full-Disclosure  linux-kernel  linux-netdev  linux-ext4  linux-hardening  linux-cve-announce  PHC 
Open Source and information security mailing list archives
 
Hash Suite: Windows password security audit tool. GUI, reports in PDF.
[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-Id: <DDBW1JYMK8Y7.37R0EJR5VFEO4@nvidia.com>
Date: Tue, 07 Oct 2025 15:49:26 +0900
From: "Alexandre Courbot" <acourbot@...dia.com>
To: "Edwin Peer" <epeer@...dia.com>, "Joel Fernandes"
 <joelagnelf@...dia.com>
Cc: "linux-kernel@...r.kernel.org" <linux-kernel@...r.kernel.org>,
 "rust-for-linux@...r.kernel.org" <rust-for-linux@...r.kernel.org>,
 "dri-devel@...ts.freedesktop.org" <dri-devel@...ts.freedesktop.org>,
 "dakr@...nel.org" <dakr@...nel.org>, "Alexandre Courbot"
 <acourbot@...dia.com>, "Alistair Popple" <apopple@...dia.com>, "Miguel
 Ojeda" <ojeda@...nel.org>, "Alex Gaynor" <alex.gaynor@...il.com>, "Boqun
 Feng" <boqun.feng@...il.com>, "Gary Guo" <gary@...yguo.net>,
 "bjorn3_gh@...tonmail.com" <bjorn3_gh@...tonmail.com>, "Benno Lossin"
 <lossin@...nel.org>, "Andreas Hindborg" <a.hindborg@...nel.org>, "Alice
 Ryhl" <aliceryhl@...gle.com>, "Trevor Gross" <tmgross@...ch.edu>, "David
 Airlie" <airlied@...il.com>, "Simona Vetter" <simona@...ll.ch>, "Maarten
 Lankhorst" <maarten.lankhorst@...ux.intel.com>, "Maxime Ripard"
 <mripard@...nel.org>, "Thomas Zimmermann" <tzimmermann@...e.de>, "John
 Hubbard" <jhubbard@...dia.com>, "Timur Tabi" <ttabi@...dia.com>,
 "joel@...lfernandes.org" <joel@...lfernandes.org>, "Elle Rhumsaa"
 <elle@...thered-steel.dev>, "Yury Norov" <yury.norov@...il.com>, "Daniel
 Almeida" <daniel.almeida@...labora.com>, "Andrea Righi"
 <arighi@...dia.com>, "nouveau@...ts.freedesktop.org"
 <nouveau@...ts.freedesktop.org>
Subject: Re: [PATCH v6 1/5] nova-core: bitfield: Move bitfield-specific code
 from register! into new macro

Hi Edwin,

(replying as I wrote the original code and introduced the points you are
discussing).

On Tue Oct 7, 2025 at 2:56 AM JST, Edwin Peer wrote:
> Hi Joel,
>
> I recognize that this patch is intended to be a code move, but I’m seeing this code for the first time, hence the comments regarding the content below.
>
> On Oct 3, 2025, at 8:47 AM, Joel Fernandes <joelagnelf@...dia.com> wrote:
>
>> The bitfield-specific into new macro. This will be used to define
>> structs with bitfields, similar to C language.
>>
>> Reviewed-by: Elle Rhumsaa <elle@...thered-steel.dev>
>> Reviewed-by: Alexandre Courbot <acourbot@...dia.com>
>> Signed-off-by: Joel Fernandes <joelagnelf@...dia.com>
>> ---
>> drivers/gpu/nova-core/bitfield.rs    | 316 +++++++++++++++++++++++++++
>> drivers/gpu/nova-core/nova_core.rs   |   3 +
>> drivers/gpu/nova-core/regs/macros.rs | 259 +---------------------
>> 3 files changed, 329 insertions(+), 249 deletions(-)
>> create mode 100644 drivers/gpu/nova-core/bitfield.rs
>>
>> diff --git a/drivers/gpu/nova-core/bitfield.rs b/drivers/gpu/nova-core/bitfield.rs
>> new file mode 100644
>> index 000000000000..dd0ef2016ff8
>> --- /dev/null
>> +++ b/drivers/gpu/nova-core/bitfield.rs
>> @@ -0,0 +1,316 @@
>> +// SPDX-License-Identifier: GPL-2.0
>> +
>> +//! Bitfield library for Rust structures
>> +//!
>> +//! Support for defining bitfields in Rust structures. Also used by the [`register!`] macro.
>> +
>> +/// Defines a struct with accessors to access bits within an inner unsigned integer.
>> +///
>> +/// # Syntax
>> +///
>> +/// ```rust
>> +/// use nova_core::bitfield;
>> +///
>> +/// #[derive(Debug, Clone, Copy, Default)]
>> +/// enum Mode {
>> +///     #[default]
>> +///     Low = 0,
>> +///     High = 1,
>> +///     Auto = 2,
>> +/// }
>> +///
>> +/// impl TryFrom<u8> for Mode {
>> +///     type Error = u8;
>> +///     fn try_from(value: u8) -> Result<Self, Self::Error> {
>> +///         match value {
>> +///             0 => Ok(Mode::Low),
>> +///             1 => Ok(Mode::High),
>> +///             2 => Ok(Mode::Auto),
>> +///             _ => Err(value),
>> +///         }
>> +///     }
>> +/// }
>> +///
>> +/// impl From<Mode> for u32 {
>> +///     fn from(mode: Mode) -> u32 {
>> +///         mode as u32
>> +///     }
>> +/// }
>
> Is there a reason for the asymmetry in the From conversions for the user facing enum type? Here we have u8 in the one direction and u32 in the other. It looks like the latter is required by the use of u32:from() in the set_<field>() accessor, but the macro would be more ergonomic if it handled the necessary upcast conversions internally too.

Mmm, good point - actually it turns out the field setters work with the
type of the storage, and not of the field. This problem was in my
original code and is not introduced by this series.

I agree that we should have symmetry here, and actually that will be a
requirement to start using the TryFrom/Into derive macros [0].

I do have a patch available for this, which I kept for when we start
using the derive macros, but we should probably integrate it at the
beginning of this series.

[0] https://lore.kernel.org/rust-for-linux/cover.1755235180.git.y.j3ms.n@gmail.com/

>
>> +///
>> +/// #[derive(Debug, Clone, Copy, Default)]
>> +/// enum State {
>> +///     #[default]
>> +///     Inactive = 0,
>> +///     Active = 1,
>> +/// }
>> +///
>> +/// impl From<bool> for State {
>> +///     fn from(value: bool) -> Self {
>> +///         if value { State::Active } else { State::Inactive }
>> +///     }
>> +/// }
>> +///
>> +/// impl From<State> for u32 {
>> +///     fn from(state: State) -> u32 {
>> +///         state as u32
>> +///     }
>> +/// }
>
> Similarly for bool vs u32.
>
>> +///
>> +/// bitfield! {
>> +///     struct ControlReg {
>> +///         3:0 mode as u8 ?=> Mode;
>> +///         7:7 state as bool => State;
>> +///     }
>> +/// }
>> +/// ```
>> +///
>> +/// This generates a struct with:
>> +/// - Field accessors: `mode()`, `state()`, etc.
>> +/// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern).
>> +/// - Debug and Default implementations.
>> +///
>> +/// Fields are defined as follows:
>> +///
>> +/// - `as <type>` simply returns the field value casted to <type>, typically `u32`, `u16`, `u8` or
>> +///   `bool`. Note that `bool` fields must have a range of 1 bit.
>> +/// - `as <type> => <into_type>` calls `<into_type>`'s `From::<<type>>` implementation and returns
>> +///   the result.
>> +/// - `as <type> ?=> <try_into_type>` calls `<try_into_type>`'s `TryFrom::<<type>>` implementation
>> +///   and returns the result. This is useful with fields for which not all values are valid.
>> +macro_rules! bitfield {
>> +    // Main entry point - defines the bitfield struct with fields
>> +    (struct $name:ident $(, $comment:literal)? { $($fields:tt)* }) => {
>> +        bitfield!(@core $name $(, $comment)? { $($fields)* });
>> +    };
>> +
>> +    // All rules below are helpers.
>> +
>> +    // Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`,
>> +    // `Default`, `BitOr`, and conversion to the value type) and field accessor methods.
>> +    (@core $name:ident $(, $comment:literal)? { $($fields:tt)* }) => {
>> +        $(
>> +        #[doc=$comment]
>> +        )?
>> +        #[repr(transparent)]
>> +        #[derive(Clone, Copy)]
>> +        pub(crate) struct $name(u32);
>> +
>> +        impl ::core::ops::BitOr for $name {
>> +            type Output = Self;
>> +
>> +            fn bitor(self, rhs: Self) -> Self::Output {
>> +                Self(self.0 | rhs.0)
>> +            }
>> +        }
>
> Why do we implement BitOr for the register type? Seems a bit out of place for an abstraction that is trying to provide a safer field level access API.

Nice catch. I guess I wanted to make it easy to combine fields into a
new value, but that's what the builder pattern is for. BitOr makes it
possible to build an invalid value from two valid ones. I'll remove it.

>
>> +
>> +        impl ::core::convert::From<$name> for u32 {
>> +            fn from(val: $name) -> u32 {
>> +                val.0
>> +            }
>> +        }
>> +
>> +        bitfield!(@fields_dispatcher $name { $($fields)* });
>> +    };
>> +
>> +    // Captures the fields and passes them to all the implementers that require field information.
>> +    //
>> +    // Used to simplify the matching rules for implementers, so they don't need to match the entire
>> +    // complex fields rule even though they only make use of part of it.
>> +    (@fields_dispatcher $name:ident {
>> +        $($hi:tt:$lo:tt $field:ident as $type:tt
>> +            $(?=> $try_into_type:ty)?
>> +            $(=> $into_type:ty)?
>> +            $(, $comment:literal)?
>> +        ;
>> +        )*
>> +    }
>> +    ) => {
>> +        bitfield!(@field_accessors $name {
>> +            $(
>> +                $hi:$lo $field as $type
>> +                $(?=> $try_into_type)?
>> +                $(=> $into_type)?
>> +                $(, $comment)?
>> +            ;
>> +            )*
>> +        });
>> +        bitfield!(@debug $name { $($field;)* });
>> +        bitfield!(@default $name { $($field;)* });
>> +    };
>> +
>> +    // Defines all the field getter/setter methods for `$name`.
>> +    (
>> +        @field_accessors $name:ident {
>> +        $($hi:tt:$lo:tt $field:ident as $type:tt
>> +            $(?=> $try_into_type:ty)?
>> +            $(=> $into_type:ty)?
>> +            $(, $comment:literal)?
>> +        ;
>> +        )*
>> +        }
>> +    ) => {
>> +        $(
>> +            bitfield!(@check_field_bounds $hi:$lo $field as $type);
>> +        )*
>> +
>> +        #[allow(dead_code)]
>> +        impl $name {
>> +            $(
>> +            bitfield!(@field_accessor $name $hi:$lo $field as $type
>> +                $(?=> $try_into_type)?
>> +                $(=> $into_type)?
>> +                $(, $comment)?
>> +                ;
>> +            );
>> +            )*
>> +        }
>> +    };
>> +
>> +    // Boolean fields must have `$hi == $lo`.
>> +    (@check_field_bounds $hi:tt:$lo:tt $field:ident as bool) => {
>> +        #[allow(clippy::eq_op)]
>> +        const _: () = {
>> +            ::kernel::build_assert!(
>> +                $hi == $lo,
>> +                concat!("boolean field `", stringify!($field), "` covers more than one bit")
>> +            );
>> +        };
>> +    };
>> +
>> +    // Non-boolean fields must have `$hi >= $lo`.
>> +    (@check_field_bounds $hi:tt:$lo:tt $field:ident as $type:tt) => {
>> +        #[allow(clippy::eq_op)]
>> +        const _: () = {
>> +            ::kernel::build_assert!(
>> +                $hi >= $lo,
>> +                concat!("field `", stringify!($field), "`'s MSB is smaller than its LSB")
>> +            );
>> +        };
>> +    };
>
> It would also be good to find a way to catch overlapping field definitions.

Overlapping fields are actually a feature.

>
>> +
>> +    // Catches fields defined as `bool` and convert them into a boolean value.
>> +    (
>> +        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool => $into_type:ty
>> +            $(, $comment:literal)?;
>> +    ) => {
>> +        bitfield!(
>> +            @leaf_accessor $name $hi:$lo $field
>> +            { |f| <$into_type>::from(if f != 0 { true } else { false }) }
>
> if f != 0 { true } else {false} => f != 0

Oops, thank - will fix.

>
>> +            $into_type => $into_type $(, $comment)?;
>> +        );
>> +    };
>> +
>> +    // Shortcut for fields defined as `bool` without the `=>` syntax.
>> +    (
>> +        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?;
>> +    ) => {
>> +        bitfield!(@field_accessor $name $hi:$lo $field as bool => bool $(, $comment)?;);
>> +    };
>> +
>> +    // Catches the `?=>` syntax for non-boolean fields.
>> +    (
>> +        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty
>> +            $(, $comment:literal)?;
>> +    ) => {
>> +        bitfield!(@leaf_accessor $name $hi:$lo $field
>> +            { |f| <$try_into_type>::try_from(f as $type) } $try_into_type =>
>> +            ::core::result::Result<
>> +                $try_into_type,
>> +                <$try_into_type as ::core::convert::TryFrom<$type>>::Error
>> +            >
>> +            $(, $comment)?;);
>> +    };
>> +
>> +    // Catches the `=>` syntax for non-boolean fields.
>> +    (
>> +        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty
>> +            $(, $comment:literal)?;
>> +    ) => {
>> +        bitfield!(@leaf_accessor $name $hi:$lo $field
>> +            { |f| <$into_type>::from(f as $type) } $into_type => $into_type $(, $comment)?;);
>> +    };
>> +
>> +    // Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax.
>> +    (
>> +        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt
>> +            $(, $comment:literal)?;
>> +    ) => {
>> +        bitfield!(@field_accessor $name $hi:$lo $field as $type => $type $(, $comment)?;);
>> +    };
>
> I realize that the additional From conversion and closure invocation this produces will likely be optimized out when compiling at a suitable optimization level, but this is inefficient for register accesses in non-optimized debug builds:
>
> https://godbolt.org/z/YcTGh9xor
>
> It should be relatively straightforward to have the macro construct appropriate wrappers for an inline accessor function only when the conversions are needed, which would compile to something more efficient by construction.

This would only be possible if the field has the same type as the
storage type, which it seldom the case. I don't think it is worth
complicating the code to support some edge case that is only relevant on
non-optimized builds.

Furthermore, conversion will be unavoidable once we start using bounded
integers.

>
>> +
>> +    // Generates the accessor methods for a single field.
>> +    (
>> +        @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident
>> +            { $process:expr } $to_type:ty => $res_type:ty $(, $comment:literal)?;
>> +    ) => {
>> +        ::kernel::macros::paste!(
>> +        const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi;
>> +        const [<$field:upper _MASK>]: u32 = ((((1 << $hi) - 1) << 1) + 1) - ((1 << $lo) - 1);
>
> I note that genmask, introduced in a subsequent patch, also uses this construction (based on the range, which does not appear to be used by current code).
>
> Using const MASK: u32 = (1 << $hi - $lo + 1) - 1 << $lo would be more clear.
>
> It can also be a good idea to first right shift the value in the accessor and then utilize an unshifted mask, since smaller constant masks can lend themselves to more efficient immediate instructions (as in the godbolt link above).

The next patch addresses this by using genmask. Let's not modify code on
a patch that is a strict move, as this would make it more difficult to
review.

>
>> +        const [<$field:upper _SHIFT>]: u32 = Self::[<$field:upper _MASK>].trailing_zeros();
>
> const SHIFT: u32 = $lo;

Indeed. Let's address that in its own patch.

Thanks for the review!

Powered by blists - more mailing lists

Powered by Openwall GNU/*/Linux Powered by OpenVZ