From nobody Thu Oct 2 22:52:49 2025 Received: from SA9PR02CU001.outbound.protection.outlook.com (mail-southcentralusazon11013005.outbound.protection.outlook.com [40.93.196.5]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 575491487F4; Tue, 30 Sep 2025 14:45:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.196.5 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243561; cv=fail; b=GT6Py8npGqpAq9F1Z1Y03NH59XFd4jQhfY2+y0kF4VgC7u+b9QDQSvfhizkbVe3dfI5kab7kwJ1fmGxV9K2LeFNESyiySBwsjHwELvjSxn9vp/yf9z6qe1d+tA3iJNKUKlEUZicPpZISoxWDvhnwK4FVFQgoxApc5Z9WUfba870= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243561; c=relaxed/simple; bh=7GDJCBBlGZppdCYl86DaQUbdpoD9WCI0Rcu5prcnuBk=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: Content-Type:MIME-Version; b=MyatZeZAqRvH4k37dNXPfyHJ7In4exIuO91us/eJ3Nlh/+ttAiSxUHXi+dRJTUqDdPRGiP1u94i3POV8fJOiHGDr7GdcL5zIMr1lOB+u4V/ZUIAjx8tUteuy51rFsuvu60Oq0Z+CBF2pCpHtBD/+Vh1lcrDTFU1xM8EHzaJfBL0= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com; spf=fail smtp.mailfrom=nvidia.com; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b=Hw8ljfZ5; arc=fail smtp.client-ip=40.93.196.5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com Authentication-Results: smtp.subspace.kernel.org; spf=fail smtp.mailfrom=nvidia.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b="Hw8ljfZ5" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=g0G7axpNgG5XqCHoQZz3TSZwgXY22unMW3U0l+5MEW3/5hQ1Lh/Wylk8+on4/+iJqWlnXaX1FbdnQKxdH7cwdFR8gEERN3UWuNXKhfmOm7DyZScFSsXZXwVX9c7VYmlcu7TF0x8WjDF6iVGJ7a4WlS0d7CMZKNUzYhAbclBzu8eZzd8bsFIwpSf4ksgQlldQ1f23RBFfXyPAlFmcPrXQpTS33+Lza+2Eetb2u40TGWlu2RFbTOJ8ib1AfE19CBd25Jy04vC6w3gvqc9zzhHkXZ/H5jQM5C61Kjho7h6LezJqVkRjsCmQBnwhBLLjgM6nPdXkdQ+2fAWcVFGmfyZJFA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=87WKxs7Jc0jKmEphFCZalvKa4d49vCf3u/nKNnPustA=; b=dfNeaFFrgGJIVA2kXfe1ogktvq3D9YSEv9T6ifi6y8Oj9INxavxdIVaR4zGkX2Y/Iv8+M29FayrqtndOCDSTjyMcP1S6EDpWwEwYrGh7IL98mlsVn6P0ugBLZka7dU1719Lr2gshSXRcIhGyr+826Ak14dfU1GBy4HlgBeztl6ic3+QGrSFo+4x39OkEWfuoTFNubQ+eAECEVwLcxPBgxcl9hhkKWzRt19q7WwFFmoWTyb5NZw5FgUBvP/vl8BfX7yJd0lpihZx78nEslohufPFApKk/6pb8dbEdYFsWthyMEeDii//QQeJnfoBRyVHvsAMJmUQceba6JFwPyAn0Zw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=nvidia.com; dmarc=pass action=none header.from=nvidia.com; dkim=pass header.d=nvidia.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=Nvidia.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=87WKxs7Jc0jKmEphFCZalvKa4d49vCf3u/nKNnPustA=; b=Hw8ljfZ5d3t/RQFFzKLYqRj6Tzkk5wOQxkS3aab0ZIGNzP425fflhHZ0GOXYxFc8QKD4deMajZmTMJqjQDfLCUZS+KgQ32X64TkYuKy5XyTp1kbAGeMkcniwP4bxnquZ1ud27++cIbww0JetbhEOb29o3Q2DfL/z+mg6g/q1veV1tHSsrAWi/FTGIOyhnj3fwW1IECf58koxKbF/KWUItGXfCsEEmfnyLWeOp6Olml5iADQNv/dxL8CVS09fpcmNhBfF2UwFQ+XbXmYB8T5gF9+DneilAqfzo7q+aAHxbTZtr2vASe8YuU/ty3dCSANJ4lo2o71+LwdX+dmDzw0Srw== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) by DM4PR12MB8475.namprd12.prod.outlook.com (2603:10b6:8:190::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9160.17; Tue, 30 Sep 2025 14:45:47 +0000 Received: from SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91]) by SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91%2]) with mapi id 15.20.9160.015; Tue, 30 Sep 2025 14:45:47 +0000 From: Joel Fernandes To: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org, dakr@kernel.org, acourbot@nvidia.com Cc: Alistair Popple , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , bjorn3_gh@protonmail.com, Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , David Airlie , Simona Vetter , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , John Hubbard , Joel Fernandes , Timur Tabi , joel@joelfernandes.org, Elle Rhumsaa , Yury Norov , Daniel Almeida , Andrea Righi , nouveau@lists.freedesktop.org Subject: [PATCH v5 1/9] nova-core: bitfield: Move bitfield-specific code from register! into new macro Date: Tue, 30 Sep 2025 10:45:29 -0400 Message-Id: <20250930144537.3559207-2-joelagnelf@nvidia.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20250930144537.3559207-1-joelagnelf@nvidia.com> References: <20250930144537.3559207-1-joelagnelf@nvidia.com> Content-Transfer-Encoding: quoted-printable X-ClientProxiedBy: BL0PR02CA0046.namprd02.prod.outlook.com (2603:10b6:207:3d::23) To SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SN7PR12MB8059:EE_|DM4PR12MB8475:EE_ X-MS-Office365-Filtering-Correlation-Id: 2beef687-d10e-4996-0e57-08de00300ad1 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|7416014|376014; X-Microsoft-Antispam-Message-Info: =?us-ascii?Q?zw/WO7liEaMLQOyQr3fwc10Fsr5W5B+avZQubyqCFW0gXCHuerTpxNqBw6Zc?= =?us-ascii?Q?gGxw8qBcscZkoGinitvXeT1a3TP6kDW7LRweUpQBkt1KeQixIcXCcrIN7/oT?= =?us-ascii?Q?eONXreCR4gdOgSBUUsxIb9cmDgH18XyMjMfUMXYjL4roZ22HrVZsDR18d+Yg?= =?us-ascii?Q?YAM1qp45cwp7wpD32ERAsRLp3gGHKG+EiY5R42PJu4XJ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FKG596jL1QN9G7JmCkFuEHxn2UOfZjZS4C0iGmh3byqKZI7/KtkyPc?= =?us-ascii?Q?i5S/w4uyPQ/JMIa0KEM2xsGBO4R1bzB1Y13+Z0rLT6Ce4oTcUocCgu84ld3k?= =?us-ascii?Q?qFSBLw4eE9fY8EJI5fHdIfU3CY+mPn2Vk1gNg4Hrq4n8u82iUM0kMIXTAlm6?= =?us-ascii?Q?/5RryT7bylt7vvpBhYvgvfWfJ/c6BwzXjg0jPdpOZRLM77uQzoCcsSYIrNS9?= =?us-ascii?Q?0zLOyl+j3WOyo2sAuCMfUc2paj930vYoblD6DG8zLEWuzUk7JaIQZS15JSyH?= =?us-ascii?Q?Tuc//hdhBxRGoAv8IVOIFQUw9U2317hzLge5MF3ugFhMma3CA6Dw4RFf4KQy?= =?us-ascii?Q?Mk3jba9ACp1j2D0OjJ+AdbCjphNgcomM?= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SN7PR12MB8059.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(366016)(1800799024)(7416014)(376014);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?us-ascii?Q?14yLlxgZ08MR3mNA9e5eKv6S+sLgqzgXKfGkG0OsTSmVCw5skEUd9E52uccA?= =?us-ascii?Q?qP48GfBz6gl0c5qvVZUE8Lgvj+vYNtIxotspki5+uhSvyu2FJn18AMFYyLLK?= =?us-ascii?Q?NH2qeXqtSAWaZfd3KCKuQCfXH+/HWHuoDBWkmhqpJAuIL40T2hnYZBTjmzD5?= =?us-ascii?Q?nlPb4JakvMPeayE8kDcWJaLJVqD6Z9At9bKGGfy8kIKpxKTC0FmvjjHuIDZR?= =?us-ascii?Q?9+fc0zOYaINc2zY7bwT6e/wHS6g5gaTTBMKfs63o8psUlfHsGTBbnTJBPCtO?= =?us-ascii?Q?mA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qNNf6Wvsugq2lzHLgoh7EA?= =?us-ascii?Q?EBRo3srpDrUbW5UUR66d7k3FY8kNPmsfMc8RA+XFCYXCIAK3xzoWQlLeb7gz?= =?us-ascii?Q?cpAezvd6UJSxXYd3Eype4R9Yi8YzHMYjsZ6L2mX1W9KJaJTcuh5JiQFjW6Bx?= =?us-ascii?Q?Fl18N+bqilyW/EY4WB7Q6H5yNAhYzTpT05qGhqDsrA7Z3nG6g23MSqgDmpfs?= =?us-ascii?Q?84DQbnnZRJykXSnOhBMTmgWJseSfbv7yhfW7sjlwvHCx8H6COcGxbw8uhAFr?= =?us-ascii?Q?ZTOvmWnE8P8KREojbkHu1Wjgdm4J6ltH/lhb0h2XnJFka3Ao20wMFAHjzYlo?= =?us-ascii?Q?HrlzzMLpGDpw/ZeTm2ETkbtGkj43Gz627kQIsWbgHTahX1qQj6jxI/FNu9t1?= =?us-ascii?Q?eS44PQfweigq1tKx+VhOlZkHtvu6a9Tz1cbhIE2Orboe6K1wpmd51dQ6YbmB?= =?us-ascii?Q?Kw=3D=3D?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 2beef687-d10e-4996-0e57-08de00300ad1 X-MS-Exchange-CrossTenant-AuthSource: SN7PR12MB8059.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Sep 2025 14:45:47.5000 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 43083d15-7273-40c1-b7db-39efd9ccc17a X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: 0ZgDjXCqL/FiVzJLNdirX4BHnNwiv1L4fZ1qbzyrwYPGFwr0ky9pnJHSXchSZYjgabf5/lXTHkh4XwGv5niAgw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM4PR12MB8475 Content-Type: text/plain; charset="utf-8" The bitfield-specific into new macro. This will be used to define structs with bitfields, similar to C language. Reviewed-by: Elle Rhumsaa Reviewed-by: Alexandre Courbot Signed-off-by: Joel Fernandes --- drivers/gpu/nova-core/bitfield.rs | 315 +++++++++++++++++++++++++++ drivers/gpu/nova-core/nova_core.rs | 3 + drivers/gpu/nova-core/regs/macros.rs | 259 +--------------------- 3 files changed, 328 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/bitf= ield.rs new file mode 100644 index 000000000000..b1e1c438b8a8 --- /dev/null +++ b/drivers/gpu/nova-core/bitfield.rs @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Bitfield library for Rust structures +//! +//! Support for defining bitfields in Rust structures. Also used by the [`= register!`] macro. +//! +//! # Syntax +//! +//! ```rust +//! use nova_core::bitfield; +//! +//! #[derive(Debug, Clone, Copy, Default)] +//! enum Mode { +//! #[default] +//! Low =3D 0, +//! High =3D 1, +//! Auto =3D 2, +//! } +//! +//! impl TryFrom for Mode { +//! type Error =3D u8; +//! fn try_from(value: u8) -> Result { +//! match value { +//! 0 =3D> Ok(Mode::Low), +//! 1 =3D> Ok(Mode::High), +//! 2 =3D> Ok(Mode::Auto), +//! _ =3D> Err(value), +//! } +//! } +//! } +//! +//! impl From for u32 { +//! fn from(mode: Mode) -> u32 { +//! mode as u32 +//! } +//! } +//! +//! #[derive(Debug, Clone, Copy, Default)] +//! enum State { +//! #[default] +//! Inactive =3D 0, +//! Active =3D 1, +//! } +//! +//! impl From for State { +//! fn from(value: bool) -> Self { +//! if value { State::Active } else { State::Inactive } +//! } +//! } +//! +//! impl From for u32 { +//! fn from(state: State) -> u32 { +//! state as u32 +//! } +//! } +//! +//! bitfield! { +//! struct ControlReg { +//! 3:0 mode as u8 ?=3D> Mode; +//! 7:7 state as bool =3D> 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 ` simply returns the field value casted to , typical= ly `u32`, `u16`, `u8` or +//! `bool`. Note that `bool` fields must have a range of 1 bit. +//! - `as =3D> ` calls ``'s `From::<>` = implementation and returns +//! the result. +//! - `as ?=3D> ` calls ``'s `TryFrom= ::<>` 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)* }) =3D> { + bitfield!(@core $name $(, $comment)? { $($fields)* }); + }; + + // All rules below are helpers. + + // Defines the wrapper `$name` type, as well as its relevant implement= ations (`Debug`, + // `Default`, `BitOr`, and conversion to the value type) and field acc= essor methods. + (@core $name:ident $(, $comment:literal)? { $($fields:tt)* }) =3D> { + $( + #[doc=3D$comment] + )? + #[repr(transparent)] + #[derive(Clone, Copy)] + pub(crate) struct $name(u32); + + impl ::core::ops::BitOr for $name { + type Output =3D Self; + + fn bitor(self, rhs: Self) -> Self::Output { + Self(self.0 | rhs.0) + } + } + + 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 re= quire 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 + $(?=3D> $try_into_type:ty)? + $(=3D> $into_type:ty)? + $(, $comment:literal)? + ; + )* + } + ) =3D> { + bitfield!(@field_accessors $name { + $( + $hi:$lo $field as $type + $(?=3D> $try_into_type)? + $(=3D> $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 + $(?=3D> $try_into_type:ty)? + $(=3D> $into_type:ty)? + $(, $comment:literal)? + ; + )* + } + ) =3D> { + $( + bitfield!(@check_field_bounds $hi:$lo $field as $type); + )* + + #[allow(dead_code)] + impl $name { + $( + bitfield!(@field_accessor $name $hi:$lo $field as $type + $(?=3D> $try_into_type)? + $(=3D> $into_type)? + $(, $comment)? + ; + ); + )* + } + }; + + // Boolean fields must have `$hi =3D=3D $lo`. + (@check_field_bounds $hi:tt:$lo:tt $field:ident as bool) =3D> { + #[allow(clippy::eq_op)] + const _: () =3D { + ::kernel::build_assert!( + $hi =3D=3D $lo, + concat!("boolean field `", stringify!($field), "` covers m= ore than one bit") + ); + }; + }; + + // Non-boolean fields must have `$hi >=3D $lo`. + (@check_field_bounds $hi:tt:$lo:tt $field:ident as $type:tt) =3D> { + #[allow(clippy::eq_op)] + const _: () =3D { + ::kernel::build_assert!( + $hi >=3D $lo, + concat!("field `", stringify!($field), "`'s MSB is smaller= than its LSB") + ); + }; + }; + + // Catches fields defined as `bool` and convert them into a boolean va= lue. + ( + @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool =3D= > $into_type:ty + $(, $comment:literal)?; + ) =3D> { + bitfield!( + @leaf_accessor $name $hi:$lo $field + { |f| <$into_type>::from(if f !=3D 0 { true } else { false }) } + $into_type =3D> $into_type $(, $comment)?; + ); + }; + + // Shortcut for fields defined as `bool` without the `=3D>` syntax. + ( + @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool $(,= $comment:literal)?; + ) =3D> { + bitfield!(@field_accessor $name $hi:$lo $field as bool =3D> bool $= (, $comment)?;); + }; + + // Catches the `?=3D>` syntax for non-boolean fields. + ( + @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt= ?=3D> $try_into_type:ty + $(, $comment:literal)?; + ) =3D> { + bitfield!(@leaf_accessor $name $hi:$lo $field + { |f| <$try_into_type>::try_from(f as $type) } $try_into_type = =3D> + ::core::result::Result< + $try_into_type, + <$try_into_type as ::core::convert::TryFrom<$type>>::Error + > + $(, $comment)?;); + }; + + // Catches the `=3D>` syntax for non-boolean fields. + ( + @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt= =3D> $into_type:ty + $(, $comment:literal)?; + ) =3D> { + bitfield!(@leaf_accessor $name $hi:$lo $field + { |f| <$into_type>::from(f as $type) } $into_type =3D> $into_t= ype $(, $comment)?;); + }; + + // Shortcut for non-boolean fields defined without the `=3D>` or `?=3D= >` syntax. + ( + @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt + $(, $comment:literal)?; + ) =3D> { + bitfield!(@field_accessor $name $hi:$lo $field as $type =3D> $type= $(, $comment)?;); + }; + + // Generates the accessor methods for a single field. + ( + @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident + { $process:expr } $to_type:ty =3D> $res_type:ty $(, $comment:l= iteral)?; + ) =3D> { + ::kernel::macros::paste!( + const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive =3D= $lo..=3D$hi; + const [<$field:upper _MASK>]: u32 =3D ((((1 << $hi) - 1) << 1) + 1= ) - ((1 << $lo) - 1); + const [<$field:upper _SHIFT>]: u32 =3D Self::[<$field:upper _MASK>= ].trailing_zeros(); + ); + + $( + #[doc=3D"Returns the value of this field:"] + #[doc=3D$comment] + )? + #[inline(always)] + pub(crate) fn $field(self) -> $res_type { + ::kernel::macros::paste!( + const MASK: u32 =3D $name::[<$field:upper _MASK>]; + const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; + ); + let field =3D ((self.0 & MASK) >> SHIFT); + + $process(field) + } + + ::kernel::macros::paste!( + $( + #[doc=3D"Sets the value of this field:"] + #[doc=3D$comment] + )? + #[inline(always)] + pub(crate) fn [](mut self, value: $to_type) -> Self { + const MASK: u32 =3D $name::[<$field:upper _MASK>]; + const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; + let value =3D (u32::from(value) << SHIFT) & MASK; + self.0 =3D (self.0 & !MASK) | value; + + self + } + ); + }; + + // Generates the `Debug` implementation for `$name`. + (@debug $name:ident { $($field:ident;)* }) =3D> { + impl ::core::fmt::Debug for $name { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::f= mt::Result { + f.debug_struct(stringify!($name)) + .field("", &format_args!("{:#x}", &self.0)) + $( + .field(stringify!($field), &self.$field()) + )* + .finish() + } + } + }; + + // Generates the `Default` implementation for `$name`. + (@default $name:ident { $($field:ident;)* }) =3D> { + /// Returns a value for the bitfield where all fields are set to t= heir default value. + impl ::core::default::Default for $name { + fn default() -> Self { + #[allow(unused_mut)] + let mut value =3D Self(Default::default()); + + ::kernel::macros::paste!( + $( + value.[](Default::default()); + )* + ); + + value + } + } + }; +} diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nov= a_core.rs index fffcaee2249f..112277c7921e 100644 --- a/drivers/gpu/nova-core/nova_core.rs +++ b/drivers/gpu/nova-core/nova_core.rs @@ -2,6 +2,9 @@ =20 //! Nova Core GPU Driver =20 +#[macro_use] +mod bitfield; + mod dma; mod driver; mod falcon; diff --git a/drivers/gpu/nova-core/regs/macros.rs b/drivers/gpu/nova-core/r= egs/macros.rs index 754c14ee7f40..945d15a2c529 100644 --- a/drivers/gpu/nova-core/regs/macros.rs +++ b/drivers/gpu/nova-core/regs/macros.rs @@ -8,7 +8,8 @@ //! //! The `register!` macro in this module provides an intuitive and readabl= e syntax for defining a //! dedicated type for each register. Each such type comes with its own fi= eld accessors that can -//! return an error if a field's value is invalid. +//! return an error if a field's value is invalid. Please look at the [`bi= tfield`] macro for the +//! complete syntax of fields definitions. =20 /// Trait providing a base address to be added to the offset of a relative= register to obtain /// its actual offset. @@ -54,15 +55,6 @@ pub(crate) trait RegisterBase { /// BOOT_0::alter(&bar, |r| r.set_major_revision(3).set_minor_revision(10)= ); /// ``` /// -/// Fields are defined as follows: -/// -/// - `as ` simply returns the field value casted to , typical= ly `u32`, `u16`, `u8` or -/// `bool`. Note that `bool` fields must have a range of 1 bit. -/// - `as =3D> ` calls ``'s `From::<>` = implementation and returns -/// the result. -/// - `as ?=3D> ` calls ``'s `TryFrom= ::<>` implementation -/// and returns the result. This is useful with fields for which not all= values are valid. -/// /// The documentation strings are optional. If present, they will be added= to the type's /// definition, or the field getter and setter methods they are attached t= o. /// @@ -284,25 +276,25 @@ pub(crate) trait RegisterBase { macro_rules! register { // Creates a register at a fixed offset of the MMIO space. ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)*= } ) =3D> { - register!(@core $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name $(, $comment)? { $($fields)* } ); register!(@io_fixed $name @ $offset); }; =20 // Creates an alias register of fixed offset register `alias` with its= own fields. ($name:ident =3D> $alias:ident $(, $comment:literal)? { $($fields:tt)*= } ) =3D> { - register!(@core $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name $(, $comment)? { $($fields)* } ); register!(@io_fixed $name @ $alias::OFFSET); }; =20 // Creates a register at a relative offset from a base address provide= r. ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $= ($fields:tt)* } ) =3D> { - register!(@core $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name $(, $comment)? { $($fields)* } ); register!(@io_relative $name @ $base [ $offset ]); }; =20 // Creates an alias register of relative offset register `alias` with = its own fields. ($name:ident =3D> $base:ty [ $alias:ident ] $(, $comment:literal)? { $= ($fields:tt)* }) =3D> { - register!(@core $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name $(, $comment)? { $($fields)* } ); register!(@io_relative $name @ $base [ $alias::OFFSET ]); }; =20 @@ -313,7 +305,7 @@ macro_rules! register { } ) =3D> { static_assert!(::core::mem::size_of::() <=3D $stride); - register!(@core $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name $(, $comment)? { $($fields)* } ); register!(@io_array $name @ $offset [ $size ; $stride ]); }; =20 @@ -334,7 +326,7 @@ macro_rules! register { $(, $comment:literal)? { $($fields:tt)* } ) =3D> { static_assert!(::core::mem::size_of::() <=3D $stride); - register!(@core $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name $(, $comment)? { $($fields)* } ); register!(@io_relative_array $name @ $base [ $offset [ $size ; $st= ride ] ]); }; =20 @@ -356,7 +348,7 @@ macro_rules! register { } ) =3D> { static_assert!($idx < $alias::SIZE); - register!(@core $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name $(, $comment)? { $($fields)* } ); register!(@io_relative $name @ $base [ $alias::OFFSET + $idx * $al= ias::STRIDE ] ); }; =20 @@ -365,241 +357,10 @@ macro_rules! register { // to avoid it being interpreted in place of the relative register arr= ay alias rule. ($name:ident =3D> $alias:ident [ $idx:expr ] $(, $comment:literal)? { = $($fields:tt)* }) =3D> { static_assert!($idx < $alias::SIZE); - register!(@core $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name $(, $comment)? { $($fields)* } ); register!(@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE= ); }; =20 - // All rules below are helpers. - - // Defines the wrapper `$name` type, as well as its relevant implement= ations (`Debug`, - // `Default`, `BitOr`, and conversion to the value type) and field acc= essor methods. - (@core $name:ident $(, $comment:literal)? { $($fields:tt)* }) =3D> { - $( - #[doc=3D$comment] - )? - #[repr(transparent)] - #[derive(Clone, Copy)] - pub(crate) struct $name(u32); - - impl ::core::ops::BitOr for $name { - type Output =3D Self; - - fn bitor(self, rhs: Self) -> Self::Output { - Self(self.0 | rhs.0) - } - } - - impl ::core::convert::From<$name> for u32 { - fn from(reg: $name) -> u32 { - reg.0 - } - } - - register!(@fields_dispatcher $name { $($fields)* }); - }; - - // Captures the fields and passes them to all the implementers that re= quire 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 - $(?=3D> $try_into_type:ty)? - $(=3D> $into_type:ty)? - $(, $comment:literal)? - ; - )* - } - ) =3D> { - register!(@field_accessors $name { - $( - $hi:$lo $field as $type - $(?=3D> $try_into_type)? - $(=3D> $into_type)? - $(, $comment)? - ; - )* - }); - register!(@debug $name { $($field;)* }); - register!(@default $name { $($field;)* }); - }; - - // Defines all the field getter/methods methods for `$name`. - ( - @field_accessors $name:ident { - $($hi:tt:$lo:tt $field:ident as $type:tt - $(?=3D> $try_into_type:ty)? - $(=3D> $into_type:ty)? - $(, $comment:literal)? - ; - )* - } - ) =3D> { - $( - register!(@check_field_bounds $hi:$lo $field as $type); - )* - - #[allow(dead_code)] - impl $name { - $( - register!(@field_accessor $name $hi:$lo $field as $type - $(?=3D> $try_into_type)? - $(=3D> $into_type)? - $(, $comment)? - ; - ); - )* - } - }; - - // Boolean fields must have `$hi =3D=3D $lo`. - (@check_field_bounds $hi:tt:$lo:tt $field:ident as bool) =3D> { - #[allow(clippy::eq_op)] - const _: () =3D { - ::kernel::build_assert!( - $hi =3D=3D $lo, - concat!("boolean field `", stringify!($field), "` covers m= ore than one bit") - ); - }; - }; - - // Non-boolean fields must have `$hi >=3D $lo`. - (@check_field_bounds $hi:tt:$lo:tt $field:ident as $type:tt) =3D> { - #[allow(clippy::eq_op)] - const _: () =3D { - ::kernel::build_assert!( - $hi >=3D $lo, - concat!("field `", stringify!($field), "`'s MSB is smaller= than its LSB") - ); - }; - }; - - // Catches fields defined as `bool` and convert them into a boolean va= lue. - ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool =3D= > $into_type:ty - $(, $comment:literal)?; - ) =3D> { - register!( - @leaf_accessor $name $hi:$lo $field - { |f| <$into_type>::from(if f !=3D 0 { true } else { false }) } - $into_type =3D> $into_type $(, $comment)?; - ); - }; - - // Shortcut for fields defined as `bool` without the `=3D>` syntax. - ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool $(,= $comment:literal)?; - ) =3D> { - register!(@field_accessor $name $hi:$lo $field as bool =3D> bool $= (, $comment)?;); - }; - - // Catches the `?=3D>` syntax for non-boolean fields. - ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt= ?=3D> $try_into_type:ty - $(, $comment:literal)?; - ) =3D> { - register!(@leaf_accessor $name $hi:$lo $field - { |f| <$try_into_type>::try_from(f as $type) } $try_into_type = =3D> - ::core::result::Result< - $try_into_type, - <$try_into_type as ::core::convert::TryFrom<$type>>::Error - > - $(, $comment)?;); - }; - - // Catches the `=3D>` syntax for non-boolean fields. - ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt= =3D> $into_type:ty - $(, $comment:literal)?; - ) =3D> { - register!(@leaf_accessor $name $hi:$lo $field - { |f| <$into_type>::from(f as $type) } $into_type =3D> $into_t= ype $(, $comment)?;); - }; - - // Shortcut for non-boolean fields defined without the `=3D>` or `?=3D= >` syntax. - ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt - $(, $comment:literal)?; - ) =3D> { - register!(@field_accessor $name $hi:$lo $field as $type =3D> $type= $(, $comment)?;); - }; - - // Generates the accessor methods for a single field. - ( - @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident - { $process:expr } $to_type:ty =3D> $res_type:ty $(, $comment:l= iteral)?; - ) =3D> { - ::kernel::macros::paste!( - const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive =3D= $lo..=3D$hi; - const [<$field:upper _MASK>]: u32 =3D ((((1 << $hi) - 1) << 1) + 1= ) - ((1 << $lo) - 1); - const [<$field:upper _SHIFT>]: u32 =3D Self::[<$field:upper _MASK>= ].trailing_zeros(); - ); - - $( - #[doc=3D"Returns the value of this field:"] - #[doc=3D$comment] - )? - #[inline(always)] - pub(crate) fn $field(self) -> $res_type { - ::kernel::macros::paste!( - const MASK: u32 =3D $name::[<$field:upper _MASK>]; - const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; - ); - let field =3D ((self.0 & MASK) >> SHIFT); - - $process(field) - } - - ::kernel::macros::paste!( - $( - #[doc=3D"Sets the value of this field:"] - #[doc=3D$comment] - )? - #[inline(always)] - pub(crate) fn [](mut self, value: $to_type) -> Self { - const MASK: u32 =3D $name::[<$field:upper _MASK>]; - const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; - let value =3D (u32::from(value) << SHIFT) & MASK; - self.0 =3D (self.0 & !MASK) | value; - - self - } - ); - }; - - // Generates the `Debug` implementation for `$name`. - (@debug $name:ident { $($field:ident;)* }) =3D> { - impl ::core::fmt::Debug for $name { - fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::f= mt::Result { - f.debug_struct(stringify!($name)) - .field("", &format_args!("{:#x}", &self.0)) - $( - .field(stringify!($field), &self.$field()) - )* - .finish() - } - } - }; - - // Generates the `Default` implementation for `$name`. - (@default $name:ident { $($field:ident;)* }) =3D> { - /// Returns a value for the register where all fields are set to t= heir default value. - impl ::core::default::Default for $name { - fn default() -> Self { - #[allow(unused_mut)] - let mut value =3D Self(Default::default()); - - ::kernel::macros::paste!( - $( - value.[](Default::default()); - )* - ); - - value - } - } - }; - // Generates the IO accessors for a fixed offset register. (@io_fixed $name:ident @ $offset:expr) =3D> { #[allow(dead_code)] --=20 2.34.1 From nobody Thu Oct 2 22:52:49 2025 Received: from SA9PR02CU001.outbound.protection.outlook.com (mail-southcentralusazon11013005.outbound.protection.outlook.com [40.93.196.5]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 700E130505D; Tue, 30 Sep 2025 14:45:56 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.196.5 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243559; cv=fail; b=K149h83qEa1j0uv0ZNv0eHSPigTH1YUXKjsLBmEmY1MltiGflIgZLJ5JnAW0ceTIlG/GR9CR9AptJkuJi3Fy77jBR5dexlG5JdsCKc4NXUIaBNIZU6c4b6Ey+OJlY5zbD/8+geVS/O0RSQ/CoZ+/UlZgbBWGm4VeIk2lM0SvxUk= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243559; c=relaxed/simple; bh=YmGcndOJyKhStZ7hjZGn8D9wwca22hX+qOKU1Jao0OU=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: Content-Type:MIME-Version; b=Dyva50JXNHHyCgxqBTa6TIpLOwMScGvbQiIaXYj9Sj+chpMVFuUyZ+uxuyNCofJxXuwbyGcdPi1kGOMYJwpKLcRbPQmHUsVy4mj+xvilqoDKyi/xzpmBMMkFGSyKhP9zCNpHYcbYpYp5mglATP3E7NhnGs6Q6JSVFQwmSH4pe0s= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com; spf=fail smtp.mailfrom=nvidia.com; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b=N9ANqMpt; arc=fail smtp.client-ip=40.93.196.5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com Authentication-Results: smtp.subspace.kernel.org; spf=fail smtp.mailfrom=nvidia.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b="N9ANqMpt" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=GjLdBYLBFugJLdq1ZP8CHnXqCVBrL1QEvchZpGvk/YTAVrHcuE63eTVEJWTAIPC1p4Z9csm3YrY4eQJAiSYzVVbXFFoOztWg3NpVWRyCWsEDE7gQlDv5TffiGvp9CG1Hx4HN+UtQL9+yy/4CZ3/h9ZTs1T620w4Qo86AOPz88eZDwBIIHyn3GvUrQUdhqpeQDRANt2vTR46Tk8d6QWbSYqnVTm6s3JxI8IACVxahl6aPebmgxA8BVhi9lzLDfTt7eqUhzrgUN/JkbCmT7JvOgXB/y2a310pkQTiAiKv5t1cW2tAWQ7XedlIfWKMP7L0uVRipby2Jfk7xr4V9LQNDFg== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=yP3mDrKIlTJDj1l+CMjvQGZOLqUl7qVCiHV8mPogE0E=; b=LRG/SREcuptETM4WvbPLTEIyaYvCbUk3RAGfBEsFhmEedi0EljMKJBK/Ju/f4FJAzTypktfxOYLfDy4+0Spdctsj8TOD43uKwKJrzyh8zJP3BPXi013Bkd0cJmcKf+XneSnMox7YQcLtOxH4TgrQZZi6s5tyJxGBKNKQNWFDDod7epSJj2X6vbTiAPs1QTccIU9RnykowSJ4w8PgOgWl7dvkiVOlcvZTZFgcwTnM1C++HPlnsYaa6OKoDS9iUHY0Tm0l5ajO0mLXC0ZgSQJB1Fqz/UyH38uM/t8Kq7+ZtfXz9iRvXCMyZvp/fUHImAYF/aktGF5ZmWl4GUKui4TybQ== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=nvidia.com; dmarc=pass action=none header.from=nvidia.com; dkim=pass header.d=nvidia.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=Nvidia.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=yP3mDrKIlTJDj1l+CMjvQGZOLqUl7qVCiHV8mPogE0E=; b=N9ANqMptkAqkIe5FKSSveZN5Q29cZuV/yxyiv0BuaE2bnyPpwTB+tjzjVBmywscQnrtIwpqzPSGMfJIMaRaWJrzfmhGTeIbj0MYgDBE8zYA95ncXmeGzN36qO0107p6GLI+ock5wD/7tQoT3CCbwoEbw25MlBOJ/daicUVixiFaQK5SsfsSZXAVDa7gHfz47jBC/EdROlQTs1J/M0UUo+Igj9DGO5vq6IUl4NnrRoDC1XmEb3JGkrp6Yrkcc458zoa/pN+uHaa1Izob5lJ3ROmRbwvjOF5VeEu56GM5dsJsVDO3eul8Q+RYjZT14KiOFNQYlYy/LmLHfRtUNQpu8VQ== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) by DM4PR12MB8475.namprd12.prod.outlook.com (2603:10b6:8:190::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9160.17; Tue, 30 Sep 2025 14:45:49 +0000 Received: from SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91]) by SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91%2]) with mapi id 15.20.9160.015; Tue, 30 Sep 2025 14:45:49 +0000 From: Joel Fernandes To: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org, dakr@kernel.org, acourbot@nvidia.com Cc: Alistair Popple , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , bjorn3_gh@protonmail.com, Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , David Airlie , Simona Vetter , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , John Hubbard , Joel Fernandes , Timur Tabi , joel@joelfernandes.org, Elle Rhumsaa , Yury Norov , Daniel Almeida , Andrea Righi , nouveau@lists.freedesktop.org Subject: [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths Date: Tue, 30 Sep 2025 10:45:30 -0400 Message-Id: <20250930144537.3559207-3-joelagnelf@nvidia.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20250930144537.3559207-1-joelagnelf@nvidia.com> References: <20250930144537.3559207-1-joelagnelf@nvidia.com> Content-Transfer-Encoding: quoted-printable X-ClientProxiedBy: BN9PR03CA0179.namprd03.prod.outlook.com (2603:10b6:408:f4::34) To SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SN7PR12MB8059:EE_|DM4PR12MB8475:EE_ X-MS-Office365-Filtering-Correlation-Id: f0f14ea3-8762-4c5e-f86d-08de00300bfa X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|7416014|376014; X-Microsoft-Antispam-Message-Info: =?us-ascii?Q?kcORPHhXM5FHQS/vxvrESu3Cpv+J2EUH1YRPf9d3P0ZefJ//xwI2oRSJXtJp?= =?us-ascii?Q?/9f2SNjvoRGNbBPlXZStfXtfeacuM1eo7YxS215AmFHqLtV+LG35aLnEfRg3?= =?us-ascii?Q?AJ0X52/GuighkzqjfhxzKXmglQ2l+yIZXJu7jLpyOsTA8nnPmAQgS6Ia+2bZ?= =?us-ascii?Q?R0m3Mijk6KlAPL1cou+OSKcC6S3xmMnMYw+MOLZfslI9O1Z0fx2uMG6Jii3k?= =?us-ascii?Q?/CdpDwl8scx6qT4IJ7EEvgGHNipxuJWqL9ms6CVSLQr5rkAe0hLTfIC6H1Qx?= =?us-ascii?Q?vd0TUnYtNDFCCBVedkmp6qFKiBGSdE7qq45FxYB1KGBcal3MlClv+Au9Saxy?= =?us-ascii?Q?hLS7UhB4/FtChkhTwuCqbxtr0vYEbR3wvESXaV+YatKMjsqLJJgtw6JG2mcI?= =?us-ascii?Q?Ck+Mp7k0va/FVV35f3bGWvCXG2NuYhOhtUkmaAvk2fykLDD3MEU15q3J6POk?= =?us-ascii?Q?gFPjAfxOCm1hirPe3D0XRQ2ltc+rOsAnUt/eXEVRk1/Jrw5G0eTfp4rJJkIW?= =?us-ascii?Q?oEFO/Ow8fXcNcntWjoI2pEiVJuxRimTtxxOsqshA5omTp3XviTSWqVrFgTc+?= =?us-ascii?Q?6HtmKhvALC9kqITyrsJ2faqAbhHHksSxCpzyETI2zkytBffg8Q4O1GoTOdQz?= =?us-ascii?Q?7qU+jgsbEWDeYMHJac5qg4QNTKc44mh8NcLKwJsMOSu4fmxKrvnCwknGaer+?= =?us-ascii?Q?ZPFMg/tKr+1ijaEDTZ4I7gC8BVDaOxRf7hNn4rpM53424fKudpeAL1WePNTU?= =?us-ascii?Q?BkQv78wrBneHjnd0cTr53aCSeYxnqXawrrzvUg8iFjYYk5NBSz06jOFGfCAs?= =?us-ascii?Q?suj61JrWg/gbOBRzP2ajEXwafNBiIIcV8S1C3CvX2hJyz9hyTeRN0ikqfc5b?= =?us-ascii?Q?wR5/2Vft+hxEV8cLfCdifUYLv30DClxyQmCUjHJFbOfOuQ5iDTXNykrnvgFE?= =?us-ascii?Q?skZnnE9uM2LQS7BgqKsj/DthRKxcUIzRgMjkHycdey0HLBOdLhn3liq546DI?= =?us-ascii?Q?40lHTOMT7KWBQIifgrAidrrJNkDXAQaVYzpnx0CmGv2ofWq6SvWybLXzZJ6r?= =?us-ascii?Q?NClFDWAoWTyzdW2zBb6ERJg4JE/d0/n2ncUcEOUTRC6EzGj8gs5zOVp3yHe8?= =?us-ascii?Q?SvCyknQMf7zXzjXtCw3MkgwK9dDPeIyZOCT4BeIvQAZdZQbpKf/FZXBObUCj?= =?us-ascii?Q?CG4ED6YH7VOhaiC/UgqCG+jtk36qIvHH6Ow//0nz6OaT1kR5OVKErCZsnxJz?= =?us-ascii?Q?31q1nn1j3NprdtJelvFrXaIbcEgXpUcdrP5ZOrs7qh7ajB2Zt/DPoOaPiv/G?= =?us-ascii?Q?0AXzxSGNthzGFPHLfgq58PK36vJFryq/5j4b52gMc8AAWTi5DhEwUyq0uLa7?= =?us-ascii?Q?JSoM0RZA70it7QxgMBcof6iVWsKTgL71TdNfNexMunb7pGk9ZjDYZAvTAvEH?= =?us-ascii?Q?r92U/hY+TnAO4ERo2Bq3qd54oxOgrg8c?= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SN7PR12MB8059.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(366016)(1800799024)(7416014)(376014);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?us-ascii?Q?l2JM2xiO27zw9nNMA2fN/ApA5kJ8fbgcwozpsE32vOTMoa4L7R5HaOujXrxi?= =?us-ascii?Q?Sze4Ey0Tba5AvmH9wiFkthGkc8gjnD5GGT154ZMlD04Dv/aArz1sy1aOVp2I?= =?us-ascii?Q?ocpJJXQD4q7RgOOIiWBS24Ltb/nyMDePNpGe5YsgJRNl9h15TINmTmUqK5CX?= =?us-ascii?Q?MkligwbEaTZnXUaJ3TS4jCH2xgRMG2HX0hw18qNt11b/Tfr6rBpNiKoYZzoJ?= =?us-ascii?Q?31IcTww6YklLyqeASk7GyLYGI+vj1eX1Jhi2GcS0Up6dTpGYfbBx6fkKulfq?= =?us-ascii?Q?zTyvi18iz4CCin164AQ+rMyGjVsfYN4kelUUVdr6gj9423aGmNYHZPjMb62G?= =?us-ascii?Q?EqQ7iz+m4sa28YsHKLnIL39euLrGn2jnJa+MQEJg+TrmQUoef0QSHValFQPK?= =?us-ascii?Q?uLdcJg/cD/AmTOSSPXEGsm8GeMviw6cPaT0AOHM9tbl2gUb0nfUXdcf4Eh7r?= =?us-ascii?Q?+uACu+S6h+nkGgB0BMbd85lsGT1OTD4IHwluk3fXVcIwoyvixjzVZxEHue4J?= =?us-ascii?Q?4qW9ccyJsgaL50gMF1JvFTgxNsOZ8pB4Uuz1MiG9FW8hKsML0rLSbBq25kWE?= =?us-ascii?Q?Fk0ePoXb+t8bsQZvA23Qfj/CzvOeEl9izafi/mm4Zsuq2GNqU9OghqhvvfHi?= =?us-ascii?Q?alLG00tBT/8UBtmOAhT7wYfeXb5eGanq7NOeXV+tkobi+zbFsNmj2GkYkUno?= =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-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: f0f14ea3-8762-4c5e-f86d-08de00300bfa X-MS-Exchange-CrossTenant-AuthSource: SN7PR12MB8059.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Sep 2025 14:45:49.4065 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 43083d15-7273-40c1-b7db-39efd9ccc17a X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: HDzzQ3GPGTfh/joesonRszJ3MY812sX44E1sDNY/OqViHpjx6pwZs5VecQ3k900imykDZoxvZ3hm0xkI7uEu3w== X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM4PR12MB8475 Content-Type: text/plain; charset="utf-8" Previously, bitfields were hardcoded to use u32 as the underlying storage type. Add support for different storage types (u8, u16, u32, u64) to the bitfield macro. New syntax is: struct Name: { ... } Reviewed-by: Elle Rhumsaa Signed-off-by: Joel Fernandes Reviewed-by: Alexandre Courbot --- drivers/gpu/nova-core/bitfield.rs | 210 ++++++++++++++------------- drivers/gpu/nova-core/regs/macros.rs | 16 +- 2 files changed, 119 insertions(+), 107 deletions(-) diff --git a/drivers/gpu/nova-core/bitfield.rs b/drivers/gpu/nova-core/bitf= ield.rs index b1e1c438b8a8..75de1c0fcb3b 100644 --- a/drivers/gpu/nova-core/bitfield.rs +++ b/drivers/gpu/nova-core/bitfield.rs @@ -3,96 +3,99 @@ //! Bitfield library for Rust structures //! //! Support for defining bitfields in Rust structures. Also used by the [`= register!`] macro. -//! -//! # Syntax -//! -//! ```rust -//! use nova_core::bitfield; -//! -//! #[derive(Debug, Clone, Copy, Default)] -//! enum Mode { -//! #[default] -//! Low =3D 0, -//! High =3D 1, -//! Auto =3D 2, -//! } -//! -//! impl TryFrom for Mode { -//! type Error =3D u8; -//! fn try_from(value: u8) -> Result { -//! match value { -//! 0 =3D> Ok(Mode::Low), -//! 1 =3D> Ok(Mode::High), -//! 2 =3D> Ok(Mode::Auto), -//! _ =3D> Err(value), -//! } -//! } -//! } -//! -//! impl From for u32 { -//! fn from(mode: Mode) -> u32 { -//! mode as u32 -//! } -//! } -//! -//! #[derive(Debug, Clone, Copy, Default)] -//! enum State { -//! #[default] -//! Inactive =3D 0, -//! Active =3D 1, -//! } -//! -//! impl From for State { -//! fn from(value: bool) -> Self { -//! if value { State::Active } else { State::Inactive } -//! } -//! } -//! -//! impl From for u32 { -//! fn from(state: State) -> u32 { -//! state as u32 -//! } -//! } -//! -//! bitfield! { -//! struct ControlReg { -//! 3:0 mode as u8 ?=3D> Mode; -//! 7:7 state as bool =3D> 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 ` simply returns the field value casted to , typical= ly `u32`, `u16`, `u8` or -//! `bool`. Note that `bool` fields must have a range of 1 bit. -//! - `as =3D> ` calls ``'s `From::<>` = implementation and returns -//! the result. -//! - `as ?=3D> ` calls ``'s `TryFrom= ::<>` implementation -//! and returns the result. This is useful with fields for which not all= values are valid. -//! + +/// Defines a struct with accessors to access bits within an inner unsigne= d integer. +/// +/// # Syntax +/// +/// ```rust +/// use nova_core::bitfield; +/// +/// #[derive(Debug, Clone, Copy, Default)] +/// enum Mode { +/// #[default] +/// Low =3D 0, +/// High =3D 1, +/// Auto =3D 2, +/// } +/// +/// impl TryFrom for Mode { +/// type Error =3D u8; +/// fn try_from(value: u8) -> Result { +/// match value { +/// 0 =3D> Ok(Mode::Low), +/// 1 =3D> Ok(Mode::High), +/// 2 =3D> Ok(Mode::Auto), +/// _ =3D> Err(value), +/// } +/// } +/// } +/// +/// impl From for u32 { +/// fn from(mode: Mode) -> u32 { +/// mode as u32 +/// } +/// } +/// +/// #[derive(Debug, Clone, Copy, Default)] +/// enum State { +/// #[default] +/// Inactive =3D 0, +/// Active =3D 1, +/// } +/// +/// impl From for State { +/// fn from(value: bool) -> Self { +/// if value { State::Active } else { State::Inactive } +/// } +/// } +/// +/// impl From for u32 { +/// fn from(state: State) -> u32 { +/// state as u32 +/// } +/// } +/// +/// bitfield! { +/// struct ControlReg(u32) { +/// 3:0 mode as u8 ?=3D> Mode; +/// 7:7 state as bool =3D> State; +/// } +/// } +/// ``` +/// +/// This generates a struct with: +/// - Field accessors: `mode()`, `state()`, etc. +/// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining = with builder pattern). +/// Note that the compiler will error out if the size of the setter's ar= g exceeds the +/// struct's storage size. +/// - Debug and Default implementations. +/// +/// Fields are defined as follows: +/// +/// - `as ` simply returns the field value casted to , typical= ly `u32`, `u16`, `u8` or +/// `bool`. Note that `bool` fields must have a range of 1 bit. +/// - `as =3D> ` calls ``'s `From::<>` = implementation and returns +/// the result. +/// - `as ?=3D> ` calls ``'s `TryFrom= ::<>` 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)* }) =3D> { - bitfield!(@core $name $(, $comment)? { $($fields)* }); + (struct $name:ident($storage:ty) $(, $comment:literal)? { $($fields:tt= )* }) =3D> { + bitfield!(@core $name $storage $(, $comment)? { $($fields)* }); }; =20 // All rules below are helpers. =20 // Defines the wrapper `$name` type, as well as its relevant implement= ations (`Debug`, // `Default`, `BitOr`, and conversion to the value type) and field acc= essor methods. - (@core $name:ident $(, $comment:literal)? { $($fields:tt)* }) =3D> { + (@core $name:ident $storage:ty $(, $comment:literal)? { $($fields:tt)*= }) =3D> { $( #[doc=3D$comment] )? #[repr(transparent)] #[derive(Clone, Copy)] - pub(crate) struct $name(u32); + pub(crate) struct $name($storage); =20 impl ::core::ops::BitOr for $name { type Output =3D Self; @@ -102,20 +105,20 @@ fn bitor(self, rhs: Self) -> Self::Output { } } =20 - impl ::core::convert::From<$name> for u32 { - fn from(val: $name) -> u32 { + impl ::core::convert::From<$name> for $storage { + fn from(val: $name) -> $storage { val.0 } } =20 - bitfield!(@fields_dispatcher $name { $($fields)* }); + bitfield!(@fields_dispatcher $name $storage { $($fields)* }); }; =20 // Captures the fields and passes them to all the implementers that re= quire 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 { + (@fields_dispatcher $name:ident $storage:ty { $($hi:tt:$lo:tt $field:ident as $type:tt $(?=3D> $try_into_type:ty)? $(=3D> $into_type:ty)? @@ -124,7 +127,7 @@ fn from(val: $name) -> u32 { )* } ) =3D> { - bitfield!(@field_accessors $name { + bitfield!(@field_accessors $name $storage { $( $hi:$lo $field as $type $(?=3D> $try_into_type)? @@ -139,7 +142,7 @@ fn from(val: $name) -> u32 { =20 // Defines all the field getter/setter methods for `$name`. ( - @field_accessors $name:ident { + @field_accessors $name:ident $storage:ty { $($hi:tt:$lo:tt $field:ident as $type:tt $(?=3D> $try_into_type:ty)? $(=3D> $into_type:ty)? @@ -155,7 +158,7 @@ fn from(val: $name) -> u32 { #[allow(dead_code)] impl $name { $( - bitfield!(@field_accessor $name $hi:$lo $field as $type + bitfield!(@field_accessor $name $storage, $hi:$lo $field as $t= ype $(?=3D> $try_into_type)? $(=3D> $into_type)? $(, $comment)? @@ -189,11 +192,11 @@ impl $name { =20 // Catches fields defined as `bool` and convert them into a boolean va= lue. ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool =3D= > $into_type:ty + @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:iden= t as bool =3D> $into_type:ty $(, $comment:literal)?; ) =3D> { bitfield!( - @leaf_accessor $name $hi:$lo $field + @leaf_accessor $name $storage, $hi:$lo $field { |f| <$into_type>::from(if f !=3D 0 { true } else { false }) } $into_type =3D> $into_type $(, $comment)?; ); @@ -201,17 +204,17 @@ impl $name { =20 // Shortcut for fields defined as `bool` without the `=3D>` syntax. ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool $(,= $comment:literal)?; + @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:iden= t as bool $(, $comment:literal)?; ) =3D> { - bitfield!(@field_accessor $name $hi:$lo $field as bool =3D> bool $= (, $comment)?;); + bitfield!(@field_accessor $name $storage, $hi:$lo $field as bool = =3D> bool $(, $comment)?;); }; =20 // Catches the `?=3D>` syntax for non-boolean fields. ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt= ?=3D> $try_into_type:ty + @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:iden= t as $type:tt ?=3D> $try_into_type:ty $(, $comment:literal)?; ) =3D> { - bitfield!(@leaf_accessor $name $hi:$lo $field + bitfield!(@leaf_accessor $name $storage, $hi:$lo $field { |f| <$try_into_type>::try_from(f as $type) } $try_into_type = =3D> ::core::result::Result< $try_into_type, @@ -222,29 +225,38 @@ impl $name { =20 // Catches the `=3D>` syntax for non-boolean fields. ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt= =3D> $into_type:ty + @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:iden= t as $type:tt =3D> $into_type:ty $(, $comment:literal)?; ) =3D> { - bitfield!(@leaf_accessor $name $hi:$lo $field + bitfield!(@leaf_accessor $name $storage, $hi:$lo $field { |f| <$into_type>::from(f as $type) } $into_type =3D> $into_t= ype $(, $comment)?;); }; =20 // Shortcut for non-boolean fields defined without the `=3D>` or `?=3D= >` syntax. ( - @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt + @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:iden= t as $type:tt $(, $comment:literal)?; ) =3D> { - bitfield!(@field_accessor $name $hi:$lo $field as $type =3D> $type= $(, $comment)?;); + bitfield!(@field_accessor $name $storage, $hi:$lo $field as $type = =3D> $type $(, $comment)?;); }; =20 // Generates the accessor methods for a single field. ( - @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident + @leaf_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident { $process:expr } $to_type:ty =3D> $res_type:ty $(, $comment:l= iteral)?; ) =3D> { ::kernel::macros::paste!( const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive =3D= $lo..=3D$hi; - const [<$field:upper _MASK>]: u32 =3D ((((1 << $hi) - 1) << 1) + 1= ) - ((1 << $lo) - 1); + const [<$field:upper _MASK>]: $storage =3D { + // Generate mask for shifting + match ::core::mem::size_of::<$storage>() { + 1 =3D> ::kernel::bits::genmask_u8($lo..=3D$hi) as $storage, + 2 =3D> ::kernel::bits::genmask_u16($lo..=3D$hi) as $storag= e, + 4 =3D> ::kernel::bits::genmask_u32($lo..=3D$hi) as $storag= e, + 8 =3D> ::kernel::bits::genmask_u64($lo..=3D$hi) as $storag= e, + _ =3D> ::kernel::build_error!("Unsupported storage type si= ze") + } + }; const [<$field:upper _SHIFT>]: u32 =3D Self::[<$field:upper _MASK>= ].trailing_zeros(); ); =20 @@ -255,7 +267,7 @@ impl $name { #[inline(always)] pub(crate) fn $field(self) -> $res_type { ::kernel::macros::paste!( - const MASK: u32 =3D $name::[<$field:upper _MASK>]; + const MASK: $storage =3D $name::[<$field:upper _MASK>]; const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; ); let field =3D ((self.0 & MASK) >> SHIFT); @@ -270,9 +282,9 @@ pub(crate) fn $field(self) -> $res_type { )? #[inline(always)] pub(crate) fn [](mut self, value: $to_type) -> Self { - const MASK: u32 =3D $name::[<$field:upper _MASK>]; + const MASK: $storage =3D $name::[<$field:upper _MASK>]; const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; - let value =3D (u32::from(value) << SHIFT) & MASK; + let value =3D (<$storage>::from(value) << SHIFT) & MASK; self.0 =3D (self.0 & !MASK) | value; =20 self diff --git a/drivers/gpu/nova-core/regs/macros.rs b/drivers/gpu/nova-core/r= egs/macros.rs index 945d15a2c529..ffd7d5cb73bb 100644 --- a/drivers/gpu/nova-core/regs/macros.rs +++ b/drivers/gpu/nova-core/regs/macros.rs @@ -276,25 +276,25 @@ pub(crate) trait RegisterBase { macro_rules! register { // Creates a register at a fixed offset of the MMIO space. ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)*= } ) =3D> { - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); register!(@io_fixed $name @ $offset); }; =20 // Creates an alias register of fixed offset register `alias` with its= own fields. ($name:ident =3D> $alias:ident $(, $comment:literal)? { $($fields:tt)*= } ) =3D> { - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); register!(@io_fixed $name @ $alias::OFFSET); }; =20 // Creates a register at a relative offset from a base address provide= r. ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $= ($fields:tt)* } ) =3D> { - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); register!(@io_relative $name @ $base [ $offset ]); }; =20 // Creates an alias register of relative offset register `alias` with = its own fields. ($name:ident =3D> $base:ty [ $alias:ident ] $(, $comment:literal)? { $= ($fields:tt)* }) =3D> { - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); register!(@io_relative $name @ $base [ $alias::OFFSET ]); }; =20 @@ -305,7 +305,7 @@ macro_rules! register { } ) =3D> { static_assert!(::core::mem::size_of::() <=3D $stride); - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); register!(@io_array $name @ $offset [ $size ; $stride ]); }; =20 @@ -326,7 +326,7 @@ macro_rules! register { $(, $comment:literal)? { $($fields:tt)* } ) =3D> { static_assert!(::core::mem::size_of::() <=3D $stride); - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); register!(@io_relative_array $name @ $base [ $offset [ $size ; $st= ride ] ]); }; =20 @@ -348,7 +348,7 @@ macro_rules! register { } ) =3D> { static_assert!($idx < $alias::SIZE); - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); register!(@io_relative $name @ $base [ $alias::OFFSET + $idx * $al= ias::STRIDE ] ); }; =20 @@ -357,7 +357,7 @@ macro_rules! register { // to avoid it being interpreted in place of the relative register arr= ay alias rule. ($name:ident =3D> $alias:ident [ $idx:expr ] $(, $comment:literal)? { = $($fields:tt)* }) =3D> { static_assert!($idx < $alias::SIZE); - bitfield!(struct $name $(, $comment)? { $($fields)* } ); + bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); register!(@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE= ); }; =20 --=20 2.34.1 From nobody Thu Oct 2 22:52:49 2025 Received: from SA9PR02CU001.outbound.protection.outlook.com (mail-southcentralusazon11013005.outbound.protection.outlook.com [40.93.196.5]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D6F3A305979; Tue, 30 Sep 2025 14:46:01 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.196.5 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243563; cv=fail; b=Jobho5fylTfdLhS6ODCLxNjMyVfW43shcO35Bq1FPMiSqYOM+WXzVxWMC30NX/x2dK5ngE0d5F0pxwLDKUtlZ+Jrl1+/K60VRDMqbrk9LcYv9/l6FZ85rNtYg41XnYnfhcxNtVlxnu6VCtu/0MtHhQx5lHvc3Lmo6+a2dlU3ZFw= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243563; c=relaxed/simple; bh=nOnRd2EX88BCR4MT9YisoEXoBcPGYW4ZBGP6WnoXDE0=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: Content-Type:MIME-Version; b=UpHyQMEkvx04gFqKz7ab/9YViXPHw1VOPwXe/Fc9CVXQBiYBkqAinniDgtAHhGK0GGn1a5vV1Bg6tBi9Iyl7u6F+2CEk+GOtAuqc6olfLHgSAx72AQRrkD7OlaRfsy8fV+xT6Hd4sH5FlcLl184ukNVPXQnt2CROHKYq/FMC6Xs= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com; spf=fail smtp.mailfrom=nvidia.com; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b=UBz6WQZn; arc=fail smtp.client-ip=40.93.196.5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com Authentication-Results: smtp.subspace.kernel.org; spf=fail smtp.mailfrom=nvidia.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b="UBz6WQZn" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=LlR1to6iF0fLV8IL9DyAk0D+oDXAygnPGiuPYa2DQNl9M/MWkmwIpKB0Z4/1U+aVdAfyBPak96++BPFEFauH4ctBIYO9jL6pRC8b6doomhTm5gSpC93EkGdyfnLXCTLwr/UHVExez9X4e8jPUfrc8Ktv0zD4JzpDjZ+HA/QYO4vTOVhhIhgDVQ4JSHB3qFfdk9q6nNzCh72JlsfRyW449O6ehI0lAEWNwSHtfdWoakF/pCzdCJUL9yfuZVFL+2grlpuC9C0yWfiTXrhiLTkBGKT+NYBl4FNleEODQWyJBLxCeSxB07fJtqM5h8NkTp78e12NQWU1skVfsb4rUejQ5w== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=7WtHuucVr0mioG8hMK3CYr/acoECPocCMbDaWYL6yQc=; b=D1RdjsXcBxNNKIMHANA00BnpLX2sOXjHBRhmG8XsUPGmIgmRO0R2veZRPQ127D7x92OA+Y6JWIe2mjzIxZ9T8kJsvfowddCOAYDRKgvy1s5kIcYQ4cUerEfU7Au7KVDaFt4PBCVzQfMWAy2y0BjGTDcujazJDfC05nbuhYIZ/C9M5WOCrb+lhLtYmA2ReziILupCcAdL01kIKuR6vGVXUZt55WpQX1CjeKbc9455qyz671mE+BxiFUz5/f3LfilpZSG9WBvEZ22ATu8ExNn1dMWzCeQdVi051x/ZRtUGcTA4iab3arszcVodVoZ8YvRLZ/kLcw0BjhkyXSkET/a6mQ== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=nvidia.com; dmarc=pass action=none header.from=nvidia.com; dkim=pass header.d=nvidia.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=Nvidia.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=7WtHuucVr0mioG8hMK3CYr/acoECPocCMbDaWYL6yQc=; b=UBz6WQZn+b4+ZeNX6wfWVw/gt7C794NErMWvb2p0iM9lQM/PKlHnGWmLXgAdmf18EO7PHTBA/XO/aOYUlHYG0kYwfCNXyn9DQhl/6iD1d62r4JxAQFUxVbHI6DwVJ6QfcIzG8a4MaAkhZ81ShkLOX4680b3/fKepcVs4mPphVp+iZxFkT2zv3h9oGmq3iAkP+Gut5Uv+wsM9Vh+qTpaAS4NPE8ollh8aai/9GQMkPIOvwQWfEH7EoV3yULwE6OmJ2OQF/PfN60SpQyG3LcD8ksnA/Cc3m4USZ6zTVQEOhQe2bOLMjVGszmxb5TFPXIsWTUbkjf79NM+joJ3NfYZojQ== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) by DM4PR12MB8475.namprd12.prod.outlook.com (2603:10b6:8:190::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9160.17; Tue, 30 Sep 2025 14:45:51 +0000 Received: from SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91]) by SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91%2]) with mapi id 15.20.9160.015; Tue, 30 Sep 2025 14:45:51 +0000 From: Joel Fernandes To: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org, dakr@kernel.org, acourbot@nvidia.com Cc: Alistair Popple , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , bjorn3_gh@protonmail.com, Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , David Airlie , Simona Vetter , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , John Hubbard , Joel Fernandes , Timur Tabi , joel@joelfernandes.org, Elle Rhumsaa , Yury Norov , Daniel Almeida , Andrea Righi , nouveau@lists.freedesktop.org Subject: [PATCH v5 3/9] nova-core: bitfield: Add support for custom visiblity Date: Tue, 30 Sep 2025 10:45:31 -0400 Message-Id: <20250930144537.3559207-4-joelagnelf@nvidia.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20250930144537.3559207-1-joelagnelf@nvidia.com> References: <20250930144537.3559207-1-joelagnelf@nvidia.com> Content-Transfer-Encoding: quoted-printable X-ClientProxiedBy: BN9PR03CA0630.namprd03.prod.outlook.com (2603:10b6:408:106::35) To SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SN7PR12MB8059:EE_|DM4PR12MB8475:EE_ X-MS-Office365-Filtering-Correlation-Id: 50d35806-395c-4e1b-cffe-08de00300d22 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|7416014|376014; X-Microsoft-Antispam-Message-Info: =?us-ascii?Q?3sz4nkNNfwrM/Ea5Xg+DQVG+vlEFzAKS6l2JTIYnJWnOsXIta6dSg4fk/jzB?= =?us-ascii?Q?E9phsQv34UoP++0/wcstKO8/5SdR44IAs3/BN020VFsfXeYO5K+LEBJ5SjSd?= =?us-ascii?Q?A2Q9e62UR3BSChcuNqE2F7AhxV5q7rl+Gh/LOINrnhkca8X3mp6HPWlavv4n?= =?us-ascii?Q?lQ7SwKJAE0iNTKtWrg1JF2l7YPC3Ac7vE92prh+1YQipVfzgVpXpMPwSkMNC?= =?us-ascii?Q?JGNlOyzWSE3J+YDAQ7BCPcrs1WSzn2Jix0vfLQGyHLg+D52BkORcPNAvDXYd?= =?us-ascii?Q?i0OOnTjHdLKeUChOpzslHmyGFR6Y72e0G4iJ/C+IsG97s4Oe3Wj8V6J+1yof?= =?us-ascii?Q?XFMZAeTTndC1Ri5uMSSNlheXEw/TSLdsfRTY9kRLc8yVK5zeGGliU2X7QHsA?= =?us-ascii?Q?RAr8eAezhuSSuT9+YLNVP+EfXzrPHnt2T0JmNNr0NRHCeVePynE8yzpT+aW7?= =?us-ascii?Q?ShjgQdwXA8PGMV3r4kxE/2oi3+r7GGrzrPVTMPkU0go3RcVoHaMeonJwVYbI?= =?us-ascii?Q?ItfNUf9r4jvWMwSBXYotNhuOghOihIRSXh8PrjDg+oP8kyO8YDMJeqAFgBse?= =?us-ascii?Q?KThfHY6LzHSuNmgLzq/V3dtDqKPd3w1oO3FsvloJC21ksWplzCqF9Oi1gBJG?= =?us-ascii?Q?bdbTxJR7W0g0LDkuEN8xxTEZBgB35UpHnoRhf9VROCVifdghenyEK4iZSEl7?= =?us-ascii?Q?SlOC/h0EvuOQAJRKwqO10jyjiN+BhzWlzMXztUTXEsQLxaXZ0geoVZyFhUlc?= =?us-ascii?Q?WrG9jWl5HMSAf7lmdbRhaWW540jOgZixaWTxSkeIvrNF3UKPu9E2jDZ0cmYv?= =?us-ascii?Q?QrsRTvn8LqWDMb+OAiqxWgdOzNDkP9OMlj0sXBsBgxe2gzADZ8DSLF71okVt?= =?us-ascii?Q?OA5dzkuoU3mcY/TpsvKps3EbzwwI2gL45+w8LCvnwIJHGrpY8NjDr7dUtk7s?= =?us-ascii?Q?j/1msoaOlz1osu/oEGGGKGfVpbM37tK8NRgsNZpHz/Pjl/GU42vs8UiZaGDl?= =?us-ascii?Q?ZgEK5GTRIQ1lSgNtStVc5IzQhqyt6YpKXPlW/Q/hDz60nXmD2t+NChVYThDx?= =?us-ascii?Q?oOKloKdTISpg0Vmxfx/gHvvoOtj94uK7q+dfpBIiUaJqtRT2CcM13MPMT3IL?= =?us-ascii?Q?9kLOw2+ZFfp5HUouDpj5o3SFujcIuql7Qj91sOD8jLxDt4puloLQuhozvN3V?= =?us-ascii?Q?N6Jqbb3Ti2vD78fr1kdwMHcDbSYMmA1g9Euqt0/GiZVcgwgqVogijabD6naS?= =?us-ascii?Q?yx3uKQx+gMY4eeQkB/j/mw18SaUG+h40FHjy0qGSzT2fp6+0CE1Iw+Gi9S/x?= =?us-ascii?Q?d96e4KnWMj3iOzoAI7WYksftSe6QkXEwu9mblQc2zPG4nkE3N6A5aw88XY2e?= =?us-ascii?Q?RaN725bZEjDq8loNez3aZsDpyqX9Ms0mAYp6BbCVObA20esu0nh9pCTWkVAD?= =?us-ascii?Q?E5dztrBjgjbJB0nNnNPTcvW7Jeosk7pP?= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SN7PR12MB8059.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(366016)(1800799024)(7416014)(376014);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?us-ascii?Q?Ef5EaXDPJihD3mG3ufJU7VypVh0iAqkvfFbxL36dm+geMWtaxYDKyYbjUqrM?= =?us-ascii?Q?PAOR0bm5AuxPbqr2OUxGqUpgYw2dFRXxaoHxiP6ouEhH5yqsZeX6haiArwJr?= =?us-ascii?Q?6wH+QgylH/NVQoOl2rppPx3Foqo8j1+Cf8vxFNGIpPEEHrAU8JX9TtTechlv?= =?us-ascii?Q?CvwyYwBmxGF2HovkN2qOAnKbH5x9LAOKZyLlP3R9rEkjUX2GrUD/YrfadB/9?= =?us-ascii?Q?57qo+U71DEB9hPmf/L+mycn0fX+lXuLU36667XELRPXc0fYgXgnB/h0f8nV8?= =?us-ascii?Q?u2jyy+AmErJXxmOeTfMhg1hWuX+1l/ZLwwWhAnRYViTGf6Oo+82BdRL22PiB?= =?us-ascii?Q?19yOA79MqIpw4QGQJYMhIsrR9OayZpZ6YXBrZpRazLiKlRYqG+cKhoSs3SWB?= =?us-ascii?Q?0t922uQv1drCxHQY8I7lWzeK7M4wBSlztK1qiEIM+FuDb0AdwleMw2qiSJqn?= =?us-ascii?Q?03b7DBlH+hBX85EkybFFebr6+ZTJDqW96sHNKAGIbC4xtzOqayqokgh+E76j?= =?us-ascii?Q?FP7dLlNF5Qud8C/I/g2Z48vqIDYV7aBHHQAiFu4D/TTjyZZc5Yd4clQ+V2IJ?= =?us-ascii?Q?3guG+6msQYd4Hx+5hrC0/h1DkjWlDFxEQX1iUPvkEahW4ku2ODeFhs2MTY1T?= =?us-ascii?Q?PkNCkDzZd/HHWtaFfrpTXyLIRBTXpYv7ZfpVP8LZbMuy0y9UMOplKN9262sh?= =?us-ascii?Q?UJYTirYpJ2qXEsFocFlb9preRfvwluNeJkFRByLkJ5otxID/afl9YAtIYEut?= =?us-ascii?Q?ZqkLmm+v2hMku7YE9QYnXXBN1lya0f3V4Hat6z8HqtkXWaf5aubAiDTDGSMU?= =?us-ascii?Q?O2MkiJAdtY4WrvyyiOMDEvVCbX3KtyQHVjfVdJirPO1LWt/OR0I6Gw5ZWOAe?= =?us-ascii?Q?BtPvmCwHVvZmbNoWOrSc141+gPLX8yxzJPn7v6r5MOCZD/DtFihLr7gTR8mr?= =?us-ascii?Q?pVqwgijy/zj6h34f8yY57IkJP/4l3Z+wNMqNSmcYC6qOagMB5x/UQStWwozp?= =?us-ascii?Q?fCzyesCT4d+eEUoOzdbPh8UWTc4htgUH5Nv1Oahgp+OzeK07yS+rlMKZp9MR?= =?us-ascii?Q?+qPgs+8EQ77M4DVC19pwYzfnJUpVMnai5OuUKC2/KYZ8eZz0p/5zEvQstEno?= =?us-ascii?Q?MYPBUFsyA3cbmD24Xr7u7x/NeLUTvQ0FLQMRuzoA2AZF72x9X9Q+ZXo2MFtF?= =?us-ascii?Q?/sjYft8ttq7H90ZknjDfWDbE178YJV0KMhNgaKbH2gD/M0+ofa+d8yl3Uk1J?= =?us-ascii?Q?DmqDjkkBCQDpFlNF8hS0JIz7cDXen3AJbitHlsWeYmyzQD25DTonCthBnM9P?= =?us-ascii?Q?IOvZmJX9j3yy3OHHv8xqDdfUf5wdRx0ojAIhe68wjDdoE87upjSw6wvg6a5K?= =?us-ascii?Q?kM3m8g+WbKP8RnPbaqk5iPNW/dWmuYgFnpIhk+yc50w58n4HdvkuviCRMu0y?= =?us-ascii?Q?OLWqFy0z6oj6W81ZvOkqOb6hBzGVNXKIXVKfjaQpjXlBW3y31Nkiii1EtpDp?= =?us-ascii?Q?+4b8p7rOm6/RuPoGz8zzZUEq5LUXeCcomd/fBwGXty+kxiw3gqJX07VrEBKK?= =?us-ascii?Q?rpEHEyI0m8YL6KWFcOdki6QyVXHc7wUrMv3R37+V?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 50d35806-395c-4e1b-cffe-08de00300d22 X-MS-Exchange-CrossTenant-AuthSource: SN7PR12MB8059.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Sep 2025 14:45:51.3307 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 43083d15-7273-40c1-b7db-39efd9ccc17a X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: MoMSOYX511cPj6YBNR/6xqhnpomYLrrT6Cy4h/jX7F5bzGVIx5ByTIDVgWbilWsP30TaI2MAMdwalMsVaEmkJg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM4PR12MB8475 Content-Type: text/plain; charset="utf-8" Add support for custom visiblity to allow for users to control visibility of the structure and helpers. Reviewed-by: Alexandre Courbot Reviewed-by: Elle Rhumsaa Signed-off-by: Joel Fernandes --- drivers/gpu/nova-core/bitfield.rs | 49 +++++++++++++++------------- drivers/gpu/nova-core/regs/macros.rs | 16 ++++----- 2 files changed, 34 insertions(+), 31 deletions(-) diff --git a/drivers/gpu/nova-core/bitfield.rs b/drivers/gpu/nova-core/bitf= ield.rs index 75de1c0fcb3b..cbedbb0078f6 100644 --- a/drivers/gpu/nova-core/bitfield.rs +++ b/drivers/gpu/nova-core/bitfield.rs @@ -57,7 +57,7 @@ /// } /// /// bitfield! { -/// struct ControlReg(u32) { +/// pub struct ControlReg(u32) { /// 3:0 mode as u8 ?=3D> Mode; /// 7:7 state as bool =3D> State; /// } @@ -71,6 +71,9 @@ /// struct's storage size. /// - Debug and Default implementations. /// +/// Note: Field accessors and setters inherit the same visibility as the s= truct itself. +/// In the example above, both `mode()` and `set_mode()` methods will be `= pub`. +/// /// Fields are defined as follows: /// /// - `as ` simply returns the field value casted to , typical= ly `u32`, `u16`, `u8` or @@ -81,21 +84,21 @@ /// 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($storage:ty) $(, $comment:literal)? { $($fields:tt= )* }) =3D> { - bitfield!(@core $name $storage $(, $comment)? { $($fields)* }); + ($vis:vis struct $name:ident($storage:ty) $(, $comment:literal)? { $($= fields:tt)* }) =3D> { + bitfield!(@core $vis $name $storage $(, $comment)? { $($fields)* }= ); }; =20 // All rules below are helpers. =20 // Defines the wrapper `$name` type, as well as its relevant implement= ations (`Debug`, // `Default`, `BitOr`, and conversion to the value type) and field acc= essor methods. - (@core $name:ident $storage:ty $(, $comment:literal)? { $($fields:tt)*= }) =3D> { + (@core $vis:vis $name:ident $storage:ty $(, $comment:literal)? { $($fi= elds:tt)* }) =3D> { $( #[doc=3D$comment] )? #[repr(transparent)] #[derive(Clone, Copy)] - pub(crate) struct $name($storage); + $vis struct $name($storage); =20 impl ::core::ops::BitOr for $name { type Output =3D Self; @@ -111,14 +114,14 @@ fn from(val: $name) -> $storage { } } =20 - bitfield!(@fields_dispatcher $name $storage { $($fields)* }); + bitfield!(@fields_dispatcher $vis $name $storage { $($fields)* }); }; =20 // Captures the fields and passes them to all the implementers that re= quire 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 $storage:ty { + (@fields_dispatcher $vis:vis $name:ident $storage:ty { $($hi:tt:$lo:tt $field:ident as $type:tt $(?=3D> $try_into_type:ty)? $(=3D> $into_type:ty)? @@ -127,7 +130,7 @@ fn from(val: $name) -> $storage { )* } ) =3D> { - bitfield!(@field_accessors $name $storage { + bitfield!(@field_accessors $vis $name $storage { $( $hi:$lo $field as $type $(?=3D> $try_into_type)? @@ -142,7 +145,7 @@ fn from(val: $name) -> $storage { =20 // Defines all the field getter/setter methods for `$name`. ( - @field_accessors $name:ident $storage:ty { + @field_accessors $vis:vis $name:ident $storage:ty { $($hi:tt:$lo:tt $field:ident as $type:tt $(?=3D> $try_into_type:ty)? $(=3D> $into_type:ty)? @@ -158,7 +161,7 @@ fn from(val: $name) -> $storage { #[allow(dead_code)] impl $name { $( - bitfield!(@field_accessor $name $storage, $hi:$lo $field as $t= ype + bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field = as $type $(?=3D> $try_into_type)? $(=3D> $into_type)? $(, $comment)? @@ -192,11 +195,11 @@ impl $name { =20 // Catches fields defined as `bool` and convert them into a boolean va= lue. ( - @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:iden= t as bool =3D> $into_type:ty + @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $f= ield:ident as bool =3D> $into_type:ty $(, $comment:literal)?; ) =3D> { bitfield!( - @leaf_accessor $name $storage, $hi:$lo $field + @leaf_accessor $vis $name $storage, $hi:$lo $field { |f| <$into_type>::from(if f !=3D 0 { true } else { false }) } $into_type =3D> $into_type $(, $comment)?; ); @@ -204,17 +207,17 @@ impl $name { =20 // Shortcut for fields defined as `bool` without the `=3D>` syntax. ( - @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:iden= t as bool $(, $comment:literal)?; + @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $f= ield:ident as bool $(, $comment:literal)?; ) =3D> { - bitfield!(@field_accessor $name $storage, $hi:$lo $field as bool = =3D> bool $(, $comment)?;); + bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as b= ool =3D> bool $(, $comment)?;); }; =20 // Catches the `?=3D>` syntax for non-boolean fields. ( - @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:iden= t as $type:tt ?=3D> $try_into_type:ty + @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $f= ield:ident as $type:tt ?=3D> $try_into_type:ty $(, $comment:literal)?; ) =3D> { - bitfield!(@leaf_accessor $name $storage, $hi:$lo $field + bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field { |f| <$try_into_type>::try_from(f as $type) } $try_into_type = =3D> ::core::result::Result< $try_into_type, @@ -225,24 +228,24 @@ impl $name { =20 // Catches the `=3D>` syntax for non-boolean fields. ( - @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:iden= t as $type:tt =3D> $into_type:ty + @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $f= ield:ident as $type:tt =3D> $into_type:ty $(, $comment:literal)?; ) =3D> { - bitfield!(@leaf_accessor $name $storage, $hi:$lo $field + bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field { |f| <$into_type>::from(f as $type) } $into_type =3D> $into_t= ype $(, $comment)?;); }; =20 // Shortcut for non-boolean fields defined without the `=3D>` or `?=3D= >` syntax. ( - @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:iden= t as $type:tt + @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $f= ield:ident as $type:tt $(, $comment:literal)?; ) =3D> { - bitfield!(@field_accessor $name $storage, $hi:$lo $field as $type = =3D> $type $(, $comment)?;); + bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as $= type =3D> $type $(, $comment)?;); }; =20 // Generates the accessor methods for a single field. ( - @leaf_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident + @leaf_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $fi= eld:ident { $process:expr } $to_type:ty =3D> $res_type:ty $(, $comment:l= iteral)?; ) =3D> { ::kernel::macros::paste!( @@ -265,7 +268,7 @@ impl $name { #[doc=3D$comment] )? #[inline(always)] - pub(crate) fn $field(self) -> $res_type { + $vis fn $field(self) -> $res_type { ::kernel::macros::paste!( const MASK: $storage =3D $name::[<$field:upper _MASK>]; const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; @@ -281,7 +284,7 @@ pub(crate) fn $field(self) -> $res_type { #[doc=3D$comment] )? #[inline(always)] - pub(crate) fn [](mut self, value: $to_type) -> Self { + $vis fn [](mut self, value: $to_type) -> Self { const MASK: $storage =3D $name::[<$field:upper _MASK>]; const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; let value =3D (<$storage>::from(value) << SHIFT) & MASK; diff --git a/drivers/gpu/nova-core/regs/macros.rs b/drivers/gpu/nova-core/r= egs/macros.rs index ffd7d5cb73bb..c0a5194e8d97 100644 --- a/drivers/gpu/nova-core/regs/macros.rs +++ b/drivers/gpu/nova-core/regs/macros.rs @@ -276,25 +276,25 @@ pub(crate) trait RegisterBase { macro_rules! register { // Creates a register at a fixed offset of the MMIO space. ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)*= } ) =3D> { - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); + bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); register!(@io_fixed $name @ $offset); }; =20 // Creates an alias register of fixed offset register `alias` with its= own fields. ($name:ident =3D> $alias:ident $(, $comment:literal)? { $($fields:tt)*= } ) =3D> { - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); + bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); register!(@io_fixed $name @ $alias::OFFSET); }; =20 // Creates a register at a relative offset from a base address provide= r. ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $= ($fields:tt)* } ) =3D> { - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); + bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); register!(@io_relative $name @ $base [ $offset ]); }; =20 // Creates an alias register of relative offset register `alias` with = its own fields. ($name:ident =3D> $base:ty [ $alias:ident ] $(, $comment:literal)? { $= ($fields:tt)* }) =3D> { - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); + bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); register!(@io_relative $name @ $base [ $alias::OFFSET ]); }; =20 @@ -305,7 +305,7 @@ macro_rules! register { } ) =3D> { static_assert!(::core::mem::size_of::() <=3D $stride); - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); + bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); register!(@io_array $name @ $offset [ $size ; $stride ]); }; =20 @@ -326,7 +326,7 @@ macro_rules! register { $(, $comment:literal)? { $($fields:tt)* } ) =3D> { static_assert!(::core::mem::size_of::() <=3D $stride); - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); + bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); register!(@io_relative_array $name @ $base [ $offset [ $size ; $st= ride ] ]); }; =20 @@ -348,7 +348,7 @@ macro_rules! register { } ) =3D> { static_assert!($idx < $alias::SIZE); - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); + bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); register!(@io_relative $name @ $base [ $alias::OFFSET + $idx * $al= ias::STRIDE ] ); }; =20 @@ -357,7 +357,7 @@ macro_rules! register { // to avoid it being interpreted in place of the relative register arr= ay alias rule. ($name:ident =3D> $alias:ident [ $idx:expr ] $(, $comment:literal)? { = $($fields:tt)* }) =3D> { static_assert!($idx < $alias::SIZE); - bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } ); + bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); register!(@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE= ); }; =20 --=20 2.34.1 From nobody Thu Oct 2 22:52:49 2025 Received: from SA9PR02CU001.outbound.protection.outlook.com (mail-southcentralusazon11013005.outbound.protection.outlook.com [40.93.196.5]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 23D9030649C; Tue, 30 Sep 2025 14:46:04 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.196.5 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243566; cv=fail; b=nsWqUj7FFV9/t5UDPcOZkzdr3+6jemmbsxMug7XmyuMXl49zjgxm/xKalF5NjB+S87S4QBsox3prg4ykvJnwNbqiJGN+E8C6uXzjVCVzoGv5DlUxKh7PmL1/Pz5qtLwT16ORl2fBU+L3J3IsjKgQu/fxq2sjJJcqXJE1CcBP2uM= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243566; c=relaxed/simple; bh=PiA9DdUO20ihmRYbX+HZjv376Xoswbeoiw4u/k8Byx4=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: Content-Type:MIME-Version; b=giZxlwx6XVGF3aD2nqNjG8EGcnzg9B8azCxVVPCcF07RX/x0X/mpJE8YqJVilK/kr7pCmiHGrPGA9y9XyDZ8lNZ6C+M/hoFXOaEigzYIwKUWoEKitIfDSMPNMuBzZovQ4n5PKcqOTkpiqvhKpPMqcmWBaabU9HoemfTJmiGanJg= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com; spf=fail smtp.mailfrom=nvidia.com; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b=gA8zfgFs; arc=fail smtp.client-ip=40.93.196.5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com Authentication-Results: smtp.subspace.kernel.org; spf=fail smtp.mailfrom=nvidia.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b="gA8zfgFs" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=vNZOAvQ65XVyG0lJSaJ44wA+ToUc5APjnCM4Mc1DRLAbERXXIRDTDXbnCVeHEOHrh/KcU9Pqhzu6Phxthp0cOIJd230irm/DxJcJ7g9FNBVv7oaviFK5D69IefjQYmXo5DswxKF7M1T+rePA/G5/h98IbqKffSh0TUdsXnFqauM5dvNfkt20Kvga64UJwgUC+BgnCUNGAyO0k1CuuWyzC8BUdA8INg4OmiTWyMFRI3pc0ltfIHX4esJB7UhI3XsEaI9tMgUFq8x7DO60Ub+1FVh0WPYdy0WEjSsS2uZuM+TQEBSDCwoS1+7XtXBLEibvvlpMe4J1nWBvo8stI3Hy8w== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=MIhJRefdc58Z2UKTmcSN+zxOh6XII1wN/mnhJXjHfrI=; b=Bk45T5DNh3NA3y6SVELG2kvxXcJP5OQn7LS9oV4yPzZ/Va7VJtXUTAhs4e/GQXcAY4NgRYPVUOtIS0oTHIkdRfV77mcT+BBHtVJri/GcViSVld/j0ORUFmmZWF10+PWIRpzJ4in32GM07ZaKndhCkwY02asDC4Qu3+wkKJ2WtLWKrN/4GuXs2tBDjvpkvJ5LGenRrPa8/zFnqhJeoF9/b/NrUXM6nQ5IaIvuinipJZZwVH1LqlbRsdxwgtv+FbdsMYDBxs45msOUJPAfWU91FuiL2VtDsAy3kZUw66nIdl9YZpBUZflUkaPpIIsxSY+OFUdUxRq/tlk+2uzUYH1NCg== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=nvidia.com; dmarc=pass action=none header.from=nvidia.com; dkim=pass header.d=nvidia.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=Nvidia.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=MIhJRefdc58Z2UKTmcSN+zxOh6XII1wN/mnhJXjHfrI=; b=gA8zfgFsLLhi5ak0a3br1pKj++SFcaPsMSEnIbhSk6D7IayAqjwdQGRKFeR9A413YK0MDiBoIHJX8xpwWKJm1er37xdio0aiqmvDwWPA6UO4j0RN8nFTTSo/0NWGyga26hVSKIjBmYcnn3SQrImxlQqk/kQ3gDhF5wuoIRGsmt94qTR5lDWz5adThz8GoqLn39Tdt2HSYq7PyneIeQT1QnDJ+bnXPziht0yBHJHfDjXOdIHk+LqH2bkcHwPxRlw45aDYAs6RG1YRmbvhsWDtQCoawrq+eobA6SYiEer+yzntmrIDO3NaYeLR/Xng82KG5SITqF2ka4qo0fyn18p0EQ== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) by DM4PR12MB8475.namprd12.prod.outlook.com (2603:10b6:8:190::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9160.17; Tue, 30 Sep 2025 14:45:55 +0000 Received: from SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91]) by SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91%2]) with mapi id 15.20.9160.015; Tue, 30 Sep 2025 14:45:53 +0000 From: Joel Fernandes To: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org, dakr@kernel.org, acourbot@nvidia.com Cc: Alistair Popple , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , bjorn3_gh@protonmail.com, Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , David Airlie , Simona Vetter , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , John Hubbard , Joel Fernandes , Timur Tabi , joel@joelfernandes.org, Elle Rhumsaa , Yury Norov , Daniel Almeida , Andrea Righi , nouveau@lists.freedesktop.org Subject: [PATCH v5 4/9] rust: Move register and bitfield macros out of Nova Date: Tue, 30 Sep 2025 10:45:32 -0400 Message-Id: <20250930144537.3559207-5-joelagnelf@nvidia.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20250930144537.3559207-1-joelagnelf@nvidia.com> References: <20250930144537.3559207-1-joelagnelf@nvidia.com> Content-Transfer-Encoding: quoted-printable X-ClientProxiedBy: BN9PR03CA0630.namprd03.prod.outlook.com (2603:10b6:408:106::35) To SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SN7PR12MB8059:EE_|DM4PR12MB8475:EE_ X-MS-Office365-Filtering-Correlation-Id: 7cf49488-52cd-42a8-e433-08de00300e2b X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|7416014|376014; X-Microsoft-Antispam-Message-Info: =?us-ascii?Q?VoIMsdmZWrVDoIT9cWgmpjQtMydzw/vm/c/r/FJFi+XXrIaep2QSY2QZ+ZxN?= =?us-ascii?Q?bQAQdz6ONDY6Z+6E2eXgxbjebsEGroGA4YtUakIxDnlR0+QtlgZlSG5Spexm?= =?us-ascii?Q?WSk1/V9VhAiEPL9Rg1ruC9ZaAP8F74y78R3tgbrcFUgaVfjkMA9NSHPiT4EH?= =?us-ascii?Q?854GTaUg7lKaEUvLy0Tqs7ko7us8wWdv/tJTHStWIlqDguGMAjG0kSeLgEKj?= =?us-ascii?Q?g/ZBoYonMXWXWWRqrxvuCzbrzKPwm2fCpxQdfQnm7gi11UJpbGszZpwlEYSw?= =?us-ascii?Q?ghXEq6u06vlL9Cz/2N/Q9cMqNmnuk6ATG49EtuEhZAXX/VpEYEcARYctp36/?= =?us-ascii?Q?MUINWvONFKNpy0tsGilRmx3Bvpl6E/q4qXSmZ8pODAU0gJQCQfFfHYyboAkK?= =?us-ascii?Q?i8YjTvmToQn6Px9ClK0wBvPZZoIFbPrmL/aoXbVjl6uatYnqC0okqjqhD7O5?= =?us-ascii?Q?WNIIHLst78gMtH9B3atKOk668HJ7OXIix+0gyWs6Pbsw9eH30XrC6F7Zjgs1?= =?us-ascii?Q?6sjoma0ireGqj43LH1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pBzM?= =?us-ascii?Q?0Y2kppDFfVa/DGv451wMqgI+fJFLic4c?= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SN7PR12MB8059.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(366016)(1800799024)(7416014)(376014);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?us-ascii?Q?26Er3yRKL/diartCGigbMrTO+WUUQ/aFZSh/MExsocMCegxlTjffxVa0N7ov?= =?us-ascii?Q?CkybwSy3cokDlRmiIDQyH72LcU67vy1nfO/Q/3KACoGaIPNFYDeoDvmN3V7M?= =?us-ascii?Q?MIo6RDS5+F9sDRzUX9f2MfD8SOuqSF3PKMZ9010QYJgRhHWxIFrsWAtn9KCh?= =?us-ascii?Q?JiFhhauO74s2BZvauCsNuXP2jPionfgIGpAxKNZ8/u3hps6z0KU3OQd0m8FW?= =?us-ascii?Q?JrrbMnBFsvnI3IlMPX95at7s3EzPQS8cVdThZZcIz5QwKgeheBKou8nOAW1B?= =?us-ascii?Q?7ZnveRWXkjeyoB/dU2CMaT24XczRBn8Aa9rBtRttcN7S5Abv948svoYNasVD?= =?us-ascii?Q?B7gRogWif8SmAGii1O7MqsSji+evDcagelednXALzoB6QvhaWIEAchUNTWro?= =?us-ascii?Q?LgTHZCqmfyhzlvJQSCVpappsaW8uN+DgT+05ujgR3uuTCsHqXg4kkDj8STJl?= =?us-ascii?Q?+jBYme5KtYQIrzA0A5tFmuWZXoFaPNnpXaoPat4msPy9mQocVII6trV0ux9l?= =?us-ascii?Q?vyru8F5dhQVnZk5pT84RFO9yLrJ0M028zy22ODSzaqv2Q+281iL4X1N5ju+1?= =?us-ascii?Q?0TznrZNYZDpgTwIkT7KWyLRGzYgJgweJTtxIZiKnTIjO6Fi7bKyzgaUnDckR?= =?us-ascii?Q?eaPuI71Q64/wmHd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iDcJ8D56?= =?us-ascii?Q?OZNcVhd9YFZ2WO+Ns5YnrP0DUKVCMHGfJ1+mNzFG?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 7cf49488-52cd-42a8-e433-08de00300e2b X-MS-Exchange-CrossTenant-AuthSource: SN7PR12MB8059.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Sep 2025 14:45:53.1241 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 43083d15-7273-40c1-b7db-39efd9ccc17a X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: fwUVTZ6dmKxIPZM5x/0f8iSegCfCxnyUp5NGukXjJhDR5V+eA7DZ8lP77OFwQqEcAm4WqLpBXPF89xvErO5OQw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM4PR12MB8475 Content-Type: text/plain; charset="utf-8" Out of broad need for the register and bitfield macros in Rust, move them out of nova into the kernel crate. Several usecases need them (Nova is already using these and Tyr developers said they need them). bitfield moved into kernel crate - defines bitfields in Rust. register moved into io module - defines hardware registers and accessors. Reviewed-by: Alexandre Courbot Reviewed-by: Elle Rhumsaa Signed-off-by: Joel Fernandes --- MAINTAINERS | 7 +++ drivers/gpu/nova-core/falcon.rs | 2 +- drivers/gpu/nova-core/falcon/gsp.rs | 4 +- drivers/gpu/nova-core/falcon/sec2.rs | 2 +- drivers/gpu/nova-core/nova_core.rs | 3 - drivers/gpu/nova-core/regs.rs | 6 +- .../gpu/nova-core =3D> rust/kernel}/bitfield.rs | 27 ++++----- rust/kernel/io.rs | 1 + .../macros.rs =3D> rust/kernel/io/register.rs | 58 ++++++++++--------- rust/kernel/lib.rs | 1 + 10 files changed, 61 insertions(+), 50 deletions(-) rename {drivers/gpu/nova-core =3D> rust/kernel}/bitfield.rs (91%) rename drivers/gpu/nova-core/regs/macros.rs =3D> rust/kernel/io/register.r= s (93%) diff --git a/MAINTAINERS b/MAINTAINERS index 841b76234045..20d06cf4b512 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4380,6 +4380,13 @@ F: include/linux/bitops.h F: lib/test_bitops.c F: tools/*/bitops* =20 +BITFIELD API [RUST] +M: Joel Fernandes +M: Alexandre Courbot +M: Yury Norov +S: Maintained +F: rust/kernel/bitfield.rs + BITOPS API BINDINGS [RUST] M: Yury Norov S: Maintained diff --git a/drivers/gpu/nova-core/falcon.rs b/drivers/gpu/nova-core/falcon= .rs index 37e6298195e4..a15fa98c8614 100644 --- a/drivers/gpu/nova-core/falcon.rs +++ b/drivers/gpu/nova-core/falcon.rs @@ -6,6 +6,7 @@ use hal::FalconHal; use kernel::device; use kernel::dma::DmaAddress; +use kernel::io::register::RegisterBase; use kernel::prelude::*; use kernel::sync::aref::ARef; use kernel::time::Delta; @@ -14,7 +15,6 @@ use crate::driver::Bar0; use crate::gpu::Chipset; use crate::regs; -use crate::regs::macros::RegisterBase; use crate::util; =20 pub(crate) mod gsp; diff --git a/drivers/gpu/nova-core/falcon/gsp.rs b/drivers/gpu/nova-core/fa= lcon/gsp.rs index f17599cb49fa..cd4960e997c8 100644 --- a/drivers/gpu/nova-core/falcon/gsp.rs +++ b/drivers/gpu/nova-core/falcon/gsp.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: GPL-2.0 =20 +use kernel::io::register::RegisterBase; + use crate::{ driver::Bar0, falcon::{Falcon, FalconEngine, PFalcon2Base, PFalconBase}, - regs::{self, macros::RegisterBase}, + regs::self, }; =20 /// Type specifying the `Gsp` falcon engine. Cannot be instantiated. diff --git a/drivers/gpu/nova-core/falcon/sec2.rs b/drivers/gpu/nova-core/f= alcon/sec2.rs index 815786c8480d..81717868a8a8 100644 --- a/drivers/gpu/nova-core/falcon/sec2.rs +++ b/drivers/gpu/nova-core/falcon/sec2.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-2.0 =20 use crate::falcon::{FalconEngine, PFalcon2Base, PFalconBase}; -use crate::regs::macros::RegisterBase; +use kernel::io::register::RegisterBase; =20 /// Type specifying the `Sec2` falcon engine. Cannot be instantiated. pub(crate) struct Sec2(()); diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nov= a_core.rs index 112277c7921e..fffcaee2249f 100644 --- a/drivers/gpu/nova-core/nova_core.rs +++ b/drivers/gpu/nova-core/nova_core.rs @@ -2,9 +2,6 @@ =20 //! Nova Core GPU Driver =20 -#[macro_use] -mod bitfield; - mod dma; mod driver; mod falcon; diff --git a/drivers/gpu/nova-core/regs.rs b/drivers/gpu/nova-core/regs.rs index 206dab2e1335..1f08e6d4045a 100644 --- a/drivers/gpu/nova-core/regs.rs +++ b/drivers/gpu/nova-core/regs.rs @@ -4,15 +4,13 @@ // but are mapped to types. #![allow(non_camel_case_types)] =20 -#[macro_use] -pub(crate) mod macros; - use crate::falcon::{ DmaTrfCmdSize, FalconCoreRev, FalconCoreRevSubversion, FalconFbifMemTy= pe, FalconFbifTarget, FalconModSelAlgo, FalconSecurityModel, PFalcon2Base, PFalconBase, Pere= grineCoreSelect, }; use crate::gpu::{Architecture, Chipset}; use kernel::prelude::*; +use kernel::register; =20 // PMC =20 @@ -331,6 +329,7 @@ pub(crate) fn mem_scrubbing_done(self) -> bool { =20 pub(crate) mod gm107 { // FUSE + use kernel::register; =20 register!(NV_FUSE_STATUS_OPT_DISPLAY @ 0x00021c04 { 0:0 display_disabled as bool; @@ -339,6 +338,7 @@ pub(crate) mod gm107 { =20 pub(crate) mod ga100 { // FUSE + use kernel::register; =20 register!(NV_FUSE_STATUS_OPT_DISPLAY @ 0x00820c04 { 0:0 display_disabled as bool; diff --git a/drivers/gpu/nova-core/bitfield.rs b/rust/kernel/bitfield.rs similarity index 91% rename from drivers/gpu/nova-core/bitfield.rs rename to rust/kernel/bitfield.rs index cbedbb0078f6..09cd5741598c 100644 --- a/drivers/gpu/nova-core/bitfield.rs +++ b/rust/kernel/bitfield.rs @@ -9,7 +9,7 @@ /// # Syntax /// /// ```rust -/// use nova_core::bitfield; +/// use kernel::bitfield; /// /// #[derive(Debug, Clone, Copy, Default)] /// enum Mode { @@ -82,10 +82,11 @@ /// the result. /// - `as ?=3D> ` calls ``'s `TryFrom= ::<>` implementation /// and returns the result. This is useful with fields for which not all= values are valid. +#[macro_export] macro_rules! bitfield { // Main entry point - defines the bitfield struct with fields ($vis:vis struct $name:ident($storage:ty) $(, $comment:literal)? { $($= fields:tt)* }) =3D> { - bitfield!(@core $vis $name $storage $(, $comment)? { $($fields)* }= ); + ::kernel::bitfield!(@core $vis $name $storage $(, $comment)? { $($= fields)* }); }; =20 // All rules below are helpers. @@ -114,7 +115,7 @@ fn from(val: $name) -> $storage { } } =20 - bitfield!(@fields_dispatcher $vis $name $storage { $($fields)* }); + ::kernel::bitfield!(@fields_dispatcher $vis $name $storage { $($fi= elds)* }); }; =20 // Captures the fields and passes them to all the implementers that re= quire field information. @@ -130,7 +131,7 @@ fn from(val: $name) -> $storage { )* } ) =3D> { - bitfield!(@field_accessors $vis $name $storage { + ::kernel::bitfield!(@field_accessors $vis $name $storage { $( $hi:$lo $field as $type $(?=3D> $try_into_type)? @@ -139,8 +140,8 @@ fn from(val: $name) -> $storage { ; )* }); - bitfield!(@debug $name { $($field;)* }); - bitfield!(@default $name { $($field;)* }); + ::kernel::bitfield!(@debug $name { $($field;)* }); + ::kernel::bitfield!(@default $name { $($field;)* }); }; =20 // Defines all the field getter/setter methods for `$name`. @@ -155,13 +156,13 @@ fn from(val: $name) -> $storage { } ) =3D> { $( - bitfield!(@check_field_bounds $hi:$lo $field as $type); + ::kernel::bitfield!(@check_field_bounds $hi:$lo $field as $typ= e); )* =20 #[allow(dead_code)] impl $name { $( - bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field = as $type + ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$= lo $field as $type $(?=3D> $try_into_type)? $(=3D> $into_type)? $(, $comment)? @@ -198,7 +199,7 @@ impl $name { @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $f= ield:ident as bool =3D> $into_type:ty $(, $comment:literal)?; ) =3D> { - bitfield!( + ::kernel::bitfield!( @leaf_accessor $vis $name $storage, $hi:$lo $field { |f| <$into_type>::from(if f !=3D 0 { true } else { false }) } $into_type =3D> $into_type $(, $comment)?; @@ -209,7 +210,7 @@ impl $name { ( @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $f= ield:ident as bool $(, $comment:literal)?; ) =3D> { - bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as b= ool =3D> bool $(, $comment)?;); + ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$lo $= field as bool =3D> bool $(, $comment)?;); }; =20 // Catches the `?=3D>` syntax for non-boolean fields. @@ -217,7 +218,7 @@ impl $name { @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $f= ield:ident as $type:tt ?=3D> $try_into_type:ty $(, $comment:literal)?; ) =3D> { - bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field + ::kernel::bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $f= ield { |f| <$try_into_type>::try_from(f as $type) } $try_into_type = =3D> ::core::result::Result< $try_into_type, @@ -231,7 +232,7 @@ impl $name { @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $f= ield:ident as $type:tt =3D> $into_type:ty $(, $comment:literal)?; ) =3D> { - bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field + ::kernel::bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $f= ield { |f| <$into_type>::from(f as $type) } $into_type =3D> $into_t= ype $(, $comment)?;); }; =20 @@ -240,7 +241,7 @@ impl $name { @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $f= ield:ident as $type:tt $(, $comment:literal)?; ) =3D> { - bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as $= type =3D> $type $(, $comment)?;); + ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$lo $= field as $type =3D> $type $(, $comment)?;); }; =20 // Generates the accessor methods for a single field. diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index ee182b0b5452..da1384fd9ab6 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -9,6 +9,7 @@ =20 pub mod mem; pub mod poll; +pub mod register; pub mod resource; =20 pub use resource::Resource; diff --git a/drivers/gpu/nova-core/regs/macros.rs b/rust/kernel/io/register= .rs similarity index 93% rename from drivers/gpu/nova-core/regs/macros.rs rename to rust/kernel/io/register.rs index c0a5194e8d97..c24d956f122f 100644 --- a/drivers/gpu/nova-core/regs/macros.rs +++ b/rust/kernel/io/register.rs @@ -17,7 +17,8 @@ /// The `T` generic argument is used to distinguish which base to use, in = case a type provides /// several bases. It is given to the `register!` macro to restrict the us= e of the register to /// implementors of this particular variant. -pub(crate) trait RegisterBase { +pub trait RegisterBase { + /// The base address for the register. const BASE: usize; } =20 @@ -26,7 +27,7 @@ pub(crate) trait RegisterBase { /// /// Example: /// -/// ```no_run +/// ```ignore /// register!(BOOT_0 @ 0x00000100, "Basic revision information about the G= PU" { /// 3:0 minor_revision as u8, "Minor revision of the chip"; /// 7:4 major_revision as u8, "Major revision of the chip"; @@ -39,7 +40,7 @@ pub(crate) trait RegisterBase { /// significant bits of the register. Each field can be accessed and modif= ied using accessor /// methods: /// -/// ```no_run +/// ```ignore /// // Read from the register's defined offset (0x100). /// let boot0 =3D BOOT_0::read(&bar); /// pr_info!("chip revision: {}.{}", boot0.major_revision(), boot0.minor_r= evision()); @@ -61,7 +62,7 @@ pub(crate) trait RegisterBase { /// It is also possible to create a alias register by using the `=3D> ALIA= S` syntax. This is useful /// for cases where a register's interpretation depends on the context: /// -/// ```no_run +/// ```ignore /// register!(SCRATCH @ 0x00000200, "Scratch register" { /// 31:0 value as u32, "Raw value"; /// }); @@ -111,7 +112,7 @@ pub(crate) trait RegisterBase { /// this register needs to implement `RegisterBase`. Here is the abo= ve example translated /// into code: /// -/// ```no_run +/// ```ignore /// // Type used to identify the base. /// pub(crate) struct CpuCtlBase; /// @@ -162,7 +163,7 @@ pub(crate) trait RegisterBase { /// compile-time or runtime bound checking. Simply define their address as= `Address[Size]`, and add /// an `idx` parameter to their `read`, `write` and `alter` methods: /// -/// ```no_run +/// ```ignore /// # fn no_run() -> Result<(), Error> { /// # fn get_scratch_idx() -> usize { /// # 0x15 @@ -211,7 +212,7 @@ pub(crate) trait RegisterBase { /// Combining the two features described in the sections above, arrays of = registers accessible from /// a base can also be defined: /// -/// ```no_run +/// ```ignore /// # fn no_run() -> Result<(), Error> { /// # fn get_scratch_idx() -> usize { /// # 0x15 @@ -273,28 +274,29 @@ pub(crate) trait RegisterBase { /// # Ok(()) /// # } /// ``` +#[macro_export] macro_rules! register { // Creates a register at a fixed offset of the MMIO space. ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)*= } ) =3D> { - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); + ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { = $($fields)* } ); register!(@io_fixed $name @ $offset); }; =20 // Creates an alias register of fixed offset register `alias` with its= own fields. ($name:ident =3D> $alias:ident $(, $comment:literal)? { $($fields:tt)*= } ) =3D> { - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); + ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { = $($fields)* } ); register!(@io_fixed $name @ $alias::OFFSET); }; =20 // Creates a register at a relative offset from a base address provide= r. ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $= ($fields:tt)* } ) =3D> { - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); + ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { = $($fields)* } ); register!(@io_relative $name @ $base [ $offset ]); }; =20 // Creates an alias register of relative offset register `alias` with = its own fields. ($name:ident =3D> $base:ty [ $alias:ident ] $(, $comment:literal)? { $= ($fields:tt)* }) =3D> { - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); + ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { = $($fields)* } ); register!(@io_relative $name @ $base [ $alias::OFFSET ]); }; =20 @@ -305,7 +307,7 @@ macro_rules! register { } ) =3D> { static_assert!(::core::mem::size_of::() <=3D $stride); - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); + ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { = $($fields)* } ); register!(@io_array $name @ $offset [ $size ; $stride ]); }; =20 @@ -326,7 +328,7 @@ macro_rules! register { $(, $comment:literal)? { $($fields:tt)* } ) =3D> { static_assert!(::core::mem::size_of::() <=3D $stride); - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); + ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { = $($fields)* } ); register!(@io_relative_array $name @ $base [ $offset [ $size ; $st= ride ] ]); }; =20 @@ -348,7 +350,7 @@ macro_rules! register { } ) =3D> { static_assert!($idx < $alias::SIZE); - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); + ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { = $($fields)* } ); register!(@io_relative $name @ $base [ $alias::OFFSET + $idx * $al= ias::STRIDE ] ); }; =20 @@ -357,7 +359,7 @@ macro_rules! register { // to avoid it being interpreted in place of the relative register arr= ay alias rule. ($name:ident =3D> $alias:ident [ $idx:expr ] $(, $comment:literal)? { = $($fields:tt)* }) =3D> { static_assert!($idx < $alias::SIZE); - bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)= * } ); + ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { = $($fields)* } ); register!(@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE= ); }; =20 @@ -414,12 +416,12 @@ pub(crate) fn read( base: &B, ) -> Self where T: ::core::ops::Deref>, - B: crate::regs::macros::RegisterBase<$base>, + B: ::kernel::io::register::RegisterBase<$base>, { const OFFSET: usize =3D $name::OFFSET; =20 let value =3D io.read32( - >::BASE = + OFFSET + >::BA= SE + OFFSET ); =20 Self(value) @@ -435,13 +437,13 @@ pub(crate) fn write( base: &B, ) where T: ::core::ops::Deref>, - B: crate::regs::macros::RegisterBase<$base>, + B: ::kernel::io::register::RegisterBase<$base>, { const OFFSET: usize =3D $name::OFFSET; =20 io.write32( self.0, - >::BASE = + OFFSET + >::BA= SE + OFFSET ); } =20 @@ -455,7 +457,7 @@ pub(crate) fn alter( f: F, ) where T: ::core::ops::Deref>, - B: crate::regs::macros::RegisterBase<$base>, + B: ::kernel::io::register::RegisterBase<$base>, F: ::core::ops::FnOnce(Self) -> Self, { let reg =3D f(Self::read(io, base)); @@ -600,11 +602,11 @@ pub(crate) fn read( idx: usize, ) -> Self where T: ::core::ops::Deref>, - B: crate::regs::macros::RegisterBase<$base>, + B: ::kernel::io::register::RegisterBase<$base>, { build_assert!(idx < Self::SIZE); =20 - let offset =3D >::BASE + + let offset =3D >::BASE + Self::OFFSET + (idx * Self::STRIDE); let value =3D io.read32(offset); =20 @@ -622,11 +624,11 @@ pub(crate) fn write( idx: usize ) where T: ::core::ops::Deref>, - B: crate::regs::macros::RegisterBase<$base>, + B: ::kernel::io::register::RegisterBase<$base>, { build_assert!(idx < Self::SIZE); =20 - let offset =3D >::BASE + + let offset =3D >::BASE + Self::OFFSET + (idx * Self::STRIDE); =20 io.write32(self.0, offset); @@ -643,7 +645,7 @@ pub(crate) fn alter( f: F, ) where T: ::core::ops::Deref>, - B: crate::regs::macros::RegisterBase<$base>, + B: ::kernel::io::register::RegisterBase<$base>, F: ::core::ops::FnOnce(Self) -> Self, { let reg =3D f(Self::read(io, base, idx)); @@ -662,7 +664,7 @@ pub(crate) fn try_read( idx: usize, ) -> ::kernel::error::Result where T: ::core::ops::Deref>, - B: crate::regs::macros::RegisterBase<$base>, + B: ::kernel::io::register::RegisterBase<$base>, { if idx < Self::SIZE { Ok(Self::read(io, base, idx)) @@ -684,7 +686,7 @@ pub(crate) fn try_write( idx: usize, ) -> ::kernel::error::Result where T: ::core::ops::Deref>, - B: crate::regs::macros::RegisterBase<$base>, + B: ::kernel::io::register::RegisterBase<$base>, { if idx < Self::SIZE { Ok(self.write(io, base, idx)) @@ -707,7 +709,7 @@ pub(crate) fn try_alter( f: F, ) -> ::kernel::error::Result where T: ::core::ops::Deref>, - B: crate::regs::macros::RegisterBase<$base>, + B: ::kernel::io::register::RegisterBase<$base>, F: ::core::ops::FnOnce(Self) -> Self, { if idx < Self::SIZE { diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 115376c2710e..66c6219abb25 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -64,6 +64,7 @@ #[cfg(CONFIG_AUXILIARY_BUS)] pub mod auxiliary; pub mod bitmap; +pub mod bitfield; pub mod bits; #[cfg(CONFIG_BLOCK)] pub mod block; --=20 2.34.1 From nobody Thu Oct 2 22:52:49 2025 Received: from SA9PR02CU001.outbound.protection.outlook.com (mail-southcentralusazon11013005.outbound.protection.outlook.com [40.93.196.5]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A5765306B33; Tue, 30 Sep 2025 14:46:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.196.5 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243569; cv=fail; b=LtQnfqsCJvyriFKDuE9p2jRRBX5LkdXCKYnTzWQQPneFJXp53uUKlvLvXoL64s0tByz86xvM4VcWL8fwFmxfWVAbe3nhskPIOTDYdZH0YewWijyMw+KYz5J+nXgHOmw6dz7Vnq/DPnn4o78nAX+Ms/kgClJKAYGJhbXuPjBLVU0= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243569; c=relaxed/simple; bh=pvJ+r2kRDFiucCTiOJnybf6STjU596oYQNOOmP1f6e0=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: Content-Type:MIME-Version; b=gsAsTaI4vhXMGoXs/mA38166bCF+ODA2VfW6rxpm2UtXcO3Kq4BSfpp56XGEoXqep1vsqxK4mmu/GcMMHFZ8F3rzRviDb8MXrMfxzLrPmIxXv69D/Sf8AC+rk6lY4EOIpoMhsCF7EhCEo5ytKRQRKv5zCXTXOo95ycs5Ls7lXQ4= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com; spf=fail smtp.mailfrom=nvidia.com; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b=bvZYFsBf; arc=fail smtp.client-ip=40.93.196.5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com Authentication-Results: smtp.subspace.kernel.org; spf=fail smtp.mailfrom=nvidia.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b="bvZYFsBf" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=mktX2cITssjNorxgOYF/qCXn+XGUVtAf4+ddxD/klkFBnRXG0oE8bwV67yMfASn5h7j4LmfFJKvHAYm/13deVCv1t29NKmZGQwLzN4jREtKUtEk7Yl0dZegXhr48+7vEQ2eSUtyB2cbPHORNeZBrx66o0qOWHuhfNU5l7SF95GA4+9yWmfbP9i8qJD4oq3BUcznPaBd9gYNCB3p9cwnvJgPWcFzDJe8i18oE7UpKmFzyaPl1f1G2pch+OvujiMy8K4qz9cmJcOdxe/qt3Gl8K7hrKXl7ztoUbyhmCaw1I3Cx5WcxtwVsvAcfhCgxjWhzY71uV1PpxcpHzJxid5fXCw== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=31r62iqpLR0Cv4Hzgj3Yz1tiqWkIM3Q+q4LFRO7vrOs=; b=NJFqM2l9vhxbYu820LcT/6yxdnnxIicNz/Axrt0wcV4/ORnwUOHsFQ07cbx0uR51Ab/L3eSNETYYd4Nd+Mf3uqp+Gk2zkTMRrYiuLSRoFAnBigGoZnfluSgz+bMaC0HCKKo4KmRhWOQTnVAJyRuBWKeyrAjASiFNicchPLxtdsXZsBl42ift4MwN5qvu4lCY5YVMdmDi5kIADoSXX5jLfYV7hocEOsFkqMInHpGdlFLyRXTzTnHsyzkQi+OCH648jpEtpBoqJp0c3D3WIjaErgKBMkQoHeSBVqz6ro79wEhlkdBTapmT7KO0ElQpv5yVThzsCWbsRwuEyifuDdhWaA== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=nvidia.com; dmarc=pass action=none header.from=nvidia.com; dkim=pass header.d=nvidia.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=Nvidia.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=31r62iqpLR0Cv4Hzgj3Yz1tiqWkIM3Q+q4LFRO7vrOs=; b=bvZYFsBfTKSOpcjacAbNCCzEx1tTCvDFR1/pbwLTUch2P075mArSL06BulGvdZJRX1UhiLyW2geJf0ea9CU734l5Sk0/oc3BW34Z7EuDSajmrEcYEcTqirvyDK83GjTmnliYqTQzrStLliTAnUyEqugX/ABzpReHsEcqIhIcvry5LefColUXIsnRA1RAzDC/zdm4Al3fiuMhzIkekQxd+wpPxCuTqcp6bisIKY4Z+GlFWRWHIQI/IYvQrK54gNsvL4N0JzTxVbSgXKmHpTT8vOFv1rHHRt3NbPPPUg0Tjzt8oYHC6LwaXBs29pHNNUajlrlwZBY5JKzPia1BuAageQ== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) by DM4PR12MB8475.namprd12.prod.outlook.com (2603:10b6:8:190::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9160.17; Tue, 30 Sep 2025 14:45:55 +0000 Received: from SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91]) by SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91%2]) with mapi id 15.20.9160.015; Tue, 30 Sep 2025 14:45:55 +0000 From: Joel Fernandes To: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org, dakr@kernel.org, acourbot@nvidia.com Cc: Alistair Popple , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , bjorn3_gh@protonmail.com, Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , David Airlie , Simona Vetter , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , John Hubbard , Joel Fernandes , Timur Tabi , joel@joelfernandes.org, Elle Rhumsaa , Yury Norov , Daniel Almeida , Andrea Righi , nouveau@lists.freedesktop.org Subject: [PATCH v5 5/9] rust: bitfield: Add a new() constructor and raw() accessor Date: Tue, 30 Sep 2025 10:45:33 -0400 Message-Id: <20250930144537.3559207-6-joelagnelf@nvidia.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20250930144537.3559207-1-joelagnelf@nvidia.com> References: <20250930144537.3559207-1-joelagnelf@nvidia.com> Content-Transfer-Encoding: quoted-printable X-ClientProxiedBy: BN9PR03CA0621.namprd03.prod.outlook.com (2603:10b6:408:106::26) To SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SN7PR12MB8059:EE_|DM4PR12MB8475:EE_ X-MS-Office365-Filtering-Correlation-Id: 07280a48-c690-46e2-c44a-08de00300f4e X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|7416014|376014; X-Microsoft-Antispam-Message-Info: =?us-ascii?Q?nuPEhRiuoEeB7tB6PATIxJqZGNxV/9AV5BhGo9pVnM5oJBpbJLor84ZZTM/n?= =?us-ascii?Q?SRo+DG6380oEk0yL9lit48eWjO389BpRV4Km/SajwPqUD0cboDhdevIVruqF?= =?us-ascii?Q?KmZG+xh6I2AWm+WCMWY28WvbGG4pEdcVi6SUCCGeVWk59AfecAPXD8F9TR1V?= =?us-ascii?Q?Kor6CFUnpf4Ww/R60ELXv38/MgPJAVtRFadIOLX+FMTm3/dkMS7Gzv6Hm05X?= =?us-ascii?Q?n1K3f0ItwbGnka42jdnyGjKmM8Vnlpq/6Gpmbx8RBEbiuR7Rr3sKyNDSMpu3?= =?us-ascii?Q?0/V6eBEzYXjvvdzhb0QYow1N3Z+AqvD2lSEExQ0MzT1hBqyQv6E8Sw+F4kst?= =?us-ascii?Q?WOUl/xmwN1h58RvOX0HBa5LBO51k408V0R2pjBpjoSpGpbfgw8SNxRiRIrZU?= =?us-ascii?Q?BY7CwQw6qJKAU+yH8GYgk+LR2qw69OiMQysRNPYkKFTta/CbAwsELxbGeJLw?= =?us-ascii?Q?OH9lnew4CI/mYzyjMlToM1xQ0J4640I2Y9Kdd3cTo1T+EGVNYkCAe0vZvkCb?= =?us-ascii?Q?M2X/selMpvul9vcsZ+o4ixr4oxYUHp8HUS8Z8GYxUsralLzmWAvQWJHYSOmC?= =?us-ascii?Q?91sIkIKuWFVKSpFAjC8PGX1jl+Rad+h4aGrqeJQqk+20MfWFspXmkkede7TI?=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NSPM;H:SN7PR12MB8059.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(366016)(1800799024)(7416014)(376014);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?us-ascii?Q?zxMECOhBK/65Fw81OG1zc6o37s7RiAgcqp08XN9VKa1aCJjjn8lV/al5sztv?= =?us-ascii?Q?ohbCEWTR/naSQjWVftiECi0iMshmqhlpmEdwa9HyV/XgEom1ynLhfmQOeY52?= =?us-ascii?Q?+Fij5aNqFrya6IT8EfGp3vD0dVjvqNFqeOesxY+irG5XQslny67jgeMgl6lw?= =?us-ascii?Q?JRycJNCdt8IlQ7cm8AmQq5EUUWD2MpyTT3shnVmUTYHWMQrqJfD1hzucZAPK?= =?us-ascii?Q?6eTB8K3uXdLg+beel+ROTRiPx3kDOWDpDy8ahSEyFhl15BJQQGieGEeCYjgT?= =?us-ascii?Q?+assDojNhnMChDevNC1oWf6wmoAWdXICwkVKKl5X4qqv1ZFPwq2TSfdTYHBL?= =?us-ascii?Q?iow4wk8y9AGsZRbpz2B3jjb8nXpu+DjArusF4MoLsa1PivbRaYH+nbsI9euz?= =?us-ascii?Q?eYY/CTKLMz2l8Dg0fMMK67qeEfqpnFR0ai+G1OVeFIhsEVQLmN0wS7O0aHtL?= =?us-ascii?Q?UREdjHtCylZ5VmTbQctZiNHGW4dChQ8KAJW6JUflekcuYjDUeTETTWIGiFvH?= =?us-ascii?Q?61h/Swzt/5XfvqfoARRaXef5xR33jR8fIoMt+FaYDiPJVfExKbNI7U+3JFxS?= =?us-ascii?Q?w1XmUQN7T7I4Mh+a81iG09gCz2tlljlyzZXJEWKh9KnL+GfYLcfKfpllif4K?= =?us-ascii?Q?1NTRIkUgs1G+hrC8mFWM/VXLpWz+7VU1w38DA4wbrWii+3BPKPF7kslS7JpE?= =?us-ascii?Q?DAVpx8G15gly3xHyS/Ad0Guzeg5ZLHzTPTEGU+gvRlB2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Network-Message-Id: 07280a48-c690-46e2-c44a-08de00300f4e X-MS-Exchange-CrossTenant-AuthSource: SN7PR12MB8059.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Sep 2025 14:45:55.0931 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 43083d15-7273-40c1-b7db-39efd9ccc17a X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: jaEiSdp64JUQl6nl6AxiGtDferlJiagkiI1W88fjL3WTCf/ii4a0WZZ8/R8H50EEkZNovZGJk57qnTcrdowslQ== X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM4PR12MB8475 Content-Type: text/plain; charset="utf-8" In order to prevent the user from directly accessing/wrapping the inner value of the struct, provide a new storage type to wrap the inner value. The bitfield framework can then control access better. For instance, we can zero out undefined bits to prevent undefined behavior of bits that are not defined. Further, we can somewhat prevent the user manipulating the bitfield's inner storage directly using .0. They can still do so by using the new bitfield storage type this patch defines, however it would not be by accident and would have to be deliberate. Suggested-by: Yury Norov Signed-off-by: Joel Fernandes --- rust/kernel/bitfield.rs | 123 +++++++++++++++++++++++++++++-------- rust/kernel/io/register.rs | 16 ++--- 2 files changed, 106 insertions(+), 33 deletions(-) diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs index 09cd5741598c..fed19918c3b9 100644 --- a/rust/kernel/bitfield.rs +++ b/rust/kernel/bitfield.rs @@ -4,7 +4,33 @@ //! //! Support for defining bitfields in Rust structures. Also used by the [`= register!`] macro. =20 -/// Defines a struct with accessors to access bits within an inner unsigne= d integer. +/// Storage wrapper for bitfield values that prevents direct construction. +/// +/// This type wraps the underlying storage value and ensures that bitfield +/// structs can only be constructed through their `new()` method, which +/// properly masks undefined bits. +#[repr(transparent)] +#[derive(Clone, Copy)] +pub struct BitfieldInternalStorage { + value: T, +} + +impl BitfieldInternalStorage { + /// Creates a new storage wrapper with the given value. + #[inline(always)] + pub const fn from_raw(value: T) -> Self { + Self { value } + } + + /// Returns the underlying raw value. + #[inline(always)] + pub const fn into_raw(self) -> T { + self.value + } +} + +/// Bitfield macro definition. +/// Define a struct with accessors to access bits within an inner unsigned= integer. /// /// # Syntax /// @@ -62,9 +88,23 @@ /// 7:7 state as bool =3D> State; /// } /// } +/// +/// // Create a bitfield from a raw value - undefined bits are zeroed +/// let reg =3D ControlReg::new(0xDEADBEEF); +/// // Only bits 0-3 and 7 are preserved (as defined by the fields) +/// +/// // Get the raw underlying value +/// let raw_value =3D reg.raw(); +/// +/// // Use the builder pattern with field setters +/// let reg2 =3D ControlReg::default() +/// .set_mode(Mode::Auto) +/// .set_state(State::Active); /// ``` /// /// This generates a struct with: +/// - Constructor: `new(value)` - creates a bitfield from a raw value, zer= oing undefined bits +/// - Raw accessor: `raw()` - returns the underlying raw value /// - Field accessors: `mode()`, `state()`, etc. /// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining = with builder pattern). /// Note that the compiler will error out if the size of the setter's ar= g exceeds the @@ -72,7 +112,7 @@ /// - Debug and Default implementations. /// /// Note: Field accessors and setters inherit the same visibility as the s= truct itself. -/// In the example above, both `mode()` and `set_mode()` methods will be `= pub`. +/// In the example above, `new()`, `raw()`, `mode()` and `set_mode()` meth= ods will be `pub`. /// /// Fields are defined as follows: /// @@ -99,19 +139,19 @@ macro_rules! bitfield { )? #[repr(transparent)] #[derive(Clone, Copy)] - $vis struct $name($storage); + $vis struct $name(::kernel::bitfield::BitfieldInternalStorage<$sto= rage>); =20 impl ::core::ops::BitOr for $name { type Output =3D Self; =20 fn bitor(self, rhs: Self) -> Self::Output { - Self(self.0 | rhs.0) + Self::new(self.raw() | rhs.raw()) } } =20 impl ::core::convert::From<$name> for $storage { fn from(val: $name) -> $storage { - val.0 + val.raw() } } =20 @@ -161,6 +201,53 @@ fn from(val: $name) -> $storage { =20 #[allow(dead_code)] impl $name { + // Generate field constants to be used later + $( + ::kernel::macros::paste!( + const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive= =3D $lo..=3D$hi; + const [<$field:upper _MASK>]: $storage =3D { + // Generate mask for shifting + match ::core::mem::size_of::<$storage>() { + 1 =3D> ::kernel::bits::genmask_u8($lo..=3D$hi) as = $storage, + 2 =3D> ::kernel::bits::genmask_u16($lo..=3D$hi) as= $storage, + 4 =3D> ::kernel::bits::genmask_u32($lo..=3D$hi) as= $storage, + 8 =3D> ::kernel::bits::genmask_u64($lo..=3D$hi) as= $storage, + _ =3D> ::kernel::build_error!("Unsupported storage= type size") + } + }; + const [<$field:upper _SHIFT>]: u32 =3D Self::[<$field:uppe= r _MASK>].trailing_zeros(); + ); + )* + + /// Creates a new bitfield instance from a raw value. + /// + /// This constructor zeros out all bits that are not defined b= y any field, + /// ensuring only valid field bits are preserved. This is to p= revent UB + /// when raw() is used to retrieve undefined bits. + #[inline(always)] + $vis fn new(value: $storage) -> Self { + // Calculate mask for all defined fields + let mut mask: $storage =3D 0; + $( + ::kernel::macros::paste!( + mask |=3D Self::[<$field:upper _MASK>]; + ); + )* + // Zero out undefined bits and wrap in BitfieldInternalSto= rage + Self(::kernel::bitfield::BitfieldInternalStorage::from_raw= (value & mask)) + } + + /// Returns the raw underlying value of the bitfield. + /// + /// This provides direct access to the storage value, useful f= or + /// debugging or when you need to work with the raw value. + /// Bits not defined are masked at construction time. + #[inline(always)] + $vis fn raw(&self) -> $storage { + self.0.into_raw() + } + + // Generate field accessors $( ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$= lo $field as $type $(?=3D> $try_into_type)? @@ -249,21 +336,6 @@ impl $name { @leaf_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $fi= eld:ident { $process:expr } $to_type:ty =3D> $res_type:ty $(, $comment:l= iteral)?; ) =3D> { - ::kernel::macros::paste!( - const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive =3D= $lo..=3D$hi; - const [<$field:upper _MASK>]: $storage =3D { - // Generate mask for shifting - match ::core::mem::size_of::<$storage>() { - 1 =3D> ::kernel::bits::genmask_u8($lo..=3D$hi) as $storage, - 2 =3D> ::kernel::bits::genmask_u16($lo..=3D$hi) as $storag= e, - 4 =3D> ::kernel::bits::genmask_u32($lo..=3D$hi) as $storag= e, - 8 =3D> ::kernel::bits::genmask_u64($lo..=3D$hi) as $storag= e, - _ =3D> ::kernel::build_error!("Unsupported storage type si= ze") - } - }; - const [<$field:upper _SHIFT>]: u32 =3D Self::[<$field:upper _MASK>= ].trailing_zeros(); - ); - $( #[doc=3D"Returns the value of this field:"] #[doc=3D$comment] @@ -274,7 +346,7 @@ impl $name { const MASK: $storage =3D $name::[<$field:upper _MASK>]; const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; ); - let field =3D ((self.0 & MASK) >> SHIFT); + let field =3D ((self.raw() & MASK) >> SHIFT); =20 $process(field) } @@ -288,8 +360,9 @@ impl $name { $vis fn [](mut self, value: $to_type) -> Self { const MASK: $storage =3D $name::[<$field:upper _MASK>]; const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; - let value =3D (<$storage>::from(value) << SHIFT) & MASK; - self.0 =3D (self.0 & !MASK) | value; + let val =3D (<$storage>::from(value) << SHIFT) & MASK; + let new_val =3D (self.raw() & !MASK) | val; + self.0 =3D ::kernel::bitfield::BitfieldInternalStorage::from_r= aw(new_val); =20 self } @@ -301,7 +374,7 @@ impl $name { impl ::core::fmt::Debug for $name { fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::f= mt::Result { f.debug_struct(stringify!($name)) - .field("", &format_args!("{:#x}", &self.0)) + .field("", &format_args!("{:#x}", &self.raw())) $( .field(stringify!($field), &self.$field()) )* @@ -316,7 +389,7 @@ fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::= core::fmt::Result { impl ::core::default::Default for $name { fn default() -> Self { #[allow(unused_mut)] - let mut value =3D Self(Default::default()); + let mut value =3D Self::new(Default::default()); =20 ::kernel::macros::paste!( $( diff --git a/rust/kernel/io/register.rs b/rust/kernel/io/register.rs index c24d956f122f..45c6ad1bfb9e 100644 --- a/rust/kernel/io/register.rs +++ b/rust/kernel/io/register.rs @@ -374,7 +374,7 @@ impl $name { pub(crate) fn read(io: &T) -> Self where T: ::core::ops::Deref>, { - Self(io.read32($offset)) + Self::new(io.read32($offset)) } =20 /// Write the value contained in `self` to the register addres= s in `io`. @@ -382,7 +382,7 @@ pub(crate) fn read(io: &T) -> Sel= f where pub(crate) fn write(self, io: &T) where T: ::core::ops::Deref>, { - io.write32(self.0, $offset) + io.write32(self.raw(), $offset) } =20 /// Read the register from its address in `io` and run `f` on = its value to obtain a new @@ -424,7 +424,7 @@ pub(crate) fn read( >::BA= SE + OFFSET ); =20 - Self(value) + Self::new(value) } =20 /// Write the value contained in `self` to `io`, using the bas= e address provided by @@ -442,7 +442,7 @@ pub(crate) fn write( const OFFSET: usize =3D $name::OFFSET; =20 io.write32( - self.0, + self.raw(), >::BA= SE + OFFSET ); } @@ -487,7 +487,7 @@ pub(crate) fn read( let offset =3D Self::OFFSET + (idx * Self::STRIDE); let value =3D io.read32(offset); =20 - Self(value) + Self::new(value) } =20 /// Write the value contained in `self` to the array register = with index `idx` in `io`. @@ -503,7 +503,7 @@ pub(crate) fn write( =20 let offset =3D Self::OFFSET + (idx * Self::STRIDE); =20 - io.write32(self.0, offset); + io.write32(self.raw(), offset); } =20 /// Read the array register at index `idx` in `io` and run `f`= on its value to obtain a @@ -610,7 +610,7 @@ pub(crate) fn read( Self::OFFSET + (idx * Self::STRIDE); let value =3D io.read32(offset); =20 - Self(value) + Self::new(value) } =20 /// Write the value contained in `self` to `io`, using the bas= e address provided by @@ -631,7 +631,7 @@ pub(crate) fn write( let offset =3D >::BASE + Self::OFFSET + (idx * Self::STRIDE); =20 - io.write32(self.0, offset); + io.write32(self.raw(), offset); } =20 /// Read the array register at index `idx` from `io`, using th= e base address provided --=20 2.34.1 From nobody Thu Oct 2 22:52:49 2025 Received: from SA9PR02CU001.outbound.protection.outlook.com (mail-southcentralusazon11013005.outbound.protection.outlook.com [40.93.196.5]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 54E70305071; Tue, 30 Sep 2025 14:46:10 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.196.5 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243572; cv=fail; b=kaiAhKl8Y8vvcOm0tfL59fkMHD4egz7ALyQWbAv9PmTpTAQfXoqc/T/SUa1tJMLOZYyD26KyWTmFzadlvsVieklGH9Q0SUqAuXCgqefouDm8QS5JOjtkKDoj3Qvhrd6LpnC0wGtZApj9209LUr1BytJbqOAZSFBwrmOOZfvmHIo= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243572; c=relaxed/simple; bh=1S6GwVsLmxm0V069jL0nSu4szjuWc8sM+FepWS44mvA=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: Content-Type:MIME-Version; b=OWytYwAcD/LoAg3iKGp+1VXmq8x4HDQpbnlWbwiZ5fdjHjaiTCaP5ZWERCRAsYDRAnBmlAmZ18DvH5/Y9I9cv53Qlsg0NEtHns8Omg6ToFrREDPppYRPArpFJnF9mKUidw9+qKenUxFrACpBQv+KDX72JV35DE/oZgrP8TAZAFo= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com; spf=fail smtp.mailfrom=nvidia.com; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b=Zx4xVQst; arc=fail smtp.client-ip=40.93.196.5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com Authentication-Results: smtp.subspace.kernel.org; spf=fail smtp.mailfrom=nvidia.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b="Zx4xVQst" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=aQ2fYQyLCVCiobOnPVfDhZNx0rh3frdBEW+ut3pW6d5KWmltBLPUsPVM9Z6MmNt3vbEC7efzf02JVZllMz0eDHE+gJ4VW8/W7vW1xCo5Asp64XFYyF37H4deXXpgyvy0wenq5W2kE3c/aQ3KR517idaefPFiNDlf9RPSCN+cgOFje8fk8h/Hz9zKewCI9pp2tV4ThuzgUdfBmfqrsKd/3j4PYftU7z3FFm4SYF172OqxURpxbJM61AdrwPk/SFKTyYCfj/NAQ/w5IzJsm+IGewEDPMDCN7u5E1mmygPVsg7oDQ3XsHKXAUs5H0odPaC5REkJ2wVl2Kj7wviQ/48UVQ== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=dRnfEF0Y1E5DmLHmOyl2YB4+Y9e+RU7O4WX35Zj7DKw=; b=tNYxb9PBY3Gd1U4K00mogen/fxN0CcXE4wohfic/K6FpIbos87oETFhYRDL7apGWQjmhr2Tg0IzOZErZFnN850ZnMG+ZglL08X3YjYsgoQpq6oGSKyYhSyi7YGLlW83Y6bcqh2ya08XOZTIbhnaev3bJtcMLAbaEb1RZX9IOoVuEeGQLY/b2qlUJuJkuR+UlCIcOnt1TUFw2CtjcKtGNOEKQQGdIiMPG1UgqokPzINJXJoBAcvYU35PqFWZf74oK6E8UVaM6F91DMx/F4UBlIF/BmjaXgTBs844ro76pgIcgcoj+/sxY5oQa2eAK4BL7HzDlwrb1mIx790GKAimdRw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=nvidia.com; dmarc=pass action=none header.from=nvidia.com; dkim=pass header.d=nvidia.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=Nvidia.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=dRnfEF0Y1E5DmLHmOyl2YB4+Y9e+RU7O4WX35Zj7DKw=; b=Zx4xVQstQg/KnRnVIb87BqofdfmtUOmM7m/q//inZCYvXhuBIJwFqpWgndonXkXBQgHIWWopoVo/zUDw8148wjBrY5I6UA7fcErLSOMJt5HQdI3Eo0kHtVNqvLqjOZfah7QkyOu4OAahJ2rEGnGUJvBiGWiQIx+0NaXIWfs8JDiyPIspARMwTgs3W0YZAdUNcb4QZOxyTMS2pnhEg2BFhkkEdtlzvx6HXCHHalw+/Lmy4h7Gm9Au8bFBYFbrmPEEav7yCwOAnoHkCobupJpcPTg/R79x6w3mIXUZzq5wrqJxeQMiQ32UnxVZtDFb28CWUMvQ0TGMX1YgVqnpPORlqg== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) by DM4PR12MB8475.namprd12.prod.outlook.com (2603:10b6:8:190::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9160.17; Tue, 30 Sep 2025 14:45:57 +0000 Received: from SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91]) by SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91%2]) with mapi id 15.20.9160.015; Tue, 30 Sep 2025 14:45:57 +0000 From: Joel Fernandes To: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org, dakr@kernel.org, acourbot@nvidia.com Cc: Alistair Popple , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , bjorn3_gh@protonmail.com, Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , David Airlie , Simona Vetter , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , John Hubbard , Joel Fernandes , Timur Tabi , joel@joelfernandes.org, Elle Rhumsaa , Yury Norov , Daniel Almeida , Andrea Righi , nouveau@lists.freedesktop.org Subject: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield Date: Tue, 30 Sep 2025 10:45:34 -0400 Message-Id: <20250930144537.3559207-7-joelagnelf@nvidia.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20250930144537.3559207-1-joelagnelf@nvidia.com> References: <20250930144537.3559207-1-joelagnelf@nvidia.com> Content-Transfer-Encoding: quoted-printable X-ClientProxiedBy: BN9PR03CA0238.namprd03.prod.outlook.com (2603:10b6:408:f8::33) To SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SN7PR12MB8059:EE_|DM4PR12MB8475:EE_ X-MS-Office365-Filtering-Correlation-Id: 3e0e96b5-eee1-4bc5-2d2d-08de003010a4 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|7416014|376014; X-Microsoft-Antispam-Message-Info: =?us-ascii?Q?6czfpQiaWfG+cVdrSOEKuKueXDVScD9haYyEOz2Xf+YKfXqzImmfrlXRaMu2?= =?us-ascii?Q?b+S/Dt7RPllbD/TK1/dwNgnHJZZCSxMXbuIFT2xiZ4JeSjfNAfBKvAgERdGs?= =?us-ascii?Q?/xfT62TlMREtNzZ/UpmL7f4Pvwj10NhoVrBjGZa4cR/L13yVFRVE7Ta0C05Y?= =?us-ascii?Q?q2HmneGBjW5hhvxMH0fkuZC85Bfp2QbgqMt2Hesl2YAnWyHzVLBTiLyX4+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GTdFOhvqW2p9+65vpgZaxC?= =?us-ascii?Q?GClEzI0Fk3dD+A7IU/i/lVLNb25InjZf9r+qc+ah+W8nHM2NqTjZGzSVdt6p?= =?us-ascii?Q?+vGfKOwFScFcUMHPsMtlyJFzssJ26WkJ5jiq4HcHX5LWDdRdzR3qZgT2sR9E?= =?us-ascii?Q?ZneEtX6/IE/5CkU+kvEXTA8RScWvxMYuBHtaxNQYuMTRiOkjzywX6w5NcV4x?= =?us-ascii?Q?Vsnb0+A837E0uc6HaAl2gWzEnaCKiOZ2yJr6Px0bRW84IgD5ccwx7T7lWbhA?= =?us-ascii?Q?k3Yenz9oeoMZ9XjGMzdRzJc77W7gBqhG9hTuDAj+utPo4XTGDKWjdTLOs0h3?= =?us-ascii?Q?2bH/C6CmvzVMR1gh15ttUa8ydDq2AgHe?= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SN7PR12MB8059.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(366016)(1800799024)(7416014)(376014);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?us-ascii?Q?L8dfjLVxfcotjj//AVGyDe0N1GvpKOqstq6CWk1ATafEhNqPWdQkpHZh6mJQ?= =?us-ascii?Q?fyFibAJTdWZzN0m9Vo20YyXz6kKciaBQiEvUMCH4KoDqHiHC8EieA1ybDcjs?= =?us-ascii?Q?lxFos5y7gQNOjVnFEKU1r/7Y+GbG6nIGJbnwYwUHo2ufikkE+gvfsvyO5Hq0?= =?us-ascii?Q?WAE0IX+ZZE6VmmDjaDqLKrnPnm386NaMZVrKqfMBBw39xjznHWbQClrhfh4p?= =?us-ascii?Q?YLD4G4bX9jcQQTLHzSHw9QI765HSwJY8XRwrAaxrRyi6j25ZEam2JCDQdOno?= =?us-ascii?Q?FTyWnSslAnFFMGzNJOHVtPvTLLlA4Y6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ii?Q?DrUwwi1es3kmbtj3oORQiY3IYDeR3CQjL4yOu8OFweKiYdHAhvkXFCSQvgKU?= =?us-ascii?Q?7QmL2RaByHKlzazs9uKR2S5eE0Rr5NOuYxaPW2aQ6KxH+y4P/WfyLlipHD4L?= =?us-ascii?Q?iyCg638HSdCUaUtjrOQ+opVro6J1kqVHHpavzGIhAsVTrkR9DPV+uP8j7Gzm?= =?us-ascii?Q?a5TLImmjNZabpKo4GtBuH824qLNnrmTdSe02pVMBoAnaREHJsY9VxpQ8XBHj?= =?us-ascii?Q?830izFTf8McG0NDfED2NJveDeBx9NYk+suff0Z+9LnD3PCyXgDQGVCM+Irku?= =?us-ascii?Q?phK60HYwqQ1P0s/7h1lj8qye2INFY3oHnZuRVedWGxa0g5dIIXi9BcvCTxC1?= =?us-ascii?Q?uczDAp+zdwThQgKfHsGU75z98p8dE9DNAWod86ui?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 3e0e96b5-eee1-4bc5-2d2d-08de003010a4 X-MS-Exchange-CrossTenant-AuthSource: SN7PR12MB8059.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Sep 2025 14:45:57.2416 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 43083d15-7273-40c1-b7db-39efd9ccc17a X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: CTAovTPLpE8dLu2UB/IP4nEG3Czj6W1MAHfH+97klRqBSI1/waE9/EHDU4EFcoSSE+V99PbbSscGPRkV5m8ugA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM4PR12MB8475 Content-Type: text/plain; charset="utf-8" Add KUNIT tests to make sure the macro is working correctly. Signed-off-by: Joel Fernandes --- rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+) diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs index fed19918c3b9..9a20bcd2eb60 100644 --- a/rust/kernel/bitfield.rs +++ b/rust/kernel/bitfield.rs @@ -402,3 +402,324 @@ fn default() -> Self { } }; } + +#[::kernel::macros::kunit_tests(kernel_bitfield)] +mod tests { + use core::convert::TryFrom; + + // Enum types for testing =3D> and ?=3D> conversions + #[derive(Debug, Clone, Copy, PartialEq)] + enum MemoryType { + Unmapped =3D 0, + Normal =3D 1, + Device =3D 2, + Reserved =3D 3, + } + + impl Default for MemoryType { + fn default() -> Self { + MemoryType::Unmapped + } + } + + impl TryFrom for MemoryType { + type Error =3D u8; + fn try_from(value: u8) -> Result { + match value { + 0 =3D> Ok(MemoryType::Unmapped), + 1 =3D> Ok(MemoryType::Normal), + 2 =3D> Ok(MemoryType::Device), + 3 =3D> Ok(MemoryType::Reserved), + _ =3D> Err(value), + } + } + } + + impl From for u64 { + fn from(mt: MemoryType) -> u64 { + mt as u64 + } + } + + #[derive(Debug, Clone, Copy, PartialEq)] + enum Priority { + Low =3D 0, + Medium =3D 1, + High =3D 2, + Critical =3D 3, + } + + impl Default for Priority { + fn default() -> Self { + Priority::Low + } + } + + impl From for Priority { + fn from(value: u8) -> Self { + match value & 0x3 { + 0 =3D> Priority::Low, + 1 =3D> Priority::Medium, + 2 =3D> Priority::High, + _ =3D> Priority::Critical, + } + } + } + + impl From for u16 { + fn from(p: Priority) -> u16 { + p as u16 + } + } + + bitfield! { + struct TestPageTableEntry(u64) { + 0:0 present as bool; + 1:1 writable as bool; + 11:9 available as u8; + 13:12 mem_type as u8 ?=3D> MemoryType; + 17:14 extended_type as u8 ?=3D> MemoryType; // For testin= g failures + 51:12 pfn as u64; + 51:12 pfn_overlap as u64; + 61:52 available2 as u16; + } + } + + bitfield! { + struct TestControlRegister(u16) { + 0:0 enable as bool; + 3:1 mode as u8; + 5:4 priority as u8 =3D> Priority; + 7:4 priority_nibble as u8; + 15:8 channel as u8; + } + } + + bitfield! { + struct TestStatusRegister(u8) { + 0:0 ready as bool; + 1:1 error as bool; + 3:2 state as u8; + 7:4 reserved as u8; + 7:0 full_byte as u8; // For entire register + } + } + + #[test] + fn test_single_bits() { + let mut pte =3D TestPageTableEntry::default(); + + assert!(!pte.present()); + assert!(!pte.writable()); + + pte =3D pte.set_present(true); + assert!(pte.present()); + + pte =3D pte.set_writable(true); + assert!(pte.writable()); + + pte =3D pte.set_writable(false); + assert!(!pte.writable()); + + assert_eq!(pte.available(), 0); + pte =3D pte.set_available(0x5); + assert_eq!(pte.available(), 0x5); + } + + #[test] + fn test_range_fields() { + let mut pte =3D TestPageTableEntry::default(); + + pte =3D pte.set_pfn(0x123456); + assert_eq!(pte.pfn(), 0x123456); + // Test overlapping field reads same value + assert_eq!(pte.pfn_overlap(), 0x123456); + + pte =3D pte.set_available(0x7); + assert_eq!(pte.available(), 0x7); + + pte =3D pte.set_available2(0x3FF); + assert_eq!(pte.available2(), 0x3FF); + + // Test TryFrom with ?=3D> for MemoryType + pte =3D pte.set_mem_type(MemoryType::Device); + assert_eq!(pte.mem_type(), Ok(MemoryType::Device)); + + pte =3D pte.set_mem_type(MemoryType::Normal); + assert_eq!(pte.mem_type(), Ok(MemoryType::Normal)); + + // Test all valid values for mem_type + pte =3D pte.set_mem_type(MemoryType::Reserved); // Valid value: 3 + assert_eq!(pte.mem_type(), Ok(MemoryType::Reserved)); + + // Test failure case using extended_type field which has 4 bits (0= -15) + // MemoryType only handles 0-3, so values 4-15 should return Err + let mut raw =3D pte.raw(); + // Set bits 17:14 to 7 (invalid for MemoryType) + raw =3D (raw & !::kernel::bits::genmask_u64(14..=3D17)) | (0x7 << = 14); + let invalid_pte =3D TestPageTableEntry::new(raw); + // Should return Err with the invalid value + assert_eq!(invalid_pte.extended_type(), Err(0x7)); + + // Test a valid value after testing invalid to ensure both cases w= ork + // Set bits 17:14 to 2 (valid: Device) + raw =3D (raw & !::kernel::bits::genmask_u64(14..=3D17)) | (0x2 << = 14); + let valid_pte =3D TestPageTableEntry::new(raw); + assert_eq!(valid_pte.extended_type(), Ok(MemoryType::Device)); + + let max_pfn =3D ::kernel::bits::genmask_u64(0..=3D39); + pte =3D pte.set_pfn(max_pfn); + assert_eq!(pte.pfn(), max_pfn); + assert_eq!(pte.pfn_overlap(), max_pfn); + } + + #[test] + fn test_builder_pattern() { + let pte =3D TestPageTableEntry::default() + .set_present(true) + .set_writable(true) + .set_available(0x7) + .set_pfn(0xABCDEF) + .set_mem_type(MemoryType::Reserved) + .set_available2(0x3FF); + + assert!(pte.present()); + assert!(pte.writable()); + assert_eq!(pte.available(), 0x7); + assert_eq!(pte.pfn(), 0xABCDEF); + assert_eq!(pte.pfn_overlap(), 0xABCDEF); + assert_eq!(pte.mem_type(), Ok(MemoryType::Reserved)); + assert_eq!(pte.available2(), 0x3FF); + } + + #[test] + fn test_raw_operations() { + let raw_value =3D 0x3FF0000003123E03u64; + + let pte =3D TestPageTableEntry::new(raw_value); + assert_eq!(pte.raw(), raw_value); + + assert!(pte.present()); + assert!(pte.writable()); + assert_eq!(pte.available(), 0x7); + assert_eq!(pte.pfn(), 0x3123); + assert_eq!(pte.pfn_overlap(), 0x3123); + assert_eq!(pte.mem_type(), Ok(MemoryType::Reserved)); + assert_eq!(pte.available2(), 0x3FF); + + // Test using direct constructor syntax TestStruct(value) + let pte2 =3D TestPageTableEntry::new(raw_value); + assert_eq!(pte2.raw(), raw_value); + } + + #[test] + fn test_u16_bitfield() { + let mut ctrl =3D TestControlRegister::default(); + + assert!(!ctrl.enable()); + assert_eq!(ctrl.mode(), 0); + assert_eq!(ctrl.priority(), Priority::Low); + assert_eq!(ctrl.priority_nibble(), 0); + assert_eq!(ctrl.channel(), 0); + + ctrl =3D ctrl.set_enable(true); + assert!(ctrl.enable()); + + ctrl =3D ctrl.set_mode(0x5); + assert_eq!(ctrl.mode(), 0x5); + + // Test From conversion with =3D> + ctrl =3D ctrl.set_priority(Priority::High); + assert_eq!(ctrl.priority(), Priority::High); + assert_eq!(ctrl.priority_nibble(), 0x2); // High =3D 2 in bits 5:4 + + ctrl =3D ctrl.set_channel(0xAB); + assert_eq!(ctrl.channel(), 0xAB); + + // Test overlapping fields + ctrl =3D ctrl.set_priority_nibble(0xF); + assert_eq!(ctrl.priority_nibble(), 0xF); + assert_eq!(ctrl.priority(), Priority::Critical); // bits 5:4 =3D 0= x3 + + let ctrl2 =3D TestControlRegister::default() + .set_enable(true) + .set_mode(0x3) + .set_priority(Priority::Medium) + .set_channel(0x42); + + assert!(ctrl2.enable()); + assert_eq!(ctrl2.mode(), 0x3); + assert_eq!(ctrl2.priority(), Priority::Medium); + assert_eq!(ctrl2.channel(), 0x42); + + let raw_value: u16 =3D 0x4217; + let ctrl3 =3D TestControlRegister::new(raw_value); + assert_eq!(ctrl3.raw(), raw_value); + assert!(ctrl3.enable()); + assert_eq!(ctrl3.priority(), Priority::Medium); + assert_eq!(ctrl3.priority_nibble(), 0x1); + assert_eq!(ctrl3.channel(), 0x42); + } + + #[test] + fn test_u8_bitfield() { + let mut status =3D TestStatusRegister::default(); + + assert!(!status.ready()); + assert!(!status.error()); + assert_eq!(status.state(), 0); + assert_eq!(status.reserved(), 0); + assert_eq!(status.full_byte(), 0); + + status =3D status.set_ready(true); + assert!(status.ready()); + assert_eq!(status.full_byte(), 0x01); + + status =3D status.set_error(true); + assert!(status.error()); + assert_eq!(status.full_byte(), 0x03); + + status =3D status.set_state(0x3); + assert_eq!(status.state(), 0x3); + assert_eq!(status.full_byte(), 0x0F); + + status =3D status.set_reserved(0xA); + assert_eq!(status.reserved(), 0xA); + assert_eq!(status.full_byte(), 0xAF); + + // Test overlapping field + status =3D status.set_full_byte(0x55); + assert_eq!(status.full_byte(), 0x55); + assert!(status.ready()); + assert!(!status.error()); + assert_eq!(status.state(), 0x1); + assert_eq!(status.reserved(), 0x5); + + let status2 =3D TestStatusRegister::default() + .set_ready(true) + .set_state(0x2) + .set_reserved(0x5); + + assert!(status2.ready()); + assert!(!status2.error()); + assert_eq!(status2.state(), 0x2); + assert_eq!(status2.reserved(), 0x5); + assert_eq!(status2.full_byte(), 0x59); + + let raw_value: u8 =3D 0x59; + let status3 =3D TestStatusRegister::new(raw_value); + assert_eq!(status3.raw(), raw_value); + assert!(status3.ready()); + assert!(!status3.error()); + assert_eq!(status3.state(), 0x2); + assert_eq!(status3.reserved(), 0x5); + assert_eq!(status3.full_byte(), 0x59); + + let status4 =3D TestStatusRegister::new(0xFF); + assert!(status4.ready()); + assert!(status4.error()); + assert_eq!(status4.state(), 0x3); + assert_eq!(status4.reserved(), 0xF); + assert_eq!(status4.full_byte(), 0xFF); + } +} --=20 2.34.1 From nobody Thu Oct 2 22:52:49 2025 Received: from SA9PR02CU001.outbound.protection.outlook.com (mail-southcentralusazon11013005.outbound.protection.outlook.com [40.93.196.5]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 55E20307499; Tue, 30 Sep 2025 14:46:12 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.196.5 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243574; cv=fail; b=F/UUVv4QS3tlxlFulAn8+xJor8HoBJVr2t2EDEZvzBclc5yMcs1iqPD2c6XbDRaYkLXsAMV/G7VI3Y7wZOOzjjYZGNMdN7qBpJdc5NLhY21SwQk66eElupWt9mtnB59FmwdvNY0mAL2IxMyeyRVkZqPH4XpKF+GGeOlrakOhLe4= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243574; c=relaxed/simple; bh=zwIAbZjMaRz7BxMy8F/U+ylUqc5ZewD6yuK1+g2RLsQ=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: Content-Type:MIME-Version; b=ruqC/HlCKMRiNCkCHl54sL6rpPyyLD6aIp5kwvyyvLNNIrJOcn8u9WZTy85TRPhJqrBOYO9CPl5qQWanXVpp8c4PBFGOU+l3nx+FEzOeCgXT7Lno6wD2Z/Mrp6xKGe7fPrvFJo+EnQGqqpt8+Zb5f2WadAEMOZWcoWLzw58ngX8= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com; spf=fail smtp.mailfrom=nvidia.com; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b=rFEJ0eQj; arc=fail smtp.client-ip=40.93.196.5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com Authentication-Results: smtp.subspace.kernel.org; spf=fail smtp.mailfrom=nvidia.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b="rFEJ0eQj" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=Kf+h0dsnd2HHW0ZeHn3oEVNKhmQWH9ALh8GfljrxboXNkH8uzdxIZGT6c/8BhD1Jfva1A8coPkalH/WBAdzcn+Sk4ruXqDt9gAMu/3fudREiMBC4JW+q5LwvNnYuNQl74gxSWW69mbURLwiUgoZBSq+ogSBBvZQrbgAFIRm6ysUF3ggGTa78dotlavnc8IclL11YmK08dA1dXotpSvfKbatFG7XxcoaN94fG3C4OLjuoFcXOVreTsYUAwJ8Q3vZa+bN8b90g4JqFB9jXeskjm63r7OckFvfYPuAVm0CvLwD2k4IKkH8ioZlE1AKqmEO0LGTJ62bzpMJ2Z/6P2fUe8Q== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=ERmKqtLjZ53vhXWrolZ2wVbOLe6ygLTfNzIFuc49vG4=; b=idmpGAR8L47JmnKnAEoy2jqDqTyYBwMFwX0a5Ka2a4++sbiefM3GgYUe1fKiuaxNWM2lKVVUXWDMGmjiKoJfGHMyHgVSGWUJDZodX27AlM4Wx6nXZ2gN8SjNxGB1QbacojBtgHhmkJWsZjpPnygg9WntM2IWGYGgBCfzKiK6oWTd77N/1OHCPIMP/CROnDdzDt5gP7vHqE9/E4mOQeL5zlOfeDaVhAi2+tV0G3m/hl/pys+hAt6hYgQ4I+3Bv7cBfDAXfS7kwWZe8CUEexTIPRuQb1fbVj+vvqB/YhsGMq05wJbSooLYUyF8dteCvuZWD+VTB75t6wg1Rwo2lwpSmQ== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=nvidia.com; dmarc=pass action=none header.from=nvidia.com; dkim=pass header.d=nvidia.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=Nvidia.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=ERmKqtLjZ53vhXWrolZ2wVbOLe6ygLTfNzIFuc49vG4=; b=rFEJ0eQjXX2PZv8wlQUV+Pd/mmd8ZunnGTetNR/YpbYdr/w6m8vCQbXKirsZXSSg8jatzObaXTUgMt5gI8x3FXEQbHYxfrAOoPtvyIp5++0VT7kcdmdY9Ilqy/ABJdzfShmlyq4SDWMGnC/IVdcRFjUqXLLikzqU9IqIr/3V35zl+xdAhMAjKcL4smF7IG5Jpd6yVD364IDlWqe8/hUjcKUcXEmgYrjPF3x4CSyVQeW/wkJrArZ0gWOv7RwXR71s4NBFwZFM0lBaNE7a65g6rwClzPOP9V7hj8bTlX1xfy6VnEyyPIhUinkzuH5QFT3IPS3xdtJESWmOdV31AA6TQA== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) by DM4PR12MB8475.namprd12.prod.outlook.com (2603:10b6:8:190::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9160.17; Tue, 30 Sep 2025 14:45:59 +0000 Received: from SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91]) by SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91%2]) with mapi id 15.20.9160.015; Tue, 30 Sep 2025 14:45:59 +0000 From: Joel Fernandes To: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org, dakr@kernel.org, acourbot@nvidia.com Cc: Alistair Popple , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , bjorn3_gh@protonmail.com, Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , David Airlie , Simona Vetter , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , John Hubbard , Joel Fernandes , Timur Tabi , joel@joelfernandes.org, Elle Rhumsaa , Yury Norov , Daniel Almeida , Andrea Righi , nouveau@lists.freedesktop.org Subject: [PATCH v5 7/9] rust: bitfield: Use 'as' operator for setter type conversion Date: Tue, 30 Sep 2025 10:45:35 -0400 Message-Id: <20250930144537.3559207-8-joelagnelf@nvidia.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20250930144537.3559207-1-joelagnelf@nvidia.com> References: <20250930144537.3559207-1-joelagnelf@nvidia.com> Content-Transfer-Encoding: quoted-printable X-ClientProxiedBy: BL1P221CA0018.NAMP221.PROD.OUTLOOK.COM (2603:10b6:208:2c5::30) To SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SN7PR12MB8059:EE_|DM4PR12MB8475:EE_ X-MS-Office365-Filtering-Correlation-Id: f539c6d3-2d39-411a-42e3-08de003011c8 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|7416014|376014; X-Microsoft-Antispam-Message-Info: =?us-ascii?Q?Pqdy81nZBF5v25HdVb5shFBfTeHHOHqHIM5wk5VRUpf+6zinWeBV0NqZqGzP?= =?us-ascii?Q?Ujr6yjYVZFeFkT1+2QvqulHwBS/3K+j7jGmx7lLdORGM0bDtdIcL7WdU9SL/?= =?us-ascii?Q?PURePVPzKzw9RwnRA0FW/EhvsDrMIZYe0/7pPMfChvcNGTyhfez25myBKIGm?= =?us-ascii?Q?iD3nGrQv3NBH5hPfuhfucsrNUlUeEJASaKgaypzuGNNECwH58FoYz55Z3l8/?= =?us-ascii?Q?xYCiLOwlGS4qmtvxE4SngLwSLqrCSboXpCx3f1YuLqjRKZz17Xwq5jLvSzqu?= =?us-ascii?Q?UWPhSQw+MJUR/ZGPUBBP/qUAgwFVC3LYS5rQHl00VtokrVHOndrAz5C90UiI?= =?us-ascii?Q?xoZ7TdPAAZ1kU/6IE46vXjWtPy0hVD2QcCB6gdQ4KrsZfAoeuwxKfO+RwSpi?= =?us-ascii?Q?tuXAfV0kljfrj2yyEAg/6A8cmAogK2Isviujj/dQiY2w9QCMKoVTLzAMacJZ?= =?us-ascii?Q?Dixt7rsC48TcHQcl5WEU/qPO86O/hhaKvhcR+T+fdi2UpIa0Dr9bxE+/Z41W?= =?us-ascii?Q?bBLMORnZimGMlWK2cpiy7MTYabHc7lBDlNPQcO4jrFlAeYOhA+wo4P1nKxaa?= =?us-ascii?Q?NuDva5X0oehxV8/HuufsmSRKZmubU+hAISf7U+qCRTakk2YHtEVbgCDAaFym?= =?us-ascii?Q?DwfFEbDmZ1SmvzT8UJZhMAqc9j0tWFoFRJibJGFKXJ22WAxNxmJeWAXJlzF7?= =?us-ascii?Q?Y/lJEoN1zYVcOza1pLzCtI2eoq12A81V5w3d+FxlpVa/mq9c70pTg/gGUefU?= =?us-ascii?Q?3AewXAD1uM1CHFDAPECMfwJ8ovX3z1a8nRSveBoMJ0gAQTM9XusjXckXbEXB?= =?us-ascii?Q?1JMJYFZKV8+Nmje07nRcFoi432MSZJSr6PAjYXQkg11l2QTNOJLiRRHFwa0q?= =?us-ascii?Q?77rl0vnkydYyTBWeMCOic+5jCys+nsp+Fvo7Ru5OrjoirKyZpsOALLVZrJN2?= =?us-ascii?Q?zfotk3YPo+MhjbzioqJZ+10vKoyLx72+PTAz+HjJDqBs5Fv6UVvPSWpSjT5M?= =?us-ascii?Q?o5ymIsNqsuaw0mFIFjCq1GWOlziqVYlCDOdADIOEUkhCkZedSmCRhAdsoP4D?= =?us-ascii?Q?sDifExdzctujZjz7wi+DNSw4RHQsc10VH3UPRsOIFgRN1pOppIAfd//+oz8m?= =?us-ascii?Q?I2ypJ3W7TMLFEwN0a4XFx1GQf9WvX+9bMEWZU7PNPyNOFsFaiqZ3YaYFY6qi?= =?us-ascii?Q?wtXHowTRz3Fd1hTUpJ0CWBClTBl863W5H84aGPn1QrCg7tEEJLv/CyBHFRvF?= =?us-ascii?Q?dI4/kr5OH5W8ANdxNqqg/zdsbzirVpIFl0+fofysah/LciJigYyufhDt/IPT?= =?us-ascii?Q?X1840wVuPMrUy2wei2Ta4BDKjqYFvawMPrZSxXOeyLDX9hXk2P33Tk44uhS6?= =?us-ascii?Q?wXGPum8HGHVEZNrTAGcDnFPRs430fiB4BWF9Trgr4fT6b8Yb49fv991hKyf6?= =?us-ascii?Q?Sp/7mAeGKhd3PRTCY7Sw4S4lt/gSs4w7?= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SN7PR12MB8059.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(366016)(1800799024)(7416014)(376014);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?us-ascii?Q?kz04wttz8pbz00AB34QazgxLw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rrZXob?= =?us-ascii?Q?1LJ44857aM3liSaF7FTmk4MTQyHY78VtPCHJmb6YwPQCMUZpUAq5MGtr7vf+?= =?us-ascii?Q?l4j77mKIq94TkxzQFJv99/+DtPFck4tIsopL7Ov+4U9ayT3yWiAwb5b4fupX?= =?us-ascii?Q?0DTr/iSfrfkpshVT+ljyHPNki/b4PUCzEFWUD4F2DvRLekJwV/KydeK+lyG6?= =?us-ascii?Q?fl+1kr6bpbtqfScPEEacnfbSAnQODKjA2riL7+RuvtLI5Hb67ypEXFAJgEud?= =?us-ascii?Q?HU9VzsuFaMMzry65FxpwiHX03vul/DFL5ngt59QSldsHY5Xe/ot5qdrrjbvW?= =?us-ascii?Q?xBDjBq0QgzJ/Rw4DEcf6aQwVdr44905425WWf99YMf8NM9vXwZM//MXarzln?= =?us-ascii?Q?PtIOGNDOmB8xE/slNyM2hxvXti4Qg+rOwXu0NCzBrOulKwoQel3mpSg5c+UI?= =?us-ascii?Q?UwxyO8xsbQ5f6CjRfoQBN0S3UTOjcP3NA7v0EEA0YY3GwPQ9+Qn21iEKYoQU?= =?us-ascii?Q?0WZMbFGLj/4XPp+tYmMFoX8TQblTrgVC1GWeflPytMm89zC4U5oJudhhe0RV?= =?us-ascii?Q?sXzO6HWAirpTyTOXiyt8aBWAvUgC6LZ8rUoEHBcaIwZPNLeHTLYFpRnu/x2x?= =?us-ascii?Q?5Czx8FMwC98hAtjRC2n29orAsTMRMhfR7sE8MgFNauuf02P2u8uyPfYakQ0L?= =?us-ascii?Q?PWqmpKnq/NFwujTtVQdS0m+a7Q/n8NEqsKufTZxz?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: f539c6d3-2d39-411a-42e3-08de003011c8 X-MS-Exchange-CrossTenant-AuthSource: SN7PR12MB8059.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Sep 2025 14:45:59.1414 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 43083d15-7273-40c1-b7db-39efd9ccc17a X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: vGHQQ/e9lozkyFu8b8Pe/m6CMpiFi+dGcDPxIelQL2cnP7L5TlEYUp6uaGRfFrY/Oiu2eQCNztCLpukREHxqgA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM4PR12MB8475 Content-Type: text/plain; charset="utf-8" The bitfield macro's setter accesors currently uses the From trait for type conversion, which is overly restrictive and prevents use cases such as narrowing conversions (e.g., u8 struct storage size does not work with 'as u32' for the field size). Replace 'from' with 'as' in the setter implementation to support this. An example of such a bitfield struct is: bitfield! { struct TestWideFields: u8 { 3:0 nibble as u32; 7:4 high_nibble as u32; 7:0 full as u64; } } Note that there is already no requirement to have the total size of all the 'as ' fields to be <=3D the struct's storage width. For example, it is already possible to have a u8 sized struct, with two 'as u8' fields. So the struct's width is already independent of the total width of the 'as uXX' instances. Link: https://lore.kernel.org/all/aMIqGBoNaJ7rUrYQ@yury/ Suggested-by: Yury Norov Signed-off-by: Joel Fernandes --- rust/kernel/bitfield.rs | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs index 9a20bcd2eb60..a74e6d45ecd3 100644 --- a/rust/kernel/bitfield.rs +++ b/rust/kernel/bitfield.rs @@ -107,8 +107,6 @@ pub const fn into_raw(self) -> T { /// - Raw accessor: `raw()` - returns the underlying raw value /// - Field accessors: `mode()`, `state()`, etc. /// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining = with builder pattern). -/// Note that the compiler will error out if the size of the setter's ar= g exceeds the -/// struct's storage size. /// - Debug and Default implementations. /// /// Note: Field accessors and setters inherit the same visibility as the s= truct itself. @@ -360,7 +358,9 @@ impl $name { $vis fn [](mut self, value: $to_type) -> Self { const MASK: $storage =3D $name::[<$field:upper _MASK>]; const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; - let val =3D (<$storage>::from(value) << SHIFT) & MASK; + // Here we are potentially narrowing value from a wider bit va= lue + // to a narrower bit value. So we have to use `as` instead of = `::from()`. + let val =3D ((value as $storage) << SHIFT) & MASK; let new_val =3D (self.raw() & !MASK) | val; self.0 =3D ::kernel::bitfield::BitfieldInternalStorage::from_r= aw(new_val); =20 @@ -505,6 +505,15 @@ struct TestStatusRegister(u8) { } } =20 + // For testing wide field types on narrow storage + bitfield! { + struct TestWideFields(u8) { + 3:0 nibble as u32; + 7:4 high_nibble as u32; + 7:0 full as u64; + } + } + #[test] fn test_single_bits() { let mut pte =3D TestPageTableEntry::default(); @@ -722,4 +731,26 @@ fn test_u8_bitfield() { assert_eq!(status4.reserved(), 0xF); assert_eq!(status4.full_byte(), 0xFF); } + + #[test] + fn test_wide_field_types() { + let mut wf =3D TestWideFields::default(); + + wf =3D wf.set_nibble(0x0000000F_u32); + assert_eq!(wf.nibble(), 0x0000000F_u32); + + wf =3D wf.set_high_nibble(0x00000007_u32); + assert_eq!(wf.high_nibble(), 0x00000007_u32); + + wf =3D wf.set_full(0xBE_u64); + assert_eq!(wf.full(), 0xBE_u64); + assert_eq!(wf.raw(), 0xBE_u8); + + wf =3D TestWideFields::default() + .set_nibble(0x5_u32) + .set_high_nibble(0xA_u32); + assert_eq!(wf.raw(), 0xA5_u8); + assert_eq!(wf.nibble(), 0x5_u32); + assert_eq!(wf.high_nibble(), 0xA_u32); + } } --=20 2.34.1 From nobody Thu Oct 2 22:52:49 2025 Received: from SA9PR02CU001.outbound.protection.outlook.com (mail-southcentralusazon11013005.outbound.protection.outlook.com [40.93.196.5]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 40EA11487F4; Tue, 30 Sep 2025 14:46:14 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.196.5 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243576; cv=fail; b=j0SiRDCz+K65f67pHyZa6doWfdzjqbbMj0wh6k2oEUcuJPO2TZ7eRmABg4DV88gpOSy2mpmdoYde73WNnFCb4uFKJ0Pvn1OUwV6rwb7s3oP8WBplK1B9kKVXbUSiE16Hu6cPUVZ80OLBYELOEVyl38aqeLFMO1esD3YZGkFWQOw= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243576; c=relaxed/simple; bh=uhKVOa45jp9/O1psiMAvW7iA9aMhq8hMcugFuydub8Q=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: Content-Type:MIME-Version; b=AnkaERA1a5dYQn4x0n/pKw49+uNCX8646wR0T6vAhXwm90KQT3eUnCwvye0sn6iKVtWI9mlDlOuLpepbCCM7JKsAdTKHJJOrerG8M+UDQ71ZzLdIXYEPlbq/qetiLmEiBNq3d4aQf6DG2D7OTn7lbA0+VpsqENbT07K4X90Alx4= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com; spf=fail smtp.mailfrom=nvidia.com; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b=eL8HY5Rl; arc=fail smtp.client-ip=40.93.196.5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com Authentication-Results: smtp.subspace.kernel.org; spf=fail smtp.mailfrom=nvidia.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b="eL8HY5Rl" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=VU96ZZsTF388ZU3+VDfOXvBa22ngiu5TeDHfq8ny0FOn+N0TKDZoDiAVnYuQSQifHFeOHMWUa33e52fufwxyZ2VMTVYyFSkqQ0vo9jg2gQB9wsHEAjcbESP4sdMypApVGckF2LN4/750w7QaP/mp0bKFZVOf+sXzzfQB1DbmOXCEZcM4m2Yq7+MNfTtQCkhxlhvr48dYJY3RRcBwN2AizH64Z0hl4hifeziw1Im1sVpcbn8IrJh6b1b6w6/CcXGRgglE8hhigfMG+VAsRQhlvvKlTZ7pNIUS57VjCTbzbKmgE7EBr4HoPsBix9ntJg3H0yWuetpc+cGOgYcpI3SmrA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=82eEbFLeAJwiAVUpsUWaBqtDv0q+s8GO2xYBDp7JVcw=; b=QCs6RvsYimfK4B0YFGlUosseWbfYYoWe5ouqhGoffgROMJhrZ05o0/0vsefyQmPzX8WgRG1UVENOE+wxjLrHJog6y9VD/oM7ZrXpw2kHblsA3Ep1i2kxXDILuPy3IzYQFqTEHgKwBH/jBMqvPZN4SJBK4xyF5AitTeo1m8guBcim6sjRiqY7I454k+JLBzDmief4GKFECXMOqse8lWRhOMulWdlFeby9Mf7ggvg/ge1I0VWFh60MkqoMOkYz5MChbLep+A5xC+v3WQtA2qJoDUg4xA0pt8NSxlH5jJIHddm041BBRUrRbluL1UjiN8H1z+6yhPlzpN/tcuR8F/SSJg== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=nvidia.com; dmarc=pass action=none header.from=nvidia.com; dkim=pass header.d=nvidia.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=Nvidia.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=82eEbFLeAJwiAVUpsUWaBqtDv0q+s8GO2xYBDp7JVcw=; b=eL8HY5Rl/LIAWECR9PIVtTE+i2Q1lktthoYUlrpSzGvzY47nvImt3jdZnwDs3fmEmqa8xP6wRHR+uKZSXszyUlJ0CniocpSqZK44S4jHxqeXzVXnWVr+H+56RpOIQlKHtjriH8iz8lyDUSNS7fNjsJvYZJljZEtOO1RZ1XDuQnhTb4V6L6amfyKFnU+NAM7XOTAqyebtq2SLUB2AyIXiuNpayznSWheWql3ACPd+vTIXowgvXN8mH6SWtXclbN2KauAfhPhImHWyCaFfvz0y1OnJr3T6nrXV8hB4wWVBC3SEe0goIkOwsZbx9AZMPynII78h5UR39f3LtiPMLyJYng== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) by DM4PR12MB8475.namprd12.prod.outlook.com (2603:10b6:8:190::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9160.17; Tue, 30 Sep 2025 14:46:01 +0000 Received: from SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91]) by SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91%2]) with mapi id 15.20.9160.015; Tue, 30 Sep 2025 14:46:01 +0000 From: Joel Fernandes To: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org, dakr@kernel.org, acourbot@nvidia.com Cc: Alistair Popple , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , bjorn3_gh@protonmail.com, Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , David Airlie , Simona Vetter , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , John Hubbard , Joel Fernandes , Timur Tabi , joel@joelfernandes.org, Elle Rhumsaa , Yury Norov , Daniel Almeida , Andrea Righi , nouveau@lists.freedesktop.org Subject: [PATCH v5 8/9] rust: bitfield: Add hardening for out of bounds access Date: Tue, 30 Sep 2025 10:45:36 -0400 Message-Id: <20250930144537.3559207-9-joelagnelf@nvidia.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20250930144537.3559207-1-joelagnelf@nvidia.com> References: <20250930144537.3559207-1-joelagnelf@nvidia.com> Content-Transfer-Encoding: quoted-printable X-ClientProxiedBy: BL1P221CA0017.NAMP221.PROD.OUTLOOK.COM (2603:10b6:208:2c5::35) To SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SN7PR12MB8059:EE_|DM4PR12MB8475:EE_ X-MS-Office365-Filtering-Correlation-Id: 553a780a-8490-462c-764b-08de003012d5 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|7416014|376014; X-Microsoft-Antispam-Message-Info: =?us-ascii?Q?hiTDoRzqgyEzS+UpD+lISe5YSeSOqJ7OeRfLj92+D/a8kuP0NHZpmeR3M8KW?= =?us-ascii?Q?bama0fHnjkPEbiY/3WQktpuAPLTe0UAo7tG7fF99DB3WGSn1gPZYPQoCkg0P?= =?us-ascii?Q?s7CHREOUm6l7E7krdUBEorz0bVQpnOi0Q4nds3xXXTsZ7iv3ud0MjF8dICZK?= =?us-ascii?Q?eDJhGoehz6Z9FzPPjHQjBDX43QXQjdxRvEmlgbOCeCRTABGEtkY6HRMGsTrf?= =?us-ascii?Q?3OUP26LSLgxmMJIo9FeXdJetbpksjNzPP368VjpfWbmaNIV472QEk8CBPBpR?= =?us-ascii?Q?vMxDBoMjFHl0JHDesiMi3StSMpAWjQrfjGz9HcMzoCH6ob97MeKXNFYUIfdm?= =?us-ascii?Q?tbYVMmJ7+8BrmDrDXtlyCKj/CWP4HOUCsVhRuNeGvubaQjeBybC86LHlSJgG?= =?us-ascii?Q?C4HTQ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?= =?us-ascii?Q?ZBIJnhBPx/cH5Tp2hgQ5CypqCy9I8Dh6O/qULfuTijgNmG7SqgeXWIB9aAbG?= =?us-ascii?Q?eMGGadWQAsh8n82Eq2YYU+0JP5BWb8i39mKgFRkDHoHjAjsuuhWandFdOmcO?= =?us-ascii?Q?0jM6Q6y6uPLxxsqIb/zc8HrdWkQRnpNx?= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SN7PR12MB8059.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(366016)(1800799024)(7416014)(376014);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?us-ascii?Q?Jz4nd7iCoq1t+49HvHhEl4Ay32gDlzsw3YsoPEU5XrVVuKODiHlbR+Fx+3rJ?= =?us-ascii?Q?V3WM6hFsunKxOlequZb7gTViJaYofKkjOwE7B1zEk1Uv0ic7u4dfynXh/Ljc?= =?us-ascii?Q?foDMpZ24yqYJqa6pXkF3LWz491xBrGOaAm9zntLjLb0acKMEOKnaV+1jOD1f?= =?us-ascii?Q?hr7d4yCyWzbHxKimzn8qgVP6Ko05uASSdrpgTNp3wTU1A176dcUHvL5J+jpg?= =?us-ascii?Q?2cgcarBsgCPI+SGQXIUxAg0I9JZv3PsCxXfx6qhaPda0EvL+O9mUrP/J4NAj?= =?us-ascii?Q?4USlnWIeLMQ0C7hbnZ5NLwrLvvnvmwyj5valwcWgzs1grqoYkzti1FJRkI5d?= =?us-ascii?Q?UhEfXSYNFEV3Wpg0rLgMNjznjVGF8l3XflrCHS7EB83k1fYt0wgVgSO6l3hH?= =?us-ascii?Q?O23pSOAa5OLO/2SPq9taS9cmSKHRsHcFwg2cuqdfUb1s6CB3X9B3ow+10du/?= =?us-ascii?Q?tce+hDi0gctkNjUwSpXGwMLSmXg8hFMBl5pzLJ0JIAPUt1B5ncBE0WyM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4aeQkZv0VVa9gQU0As2eDk2Rg+OiWncxsKfnf+OsPx/QztEP?= =?us-ascii?Q?Q+LaoDvUgWoAesaIdjwJfwLFrkZU2rLHKvmMGBIqdyTlG23ZvHThVSA3d4WE?= =?us-ascii?Q?XxDr7Kyc37NlZYDCOZkovl2/bowoazAiSP+arH2mfPF+Iq/4jBGJ8Nn9DEPe?= =?us-ascii?Q?yApg3u9zKwv42FBXBs474c6snguJ3bYc1KmrsrHL?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 553a780a-8490-462c-764b-08de003012d5 X-MS-Exchange-CrossTenant-AuthSource: SN7PR12MB8059.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Sep 2025 14:46:00.9021 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 43083d15-7273-40c1-b7db-39efd9ccc17a X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: CPNwlf7PuRzp2WCNhOPO1fTlOU/mUNnkCWR9S3nUEpCGcdMNybkH/YzCRRUb1Sc5or7/OXujWloHQPYnkG57wA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM4PR12MB8475 Content-Type: text/plain; charset="utf-8" Similar to bitmap.rs, add hardening to print errors or assert if the setter API is used to write out-of-bound values. Suggested-by: Yury Norov Signed-off-by: Joel Fernandes --- rust/kernel/bitfield.rs | 32 +++++++++++++++++++++++++++++++- security/Kconfig.hardening | 9 +++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs index a74e6d45ecd3..655f940479f1 100644 --- a/rust/kernel/bitfield.rs +++ b/rust/kernel/bitfield.rs @@ -29,6 +29,20 @@ pub const fn into_raw(self) -> T { } } =20 +/// Assertion macro for bitfield +#[macro_export] +macro_rules! bitfield_assert { + ($cond:expr, $($arg:tt)+) =3D> { + #[cfg(CONFIG_RUST_BITFIELD_HARDENED)] + ::core::assert!($cond, $($arg)*); + + #[cfg(not(CONFIG_RUST_BITFIELD_HARDENED))] + if !($cond) { + $crate::pr_err!($($arg)+); + } + } +} + /// Bitfield macro definition. /// Define a struct with accessors to access bits within an inner unsigned= integer. /// @@ -358,9 +372,25 @@ impl $name { $vis fn [](mut self, value: $to_type) -> Self { const MASK: $storage =3D $name::[<$field:upper _MASK>]; const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; + const BITS: u32 =3D ($hi - $lo + 1) as u32; + const MAX_VALUE: $storage =3D + if BITS >=3D (::core::mem::size_of::<$storage>() * 8) as u= 32 { + !0 + } else { + (1 << BITS) - 1 + }; + + // Check for overflow - value should fit within the field's bi= ts. // Here we are potentially narrowing value from a wider bit va= lue // to a narrower bit value. So we have to use `as` instead of = `::from()`. - let val =3D ((value as $storage) << SHIFT) & MASK; + let raw_field_value =3D value as $storage; + + $crate::bitfield_assert!( + raw_field_value <=3D MAX_VALUE, + "value {} exceeds {} for a {} bit field", raw_field_value,= MAX_VALUE, BITS + ); + + let val =3D (raw_field_value << SHIFT) & MASK; let new_val =3D (self.raw() & !MASK) | val; self.0 =3D ::kernel::bitfield::BitfieldInternalStorage::from_r= aw(new_val); =20 diff --git a/security/Kconfig.hardening b/security/Kconfig.hardening index 86f8768c63d4..e9fc6dcbd6c3 100644 --- a/security/Kconfig.hardening +++ b/security/Kconfig.hardening @@ -265,6 +265,15 @@ config RUST_BITMAP_HARDENED =20 If unsure, say N. =20 +config RUST_BITFIELD_HARDENED + bool "Check integrity of bitfield Rust API" + depends on RUST + help + Enables additional assertions in the Rust Bitfield API to catch + values that exceed the bitfield bounds. + + If unsure, say N. + config BUG_ON_DATA_CORRUPTION bool "Trigger a BUG when data corruption is detected" select LIST_HARDENED --=20 2.34.1 From nobody Thu Oct 2 22:52:49 2025 Received: from SA9PR02CU001.outbound.protection.outlook.com (mail-southcentralusazon11013005.outbound.protection.outlook.com [40.93.196.5]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3CAC73090E8; Tue, 30 Sep 2025 14:46:16 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=40.93.196.5 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243577; cv=fail; b=pDETJoMjbDoKV9tg46x4UVmPoZ40deJarVOvITw/m4qTty6oHaVuKZR4nnN+Xl0kR0zZ9IgalJm1NOsHM/TLPhNqZMlXtUB2DhLerq72WJjDQ8F5EL4a6ms9ulzbKRdsf5Xujl6C883kepoqOKRPkgK/miujmIRuZnNUqnytfqg= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759243577; c=relaxed/simple; bh=XuYzRNR2Dvb0gYPXyLeWAaJX0p8wm+SV8Hb5IHVPCzw=; h=From:To:Cc:Subject:Date:Message-Id:In-Reply-To:References: Content-Type:MIME-Version; b=K8R3rREzV+tEl4BPAZ/EuQmgLYxMh7eNC1ojSZnkA8IB/zDdpFf4rTPdmJHStIz5CUp/LHO/l5bBxkbmkOvyu/nzsORW6BEtNd582vwDHToyh59tp1CoZsGPqHYhw9XdIHB8+H1QtQJ0ISBPbG8jYv5vVnPh/4Eki4n2+0MY9Fo= ARC-Authentication-Results: i=2; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com; spf=fail smtp.mailfrom=nvidia.com; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b=ti6Fl5bw; arc=fail smtp.client-ip=40.93.196.5 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=nvidia.com Authentication-Results: smtp.subspace.kernel.org; spf=fail smtp.mailfrom=nvidia.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=Nvidia.com header.i=@Nvidia.com header.b="ti6Fl5bw" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=UI1jmLD5ayFI0GJvMeuNf+JvRPDAo4cFdgu9fgreHEqCFsccojU0dreSnHddG7C1Joo4kPTbpt/YFTLJdjt+Tzg8YECtllZWl0Hmcs5eOyLDC822Ob/UacYa2xtg8ggRUEaNYoZaR5cCQtSnpB2v3iOrTt7MRiWVoUrkw+jiICZwngSXAbVn3Y2LSURMs+RZMiEkD6tgukRVZ7fhQYeEllgvLwOEZ3uvUgrsHkJlPo1iNzdZFvwMousTwClsW+yjSLsJ6+Att1Lj+xtGmQkyRL/RJYb86ENiTPlkZLu6VKBfjavPo3wBd/ffjszGSgw46vVkyszaJ6UIZnfwfiFtew== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector10001; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=8vKBziK4if3SD7aI5boBApPldSrAxEwqRs+2ud+8YaI=; b=IBfKmBPrSmfkHFhtBpRmMiCMbhFx41F0li1Q9l1/oaJIoe2DqrEu3kNzRyWFkb3JO9kpkWfEr+Yn0lepEG5ZHrkED15MJNcVdF/k6NpWXZnw08TpXerzhOYEFqyr4SCqHrc1jR5rtGdpB5Wadpx3B7jt6QOQ0srQpg3CrIbD4MyaS4bmSGcQOTMnS9yuHqLNZEH3qqOQs6wYt5X5YfXjJNlm87juWB3ckPnO7paDd7dUTV3UC35Rvq9hFr4Ft0pbKD7sx2vs0jX6HFwsbpziDc7kMrAv+Ee9tIi33VaMhUfLNS3ooEi8n1WCwVCDpUPkulmimk3ct8gkgszZmW9KWA== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=nvidia.com; dmarc=pass action=none header.from=nvidia.com; dkim=pass header.d=nvidia.com; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=Nvidia.com; s=selector2; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=8vKBziK4if3SD7aI5boBApPldSrAxEwqRs+2ud+8YaI=; b=ti6Fl5bwhqKvu+yc6Hn7svrLvpugOGRVgL134UB6SQ0NLnzeALOwNxt6W/u8ETizFqA6FvsZNBsY92p6mVovMcJpkfDdLnzw2V3Y3tWZ3tajo8vi3n85Fcc7dHTb3ZXItROhB68wlqVmGERnIdN6nZvM8qQbb1T0B01ZX0q7gbbfJyicudSV7EiHQcT6AVHSNE4IIAVdGONvWPrN6TFtqkFkClvaR+29afimscx9k13Um2isdvZ06DSbUGCDCSd1AumKYQ3pFsTsr/OTSMymUB1XCm6dbQPVNJVOI+j2YS9Qy21Jy+z0L/ZhUf9DNqE70gxJByPzWI8pWXxmTjwAJg== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) by DM4PR12MB8475.namprd12.prod.outlook.com (2603:10b6:8:190::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9160.17; Tue, 30 Sep 2025 14:46:02 +0000 Received: from SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91]) by SN7PR12MB8059.namprd12.prod.outlook.com ([fe80::4ee2:654e:1fe8:4b91%2]) with mapi id 15.20.9160.015; Tue, 30 Sep 2025 14:46:02 +0000 From: Joel Fernandes To: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org, dakr@kernel.org, acourbot@nvidia.com Cc: Alistair Popple , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , bjorn3_gh@protonmail.com, Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , David Airlie , Simona Vetter , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , John Hubbard , Joel Fernandes , Timur Tabi , joel@joelfernandes.org, Elle Rhumsaa , Yury Norov , Daniel Almeida , Andrea Righi , nouveau@lists.freedesktop.org Subject: [PATCH v5 9/9] rust: bitfield: Add hardening for undefined bits Date: Tue, 30 Sep 2025 10:45:37 -0400 Message-Id: <20250930144537.3559207-10-joelagnelf@nvidia.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20250930144537.3559207-1-joelagnelf@nvidia.com> References: <20250930144537.3559207-1-joelagnelf@nvidia.com> Content-Transfer-Encoding: quoted-printable X-ClientProxiedBy: BL1P221CA0022.NAMP221.PROD.OUTLOOK.COM (2603:10b6:208:2c5::16) To SN7PR12MB8059.namprd12.prod.outlook.com (2603:10b6:806:32b::7) Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: SN7PR12MB8059:EE_|DM4PR12MB8475:EE_ X-MS-Office365-Filtering-Correlation-Id: 90827608-9706-4dcb-54e4-08de003013de X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|366016|1800799024|7416014|376014; X-Microsoft-Antispam-Message-Info: =?us-ascii?Q?0MWV1nD4etnuplflirj13De8WloMcyUB4C6jDYbrhIWm4qY97wfm0jdmuRdT?= =?us-ascii?Q?W7oi7NWs6Xg/1DZIIagEeBF5jxJOWBjOuJ0rh61vIn1kMXY5pAH3AoweWbQA?= =?us-ascii?Q?sfsfPYFk85Sh7lkqPW/509HDMW44/Yqm925FLqE5ugaHn6+0mfvKAbhm/OLK?= =?us-ascii?Q?nc8GxkMTpXZtK2XgAzwwkNwrn4eYHXimimGVyLR/fKvl/mVSKYm1S2ym978c?= =?us-ascii?Q?A4PMO2nOfUkz659dSwl00WbZ3VhXy5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REGYZ5zegx9iSEPn0AuDNvCyfeqINqBlgcmbPuEo90WqaZgLwPVX?= =?us-ascii?Q?cAzvNSjmGa2qGrBBaatyvBW9BeM/x93rqrQjHEoNkF9njLfpxDLi+izpWYAZ?= =?us-ascii?Q?d3OeM1niQ7bN+5voyhGbuuNT4uL8ag5tlC+qlHxld6EurTzc6HKEw3P0bhuP?= =?us-ascii?Q?NOVsi2SS7qmzOcymOb3v1Q1yTlTim+D0wsaqvy4A/VidjxFu0qjE56v2BuJN?= =?us-ascii?Q?Mg16JMmwQHzp97qCqUwqAfmQBtu84kRtVKqNmPM5HA1tsqKZ6+r53LqI0hOW?= =?us-ascii?Q?w0NoPRR2X1OJ0EYqKK6Ct6nHUW4v/gAy?= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:SN7PR12MB8059.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(366016)(1800799024)(7416014)(376014);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?us-ascii?Q?EJ6gy0e0okXXI7QBVv+BcwI8HwleRJZ8nB06NpiQx+TRSgW6y7AGvHy/1SgO?= =?us-ascii?Q?4D2qOKXsHC8naZuPD/fZSoitpXQ6GA1JmMluNw45DaCt4BoigOLOTeWgsKZn?= =?us-ascii?Q?yNRnKMR49xzXHK5YyGCRxRLXx1lmfGJDYGqsfAw5Lsnq2BoKwjzEESHT8uiw?= =?us-ascii?Q?9t7yuBlbloQdZabRVBZ4n8NB7PymaqrlzKBsqQ8lPfUxP/1//Nj7TvqZo/lE?= =?us-ascii?Q?bAjb3LuDdCOEIEGDGBiDK/4+b4hZWAAlqpTC+/eYV06YxE54asW3wXV6xnsC?= =?us-ascii?Q?8aIkmSfzalZYL7KZ8sEVBlIDzG7M4zTdLWdVEmLG9rG+sW9WIZyBWDgt5eV9?= =?us-ascii?Q?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abJ0Ha7QCyA90Yk/99ClkiYCdx?= =?us-ascii?Q?7XK22UxRqbVTR9GxToMHLs2c9tH5dKf+29WGsYpFuvVisAqDl9af3ArBmnKk?= =?us-ascii?Q?5JLZWNVrw2j2zIsd+TVLut0FPg9vrPe8ISBGjsOK4P4Oris/OjuFqepDsAvP?= =?us-ascii?Q?Dkhku5pVJme3Zw4iWC76V9+poQ3dO1c/3f0IC8/VZPmWvTw+KaNtuj4rFzmy?= =?us-ascii?Q?uVhUOm1Avk78TOSPXEVZOcZRvZG0XUgqWtmBieZCFkoT2I+aTJJyHZNVN/NY?= =?us-ascii?Q?+SwUqrbue75/U1DH5kS/jv6tNw3geswT/FMkf7a1h+ONAoVbpD2niKkphYMo?= =?us-ascii?Q?6dSdtvokTL2w7eHIct+l5g1gMd4wQdF414rwV8pa?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 90827608-9706-4dcb-54e4-08de003013de X-MS-Exchange-CrossTenant-AuthSource: SN7PR12MB8059.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 30 Sep 2025 14:46:02.6852 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 43083d15-7273-40c1-b7db-39efd9ccc17a X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: TZEDnPDicfAQ3SwEPejUEigTXXXvq+WMcrHAHm1UXgyVXoDJm12avj8778JMJyECs6kypCyWZKl8lC4y0+4mYw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM4PR12MB8475 Content-Type: text/plain; charset="utf-8" When creating a new bitfield, it is possible that the value contains bits set. Such usage can be the result of an error in the usage of the bitfield. Print an error in regular configs, and assert in a hardened config (CONFIG_RUST_BITFIELD_HARDENED). If the design is deliberate, the user may silence these errors or assertions by defining the bitfield as reserved. Suggested-by: Yury Norov Signed-off-by: Joel Fernandes --- rust/kernel/bitfield.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs index 655f940479f1..606494bf4245 100644 --- a/rust/kernel/bitfield.rs +++ b/rust/kernel/bitfield.rs @@ -117,7 +117,9 @@ macro_rules! bitfield_assert { /// ``` /// /// This generates a struct with: -/// - Constructor: `new(value)` - creates a bitfield from a raw value, zer= oing undefined bits +/// - Constructor: `new(value)` - creates a bitfield from a raw value, zer= oing undefined bits. +/// If any of the bits passed are set, but not defined as a bitfield, an= error is printed. +/// To silence these errors, either define all fields or initialize the = bit positions to 0. /// - Raw accessor: `raw()` - returns the underlying raw value /// - Field accessors: `mode()`, `state()`, etc. /// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining = with builder pattern). @@ -236,6 +238,10 @@ impl $name { /// This constructor zeros out all bits that are not defined b= y any field, /// ensuring only valid field bits are preserved. This is to p= revent UB /// when raw() is used to retrieve undefined bits. + /// + /// If any of the bits passed are set, but not defined as a bi= tfield, + /// an error is printed. To silence these errors, either defin= e all fields + /// or initialize the respective bit positions to 0. #[inline(always)] $vis fn new(value: $storage) -> Self { // Calculate mask for all defined fields @@ -245,6 +251,18 @@ impl $name { mask |=3D Self::[<$field:upper _MASK>]; ); )* + + // Check if any undefined bits are set + $crate::bitfield_assert!( + (value & !mask) =3D=3D 0, + concat!( + "Value 0x{:x} has bits set outside of defined fiel= d ranges ", + "(mask: 0x{:x}). To avoid this assertion, either d= efine all ", + "fields or initialize unused bits to 0." + ), + value, mask + ); + // Zero out undefined bits and wrap in BitfieldInternalSto= rage Self(::kernel::bitfield::BitfieldInternalStorage::from_raw= (value & mask)) } --=20 2.34.1