From nobody Sat Feb 7 11:30:56 2026 Received: from DM1PR04CU001.outbound.protection.outlook.com (mail-centralusazon11010008.outbound.protection.outlook.com [52.101.61.8]) (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 04B902E2845; Thu, 9 Oct 2025 12:37:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.61.8 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760013455; cv=fail; b=UD2En9/MaQxYz5ieUJwvG7oRc06JgmBMmovUwxntLPJrK5NaCaKp5IKVaZG2sc+ozttTrq27jHIJaurxwXWARpRh2I3uFSk2OjwYF29TOG3XMRywCEHd30ghUcQWA9wyHVI0riywtCi4khGLpOFpBceKn+a0HJ6uhuEad8xOlYs= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760013455; c=relaxed/simple; bh=tSeR9TdA+q90HYvcf+6oKrfKao9sXI4N6Fgito7Hl+k=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=NWuWAgZl334iGRl/rUgR45fRSF/bDhmBq9anFAysETmCXVmESbOBPx36gnpl1cqsYOEzmtBqvcBMaLxDnP4CNpaZwcEf8xokr1MSeFZZCChJBOIW+Ppe3iYqxp2+UcyT/qGObgjFgcUC5PKnMXUZRSq0v9uxQmz9HCC9pMtrZgc= 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=AuXczbLi; arc=fail smtp.client-ip=52.101.61.8 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="AuXczbLi" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=DKvoluWRmith0nEQNap+yvsdPJErGG/Rj34kEofqm4D2KTRro2th0frS2rGzVTWh7fVdZUdISTg5G7HCPcduRdLGf6QhCjp2zV/V8sflviq0sSlgOdkK40U6Au2WuV0Hnmx7WT6KJ6pYKtYhScYgQlGp2QoaYTBsRfoxn8p/Fz5LP7+j9Ir8dUh/68UnACtdMwqOw28/gjDhUytdptAxO1zFbEAPdeIqqLhVvlDmckblHTQq+Yzwxhz0wW50GUbik29zjUjtfNLWAZhBI69uLLkVEAzx/3zL3kbJb4H1Gguxnpp7iRHR+J6NRghzO1a2PhEwb2KJetq9Vfvlobg19A== 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=y7WBR0kFbgD6TqD0z3deiHutQLa8aDPTqkNbPWDcsB8=; b=zLngqSjxiCJrMT8PjlVOKuFGhGfzhcPfu6NVx8/ebAtuTpGF9LFqZwH6X8orp5OyIcLE4Z2cEGANsU/faoupN9yZnd4p5zX0+EWkw5FZkFmKirHjU6VvCusMph3cqmfJHNmoeQx/q/WiDOnysnuoRT9W3Acq5fKXtKamakHsuHcUZvvc7cf22WezYdV93+FFpja3wuKnscM7Y3mvCmX3KM+55GH+z3Q7woLHOGSlzStRHandmah11jaz5ez006soGioYmwzgS5NqbnrKaLeeJDMOjwinpgJw9HAO2LtK7B1AvJjzs2CqlEr+eKAY9ozErCLyJL3BqC0yAXt4S0hneQ== 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=y7WBR0kFbgD6TqD0z3deiHutQLa8aDPTqkNbPWDcsB8=; b=AuXczbLiJmucyyFQntEtWUShg102deB7+9CBwoG95aBD+0gZ1N5NtKZJKKPWP8DM8q+V8EebxFgaKLJDfnLhX3PfvMZ5Fi7VgkCbPYX4fLUhwL7Itl05hMnWpoEnjF1YUvS8GAH8RMdo8pjdeLGH/WLSO0ekC4N8mBEInzWgv40j7BqGh2sh2fKOrPGwgzlERr8Z4JIi3LywWIjHvEdtp4h0/VJY1J/89v7/7bUqQy8YRFzJ0xQ7yeVlftuqdpraBC1TKzK81eikpIqa/U1nDmBdUjGliOrbByEMEZX+zrQaWFKQf2U/ppOOSEuPhjZfmS0jYYmBV2AMZd92NN595w== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from CH2PR12MB3990.namprd12.prod.outlook.com (2603:10b6:610:28::18) by CY8PR12MB8315.namprd12.prod.outlook.com (2603:10b6:930:7e::8) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9203.9; Thu, 9 Oct 2025 12:37:28 +0000 Received: from CH2PR12MB3990.namprd12.prod.outlook.com ([fe80::7de1:4fe5:8ead:5989]) by CH2PR12MB3990.namprd12.prod.outlook.com ([fe80::7de1:4fe5:8ead:5989%6]) with mapi id 15.20.9203.009; Thu, 9 Oct 2025 12:37:28 +0000 From: Alexandre Courbot Date: Thu, 09 Oct 2025 21:37:08 +0900 Subject: [PATCH RFC v2 1/3] gpu: nova-core: register: use field type for Into implementation Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20251009-bounded_ints-v2-1-ff3d7fee3ffd@nvidia.com> References: <20251009-bounded_ints-v2-0-ff3d7fee3ffd@nvidia.com> In-Reply-To: <20251009-bounded_ints-v2-0-ff3d7fee3ffd@nvidia.com> To: Danilo Krummrich , Joel Fernandes , Yury Norov , Jesung Yang , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross Cc: nouveau@lists.freedesktop.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alexandre Courbot , Edwin Peer X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYCP286CA0101.JPNP286.PROD.OUTLOOK.COM (2603:1096:400:2b4::14) To CH2PR12MB3990.namprd12.prod.outlook.com (2603:10b6:610:28::18) 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: CH2PR12MB3990:EE_|CY8PR12MB8315:EE_ X-MS-Office365-Filtering-Correlation-Id: 3250571d-8dcc-47d6-3203-08de07309b94 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|376014|1800799024|7416014|366016|10070799003|921020; X-Microsoft-Antispam-Message-Info: =?utf-8?B?ZCtGVFMrZklZaS9Ya09YbmViMkNOYWs3NXZxNGVnWnUxU201YmZwTTVucHY2?= =?utf-8?B?M3h3QUw2NStWeVJPS3g5RFF0d3dvdTByakMrZnE4ZElwSjFpWWRtSWZWVTl1?= =?utf-8?B?KzIrZ094MzFsM3ZkRG5UR1pOUVRQaWJKNGgyZ290emxoTk53czYxc1F6UDdO?= =?utf-8?B?REc3eDA3cjBtajU3bE9tUy9lKzkvVU8wdm1Yb0E5SWRLWWUxdU5qMzQ4ZXVh?= =?utf-8?B?Ky9vL1djQksxSkZxZ3VNN3JUOEQvcFZuQ3o5Sit2c0N5T1lJdGJ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:CH2PR12MB3990.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(376014)(1800799024)(7416014)(366016)(10070799003)(921020);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?QUhzU0VVcGJobTNiZUpjS3VRL2tIUGd5cUlQUjk3blRieTRBTEFlaHN4TVc1?= =?utf-8?B?Vm1XcWUxZUZtaFpUYXFCZy9vRmVZNjBvaE9FUkpCbDNCNmcyQzhDRjlkNExQ?= =?utf-8?B?Ti9uQ3R1bWlkdFl1VytmVFNKY09YaGI0MlMrTG00OEIwM0VwN0ExaE9oeEs0?= =?utf-8?B?RmpUL0xRa2YvdlJ5NHZhL2tQRWZuV2VTblA2N2l4OG1rQnJyTFhBbUJvYUpQ?= =?utf-8?B?cDhJTExMTnMwS3VIMnJLL2U0ZmdTK3Z6NEVFVjFqbkZ2akVoMGxPWTlOMmx0?= =?utf-8?B?U0VtaUNKNGhPU2dpSU9TNjMvbngxVnZCWSs2UFk0NHhpSFJGbzNWZmxLamVx?= =?utf-8?B?L0pWR3E2SHBUSFVSQWp6WjZOM0M5dGNTRTZDNE8za25XcThQWjNBQjQ4YlQy?= =?utf-8?B?L28vd1lVREFIZ2IvVlhXWmw5akM5VDZDdTVTRysydXhXeTdsWDVpWjhIWUV3?= =?utf-8?B?TDZ3aE96a21SZkxQMnJQRmt3ZWo4WHI1Q0IzcitSQ3U5alJpT2c3WGJqZkVP?= =?utf-8?B?aTBYMDRCTWRReDFqVHRNMk5ZdTdhVnJnaFhWK09jcnJvcCswQkZ0STBpcFU0?= =?utf-8?B?b3BqckcwUUNIUHk4MEFDRjhRQU5BQTNObnRXRGdPMHJtVmRkWCtyeVovK3Bk?= =?utf-8?B?NjVuSk9uSnBrN1VaaXhlUnpmdFFpMWF3K2pkekdxVVpWSUY1T281V0JGajVp?= =?utf-8?B?Y2NOQUZpMEVHTHB4SVZXSXAxcnlUNko2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bVdiUnlzdTd0bVhHaVAyQ2NxZXBvVDZ3dllSNjlZZUZN?= =?utf-8?B?Z1pBUHRqeDBNRUZNY2lFTGlDbW8xaHJZTS9LR0ZWeW5SOWhOMnpFT1hHemND?= =?utf-8?B?WjVRaUI5Q3pYQ1ZmY21yeGdrM0Y5eW9MdG9aNnZRTTExU24yQ0lDeVBiNjBO?= =?utf-8?B?aFF5dE1xLzJnUElTMDBxNEM0eGh5bDBoTEtFeTJrWE1qSGpIb3dsQTlMNFY5?= =?utf-8?B?RHJhQWxFTzFHRTJRTUVlZnJYZ3ZXWnNUMFhoQU0xVXBwOG9zRnZSZ0QxMEY5?= =?utf-8?B?M3pObEJoZms4WG9ncGw2dGxkMTY1NmZCTE5aVHVWMmZZeUhVdXc4eFREMEV4?= =?utf-8?B?SytpS1B4UWFyaG0zYTE3bkRLQWlnM0xwelZKQktCNVlzTHZmODFKTDJpRWVB?= =?utf-8?B?ZjdnWEJNUFBzdytNRG44L3pXcDV3MEVxclBSM2h0cElxSGRDSjd4USsvYnZz?= =?utf-8?B?YVBQa0tQOWhBb0Zib1J4WmREeFBUcENHbFNNSHZkK1JRMitUaXBmaFZNK3NW?= =?utf-8?Q?rdwIsiO7V+V/lTgdWHAPguWCDlf32tFAOh049f99g9JY?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 3250571d-8dcc-47d6-3203-08de07309b94 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 09 Oct 2025 12:37:28.4377 (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: BGczkW3tXV4DkGWn/ykj1vaA8F3HpaAV2eNNudGR62jOBpqtQ3AHCqLBgZnFW3SGLSj087/q2Q+IogOsAjNVDw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: CY8PR12MB8315 The getter method of a field works with the field type, but its setter expects the type of the register. This leads to an asymmetry in the From/Into implementations required for a field with a dedicated type. For instance, a field declared as pub struct ControlReg(u32) { 3:0 mode as u8 ?=3D> Mode; ... } currently requires the following implementations: impl TryFrom for Mode { ... } impl From for u32 { ... } Change this so the `From` now needs to be implemented for `u8`, i.e. the primitive type of the field. This is more consistent, and will become a requirement once we start using the TryFrom/Into derive macros to implement these automatically. Reported-by: Edwin Peer Signed-off-by: Alexandre Courbot Reviewed-by: Edwin Peer Reviewed-by: Joel Fernandes --- drivers/gpu/nova-core/falcon.rs | 38 +++++++++++++++++++++++++-------= ---- drivers/gpu/nova-core/regs/macros.rs | 10 +++++----- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/drivers/gpu/nova-core/falcon.rs b/drivers/gpu/nova-core/falcon= .rs index 37e6298195e4..3f505b870601 100644 --- a/drivers/gpu/nova-core/falcon.rs +++ b/drivers/gpu/nova-core/falcon.rs @@ -22,11 +22,11 @@ pub(crate) mod sec2; =20 // TODO[FPRI]: Replace with `ToPrimitive`. -macro_rules! impl_from_enum_to_u32 { +macro_rules! impl_from_enum_to_u8 { ($enum_type:ty) =3D> { - impl From<$enum_type> for u32 { + impl From<$enum_type> for u8 { fn from(value: $enum_type) -> Self { - value as u32 + value as u8 } } }; @@ -46,7 +46,7 @@ pub(crate) enum FalconCoreRev { Rev6 =3D 6, Rev7 =3D 7, } -impl_from_enum_to_u32!(FalconCoreRev); +impl_from_enum_to_u8!(FalconCoreRev); =20 // TODO[FPRI]: replace with `FromPrimitive`. impl TryFrom for FalconCoreRev { @@ -81,7 +81,7 @@ pub(crate) enum FalconCoreRevSubversion { Subversion2 =3D 2, Subversion3 =3D 3, } -impl_from_enum_to_u32!(FalconCoreRevSubversion); +impl_from_enum_to_u8!(FalconCoreRevSubversion); =20 // TODO[FPRI]: replace with `FromPrimitive`. impl TryFrom for FalconCoreRevSubversion { @@ -125,7 +125,7 @@ pub(crate) enum FalconSecurityModel { /// Also known as High-Secure, Privilege Level 3 or PL3. Heavy =3D 3, } -impl_from_enum_to_u32!(FalconSecurityModel); +impl_from_enum_to_u8!(FalconSecurityModel); =20 // TODO[FPRI]: replace with `FromPrimitive`. impl TryFrom for FalconSecurityModel { @@ -157,7 +157,7 @@ pub(crate) enum FalconModSelAlgo { #[default] Rsa3k =3D 1, } -impl_from_enum_to_u32!(FalconModSelAlgo); +impl_from_enum_to_u8!(FalconModSelAlgo); =20 // TODO[FPRI]: replace with `FromPrimitive`. impl TryFrom for FalconModSelAlgo { @@ -179,7 +179,7 @@ pub(crate) enum DmaTrfCmdSize { #[default] Size256B =3D 0x6, } -impl_from_enum_to_u32!(DmaTrfCmdSize); +impl_from_enum_to_u8!(DmaTrfCmdSize); =20 // TODO[FPRI]: replace with `FromPrimitive`. impl TryFrom for DmaTrfCmdSize { @@ -202,7 +202,6 @@ pub(crate) enum PeregrineCoreSelect { /// RISC-V core is active. Riscv =3D 1, } -impl_from_enum_to_u32!(PeregrineCoreSelect); =20 impl From for PeregrineCoreSelect { fn from(value: bool) -> Self { @@ -213,6 +212,15 @@ fn from(value: bool) -> Self { } } =20 +impl From for bool { + fn from(value: PeregrineCoreSelect) -> Self { + match value { + PeregrineCoreSelect::Falcon =3D> false, + PeregrineCoreSelect::Riscv =3D> true, + } + } +} + /// Different types of memory present in a falcon core. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum FalconMem { @@ -236,7 +244,7 @@ pub(crate) enum FalconFbifTarget { /// Non-coherent system memory (System DRAM). NoncoherentSysmem =3D 2, } -impl_from_enum_to_u32!(FalconFbifTarget); +impl_from_enum_to_u8!(FalconFbifTarget); =20 // TODO[FPRI]: replace with `FromPrimitive`. impl TryFrom for FalconFbifTarget { @@ -263,7 +271,6 @@ pub(crate) enum FalconFbifMemType { /// Physical memory addresses. Physical =3D 1, } -impl_from_enum_to_u32!(FalconFbifMemType); =20 /// Conversion from a single-bit register field. impl From for FalconFbifMemType { @@ -275,6 +282,15 @@ fn from(value: bool) -> Self { } } =20 +impl From for bool { + fn from(value: FalconFbifMemType) -> Self { + match value { + FalconFbifMemType::Virtual =3D> false, + FalconFbifMemType::Physical =3D> true, + } + } +} + /// Type used to represent the `PFALCON` registers address base for a give= n falcon engine. pub(crate) struct PFalconBase(()); =20 diff --git a/drivers/gpu/nova-core/regs/macros.rs b/drivers/gpu/nova-core/r= egs/macros.rs index 754c14ee7f40..73811a115762 100644 --- a/drivers/gpu/nova-core/regs/macros.rs +++ b/drivers/gpu/nova-core/regs/macros.rs @@ -482,7 +482,7 @@ impl $name { register!( @leaf_accessor $name $hi:$lo $field { |f| <$into_type>::from(if f !=3D 0 { true } else { false }) } - $into_type =3D> $into_type $(, $comment)?; + bool $into_type =3D> $into_type $(, $comment)?; ); }; =20 @@ -499,7 +499,7 @@ impl $name { $(, $comment:literal)?; ) =3D> { register!(@leaf_accessor $name $hi:$lo $field - { |f| <$try_into_type>::try_from(f as $type) } $try_into_type = =3D> + { |f| <$try_into_type>::try_from(f as $type) } $type $try_into= _type =3D> ::core::result::Result< $try_into_type, <$try_into_type as ::core::convert::TryFrom<$type>>::Error @@ -513,7 +513,7 @@ impl $name { $(, $comment:literal)?; ) =3D> { register!(@leaf_accessor $name $hi:$lo $field - { |f| <$into_type>::from(f as $type) } $into_type =3D> $into_t= ype $(, $comment)?;); + { |f| <$into_type>::from(f as $type) } $type $into_type =3D> $= into_type $(, $comment)?;); }; =20 // Shortcut for non-boolean fields defined without the `=3D>` or `?=3D= >` syntax. @@ -527,7 +527,7 @@ impl $name { // 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)?; + { $process:expr } $prim_type:tt $to_type:ty =3D> $res_type:ty = $(, $comment:literal)?; ) =3D> { ::kernel::macros::paste!( const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive =3D= $lo..=3D$hi; @@ -559,7 +559,7 @@ pub(crate) fn $field(self) -> $res_type { 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; + let value =3D (u32::from($prim_type::from(value)) << SHIFT) & = MASK; self.0 =3D (self.0 & !MASK) | value; =20 self --=20 2.51.0 From nobody Sat Feb 7 11:30:56 2026 Received: from DM1PR04CU001.outbound.protection.outlook.com (mail-centralusazon11010023.outbound.protection.outlook.com [52.101.61.23]) (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 5DEC62E1F1F; Thu, 9 Oct 2025 12:37:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.61.23 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760013459; cv=fail; b=Kwbo31QHQVisSb2TXnYyXTsQA32ytCF20K6SBwWli5bgsf5SxiQmnqkhuc7e1CLFRjqOYlN9yQFkxym2cXdXZe/lm2yQ4jrNlp6O5d64RnT4M5c0oZwl8MWwlkoOoG3IsqbKJ17mqv0bn8uMsXAEywBT8yavDYScstAV3Xaf+LA= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760013459; c=relaxed/simple; bh=XDlmTAxXlysxKQDh8qxFDzDOG8RQIjhEWW3C3sWRHiU=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=TXseErjiZ4f71l+6trplAF6DzWtGwwDoNga1A57JfjeR5X7rPO8cXxmUr0DgpjoTW7eybimwUOxrSCWHR8KrYKH9PW+pL4PWbRQrMX3QCMHxEWDgu0Dlnkh+vDZPbtSUy/76BwRmIEqBqL+GBJN4LS2NsX606urtIcMiSm1GMc4= 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=b94ywZ2+; arc=fail smtp.client-ip=52.101.61.23 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="b94ywZ2+" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=QN/weG+s1PSKElqopoomqt0tMAOUPLAT5jOByH5/R2i+K2DxNtsJ3gZIGS3jUpdb9muyrGdMKtNZjzlgdEbOOGnuNUKCXOn+73Q0xB7d6XVyIE0QT6QaIoRoKAoaPIB1Ag1hcYDqta6la5QukmM5qimUMt7T3ig5XbBy2/uxZcggZpcxmxKpjf+UgG4VB0c0Ni4P4FJpUxrEW8GoQC84Re9nObtgALrkszxUlnYc+0kSJmNYfsSFRV7y7Ztv8xdlwT8wqj0aUu/34A0v9w6qsMko32fedDjcUPlggTn0HwpSXk5Id9q1Y3jiR9MsUKtehRvdMKj+jgqFH8RsrZYtvw== 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=qH+yJLowws0j6nJTSuZDoxWZdEtWofDOV4UK1VDo+9g=; b=k2IEdeDbxpiEo2ScUjMHtonvAYLlJW3DFixxSeyhciOcVKP5wxYq9RvIZ4xHYCteO9QDj6547R0k7UL+I4eJAoYYKd2T9XJ30wUoXLvBVSwqYsIXROZunEtcjHC/QxKmEXmVff7r25BC4i7AkQAh4LYIgOpJYDknH5jg99wRrZmLpKY1oVUdqwHTH/pmx36/qgjMFVTP8NbrBoKpCTQs4pqBAZosGJB8rRqvJhahCRKhknzwt9C4ahE6uyZdtI70EXXPc5KsZbHbp8heCH5me5189mVUaVTHZ42Xolpzz2lH56YDUjdVmrknZE7NRJqMWbdwmmhWJoYJN8ftqGiKGg== 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=qH+yJLowws0j6nJTSuZDoxWZdEtWofDOV4UK1VDo+9g=; b=b94ywZ2+e33iS6R/6lbMKtwcwOCC2UK+1nj1O3X5SYTEa3VvSvUHw85qYCbzcrirDU5d/lQVFXRhrfR0W7CitishCICQh6I9eyxqMYOLLEPqB/Km6vC6o6MEoP4i5ZNxqaGYsfji1h4kbpgSxfoj4T+WKc2DYUZ5BKS8FGtHOIJCBfM1cegL8YO9uVoZ8UUl3ZiE1s4RHWlliFWU1POG75VaqGl7FV86o1BxNaATqxWC+pynJHKn/qoC6msG8mv6uCxfaMnc8Lm9VPAQOanpljyPQNdM7xac0LCDg4zSmxtoN53gm+iFsGMotKNFpblyUEuDQTa4TD2bUPi+QQJrCA== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from CH2PR12MB3990.namprd12.prod.outlook.com (2603:10b6:610:28::18) by CY8PR12MB8315.namprd12.prod.outlook.com (2603:10b6:930:7e::8) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9203.9; Thu, 9 Oct 2025 12:37:32 +0000 Received: from CH2PR12MB3990.namprd12.prod.outlook.com ([fe80::7de1:4fe5:8ead:5989]) by CH2PR12MB3990.namprd12.prod.outlook.com ([fe80::7de1:4fe5:8ead:5989%6]) with mapi id 15.20.9203.009; Thu, 9 Oct 2025 12:37:32 +0000 From: Alexandre Courbot Date: Thu, 09 Oct 2025 21:37:09 +0900 Subject: [PATCH RFC v2 2/3] rust: kernel: add bounded integer types Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20251009-bounded_ints-v2-2-ff3d7fee3ffd@nvidia.com> References: <20251009-bounded_ints-v2-0-ff3d7fee3ffd@nvidia.com> In-Reply-To: <20251009-bounded_ints-v2-0-ff3d7fee3ffd@nvidia.com> To: Danilo Krummrich , Joel Fernandes , Yury Norov , Jesung Yang , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross Cc: nouveau@lists.freedesktop.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TYCP301CA0016.JPNP301.PROD.OUTLOOK.COM (2603:1096:400:381::17) To CH2PR12MB3990.namprd12.prod.outlook.com (2603:10b6:610:28::18) 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: CH2PR12MB3990:EE_|CY8PR12MB8315:EE_ X-MS-Office365-Filtering-Correlation-Id: 13349d4e-910c-412f-b776-08de07309d90 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|376014|1800799024|7416014|366016|10070799003|921020; X-Microsoft-Antispam-Message-Info: =?utf-8?B?ZThkcVIzeklVYmc3a1VTM2JMU3U0cGI1Z284WTd6aE1MUFNVbkhRWG5BQUxE?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RmbFhwV1lIaFY1bkdQTVIzSmFF?= =?utf-8?B?OW1hWXV0UVlWczBjSGRxSUFjNFk2dU5GZDlEWi9WUXg1Z09YYllpNVhLTjZR?= =?utf-8?B?dnNuVVdFc0JXeHpCNzZVRGhvSlNkU3lmOVEvZmlMRVE0WHZkQ0s4TUM4TjJW?= =?utf-8?Q?B3Js3bg0drevMG3FIRBpFgOfvKuyYw=3D?= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CH2PR12MB3990.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(376014)(1800799024)(7416014)(366016)(10070799003)(921020);DIR:OUT;SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: =?utf-8?B?RS9ybHJOVWphUzYvczJxSzVscGZlSHVyWlgwWENBL1lXc0phNk5zZ29RRm1y?= =?utf-8?B?bzd0bGVaNHo5QTlERlhDTjZkNEt2TzhFU3FNY1p0K2l1eDhKM2lSQ2tIWHNJ?= =?utf-8?B?ZTlCbGhkSlNrUkxiYk1BRXZwVDIzWXROOEFwUTY0aWJpVlR6VGVlby8rMHpl?= =?utf-8?B?UVhUUmtqaE1SN3lMY21kQ2tRcVNCREhlRUY3Mm54cVNSUzh6WmJZYXNKWUp4?= =?utf-8?B?ZUxTNTh3cmdBNEJzdWhTREJwSjUvL004QXczSHBmWmc3TUNEVzJFR0xCV0p2?= =?utf-8?B?eG9CVGFtVnA5ZHhoVUczVlVJb0Rud2R3WXBza0xYZXVCdDJ1aG5Id0F3MXBE?= =?utf-8?B?V3VUWFJHTjhpZlJzMHI1Z3lpNmI0UDdIbmpLTUJQOEVNQTNmWGJpamNMdDNC?= =?utf-8?B?VEdKb3EyYU9aSDE2eGFnZG93bXFLN3JZaWwraTl5T0EvbnNDa2lYd3R0aHM4?= =?utf-8?B?d0JNdDhSUGU3QzdwTXQxRGsvL3FzTU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dXpkMmhvblJHcjhmcFBxaGNCTEFBd1hCQzg3dHJEbFl5?= =?utf-8?B?b2VYYVdZZmlDaFpGQnJSZEh3enRoMTB5TGM1akRwWGRVWVh0aVBENGljSEdX?= =?utf-8?B?VGJCVHhOajlBcnJTdkRCTHhhOWFsUUdTcXNyTUY2SklwaHhvUVp4QUpJV2tN?= =?utf-8?B?V1NsWHovM0duYTVocnpOTmFRY0x3dEh1V1hoVlNQWndHcGlWSFplTWpqUDRD?= =?utf-8?B?VjNHa1pySzFlLzY1VFE3Qk41OFlxdGVRdVZieEVRaVZnRC9ZaEN1ektQSGpK?= =?utf-8?B?NUVDQzJiYngxQ2tjaVdUbjYzRG92U0lQbVRlZFYzOGVodnhGakJ4YUc1QzJt?= =?utf-8?B?bmxNbXpycEhYcjhydFMxeWl0SDd1dlliT3NRYlhld3FnZ0pWYUtlMnBENDNj?= =?utf-8?B?eGZDVkhDaHVMRnllRzdYc0duVk9FVFRsajBJSDQ2NlZWajN3WFE5NDAvWkIz?= =?utf-8?B?YnlUNUhVVGZ3eTk1WGxHdnp5S1hvd2l0aFpPNzhhQUhsUmNHeEttTVV5RmZN?= =?utf-8?B?MzVlNmFudEZKZVMyOExqd1h1MmJUMk5XazdrZ24yT0hkM0JGekRFSnpoRzk4?= =?utf-8?B?cUJCQ0V1ckhzeXh1V2RrM2Jwck5kNk5oWWZWTWhyUzBNZGdVVmFpTEx4VmFj?= =?utf-8?B?Z1RGekVWdmE4RlUyV1hWTUQwU0VjSEpKTExkbGs5RE9mWGY3Um5RS1E0YTJh?= =?utf-8?B?ZHdVOXJSRTlNWW05MkpSTDlwSGN2NDFGVGdhK3VBTXc5ejY1c3BkNUlIdllJ?= =?utf-8?Q?MgxhTXuL2K0FuLFeWIch8xIiQqb3Z9fgGZoaM8yNs5BS?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 13349d4e-910c-412f-b776-08de07309d90 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 09 Oct 2025 12:37:32.0220 (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: gzMQFvpBHEQ/1sgun3uXUiRdFcQBkbbzpo/IomgK9u43BQvUntDOTmgeHxWaLFZTxkvkt3K2GDskvxbDr+QZsA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: CY8PR12MB8315 Add the BoundedInt type, which restricts the number of bits allowed to be used in a given integer value. This is useful to carry guarantees when setting bitfields. Alongside this type, many `From` and `TryFrom` implementations are provided to reduce friction when using with regular integer types. Proxy implementations of common integer traits are also provided. Signed-off-by: Alexandre Courbot --- rust/kernel/lib.rs | 1 + rust/kernel/num.rs | 499 +++++++++++++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 500 insertions(+) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index fcffc3988a90..21c1f452ee6a 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -101,6 +101,7 @@ pub mod mm; #[cfg(CONFIG_NET)] pub mod net; +pub mod num; pub mod of; #[cfg(CONFIG_PM_OPP)] pub mod opp; diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs new file mode 100644 index 000000000000..b2aad95ce51c --- /dev/null +++ b/rust/kernel/num.rs @@ -0,0 +1,499 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Numerical types for the kernel. + +use kernel::prelude::*; + +/// Integer type for which only the bits `0..NUM_BITS` are valid. +/// +/// # Invariants +/// +/// Stored values are represented with at most `NUM_BITS` bits. +#[repr(transparent)] +#[derive(Clone, Copy, Debug, Default, Hash)] +pub struct BoundedInt(T); + +/// Returns `true` if `$value` can be represented with at most `$NUM_BITS`= on `$type`. +macro_rules! is_in_bounds { + ($value:expr, $type:ty, $num_bits:expr) =3D> {{ + let v =3D $value; + v & <$type as Boundable>::MASK =3D=3D v + }}; +} + +/// Trait for primitive integer types that can be used with `BoundedInt`. +pub trait Boundable +where + Self: Sized + Copy + core::ops::BitAnd + core::cmp::P= artialEq, + Self: TryInto + TryInto + TryInto + TryInto, +{ + /// Mask of the valid bits for this type. + const MASK: Self; + + /// Returns `true` if `value` can be represented with at most `NUM_BIT= S`. + /// + /// TODO: post-RFC: replace this with a left-shift followed by right-s= hift operation. This will + /// allow us to handle signed values as well. + fn is_in_bounds(value: Self) -> bool { + is_in_bounds!(value, Self, NUM_BITS) + } +} + +impl Boundable for u8 { + const MASK: u8 =3D crate::bits::genmask_u8(0..=3D(NUM_BITS - 1)); +} + +impl Boundable for u16 { + const MASK: u16 =3D crate::bits::genmask_u16(0..=3D(NUM_BITS - 1)); +} + +impl Boundable for u32 { + const MASK: u32 =3D crate::bits::genmask_u32(0..=3D(NUM_BITS - 1)); +} + +impl Boundable for u64 { + const MASK: u64 =3D crate::bits::genmask_u64(0..=3D(NUM_BITS - 1)); +} + +impl BoundedInt +where + T: Boundable, +{ + /// Checks that `value` is valid for this type at compile-time and bui= ld a new value. + /// + /// This relies on [`build_assert!`] to perform validation at compile-= time. If `value` cannot + /// be inferred to be in bounds at compile-time, use the fallible [`Se= lf::try_new`] instead. + /// + /// When possible, use one of the `new_const` methods instead of this = method as it statically + /// validates `value` instead of relying on the compiler's optimizatio= ns. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::BoundedInt; + /// + /// # fn some_number() -> u32 { 0xffffffff } + /// + /// assert_eq!(BoundedInt::::new(1).get(), 1); + /// assert_eq!(BoundedInt::::new(0xff).get(), 0xff); + /// + /// // Triggers a build error as `0x1ff` doesn't fit into 8 bits. + /// // assert_eq!(BoundedInt::::new(0x1ff).get(), 0x1ff); + /// + /// let v: u32 =3D some_number(); + /// // Triggers a build error as `v` cannot be asserted to fit within = 4 bits... + /// // let _ =3D BoundedInt::::new(v); + /// // ... but this works as the compiler can assert the range from th= e mask. + /// let _ =3D BoundedInt::::new(v & 0xf); + /// ``` + pub fn new(value: T) -> Self { + crate::build_assert!( + T::is_in_bounds(value), + "Provided parameter is larger than maximal supported value" + ); + + Self(value) + } + + /// Attempts to convert `value` into a value bounded by `NUM_BITS`. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::BoundedInt; + /// + /// assert_eq!(BoundedInt::::try_new(1).map(|v| v.get()), Ok(1)= ); + /// assert_eq!(BoundedInt::::try_new(0xff).map(|v| v.get()), O= k(0xff)); + /// + /// // `0x1ff` doesn't fit into 8 bits. + /// assert_eq!(BoundedInt::::try_new(0x1ff), Err(EOVERFLOW)); + /// ``` + pub fn try_new(value: T) -> Result { + if !T::is_in_bounds(value) { + Err(EOVERFLOW) + } else { + Ok(Self(value)) + } + } + + /// Returns the contained value as a primitive type. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::BoundedInt; + /// + /// let v =3D BoundedInt::::new_const::<7>(); + /// assert_eq!(v.get(), 7u32); + /// ``` + pub fn get(self) -> T { + if !T::is_in_bounds(self.0) { + // SAFETY: Per the invariants, `self.0` cannot have bits set o= utside of `MASK`, so + // this block will + // never be reached. + unsafe { core::hint::unreachable_unchecked() } + } + self.0 + } + + /// Increase the number of bits usable for `self`. + /// + /// This operation cannot fail. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::BoundedInt; + /// + /// let v =3D BoundedInt::::new_const::<7>(); + /// let larger_v =3D v.enlarge::<12>(); + /// // The contained values are equal even though `larger_v` has a big= ger capacity. + /// assert_eq!(larger_v, v); + /// ``` + pub const fn enlarge(self) -> BoundedInt + where + T: Boundable, + T: Copy, + { + build_assert!(NEW_NUM_BITS >=3D NUM_BITS); + + // INVARIANT: the value did fit within `NUM_BITS`, so it will all = the more fit within + // `NEW_NUM_BITS` which is larger. + BoundedInt(self.0) + } + + /// Shrink the number of bits usable for `self`. + /// + /// Returns `EOVERFLOW` if the value of `self` cannot be represented w= ithin `NEW_NUM_BITS`. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::BoundedInt; + /// + /// let v =3D BoundedInt::::new_const::<7>(); + /// let smaller_v =3D v.shrink::<4>()?; + /// // The contained values are equal even though `smaller_v` has a sm= aller capacity. + /// assert_eq!(smaller_v, v); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub fn shrink(self) -> Result> + where + T: Boundable, + T: Copy, + { + BoundedInt::::try_new(self.get()) + } + + /// Casts `self` into a `BoundedInt` using a different storage type, b= ut using the same + /// number of bits for representation. + /// + /// This method cannot fail as the number of bits used for representat= ion doesn't change. + /// + /// # Examples + /// + /// ``` + /// use kernel::num::BoundedInt; + /// + /// let v =3D BoundedInt::::new_const::<7>(); + /// let smaller_v: BoundedInt =3D v.cast(); + /// // The contained values are equal even though `smaller_v` has a sm= aller storage type. + /// assert_eq!(u32::from(smaller_v.get()), v.get()); + /// ``` + pub fn cast(self) -> BoundedInt + where + U: TryFrom + Boundable, + { + // SAFETY: the contained value is represented using `NUM_BITS`, an= d `U` can be bounded to + // `NUM_BITS`, hence the conversion cannot fail. + let value =3D unsafe { U::try_from(self.0).unwrap_unchecked() }; + + // INVARIANT: although the storage type has changed, the value is = still represented within + // `NUM_BITS`. + BoundedInt(value) + } +} + +/// Validating the value as a const expression cannot be done as a regular= method, as the +/// arithmetic expressions we rely on to check the bounds are not const. T= hus, implement +/// `new_const` using a macro. +macro_rules! impl_const_new { + ($($type:ty)*) =3D> { + $( + impl BoundedInt<$type, NUM_BITS> { + /// Creates a bounded value for `VALUE`, statically validated. + /// + /// This method should be used instead of [`Self::new`] when t= he value is a constant + /// expression. + /// + /// # Examples + /// ``` + /// use kernel::num::BoundedInt; + /// + #[doc =3D ::core::concat!( + "let v =3D BoundedInt::<", + ::core::stringify!($type), + ", 4>::new_const::<7>();")] + /// assert_eq!(v.get(), 7); + /// ``` + pub const fn new_const() -> Self { + build_assert!(is_in_bounds!(VALUE, $type, NUM_BITS)); + + Self(VALUE) + } + } + )* + }; +} + +impl_const_new!(u8 u16 u32 u64); + +/// Declares a new `$trait` and implements it for all bounded types repres= ented using `$num_bits`. +/// +/// This is used to declare properties as traits that we can use for later= implementations. +macro_rules! impl_size_rule { + ($trait:ident, $($num_bits:literal)*) =3D> { + trait $trait {} + + $( + impl $trait for BoundedInt where T: Boundable<$nu= m_bits> {} + )* + }; +} + +// Bounds that are larger than a `u64`. +impl_size_rule!(LargerThanU64, 64); + +// Bounds that are larger than a `u32`. +impl_size_rule!(LargerThanU32, + 32 33 34 35 36 37 38 39 + 40 41 42 43 44 45 46 47 + 48 49 50 51 52 53 54 55 + 56 57 58 59 60 61 62 63 +); +// Anything larger than `u64` is also larger than `u32`. +impl LargerThanU32 for T where T: LargerThanU64 {} + +// Bounds that are larger than a `u16`. +impl_size_rule!(LargerThanU16, + 16 17 18 19 20 21 22 23 + 24 25 26 27 28 29 30 31 +); +// Anything larger than `u32` is also larger than `u16`. +impl LargerThanU16 for T where T: LargerThanU32 {} + +// Bounds that are larger than a `u8`. +impl_size_rule!(LargerThanU8, 8 9 10 11 12 13 14 15); +// Anything larger than `u16` is also larger than `u8`. +impl LargerThanU8 for T where T: LargerThanU16 {} + +// Bounds that are larger than a boolean. +impl_size_rule!(LargerThanBool, 1 2 3 4 5 6 7); +// Anything larger than `u8` is also larger than `bool`. +impl LargerThanBool for T where T: LargerThanU8 {} + +/// Generates `From` implementations from a primitive type into a bounded = integer that is +/// guaranteed to being able to contain it. +macro_rules! impl_from_primitive { + ($($type:ty =3D> $trait:ident),*) =3D> { + $( + impl From<$type> for BoundedInt + where + Self: $trait, + T: From<$type>, + { + fn from(value: $type) -> Self { + Self(T::from(value)) + } + } + )* + } +} + +impl_from_primitive!( + bool =3D> LargerThanBool, + u8 =3D> LargerThanU8, + u16 =3D> LargerThanU16, + u32 =3D> LargerThanU32, + u64 =3D> LargerThanU64 +); + +impl_size_rule!(FitsIntoBool, 1); + +impl_size_rule!(FitsIntoU8, 2 3 4 5 6 7 8); + +// Anything that fits into a `bool` also fits into a `u8`. +impl FitsIntoU8 for T where T: FitsIntoBool {} + +impl_size_rule!(FitsIntoU16, 9 10 11 12 13 14 15 16); + +// Anything that fits into a `u8` also fits into a `u16`. +impl FitsIntoU16 for T where T: FitsIntoU8 {} + +impl_size_rule!(FitsIntoU32, + 17 18 19 20 21 22 23 24 + 25 26 27 28 29 30 31 32 +); + +// Anything that fits into a `u16` also fits into a `u32`. +impl FitsIntoU32 for T where T: FitsIntoU16 {} + +impl_size_rule!(FitsIntoU64, + 33 34 35 36 37 38 39 40 + 41 42 43 44 45 46 47 48 + 49 50 51 52 53 54 55 56 + 57 58 59 60 61 62 63 64 +); + +// Anything that fits into a `u32` also fits into a `u64`. +impl FitsIntoU64 for T where T: FitsIntoU32 {} + +/// Generates `From` implementations from a bounded integer into a primiti= ve type that is +/// guaranteed to being able to contain it. +macro_rules! impl_into_primitive { + ($($trait:ident =3D> $type:ty),*) =3D> { + $( + impl From> for $ty= pe + where + T: Boundable, + BoundedInt: $trait + { + fn from(value: BoundedInt) -> Self { + // SAFETY: per the `BoundedInt` invariants, less than 8 bi= ts are used to the conversion + // cannot fail. + unsafe { value.get().try_into().unwrap_unchecked() } + } + } + )* + } +} + +impl_into_primitive!( + FitsIntoU8 =3D> u8, + FitsIntoU16 =3D> u16, + FitsIntoU32 =3D> u32, + FitsIntoU64 =3D> u64 +); + +// Conversion to boolean must be handled separately as it does not have `T= ryFrom` implementation +// from integers. +impl From> for bool +where + T: Boundable<1>, + BoundedInt: FitsIntoBool, + T: PartialEq + Zeroable, +{ + fn from(value: BoundedInt) -> Self { + value.get() !=3D Zeroable::zeroed() + } +} + +/// Trait similar to `TryInto` to avoid conflicting implementations errors. +pub trait TryIntoBounded, const NUM_BITS: u32> { + /// Attempts to convert `self` into a value bounded by `NUM_BITS`. + fn try_into(self) -> Result>; +} + +/// Any value can be attempted to be converted into a bounded integer of a= ny size. +impl TryIntoBounded for U +where + T: Boundable, + U: TryInto, +{ + fn try_into(self) -> Result> { + self.try_into() + .map_err(|_| EOVERFLOW) + .and_then(BoundedInt::try_new) + } +} + +/// `BoundedInts` can be compared if their respective storage types can be. +impl PartialEq> + for BoundedInt +where + T: Boundable, + U: Boundable, + T: PartialEq, +{ + fn eq(&self, other: &BoundedInt) -> bool { + self.get() =3D=3D other.get() + } +} + +impl Eq for BoundedInt where T: Bound= able {} + +/// `BoundedInts` can be ordered if their respective storage types can be. +impl PartialOrd> + for BoundedInt +where + T: Boundable, + U: Boundable, + T: PartialOrd, +{ + fn partial_cmp(&self, other: &BoundedInt) -> Option { + self.get().partial_cmp(&other.get()) + } +} + +impl Ord for BoundedInt +where + T: Boundable, + T: Ord, +{ + fn cmp(&self, other: &Self) -> core::cmp::Ordering { + self.get().cmp(&other.get()) + } +} + +/// Allow comparison with non-bounded values. +impl PartialEq for BoundedInt +where + T: Boundable, + T: PartialEq, +{ + fn eq(&self, other: &T) -> bool { + self.get() =3D=3D *other + } +} + +/// Allow ordering with non-bounded values. +impl PartialOrd for BoundedInt +where + T: Boundable, + T: PartialOrd, +{ + fn partial_cmp(&self, other: &T) -> Option { + self.get().partial_cmp(other) + } +} + +impl core::fmt::Display for BoundedInt +where + T: Boundable, + T: core::fmt::Display, +{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.0.fmt(f) + } +} + +impl core::fmt::LowerHex for BoundedInt +where + T: Boundable, + T: core::fmt::LowerHex, +{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.0.fmt(f) + } +} + +impl core::fmt::UpperHex for BoundedInt +where + T: Boundable, + T: core::fmt::UpperHex, +{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.0.fmt(f) + } +} --=20 2.51.0 From nobody Sat Feb 7 11:30:56 2026 Received: from DM1PR04CU001.outbound.protection.outlook.com (mail-centralusazon11010024.outbound.protection.outlook.com [52.101.61.24]) (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 02C8F2E7F04; Thu, 9 Oct 2025 12:37:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=fail smtp.client-ip=52.101.61.24 ARC-Seal: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760013465; cv=fail; b=Gyn2Gb+e9Qi+/EAyHo6T3H0b189TBf8wklFXBLGOYRWLEXj4Z3K146ZgPycfcsspVTiFNt+5JvcLXkX+0JsgC4SQosRbbHCgOwj+/NIHIebroornki/ZBWIFRAgHT7bwtPjlxJgLwDuYbN9ZM/5RvNF7/rdn5MfEpRSuWDAbay0= ARC-Message-Signature: i=2; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1760013465; c=relaxed/simple; bh=AVpOVX4elNOy/iH4pU/TIR1YlqIX+zuIGtEsWxt3xU4=; h=From:Date:Subject:Content-Type:Message-Id:References:In-Reply-To: To:Cc:MIME-Version; b=TNBY/zETPRFj8Ba1KwUNWYh9WxU7RO33yG8s/0X4PwGlN5vdWpQKzpvm1Ucm90I47V2yorcmntTUC4fpmUOTauGKK9FeCYeePNSgDyuUZWDooIiUhXVmg/421BJvC/AkUfFkrdad4nxqOsKy7y33Q1BMjFrORSDWr/7pNFUHtro= 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=R3LJIOP/; arc=fail smtp.client-ip=52.101.61.24 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="R3LJIOP/" ARC-Seal: i=1; a=rsa-sha256; s=arcselector10001; d=microsoft.com; cv=none; b=RmPb4vIj9kSDmH7DZBoT655F0TaxDi2kDJcsrS7CGmztHpZqabzpQgydIxqoF7R7hpE6eseuPXBmY6tdeHsGRgGhmudW8Zvr5SJp6UP4d9hlvQYg5jE1tfl5ytQHrYfTMOujjzAbQscD17dmgkxI6QLMIkx8HNOuZr+ynbtaG7uY4paJYgNgLlKOYsUj6RGEzuBfOWwLOxwXowYwJkq0OOaSTwkg8+P9sYyltz9XgSE3IzLSL6MjUpGz6H5nzp5m6sy+ekpjU3gF8h2D3TfS+YuSn1vcuR+F9UIkSOb/LWhg1XK5oA9ltdIAx3PWa+kzNH4/oFLuTihK5UDwNM2JkA== 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=352JxOotCkflHo1RmpVMy7UYec4On/TeptZzEK9q52c=; b=I9ss9vWldxlAes8IKmoR9X8kahOp3a4AaiHtBElZnOv9K6hTH/b00kXUB831Llvn1dHrdZyjI4G/W5dcrHQdc1tAASs8XVaROH8QaUSVp6igOsKjr92ljzGVMAariEiO+pCVJnBy3QIQRqNYtlnHDLeYFEtHpJO0LM89oLquPI+geN0fgorODni3h66kuLs+d7G5Him7TxkDGIbV9MXflwRHKM4Ork/fYNCcBCJcFn0lo3zSQ9EO8KBniCt/Cn+MOeWJw9CQt5aBHk7XSNlYuyR98Tx7yBoB2RhyT3SdcyUEp7Tq36luI6PpA6qTSTMZKOB1dMZaU5/EnXrOzEMwwg== 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=352JxOotCkflHo1RmpVMy7UYec4On/TeptZzEK9q52c=; b=R3LJIOP/Y/uvSJ2PBMBMkChhLTvywvAAAgkrsnqddQfpdKmRtw255utwip1vzrwIHwaf93/XH3W5y3xMLaWsqntzJpA66xmUoVoa2vv7JzyB8hFTjL66ZwrdNL0je1q1xCZD44PkugwUs1FrmyfEKR+xcdLMu1mvyhqEWX50bfj45eaJKhm555JuAbugbrzCdVfk1rSmmLPYsLdehhgVRo5gNRBe0gLa76y6SGS0kNVYJzRknFbSbww5+POsurEYj7OR0eIPe+Iukxn3zwKS8HIoWJN9NbSGthsv8aRpqGosc+N8J8LByZdZy5vKh776gc5MinY/jvGDzdn8SBH2oA== Authentication-Results: dkim=none (message not signed) header.d=none;dmarc=none action=none header.from=nvidia.com; Received: from CH2PR12MB3990.namprd12.prod.outlook.com (2603:10b6:610:28::18) by CY8PR12MB8315.namprd12.prod.outlook.com (2603:10b6:930:7e::8) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.9203.9; Thu, 9 Oct 2025 12:37:36 +0000 Received: from CH2PR12MB3990.namprd12.prod.outlook.com ([fe80::7de1:4fe5:8ead:5989]) by CH2PR12MB3990.namprd12.prod.outlook.com ([fe80::7de1:4fe5:8ead:5989%6]) with mapi id 15.20.9203.009; Thu, 9 Oct 2025 12:37:36 +0000 From: Alexandre Courbot Date: Thu, 09 Oct 2025 21:37:10 +0900 Subject: [PATCH RFC v2 3/3] gpu: nova-core: use BoundedInt Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20251009-bounded_ints-v2-3-ff3d7fee3ffd@nvidia.com> References: <20251009-bounded_ints-v2-0-ff3d7fee3ffd@nvidia.com> In-Reply-To: <20251009-bounded_ints-v2-0-ff3d7fee3ffd@nvidia.com> To: Danilo Krummrich , Joel Fernandes , Yury Norov , Jesung Yang , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross Cc: nouveau@lists.freedesktop.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, Alexandre Courbot X-Mailer: b4 0.14.3 X-ClientProxiedBy: TY4P286CA0095.JPNP286.PROD.OUTLOOK.COM (2603:1096:405:369::14) To CH2PR12MB3990.namprd12.prod.outlook.com (2603:10b6:610:28::18) 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: CH2PR12MB3990:EE_|CY8PR12MB8315:EE_ X-MS-Office365-Filtering-Correlation-Id: 27d9c71a-0b2e-4833-1b9d-08de0730a002 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0;ARA:13230040|376014|1800799024|7416014|366016|10070799003|921020; X-Microsoft-Antispam-Message-Info: =?utf-8?B?UjAyanFhUXFKRVJMMWJyUlZGeXMxZ3JObjdkZkVLWnRqek9na2JSVExGaWRY?= =?utf-8?B?dlE3QllORm5FMURiSjBXVVZ2NjQyRy9wNjZCaHlVQXlCOUhnby9kbi9QNXE1?= =?utf-8?B?REw0Qkx5Zng5WS8rRktlRURqY1BiRUNoZFB5MHE4WXNqejFxdC9xZ0hIWVh6?= =?utf-8?B?RERiaWVoc2xBT0pCNWdSQlN6WkZJZmcwZjF5VEdTRU0wYnlhUFVTRGc5SEVD?= =?utf-8?B?bWI0MTc1L3VpN1luVzFVUHBzdVZJdWtmVHhCZGJvZjBYeE13MUVxWTlVclk1?= =?utf-8?B?S2NXZ1BFTFZuaFkxQmI2M242V0dkWTQzMmZ4V3JNRVk2TmFpMllGc0s1eWMy?= =?utf-8?B?WWdEMkF3RzVrQU9ZOVVTNnB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VjbUorcmtQZGtkUmtQSWg5OWJTdGlXdTBTblVMelRjQ2p0YlA4?= =?utf-8?B?M1ZlQm1NMFVqQVpHbDdaN3h4R2ZnQUorTlRPLzJNUlgyaFRFbjFQbEZCVG1Z?= =?utf-8?B?VkxmUStpQkVwTEx5L3IxclJHeUVDWnBGRnMyeG5idmNkT05SYXFtOS9VR1Bv?= =?utf-8?B?eWpMZ21SRStBYnl6SEJJd0Z0UDR1S05raWI0ZkQrWlZ0MVJjZk9Zc0FuL1V0?= =?utf-8?B?T3doRmUydVFxTU03bkhCaG0yRUMyWGpRcVY3SHhyOWV4RWxPbkMzR3R5bklY?= =?utf-8?B?YVl2TG1abS9oVkJJRUthM1J4NDh6NEE1R050b0kzNklIYUF6UG5oazV1Visv?= =?utf-8?B?N0dpUTEya25ycmlwZFpibnIvRzFtTURJb0c5RkJYUmRjbjJIZ3JJNDdwd3cz?= =?utf-8?B?dkJ0eThrR0pOcVkvcndCSlFXaXNzbUlWRmdrSHdCcFU2S1VXbXRHaFlyRG02?= =?utf-8?B?eXVrZGpQQ0hCZWljUG1RRjQ1QmxGTXpYNy9OS0JvNGYzSmVxMVNWQzRPZVJ3?= =?utf-8?B?KzJtVzJhYVpHb08xYUttQXBKaGRVNVdjNG9UTHZWdHRzbTBIQUludEdyS2dK?= =?utf-8?B?SlZPSmNBVW5IWWJPbFg4VTlTT1FYNzJiSEswTWpHYmFCbWJLeXhBeWlVamZS?= =?utf-8?B?MDhqQjU3OE9aNWo2a202aDd1KytBeitjSTFSaWx3alZ5akc0YlgzRjNFK3lT?= =?utf-8?B?R0xmR2FZUU1LTm9GTkpqV0VHTFg1enVvQTNiNmNhRWQ5alRjZHMveVoxZXo1?= =?utf-8?Q?bEkdMV?= X-Forefront-Antispam-Report: CIP:255.255.255.255;CTRY:;LANG:en;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:CH2PR12MB3990.namprd12.prod.outlook.com;PTR:;CAT:NONE;SFS:(13230040)(376014)(1800799024)(7416014)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?B?L0JJckJMMnZ1TUVINVR3bVhPZi9tTlI2OXJEcXVpQ0NSaHd4VldTZUk1Qjdo?= =?utf-8?B?OUpIclN0VW5FU3lRRU90UkgvNENaY3FYODhzaENGb1RlNzBDWVV3NlVvMzlL?= =?utf-8?B?SThIajMrKzY3NmdHL2FxYmFzbzNkdTVJb0h1bFVQSXhFeWttMWhSUTAzWWVo?= =?utf-8?B?TTdBUTZpUzZKTlhYeFlSSm1jL3FJNCtqYnZYM1phckFBVllEMnI1NzQ5R0Yr?= =?utf-8?B?ZnlzZm5LbXlIQjJlL0p4WEhzdDFINFJwQ1RWVHNLTzJDaXlTYU1hVjQ3Umx4?= =?utf-8?B?a3pGWFQyc2RjazJTdGEyc3Z0ZkxpblpNamFpQTFJanM0ZTZvMS9LNDZsdEtl?= =?utf-8?B?eGxEd21HT05ZejIva3pxMVo5Z2FwOTM2M3JZcmtkVzVVWnRJT1ZwaXRCU2hz?= =?utf-8?B?SjNMMkkwV2ZkdHhPNVlzSEFTa0hyY28rdmsyMm4rTk5xYm0yVWNGaTNmRVhy?= =?utf-8?Q?Aj7Oy+4uIz32fRwQqV/8y0MlDNVW6kNpkHqMo7dtnOZS?= X-OriginatorOrg: Nvidia.com X-MS-Exchange-CrossTenant-Network-Message-Id: 27d9c71a-0b2e-4833-1b9d-08de0730a002 X-MS-Exchange-CrossTenant-AuthSource: CH2PR12MB3990.namprd12.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 09 Oct 2025 12:37:36.2091 (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: SWqtfwojXcP4Q9sDCzKEfq3v9xE8CHDrOxlMzrZu3BHyfQyV1pni+UQq7jLrjWr6Ok4tY24J/aVgcZPBH5uktw== X-MS-Exchange-Transport-CrossTenantHeadersStamped: CY8PR12MB8315 Use BoundedInt with the register!() macro and adapt the nova-core code accordingly. This makes it impossible to trim values when setting a register field, because either the value of the field has been inferred at compile-time to fit within the bounds of the field, or the user has been forced to check at runtime that it does indeed fit. The use of BoundedInt actually simplifies register fields definitions, as they don't need an intermediate storage type (the "as ..." part of fields definitions). Instead, the internal storage type for each field is now the bounded integer of its width in bits, which can optionally be converted to another type that implements `From`` or `TryFrom`` for that bounded integer type. This means that something like register!(NV_PDISP_VGA_WORKSPACE_BASE @ 0x00625f04 { 3:3 status_valid as bool, 31:8 addr as u32, }); Now becomes register!(NV_PDISP_VGA_WORKSPACE_BASE @ 0x00625f04 { 3:3 status_valid =3D> bool, 31:8 addr, }); (here `status_valid` is infallibly converted to a bool for convenience and to remain compatible with the previous semantics) The field setter/getters are also simplified. If a field has no target type, then its setter expects any type that implements `Into` to the field's bounded integer type. Due to the many `From` implementations for primitive types, this means that most calls can be left unchanged. If the caller passes a value that is potentially larger than the field's capacity, it must use the `try_` variant of the setter, which returns an error if the value cannot be converted at runtime. For fields that use `=3D>` to convert to another type, both setter and getter are always infallible. For fields that use `?=3D>` to fallibly convert to another type, only the getter needs to be fallible as the setter always provide valid values by design. Outside of the register macro, the biggest changes occur in `falcon.rs`, which defines many enums for fields - their conversion implementations need to be changed from the original primitive type of the field to the new corresponding bounded int type. Hopefully the TryFrom/Into derive macros [1] can take care of implementing these, but it will need to be adapted to support bounded integers... :/ But overall, I am rather happy at how simple it was to convert the whole of nova-core to this. Note: This RFC uses nova-core's register!() macro for practical purposes, but the hope is to move this patch on top of the bitfield macro after it is split out [2]. [1] https://lore.kernel.org/rust-for-linux/cover.1755235180.git.y.j3ms.n@gm= ail.com/ [2] https://lore.kernel.org/rust-for-linux/20251003154748.1687160-1-joelagn= elf@nvidia.com/ Signed-off-by: Alexandre Courbot --- drivers/gpu/nova-core/falcon.rs | 134 ++++++++------- drivers/gpu/nova-core/falcon/hal/ga102.rs | 5 +- drivers/gpu/nova-core/fb/hal/ga100.rs | 3 +- drivers/gpu/nova-core/gpu.rs | 9 +- drivers/gpu/nova-core/regs.rs | 139 ++++++++-------- drivers/gpu/nova-core/regs/macros.rs | 264 +++++++++++++++-----------= ---- 6 files changed, 283 insertions(+), 271 deletions(-) diff --git a/drivers/gpu/nova-core/falcon.rs b/drivers/gpu/nova-core/falcon= .rs index 3f505b870601..71cb09cf7d67 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::num::{Boundable, BoundedInt}; use kernel::prelude::*; use kernel::sync::aref::ARef; use kernel::time::Delta; @@ -22,11 +23,14 @@ pub(crate) mod sec2; =20 // TODO[FPRI]: Replace with `ToPrimitive`. -macro_rules! impl_from_enum_to_u8 { - ($enum_type:ty) =3D> { - impl From<$enum_type> for u8 { +macro_rules! impl_from_enum_to_bounded { + ($enum_type:ty, $length:literal) =3D> { + impl From<$enum_type> for BoundedInt + where + T: From + Boundable<$length>, + { fn from(value: $enum_type) -> Self { - value as u8 + BoundedInt::new(T::from(value as u8)) } } }; @@ -46,16 +50,19 @@ pub(crate) enum FalconCoreRev { Rev6 =3D 6, Rev7 =3D 7, } -impl_from_enum_to_u8!(FalconCoreRev); +impl_from_enum_to_bounded!(FalconCoreRev, 4); =20 // TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom for FalconCoreRev { +impl TryFrom> for FalconCoreRev +where + T: Boundable<4>, +{ type Error =3D Error; =20 - fn try_from(value: u8) -> Result { + fn try_from(value: BoundedInt) -> Result { use FalconCoreRev::*; =20 - let rev =3D match value { + let rev =3D match u8::from(value) { 1 =3D> Rev1, 2 =3D> Rev2, 3 =3D> Rev3, @@ -81,24 +88,25 @@ pub(crate) enum FalconCoreRevSubversion { Subversion2 =3D 2, Subversion3 =3D 3, } -impl_from_enum_to_u8!(FalconCoreRevSubversion); +impl_from_enum_to_bounded!(FalconCoreRevSubversion, 2); =20 // TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom for FalconCoreRevSubversion { - type Error =3D Error; - - fn try_from(value: u8) -> Result { +impl From> for FalconCoreRevSubversion +where + T: Boundable<2>, +{ + fn from(value: BoundedInt) -> Self { use FalconCoreRevSubversion::*; =20 - let sub_version =3D match value & 0b11 { + match u8::from(value) { 0 =3D> Subversion0, 1 =3D> Subversion1, 2 =3D> Subversion2, 3 =3D> Subversion3, - _ =3D> return Err(EINVAL), - }; - - Ok(sub_version) + // TODO: somehow the compiler cannot infer that `value` cannot= be > 3. Find a way to + // handle this gracefully, or switch back to fallible ops. + _ =3D> panic!(), + } } } =20 @@ -125,16 +133,19 @@ pub(crate) enum FalconSecurityModel { /// Also known as High-Secure, Privilege Level 3 or PL3. Heavy =3D 3, } -impl_from_enum_to_u8!(FalconSecurityModel); +impl_from_enum_to_bounded!(FalconSecurityModel, 2); =20 // TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom for FalconSecurityModel { +impl TryFrom> for FalconSecurityModel +where + T: Boundable<2>, +{ type Error =3D Error; =20 - fn try_from(value: u8) -> Result { + fn try_from(value: BoundedInt) -> Result { use FalconSecurityModel::*; =20 - let sec_model =3D match value { + let sec_model =3D match u8::from(value) { 0 =3D> None, 2 =3D> Light, 3 =3D> Heavy, @@ -157,14 +168,17 @@ pub(crate) enum FalconModSelAlgo { #[default] Rsa3k =3D 1, } -impl_from_enum_to_u8!(FalconModSelAlgo); +impl_from_enum_to_bounded!(FalconModSelAlgo, 8); =20 // TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom for FalconModSelAlgo { +impl TryFrom> for FalconModSelAlgo +where + T: Boundable<8>, +{ type Error =3D Error; =20 - fn try_from(value: u8) -> Result { - match value { + fn try_from(value: BoundedInt) -> Result { + match u8::from(value) { 1 =3D> Ok(FalconModSelAlgo::Rsa3k), _ =3D> Err(EINVAL), } @@ -179,14 +193,17 @@ pub(crate) enum DmaTrfCmdSize { #[default] Size256B =3D 0x6, } -impl_from_enum_to_u8!(DmaTrfCmdSize); +impl_from_enum_to_bounded!(DmaTrfCmdSize, 3); =20 // TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom for DmaTrfCmdSize { +impl TryFrom> for DmaTrfCmdSize +where + T: Boundable<3>, +{ type Error =3D Error; =20 - fn try_from(value: u8) -> Result { - match value { + fn try_from(value: BoundedInt) -> Result { + match u8::from(value) { 0x6 =3D> Ok(Self::Size256B), _ =3D> Err(EINVAL), } @@ -202,25 +219,20 @@ pub(crate) enum PeregrineCoreSelect { /// RISC-V core is active. Riscv =3D 1, } +impl_from_enum_to_bounded!(PeregrineCoreSelect, 1); =20 -impl From for PeregrineCoreSelect { - fn from(value: bool) -> Self { - match value { +impl From> for PeregrineCoreSelect +where + T: Boundable<1> + Zeroable, +{ + fn from(value: BoundedInt) -> Self { + match bool::from(value) { false =3D> PeregrineCoreSelect::Falcon, true =3D> PeregrineCoreSelect::Riscv, } } } =20 -impl From for bool { - fn from(value: PeregrineCoreSelect) -> Self { - match value { - PeregrineCoreSelect::Falcon =3D> false, - PeregrineCoreSelect::Riscv =3D> true, - } - } -} - /// Different types of memory present in a falcon core. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum FalconMem { @@ -244,14 +256,17 @@ pub(crate) enum FalconFbifTarget { /// Non-coherent system memory (System DRAM). NoncoherentSysmem =3D 2, } -impl_from_enum_to_u8!(FalconFbifTarget); +impl_from_enum_to_bounded!(FalconFbifTarget, 2); =20 // TODO[FPRI]: replace with `FromPrimitive`. -impl TryFrom for FalconFbifTarget { +impl TryFrom> for FalconFbifTarget +where + T: Boundable<2>, +{ type Error =3D Error; =20 - fn try_from(value: u8) -> Result { - let res =3D match value { + fn try_from(value: BoundedInt) -> Result { + let res =3D match u8::from(value) { 0 =3D> Self::LocalFb, 1 =3D> Self::CoherentSysmem, 2 =3D> Self::NoncoherentSysmem, @@ -271,26 +286,21 @@ pub(crate) enum FalconFbifMemType { /// Physical memory addresses. Physical =3D 1, } +impl_from_enum_to_bounded!(FalconFbifMemType, 1); =20 /// Conversion from a single-bit register field. -impl From for FalconFbifMemType { - fn from(value: bool) -> Self { - match value { +impl From> for FalconFbifMemType +where + T: Boundable<1> + Zeroable, +{ + fn from(value: BoundedInt) -> Self { + match bool::from(value) { false =3D> Self::Virtual, true =3D> Self::Physical, } } } =20 -impl From for bool { - fn from(value: FalconFbifMemType) -> Self { - match value { - FalconFbifMemType::Virtual =3D> false, - FalconFbifMemType::Physical =3D> true, - } - } -} - /// Type used to represent the `PFALCON` registers address base for a give= n falcon engine. pub(crate) struct PFalconBase(()); =20 @@ -440,7 +450,7 @@ pub(crate) fn reset(&self, bar: &Bar0) -> Result { self.reset_wait_mem_scrubbing(bar)?; =20 regs::NV_PFALCON_FALCON_RM::default() - .set_value(regs::NV_PMC_BOOT_0::read(bar).into()) + .set_value(u32::from(regs::NV_PMC_BOOT_0::read(bar))) .write(bar, &E::ID); =20 Ok(()) @@ -507,18 +517,18 @@ fn dma_wr>( .set_base((dma_start >> 8) as u32) .write(bar, &E::ID); regs::NV_PFALCON_FALCON_DMATRFBASE1::default() - .set_base((dma_start >> 40) as u16) + .try_set_base(dma_start >> 40)? .write(bar, &E::ID); =20 let cmd =3D regs::NV_PFALCON_FALCON_DMATRFCMD::default() .set_size(DmaTrfCmdSize::Size256B) .set_imem(target_mem =3D=3D FalconMem::Imem) - .set_sec(if sec { 1 } else { 0 }); + .set_sec(BoundedInt::new(if sec { 1 } else { 0 })); =20 for pos in (0..num_transfers).map(|i| i * DMA_LEN) { // Perform a transfer of size `DMA_LEN`. regs::NV_PFALCON_FALCON_DMATRFMOFFS::default() - .set_offs(load_offsets.dst_start + pos) + .try_set_offs(load_offsets.dst_start + pos)? .write(bar, &E::ID); regs::NV_PFALCON_FALCON_DMATRFFBOFFS::default() .set_offs(src_start + pos) diff --git a/drivers/gpu/nova-core/falcon/hal/ga102.rs b/drivers/gpu/nova-c= ore/falcon/hal/ga102.rs index 0b1cbe7853b3..08c8b4123ce8 100644 --- a/drivers/gpu/nova-core/falcon/hal/ga102.rs +++ b/drivers/gpu/nova-core/falcon/hal/ga102.rs @@ -55,7 +55,7 @@ fn signature_reg_fuse_version_ga102( =20 // `ucode_idx` is guaranteed to be in the range [0..15], making the `r= ead` calls provable valid // at build-time. - let reg_fuse_version =3D if engine_id_mask & 0x0001 !=3D 0 { + let reg_fuse_version: u16 =3D if engine_id_mask & 0x0001 !=3D 0 { regs::NV_FUSE_OPT_FPF_SEC2_UCODE1_VERSION::read(bar, ucode_idx).da= ta() } else if engine_id_mask & 0x0004 !=3D 0 { regs::NV_FUSE_OPT_FPF_NVDEC_UCODE1_VERSION::read(bar, ucode_idx).d= ata() @@ -64,7 +64,8 @@ fn signature_reg_fuse_version_ga102( } else { dev_err!(dev, "unexpected engine_id_mask {:#x}", engine_id_mask); return Err(EINVAL); - }; + } + .into(); =20 // TODO[NUMM]: replace with `last_set_bit` once it lands. Ok(u16::BITS - reg_fuse_version.leading_zeros()) diff --git a/drivers/gpu/nova-core/fb/hal/ga100.rs b/drivers/gpu/nova-core/= fb/hal/ga100.rs index 871c42bf033a..5449902f2489 100644 --- a/drivers/gpu/nova-core/fb/hal/ga100.rs +++ b/drivers/gpu/nova-core/fb/hal/ga100.rs @@ -2,6 +2,7 @@ =20 struct Ga100; =20 +use kernel::num::BoundedInt; use kernel::prelude::*; =20 use crate::driver::Bar0; @@ -18,7 +19,7 @@ pub(super) fn read_sysmem_flush_page_ga100(bar: &Bar0) ->= u64 { =20 pub(super) fn write_sysmem_flush_page_ga100(bar: &Bar0, addr: u64) { regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI::default() - .set_adr_63_40((addr >> FLUSH_SYSMEM_ADDR_SHIFT_HI) as u32) + .set_adr_63_40(BoundedInt::new(addr >> FLUSH_SYSMEM_ADDR_SHIFT_HI)= .cast()) .write(bar); regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::default() .set_adr_39_08((addr >> FLUSH_SYSMEM_ADDR_SHIFT) as u32) diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs index 5da9ad726483..7ed382d82fc7 100644 --- a/drivers/gpu/nova-core/gpu.rs +++ b/drivers/gpu/nova-core/gpu.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 =20 +use kernel::num::BoundedInt; use kernel::{device, devres::Devres, error::code::*, pci, prelude::*, sync= ::Arc}; =20 use crate::driver::Bar0; @@ -131,15 +132,15 @@ fn try_from(value: u8) -> Result { } =20 pub(crate) struct Revision { - major: u8, - minor: u8, + major: BoundedInt, + minor: BoundedInt, } =20 impl Revision { fn from_boot0(boot0: regs::NV_PMC_BOOT_0) -> Self { Self { - major: boot0.major_revision(), - minor: boot0.minor_revision(), + major: boot0.major_revision().cast(), + minor: boot0.minor_revision().cast(), } } } diff --git a/drivers/gpu/nova-core/regs.rs b/drivers/gpu/nova-core/regs.rs index 206dab2e1335..1542d72e4a65 100644 --- a/drivers/gpu/nova-core/regs.rs +++ b/drivers/gpu/nova-core/regs.rs @@ -17,18 +17,19 @@ // PMC =20 register!(NV_PMC_BOOT_0 @ 0x00000000, "Basic revision information about th= e GPU" { - 3:0 minor_revision as u8, "Minor revision of the chip"; - 7:4 major_revision as u8, "Major revision of the chip"; - 8:8 architecture_1 as u8, "MSB of the architecture"; - 23:20 implementation as u8, "Implementation version of the architect= ure"; - 28:24 architecture_0 as u8, "Lower bits of the architecture"; + 3:0 minor_revision, "Minor revision of the chip"; + 7:4 major_revision, "Major revision of the chip"; + 8:8 architecture_1, "MSB of the architecture"; + 23:20 implementation, "Implementation version of the architecture"; + 28:24 architecture_0, "Lower bits of the architecture"; }); =20 impl NV_PMC_BOOT_0 { /// Combines `architecture_0` and `architecture_1` to obtain the archi= tecture of the chip. pub(crate) fn architecture(self) -> Result { Architecture::try_from( - self.architecture_0() | (self.architecture_1() << Self::ARCHIT= ECTURE_0_RANGE.len()), + u8::from(self.architecture_0()) + | (u8::from(self.architecture_1()) << Self::ARCHITECTURE_0= _RANGE.len()), ) } =20 @@ -49,7 +50,7 @@ pub(crate) fn chipset(self) -> Result { =20 register!(NV_PBUS_SW_SCRATCH_0E_FRTS_ERR =3D> NV_PBUS_SW_SCRATCH[0xe], "scratch register 0xe used as FRTS firmware error code" { - 31:16 frts_err_code as u16; + 31:16 frts_err_code; }); =20 // PFB @@ -58,17 +59,17 @@ pub(crate) fn chipset(self) -> Result { // GPU to perform sysmembar operations (see `fb::SysmemFlush`). =20 register!(NV_PFB_NISO_FLUSH_SYSMEM_ADDR @ 0x00100c10 { - 31:0 adr_39_08 as u32; + 31:0 adr_39_08; }); =20 register!(NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI @ 0x00100c40 { - 23:0 adr_63_40 as u32; + 23:0 adr_63_40; }); =20 register!(NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE @ 0x00100ce0 { - 3:0 lower_scale as u8; - 9:4 lower_mag as u8; - 30:30 ecc_mode_enabled as bool; + 3:0 lower_scale; + 9:4 lower_mag; + 30:30 ecc_mode_enabled =3D> bool; }); =20 impl NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE { @@ -87,7 +88,7 @@ pub(crate) fn usable_fb_size(self) -> u64 { } =20 register!(NV_PFB_PRI_MMU_WPR2_ADDR_LO@0x001fa824 { - 31:4 lo_val as u32, "Bits 12..40 of the lower (inclusive) bound of = the WPR2 region"; + 31:4 lo_val, "Bits 12..40 of the lower (inclusive) bound of the WPR= 2 region"; }); =20 impl NV_PFB_PRI_MMU_WPR2_ADDR_LO { @@ -98,7 +99,7 @@ pub(crate) fn lower_bound(self) -> u64 { } =20 register!(NV_PFB_PRI_MMU_WPR2_ADDR_HI@0x001fa828 { - 31:4 hi_val as u32, "Bits 12..40 of the higher (exclusive) bound of= the WPR2 region"; + 31:4 hi_val, "Bits 12..40 of the higher (exclusive) bound of the WP= R2 region"; }); =20 impl NV_PFB_PRI_MMU_WPR2_ADDR_HI { @@ -123,7 +124,7 @@ pub(crate) fn higher_bound(self) -> u64 { // `PGC6_AON_SECURE_SCRATCH_GROUP_05` register (which it needs to read GFW= _BOOT). register!(NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_PRIV_LEVEL_MASK @ 0x00118128, "Privilege level mask register" { - 0:0 read_protection_level0 as bool, "Set after FWSEC lowers its pr= otection level"; + 0:0 read_protection_level0 =3D> bool, "Set after FWSEC lowers its = protection level"; }); =20 // OpenRM defines this as a register array, but doesn't specify its size a= nd only uses its first @@ -133,7 +134,7 @@ pub(crate) fn higher_bound(self) -> u64 { register!( NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_0_GFW_BOOT =3D> NV_PGC6_AON_SECURE= _SCRATCH_GROUP_05[0], "Scratch group 05 register 0 used as GFW boot progress indicator" { - 7:0 progress as u8, "Progress of GFW boot (0xff means completed= )"; + 7:0 progress, "Progress of GFW boot (0xff means completed)"; } ); =20 @@ -145,13 +146,13 @@ pub(crate) fn completed(self) -> bool { } =20 register!(NV_PGC6_AON_SECURE_SCRATCH_GROUP_42 @ 0x001183a4 { - 31:0 value as u32; + 31:0 value; }); =20 register!( NV_USABLE_FB_SIZE_IN_MB =3D> NV_PGC6_AON_SECURE_SCRATCH_GROUP_42, "Scratch group 42 register used as framebuffer size" { - 31:0 value as u32, "Usable framebuffer size, in megabytes"; + 31:0 value, "Usable framebuffer size, in megabytes"; } ); =20 @@ -165,8 +166,8 @@ pub(crate) fn usable_fb_size(self) -> u64 { // PDISP =20 register!(NV_PDISP_VGA_WORKSPACE_BASE @ 0x00625f04 { - 3:3 status_valid as bool, "Set if the `addr` field is valid"; - 31:8 addr as u32, "VGA workspace base address divided by 0x10000"; + 3:3 status_valid =3D> bool, "Set if the `addr` field is valid"; + 31:8 addr, "VGA workspace base address divided by 0x10000"; }); =20 impl NV_PDISP_VGA_WORKSPACE_BASE { @@ -185,40 +186,40 @@ pub(crate) fn vga_workspace_addr(self) -> Option= { pub(crate) const NV_FUSE_OPT_FPF_SIZE: usize =3D 16; =20 register!(NV_FUSE_OPT_FPF_NVDEC_UCODE1_VERSION @ 0x00824100[NV_FUSE_OPT_FP= F_SIZE] { - 15:0 data as u16; + 15:0 data; }); =20 register!(NV_FUSE_OPT_FPF_SEC2_UCODE1_VERSION @ 0x00824140[NV_FUSE_OPT_FPF= _SIZE] { - 15:0 data as u16; + 15:0 data; }); =20 register!(NV_FUSE_OPT_FPF_GSP_UCODE1_VERSION @ 0x008241c0[NV_FUSE_OPT_FPF_= SIZE] { - 15:0 data as u16; + 15:0 data; }); =20 // PFALCON =20 register!(NV_PFALCON_FALCON_IRQSCLR @ PFalconBase[0x00000004] { - 4:4 halt as bool; - 6:6 swgen0 as bool; + 4:4 halt =3D> bool; + 6:6 swgen0 =3D> bool; }); =20 register!(NV_PFALCON_FALCON_MAILBOX0 @ PFalconBase[0x00000040] { - 31:0 value as u32; + 31:0 value =3D> u32; }); =20 register!(NV_PFALCON_FALCON_MAILBOX1 @ PFalconBase[0x00000044] { - 31:0 value as u32; + 31:0 value =3D> u32; }); =20 register!(NV_PFALCON_FALCON_RM @ PFalconBase[0x00000084] { - 31:0 value as u32; + 31:0 value =3D> u32; }); =20 register!(NV_PFALCON_FALCON_HWCFG2 @ PFalconBase[0x000000f4] { - 10:10 riscv as bool; - 12:12 mem_scrubbing as bool, "Set to 0 after memory scrubbing is com= pleted"; - 31:31 reset_ready as bool, "Signal indicating that reset is complete= d (GA102+)"; + 10:10 riscv =3D> bool; + 12:12 mem_scrubbing =3D> bool, "Set to 0 after memory scrubbing is c= ompleted"; + 31:31 reset_ready =3D> bool, "Signal indicating that reset is comple= ted (GA102+)"; }); =20 impl NV_PFALCON_FALCON_HWCFG2 { @@ -229,101 +230,101 @@ pub(crate) fn mem_scrubbing_done(self) -> bool { } =20 register!(NV_PFALCON_FALCON_CPUCTL @ PFalconBase[0x00000100] { - 1:1 startcpu as bool; - 4:4 halted as bool; - 6:6 alias_en as bool; + 1:1 startcpu =3D> bool; + 4:4 halted =3D> bool; + 6:6 alias_en =3D> bool; }); =20 register!(NV_PFALCON_FALCON_BOOTVEC @ PFalconBase[0x00000104] { - 31:0 value as u32; + 31:0 value =3D> u32; }); =20 register!(NV_PFALCON_FALCON_DMACTL @ PFalconBase[0x0000010c] { - 0:0 require_ctx as bool; - 1:1 dmem_scrubbing as bool; - 2:2 imem_scrubbing as bool; - 6:3 dmaq_num as u8; - 7:7 secure_stat as bool; + 0:0 require_ctx =3D> bool; + 1:1 dmem_scrubbing =3D> bool; + 2:2 imem_scrubbing =3D> bool; + 6:3 dmaq_num; + 7:7 secure_stat =3D> bool; }); =20 register!(NV_PFALCON_FALCON_DMATRFBASE @ PFalconBase[0x00000110] { - 31:0 base as u32; + 31:0 base =3D> u32; }); =20 register!(NV_PFALCON_FALCON_DMATRFMOFFS @ PFalconBase[0x00000114] { - 23:0 offs as u32; + 23:0 offs; }); =20 register!(NV_PFALCON_FALCON_DMATRFCMD @ PFalconBase[0x00000118] { - 0:0 full as bool; - 1:1 idle as bool; - 3:2 sec as u8; - 4:4 imem as bool; - 5:5 is_write as bool; - 10:8 size as u8 ?=3D> DmaTrfCmdSize; - 14:12 ctxdma as u8; - 16:16 set_dmtag as u8; + 0:0 full =3D> bool; + 1:1 idle =3D> bool; + 3:2 sec; + 4:4 imem =3D> bool; + 5:5 is_write =3D> bool; + 10:8 size ?=3D> DmaTrfCmdSize; + 14:12 ctxdma; + 16:16 set_dmtag; }); =20 register!(NV_PFALCON_FALCON_DMATRFFBOFFS @ PFalconBase[0x0000011c] { - 31:0 offs as u32; + 31:0 offs =3D> u32; }); =20 register!(NV_PFALCON_FALCON_DMATRFBASE1 @ PFalconBase[0x00000128] { - 8:0 base as u16; + 8:0 base; }); =20 register!(NV_PFALCON_FALCON_HWCFG1 @ PFalconBase[0x0000012c] { - 3:0 core_rev as u8 ?=3D> FalconCoreRev, "Core revision"; - 5:4 security_model as u8 ?=3D> FalconSecurityModel, "Security mode= l"; - 7:6 core_rev_subversion as u8 ?=3D> FalconCoreRevSubversion, "Core= revision subversion"; + 3:0 core_rev ?=3D> FalconCoreRev, "Core revision"; + 5:4 security_model ?=3D> FalconSecurityModel, "Security model"; + 7:6 core_rev_subversion =3D> FalconCoreRevSubversion, "Core revisi= on subversion"; }); =20 register!(NV_PFALCON_FALCON_CPUCTL_ALIAS @ PFalconBase[0x00000130] { - 1:1 startcpu as bool; + 1:1 startcpu =3D> bool; }); =20 // Actually known as `NV_PSEC_FALCON_ENGINE` and `NV_PGSP_FALCON_ENGINE` d= epending on the falcon // instance. register!(NV_PFALCON_FALCON_ENGINE @ PFalconBase[0x000003c0] { - 0:0 reset as bool; + 0:0 reset =3D> bool; }); =20 register!(NV_PFALCON_FBIF_TRANSCFG @ PFalconBase[0x00000600[8]] { - 1:0 target as u8 ?=3D> FalconFbifTarget; - 2:2 mem_type as bool =3D> FalconFbifMemType; + 1:0 target ?=3D> FalconFbifTarget; + 2:2 mem_type =3D> FalconFbifMemType; }); =20 register!(NV_PFALCON_FBIF_CTL @ PFalconBase[0x00000624] { - 7:7 allow_phys_no_ctx as bool; + 7:7 allow_phys_no_ctx =3D> bool; }); =20 /* PFALCON2 */ =20 register!(NV_PFALCON2_FALCON_MOD_SEL @ PFalcon2Base[0x00000180] { - 7:0 algo as u8 ?=3D> FalconModSelAlgo; + 7:0 algo ?=3D> FalconModSelAlgo; }); =20 register!(NV_PFALCON2_FALCON_BROM_CURR_UCODE_ID @ PFalcon2Base[0x00000198]= { - 7:0 ucode_id as u8; + 7:0 ucode_id =3D> u8; }); =20 register!(NV_PFALCON2_FALCON_BROM_ENGIDMASK @ PFalcon2Base[0x0000019c] { - 31:0 value as u32; + 31:0 value =3D> u32; }); =20 // OpenRM defines this as a register array, but doesn't specify its size a= nd only uses its first // element. Be conservative until we know the actual size or need to use m= ore registers. register!(NV_PFALCON2_FALCON_BROM_PARAADDR @ PFalcon2Base[0x00000210[1]] { - 31:0 value as u32; + 31:0 value =3D> u32; }); =20 // PRISCV =20 register!(NV_PRISCV_RISCV_BCR_CTRL @ PFalconBase[0x00001668] { - 0:0 valid as bool; - 4:4 core_select as bool =3D> PeregrineCoreSelect; - 8:8 br_fetch as bool; + 0:0 valid =3D> bool; + 4:4 core_select =3D> PeregrineCoreSelect; + 8:8 br_fetch =3D> bool; }); =20 // The modules below provide registers that are not identical on all suppo= rted chips. They should @@ -333,7 +334,7 @@ pub(crate) mod gm107 { // FUSE =20 register!(NV_FUSE_STATUS_OPT_DISPLAY @ 0x00021c04 { - 0:0 display_disabled as bool; + 0:0 display_disabled =3D> bool; }); } =20 @@ -341,6 +342,6 @@ pub(crate) mod ga100 { // FUSE =20 register!(NV_FUSE_STATUS_OPT_DISPLAY @ 0x00820c04 { - 0:0 display_disabled as bool; + 0:0 display_disabled =3D> bool; }); } diff --git a/drivers/gpu/nova-core/regs/macros.rs b/drivers/gpu/nova-core/r= egs/macros.rs index 73811a115762..54c7f6fc746b 100644 --- a/drivers/gpu/nova-core/regs/macros.rs +++ b/drivers/gpu/nova-core/regs/macros.rs @@ -398,12 +398,9 @@ fn from(reg: $name) -> u32 { register!(@fields_dispatcher $name { $($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. + // Dispatch fields for the bounded integers syntax. (@fields_dispatcher $name:ident { - $($hi:tt:$lo:tt $field:ident as $type:tt + $($hi:tt:$lo:tt $field:ident $(?=3D> $try_into_type:ty)? $(=3D> $into_type:ty)? $(, $comment:literal)? @@ -411,123 +408,25 @@ fn from(reg: $name) -> u32 { )* } ) =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 }) } - bool $into_type =3D> $into_type $(, $comment)?; + $( + register!(@private_field_accessors $name $hi:$lo $field); + register!(@public_field_accessors $name $hi:$lo $field + $(?=3D> $try_into_type)? + $(=3D> $into_type)? + $(, $comment)? ); + )* + } + + register!(@debug $name { $($field;)* }); + register!(@default $name { $($field;)* }); + }; =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)?; - ) =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) } $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) } $type $into_type =3D> $= into_type $(, $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 } $prim_type:tt $to_type:ty =3D> $res_type:ty = $(, $comment:literal)?; + @private_field_accessors $name:ident $hi:tt:$lo:tt $field:ident ) =3D> { ::kernel::macros::paste!( const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive =3D= $lo..=3D$hi; @@ -535,38 +434,135 @@ impl $name { const [<$field:upper _SHIFT>]: u32 =3D Self::[<$field:upper _MASK>= ].trailing_zeros(); ); =20 - $( - #[doc=3D"Returns the value of this field:"] - #[doc=3D$comment] - )? - #[inline(always)] - pub(crate) fn $field(self) -> $res_type { - ::kernel::macros::paste!( + ::kernel::macros::paste!( + fn [<$field _internal>](self) -> + ::kernel::num::BoundedInt { const MASK: u32 =3D $name::[<$field:upper _MASK>]; const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; + // Ensure the returned type has the same width as the field. + ::kernel::static_assert!( + MASK >> SHIFT =3D=3D >::MASK ); + let field =3D ((self.0 & MASK) >> SHIFT); =20 - $process(field) + ::kernel::num::BoundedInt::::new(field) } =20 - ::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 { + fn []( + mut self, + value: ::kernel::num::BoundedInt, + ) -> Self + { const MASK: u32 =3D $name::[<$field:upper _MASK>]; const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; - let value =3D (u32::from($prim_type::from(value)) << SHIFT) & = MASK; + // Ensure the returned type has the same width as the field. + ::kernel::static_assert!( + MASK >> SHIFT =3D=3D >::MASK + ); + + let value =3D (value.get() << SHIFT) & MASK; self.0 =3D (self.0 & !MASK) | value; =20 self } + + fn []( + mut self, + value: T, + ) -> ::kernel::error::Result + where T: ::kernel::num::TryIntoBounded, + { + const MASK: u32 =3D $name::[<$field:upper _MASK>]; + const SHIFT: u32 =3D $name::[<$field:upper _SHIFT>]; + // Ensure the returned type has the same width as the field. + ::kernel::static_assert!( + MASK >> SHIFT =3D=3D >::MASK + ); + let value =3D value.try_into()?; + + let value =3D (value.get() << SHIFT) & MASK; + self.0 =3D (self.0 & !MASK) | value; + + Ok(self) + } ); }; =20 + // Generates the public accessors for fields infallibly (`=3D>`) conve= rted to a type. + ( + @public_field_accessors $name:ident $hi:tt:$lo:tt $field:ident =3D= > $into_type:ty + $(, $comment:literal)? + ) =3D> { + ::kernel::macros::paste!( + pub(crate) fn $field(self) -> $into_type + { + self.[<$field _internal>]().into() + } + + pub(crate) fn [](self, value: $into_type) -> Self + { + self.[](value.into()) + } + ); + }; + + // Generates the public accessors for fields fallibly (`?=3D>`) conver= ted to a type. + ( + @public_field_accessors $name:ident $hi:tt:$lo:tt $field:ident ?= =3D> $try_into_type:ty + $(, $comment:literal)? + ) =3D> { + ::kernel::macros::paste!( + pub(crate) fn $field(self) -> + Result< + $try_into_type, + <$try_into_type as ::core::convert::TryFrom< + ::kernel::num::BoundedInt + >>::Error + > + { + self.[<$field _internal>]().try_into() + } + + pub(crate) fn [](self, value: $try_into_type) -> Self + { + self.[](value.into()) + } + ); + }; + + // Generates the public accessors for fields not converted to a type. + ( + @public_field_accessors $name:ident $hi:tt:$lo:tt $field:ident $(,= $comment:literal)? + ) =3D> { + ::kernel::macros::paste!( + pub(crate) fn $field(self) -> + ::kernel::num::BoundedInt + { + self.[<$field _internal>]() + } + + pub(crate) fn []( + self, + value: T, + ) -> Self + where T: Into<::kernel::num::BoundedInt>, + { + self.[](value.into()) + } + + pub(crate) fn []( + self, + value: T, + ) -> ::kernel::error::Result + where T: ::kernel::num::TryIntoBounded, + { + Ok(self.[](value.try_into()?)) + } + ); + }; + + // Generates the `Debug` implementation for `$name`. (@debug $name:ident { $($field:ident;)* }) =3D> { impl ::core::fmt::Debug for $name { @@ -582,6 +578,8 @@ fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::= core::fmt::Result { }; =20 // Generates the `Default` implementation for `$name`. + // TODO: hack - we should not use the internal method. Maybe add priva= te methods returning the + // defaults value for each field? (@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 { @@ -591,7 +589,7 @@ fn default() -> Self { =20 ::kernel::macros::paste!( $( - value.[](Default::default()); + value.[](Default::default()); )* ); =20 --=20 2.51.0