Re: [PATCH v2] rust: bitfield: require integer storage

From: Alexandre Courbot

Date: Tue Sep 22 2026 - 10:23:06 EST


On Tue Sep 22, 2026 at 2:28 PM JST, Yilin Chen wrote:
> The bitfield! macro generates an unconditional Zeroable implementation
> for its wrapper type. An empty field list generates no Bounded usage, so
> the storage type can bypass the Integer requirement.
>
> Require the storage type to implement the sealed Integer trait for the
> generated Zeroable implementation. This ensures that bitfield storage is
> limited to primitive integer types with a valid all-zero bit pattern.
>
> Fixes: b7b8b4ccdad4 ("rust: extract `bitfield!` macro from `register!`")
> Assisted-by: GPT-5.6 Sol
> Signed-off-by: Yilin Chen <1479826151@xxxxxx>

Looks like my wish [1] has been instantly granted.

[1] https://lore.kernel.org/rust-for-linux/DLLVY7G20JJA.2B0KTTODUU9FG@xxxxxxxxxx/

> ---
> Changes in v2:
> - Add `where $storage: ::kernel::num::Integer` bound.
> - Update `// SAFETY` section.
> ---
>
> I track the default rust-next branch, and there is not any code about
> `AsRepr` in that branch. So in patch v1, I didn't know that case could
> not compile. Thank you for your feedback!
>
> rust/kernel/bitfield.rs | 9 +++++++--
> 1 file changed, 7 insertions(+), 2 deletions(-)
>
> diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
> index a0d089423f21..b1fc98d7f8c3 100644
> --- a/rust/kernel/bitfield.rs
> +++ b/rust/kernel/bitfield.rs
> @@ -330,8 +330,13 @@ impl $name {
> }
> }
>
> - // SAFETY: `$storage` is `Zeroable` and `$name` is transparent.
> - unsafe impl ::pin_init::Zeroable for $name {}
> + // SAFETY:
> + // - `$storage: Integer` is sealed to primitive integer types, for which the all-zero bit
> + // pattern is valid.
> + // - `$name` is `repr(transparent)` over `$storage`.
> + unsafe impl ::pin_init::Zeroable for $name
> + where $storage: ::kernel::num::Integer
> + {}

While I guess that would somehow work, I think the proper place to do
this is the struct definition, i.e:

$vis struct $name
where
$storage: $crate::num::Integer,
{
inner: $storage,
}

This makes the error message also more explicit about what the problem
is (a bitfield requires an `Integer`, not merely the ability to
initialize it to zero).